forked from resemble-ai/chatterbox
-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathChatterboxToolkitUI.py
More file actions
2375 lines (2112 loc) · 146 KB
/
ChatterboxToolkitUI.py
File metadata and controls
2375 lines (2112 loc) · 146 KB
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
# gradio_vc_app.py
# Standard imports
import importlib
import torch
import gradio as gr
from omegaconf import DictConfig
import sys
import os
import re
from datetime import datetime
import time
import soundfile as sf
import logging
import shutil
import zipfile
import json # For manifest
import random
# NLTK for text processing
import nltk
_punkt_is_ready = False
# Define a local NLTK data path within the current working directory
NLTK_DATA_PATH = os.path.join(os.getcwd(), 'nltk_data')
# Ensure the download directory exists
os.makedirs(NLTK_DATA_PATH, exist_ok=True)
# Add this path to NLTK's data search paths.
# It's crucial this is done *before* any data access or download attempts.
if NLTK_DATA_PATH not in nltk.data.path:
nltk.data.path.append(NLTK_DATA_PATH)
try:
# --- STEP 1: Attempt initial functional test ---
# Try to use sent_tokenize directly. If it works, 'punkt' is ready.
# This also acts as a check for any 'punkt_tab' or other internal loading issues.
nltk.sent_tokenize("This is a simple test sentence for NLTK punkt tokenizer.")
_punkt_is_ready = True
print("NLTK 'punkt' tokenizer is functional (already installed and loaded).")
except Exception as e_initial_test: # Catch any error that means sent_tokenize doesn't work
print(f"NLTK 'punkt' tokenizer is not functional or data is missing/corrupted. Initial test error: {e_initial_test}")
print(f"Attempting to download/re-download 'punkt' to {NLTK_DATA_PATH} with 'force=True' to ensure completeness...")
try:
# `punkt` is the correct package to download. `punkt_tab` is an internal resource name.
success_download = nltk.download('punkt_tab', download_dir=NLTK_DATA_PATH, quiet=True, force=True)
if success_download:
# --- STEP 3: Re-test after download ---
# Immediately try to use it again to confirm functionality after download.
nltk.sent_tokenize("This is a test sentence after successful download.")
_punkt_is_ready = True
print("NLTK 'punkt' tokenizer successfully downloaded and is functional.")
else:
raise Exception("NLTK 'punkt' download command returned False.")
except Exception as e_download:
# If download or post-download test fails, report the error and mark as not ready.
print(f"FAILED to make NLTK 'punkt' tokenizer functional after download attempt. Error: {e_download}")
print("Text splitting functionality will be disabled or might fail.")
_punkt_is_ready = False # Ensure flag is False if download or post-download test fails.
# End of NLTK setup block. All other existing imports and code remain the same.
# External library imports for models and audio processing
import pydub
import webrtcvad
# NOTE: Make sure these are installed: pip install librosa soundfile huggingface_hub omegaconf numpy nltk pydub webrtcvad-wheels
# --- PORTABILITY FIX: Dynamically find the path to the 'src' directory ---
# Get the absolute path of the directory where the script is located
script_dir = os.path.dirname(os.path.abspath(__file__))
# Construct the path to the 'src' directory, which is a sibling to the script
chatterbox_src_path = os.path.join(script_dir, 'src')
# Add the 'src' path to the system path if it's not already there
if chatterbox_src_path not in sys.path:
sys.path.insert(0, chatterbox_src_path)
old_sys_path = [] # Define for the print statement below
print(f"--- Dynamically added '{chatterbox_src_path}' to sys.path ---")
else:
old_sys_path = [chatterbox_src_path] # Acts as a flag that path was already present
# --- Import and Reload local chatterbox modules ---
import chatterbox.vc
import chatterbox.models.s3gen
import chatterbox.tts
importlib.reload(chatterbox.models.s3gen)
importlib.reload(chatterbox.vc)
importlib.reload(chatterbox.tts)
# --- Debugging print statements (keep for verification) ---
# This print statement is now just for confirming the load path
print(f"Loaded chatterbox.models.s3gen from: {chatterbox.models.s3gen.__file__}")
print(f"Loaded chatterbox.vc from: {chatterbox.vc.__file__}")
print(f"Loaded chatterbox.tts from: {chatterbox.tts.__file__}")
print(f"--------------------")
from chatterbox.vc import ChatterboxVC
from chatterbox.tts import ChatterboxTTS
logging.basicConfig(level=logging.INFO)
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
_model_vc_instance = None
_model_tts_instance = None
# --- Global State for "Regenerate Audio" feature ---
_last_single_tts_output_path_state_value = None # Stores the actual path string
def get_vc_model():
global _model_vc_instance
if _model_vc_instance is None:
print(f"Loading ChatterboxVC model on {DEVICE}...")
_model_vc_instance = ChatterboxVC.from_pretrained(DEVICE)
print("ChatterboxVC model loaded successfully.")
return _model_vc_instance
def get_tts_model():
global _model_tts_instance
if _model_tts_instance is None:
print(f"Loading ChatterboxTTS model on {DEVICE}...")
_model_tts_instance = ChatterboxTTS.from_pretrained(DEVICE)
print("ChatterboxTTS model loaded successfully.")
return _model_tts_instance
def sanitize_filename(name):
s = str(name)
s = re.sub(r'[\\/:*?"<>|]+', '', s)
s = s.replace(' ', '_')
return s
def get_text_snippet_for_filename(text, max_len=30):
if not text: return "untitled_text"
s = re.sub(r'[^a-zA-Z0-9\s]', '', text).strip()
s = re.sub(r'\s+', '_', s)
s = s.strip('_')
if not s: return "untitled_text"
return s[:max_len]
def set_seed(seed: int):
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
# Note: random and numpy are not imported, so these lines would cause an error.
# If you intend to use them, ensure 'import random' and 'import numpy as np' are at the top.
# random.seed(seed)
# np.random.seed(seed)
global_log_messages_tts = []
global_log_messages_vc = []
global_log_messages_batch_tts = []
global_log_messages_batch_vc = []
def yield_tts_updates(log_msg=None, audio_data=None, file_list=None, log_append=True):
global global_log_messages_tts
if log_msg:
if log_append: global_log_messages_tts.append(f"[{datetime.now().strftime('%H:%M:%S')}] {log_msg}")
else: global_log_messages_tts = [f"[{datetime.now().strftime('%H:%M:%S')}] {log_msg}"]
log_update = gr.update(value="\n".join(global_log_messages_tts))
if audio_data is not None:
audio_update = gr.update(value=audio_data, visible=True)
files_update = gr.update(value=None, visible=False)
elif file_list is not None and len(file_list) > 0:
audio_update = gr.update(value=None, visible=False)
files_update = gr.update(value=file_list, visible=True)
else:
audio_update = gr.update(value=None, visible=False)
files_update = gr.update(value=None, visible=False)
yield log_update, audio_update, files_update
def yield_batch_tts_updates(log_msg=None, file_list=None, log_append=True):
global global_log_messages_batch_tts
if log_msg:
if log_append: global_log_messages_batch_tts.append(f"[{datetime.now().strftime('%H:%M:%S')}] {log_msg}")
else: global_log_messages_batch_tts = [f"[{datetime.now().strftime('%H:%M:%S')}] {log_msg}"]
log_update = gr.update(value="\n".join(global_log_messages_batch_tts))
if file_list is not None and len(file_list) > 0: files_update = gr.update(value=file_list, visible=True)
else: files_update = gr.update(value=None, visible=False)
yield log_update, files_update
def yield_batch_vc_updates(log_msg=None, file_list=None, log_append=True):
global global_log_messages_batch_vc
if log_msg:
if log_append: global_log_messages_batch_vc.append(f"[{datetime.now().strftime('%H:%M:%S')}] {log_msg}")
else: global_log_messages_batch_vc = [f"[{datetime.now().strftime('%H:%M:%S')}] {log_msg}"]
log_update = gr.update(value="\n".join(global_log_messages_batch_vc))
if file_list is not None and len(file_list) > 0: files_update = gr.update(value=file_list, visible=True)
else: files_update = gr.update(value=None, visible=False)
yield log_update, files_update
def yield_vc_updates(log_msg=None, audio_data=None, file_list=None, log_append=True):
global global_log_messages_vc
if log_msg:
if log_append: global_log_messages_vc.append(f"[{datetime.now().strftime('%H:%M:%S')}] {log_msg}")
else: global_log_messages_vc = [f"[{datetime.now().strftime('%H:%M:%S')}] {log_msg}"]
log_update = gr.update(value="\n".join(global_log_messages_vc))
if audio_data is not None:
audio_update = gr.update(value=audio_data, visible=True)
files_update = gr.update(value=None, visible=False)
elif file_list is not None and len(file_list) > 0:
audio_update = gr.update(value=None, visible=False)
files_update = gr.update(value=file_list, visible=True)
else:
audio_update = gr.update(value=None, visible=False)
files_update = gr.update(value=None, visible=False)
yield log_update, audio_update, files_update
PROJECTS_BASE_DIR = "projects"
_current_project_root_dir = ""
_current_project_name = ""
PROJECT_SUBDIRS = {
"input_files": "input_files", "voice_conversion": "voice_conversion", "processed_text": "processed_text",
"processed_audio": "processed_audio", "single_generations_tts": os.path.join("single_generations", "tts"), # Renamed to 'single_generations_tts' for clarity, points to tts
"single_generations_vc": os.path.join("single_generations", "vc"),
"batch_generations_tts": os.path.join("batch_generations", "tts"),
"batch_generations_vc": os.path.join("batch_generations", "vc"),
}
_trigger_ui_update_on_project_state_change = None
def ensure_projects_base_dir():
os.makedirs(PROJECTS_BASE_DIR, exist_ok=True)
logging.info(f"Ensured '{PROJECTS_BASE_DIR}' directory exists.")
def _get_project_path(project_name): return os.path.join(PROJECTS_BASE_DIR, sanitize_filename(project_name))
def list_projects():
ensure_projects_base_dir()
projects = [d for d in os.listdir(PROJECTS_BASE_DIR) if os.path.isdir(os.path.join(PROJECTS_BASE_DIR, d)) and not d.startswith('.')]
logging.info(f"Found projects: {projects}")
return projects
def create_project(project_name):
global _current_project_root_dir, _current_project_name
if not project_name or not project_name.strip(): raise gr.Error("Project name cannot be empty.")
sanitized_name = sanitize_filename(project_name)
project_path = _get_project_path(sanitized_name)
if os.path.exists(project_path): raise gr.Error(f"Project '{sanitized_name}' already exists.")
try:
os.makedirs(project_path)
for _, subdir_path in PROJECT_SUBDIRS.items(): os.makedirs(os.path.join(project_path, subdir_path), exist_ok=True)
logging.info(f"Project '{sanitized_name}' created at: {project_path}")
_current_project_root_dir = project_path
_current_project_name = sanitized_name
updated_projects = list_projects()
current_dropdown_value = _current_project_name if _current_project_name in updated_projects else (updated_projects[0] if updated_projects else None)
# Main outputs for project selection/creation itself
main_outputs_tuple = (
gr.update(choices=updated_projects, value=current_dropdown_value),
gr.update(value=_current_project_root_dir),
f"Project '{_current_project_name}' created and set as current."
)
# Get updates for all other dependent UI elements
other_ui_updates_list = _trigger_ui_update_on_project_state_change() if _trigger_ui_update_on_project_state_change else []
return main_outputs_tuple + tuple(other_ui_updates_list)
except Exception as e:
logging.error(f"Error creating project '{sanitized_name}': {e}")
raise gr.Error(f"Error creating project: {e}")
def set_current_project_instance(project_name=None):
global _current_project_root_dir, _current_project_name
if not project_name:
_current_project_root_dir = ""
_current_project_name = ""
logging.info("Current project cleared.")
main_outputs_tuple = (gr.update(value=None, choices=list_projects()), gr.update(value=""), "No project selected.")
else:
project_path = _get_project_path(project_name)
if not os.path.isdir(project_path) or not all(os.path.isdir(os.path.join(project_path, PROJECT_SUBDIRS[sub_key])) for sub_key in ["input_files", "voice_conversion", "processed_text", "processed_audio"]):
logging.error(f"Project directory '{project_name}' not found or incomplete: {project_path}")
raise gr.Error(f"Project '{project_name}' is not a valid Chatterbox project or is incomplete. Please ensure it contains the expected subfolders (e.g., input_files, voice_conversion).")
_current_project_root_dir = project_path
_current_project_name = project_name
logging.info(f"Current project set to: '{_current_project_name}' at '{_current_project_root_dir}'")
main_outputs_tuple = (gr.update(value=_current_project_name, choices=list_projects()), gr.update(value=_current_project_root_dir), f"Project '{_current_project_name}' selected.")
other_ui_updates_list = _trigger_ui_update_on_project_state_change() if _trigger_ui_update_on_project_state_change else []
return main_outputs_tuple + tuple(other_ui_updates_list)
def upload_files_to_project(files, target_folder_key):
if not _current_project_root_dir: raise gr.Error("No project selected. Please select or create a project first.")
if not files: return "No files uploaded."
if target_folder_key not in PROJECT_SUBDIRS: raise gr.Error(f"Invalid target folder key: {target_folder_key}")
target_dir = os.path.join(_current_project_root_dir, PROJECT_SUBDIRS[target_folder_key])
os.makedirs(target_dir, exist_ok=True)
uploaded_count = 0
messages = []
for file_obj in files:
src_path = file_obj.name
filename = os.path.basename(src_path)
dest_path = os.path.join(target_dir, filename)
try:
shutil.copy(src_path, dest_path)
uploaded_count += 1
logging.info(f"Copied '{src_path}' to '{dest_path}'")
messages.append(f"Copied: {filename}")
except Exception as e:
logging.error(f"Error copying file {filename}: {e}")
messages.append(f"Failed to copy '{filename}': {e}")
return f"Successfully copied {uploaded_count} file(s) to '{PROJECT_SUBDIRS[target_folder_key]}'.\n" + "\n".join(messages)
def list_project_files(subdir_key, file_extension_filter=None):
if not _current_project_root_dir: return []
target_dir = os.path.join(_current_project_root_dir, PROJECT_SUBDIRS[subdir_key])
if not os.path.isdir(target_dir): return []
files = os.listdir(target_dir)
if file_extension_filter:
if isinstance(file_extension_filter, str): files = [f for f in files if f.lower().endswith(file_extension_filter)]
elif isinstance(file_extension_filter, (list, tuple)): files = [f for f in files if any(f.lower().endswith(ext) for ext in file_extension_filter)]
return sorted(files)
def get_project_file_absolute_path(filename, subdir_key):
if not _current_project_root_dir: return None
if subdir_key not in PROJECT_SUBDIRS: return None
return os.path.join(_current_project_root_dir, PROJECT_SUBDIRS[subdir_key], filename)
def generate_vc(audio_filepath,target_voice_filepath,inference_cfg_rate: float,sigma_min: float,batch_mode: bool,batch_parameter: str,batch_values_str: str ):
model_vc = get_vc_model()
yield from yield_vc_updates(log_msg="Starting Voice Conversion...", log_append=False, audio_data=None, file_list=None)
base_output_dir = ""
if _current_project_root_dir and _current_project_name:
yield from yield_vc_updates(log_msg=f"Active project: '{_current_project_name}'. Saving outputs there.")
if batch_mode: base_output_dir = os.path.join(_current_project_root_dir, PROJECT_SUBDIRS["batch_generations_vc"])
else: base_output_dir = os.path.join(_current_project_root_dir, PROJECT_SUBDIRS["single_generations_vc"])
else:
yield from yield_vc_updates(log_msg="No project selected, using generic 'outputs' folder.")
base_output_dir = os.path.join("outputs", "voice2voice")
input_audio_name = os.path.splitext(os.path.basename(audio_filepath))[0] if audio_filepath else "no_input_audio"
target_voice_name = os.path.splitext(os.path.basename(target_voice_filepath))[0] if target_voice_filepath else "default_voice"
date_folder = datetime.now().strftime('%Y%m%d')
vc_base_date_dir = os.path.join(base_output_dir, date_folder)
vc_pair_dir_name = f"{sanitize_filename(input_audio_name)}_x_{sanitize_filename(target_voice_name)}"
vc_pair_output_dir = os.path.join(vc_base_date_dir, vc_pair_dir_name)
os.makedirs(vc_pair_output_dir, exist_ok=True)
try:
if batch_mode:
yield from yield_vc_updates(log_msg="Batch mode enabled. Parsing values...")
try: batch_values = [float(val.strip()) for val in batch_values_str.split(',') if val.strip()]
except ValueError: raise gr.Error("Error: Invalid batch values. Please enter comma-separated numbers.")
if not batch_values: raise gr.Error("Error: Please provide comma-separated values for batch generation.")
yield from yield_vc_updates(log_msg=f"Batch sweep on '{batch_parameter}' with values: {batch_values}")
yield from yield_vc_updates(log_msg=f"Generating {len(batch_values)} items in batch...")
batch_run_dir = os.path.join(vc_pair_output_dir, f"batch_sweep_{sanitize_filename(batch_parameter)}_{datetime.now().strftime('%H%M%S')}")
os.makedirs(batch_run_dir, exist_ok=True)
generated_file_paths = []
for i, value in enumerate(batch_values):
current_inference_cfg_rate, current_sigma_min, param_prefix = inference_cfg_rate, sigma_min, "unknown"
if batch_parameter == "Inference CFG Rate": current_inference_cfg_rate, param_prefix = value, f"cfg_{str(value).replace('.', '_')}"
elif batch_parameter == "Sigma Min": current_sigma_min, param_prefix = value, f"sigma_{str(value).replace('.', '_')}"
else: raise gr.Error(f"Unsupported batch parameter: {batch_parameter}")
logging.info(f"Generating item {i+1}/{len(batch_values)}: {batch_parameter}={value}")
yield from yield_vc_updates(log_msg=f"Generating item {i+1}/{len(batch_values)}: {batch_parameter}={value}")
wav = model_vc.generate(audio_filepath,target_voice_path=target_voice_filepath,inference_cfg_rate=current_inference_cfg_rate,sigma_min=current_sigma_min)
output_filename = f"{sanitize_filename(param_prefix)}_{datetime.now().strftime('%H%M%S_%f')}.wav"
output_path = os.path.join(batch_run_dir, output_filename)
model_vc.save_wav(wav, output_path)
generated_file_paths.append(output_path)
yield from yield_vc_updates(log_msg=f"Saved: {output_path}")
final_message = f"Batch generation complete. {len(generated_file_paths)} files saved in: {batch_run_dir}"
yield from yield_vc_updates(log_msg=final_message, file_list=generated_file_paths)
gr.Info(final_message)
else:
yield from yield_vc_updates(log_msg="Performing single Voice-to-Voice generation...")
wav = model_vc.generate(audio_filepath,target_voice_path=target_voice_filepath,inference_cfg_rate=inference_cfg_rate,sigma_min=sigma_min)
single_output_filename = f"output_{datetime.now().strftime('%H%M%S_%f')}.wav"
single_output_path = os.path.join(vc_pair_output_dir, single_output_filename)
model_vc.save_wav(wav, single_output_path)
output_audio_sr_np = (model_vc.sr, wav.squeeze(0).numpy())
final_message = f"Single Voice-to-Voice generation complete. File saved in: {single_output_path}"
yield from yield_vc_updates(log_msg=final_message, audio_data=output_audio_sr_np, file_list=[single_output_path])
gr.Info(final_message)
except Exception as e:
error_msg = f"Error during Voice Conversion: {str(e)}"
yield from yield_vc_updates(log_msg=error_msg, audio_data=None, file_list=None)
raise gr.Error(error_msg)
def generate_tts(text,audio_prompt_path,exaggeration,temperature,seed_num,cfg_weight,batch_mode: bool,batch_parameter: str,batch_values_str: str):
global _last_single_tts_output_path_state_value # To store the last generated path
model_tts = get_tts_model()
yield from yield_tts_updates(log_msg="Starting Text-to-Voice Generation...", log_append=False, audio_data=None, file_list=None)
base_output_dir = ""
if _current_project_root_dir and _current_project_name:
yield from yield_tts_updates(log_msg=f"Active project: '{_current_project_name}'. Saving outputs there.")
if batch_mode: base_output_dir = os.path.join(_current_project_root_dir, PROJECT_SUBDIRS["batch_generations_tts"])
else: base_output_dir = os.path.join(_current_project_root_dir, PROJECT_SUBDIRS["single_generations_tts"])
else:
yield from yield_tts_updates(log_msg="No project selected, using generic 'outputs' folder.")
base_output_dir = os.path.join("outputs", "text2voice")
date_folder = datetime.now().strftime('%Y%m%d')
text_snippet_shorter = get_text_snippet_for_filename(text, max_len=15)
ref_audio_name = sanitize_filename(os.path.splitext(os.path.basename(audio_prompt_path))[0]) if audio_prompt_path else "no_ref_audio"
combined_tts_folder_name = f"{text_snippet_shorter}_x_{ref_audio_name}"
tts_output_combined_dir = os.path.join(base_output_dir, date_folder, combined_tts_folder_name)
os.makedirs(tts_output_combined_dir, exist_ok=True)
try:
tts_output_filepath = None # Initialize
if batch_mode:
yield from yield_tts_updates(log_msg="Batch mode enabled. Parsing values...")
batch_values = []
try:
if batch_parameter == "Seed": batch_values = [int(val.strip()) for val in batch_values_str.split(',') if val.strip()]
else: batch_values = [float(val.strip()) for val in batch_values_str.split(',') if val.strip()]
except ValueError: raise gr.Error("Error: Invalid batch values. Please enter comma-separated numbers.")
if not batch_values: raise gr.Error("Error: Please provide comma-separated values for batch generation.")
yield from yield_tts_updates(log_msg=f"Batch sweep on '{batch_parameter}' with values: {batch_values}")
yield from yield_tts_updates(log_msg=f"Generating {len(batch_values)} items in batch...")
batch_run_dir = os.path.join(tts_output_combined_dir, f"batch_sweep_{sanitize_filename(batch_parameter)}_{datetime.now().strftime('%H%M%S')}")
os.makedirs(batch_run_dir, exist_ok=True)
generated_tts_file_paths = []
for i, value in enumerate(batch_values):
current_exaggeration, current_temperature, current_cfg_weight, current_seed_num, param_prefix = exaggeration, temperature, cfg_weight, seed_num, "unknown"
if batch_parameter == "Exaggeration": current_exaggeration, param_prefix = value, f"exagg_{str(value).replace('.', '_')}"
elif batch_parameter == "Temperature": current_temperature, param_prefix = value, f"temp_{str(value).replace('.', '_')}"
elif batch_parameter == "CFG/Pace": current_cfg_weight, param_prefix = value, f"cfg_{str(value).replace('.', '_')}"
elif batch_parameter == "Seed": current_seed_num, param_prefix = value, f"seed_{value}"
if current_seed_num != 0: set_seed(int(current_seed_num)); yield from yield_tts_updates(log_msg=f"Using seed: {int(current_seed_num)} for this item.")
logging.info(f"Generating item {i+1}/{len(batch_values)}: {batch_parameter}={value}")
yield from yield_tts_updates(log_msg=f"Generating item {i+1}/{len(batch_values)}: {batch_parameter}={value}")
wav = model_tts.generate(text,audio_prompt_path=audio_prompt_path,exaggeration=current_exaggeration,temperature=current_temperature,cfg_weight=current_cfg_weight)
output_sr_np = (model_tts.sr, wav.squeeze(0).numpy())
tts_output_filename = f"{param_prefix}_{datetime.now().strftime('%H%M%S_%f')}.wav"
tts_output_filepath = os.path.join(batch_run_dir, tts_output_filename)
sf.write(tts_output_filepath, output_sr_np[1], output_sr_np[0])
generated_tts_file_paths.append(tts_output_filepath)
yield from yield_tts_updates(log_msg=f"Saved: {tts_output_filepath}")
final_message = f"Batch generation complete. {len(generated_tts_file_paths)} files saved in: {batch_run_dir}"
yield from yield_tts_updates(log_msg=final_message, file_list=generated_tts_file_paths)
gr.Info(final_message)
else:
if seed_num != 0: set_seed(int(seed_num)); yield from yield_tts_updates(log_msg=f"Using seed: {int(seed_num)}")
wav = model_tts.generate(text,audio_prompt_path=audio_prompt_path,exaggeration=exaggeration,temperature=temperature,cfg_weight=cfg_weight)
output_sr_np = (model_tts.sr, wav.squeeze(0).numpy())
tts_output_filename = f"output_{datetime.now().strftime('%H%M%S_%f')}.wav"
tts_output_filepath = os.path.join(tts_output_combined_dir, tts_output_filename)
sf.write(tts_output_filepath, output_sr_np[1], output_sr_np[0])
yield from yield_tts_updates(log_msg=f"Saved TTS audio to: {tts_output_filepath}")
final_message = "Text-to-Voice generation complete."
yield from yield_tts_updates(log_msg=final_message, audio_data=output_sr_np, file_list=[tts_output_filepath])
gr.Info(final_message)
if tts_output_filepath: # If a file was saved (primarily for single mode)
_last_single_tts_output_path_state_value = tts_output_filepath
logging.info(f"Updated _last_single_tts_output_path_state_value to: {_last_single_tts_output_path_state_value}")
except Exception as e:
error_msg = f"Error during Text-to-Voice generation: {str(e)}"
_last_single_tts_output_path_state_value = None # Clear on error
yield from yield_tts_updates(log_msg=error_msg, audio_data=None, file_list=None)
raise gr.Error(error_msg)
# --- PERFORMANCE FIX: Set sensible defaults to avoid loading the model at startup ---
default_inference_cfg_rate = 0.5
default_sigma_min = 1e-06
# -----------------------------------------------------------------------------
def toggle_tts_batch_options_visibility(checkbox_state): return gr.update(visible=checkbox_state)
def toggle_vc_batch_options_visibility(checkbox_state): return gr.update(visible=checkbox_state)
def update_tts_text_project_dropdown_choices(): return gr.update(choices=list_project_files('processed_text', '.txt'))
def select_tts_text_from_project(filename):
if not filename: return gr.update(value="")
path = get_project_file_absolute_path(filename, 'processed_text')
if not path or not os.path.exists(path): raise gr.Error(f"File not found: {path}")
with open(path, 'r', encoding='utf-8') as f: content = f.read()
return gr.update(value=content)
# NEW: Function to select TTS reference audio from project
def select_tts_ref_audio_from_project(filename):
if not filename: return gr.update(value=None)
path = get_project_file_absolute_path(filename, 'voice_conversion') # Reference audio for TTS generally comes from voice_conversion for voice cloning
if not path or not os.path.exists(path): raise gr.Error(f"File not found: {path}")
return gr.update(value=path)
def update_vc_input_audio_project_dropdown_choices(): return gr.update(choices=list_project_files('processed_audio', '.wav'))
def select_vc_input_audio_from_project(filename):
if not filename: return gr.update(value=None)
path = get_project_file_absolute_path(filename, 'processed_audio')
if not path or not os.path.exists(path): raise gr.Error(f"File not found: {path}")
return gr.update(value=path)
def update_vc_target_voice_project_dropdown_choices(): return gr.update(choices=list_project_files('voice_conversion', '.wav'))
def select_vc_target_voice_from_project(filename):
if not filename: return gr.update(value=None)
path = get_project_file_absolute_path(filename, 'voice_conversion')
if not path or not os.path.exists(path): raise gr.Error(f"File not found: {path}")
return gr.update(value=path)
def split_text_document(text_filepath, max_chars_per_chunk):
yield "Starting text splitting...", gr.update(value=None, visible=False)
if not _current_project_root_dir: raise gr.Error("No project selected. Please select or create a project to split text.")
global _punkt_is_ready
if not _punkt_is_ready: raise gr.Error("NLTK 'punkt' tokenizer is not functional. Please check console output during startup for download errors or try restarting the app.")
output_dir = os.path.join(_current_project_root_dir, PROJECT_SUBDIRS["processed_text"])
os.makedirs(output_dir, exist_ok=True)
try:
if not text_filepath or not os.path.exists(text_filepath): raise gr.Error("No input text file provided or file does not exist.")
with open(text_filepath, 'r', encoding='utf-8') as f: full_text = f.read()
sentences = nltk.sent_tokenize(full_text)
chunks, current_chunk, current_chunk_len = [], [], 0
original_filename_base = sanitize_filename(os.path.splitext(os.path.basename(text_filepath))[0])
chunk_count, generated_file_paths = 0, []
yield f"Loaded text from {os.path.basename(text_filepath)}. Splitting into {len(sentences)} sentences...", gr.update(value=None, visible=False)
for i, sentence in enumerate(sentences):
if current_chunk and (current_chunk_len + len(sentence) + (1 if current_chunk else 0) > max_chars_per_chunk):
chunk_text = " ".join(current_chunk).strip()
if chunk_text:
chunk_count += 1
output_filename = f"{original_filename_base}_part_{chunk_count:03d}.txt"
output_path = os.path.join(output_dir, output_filename)
with open(output_path, 'w', encoding='utf-8') as outfile: outfile.write(chunk_text)
generated_file_paths.append(output_path)
yield f"Processed {i+1}/{len(sentences)} sentences. Saved chunk {chunk_count}.", gr.update(value=None, visible=False)
current_chunk, current_chunk_len = [sentence], len(sentence)
else:
current_chunk.append(sentence)
current_chunk_len += len(sentence) + (1 if current_chunk_len > 0 else 0)
if current_chunk:
chunk_text = " ".join(current_chunk).strip()
if chunk_text:
chunk_count += 1
output_filename = f"{original_filename_base}_part_{chunk_count:03d}.txt"
output_path = os.path.join(output_dir, output_filename)
with open(output_path, 'w', encoding='utf-8') as outfile: outfile.write(chunk_text)
generated_file_paths.append(output_path)
yield f"Finished processing sentences. Saved final chunk {chunk_count}.", gr.update(value=None, visible=False)
if not generated_file_paths: raise gr.Error("No text chunks were generated. The input text might be too short or contains no sentences.")
final_message = f"Text splitting complete. Generated {len(generated_file_paths)} chunks."
yield final_message, gr.File(value=generated_file_paths, visible=True)
gr.Info(final_message)
except Exception as e:
error_msg = f"Error during text splitting: {str(e)}"
yield error_msg, gr.update(value=None, visible=False)
raise gr.Error(error_msg)
def _vad_split_audio_segment(audio_segment, frame_rate=16000, frame_duration_ms=30, vad_aggressiveness=3):
vad = webrtcvad.Vad(vad_aggressiveness)
audio_segment_resampled = audio_segment.set_frame_rate(frame_rate).set_channels(1).set_sample_width(2)
samples_per_frame = int(frame_rate * frame_duration_ms / 1000)
segments, current_segment_start_ms = [], None
for i in range(0, len(audio_segment_resampled) - samples_per_frame + 1, samples_per_frame):
frame_start_ms = i * 1000 // frame_rate
frame_bytes = audio_segment_resampled[frame_start_ms: frame_start_ms + frame_duration_ms].raw_data
is_speech = vad.is_speech(frame_bytes, frame_rate)
if is_speech:
if current_segment_start_ms is None: current_segment_start_ms = frame_start_ms
elif current_segment_start_ms is not None:
segments.append((current_segment_start_ms, frame_start_ms + frame_duration_ms)); current_segment_start_ms = None
if current_segment_start_ms is not None: segments.append((current_segment_start_ms, len(audio_segment_resampled)))
return segments
def find_best_silence_cut_point(audio_buffer: pydub.AudioSegment, target_ms: int, max_look_back_ms: int, min_chunk_len_ms: int, min_silence_len_for_cut_detection_ms: int):
search_window_start_ms = max(0, target_ms - max_look_back_ms)
search_window = audio_buffer[search_window_start_ms:target_ms]
if not search_window: return target_ms
silence_thresh = audio_buffer.dBFS - 10
silence_intervals = pydub.silence.detect_silence( search_window, min_silence_len=min_silence_len_for_cut_detection_ms, silence_thresh=silence_thresh)
best_cut_point_within_buffer = target_ms
for silence_start_relative, silence_end_relative in reversed(silence_intervals):
candidate_cut_point_relative_to_search_window = silence_end_relative
absolute_candidate_cut_point = search_window_start_ms + candidate_cut_point_relative_to_search_window
if absolute_candidate_cut_point >= min_chunk_len_ms:
best_cut_point_within_buffer = absolute_candidate_cut_point
break
return best_cut_point_within_buffer
def split_audio_document(audio_filepath, max_duration_sec, min_duration_sec, min_silence_for_cut_ms):
yield "Starting audio splitting...", gr.update(value=None, visible=False)
if not _current_project_root_dir: raise gr.Error("No project selected. Please select or create a project to split audio.")
output_dir = os.path.join(_current_project_root_dir, PROJECT_SUBDIRS["processed_audio"])
os.makedirs(output_dir, exist_ok=True)
try:
if not audio_filepath or not os.path.exists(audio_filepath): raise gr.Error("No input audio file provided or file does not exist.")
yield f"Loading audio from {os.path.basename(audio_filepath)}...", gr.update(value=None, visible=False)
audio = pydub.AudioSegment.from_file(audio_filepath)
original_total_length_ms, max_duration_ms, min_duration_ms = len(audio), max_duration_sec * 1000, min_duration_sec * 1000
if min_duration_ms > max_duration_ms: raise gr.Error("Minimum duration (s) cannot be greater than Maximum duration (s).")
generated_audio_paths, original_filename_base = [], sanitize_filename(os.path.splitext(os.path.basename(audio_filepath))[0])
speech_segments_vad_results = _vad_split_audio_segment(audio, vad_aggressiveness=0)
yield f"Audio loaded ({round(original_total_length_ms/1000, 2)}s). Detected {len(speech_segments_vad_results)} raw speech regions. Resegmenting...", gr.update(value=None, visible=False)
full_audio_buffer, last_processed_audio_source_ms, chunk_number = pydub.AudioSegment.empty(), 0, 1
for i, (speech_start, speech_end) in enumerate(speech_segments_vad_results):
silence_start, silence_end = last_processed_audio_source_ms, speech_start
if silence_end > silence_start: full_audio_buffer += audio[silence_start:silence_end]
full_audio_buffer += audio[speech_start:speech_end]
last_processed_audio_source_ms = speech_end
while True:
if len(full_audio_buffer) < min_duration_ms: break
target_cut_point_in_buffer = min(len(full_audio_buffer), max_duration_ms)
look_back_window_ms = min(target_cut_point_in_buffer, max_duration_ms)
actual_cut_point_ms = find_best_silence_cut_point(full_audio_buffer, target_ms=target_cut_point_in_buffer, max_look_back_ms=look_back_window_ms, min_chunk_len_ms=min_duration_ms, min_silence_len_for_cut_detection_ms=min_silence_for_cut_ms)
is_forced_cut = len(full_audio_buffer) > max_duration_ms
is_internal_good_cut = (actual_cut_point_ms < len(full_audio_buffer)) and (actual_cut_point_ms >= min_duration_ms)
if not (is_forced_cut or is_internal_good_cut): break
new_chunk_to_export = full_audio_buffer[0:actual_cut_point_ms]
if len(new_chunk_to_export) < min_duration_ms:
yield f"Proposed chunk ({round(len(new_chunk_to_export)/1000, 2)}s) too short, accumulating more.", gr.update(value=None, visible=False)
break
output_path = os.path.join(output_dir, f"{original_filename_base}_part_{chunk_number:03d}.wav")
new_chunk_to_export.export(output_path, format="wav")
generated_audio_paths.append(output_path)
yield f"Saved audio chunk {chunk_number} (duration: {round(len(new_chunk_to_export)/1000, 2)}s).", gr.update(value=None, visible=False)
full_audio_buffer = full_audio_buffer[actual_cut_point_ms:]
chunk_number += 1
remaining_audio_after_vad_segments = audio[last_processed_audio_source_ms:]
full_audio_buffer += remaining_audio_after_vad_segments
if len(full_audio_buffer) > 0:
if len(full_audio_buffer) >= min_duration_ms:
output_path = os.path.join(output_dir, f"{original_filename_base}_part_{chunk_number:03d}.wav")
full_audio_buffer.export(output_path, format="wav")
generated_audio_paths.append(output_path)
yield f"Saved final audio chunk {chunk_number} (duration: {round(len(full_audio_buffer)/1000, 2)}s). All input processed.", gr.update(value=None, visible=False)
else:
yield f"Discarding small remaining buffer of {round(len(full_audio_buffer)/1000, 2)}s (less than minimum duration {min_duration_sec}s).", gr.update(value=None, visible=False)
if not generated_audio_paths: raise gr.Error("No audio chunks were generated. Input may be too short, has no detectable speech, or duration settings are too restrictive.")
final_message = f"Audio splitting complete. Generated {len(generated_audio_paths)} chunks."
yield final_message, gr.File(value=generated_audio_paths, visible=True)
gr.Info(final_message)
except Exception as e:
error_msg = f"Error during audio splitting: {str(e)}"
yield error_msg, gr.update(value=None, visible=False)
raise gr.Error(error_msg)
def update_dp_text_project_dropdown_choices(): return gr.update(choices=list_project_files('input_files', '.txt'))
def select_dp_text_from_project(filename):
if not filename: return gr.update(value=None)
path = get_project_file_absolute_path(filename, 'input_files')
if not path or not os.path.exists(path): raise gr.Error(f"File not found: {path}")
return gr.update(value=path)
def update_dp_audio_project_dropdown_choices(): return gr.update(choices=list_project_files('input_files', ['.wav', '.mp3', '.flac']))
def select_dp_audio_from_project(filename):
if not filename: return gr.update(value=None)
path = get_project_file_absolute_path(filename, 'input_files')
if not path or not os.path.exists(path): raise gr.Error(f"File not found: {path}")
return gr.update(value=path)
def handle_batch_tts_zip_upload(zip_filepath):
if not _current_project_root_dir: raise gr.Error("No project selected. Please select or create a project to upload batch files.")
if not zip_filepath: return gr.update(value="", visible=True), [], "No zip file uploaded."
extract_dir_name = f"temp_batch_upload_{datetime.now().strftime('%Y%m%d_%H%M%S_%f')}"
extract_path = os.path.join(_current_project_root_dir, PROJECT_SUBDIRS["input_files"], extract_dir_name)
os.makedirs(extract_path, exist_ok=True)
extracted_files = []
try:
with zipfile.ZipFile(zip_filepath, 'r') as zip_ref:
for member in zip_ref.namelist():
if member.endswith('.txt') and not os.path.basename(member).startswith('__MACOSX'):
target_file_path = os.path.join(extract_path, os.path.basename(member))
with zip_ref.open(member) as source, open(target_file_path, "wb") as target: shutil.copyfileobj(source, target)
extracted_files.append(target_file_path)
extracted_files.sort()
if not extracted_files: raise gr.Error("No .txt files found in the uploaded zip archive.")
display_names = [os.path.basename(f) for f in extracted_files]
message = f"Successfully extracted {len(extracted_files)} text files from zip. Ready for batch TTS."
return "\n".join(display_names), extracted_files, message
except Exception as e:
if os.path.exists(extract_path): shutil.rmtree(extract_path)
raise gr.Error(f"Error processing zip file: {e}")
def load_batch_tts_project_files():
if not _current_project_root_dir: raise gr.Error("No project selected. Please select a project to load files from.")
txt_files = list_project_files('processed_text', '.txt')
full_paths = [get_project_file_absolute_path(f, 'processed_text') for f in txt_files]
if not full_paths: raise gr.Error(f"No .txt files found in '{PROJECT_SUBDIRS['processed_text']}' of the current project.")
display_names = [os.path.basename(f) for f in full_paths]
message = f"Loaded {len(full_paths)} text files from project '{_current_project_name}'s '{PROJECT_SUBDIRS['processed_text']}' directory. Ready for batch TTS."
return "\n".join(display_names), full_paths, message
def clear_batch_tts_files(): return "", [], "File selection cleared."
def update_batch_tts_ref_audio_project_dropdown_choices(): return gr.update(choices=list_project_files('voice_conversion', '.wav'))
def select_batch_tts_ref_audio_from_project(filename):
if not filename: return gr.update(value=None)
path = get_project_file_absolute_path(filename, 'voice_conversion')
if not path or not os.path.exists(path): raise gr.Error(f"File not found: {path}")
return gr.update(value=path)
def _save_batch_tts_manifest(batch_output_dir, ref_audio_path):
manifest_path = os.path.join(batch_output_dir, "manifest.json")
manifest_data = {
"reference_audio_path": ref_audio_path,
"batch_run_timestamp": os.path.basename(batch_output_dir),
}
try:
with open(manifest_path, 'w') as f:
json.dump(manifest_data, f, indent=4)
logging.info(f"Saved batch TTS manifest to: {manifest_path}")
except Exception as e:
logging.error(f"Error saving batch TTS manifest: {e}")
def run_batch_tts(ref_audio_path_tts_batch,tts_exaggeration_batch,tts_temp_batch,tts_seed_num_batch,tts_cfg_weight_batch,text_files_to_process_list,concatenate_output: bool):
model_tts = get_tts_model()
yield from yield_batch_tts_updates(log_msg="Starting Batch Text-to-Voice Generation...", log_append=False, file_list=None)
if not text_files_to_process_list: raise gr.Error("No text files selected for batch processing.")
if not ref_audio_path_tts_batch or not os.path.exists(ref_audio_path_tts_batch): raise gr.Error("Reference audio for batch TTS is required and must exist.")
if not _current_project_root_dir: raise gr.Error("No project selected. Outputs cannot be meaningfully saved for batch runs without a project.")
base_output_dir = os.path.join(_current_project_root_dir, PROJECT_SUBDIRS["batch_generations_tts"])
run_id = datetime.now().strftime('%Y%m%d_%H%M%S_%f')
batch_run_specific_output_dir = os.path.join(base_output_dir, run_id) # This is the main folder for this specific batch run
single_files_output_dir = os.path.join(batch_run_specific_output_dir, "single_files")
concatenated_output_dir = os.path.join(batch_run_specific_output_dir, "concatenated")
os.makedirs(single_files_output_dir, exist_ok=True)
if concatenate_output: os.makedirs(concatenated_output_dir, exist_ok=True)
# Save manifest
_save_batch_tts_manifest(batch_run_specific_output_dir, ref_audio_path_tts_batch)
yield from yield_batch_tts_updates(log_msg=f"Batch run ID: {run_id}. Saving to: {batch_run_specific_output_dir}")
yield from yield_batch_tts_updates(log_msg=f"Processing {len(text_files_to_process_list)} text files...")
all_generated_wav_paths = []
log_messages_list = []
try:
for i, text_filepath in enumerate(text_files_to_process_list):
text_filename = os.path.basename(text_filepath)
with open(text_filepath, 'r', encoding='utf-8') as f: text_content = f.read()
if tts_seed_num_batch != 0: set_seed(int(tts_seed_num_batch))
log_messages_list.append(f"Generating audio for {text_filename} ({i+1}/{len(text_files_to_process_list)})...")
yield from yield_batch_tts_updates(log_msg="\n".join(log_messages_list), log_append=False, file_list=None)
wav = model_tts.generate(text_content,audio_prompt_path=ref_audio_path_tts_batch,exaggeration=tts_exaggeration_batch,temperature=tts_temp_batch,cfg_weight=tts_cfg_weight_batch)
output_sr_np = (model_tts.sr, wav.squeeze(0).numpy())
output_filename = f"{sanitize_filename(os.path.splitext(text_filename)[0])}_{datetime.now().strftime('%H%M%S_%f')}.wav"
output_path = os.path.join(single_files_output_dir, output_filename)
sf.write(output_path, output_sr_np[1], output_sr_np[0])
all_generated_wav_paths.append(output_path)
log_messages_list.append(f"-> Saved: {output_filename}")
yield from yield_batch_tts_updates(log_msg="\n".join(log_messages_list), log_append=False, file_list=None)
final_files_for_gr_output = all_generated_wav_paths
if concatenate_output and all_generated_wav_paths:
yield from yield_batch_tts_updates(log_msg="Concatenating generated audio files...")
combined_audio = pydub.AudioSegment.silent(duration=100)
for wav_path in all_generated_wav_paths:
combined_audio += pydub.AudioSegment.from_wav(wav_path)
combined_audio += pydub.AudioSegment.silent(duration=500)
concatenated_filename = f"batch_tts_combined_{run_id}.wav"
concatenated_path = os.path.join(concatenated_output_dir, concatenated_filename)
combined_audio.export(concatenated_path, format="wav")
final_files_for_gr_output = [concatenated_path]
yield from yield_batch_tts_updates(log_msg=f"Concatenated audio saved to: {concatenated_path}", file_list=final_files_for_gr_output)
gr.Info("Batch TTS and concatenation complete!")
else:
yield from yield_batch_tts_updates(log_msg=f"Batch TTS complete. {len(all_generated_wav_paths)} individual files saved.", file_list=final_files_for_gr_output)
gr.Info("Batch TTS complete!")
except Exception as e:
error_msg = f"Error during Batch Text-to-Voice generation: {str(e)}"
yield from yield_batch_tts_updates(log_msg=error_msg, file_list=None)
raise gr.Error(error_msg)
def handle_batch_vc_zip_upload(zip_filepath_vc):
if not _current_project_root_dir: raise gr.Error("No project selected. Please select or create a project to upload batch files.")
if not zip_filepath_vc: return gr.update(value="", visible=True), [], "No .zip file uploaded for Batch VC."
extract_dir_name = f"temp_batch_vc_upload_{datetime.now().strftime('%Y%m%d_%H%M%S_%f')}"
extract_path = os.path.join(_current_project_root_dir, PROJECT_SUBDIRS["input_files"], extract_dir_name)
os.makedirs(extract_path, exist_ok=True)
extracted_files = []
valid_audio_extensions = ('.wav', '.mp3', '.flac')
try:
with zipfile.ZipFile(zip_filepath_vc, 'r') as zip_ref:
for member in zip_ref.namelist():
if member.lower().endswith(valid_audio_extensions) and not os.path.basename(member).startswith('__MACOSX'):
target_file_path = os.path.join(extract_path, os.path.basename(member))
with zip_ref.open(member) as source, open(target_file_path, "wb") as target: shutil.copyfileobj(source, target)
extracted_files.append(target_file_path)
extracted_files.sort()
if not extracted_files: raise gr.Error(f"No audio files ({', '.join(valid_audio_extensions)}) found in the uploaded zip archive.")
display_names = [os.path.basename(f) for f in extracted_files]
message = f"Successfully extracted {len(extracted_files)} audio files from zip. Ready for Batch VC."
return "\n".join(display_names), extracted_files, message
except Exception as e:
if os.path.exists(extract_path): shutil.rmtree(extract_path)
raise gr.Error(f"Error processing zip file for Batch VC: {e}")
def load_batch_vc_project_files():
if not _current_project_root_dir: raise gr.Error("No project selected. Please select a project to load files from.")
audio_files = list_project_files('processed_audio', ('.wav', '.mp3', '.flac'))
full_paths = [get_project_file_absolute_path(f, 'processed_audio') for f in audio_files]
if not full_paths: raise gr.Error(f"No audio files found in '{PROJECT_SUBDIRS['processed_audio']}' of the current project.")
display_names = [os.path.basename(f) for f in full_paths]
message = f"Loaded {len(full_paths)} audio files from project '{_current_project_name}'s '{PROJECT_SUBDIRS['processed_audio']}' directory. Ready for Batch VC."
return "\n".join(display_names), full_paths, message
def clear_batch_vc_files(): return "", [], "File selection cleared for Batch VC."
def update_batch_vc_ref_voice_project_dropdown_choices(): return gr.update(choices=list_project_files('voice_conversion', '.wav'))
def select_batch_vc_ref_voice_from_project(filename):
if not filename: return gr.update(value=None)
path = get_project_file_absolute_path(filename, 'voice_conversion')
if not path or not os.path.exists(path): raise gr.Error(f"Reference voice file not found: {path}")
return gr.update(value=path)
def run_batch_vc(ref_voice_path_vc_batch,vc_inference_cfg_rate_batch,vc_sigma_min_batch,audio_files_to_process_list,concatenate_output_vc: bool):
model_vc = get_vc_model()
yield from yield_batch_vc_updates(log_msg="Starting Batch Voice Conversion...", log_append=False, file_list=None)
if not audio_files_to_process_list: raise gr.Error("No audio files selected for batch VC processing.")
if not ref_voice_path_vc_batch or not os.path.exists(ref_voice_path_vc_batch): raise gr.Error("Reference voice for batch VC is required and must exist.")
if not _current_project_root_dir: raise gr.Error("No project selected. Outputs cannot be meaningfully saved for batch runs without a project.")
base_output_dir = os.path.join(_current_project_root_dir, PROJECT_SUBDIRS["batch_generations_vc"])
run_id = datetime.now().strftime('%Y%m%d_%H%M%S_%f')
batch_output_dir = os.path.join(base_output_dir, run_id)
single_files_output_dir_vc = os.path.join(batch_output_dir, "single_files")
concatenated_output_dir_vc = os.path.join(batch_output_dir, "concatenated")
os.makedirs(single_files_output_dir_vc, exist_ok=True)
if concatenate_output_vc: os.makedirs(concatenated_output_dir_vc, exist_ok=True)
yield from yield_batch_vc_updates(log_msg=f"Batch VC run ID: {run_id}. Saving to: {batch_output_dir}")
yield from yield_batch_vc_updates(log_msg=f"Processing {len(audio_files_to_process_list)} audio files...")
all_converted_wav_paths = []
log_messages_list_vc = []
try:
for i, audio_filepath in enumerate(audio_files_to_process_list):
audio_filename = os.path.basename(audio_filepath)
log_messages_list_vc.append(f"Converting voice for {audio_filename} ({i+1}/{len(audio_files_to_process_list)})...")
yield from yield_batch_vc_updates(log_msg="\n".join(log_messages_list_vc), log_append=False, file_list=None)
wav = model_vc.generate(audio_filepath,target_voice_path=ref_voice_path_vc_batch,inference_cfg_rate=vc_inference_cfg_rate_batch,sigma_min=vc_sigma_min_batch)
output_filename = f"{sanitize_filename(os.path.splitext(audio_filename)[0])}_vc_{datetime.now().strftime('%H%M%S_%f')}.wav"
output_path = os.path.join(single_files_output_dir_vc, output_filename)
model_vc.save_wav(wav, output_path)
all_converted_wav_paths.append(output_path)
log_messages_list_vc.append(f"-> Saved: {output_filename}")
yield from yield_batch_vc_updates(log_msg="\n".join(log_messages_list_vc), log_append=False, file_list=None)
final_files_for_gr_output = all_converted_wav_paths
if concatenate_output_vc and all_converted_wav_paths:
yield from yield_batch_vc_updates(log_msg="Concatenating converted audio files...")
combined_audio = pydub.AudioSegment.silent(duration=100)
for wav_path in all_converted_wav_paths:
if os.path.exists(wav_path):
audio_segment = pydub.AudioSegment.from_wav(wav_path)
combined_audio += audio_segment
combined_audio += pydub.AudioSegment.silent(duration=500)
else:
yield from yield_batch_vc_updates(log_msg=f"Warning: File not found for concatenation: {wav_path}")
concatenated_filename = f"batch_vc_combined_{run_id}.wav"
concatenated_path = os.path.join(concatenated_output_dir_vc, concatenated_filename)
combined_audio.export(concatenated_path, format="wav")
final_files_for_gr_output = [concatenated_path]
yield from yield_batch_vc_updates(log_msg=f"Concatenated audio saved to: {concatenated_path}", file_list=final_files_for_gr_output)
gr.Info("Batch VC and concatenation complete!")
else:
yield from yield_batch_vc_updates(log_msg=f"Batch VC complete. {len(all_converted_wav_paths)} individual files saved.", file_list=final_files_for_gr_output)
gr.Info("Batch VC complete!")
except Exception as e:
error_msg = f"Error during Batch Voice Conversion: {str(e)}"
yield from yield_batch_vc_updates(log_msg=error_msg, file_list=None)
raise gr.Error(error_msg)
# --- Data Preparation Helpers for Editing ---
def update_edit_text_dropdown_choices():
new_choices = list_project_files('processed_text', '.txt')
# Return two values: an update for the dropdown, and the list of choices for the state
return gr.update(choices=new_choices, value=None), new_choices
def load_edit_text_content_only(filename): # Renamed for clarity
"""Loads content of selected text file into the editor, enables save button."""
if not _current_project_root_dir:
# This case should ideally be handled by UI visibility, but a last-resort check
return "", gr.update(interactive=False), gr.update(interactive=False), gr.update(interactive=False), "No project selected.", [] # Return default states
if not filename:
# No file selected in dropdown, reset editor state
return "", gr.update(interactive=False), gr.update(interactive=False), gr.update(interactive=False), "Select a text file from the dropdown to edit.", []
path = get_project_file_absolute_path(filename, 'processed_text')
if not path or not os.path.exists(path):
return "", gr.update(interactive=False), gr.update(interactive=False), gr.update(interactive=False), f"Error: File '{filename}' not found. Please refresh list.", []
try:
with open(path, 'r', encoding='utf-8') as f:
content = f.read()
# Fetch all available files for navigation from the project subdirectory
all_available_files = list_project_files('processed_text', '.txt')
nav_buttons_interactive = len(all_available_files) > 1
# Return content, interactiveness for save button, and log message
return (
gr.update(value=content, interactive=True),
gr.update(interactive=True),
# Correctly set interactive state for prev/next buttons
gr.update(interactive=nav_buttons_interactive), # Prev button
gr.update(interactive=nav_buttons_interactive), # Next button
f"Loaded '{filename}' for editing. You can now make changes.",
all_available_files # Update the state with full list
)
except Exception as e:
return "", gr.update(interactive=False), gr.update(interactive=False), gr.update(interactive=False), f"Error loading '{filename}': {e}", []
def save_edited_text_content(filename_selected_in_dropdown, new_content_from_textbox):
"""Saves the edited content back to the original file."""
if not _current_project_root_dir:
raise gr.Error("No project selected. Save failed.")
if not filename_selected_in_dropdown:
raise gr.Error("No file selected for saving.")
path = get_project_file_absolute_path(filename_selected_in_dropdown, 'processed_text')
if not path or not os.path.exists(path):
raise gr.Error(f"Original file not found: {path}. Cannot save.")
try:
with open(path, 'w', encoding='utf-8') as f:
f.write(new_content_from_textbox)
return gr.update(value=new_content_from_textbox, interactive=True), gr.update(interactive=True), f"Changes to '{filename_selected_in_dropdown}' saved successfully."
except Exception as e:
raise gr.Error(f"Error saving file '{filename_selected_in_dropdown}': {e}")
def navigate_text_file(current_filename: str, file_list_state: list, direction: int):
"""Navigates to the next/previous file in the list."""
if not file_list_state:
# Note: The dropdown value might not be None here, it might be the last selected value.
# If the list is empty, always disable buttons and give a message.
return None, "No files to navigate.", gr.update(interactive=False), gr.update(interactive=False)
try:
# Find current index. If not found (e.g., file deleted), default to a valid index or start/end.
current_idx = file_list_state.index(current_filename) if current_filename in file_list_state else -1
if current_idx == -1 and len(file_list_state) > 0:
# If current file isn't in list but list is not empty, start from beginning/end
new_idx = 0 if direction == 1 else len(file_list_state) - 1
else:
# Normal navigation
new_idx = (current_idx + direction) % len(file_list_state)
next_filename = file_list_state[new_idx]
# Navigation buttons are interactive if there's more than one file to navigate between
nav_buttons_interactive = len(file_list_state) > 1
return next_filename, f"Navigating to: {next_filename}", gr.update(interactive=nav_buttons_interactive), gr.update(interactive=nav_buttons_interactive)
except Exception as e:
# Fallback on unexpected error, keep current filename, disable nav, log error
return current_filename, f"Error navigating files: {e}", gr.update(interactive=False), gr.update(interactive=False)
def load_random_text_file():
if not _current_project_root_dir:
return None, gr.update(value="", interactive=False), gr.update(interactive=False), gr.update(interactive=False), "No project selected.", []
# Get all potential files to display
all_txt_files = list_project_files('processed_text', '.txt')
if not all_txt_files:
return None, gr.update(value="", interactive=False), gr.update(interactive=False), gr.update(interactive=False), "No .txt files found in project's processed_text folder.", []
# Select a random file
random_filename = random.choice(all_txt_files)
# Load its content
file_path = get_project_file_absolute_path(random_filename, 'processed_text')
try:
with open(file_path, 'r', encoding='utf-8') as f:
content = f.read()
nav_buttons_interactive = len(all_txt_files) > 1
return (
random_filename, # dropdown value
gr.update(value=content, interactive=True), # textbox value
gr.update(interactive=nav_buttons_interactive), # Prev button
gr.update(interactive=nav_buttons_interactive), # Next button
f"Loaded random file: '{random_filename}'.", # Log message
all_txt_files # Update current_editable_files_state
)
except Exception as e:
return None, gr.update(value="", interactive=False), gr.update(interactive=False), gr.update(interactive=False), f"Error loading random file '{random_filename}': {e}", []
# --- Regenerate Audio Tab Helpers ---
def list_batch_tts_runs():
if not _current_project_root_dir:
return []
batch_tts_base = os.path.join(_current_project_root_dir, PROJECT_SUBDIRS["batch_generations_tts"])
if not os.path.isdir(batch_tts_base):
return []
runs = [d for d in os.listdir(batch_tts_base) if os.path.isdir(os.path.join(batch_tts_base, d))]
return sorted(runs, reverse=True) # Newest first
def _load_batch_tts_manifest(batch_run_dir_name):
if not _current_project_root_dir or not batch_run_dir_name:
return None
manifest_path = os.path.join(_current_project_root_dir, PROJECT_SUBDIRS["batch_generations_tts"], batch_run_dir_name, "manifest.json")
if os.path.exists(manifest_path):
try:
with open(manifest_path, 'r') as f:
return json.load(f)
except Exception as e:
logging.error(f"Error loading manifest {manifest_path}: {e}")
return None
def load_batch_tts_run_files(batch_run_dir_name):
if not _current_project_root_dir or not batch_run_dir_name:
# If no batch run selected or project not active, reset all related UI elements
return (
gr.update(choices=[], value=None, interactive=False), # Audio file dropdown
"", # Log message
None, # _regen_selected_batch_run_path_state
None, # _regen_batch_ref_audio_path_state
gr.update(interactive=False), # regen_send_to_tts_btn
gr.update(interactive=False, visible=True), # regen_concatenate_btn
gr.update(value=None, visible=False) # regen_concatenated_output_file
)
selected_run_full_path = os.path.join(_current_project_root_dir, PROJECT_SUBDIRS["batch_generations_tts"], batch_run_dir_name)
single_files_dir = os.path.join(selected_run_full_path, "single_files")
new_regen_selected_batch_run_path_state = selected_run_full_path
audio_files = []
if os.path.isdir(single_files_dir):