-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathpandrator.py
5612 lines (4664 loc) · 287 KB
/
pandrator.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
import tkinter as tk
from tkinter import filedialog, messagebox
import customtkinter as ctk
import re
import json
import threading
import requests
import logging
import time
import datetime
from pydub import AudioSegment
import io
import os
import subprocess
from unidecode import unidecode
import unicodedata
import tempfile
import difflib
from sentence_splitter import SentenceSplitter
import pygame
import shutil
from CTkMessagebox import CTkMessagebox
import ctypes
import math
import platform
from CTkToolTip import CTkToolTip
from num2words import num2words
import ffmpeg
from pdftextract import XPdf
import regex
import hasami
import argparse
import concurrent.futures
import ebooklib
from ebooklib import epub
from bs4 import BeautifulSoup
from mutagen.mp3 import MP3
from mutagen.id3 import ID3, APIC, TIT2, TALB, TPE1, TCON
from mutagen.mp4 import MP4, MP4Cover
from mutagen.oggopus import OggOpus
from mutagen.flac import Picture
from mutagen.id3 import PictureType
import base64
from PIL import Image
import yt_dlp
# Conditional imports for torch and RVC
try:
import torch
torch_available = True
except ImportError:
torch_available = False
try:
from rvc_python.infer import RVCInference
rvc_available = True
except ImportError:
rvc_available = False
rvc_functionality_available = torch_available and rvc_available
silero_languages = [
{"name": "German (v3)", "code": "v3_de.pt"},
{"name": "English (v3)", "code": "v3_en.pt"},
{"name": "English Indic (v3)", "code": "v3_en_indic.pt"},
{"name": "Spanish (v3)", "code": "v3_es.pt"},
{"name": "French (v3)", "code": "v3_fr.pt"},
{"name": "Indic (v3)", "code": "v3_indic.pt"},
{"name": "Russian (v3.1)", "code": "v3_1_ru.pt"},
{"name": "Tatar (v3)", "code": "v3_tt.pt"},
{"name": "Ukrainian (v3)", "code": "v3_ua.pt"},
{"name": "Uzbek (v3)", "code": "v3_uz.pt"},
{"name": "Kalmyk (v3)", "code": "v3_xal.pt"}
]
class TextPreprocessor:
def __init__(self, language_var, max_sentence_length, enable_sentence_splitting,
enable_sentence_appending, remove_diacritics, disable_paragraph_detection, tts_service):
self.language_var = language_var
self.max_sentence_length = max_sentence_length
self.enable_sentence_splitting = enable_sentence_splitting
self.enable_sentence_appending = enable_sentence_appending
self.remove_diacritics = remove_diacritics
self.disable_paragraph_detection = disable_paragraph_detection
self.tts_service = tts_service
self.chunk_size = 20000
def preprocess_text(self, text, pdf_preprocessed, source_file, disable_paragraph_detection):
if len(text) > self.chunk_size:
processed_sentences = self.parallel_preprocess_text(text, pdf_preprocessed, source_file, disable_paragraph_detection.get())
else:
processed_sentences = self.sequential_preprocess_text(text, pdf_preprocessed, source_file, disable_paragraph_detection.get())
# Add the merging of consecutive chapter sentences here
processed_sentences = self.merge_consecutive_chapters(processed_sentences)
return processed_sentences
def parallel_preprocess_text(self, text, pdf_preprocessed, source_file, disable_paragraph_detection):
chunks = self.split_text_into_chunks(text)
args = (
self.language_var.get(),
self.max_sentence_length.get(),
self.enable_sentence_splitting.get(),
self.enable_sentence_appending.get(),
self.remove_diacritics.get(),
self.tts_service.get()
)
with concurrent.futures.ProcessPoolExecutor() as executor:
# Use enumerate to keep track of the original chunk order
future_to_index = {executor.submit(self.process_chunk, chunk, pdf_preprocessed, source_file, disable_paragraph_detection, *args): i
for i, chunk in enumerate(chunks)}
# Create a list to store results in the correct order
processed_chunks = [None] * len(chunks)
for future in concurrent.futures.as_completed(future_to_index):
index = future_to_index[future]
processed_chunks[index] = future.result()
# Flatten the list of processed sentences
all_processed_sentences = [sentence for chunk in processed_chunks for sentence in chunk]
# Renumber the sentences
for i, sentence in enumerate(all_processed_sentences, start=1):
sentence['sentence_number'] = str(i)
return all_processed_sentences
@staticmethod
def process_chunk(chunk, pdf_preprocessed, source_file, disable_paragraph_detection, language, max_sentence_length,
enable_sentence_splitting, enable_sentence_appending, remove_diacritics, tts_service):
# Normalize newlines to LF and replace carriage returns with LF
chunk = re.sub(r'\r\n?', '\n', chunk)
paragraph_breaks = []
if not disable_paragraph_detection:
if pdf_preprocessed:
paragraph_breaks = list(re.finditer(r'\n', chunk))
elif not pdf_preprocessed and source_file.endswith(".pdf"):
chunk = TextPreprocessor.preprocess_text_pdf(chunk)
elif source_file.endswith("_edited.txt"):
paragraph_breaks = list(re.finditer(r'\n', chunk))
else:
chunk = re.sub(r'(?<!\n)\n(?!\n)', ' ', chunk)
paragraph_breaks = list(re.finditer(r'\n', chunk))
# Replace tabs with spaces
chunk = re.sub(r'\t', ' ', chunk)
if remove_diacritics:
chunk = ''.join(char for char in chunk if not unicodedata.combining(char))
chunk = unidecode(chunk)
# Additional preprocessing step to handle chapters, section titles, etc.
chunk = re.sub(r'(^|\n+)([^\n.!?]+)(?=\n+|$)', r'\1\2.', chunk)
sentences = TextPreprocessor.split_into_sentences(chunk, language, tts_service)
processed_sentences = []
for sentence in sentences:
if not sentence.strip(): # Skip empty sentences
continue
is_paragraph = False
for match in paragraph_breaks:
preceding_text = chunk[match.start()-15:match.start()]
sentence_end = sentence[-15:]
if TextPreprocessor.calculate_similarity(preceding_text, sentence_end) >= 0.8:
is_paragraph = True
break
is_chapter = False
if "[[Chapter]]" in sentence:
is_chapter = True
sentence = sentence.replace("[[Chapter]]", "").strip()
is_paragraph = True # Mark chapter sentences as paragraphs
sentence_dict = {
"original_sentence": sentence,
"paragraph": "yes" if is_paragraph else "no",
"chapter": "yes" if is_chapter else "no",
"split_part": None
}
if enable_sentence_splitting:
split_sentences = TextPreprocessor.split_long_sentences(sentence_dict, max_sentence_length)
processed_sentences.extend(split_sentences)
else:
processed_sentences.append(sentence_dict)
if enable_sentence_appending:
processed_sentences = TextPreprocessor.append_short_sentences(processed_sentences, max_sentence_length)
split_sentences = []
for sentence_dict in processed_sentences:
split_sentences.extend(TextPreprocessor.split_long_sentences_2(sentence_dict, max_sentence_length))
return split_sentences
def split_text_into_chunks(self, text):
chunks = []
total_length = len(text)
target_chunk_size = total_length // 4
start = 0
while start < total_length:
# Find the next paragraph break after the target chunk size
end = start + target_chunk_size
next_para_break = text.find('\n\n', end)
if next_para_break == -1:
# If no paragraph break is found, this is the last chunk
chunks.append(text[start:])
break
# Find the last sentence end before the paragraph break
last_sentence_end = max(
text.rfind('. ', start, next_para_break),
text.rfind('! ', start, next_para_break),
text.rfind('? ', start, next_para_break)
)
if last_sentence_end == -1 or last_sentence_end <= start:
# If no sentence end is found, use the paragraph break
end = next_para_break + 2
else:
# Use the last sentence end + 2 to include the period and space
end = last_sentence_end + 2
chunks.append(text[start:end])
start = end
return chunks
def sequential_preprocess_text(self, text, pdf_preprocessed, source_file, disable_paragraph_detection):
return self.process_chunk(text, pdf_preprocessed, source_file, disable_paragraph_detection,
self.language_var.get(), self.max_sentence_length.get(),
self.enable_sentence_splitting.get(), self.enable_sentence_appending.get(),
self.remove_diacritics.get(), self.tts_service.get())
@staticmethod
def preprocess_text_pdf(text, remove_double_newlines=False):
text = regex.sub(r'\r\n|\r', '\n', text)
text = regex.sub(r'[\x00-\x09\x0B-\x1F\x7F]', '', text)
if remove_double_newlines:
text = regex.sub(r'(?<![.!?])\n\n', ' ', text)
else:
text = regex.sub(r'\n$(?<!\n[ \t]*\n)|(?<!\n[ \t]*)\n(?![ \t]*\n)', ' ', text)
text = regex.sub(r'[ \\t]*\\n[ \\t]*\\n[ \\t]*(?:\\n[ \\t]*){0,2}', '\\n', text)
text = regex.sub(r' {2,}', ' ', text)
text = regex.sub(r'(?m)^[ \\t]+', '', text)
return text
@staticmethod
def split_into_sentences(text, language, tts_service):
if tts_service == "XTTS":
if language == "zh-cn":
return TextPreprocessor.split_chinese_sentences(text)
elif language == "ja":
return hasami.segment_sentences(text)
else:
splitter = SentenceSplitter(language=language)
return splitter.split(text)
else: # Silero
silero_to_simple_lang_codes = {
"German (v3)": "de", "English (v3)": "en", "English Indic (v3)": "en",
"Spanish (v3)": "es", "French (v3)": "fr", "Indic (v3)": "hi",
"Russian (v3.1)": "ru", "Tatar (v3)": "tt", "Ukrainian (v3)": "uk",
"Uzbek (v3)": "uz", "Kalmyk (v3)": "xal"
}
language = silero_to_simple_lang_codes.get(language, "en")
splitter = SentenceSplitter(language=language)
return splitter.split(text)
@staticmethod
def split_chinese_sentences(text):
end_punctuation = '。!?…'
segments = re.split(f'([{end_punctuation}])', text)
sentences = [''.join(segments[i:i+2]).strip() for i in range(0, len(segments), 2) if segments[i]]
return sentences
@staticmethod
def calculate_similarity(str1, str2):
return difflib.SequenceMatcher(None, str1, str2).ratio()
@staticmethod
def split_long_sentences(sentence_dict, max_sentence_length):
sentence = sentence_dict["original_sentence"]
paragraph = sentence_dict["paragraph"]
if len(sentence) <= max_sentence_length:
# Return a copy of the original dictionary preserving all values
return [sentence_dict.copy()]
punctuation_marks = [',', ';', ':', '。', '!', '?'] if sentence_dict.get("language") == "zh-cn" else [',', ':', ';', '–']
conjunction_marks = [' and ', ' or ', 'which'] if sentence_dict.get("language") != "zh-cn" else []
min_distance = 10 if sentence_dict.get("language") == "zh-cn" else 30
best_split_index = TextPreprocessor.find_best_split_index(sentence, punctuation_marks, conjunction_marks, min_distance, max_sentence_length)
if best_split_index is None:
return [sentence_dict.copy()]
first_part = sentence[:best_split_index].strip()
second_part = sentence[best_split_index:].strip()
# Create copies of the original dictionary for each part and update only relevant fields
first_part_dict = sentence_dict.copy()
first_part_dict.update({
"original_sentence": first_part,
"split_part": 0,
"paragraph": "no"
})
second_part_dict = sentence_dict.copy()
second_part_dict.update({
"original_sentence": second_part,
"split_part": 1,
"paragraph": paragraph
})
return [first_part_dict, second_part_dict]
@staticmethod
def find_best_split_index(sentence, punctuation_marks, conjunction_marks, min_distance, max_sentence_length):
best_split_index = None
min_diff = float('inf')
for mark in punctuation_marks:
indices = [i for i, c in enumerate(sentence) if c == mark]
for index in indices:
if min_distance <= index <= len(sentence) - min_distance:
if not (mark == ',' and index > 0 and index < len(sentence) - 1 and
sentence[index-1].isdigit() and sentence[index+1].isdigit()):
diff = abs(index - len(sentence) // 2)
if diff < min_diff:
min_diff = diff
best_split_index = index + 1
if best_split_index is None:
for mark in conjunction_marks:
index = sentence.find(mark)
if min_distance <= index <= len(sentence) - min_distance:
best_split_index = index
break
return best_split_index
@staticmethod
def split_long_sentences_2(sentence_dict, max_sentence_length):
sentence = sentence_dict["original_sentence"]
paragraph = sentence_dict["paragraph"]
split_part = sentence_dict["split_part"]
if len(sentence) <= max_sentence_length:
return [sentence_dict]
punctuation_marks = [',', ';', ':', '。', '!', '?'] if sentence_dict.get("language") == "zh-cn" else [',', ':', ';', '–']
conjunction_marks = [' and ', ' or ', 'which'] if sentence_dict.get("language") != "zh-cn" else []
min_distance = 10 if sentence_dict.get("language") == "zh-cn" else 30
best_split_index = TextPreprocessor.find_best_split_index(sentence, punctuation_marks, conjunction_marks, min_distance, max_sentence_length)
if best_split_index is None:
return [sentence_dict]
first_part = sentence[:best_split_index].strip()
second_part = sentence[best_split_index:].strip()
split_sentences = []
split_part_prefix = "0" if split_part is None else str(split_part)
# Preserve other fields by making a copy of sentence_dict for both parts
first_part_dict = sentence_dict.copy()
first_part_dict.update({
"original_sentence": first_part,
"split_part": split_part_prefix + "a",
"paragraph": "no"
})
split_sentences.append(first_part_dict)
if len(second_part) > max_sentence_length:
second_part_dict = sentence_dict.copy()
if split_part_prefix == "0" and paragraph == "yes":
second_part_dict.update({
"original_sentence": second_part,
"split_part": "1a",
"paragraph": "yes"
})
split_sentences.extend(TextPreprocessor.split_long_sentences_2(second_part_dict, max_sentence_length))
else:
second_part_dict.update({
"original_sentence": second_part,
"split_part": split_part_prefix + "b",
"paragraph": "no" if split_part_prefix == "0" else paragraph
})
split_sentences.extend(TextPreprocessor.split_long_sentences_2(second_part_dict, max_sentence_length))
else:
second_part_dict = sentence_dict.copy()
second_part_dict.update({
"original_sentence": second_part,
"split_part": split_part_prefix + "b",
"paragraph": paragraph
})
split_sentences.append(second_part_dict)
return split_sentences
@staticmethod
def append_short_sentences(sentence_dicts, max_sentence_length):
appended_sentences = []
i = 0
while i < len(sentence_dicts):
current_sentence = sentence_dicts[i]
# Chapter sentences are never modified
if current_sentence.get("chapter") == "yes":
appended_sentences.append(current_sentence)
i += 1
continue
# Paragraph sentences: attempt to append to the previous sentence
if current_sentence.get("paragraph") == "yes":
if i > 0:
prev_sentence = appended_sentences[-1]
if prev_sentence.get("chapter") != "yes":
combined_text = prev_sentence["original_sentence"] + ' ' + current_sentence["original_sentence"]
if len(combined_text) <= max_sentence_length:
prev_sentence["original_sentence"] = combined_text
prev_sentence["paragraph"] = "yes"
i += 1
continue
# If we can't append to the previous sentence, add current sentence as is
appended_sentences.append(current_sentence)
i += 1
continue
# Try to append to the previous sentence
if i > 0:
prev_sentence = appended_sentences[-1]
if (prev_sentence.get("chapter") != "yes" and
prev_sentence.get("paragraph") != "yes"):
combined_text = prev_sentence["original_sentence"] + ' ' + current_sentence["original_sentence"]
if len(combined_text) <= max_sentence_length:
prev_sentence["original_sentence"] = combined_text
i += 1
continue
# Try to prepend to the next sentence
if i < len(sentence_dicts) - 1:
next_sentence = sentence_dicts[i + 1]
if (next_sentence.get("chapter") != "yes" and
next_sentence.get("paragraph") != "yes"):
combined_text = current_sentence["original_sentence"] + ' ' + next_sentence["original_sentence"]
if len(combined_text) <= max_sentence_length:
# Modify the next sentence and skip it
next_sentence["original_sentence"] = combined_text
i += 2
appended_sentences.append(next_sentence)
continue
# If no appending or prepending occurred, add the current sentence as is
appended_sentences.append(current_sentence)
i += 1
return appended_sentences
@staticmethod
def convert_digits_to_words(sentence, language):
def replace_numbers(match):
number = match.group(0)
try:
silero_to_num2words_lang = {
"German (v3)": "de",
"English (v3)": "en",
"English Indic (v3)": "en",
"Spanish (v3)": "es",
"French (v3)": "fr",
"Indic (v3)": "hi",
"Russian (v3.1)": "ru",
"Tatar (v3)": "tt",
"Ukrainian (v3)": "uk",
"Uzbek (v3)": "uz",
"Kalmyk (v3)": "xal"
}
num2words_lang = silero_to_num2words_lang.get(language, "en")
return num2words(int(number), lang=num2words_lang)
except ValueError:
return number
return re.sub(r'\d+', replace_numbers, sentence)
def convert_digits_to_words(self, sentence):
def replace_numbers(match):
number = match.group(0)
try:
# Get the selected Silero language
silero_language_name = self.language_var.get()
# Map Silero language names to num2words language codes
silero_to_num2words_lang = {
"German (v3)": "de",
"English (v3)": "en",
"English Indic (v3)": "en",
"Spanish (v3)": "es",
"French (v3)": "fr",
"Indic (v3)": "hi",
"Russian (v3.1)": "ru",
"Tatar (v3)": "tt",
"Ukrainian (v3)": "uk",
"Uzbek (v3)": "uz",
"Kalmyk (v3)": "xal"
}
# Get the corresponding num2words language code
num2words_lang = silero_to_num2words_lang.get(silero_language_name, "en")
return num2words(int(number), lang=num2words_lang)
except ValueError:
return number
return re.sub(r'\d+', replace_numbers, sentence)
@staticmethod
def merge_consecutive_chapters(sentences):
merged_sentences = []
i = 0
while i < len(sentences):
current_sentence = sentences[i]
# Check if the current sentence is marked as a chapter
if current_sentence.get("chapter") == "yes":
merged_sentence_text = current_sentence["original_sentence"].strip()
# Look ahead to merge consecutive chapter sentences
i += 1
while i < len(sentences) and sentences[i].get("chapter") == "yes":
next_sentence_text = sentences[i]["original_sentence"].strip()
# Ensure each sentence ends with punctuation
if not merged_sentence_text.endswith(('.', '!', '?')):
merged_sentence_text += "."
merged_sentence_text += " " + next_sentence_text
i += 1
# After merging, mark the sentence as both a chapter and a paragraph
merged_sentences.append({
"original_sentence": merged_sentence_text.strip(),
"paragraph": "yes", # Mark it as a paragraph
"chapter": "yes", # Retain chapter marking
"split_part": None
})
else:
# If it's not a chapter, just add the sentence as-is
merged_sentences.append(current_sentence)
i += 1
return merged_sentences
class TTSOptimizerGUI:
def __init__(self, master):
self.master = master
master.title("Pandrator")
ctk.set_appearance_mode("dark") # Set the appearance mode to dark
self.timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
width = master.winfo_screenwidth()
height = master.winfo_screenheight()
geometry = str(width) + "x" + str(height)
master.geometry(geometry)
# Set up logging
logs_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "logs")
os.makedirs(logs_dir, exist_ok=True)
self.log_file_path = os.path.join(logs_dir, f"pandrator_{self.timestamp}.log")
logger = logging.getLogger() # Get the root logger
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s [%(levelname)s] %(message)s")
file_handler = logging.FileHandler(self.log_file_path, mode='w')
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
stream_handler = logging.StreamHandler()
stream_handler.setFormatter(formatter)
logger.addHandler(stream_handler)
# Log the absolute path of the log file
logging.info(f"Log file created at: {self.log_file_path}")
self.channel = None
self.playlist_index = None
self.previous_tts_service = None
self.enable_tts_evaluation = ctk.BooleanVar(value=False)
self.stop_flag = False
self.pdf_preprocessed = False
self.delete_session_flag = False
self.pre_selected_source_file = None
self.external_server_connected = False
self.use_external_server_voicecraft = ctk.BooleanVar(value=False)
self.external_server_url_voicecraft = ctk.StringVar()
self.external_server_url = ctk.StringVar()
self.use_external_server = ctk.BooleanVar(value=False)
self.external_server_address = ctk.StringVar()
self.external_server_address.trace_add("write", self.populate_speaker_dropdown)
self.enable_dubbing = ctk.BooleanVar(value=False)
self.server_connected = False
self.external_server_connected_voicecraft = False
self.remove_double_newlines = ctk.BooleanVar(value=False)
self.advanced_settings_switch = None
self.tts_voices_folder = "tts_voices"
self.unload_model_after_sentence = ctk.BooleanVar(value=False)
self.source_file = ""
self.first_optimisation_prompt = ctk.StringVar(value="Your task is to spell out abbreviations and titles and convert Roman numerals to English words in the sentence(s) you are given. For example: Prof. to Professor, Dr. to Doctor, et. al. to et alia, etc. to et cetera, Section III to Section Three, Chapter V to Chapter Five and so on. Don't change ANYTHING ELSE and output ONLY the complete processed text. If no adjustments are necessary, just output the sentence(s) without changing or appending ANYTHING. Include ABSOLUTELY NO comments, NO acknowledgments, NO explanations, NO notes and so on. This is your text: ")
self.second_optimisation_prompt = ctk.StringVar(value="Your task is to analyze a text fragment carefully and correct punctuation. Also, correct any misspelled words and possible OCR artifacts based on context. If there is a number that looks out of place because it could have been a page number captured by OCR and doesn't fit in the context, remove it. Don't change ANYTHING ELSE and output ONLY the complete processed text (even if no changes were made). No comments, acknowledgments, explanations or notes. This is your text: ")
self.third_optimisation_prompt = ctk.StringVar(value="Your task is to spell difficult FOREIGN, NON-ENGLISH words phonetically. Don't alter ANYTHING ELSE in the text - English words remain the same. Don't do anything else, don't add anything, don't include any comments, explanations, notes or acknowledgments. Example: Jiyu means freedom in Japanese becomes jeeyou means freedom in Japanese - jiyu is spelled phonetically as a Japanese word, the rest is not changed. This is your text: ")
self.enable_first_evaluation = ctk.BooleanVar(value=False)
self.enable_second_evaluation = ctk.BooleanVar(value=False)
self.enable_third_evaluation = ctk.BooleanVar(value=False)
self.enable_first_prompt = ctk.BooleanVar(value=True)
self.enable_second_prompt = ctk.BooleanVar(value=False)
self.enable_third_prompt = ctk.BooleanVar(value=False)
self.silence_length = ctk.IntVar(value=750)
self.paragraph_silence_length = ctk.IntVar(value=2000)
self.output_format = ctk.StringVar(value="opus")
self.bitrate = ctk.StringVar(value="64k")
self.first_prompt_model = ctk.StringVar(value="default")
self.second_prompt_model = ctk.StringVar(value="default")
self.third_prompt_model = ctk.StringVar(value="default")
self.loaded_model = None
self.enable_sentence_splitting = ctk.BooleanVar(value=True)
self.max_sentence_length = ctk.IntVar(value=160)
self.enable_sentence_appending = ctk.BooleanVar(value=True)
self.remove_diacritics = ctk.BooleanVar(value=False)
self.enable_fade = ctk.BooleanVar(value=True)
self.fade_in_duration = ctk.IntVar(value=75)
self.fade_out_duration = ctk.IntVar(value=75)
self.enable_rvc = ctk.BooleanVar(value=False)
self.enable_llm_processing = ctk.BooleanVar(value=False)
self.enable_first_prompt = ctk.BooleanVar(value=self.enable_llm_processing.get())
self.playlist_stopped = False
self.target_mos_value = ctk.StringVar(value="2.9")
self.max_attempts = ctk.IntVar(value=5)
self.paused = False
self.playing = False
self.session_name = ctk.StringVar()
self.tts_service = ctk.StringVar(value="XTTS")
self.mark_paragraphs_multiple_newlines = ctk.BooleanVar(value=False)
self.xtts_temperature = ctk.DoubleVar(value=0.75)
self.xtts_length_penalty = ctk.DoubleVar(value=1.0)
self.xtts_repetition_penalty = ctk.DoubleVar(value=5.0)
self.xtts_top_k = ctk.IntVar(value=50)
self.xtts_top_p = ctk.DoubleVar(value=0.85)
self.xtts_speed = ctk.DoubleVar(value=1.0)
self.xtts_enable_text_splitting = ctk.BooleanVar(value=True)
self.xtts_stream_chunk_size = ctk.IntVar(value=100)
self.enable_translation = ctk.BooleanVar(value=False)
self.original_language = ctk.StringVar(value="English")
self.target_language = ctk.StringVar(value="en")
self.enable_translation_evaluation = ctk.BooleanVar(value=False)
self.enable_glossary = ctk.BooleanVar(value=False)
self.translation_model = ctk.StringVar(value="sonnet")
self.anthropic_api_key = ctk.StringVar()
self.openai_api_key = ctk.StringVar()
self.deepl_api_key = ctk.StringVar()
self.selected_video_file = ctk.StringVar()
self.video_file_selection_label = None
self.whisperx_language = ctk.StringVar(value="English")
self.whisperx_model = ctk.StringVar(value="large-v3")
self.language_var = ctk.StringVar(value="en")
self.selected_speaker = ctk.StringVar(value="")
self.rvc_models_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "rvc_models")
os.makedirs(self.rvc_models_dir, exist_ok=True)
self.rvc_models = self.get_rvc_models()
self.rvc_models_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "rvc_models")
os.makedirs(self.rvc_models_dir, exist_ok=True)
self.rvc_models = self.get_rvc_models()
self.top_k = ctk.StringVar(value="50")
self.top_p = ctk.StringVar(value="0.9")
self.temperature = ctk.StringVar(value="0.7")
self.stop_repetition = ctk.StringVar(value="10")
self.kvcache = ctk.StringVar(value="0")
self.sample_batch_size = ctk.StringVar(value="8")
self.metadata = {"title": "", "album": "", "artist": "", "genre": "", "language": ""}
self.metadata_title = ctk.StringVar()
self.metadata_album = ctk.StringVar()
self.metadata_artist = ctk.StringVar()
self.metadata_genre = ctk.StringVar()
self.metadata_language = ctk.StringVar()
# Bind keyboard and mouse events
self.master.bind("<space>", self.handle_keyboard_event)
self.master.bind("<m>", self.mark_sentences_for_regeneration)
self.master.bind("<M>", self.mark_sentences_for_regeneration)
self.master.bind("<Button-3>", self.mark_sentences_for_regeneration)
self.load_metadata() # Load metadata on startup
self.current_sentence = None
self.previous_sentence = None
self.whisper_languages = [
'Afrikaans', 'Albanian', 'Amharic', 'Arabic', 'Armenian', 'Assamese', 'Azerbaijani', 'Bashkir', 'Basque',
'Belarusian', 'Bengali', 'Bosnian', 'Breton', 'Bulgarian', 'Burmese', 'Cantonese', 'Castilian', 'Catalan',
'Chinese', 'Croatian', 'Czech', 'Danish', 'Dutch', 'English', 'Estonian', 'Faroese', 'Finnish', 'Flemish',
'French', 'Galician', 'Georgian', 'German', 'Greek', 'Gujarati', 'Haitian', 'Haitian Creole', 'Hausa',
'Hawaiian', 'Hebrew', 'Hindi', 'Hungarian', 'Icelandic', 'Indonesian', 'Italian', 'Japanese', 'Javanese',
'Kannada', 'Kazakh', 'Khmer', 'Korean', 'Lao', 'Latin', 'Latvian', 'Letzeburgesch', 'Lingala', 'Lithuanian',
'Luxembourgish', 'Macedonian', 'Malagasy', 'Malay', 'Malayalam', 'Maltese', 'Maori', 'Marathi', 'Moldavian',
'Moldovan', 'Mongolian', 'Myanmar', 'Nepali', 'Norwegian', 'Nynorsk', 'Occitan', 'Panjabi', 'Pashto',
'Persian', 'Polish', 'Portuguese', 'Punjabi', 'Pushto', 'Romanian', 'Russian', 'Sanskrit', 'Serbian',
'Shona', 'Sindhi', 'Sinhala', 'Sinhalese', 'Slovak', 'Slovenian', 'Somali', 'Spanish', 'Sundanese',
'Swahili', 'Swedish', 'Tagalog', 'Tajik', 'Tamil', 'Tatar', 'Telugu', 'Thai', 'Tibetan', 'Turkish',
'Turkmen', 'Ukrainian', 'Urdu', 'Uzbek', 'Valencian', 'Vietnamese', 'Welsh', 'Yiddish', 'Yoruba'
]
self.main_frame = ctk.CTkFrame(master)
self.main_frame.pack(fill=tk.BOTH, expand=True)
# Configure columns to have equal weight AND uniform width
self.main_frame.grid_columnconfigure(0, weight=1, uniform="group1") # Uniform group
self.main_frame.grid_columnconfigure(1, weight=1, uniform="group1") # Same uniform group
# Create left and right frames
self.left_frame = ctk.CTkFrame(self.main_frame)
self.right_frame = ctk.CTkFrame(self.main_frame)
self.left_frame.grid(row=0, column=0, sticky="nsew")
self.right_frame.grid(row=0, column=1, sticky="nsew")
# Make sure the main frame's row expands
self.main_frame.grid_rowconfigure(0, weight=1)
# Inside left_frame: Use grid for the scrollable frame
self.left_scrollable_frame = ctk.CTkScrollableFrame(self.left_frame)
self.left_scrollable_frame.grid(row=0, column=0, sticky="nsew") # Use grid and sticky
self.left_frame.grid_rowconfigure(0, weight=1) # Let the scrollable frame expand vertically
self.left_frame.grid_columnconfigure(0, weight=1) # Let the scrollable frame expand horizontally
self.tabview = ctk.CTkTabview(self.left_scrollable_frame)
self.tabview.pack(fill=tk.BOTH, expand=True, padx=3, pady=5)
# Create tabs
self.create_session_tab()
self.create_text_processing_tab()
self.create_audio_processing_tab()
self.create_api_keys_tab()
self.create_logs_tab()
self.create_train_xtts_tab()
# Create Generated Sentences section in right frame
self.create_generated_sentences_section()
# Additional setup
#self.update_tts_service()
self.toggle_advanced_tts_settings()
self.text_preprocessor = TextPreprocessor(self.language_var, self.max_sentence_length,
self.enable_sentence_splitting, self.enable_sentence_appending,
self.remove_diacritics, self.disable_paragraph_detection, self.tts_service)
self.initialize_rvc()
def create_session_tab(self):
self.session_tab = self.tabview.add("Session")
self.session_tab.grid_columnconfigure(0, weight=1, uniform="session_columns")
self.session_tab.grid_columnconfigure(1, weight=1, uniform="session_columns")
self.session_tab.grid_columnconfigure(2, weight=1, uniform="session_columns")
self.session_tab.grid_columnconfigure(3, weight=1, uniform="session_columns")
self.session_name_label = ctk.CTkLabel(self.session_tab, text="Untitled Session", font=ctk.CTkFont(size=20, weight="bold"))
self.session_name_label.grid(row=0, column=0, columnspan=4, padx=5, pady=5, sticky=tk.W)
# Session Section
ctk.CTkLabel(self.session_tab, text="Session", font=ctk.CTkFont(size=14, weight="bold")).grid(row=1, column=0, columnspan=4, padx=10, pady=10, sticky=tk.W)
session_frame = ctk.CTkFrame(self.session_tab, fg_color="gray20", corner_radius=10)
session_frame.grid(row=2, column=0, columnspan=4, padx=10, pady=(0, 20), sticky=tk.EW)
session_frame.grid_columnconfigure(0, weight=1)
session_frame.grid_columnconfigure(1, weight=1)
session_frame.grid_columnconfigure(2, weight=1)
session_frame.grid_columnconfigure(3, weight=1)
ctk.CTkButton(session_frame, text="New Session", command=self.new_session, fg_color="#2e8b57", hover_color="#3cb371").grid(row=0, column=0, padx=10, pady=(10, 10), sticky=tk.EW)
ctk.CTkButton(session_frame, text="Load Session", command=self.load_session).grid(row=0, column=1, padx=10, pady=(10, 10), sticky=tk.EW)
ctk.CTkButton(session_frame, text="Delete Session", command=self.delete_session, fg_color="dark red", hover_color="red").grid(row=0, column=3, padx=10, pady=(10, 10), sticky=tk.EW)
ctk.CTkButton(session_frame, text="View Session Folder", command=self.view_session_folder).grid(row=0, column=2, padx=10, pady=(10, 10), sticky=tk.EW)
# Source File Section
ctk.CTkLabel(self.session_tab, text="Source File", font=ctk.CTkFont(size=14, weight="bold")).grid(row=3, column=0, columnspan=4, padx=10, pady=10, sticky=tk.W)
source_file_frame = ctk.CTkFrame(self.session_tab, fg_color="gray20", corner_radius=10)
source_file_frame.grid(row=4, column=0, columnspan=4, padx=10, pady=(0, 20), sticky=tk.EW)
source_file_frame.grid_columnconfigure(0, weight=1)
source_file_frame.grid_columnconfigure(1, weight=1)
source_file_frame.grid_columnconfigure(2, weight=2)
self.select_file_button = ctk.CTkButton(source_file_frame, text="Select File", command=self.select_file)
self.select_file_button.grid(row=0, column=0, padx=10, pady=(10, 10), sticky=tk.EW)
self.paste_text_button = ctk.CTkButton(source_file_frame, text="Paste or Write", command=self.paste_text)
self.paste_text_button.grid(row=0, column=1, padx=10, pady=(10, 10), sticky=tk.EW)
self.download_from_url_button = ctk.CTkButton(source_file_frame, text="Download from URL", command=self.download_from_url)
self.download_from_url_button.grid(row=0, column=2, padx=5, pady=(10, 10), sticky=tk.EW) # Added URL button
self.selected_file_label = ctk.CTkLabel(source_file_frame, text="No file selected")
self.selected_file_label.grid(row=0, column=3, padx=10, pady=(10, 10), sticky=tk.W)
# TTS Settings Section
ctk.CTkLabel(self.session_tab, text="TTS Settings", font=ctk.CTkFont(size=14, weight="bold")).grid(row=5, column=0, columnspan=4, padx=10, pady=10, sticky=tk.W)
session_settings_frame = ctk.CTkFrame(self.session_tab, fg_color="gray20", corner_radius=10)
session_settings_frame.grid(row=6, column=0, columnspan=4, padx=10, pady=(0, 20), sticky=tk.EW)
session_settings_frame.grid_columnconfigure(0, weight=1)
session_settings_frame.grid_columnconfigure(1, weight=1)
session_settings_frame.grid_columnconfigure(2, weight=1)
session_settings_frame.grid_columnconfigure(3, weight=1)
ctk.CTkLabel(session_settings_frame, text="TTS Service:").grid(row=2, column=0, padx=10, pady=5, sticky=tk.W)
self.tts_service_dropdown = ctk.CTkOptionMenu(session_settings_frame, variable=self.tts_service, values=["XTTS", "VoiceCraft", "Silero"], command=self.update_tts_service)
self.tts_service_dropdown.grid(row=2, column=1, padx=10, pady=5, sticky=tk.EW)
self.voicecraft_model = ctk.StringVar(value="330M_TTSEnhanced")
self.voicecraft_model_label = ctk.CTkLabel(session_settings_frame, text="VoiceCraft Model:")
self.voicecraft_model_label.grid(row=3, column=0, padx=10, pady=5, sticky=tk.W)
self.voicecraft_model_dropdown = ctk.CTkOptionMenu(session_settings_frame, variable=self.voicecraft_model, values=["830M_TTSEnhanced", "330M_TTSEnhanced"])
self.voicecraft_model_dropdown.grid(row=3, column=1, padx=10, pady=5, sticky=tk.EW)
self.voicecraft_model_label.grid_remove()
self.voicecraft_model_dropdown.grid_remove()
self.xtts_model = ctk.StringVar(value="")
self.xtts_model_label = ctk.CTkLabel(session_settings_frame, text="XTTS Model:")
self.xtts_model_label.grid(row=3, column=0, padx=10, pady=5, sticky=tk.W)
self.xtts_model_dropdown = ctk.CTkOptionMenu(session_settings_frame, variable=self.xtts_model, values=[], command=self.on_xtts_model_change)
self.xtts_model_dropdown.grid(row=3, column=1, padx=10, pady=5, sticky=tk.EW)
self.connect_to_server_button = ctk.CTkButton(session_settings_frame, text="Connect to Server", command=self.connect_to_server)
self.connect_to_server_button.grid(row=2, column=2, columnspan=2, padx=10, pady=5, sticky=tk.EW)
self.use_external_server_switch = ctk.CTkSwitch(session_settings_frame, text="Use an external server", variable=self.use_external_server, command=self.toggle_external_server)
self.use_external_server_switch.grid(row=4, column=0, padx=10, pady=5, sticky=tk.W)
self.external_server_url_entry = ctk.CTkEntry(session_settings_frame, textvariable=self.external_server_url)
self.external_server_url_entry.grid(row=4, column=1, columnspan=3, padx=10, pady=5, sticky=tk.EW)
self.external_server_url_entry.grid_remove()
self.use_external_server_voicecraft_switch = ctk.CTkSwitch(session_settings_frame, text="Use an external server", variable=self.use_external_server_voicecraft, command=self.toggle_external_server)
self.use_external_server_voicecraft_switch.grid(row=5, column=0, padx=10, pady=5, sticky=tk.W)
self.use_external_server_voicecraft_switch.grid_remove()
self.external_server_url_entry_voicecraft = ctk.CTkEntry(session_settings_frame, textvariable=self.external_server_url_voicecraft)
self.external_server_url_entry_voicecraft.grid(row=5, column=1, columnspan=3, padx=10, pady=5, sticky=tk.EW)
self.external_server_url_entry_voicecraft.grid_remove()
ctk.CTkLabel(session_settings_frame, text="Language:").grid(row=6, column=0, padx=10, pady=5, sticky=tk.W)
self.language_dropdown = ctk.CTkComboBox(
session_settings_frame,
variable=self.language_var,
values=["en", "es", "fr", "de", "it", "pt", "pl", "tr", "ru", "nl", "cs", "ar", "zh-cn", "ja", "hu", "ko", "hi"]
)
self.language_dropdown.grid(row=6, column=1, padx=10, pady=5, sticky=tk.EW)
self.language_var.trace_add("write", self.on_language_selected)
ctk.CTkLabel(session_settings_frame, text="Speaker Voice:").grid(row=7, column=0, padx=10, pady=5, sticky=tk.W)
self.speaker_dropdown = ctk.CTkOptionMenu(session_settings_frame, variable=self.selected_speaker, values=[])
self.speaker_dropdown.grid(row=7, column=1, padx=10, pady=5, sticky=tk.EW)
self.upload_new_voices_button = ctk.CTkButton(session_settings_frame, text="Upload New Voices", command=self.upload_speaker_voice)
self.upload_new_voices_button.grid(row=7, column=2, padx=10, pady=(10, 10), sticky=tk.EW)
self.sample_length = ctk.StringVar(value="3")
self.sample_length_dropdown = ctk.CTkOptionMenu(session_settings_frame, variable=self.sample_length, values=[str(i) for i in range(3, 13)])
self.sample_length_dropdown.grid(row=7, column=3, padx=10, pady=5, sticky=tk.EW)
self.sample_length_dropdown.grid_remove()
ctk.CTkLabel(session_settings_frame, text="Speed:").grid(row=8, column=0, padx=10, pady=5, sticky=tk.W)
speed_slider = ctk.CTkSlider(session_settings_frame, from_=0.2, to=2.0, number_of_steps=180, variable=self.xtts_speed)
speed_slider.grid(row=8, column=1, columnspan=2, padx=10, pady=5, sticky=tk.EW)
self.speed_value_label = ctk.CTkLabel(session_settings_frame, text=f"Speed: {self.xtts_speed.get():.2f}")
self.speed_value_label.grid(row=8, column=3, padx=10, pady=5, sticky=tk.W)
speed_slider.configure(command=self.update_speed_label)
self.show_advanced_tts_settings = ctk.BooleanVar(value=False)
self.advanced_settings_switch = ctk.CTkSwitch(session_settings_frame, text="Advanced TTS Settings", variable=self.show_advanced_tts_settings, command=self.toggle_advanced_tts_settings)
self.advanced_settings_switch.grid(row=9, column=0, padx=5, pady=5, sticky=tk.W)
self.create_xtts_advanced_settings_frame()
self.create_voicecraft_advanced_settings_frame()
# Dubbing Section
self.dubbing_frame = ctk.CTkFrame(self.session_tab, fg_color="gray20", corner_radius=10)
self.dubbing_frame.grid(row=7, column=0, columnspan=4, padx=10, pady=(0, 20), sticky=tk.EW)
self.dubbing_frame.grid_columnconfigure((0, 1, 2, 3), weight=1)
self.dubbing_frame.grid_remove()
ctk.CTkLabel(self.dubbing_frame, text="Dubbing", font=ctk.CTkFont(size=14, weight="bold")).grid(row=0, column=0, columnspan=4, padx=10, pady=10, sticky=tk.W)
# Transcription Options Frame
self.transcription_frame = ctk.CTkFrame(self.dubbing_frame, fg_color="gray20", corner_radius=10)
self.transcription_frame.grid(row=1, column=0, columnspan=5, padx=10, pady=(10, 5), sticky=tk.EW)
self.transcription_frame.grid_columnconfigure((0, 1, 2, 3, 4), weight=1)
ctk.CTkLabel(self.transcription_frame, text="Transcription Options:", font=ctk.CTkFont(size=12, weight="bold")).grid(row=0, column=0, columnspan=5, padx=10, pady=(5, 5), sticky=tk.W)
ctk.CTkLabel(self.transcription_frame, text="Language:").grid(row=1, column=0, padx=10, pady=5, sticky=tk.W)
self.whisperx_language_dropdown = ctk.CTkComboBox(self.transcription_frame, variable=self.whisperx_language, values=self.whisper_languages)
self.whisperx_language_dropdown.grid(row=1, column=1, padx=10, pady=5, sticky=tk.W)
ctk.CTkLabel(self.transcription_frame, text="Model:").grid(row=1, column=2, padx=10, pady=5, sticky=tk.W)
self.whisperx_model_dropdown = ctk.CTkOptionMenu(self.transcription_frame, variable=self.whisperx_model, values=["small", "small.en", "medium", "medium.en", "large-v2", "large-v3"])
self.whisperx_model_dropdown.grid(row=1, column=3, padx=10, pady=5, sticky=tk.W)
# Translation Options Frame
self.translation_frame = ctk.CTkFrame(self.dubbing_frame, fg_color="gray20", corner_radius=10)
self.translation_frame.grid(row=2, column=0, columnspan=5, padx=10, pady=(10, 5), sticky=tk.EW)
self.translation_frame.grid_columnconfigure((0, 1, 2, 3, 4), weight=1)
ctk.CTkLabel(self.translation_frame, text="Translation Options:", font=ctk.CTkFont(size=12, weight="bold")).grid(row=0, column=0, columnspan=5, padx=10, pady=(5, 5), sticky=tk.W)
self.enable_translation_switch = ctk.CTkSwitch(self.translation_frame, text="Translate subtitles", variable=self.enable_translation)
self.enable_translation_switch.grid(row=1, column=0, columnspan=2, padx=10, pady=5, sticky=tk.W)
ctk.CTkLabel(self.translation_frame, text="From:").grid(row=2, column=0, padx=10, pady=5, sticky=tk.W)
self.original_language_dropdown = ctk.CTkComboBox(self.translation_frame, variable=self.original_language, values=self.whisper_languages)
self.original_language_dropdown.grid(row=2, column=1, padx=10, pady=5, sticky=tk.W)
ctk.CTkLabel(self.translation_frame, text="To:").grid(row=2, column=2, padx=10, pady=5, sticky=tk.W)
self.target_language_dropdown = ctk.CTkOptionMenu(self.translation_frame, variable=self.target_language, values=["en", "es", "fr", "de", "it", "pt", "pl", "tr", "ru", "nl", "cs", "ar", "zh-cn", "ja", "hu", "ko", "hi"])
self.target_language_dropdown.grid(row=2, column=3, padx=10, pady=5, sticky=tk.W)
self.enable_translation_evaluation_switch = ctk.CTkSwitch(self.translation_frame, text="Enable evaluation", variable=self.enable_translation_evaluation)
self.enable_translation_evaluation_switch.grid(row=3, column=0, columnspan=2, padx=10, pady=5, sticky=tk.W)
self.enable_glossary_switch = ctk.CTkSwitch(self.translation_frame, text="Enable glossary", variable=self.enable_glossary)
self.enable_glossary_switch.grid(row=3, column=2, columnspan=2, padx=10, pady=5, sticky=tk.W)
ctk.CTkLabel(self.translation_frame, text="Translation Model:").grid(row=4, column=0, padx=10, pady=5, sticky=tk.W)
self.translation_model_dropdown = ctk.CTkOptionMenu(self.translation_frame, variable=self.translation_model, values=["haiku", "sonnet", "gpt-4o-mini", "gpt-4o", "deepl", "local"], width=150)
self.translation_model_dropdown.grid(row=4, column=1, padx=10, pady=5, sticky=tk.W)
self.translation_model.trace_add("write", self.on_translation_model_change)
# Video File Selection (for SRT input)
self.video_file_selection_frame = ctk.CTkFrame(self.dubbing_frame, fg_color="gray20", corner_radius=10)
self.video_file_selection_frame.grid(row=3, column=0, columnspan=5, padx=10, pady=(10, 5), sticky=tk.EW)
self.video_file_selection_frame.grid_columnconfigure((0, 1, 2), weight=1)
self.video_file_selection_frame.grid_remove()
ctk.CTkLabel(self.video_file_selection_frame, text="Video File:").grid(row=0, column=0, padx=10, pady=5, sticky=tk.W)
self.selected_video_file_entry = ctk.CTkEntry(self.video_file_selection_frame, textvariable=self.selected_video_file, state="readonly")
self.selected_video_file_entry.grid(row=0, column=1, padx=10, pady=5, sticky=tk.EW)
self.select_video_button = ctk.CTkButton(self.video_file_selection_frame, text="Select Video", command=self.select_video_file)
self.select_video_button.grid(row=0, column=2, padx=10, pady=5, sticky=tk.E)
# Dubbing Generation Buttons
self.dubbing_buttons_frame = ctk.CTkFrame(self.dubbing_frame, fg_color="gray20", corner_radius=10)
self.dubbing_buttons_frame.grid(row=4, column=0, columnspan=5, padx=10, pady=(10, 5), sticky=tk.EW)
self.dubbing_buttons_frame.grid_columnconfigure((0, 1, 2, 3), weight=1)
self.generate_dubbing_audio_button = ctk.CTkButton(self.dubbing_buttons_frame, text="Generate Dubbing Audio", fg_color="#2e8b57", hover_color="#3cb371", command=self.generate_dubbing_audio)
self.generate_dubbing_audio_button.grid(row=0, column=0, padx=5, pady=5, sticky=tk.EW)
self.add_dubbing_to_video_button = ctk.CTkButton(self.dubbing_buttons_frame, text="Add Dubbing to Video", command=self.add_dubbing_to_video)
self.add_dubbing_to_video_button.grid(row=0, column=1, padx=5, pady=5, sticky=tk.EW)
self.only_transcribe_button = ctk.CTkButton(self.dubbing_buttons_frame, text="Only Transcribe", command=self.only_transcribe)
self.only_transcribe_button.grid(row=0, column=2, padx=5, pady=5, sticky=tk.EW)
self.only_translate_button = ctk.CTkButton(self.dubbing_buttons_frame, text="Only Translate", command=self.only_translate)
self.only_translate_button.grid(row=0, column=3, padx=5, pady=5, sticky=tk.EW)
# Output Options Section
self.output_options_label = ctk.CTkLabel(self.session_tab, text="Output Options", font=ctk.CTkFont(size=14, weight="bold"))
self.output_options_label.grid(row=8, column=0, columnspan=6, padx=10, pady=10, sticky=tk.W)
self.output_options_frame = ctk.CTkFrame(self.session_tab, fg_color="gray20", corner_radius=10)
self.output_options_frame.grid(row=9, column=0, columnspan=6, padx=3, pady=(0, 20), sticky=tk.EW)
for i in range(6):
self.output_options_frame.grid_columnconfigure(i, weight=1)
ctk.CTkLabel(self.output_options_frame, width=70, text="Format:").grid(row=0, column=0, padx=3, pady=5, sticky=tk.EW)
self.output_format = ctk.StringVar(value="m4b")
self.format_dropdown = ctk.CTkOptionMenu(self.output_options_frame, variable=self.output_format, values=["m4b", "opus", "mp3", "wav"], width=70)
self.format_dropdown.grid(row=0, column=1, padx=3, pady=5, sticky=tk.W)
ctk.CTkLabel(self.output_options_frame, width=70, text="Bitrate:").grid(row=0, column=2, padx=3, pady=5, sticky=tk.W)
self.bitrate = ctk.StringVar(value="64k")
self.bitrate_dropdown = ctk.CTkOptionMenu(self.output_options_frame, variable=self.bitrate, values=["16k", "32k", "64k", "128k", "196k", "312k"], width=70)
self.bitrate_dropdown.grid(row=0, column=3, padx=3, pady=5, sticky=tk.W)
self.upload_cover_button = ctk.CTkButton(self.output_options_frame, text="Upload Cover", command=self.upload_cover)