forked from DrewThomasson/VoxNovel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gui_run.py
3238 lines (2397 loc) · 126 KB
/
gui_run.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#This will download the booknlp files using my huggingface backup
import download_missing_booknlp_models
print("Starting...")
#this is code that will be used to turn numbers like 1,000 and in a txt file into 1000 go then booknlp doesnt make it weird and then when the numbers are generated it comes out fine
import re
def process_large_numbers_in_txt(file_path):
# Read the contents of the file
with open(file_path, 'r') as file:
content = file.read()
# Regular expression to match numbers with commas
pattern = r'\b\d{1,3}(,\d{3})+\b'
# Remove commas in numerical sequences
modified_content = re.sub(pattern, lambda m: m.group().replace(',', ''), content)
# Write the modified content back to the file
with open(file_path, 'w') as file:
file.write(modified_content)
# Usage example
#file_path = 'test_1.txt' # Replace with your actual file path
#process_large_numbers_in_txt(file_path)
#this code here will remove any blank text rows from the csv file
import pandas as pd
def remove_empty_text_rows(csv_file):
# Read the CSV file
data = pd.read_csv(csv_file)
# Remove rows where the 'Text' column is empty or NaN
data = data[data['Text'].notna() & (data['Text'] != '')]
# Write the modified DataFrame back to the CSV file
data.to_csv(csv_file, index=False)
print(f"Rows with empty 'Text' column have been removed from {csv_file}")
# Example usage
#csv_file = 'path_to_your_csv_file.csv' # Replace with your CSV file path
#remove_empty_text_rows(csv_file)
#this code here will split book.csv file by the custom weird chapter deliminator for amachines to see
import pandas as pd
def process_and_split_csv(file_path, split_string):
def split_text(text, split_string, original_row):
# Split the text at the specified string and find the index of the split
split_index = text.find(split_string)
parts = text.split(split_string)
new_rows = []
start_location = original_row['Start Location']
for index, part in enumerate(parts):
new_row = original_row.copy()
if index == 0:
new_row['Text'] = part
new_row['End Location'] = start_location + split_index
else:
new_row['Text'] = split_string + part
new_row['Start Location'] = start_location + split_index
new_row['End Location'] = start_location + split_index + len(split_string) + len(part)
split_index += len(split_string) + len(part) # Update for the next part
new_rows.append(new_row)
return new_rows
def process_csv(df, split_string):
new_rows = []
for _, row in df.iterrows():
text = row['Text']
if isinstance(text, str) and split_string in text:
new_rows.extend(split_text(text, split_string, row))
else:
new_rows.append(row)
return pd.DataFrame(new_rows)
# Read the CSV file
df = pd.read_csv(file_path)
# Process the DataFrame
new_df = process_csv(df, split_string)
# Write the modified DataFrame back to the CSV file
new_df.to_csv(file_path, index=False)
# Example usage
#file_path = 'Working_files/Book/book.csv'
#split_string = 'NEWCHAPTERABC'
#process_and_split_csv(file_path, split_string)
#this code right here isnt the book grabbing thing but its before to refrence in ordero to create the sepecial chapter labeled book thing with calibre idk some systems cant seem to get it so just in case but the next bit of code after this is the book grabbing code with booknlp
import os
import subprocess
import ebooklib
from ebooklib import epub
from bs4 import BeautifulSoup
import re
import csv
import nltk
import shutil
# Only run the main script if Value is True
def create_chapter_labeled_book(ebook_file_path):
# Function to ensure the existence of a directory
def ensure_directory(directory_path):
if not os.path.exists(directory_path):
os.makedirs(directory_path)
print(f"Created directory: {directory_path}")
ensure_directory('Working_files/Book')
def convert_to_epub(input_path, output_path):
# Convert the ebook to EPUB format using Calibre's ebook-convert
try:
subprocess.run(['ebook-convert', input_path, output_path], check=True)
except subprocess.CalledProcessError as e:
print(f"An error occurred while converting the eBook: {e}")
return False
return True
def save_chapters_as_text(epub_path):
# Create the directory if it doesn't exist
directory = "Working_files/temp_ebook"
#Clean up the text chapter folders by wiping it before creating chapters for selected ebook.
#Lazily done by just deleting the directly and everything in it.
if os.path.exists(directory):
shutil.rmtree(directory)
ensure_directory(directory)
# Open the EPUB file
book = epub.read_epub(epub_path)
previous_chapter_text = ''
previous_filename = ''
chapter_counter = 0
# Iterate through the items in the EPUB file
for item in book.get_items():
if item.get_type() == ebooklib.ITEM_DOCUMENT:
# Use BeautifulSoup to parse HTML content
soup = BeautifulSoup(item.get_content(), 'html.parser')
text = soup.get_text()
# Check if the text is not empty
if text.strip():
if len(text) < 2300 and previous_filename:
# Append text to the previous chapter if it's short
with open(previous_filename, 'a', encoding='utf-8') as file:
file.write('\n' + text)
else:
# Create a new chapter file and increment the counter
previous_filename = os.path.join(directory, f"chapter_{chapter_counter}.txt")
chapter_counter += 1
with open(previous_filename, 'w', encoding='utf-8') as file:
file.write(text)
print(f"Saved chapter: {previous_filename}")
# Example usage
input_ebook = ebook_file_path # Replace with your eBook file path
output_epub = 'Working_files/temp.epub'
if os.path.exists(output_epub):
os.remove(output_epub)
print(f"File {output_epub} has been removed.")
else:
print(f"The file {output_epub} does not exist.")
if convert_to_epub(input_ebook, output_epub):
save_chapters_as_text(output_epub)
# Download the necessary NLTK data (if not already present)
nltk.download('punkt')
"""
def process_chapter_files(folder_path, output_csv):
with open(output_csv, 'w', newline='', encoding='utf-8') as csvfile:
writer = csv.writer(csvfile)
# Write the header row
writer.writerow(['Text', 'Start Location', 'End Location', 'Is Quote', 'Speaker', 'Chapter'])
# Process each chapter file
chapter_files = sorted(os.listdir(folder_path), key=lambda x: int(x.split('_')[1].split('.')[0]))
for filename in chapter_files:
if filename.startswith('chapter_') and filename.endswith('.txt'):
chapter_number = int(filename.split('_')[1].split('.')[0])
file_path = os.path.join(folder_path, filename)
try:
with open(file_path, 'r', encoding='utf-8') as file:
text = file.read()
sentences = nltk.tokenize.sent_tokenize(text)
for sentence in sentences:
start_location = text.find(sentence)
end_location = start_location + len(sentence)
writer.writerow([sentence, start_location, end_location, 'True', 'Narrator', chapter_number])
except Exception as e:
print(f"Error processing file {filename}: {e}")
"""
def process_chapter_files(folder_path, output_csv):
with open(output_csv, 'w', newline='', encoding='utf-8') as csvfile:
writer = csv.writer(csvfile)
# Write the header row
writer.writerow(['Text', 'Start Location', 'End Location', 'Is Quote', 'Speaker', 'Chapter'])
# Process each chapter file
chapter_files = sorted(os.listdir(folder_path), key=lambda x: int(x.split('_')[1].split('.')[0]))
for filename in chapter_files:
if filename.startswith('chapter_') and filename.endswith('.txt'):
chapter_number = int(filename.split('_')[1].split('.')[0])
file_path = os.path.join(folder_path, filename)
try:
with open(file_path, 'r', encoding='utf-8') as file:
text = file.read()
# Insert "NEWCHAPTERABC" at the beginning of each chapter's text
if text:
text = "NEWCHAPTERABC" + text
sentences = nltk.tokenize.sent_tokenize(text)
for sentence in sentences:
start_location = text.find(sentence)
end_location = start_location + len(sentence)
writer.writerow([sentence, start_location, end_location, 'True', 'Narrator', chapter_number])
except Exception as e:
print(f"Error processing file {filename}: {e}")
# Example usage
folder_path = "Working_files/temp_ebook" # Replace with your folder path
output_csv = 'Working_files/Book/Other_book.csv'
process_chapter_files(folder_path, output_csv)
def wipe_folder(folder_path):
# Check if the folder exists
if not os.path.exists(folder_path):
print(f"The folder {folder_path} does not exist.")
return
# Iterate through all files in the folder
for filename in os.listdir(folder_path):
file_path = os.path.join(folder_path, filename)
# Check if it's a file and not a directory
if os.path.isfile(file_path):
try:
os.remove(file_path)
print(f"Removed file: {file_path}")
except Exception as e:
print(f"Failed to remove {file_path}. Reason: {e}")
else:
print(f"Skipping directory: {file_path}")
# Example usage
# folder_to_wipe = 'Working_files/temp_ebook' # Replace with the path to your folder
# wipe_folder(folder_to_wipe)
def sort_key(filename):
"""Extract chapter number for sorting."""
match = re.search(r'chapter_(\d+)\.txt', filename)
return int(match.group(1)) if match else 0
def combine_chapters(input_folder, output_file):
# Create the output folder if it doesn't exist
os.makedirs(os.path.dirname(output_file), exist_ok=True)
# List all txt files and sort them by chapter number
files = [f for f in os.listdir(input_folder) if f.endswith('.txt')]
sorted_files = sorted(files, key=sort_key)
with open(output_file, 'w') as outfile:
for i, filename in enumerate(sorted_files):
with open(os.path.join(input_folder, filename), 'r') as infile:
outfile.write(infile.read())
# Add the marker unless it's the last file
if i < len(sorted_files) - 1:
outfile.write("\nNEWCHAPTERABC\n")
# Paths
input_folder = 'Working_files/temp_ebook'
output_file = 'Working_files/Book/Chapter_Book.txt'
# Combine the chapters
combine_chapters(input_folder, output_file)
ensure_directory('Working_files/Book')
#create_chapter_labeled_book()
#this is the Booknlp book grabber code
import os
import subprocess
import tkinter as tk
from tkinter import filedialog, messagebox
from epub2txt import epub2txt
from booknlp.booknlp import BookNLP
import nltk
import re
nltk.download('averaged_perceptron_tagger')
epub_file_path = ""
chapters = []
ebook_file_path = ""
input_file_is_txt = False
def convert_epub_and_extract_chapters(epub_path):
# Regular expression to match the chapter lines in the output
chapter_pattern = re.compile(r'Detected chapter: \* (.*)')
# List to store the extracted chapter names
chapter_names = []
# Start the conversion process and capture the output
process = subprocess.Popen(['ebook-convert', epub_path, '/dev/null'],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
universal_newlines=True)
# Read the output line by line
for line in iter(process.stdout.readline, ''):
print(line, end='') # You can comment this out if you don't want to see the output
match = chapter_pattern.search(line)
if match:
chapter_names.append(match.group(1))
# Wait for the process to finish
process.stdout.close()
process.wait()
return chapter_names
def calibre_installed():
"""Check if Calibre's ebook-convert tool is available."""
try:
subprocess.run(['ebook-convert', '--version'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
return True
except FileNotFoundError:
print("""ERROR NO CALIBRE: running epub2txt convert version...
It appears you dont have the calibre commandline tools installed on your,
This will allow you to convert from any ebook file format:
Calibre supports the following input formats: CBZ, CBR, CBC, CHM, EPUB, FB2, HTML, LIT, LRF, MOBI, ODT, PDF, PRC, PDB, PML, RB, RTF, SNB, TCR, TXT.
If you want this feature please follow online instruction for downloading the calibre commandline tool.
For Linux its:
sudo apt update && sudo apt upgrade
sudo apt install calibre
""")
return False
def convert_with_calibre(file_path, output_format="txt"):
"""Convert a file using Calibre's ebook-convert tool."""
output_path = file_path.rsplit('.', 1)[0] + '.' + output_format
subprocess.run(['ebook-convert', file_path, output_path])
return output_path
def process_file():
global epub_file_path
global ebook_file_path
global input_file_is_txt
file_path = filedialog.askopenfilename(
title='Select File',
filetypes=[('Supported Files',
('*.cbz', '*.cbr', '*.cbc', '*.chm', '*.epub', '*.fb2', '*.html', '*.lit', '*.lrf',
'*.mobi', '*.odt', '*.pdf', '*.prc', '*.pdb', '*.pml', '*.rb', '*.rtf', '*.snb',
'*.tcr', '*.txt'))]
)
ebook_file_path = file_path
if ".epub" in file_path.lower():
epub_file_path = file_path
if ".txt" in file_path.lower():
input_file_is_txt = True
if not file_path:
return
if file_path.lower().endswith(('.cbz', '.cbr', '.cbc', '.chm', '.epub', '.fb2', '.html', '.lit', '.lrf',
'.mobi', '.odt', '.pdf', '.prc', '.pdb', '.pml', '.rb', '.rtf', '.snb', '.tcr')) and calibre_installed():
file_path = convert_with_calibre(file_path)
elif file_path.lower().endswith('.epub') and not calibre_installed():
content = epub2txt(file_path)
if not os.path.exists('Working_files'):
os.makedirs('Working_files')
file_path = os.path.join('Working_files', 'Book.txt')
with open(file_path, 'w', encoding='utf-8') as f:
f.write(content)
elif not file_path.lower().endswith('.txt'):
messagebox.showerror("Error", "Selected file format is not supported or Calibre is not installed.")
return
# Now process the TXT file with BookNLP
book_id = "Book"
output_directory = os.path.join('Working_files', book_id)
model_params = {
"pipeline": "entity,quote,supersense,event,coref",
"model": "big"
}
#this will turn stuff like 1,000 and 18,000 into 1000 and 18000 so booknlp doesnt mess them up with tokenization
process_large_numbers_in_txt(file_path)
booknlp = BookNLP("en", model_params)
if calibre_installed():
global filepath
create_chapter_labeled_book(file_path)
booknlp.process('Working_files/Book/Chapter_Book.txt', output_directory, book_id)
#only delete the txt file if the input file isnt a txt file else then youll be deleting the original input file
if input_file_is_txt != True:
os.remove(file_path)
print(f"deleted file: {file_path} because its not needed anymore after the ebook convertsion to txt")
else:
booknlp.process(file_path, output_directory, book_id)
#os.remove(file_path)
#print(f"deleted file: {file_path}")
global chapters
if epub_file_path == "":
chapters = convert_epub_and_extract_chapters(epub_file_path)
print("Success, File processed successfully!")
# Close the GUI
root.destroy()
root = tk.Tk()
root.title("BookNLP Processor")
frame = tk.Frame(root, padx=20, pady=20)
frame.pack(padx=10, pady=10)
process_button = tk.Button(frame, text="Process File", command=process_file)
process_button.pack()
root.mainloop()
import pandas as pd
def filter_and_correct_quotes(file_path):
with open(file_path, 'r', encoding='utf-8') as file:
lines = file.readlines()
corrected_lines = []
# Filter out lines with mismatched quotes
for line in lines:
if line.count('"') % 2 == 0:
corrected_lines.append(line)
with open(file_path, 'w', encoding='utf-8') as file:
file.writelines(corrected_lines)
print(f"Processed {len(lines)} lines.")
print(f"Removed {len(lines) - len(corrected_lines)} problematic lines.")
print(f"Wrote {len(corrected_lines)} lines back to the file.")
if __name__ == "__main__":
file_path = "Working_files/Book/Book.quotes"
filter_and_correct_quotes(file_path)
import pandas as pd
import re
import glob
import os
def process_files(quotes_file, tokens_file):
skip_rows = []
while True:
try:
df_quotes = pd.read_csv(quotes_file, delimiter="\t", skiprows=skip_rows)
break
except pd.errors.ParserError as e:
msg = str(e)
match = re.search(r'at row (\d+)', msg)
if match:
problematic_row = int(match.group(1))
print(f"Skipping problematic row {problematic_row} in {quotes_file}")
skip_rows.append(problematic_row)
else:
print(f"Error reading {quotes_file}: {e}")
return
df_tokens = pd.read_csv(tokens_file, delimiter="\t", on_bad_lines='skip', quoting=3)
last_end_id = 0
nonquotes_data = []
for index, row in df_quotes.iterrows():
start_id = row['quote_start']
end_id = row['quote_end']
filtered_tokens = df_tokens[(df_tokens['token_ID_within_document'] > last_end_id) &
(df_tokens['token_ID_within_document'] < start_id)]
words_chunk = ' '.join([str(token_row['word']) for index, token_row in filtered_tokens.iterrows()])
words_chunk = words_chunk.replace(" n't", "n't").replace(" n’", "n’").replace("( ", "(").replace(" ,", ",").replace("gon na", "gonna").replace(" n’t", "n’t")
words_chunk = re.sub(r' (?=[^a-zA-Z0-9\s])', '', words_chunk)
if words_chunk:
nonquotes_data.append([words_chunk, last_end_id, start_id, "False", "Narrator"])
last_end_id = end_id
nonquotes_df = pd.DataFrame(nonquotes_data, columns=["Text", "Start Location", "End Location", "Is Quote", "Speaker"])
output_filename = os.path.join(os.path.dirname(quotes_file), "non_quotes.csv")
nonquotes_df.to_csv(output_filename, index=False)
print(f"Saved nonquotes.csv to {output_filename}")
def main():
quotes_files = glob.glob('Working_files/**/*.quotes', recursive=True)
tokens_files = glob.glob('Working_files/**/*.tokens', recursive=True)
for q_file in quotes_files:
base_name = os.path.splitext(os.path.basename(q_file))[0]
matching_token_files = [t_file for t_file in tokens_files if os.path.splitext(os.path.basename(t_file))[0] == base_name]
if matching_token_files:
process_files(q_file, matching_token_files[0])
print("All processing complete!")
if __name__ == "__main__":
main()
import pandas as pd
import re
import glob
import os
import nltk
def process_files(quotes_file, entities_file):
# Load the files
df_quotes = pd.read_csv(quotes_file, delimiter="\t")
df_entities = pd.read_csv(entities_file, delimiter="\t")
character_info = {}
def is_pronoun(word):
tagged_word = nltk.pos_tag([word])
return 'PRP' in tagged_word[0][1] or 'PRP$' in tagged_word[0][1]
def get_gender(pronoun):
male_pronouns = ['he', 'him', 'his']
female_pronouns = ['she', 'her', 'hers']
if pronoun in male_pronouns:
return 'Male'
elif pronoun in female_pronouns:
return 'Female'
return 'Unknown'
# Process the quotes dataframe
for index, row in df_quotes.iterrows():
char_id = row['char_id']
mention = row['mention_phrase']
# Initialize character info if not already present
if char_id not in character_info:
character_info[char_id] = {"names": {}, "pronouns": {}, "quote_count": 0}
# Update names or pronouns based on the mention_phrase
if is_pronoun(mention):
character_info[char_id]["pronouns"].setdefault(mention.lower(), 0)
character_info[char_id]["pronouns"][mention.lower()] += 1
else:
character_info[char_id]["names"].setdefault(mention, 0)
character_info[char_id]["names"][mention] += 1
character_info[char_id]["quote_count"] += 1
# Process the entities dataframe
for index, row in df_entities.iterrows():
coref = row['COREF']
name = row['text']
if coref in character_info:
if is_pronoun(name):
character_info[coref]["pronouns"].setdefault(name.lower(), 0)
character_info[coref]["pronouns"][name.lower()] += 1
else:
character_info[coref]["names"].setdefault(name, 0)
character_info[coref]["names"][name] += 1
# Extract the most likely name and gender for each character
for char_id, info in character_info.items():
most_likely_name = max(info["names"].items(), key=lambda x: x[1])[0] if info["names"] else "Unknown"
most_common_pronoun = max(info["pronouns"].items(), key=lambda x: x[1])[0] if info["pronouns"] else None
gender = get_gender(most_common_pronoun) if most_common_pronoun else 'Unknown'
gender_suffix = ".M" if gender == 'Male' else ".F" if gender == 'Female' else ".?"
info["formatted_speaker"] = f"{char_id}:{most_likely_name}{gender_suffix}"
info["most_likely_name"] = most_likely_name
info["gender"] = gender
# Write the formatted data to quotes.csv
output_filename = os.path.join(os.path.dirname(quotes_file), "quotes.csv")
with open(output_filename, 'w', newline='') as outfile:
fieldnames = ["Text", "Start Location", "End Location", "Is Quote", "Speaker"]
writer = pd.DataFrame(columns=fieldnames)
for index, row in df_quotes.iterrows():
char_id = row['char_id']
if not re.search('[a-zA-Z0-9]', row['quote']):
print(f"Removing row with text: {row['quote']}")
continue
if character_info[char_id]["quote_count"] == 1:
formatted_speaker = "Narrator"
else:
formatted_speaker = character_info[char_id]["formatted_speaker"] if char_id in character_info else "Unknown"
new_row = {"Text": row['quote'], "Start Location": row['quote_start'], "End Location": row['quote_end'], "Is Quote": "True", "Speaker": formatted_speaker}
#turn the new_row into a data frame
new_row_df = pd.DataFrame([new_row])
# Concatenate 'writer' with 'new_row_df'
writer = pd.concat([writer, new_row_df], ignore_index=True)
writer.to_csv(output_filename, index=False)
print(f"Saved quotes.csv to {output_filename}")
def main():
# Use glob to get all .quotes and .entities files within the "Working_files" directory and its subdirectories
quotes_files = glob.glob('Working_files/**/*.quotes', recursive=True)
entities_files = glob.glob('Working_files/**/*.entities', recursive=True)
# Pair and process .quotes and .entities files with matching filenames (excluding the extension)
for q_file in quotes_files:
base_name = os.path.splitext(os.path.basename(q_file))[0]
matching_entities_files = [e_file for e_file in entities_files if os.path.splitext(os.path.basename(e_file))[0] == base_name]
if matching_entities_files:
process_files(q_file, matching_entities_files[0])
print("All processing complete!")
if __name__ == "__main__":
main()
import pandas as pd
import re
import glob
import os
def process_files(quotes_file, tokens_file):
# Load the files
df_quotes = pd.read_csv(quotes_file, delimiter="\t")
df_tokens = pd.read_csv(tokens_file, delimiter="\t", on_bad_lines='skip', quoting=3)
last_end_id = 0 # Initialize the last_end_id to 0
nonquotes_data = [] # List to hold data for nonquotes.csv
# Iterate through the quotes dataframe
for index, row in df_quotes.iterrows():
start_id = row['quote_start']
end_id = row['quote_end']
# Get tokens between the end of the last quote and the start of the current quote
filtered_tokens = df_tokens[(df_tokens['token_ID_within_document'] > last_end_id) &
(df_tokens['token_ID_within_document'] < start_id)]
# Build the word chunk
#words_chunk = ' '.join([token_row['word'] for index, token_row in filtered_tokens.iterrows()])
words_chunk = ' '.join([str(token_row['word']) for index, token_row in filtered_tokens.iterrows()])
words_chunk = words_chunk.replace(" n't", "n't").replace(" n’", "n’").replace(" ’", "’").replace(" ,", ",").replace(" .", ".").replace(" n’t", "n’t")
words_chunk = re.sub(r' (?=[^a-zA-Z0-9\s])', '', words_chunk)
# Append data to nonquotes_data if words_chunk is not empty
if words_chunk:
nonquotes_data.append([words_chunk, last_end_id, start_id, "False", "Narrator"])
last_end_id = end_id # Update the last_end_id to the end_id of the current quote
# Create a DataFrame for non-quote data
nonquotes_df = pd.DataFrame(nonquotes_data, columns=["Text", "Start Location", "End Location", "Is Quote", "Speaker"])
# Write to nonquotes.csv
output_filename = os.path.join(os.path.dirname(quotes_file), "non_quotes.csv")
nonquotes_df.to_csv(output_filename, index=False)
print(f"Saved nonquotes.csv to {output_filename}")
def main():
# Use glob to get all .quotes and .tokens files within the "Working_files" directory and its subdirectories
quotes_files = glob.glob('Working_files/**/*.quotes', recursive=True)
tokens_files = glob.glob('Working_files/**/*.tokens', recursive=True)
# Pair and process .quotes and .tokens files with matching filenames (excluding the extension)
for q_file in quotes_files:
base_name = os.path.splitext(os.path.basename(q_file))[0]
matching_token_files = [t_file for t_file in tokens_files if os.path.splitext(os.path.basename(t_file))[0] == base_name]
if matching_token_files:
process_files(q_file, matching_token_files[0])
print("All processing complete!")
if __name__ == "__main__":
main()
import pandas as pd
import numpy as np
# Read the CSV files
quotes_df = pd.read_csv("Working_files/Book/quotes.csv")
non_quotes_df = pd.read_csv("Working_files/Book/non_quotes.csv")
# Concatenate the dataframes
combined_df = pd.concat([quotes_df, non_quotes_df], ignore_index=True)
# Convert 'None' to NaN
combined_df.replace('None', np.nan, inplace=True)
# Drop rows with NaN in 'Start Location'
combined_df.dropna(subset=['Start Location'], inplace=True)
# Convert the 'Start Location' column to integers
combined_df["Start Location"] = combined_df["Start Location"].astype(int)
# Sort by 'Start Location'
sorted_df = combined_df.sort_values(by="Start Location")
# Save to 'book.csv'
sorted_df.to_csv("Working_files/Book/book.csv", index=False)
#if booknlp came up with nothing then just use the other_book.csv file thank god i still have that code
import os
import tkinter as tk
from tkinter import messagebox
def is_single_line_file(filename):
with open(filename, 'r') as file:
return len(file.readlines()) <= 1
def copy_if_single_line(source_file, destination_file):
if not os.path.isfile(source_file):
return f"The source file '{source_file}' does not exist."
elif is_single_line_file(destination_file):
with open(source_file, 'r') as source:
content = source.read()
with open(destination_file, 'w') as dest:
dest.write(content)
# Popup message
root = tk.Tk()
root.withdraw() # Hide the main window
messagebox.showinfo("Notification", "The 'book.csv' file was found to be empty, so all lines in the book will be said by the narrator.")
root.destroy()
return f"File '{destination_file}' had only one line or was empty and has been filled with the contents of '{source_file}'."
else:
return f"File '{destination_file}' had more than one line, and no action was taken."
source_file = 'Working_files/Book/Other_book.csv'
destination_file = 'Working_files/Book/book.csv'
result = copy_if_single_line(source_file, destination_file)
print(result)
#this is a clean up script to try to clean up the quotes.csv and non_quotes.csv files of any types formed by booknlp
import pandas as pd
import os
import re
def process_text(text):
# Apply the rule to remove spaces before punctuation and other non-alphanumeric characters
text = re.sub(r' (?=[^a-zA-Z0-9\s])', '', text)
# Replace " n’t" with "n’t"
text = text.replace(" n’t", "n’t").replace("[", "(").replace("]", ")").replace("gon na", "gonna").replace("—————–", "").replace(" n't", "n't")
return text
def process_file(filename):
# Load the file
df = pd.read_csv(filename)
# Check if the "Text" column exists
if "Text" in df.columns:
# Apply the rules to the "Text" column
df['Text'] = df['Text'].apply(lambda x: process_text(str(x)))
# Save the processed data back to the file
df.to_csv(filename, index=False)
print(f"Processed and saved {filename}")
else:
print(f"Column 'Text' not found in {filename}")
def main():
folder_path = "Working_files/Book/"
files = ["non_quotes.csv", "quotes.csv", "book.csv"]
for filename in files:
full_path = os.path.join(folder_path, filename)
if os.path.exists(full_path):
process_file(full_path)
else:
print(f"File {filename} not found in {folder_path}")
if __name__ == "__main__":
main()
#this code here will split the bookcsv file by the calibre chapter deliminators such if calibre is installed
if calibre_installed():
process_and_split_csv("Working_files/Book/book.csv", 'NEWCHAPTERABC')
remove_empty_text_rows("Working_files/Book/book.csv")
#this will wipe the computer of any current audio clips from a previous session
#but itll ask the user first
import os
import tkinter as tk
from tkinter import messagebox
def check_and_wipe_folder(directory_path):
# Check if the directory exists
if not os.path.exists(directory_path):
print(f"The directory {directory_path} does not exist!")
return
# Check for .wav files in the directory
wav_files = [f for f in os.listdir(directory_path) if f.endswith('.wav')]
if wav_files: # If there are .wav files
# Initialize tkinter
root = tk.Tk()
root.withdraw() # Hide the main window
# Ask the user if they want to delete the files
response = messagebox.askyesno("Confirm Deletion", "Audio clips from a previous session have been found. Do you want to wipe them?")
root.destroy() # Destroy the tkinter instance
if response: # If the user clicks 'Yes'
# Iterate through files and delete them
for filename in wav_files:
file_path = os.path.join(directory_path, filename)
try:
os.remove(file_path)
print(f"Deleted: {file_path}")
except Exception as e:
print(f"Failed to delete {file_path}. Reason: {e}")
else:
print("Wipe operation cancelled by the user.")
else:
print("No audio clips from a previous session were found.")
# Usage
check_and_wipe_folder("Working_files/generated_audio_clips/")
#This import will run the gui that will allow you to manually check over and modify the charactor choices for each line made by booknlp
#Then you can change a couple of lines to joe that were incorrectly found to be the Narrerator and such :)
from speaker_editor import BookEditor
if __name__ == "__main__":
app = BookEditor("Working_files/Book/book.csv")
app.mainloop()
from TTS.api import TTS
import tkinter as tk
from tkinter import ttk, scrolledtext, messagebox, simpledialog, filedialog
import threading
import pandas as pd
import random
import os
import time
import os
import pandas as pd
import random
import shutil
import torch
import torchaudio
import time
import pygame
import nltk
from nltk.tokenize import sent_tokenize
from TTS.tts.configs.xtts_config import XttsConfig
from TTS.tts.models.xtts import Xtts
nltk.download('punkt')
# Ensure that nltk punkt is downloaded
nltk.download('punkt', quiet=True)
demo_text = "Imagine a world where endless possibilities await around every corner."
# Load the CSV data
csv_file="Working_files/Book/book.csv"
data = pd.read_csv(csv_file)
#voice actors folder
voice_actors_folder ="tortoise/voices/"
# Get the list of voice actors
voice_actors = [va for va in os.listdir(voice_actors_folder) if va != "cond_latent_example"]
male_voice_actors = [va for va in voice_actors if va.endswith(".M")]
female_voice_actors = [va for va in voice_actors if va.endswith(".F")]
SILENCE_DURATION_MS = 750
# Dictionary to hold each character's selected language
character_languages = {}
models = TTS().list_models()
#selected_tts_model = 'tts_models/multilingual/multi-dataset/xtts_v2'
#I have to do this right now cause they made a weird change to coqui idk super weird the list models isnt working right now
#so this will chekc if its a list isk man and if not then the bug is still there and itll apply the fix
if isinstance(models, list):
print("good it's a list I can apply normal code for model list")
selected_tts_model = models[0]
else:
tts_manager = TTS().list_models()
all_models = tts_manager.list_models()
models = all_models
selected_tts_model = models[0]