forked from JarodMica/StyleTTS-WebUI
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebui.py
More file actions
1506 lines (1263 loc) · 56.4 KB
/
webui.py
File metadata and controls
1506 lines (1263 loc) · 56.4 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
import os
import sys
if os.path.exists("runtime"):
# Get the directory where the script is located
script_dir = os.path.dirname(os.path.abspath(__file__))
# Add this directory to sys.path
if script_dir not in sys.path:
sys.path.insert(0, script_dir)
espeak_path = os.path.join(os.path.dirname(__file__), 'espeak NG')
espeak_library = os.path.join(os.path.dirname(__file__), 'espeak NG', 'libespeak-ng.dll')
espeak_data_path = os.path.join(espeak_path, 'espeak-ng-data')
os.environ['PHONEMIZER_ESPEAK_PATH'] = espeak_path
os.environ['PHONEMIZER_ESPEAK_LIBRARY'] = espeak_library
os.environ['ESPEAK_DATA_PATH'] = espeak_data_path
import gradio as gr
import torch
import time
import yaml
import multiprocessing
import shutil
import datetime
import glob
import webbrowser
import socket
import numpy as np
import pandas as pd
from scipy.io.wavfile import write
from pydub import AudioSegment
from io import BytesIO
import nltk.data
from styletts2.train_finetune_accelerate import main as run_train
from mutagen import wave
from mutagen.wave import WAVE
from mutagen.id3 import TXXX
from styletts2.utils import *
from modules.tortoise_dataset_tools.dataset_whisper_tools.dataset_maker_large_files import *
from modules.tortoise_dataset_tools.dataset_whisper_tools.combine_folders import *
from Utils.splitcombine import split_and_recombine_text
import nltk
# Path to the settings file
SETTINGS_FILE_PATH = os.path.join(".","Configs","generate_settings.yaml")
APP_SETTINGS_FILE_PATH = os.path.join(".","Configs","app_settings.yaml")
GENERATE_SETTINGS = {}
TRAINING_DIR = "training"
BASE_CONFIG_FILE_PATH = os.path.join(".","Configs","template_config_ft.yml")
DEFAULT_VOICE_MODEL = os.path.join("models","pretrain_base_1","epochs_2nd_00020.pth")
WHISPER_MODELS = ["tiny", "base", "small", "medium", "large", "large-v1", "large-v2", "large-v3"]
VALID_AUDIO_EXT = [
".mp3",
".wav",
".flac",
".aac",
".ogg",
".m4a",
".opus"
]
device = 'cuda' if torch.cuda.is_available() else 'cpu'
global_phonemizer = None
model = None
model_params = None
sampler = None
textcleaner = None
to_mel = None
params_whole = None
loaded = False
ref_s = None
lastRefS = {}
appSettings = {}
generateSettings = {}
genData = {}
genHistory = {
"df":None,
"originalDF":None,
"selectedRecord":None
}
genHistoryDF = None
historyFileList = []
defaults = {
'SCMaxLength': 280,
'SCDesiredLength': 250,
}
def load_all_models(model_path):
global global_phonemizer, model, model_params, sampler, textcleaner, to_mel, params_whole
model_config = (get_model_configuration(model_path))
if not model_config:
return None
config = load_configurations(model_config)
sigma_value = config['model_params']['diffusion']['dist']['sigma_data']
model, model_params = load_models_webui(sigma_value, device)
global_phonemizer = load_phonemizer()
sampler = create_sampler(model)
textcleaner = TextCleaner()
to_mel = torchaudio.transforms.MelSpectrogram(
n_mels=80, n_fft=2048, win_length=1200, hop_length=300)
params_whole = load_pretrained_model(model, model_path=model_path)
return {'global_phonemizer':global_phonemizer,'model':model,'model_params':model_params,'sampler':sampler,'textcleaner':textcleaner,'to_mel':to_mel,'params_whole':params_whole}
def unload_all_models():
global global_phonemizer, model, model_params, sampler, textcleaner, to_mel, params_whole, ref_s
if global_phonemizer:
del global_phonemizer
global_phonemizer = None
print("Unloaded phonemizer")
if model:
del model
model = None
print("Unloaded model")
if model_params:
del model_params
model_params = None
print("Unloaded model params")
if sampler:
del sampler
sampler = None
print("Unloaded sampler")
if textcleaner:
del textcleaner
textcleaner = None
print("Unloaded textcleaner")
if to_mel:
del to_mel
to_mel = None
print("Unloaded to_mel")
if params_whole:
del params_whole
params_whole = None
print("Unloaded params_whole")
# if ref_s:
# ref_s = None
# del ref_s
# print("Unloaded ref_s")
do_gc()
torch.cuda.empty_cache()
gr.Info("All models unloaded.")
def do_gc():
import gc
gc.collect()
try:
torch.cuda.empty_cache()
except Exception as e:
pass
def get_file_path(root_path, voice, file_extension, error_message):
model_path = os.path.join(root_path, voice)
if not os.path.exists(model_path):
raise gr.Error(f'No {file_extension} located in "{root_path}" folder')
for file in os.listdir(model_path):
if file.endswith(file_extension):
return os.path.join(model_path, file)
raise gr.Error(error_message)
def get_model_configuration(model_path):
base_directory, _ = os.path.split(model_path)
for file in os.listdir(base_directory):
if file.endswith(".yml"):
configuration_path = os.path.join(base_directory, file)
return configuration_path
raise gr.Error("No configuration file found in the model folder")
def load_voice_model(voice):
return get_file_path(root_path="models", voice=voice, file_extension=".pth", error_message="No TTS model found in specified location")
def generate_audio(text, voice, reference_audio_file, SCDesiredLength, SCMaxLength, seed, alpha, beta, diffusion_steps, embedding_scale, voice_model, audio_opt_path=None, voices_root="voices",):
global generateSettings, ref_s, lastRefS, loaded
original_seed = int(seed)
reference_audio_path = os.path.join(voices_root, voice, reference_audio_file)
start = time.time()
if original_seed==-1:
seed_value = random.randint(0, 2**32 - 1)
else:
seed_value = original_seed
set_seeds(seed_value)
mean, std = -4, 4
lastRefStmp = {
'reference_audio_path':reference_audio_path,
'model':model,
'to_mel':to_mel,
'mean':mean,
'std':std,
'device':device
}
if lastRefS != lastRefStmp:
ref_s = None
lastRefS = lastRefStmp
else:
print('reusing existing ref_s')
if ref_s == None:
print('Computing ref_s')
ref_s = compute_style(reference_audio_path, model, to_mel, mean, std, device)
texts = split_and_recombine_text(text,SCDesiredLength,SCMaxLength)
print(f'seed: {seed_value}\nalpha: {alpha}\nbeta: {beta}\nembedding_scale: {embedding_scale}\ndiffusion_steps: {diffusion_steps}\nvoice: {voice}\nvoice_model: {voice_model}')
combined_audio = AudioSegment.empty()
for t in texts:
# print(f'Generating: {t}')
bytes_wav = bytes()
byte_io = BytesIO(bytes_wav)
# bytes_wav.seek(0)
write(byte_io, 24000, inference(t, ref_s, model, sampler, textcleaner, to_mel, device, model_params, global_phonemizer=global_phonemizer, alpha=alpha, beta=beta, diffusion_steps=diffusion_steps, embedding_scale=embedding_scale))
audio_segment = AudioSegment.from_wav(byte_io)
audio_segment = audio_segment[:-80]
audio_segment = audio_segment + 1 # make it a bit louder
combined_audio += audio_segment
rtf = (time.time() - start)
print(f"RTF = {rtf:5f}")
print(f"{voice} Synthesized:")
genDate = datetime.datetime.now()
genDateLocal = datetime.datetime.strptime(genDate.strftime("%c"), '%a %b %d %H:%M:%S %Y')
genDateReadable = genDateLocal.strftime("%m-%d-%y_%H-%M-%S")
os.makedirs(os.path.join(".","results",f"{voice}"), exist_ok=True)
audio_opt_path = os.path.join("results", f"{voice}", f"{voice}-{genDateReadable}.wav")
generateSettings = {
"text": text,
"voice": voice,
"reference_audio_file": reference_audio_file,
"SCDesiredLength": SCDesiredLength,
"SCMaxLength": SCMaxLength,
"seed": original_seed if original_seed == -1 else seed_value,
"alpha": alpha,
"beta": beta,
"diffusion_steps": diffusion_steps,
"embedding_scale": embedding_scale,
"voice_model" : voice_model
}
save_settings(generateSettings)
audio_opt_dir = os.path.dirname(audio_opt_path)
audio_opt_filename = os.path.basename(audio_opt_path)
output_file_path = os.path.join(audio_opt_dir, audio_opt_filename)
output_wav_path = os.path.join(audio_opt_dir,f'{os.path.splitext(os.path.basename(output_file_path))[0]}.wav')
output_mp3_path = os.path.join(audio_opt_dir,f'{os.path.splitext(os.path.basename(output_file_path))[0]}.mp3')
combined_audio.export(output_wav_path, format='wav')
if appSettings['enableID3tagging']:
ID3Tags = {
'seed':seed_value,
'original_seed':original_seed,
'alpha':alpha,
'beta':beta,
'diffusion_steps':diffusion_steps,
'embedding_scale':embedding_scale,
'reference_audio_path':reference_audio_path,
"SCDesiredLength": SCDesiredLength,
"SCMaxLength": SCMaxLength,
'voice':voice,
'voice_model':voice_model,
'rtf':f'{rtf:5f}',
'text':text,
'date_generated': genDateLocal.strftime("%Y-%m-%d, %H:%M:%S")
}
tagWAV(output_wav_path,ID3Tags)
genHistoryArray = getGenHistory()
return audio_opt_path, [[seed_value]], genHistoryArray[["voice", "seed", "date_generated","filepath"]] if appSettings['enableID3tagging'] else None
def train_model(data):
return f"Model trained with data: {data}"
def update_settings(setting_value):
return f"Settings updated to: {setting_value}"
def get_folder_list(root):
folder_list = [item for item in os.listdir(root) if os.path.isdir(os.path.join(root, item))]
return folder_list
def get_reference_audio_list(voice_name, root="voices"):
reference_directory_list = os.listdir(os.path.join(root, voice_name))
return reference_directory_list
# def get_voice_models():
# folders_to_browse = ["training", "models"]
# model_list = []
# for folder in folders_to_browse:
# # Construct the search pattern
# search_pattern = os.path.join(folder, '**', '*.pth')
# # Use glob to find all matching files, recursively search in subfolders
# matching_files = glob.glob(search_pattern, recursive=True)
# # Extend the model_list with the found files
# model_list.extend(matching_files)
# return model_list
def get_voice_models():
folders_to_browse = ["training", "models"]
files = []
for folder in folders_to_browse:
for root, _, filenames in os.walk(folder):
for filename in filenames:
if filename.endswith('pth'):
files.append(rf"{os.path.join(root, filename)}")
# print(rf"{os.path.join(root, filename)}")
# print(files)
return files
def update_reference_audio(voice):
return gr.Dropdown(choices=get_reference_audio_list(voice), value=get_reference_audio_list(voice)[0])
def update_voice_model(model_path):
gr.Info("Wait for models to load...")
# model_path = get_models_path(voice, model_name)
path_components = model_path.split(os.path.sep)
voice = path_components[1]
loaded_check = load_all_models(model_path=model_path)
# if loaded_check:
# raise gr.Warning("No model or model configuration loaded, check model config file is present")
gr.Info("Models finished loading")
def get_models_path(voice, model_name, root="models"):
return os.path.join(root, voice, model_name)
def update_voice_settings(voice):
try:
# gr.Info("Wait for models to load...")
# model_name = get_voice_models(voice)
# model_path = get_models_path(voice, model_name[0])
# loaded_check = load_all_models(model_path=model_path)
# if loaded_check == None:
# gr.Warning("No model or model configuration loaded, check model config file is present")
ref_aud_path = update_reference_audio(voice)
# gr.Info("Models finished loading")
return ref_aud_path #gr.Dropdown(choices=model_name, value=model_name[0] if model_name else None)
except:
gr.Warning("No models found for the chosen voice, new models not loaded")
ref_aud_path = update_reference_audio(voice)
return ref_aud_path, gr.Dropdown(choices=[])
def load_settings(settingsType='generate'):
if settingsType == 'generate':
global generateSettings, loaded
try:
with open(SETTINGS_FILE_PATH, "r") as f:
generateSettings = yaml.safe_load(f)
loaded = True
if not os.path.isfile(generateSettings['voice_model']):
print(f'{generateSettings["voice_model"]} not found, loading pretained base model instead.')
generateSettings['voice_model'] = DEFAULT_VOICE_MODEL
return generateSettings
except FileNotFoundError:
if reference_audio_list:
reference_file = reference_audio_list[0]
else:
reference_file = None
if voice_list_with_defaults:
voice = voice_list_with_defaults[0]
else:
voice = None
settings_list = {
"text": "Inferencing with this sentence, just to make sure things work!",
"voice": voice,
"reference_audio_file": reference_file,
"SCDesiredLength":defaults['SCDesiredLength'],
"SCMaxLength":defaults['SCMaxLength'],
"seed" : "-1",
"alpha": 0.3,
"beta": 0.7,
"diffusion_steps": 30,
"embedding_scale": 1.0,
"voice_model" : "models\pretrain_base_1\epochs_2nd_00020.pth"
}
return settings_list
if settingsType == 'app':
global appSettings
try:
with open(APP_SETTINGS_FILE_PATH, "r") as f:
appSettings = yaml.safe_load(f)
return appSettings
except FileNotFoundError:
appSettings = {
"enableID3tagging": True
}
save_settings(appSettings,'app')
return appSettings
def save_settings(settings,settingsType='generation'):
if settingsType == 'generation':
with open(SETTINGS_FILE_PATH, "w") as f:
yaml.safe_dump(settings, f)
if settingsType == 'app':
with open(APP_SETTINGS_FILE_PATH, "w") as f:
yaml.safe_dump(settings, f)
def update_button_proxy():
voice_list_with_defaults = get_voice_list(append_defaults=True)
datasets_list = get_voice_list(get_voice_dir("datasets"), append_defaults=True)
train_list = get_folder_list(root="training")
return gr.Dropdown(choices=voice_list_with_defaults), gr.Dropdown(choices=reference_audio_list), gr.Dropdown(choices=datasets_list), gr.Dropdown(choices=train_list), gr.Dropdown(choices=train_list)
def update_data_proxy(voice_name):
train_data = os.path.join(TRAINING_DIR, voice_name,"train_phoneme.txt")
val_data = os.path.join(TRAINING_DIR, voice_name, "validation_phoneme.txt")
root_path = os.path.join(TRAINING_DIR, voice_name, "audio")
return gr.Textbox(train_data), gr.Textbox(val_data), gr.Textbox(root_path)
def save_yaml_config(config, voice_name):
os.makedirs(os.path.join(TRAINING_DIR, voice_name), exist_ok=True) # Create the output directory if it doesn't exist
output_file_path = os.path.join(TRAINING_DIR, voice_name, f"{voice_name}_config.yml")
with open(output_file_path, 'w') as file:
yaml.dump(config, file)
def update_config(voice_name, save_freq, log_interval, epochs, batch_size, max_len, rolling_model_retention_count, pretrained_model, load_only_params, F0_path, ASR_config, ASR_path, PLBERT_dir, train_data, val_data, root_path, diff_epoch, joint_epoch):
with open(BASE_CONFIG_FILE_PATH, "r") as f:
config = yaml.safe_load(f)
config["log_dir"] = os.path.join(TRAINING_DIR, voice_name, "models")
config["save_freq"] = save_freq
config["log_interval"] = log_interval
config["epochs"] = epochs
config["batch_size"] = batch_size
config["max_len"] = max_len
config["rolling_model_retention_count"] = rolling_model_retention_count
config["pretrained_model"] = pretrained_model
config["load_only_params"] = load_only_params
config["F0_path"] = F0_path
config["ASR_config"] = ASR_config
config["ASR_path"] = ASR_path
config["PLBERT_dir"] = PLBERT_dir
config["data_params"]["train_data"] = train_data
config["data_params"]["val_data"] = val_data
config["data_params"]["root_path"] = root_path
config["loss_params"]["diff_epoch"] = diff_epoch
config["loss_params"]["joint_epoch"] = joint_epoch
save_yaml_config(config, voice_name=voice_name)
return "Configuration updated successfully."
def get_dataset_continuation(voice):
try:
training_dir = f"training/{voice}/processed"
if os.path.exists(training_dir):
processed_dataset_list = [folder for folder in os.listdir(training_dir) if os.path.isdir(os.path.join(training_dir, folder))]
if processed_dataset_list:
processed_dataset_list.append("")
return gr.Dropdown(choices=processed_dataset_list, value="", interactive=True)
except Exception as e:
print(f"Error getting dataset continuation: {str(e)}")
return gr.Dropdown(choices=[], value="", interactive=True)
def load_whisper_model(language=None, model_name=None, progress=None):
import whisperx
# import whisper
if torch.cuda.is_available():
device = "cuda"
else:
raise gr.Error("Non-Nvidia GPU detected, or CUDA not available")
try:
whisper_model = whisperx.load_model(model_name, device, download_root="whisper_models", compute_type="float16")
except Exception as e: # for older GPUs
print(f"Debugging info: {e}")
whisper_model = whisperx.load_model(model_name, device, download_root="whisper_models", compute_type="int8")
# whisper_align_model = whisperx.load_align_model(model_name="WAV2VEC2_ASR_LARGE_LV60K_960H" if language=="en" else None, language_code=language, device=device)
print("Loaded Whisper model")
return whisper_model
def get_training_folder(voice) -> str:
'''
voice(str) : voice to retrieve training folder from
'''
return f"./training/{voice}"
# Pretty much taken from the AI-voice-cloning repo for the code I implemented
def transcribe_other_language_proxy(voice, language, chunk_size, continuation_directory, align, rename, num_processes, keep_originals,
srt_multiprocessing, ext, speaker_id, whisper_model, progress=gr.Progress(track_tqdm=True)):
whisper_model = load_whisper_model(language=language, model_name=whisper_model)
num_processes = int(num_processes)
training_folder = get_training_folder(voice)
processed_folder = os.path.join(training_folder,"processed")
dataset_dir = os.path.join(processed_folder, "run")
merge_dir = os.path.join(dataset_dir, "dataset/wav_splits")
audio_dataset_path = os.path.join(merge_dir, 'audio')
train_text_path = os.path.join(dataset_dir, 'dataset/train.txt')
validation_text_path = os.path.join(dataset_dir, 'dataset/validation.txt')
large_file_num_processes = int(num_processes/2) # Used for instances where larger files are being processed, as to not run out of RAM
items_to_move = [audio_dataset_path, train_text_path, validation_text_path]
for item in items_to_move:
if os.path.exists(os.path.join(training_folder, os.path.basename(item))):
raise gr.Error(f'Remove ~~train.txt ~~validation.txt ~~audio(folder) from "./training/{voice}" before trying to transcribe a new dataset. Or click the "Archive Existing" button')
if continuation_directory:
dataset_dir = os.path.join(processed_folder, continuation_directory)
elif os.path.exists(dataset_dir):
current_datetime = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
new_dataset_dir = os.path.join(processed_folder, f"run_{current_datetime}")
os.rename(dataset_dir, new_dataset_dir)
from modules.tortoise_dataset_tools.audio_conversion_tools.split_long_file import get_duration, process_folder
chosen_directory = os.path.join("./datasets", voice)
items = [item for item in os.listdir(chosen_directory) if os.path.splitext(item)[1].lower() in VALID_AUDIO_EXT]
# This is to prevent an error below when processing "non audio" files. This will occur with other types, but .pth should
# be the only other ones in the voices folder.
# for file in items:
# if file.endswith(".pth"):
# items.remove(file)
# In case of sudden restart, removes this intermediary file used for rename
for file in items:
if "file___" in file:
os.remove(os.path.join(chosen_directory, file))
file_durations = [get_duration(os.path.join(chosen_directory, item)) for item in items if os.path.isfile(os.path.join(chosen_directory, item))]
progress(0.0, desc="Splitting long files")
if any(duration > 3600*2 for duration in file_durations):
process_folder(chosen_directory, large_file_num_processes)
if not keep_originals:
originals_pre_split_path = os.path.join(chosen_directory, "original_pre_split")
try:
shutil.rmtree(originals_pre_split_path)
except:
# There is no directory to delete
pass
progress(0.0, desc="Converting to MP3 files") # add tqdm later
if ext=="mp3":
import modules.tortoise_dataset_tools.audio_conversion_tools.convert_to_mp3 as c2mp3
# Hacky way to get the functions working without changing where they output to...
for item in os.listdir(chosen_directory):
if os.path.isfile(os.path.join(chosen_directory, item)):
original_dir = os.path.join(chosen_directory, "original_files")
if not os.path.exists(original_dir):
os.makedirs(original_dir)
item_path = os.path.join(chosen_directory, item)
try:
shutil.move(item_path, original_dir)
except:
os.remove(item_path)
try:
c2mp3.process_folder(original_dir, large_file_num_processes)
except:
raise gr.Error('No files found in the voice folder specified, make sure it is not empty. If you interrupted the process, the files may be in the "original_files" folder')
# Hacky way to move the files back into the main voice folder
for item in os.listdir(os.path.join(original_dir, "converted")):
item_path = os.path.join(original_dir, "converted", item)
if os.path.isfile(item_path):
try:
shutil.move(item_path, chosen_directory)
except:
os.remove(item_path)
if not keep_originals:
originals_files = os.path.join(chosen_directory, "original_files")
try:
shutil.rmtree(originals_files)
except:
# There is no directory to delete
pass
progress(0.4, desc="Processing audio files")
process_audio_files(base_directory=dataset_dir,
language=language,
audio_dir=chosen_directory,
chunk_size=chunk_size,
no_align=align,
rename_files=rename,
num_processes=num_processes,
whisper_model=whisper_model,
srt_multiprocessing=srt_multiprocessing,
ext=ext,
speaker_id=speaker_id,
sr_rate=24000
)
progress(0.7, desc="Audio processing completed")
progress(0.7, desc="Merging segments")
merge_segments(merge_dir)
progress(0.9, desc="Segment merging completed")
try:
for item in items_to_move:
if os.path.exists(os.path.join(training_folder, os.path.basename(item))):
print("Already exists")
else:
shutil.move(item, training_folder)
shutil.rmtree(dataset_dir)
except Exception as e:
raise gr.Error(e)
progress(1, desc="Transcription and processing completed successfully!")
return "Transcription and processing completed successfully!"
def phonemize_files(voice, progress=gr.Progress(track_tqdm=True)):
training_root = get_training_folder(voice)
train_text_path = os.path.join(training_root, "train.txt")
train_opt_path = os.path.join(training_root, "train_phoneme.txt")
validation_text_path = os.path.join(training_root, "validation.txt")
validation_opt_path = os.path.join(training_root, "validation_phoneme.txt")
# Hardcoded to "both" to stay consistent with the train_to_phoneme.py script and not having to modify it
option = "both"
from modules.styletts2_phonemizer.train_to_phoneme import process_file
progress(0.0, desc="Train Phonemization Starting")
process_file(train_text_path, train_opt_path, option)
progress(0.9, desc="Validation Phonemization Starting")
process_file(validation_text_path, validation_opt_path, option)
return "Phonemization complete!"
def archive_dataset(voice):
training_folder = get_training_folder(voice)
archive_root = os.path.join(training_folder,"archived_data")
current_datetime = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
archive_folder = os.path.join(archive_root,current_datetime)
items_to_move = ["train.txt", "validation.txt", "audio", "train_phoneme.txt", "validation_phoneme.txt"]
training_folder_contents = os.listdir(training_folder)
if not any(item in training_folder_contents for item in items_to_move):
raise gr.Error("No files to move")
for item in items_to_move:
os.makedirs(archive_folder, exist_ok=True)
move_item_path = os.path.join(training_folder, item)
if os.path.exists(move_item_path):
try:
shutil.move(move_item_path, archive_folder)
except:
raise gr.Error(f'Close out of any windows using where "{item} is located!')
gr.Info('Finished archiving files to "archived_data" folder')
voice_list_with_defaults = get_voice_list(append_defaults=True)
datasets_list = get_voice_list(get_voice_dir("datasets"), append_defaults=True)
if voice_list_with_defaults:
reference_audio_list = get_reference_audio_list(voice_list_with_defaults[0])
train_list = get_folder_list(root="training")
else:
reference_audio_list = None
voice_list_with_default = None
train_list = None
def is_port_in_use(port):
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
return sock.connect_ex(('localhost', port)) == 0
def tagWAV(filepath,newtags={}):
'''
Basic and easy implementation to tag generated files
intention is to be able to inject generation settings
into each wav, enabling easy setting repeats similar to
that seen in Automatic1111 for SD.
ex: tagWAV(filepath,{'seed':1806341205,'beta':0.2}))
generation history done
todo: implement "send to generation tab" functionality.
'''
if len(newtags) == 0:
print('No tags provided')
return
wav = WAVE(filepath)
id3 = wav.tags
try:
wave.WAVE.add_tags(wav)
wav.save(filepath, v2_version=3)
id3 = wav.tags
except Exception as e:
print(f"Error adding tag: {e}")
try:
for t in newtags:
id3.add(TXXX(encoding=3, desc=t, text=str(newtags[t])))
# print(f"{t}:{newtags[t]}")
except Exception as e:
print(f"Error tagging wav: {e}")
separator = '/'
id3.save(filepath, v23_sep=separator)
wav = wave.WAVE(filepath)
id3 = wav.tags
for t in newtags:
t = f'TXXX:{t}'
return True
def getWAVtags(filepath):
'''
return all relevant tags from a wav file
'''
try:
wav = wave.WAVE(filepath)
id3 = wav.tags
except Exception as e:
print(f"Error loading wav tags: {e}")
return False
neededTags = ['voice','seed','original_seed','alpha','beta','diffusion_steps','embedding_scale','reference_audio_path','voice_model','SCDesiredLength','SCMaxLength','rtf','text','date_generated']
returnTags = {}
for t in neededTags:
tx = f'TXXX:{t}'
try:
returnTags[t] = id3[tx]
except Exception as e:
returnTags[t] = None
return returnTags
def getGenHistory():
'''
Iterates over results folder and subfolders for .wav/.mp3 files that have ID3 tags generated by this app
creates a set of lists to be run through np.column_stack to populate the dataframe on the history page with
'''
global historyFileList
global genHistory
df = genHistory['originalDF']
tmp_historyFileList = [os.path.join(dirpath,f) for (dirpath, dirnames, filenames) in os.walk('results') for f in filenames if f.endswith('.wav') or f.endswith('.mp3')]
data = {}
historyFileIter = 0
for f in tmp_historyFileList:
ftags = getWAVtags(f)
if ftags:
# print(ftags)
historyFileList.append(f)
data[historyFileIter] = [
f,
ftags['voice_model'][0],
ftags['voice'][0],
ftags['reference_audio_path'][0],
ftags['SCDesiredLength'],
ftags['SCMaxLength'],
ftags['date_generated'][0],
ftags['seed'][0],
ftags['original_seed'][0],
ftags['alpha'][0],
ftags['beta'][0],
ftags['diffusion_steps'][0],
ftags['embedding_scale'][0],
ftags['rtf'][0],
ftags['text'][0]
]
historyFileIter += 1
genHistoryDF = pd.DataFrame.from_dict(data, orient='index',
columns=['filepath','voice_model','voice','reference_audio_path','SCDesiredLength','SCMaxLength','date_generated','seed','original_seed','alpha','beta','diffusion_steps','embedding_scale','rtf','text'])
genHistory['df'] = genHistoryDF
genHistory['originalDF'] = genHistoryDF
return genHistory['df']
def populateGenHistoryData(value, evt: gr.EventData, sel: gr.SelectData):
'''
Grabs necessary info for displaying the clicked history record
'''
filepath = sel.row_value[-1]
df = genHistory['df']
df = df.loc[(df.filepath == filepath)].reset_index(drop=True)
record = df.loc[(df.filepath == filepath)].to_dict('index')[0]
audioReturn = os.path.join(".", record['filepath'])
textReturn = f"{record['text']}"
settingsReturn = np.array(list({k:v for k,v in record.items() if k not in ['text']}.items()))
return audioReturn,textReturn,settingsReturn
def UpdateMetadataFlag(value):
appSettings['enableID3tagging'] = value
save_settings(appSettings,settingsType='app')
def filterHistoryDF(historyVoiceSelection,enteredText):
'''
Filters generation history records and returns a filtered dataframe
'''
global genHistory
df = genHistory['originalDF']
filterHistoryEnteredText = enteredText
filterHistoryVoiceSelection = historyVoiceSelection
if len(filterHistoryVoiceSelection) == 0:
filterHistoryVoiceSelection = ['All']
if 'All' in filterHistoryVoiceSelection:
filterHistoryVoiceSelection = df['voice'].unique().tolist()
filteredGenHistoryDF = df.loc[(df.voice.isin(filterHistoryVoiceSelection)),]
filteredGenHistoryDF = filteredGenHistoryDF.reset_index(drop=True)
genHistory['df'] = filteredGenHistoryDF
if filterHistoryEnteredText:
mask = filteredGenHistoryDF['text'].str.contains('|'.join(filterHistoryEnteredText))
filteredGenHistoryDF = filteredGenHistoryDF[mask]
return filteredGenHistoryDF[["voice", "seed", "date_generated","filepath"]], historyVoiceSelection, enteredText
def get_training_config(voice):
filename = None
for voiceFile in os.listdir(os.path.join("training", voice)):
if voiceFile.endswith('_config.yml'):
filename = voiceFile
break
if not filename:
print(f"No configuration file found in the directory for {voice}")
return False
else:
config_path = os.path.join("training", voice, filename)
return config_path
def main():
initial_settings = load_settings()
appSettings = load_settings(settingsType='app')
list_of_models = get_voice_models()
if voice_list_with_defaults:
load_all_models(initial_settings["voice_model"])
ref_audio_file_choices = get_reference_audio_list(initial_settings["voice"])
else:
# list_of_models = None
ref_audio_file_choices = None
with gr.Blocks(css=".gradio-container-4-38-1 table {height: 250px; width: 100%;overflow-x: hidden !important; overflow-y: scroll !important; scrollbar-width: thin !important; padding-right: 17px !important; box-sizing: content-box !important;} ::-webkit-scrollbar {display: none;}") as demo:
with gr.Tabs() as tabs:
with gr.Tab(id="generation", label="Generation"):
with gr.Column():
with gr.Row():
GENERATE_SETTINGS["text"] = gr.Textbox(label="Input Text", value=initial_settings["text"])
with gr.Row():
with gr.Column():
with gr.Row():
with gr.Column():
GENERATE_SETTINGS["voice_model"] = gr.Dropdown(
choices=list_of_models, interactive=True, label="Voice Models", type="value", value=initial_settings["voice_model"], filterable=True,
info="Model to use when inferencing, found in the models and training folders."
)
GENERATE_SETTINGS["voice"] = gr.Dropdown(
choices=voice_list_with_defaults, label="Voice", type="value", value=initial_settings["voice"],
info="Name of folder in voices directory."
)
GENERATE_SETTINGS["reference_audio_file"] = gr.Dropdown(
choices=ref_audio_file_choices, label="Reference Audio", type="value", value=initial_settings["reference_audio_file"],
info="Name of file inside the above folder to use as reference when inferencing."
)
with gr.Row():
with gr.Column():
GENERATE_SETTINGS["SCMaxLength"] = gr.Slider(
label="Max Length", minimum=1, maximum=505, step=1, value=initial_settings["SCMaxLength"] if "SCMaxLength" in initial_settings.keys() else 280,
info="Max character count to use in each inference."
)
GENERATE_SETTINGS["SCDesiredLength"] = gr.Slider(
label="Desired Length", minimum=1, maximum=505, step=1, value=initial_settings["SCDesiredLength"] if "SCDesiredLength" in initial_settings.keys() else 250,
info="Desired character count in each inferene, not to exceed Max Length."
)
with gr.Accordion("What are Max and Desired lengths for?", open=False):
with gr.Row():
gr.Markdown("When inference text is too long the quality of the output degrades, and there is a hard cap of 505 characters on top of that. Using the split and recombine function allows virtually unlimited inference length. Fine tune these values to get the best sounding output. Trial and error is the only way to dial these in. Will try not to split mid-sentence to infer full sentences.")
with gr.Row():
resetSCValuesButton = gr.Button("Reset these to default")
def limitSCDesiredLength(scDesired,scMax):
return gr.update(maximum=scMax, value=scMax if scDesired > scMax else scMax if scMax < initial_settings["SCDesiredLength"] else initial_settings["SCDesiredLength"])
def persistSCDesireLength(scDesired):
# if user changes value of this slider, doing this will let it return to that
# value as the max length slider is adjusted.
initial_settings["SCDesiredLength"] = scDesired
def resetSCValues():
initial_settings["SCMaxLength"] = defaults["SCMaxLength"]
initial_settings["SCDesiredLength"] = defaults["SCDesiredLength"]
return initial_settings["SCMaxLength"],initial_settings["SCDesiredLength"]
GENERATE_SETTINGS["SCDesiredLength"].input(persistSCDesireLength,
inputs=GENERATE_SETTINGS["SCDesiredLength"])
GENERATE_SETTINGS["SCMaxLength"].change(limitSCDesiredLength,
inputs=[GENERATE_SETTINGS["SCDesiredLength"],
GENERATE_SETTINGS["SCMaxLength"]],
outputs=GENERATE_SETTINGS["SCDesiredLength"])
resetSCValuesButton.click(resetSCValues,
outputs=[GENERATE_SETTINGS["SCMaxLength"],
GENERATE_SETTINGS["SCDesiredLength"]])
with gr.Column():
GENERATE_SETTINGS["seed"] = gr.Textbox(
label="Seed", value=initial_settings["seed"]
)
GENERATE_SETTINGS["alpha"] = gr.Slider(
label="alpha", minimum=0, maximum=2.0, step=0.1, value=initial_settings["alpha"],
info="Similarity to reference audio file's voice. 0 is very similar to reference file, 1+ is very dissimilar. Loss of quality is likely the lower this setting."
)
GENERATE_SETTINGS["beta"] = gr.Slider(
label="beta", minimum=0, maximum=2.0, step=0.1, value=initial_settings["beta"],
info="Prosody / expressiveness. 0 is very bland/monotonous and higher values are more expressive. Too high and you will begin to skip and/or skew word pronunciation."
)
GENERATE_SETTINGS["diffusion_steps"] = gr.Slider(
label="Diffusion Steps", minimum=0, maximum=400, step=1, value=initial_settings["diffusion_steps"],
info="Number of diffusion passes, theoretically the higher the better at the cost of speed."
)
GENERATE_SETTINGS["embedding_scale"] = gr.Slider(
label="Embedding Scale", minimum=0, maximum=4.0, step=0.1, value=initial_settings["embedding_scale"],
info="Emotion. Higher values result in a higher range of emotion (or variance in tone)."
)
with gr.Column():
generation_output = gr.Audio(label="Output")
seed_output = gr.Dataframe(
headers=["Seed"],
datatype=["number"],
value=[],
height=200,
min_width=200
)
with gr.Row():
update_button = gr.Button("Update Voices")
generate_button = gr.Button("Generate", variant="primary")
with gr.Tab(id="History", label="History"):
with gr.Column():
with gr.Row():
with gr.Column():
genHistoryDF = getGenHistory()
# grab voices for filter
voiceList = []
voiceList = genHistoryDF['voice'].unique().tolist()
voiceList = ['All'] + voiceList
selectedFilePlayer = gr.Audio(label="Player", show_label=False, interactive=False)
with gr.Accordion("Generation Text", open=True):
generationHistoryText = gr.Markdown("No history record selected")
with gr.Accordion("Generation Settings", open=True):
sendToGenerationTabButton = gr.Button("Send to Generation Tab", variant="primary", size="sm", visible=False)
generationHistorySettings = gr.Dataframe(
type="pandas",
headers=["Option", "Value"],