forked from IAHispano/Applio
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinfer-web.py
3114 lines (2822 loc) · 123 KB
/
infer-web.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os, sys
from tensorboard import program
now_dir = os.getcwd()
sys.path.append(now_dir)
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
os.environ["OPENBLAS_NUM_THREADS"] = "1"
os.environ["no_proxy"] = "localhost, 127.0.0.1, ::1"
import logging
import shutil
import threading
from assets.configs.config import Config
import lib.globals.globals as rvc_globals
import lib.tools.modelFetcher as modelFetcher
import math as math
import ffmpeg as ffmpeg
import traceback
import warnings
from random import shuffle
from subprocess import Popen
from time import sleep
import json
import pathlib
import fairseq
import socket
import requests
import subprocess
import matplotlib.pyplot as plt
logging.getLogger("httpx").setLevel(logging.CRITICAL)
logging.getLogger("requests").setLevel(logging.CRITICAL)
logging.getLogger("faiss").setLevel(logging.WARNING)
import faiss
import gradio as gr
import numpy as np
import torch as torch
import regex as re
import soundfile as SF
SFWrite = SF.write
from dotenv import load_dotenv
from sklearn.cluster import MiniBatchKMeans
import datetime
from glob import glob1
import signal
from signal import SIGTERM
from assets.i18n.i18n import I18nAuto
from lib.modules.train.process_ckpt import (
change_info,
extract_small_model,
merge,
show_info,
)
from lib.modules.uvr5.mdxnet import MDXNetDereverb
from lib.modules.uvr5.preprocess import AudioPre, AudioPreDeEcho
from lib.modules.vc.modules import VC
from lib.modules.vc.utils import *
import lib.globals.globals as rvc_globals
import nltk
nltk.download("punkt", quiet=True)
import tabs.resources as resources
import tabs.tts as tts
import tabs.merge as mergeaudios
import tabs.processing as processing
import tabs.analyzer as analyzer
from lib.modules.infer.csvutil import CSVutil
import time
from shlex import quote as SQuote
logger = logging.getLogger(__name__)
RQuote = lambda val: SQuote(str(val))
tmp = os.path.join(now_dir, "temp")
# directories = ["logs", "datasets", "weights", "audio-others", "audio-outputs"]
shutil.rmtree(tmp, ignore_errors=True)
os.makedirs(tmp, exist_ok=True)
# Start the download server
host = "localhost"
port = 8000
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(2) # Timeout in seconds
try:
sock.connect((host, port))
logger.warn(
f"Something is listening on port {port}; check open connection and restart Applio."
)
logger.warn("Trying to start it anyway")
sock.close()
requests.post("http://localhost:8000/shutdown")
time.sleep(3)
script_path = os.path.join(now_dir, "lib", "tools", "server.py")
try:
subprocess.Popen(f"python {script_path}", shell=True)
except Exception as e:
logger.error(f"Failed to start the Flask server")
logger.error(e)
except Exception as e:
sock.close()
script_path = os.path.join(now_dir, "lib", "tools", "server.py")
try:
subprocess.Popen(f"python {script_path}", shell=True)
except Exception as e:
logger.error("Failed to start the Flask server")
logger.error(e)
os.makedirs(tmp, exist_ok=True)
os.makedirs(os.path.join(now_dir, "logs"), exist_ok=True)
os.makedirs(os.path.join(now_dir, "logs/weights"), exist_ok=True)
os.environ["temp"] = tmp
warnings.filterwarnings("ignore")
torch.manual_seed(114514)
logging.getLogger("numba").setLevel(logging.WARNING)
if not os.path.isdir("lib/csvdb/"):
os.makedirs("lib/csvdb")
frmnt, stp = open("lib/csvdb/formanting.csv", "w"), open("lib/csvdb/stop.csv", "w")
frmnt.close()
stp.close()
global DoFormant, Quefrency, Timbre
try:
DoFormant, Quefrency, Timbre = CSVutil(
"lib/csvdb/formanting.csv", "r", "formanting"
)
DoFormant = (
lambda DoFormant: True
if DoFormant.lower() == "true"
else (False if DoFormant.lower() == "false" else DoFormant)
)(DoFormant)
except (ValueError, TypeError, IndexError):
DoFormant, Quefrency, Timbre = False, 1.0, 1.0
CSVutil(
"lib/csvdb/formanting.csv", "w+", "formanting", DoFormant, Quefrency, Timbre
)
load_dotenv()
config = Config()
vc = VC(config)
if config.dml == True:
def forward_dml(ctx, x, scale):
ctx.scale = scale
res = x.clone().detach()
return res
fairseq.modules.grad_multiply.GradMultiply.forward = forward_dml
i18n = I18nAuto()
i18n.print()
# 判断是否有能用来训练和加速推理的N卡
ngpu = torch.cuda.device_count()
gpu_infos = []
mem = []
if_gpu_ok = False
isinterrupted = 0
if torch.cuda.is_available() or ngpu != 0:
for i in range(ngpu):
gpu_name = torch.cuda.get_device_name(i)
gpu_infos.append("%s\t%s" % (i, gpu_name))
mem.append(
int(
torch.cuda.get_device_properties(i).total_memory / 1024 / 1024 / 1024
+ 0.4
)
)
if len(gpu_infos) > 0:
gpu_info = "\n".join(gpu_infos)
default_batch_size = min(mem) // 2
else:
gpu_info = (
"Unfortunately, there is no compatible GPU available to support your training."
)
default_batch_size = 1
gpus = "-".join([i[0] for i in gpu_infos])
class ToolButton(gr.Button, gr.components.FormComponent):
"""Small button with single emoji as text, fits inside gradio forms"""
def __init__(self, **kwargs):
super().__init__(variant="tool", **kwargs)
def get_block_name(self):
return "button"
import lib.modules.uvr5.mdx as mdx
from lib.modules.uvr5.mdxprocess import (
get_model_list,
get_demucs_model_list,
id_to_ptm,
prepare_mdx,
run_mdx,
)
hubert_model = None
weight_root = os.getenv("weight_root")
weight_uvr5_root = os.getenv("weight_uvr5_root")
index_root = os.getenv("index_root")
datasets_root = "datasets"
fshift_root = "lib/modules/infer/formantshiftcfg"
audio_root = "assets\\audios"
audio_others_root = "assets/audios/audio-others"
sup_audioext = {
"wav",
"mp3",
"flac",
"ogg",
"opus",
"m4a",
"mp4",
"aac",
"alac",
"wma",
"aiff",
"webm",
"ac3",
}
names = [
os.path.join(root, file)
for root, _, files in os.walk(weight_root)
for file in files
if file.endswith((".pth", ".onnx"))
]
indexes_list = [
os.path.join(root, name)
for root, _, files in os.walk(index_root, topdown=False)
for name in files
if name.endswith(".index") and "trained" not in name
]
audio_paths = [
os.path.join(root, name)
for root, _, files in os.walk(audio_root, topdown=False)
for name in files
if name.endswith(tuple(sup_audioext)) and root == audio_root
]
audio_others_paths = [
os.path.join(root, name)
for root, _, files in os.walk(audio_others_root, topdown=False)
for name in files
if name.endswith(tuple(sup_audioext)) and root == audio_others_root
]
check_for_name = lambda: sorted(names)[0] if names else ""
datasets = []
for foldername in os.listdir(os.path.join(now_dir, datasets_root)):
if os.path.isdir(os.path.join(now_dir, "datasets", foldername)):
datasets.append(foldername)
def get_dataset():
if len(datasets) > 0:
return sorted(datasets)[0]
else:
return ""
def change_dataset(trainset_dir4):
return gr.Textbox.update(value=trainset_dir4)
uvr5_names = [
"HP2_all_vocals.pth",
"HP3_all_vocals.pth",
"HP5_only_main_vocal.pth",
"VR-DeEchoAggressive.pth",
"VR-DeEchoDeReverb.pth",
"VR-DeEchoNormal.pth",
]
__s = "https://huggingface.co/lj1995/VoiceConversionWebUI/resolve/main/uvr5_weights/"
def id_(mkey):
if mkey in uvr5_names:
model_name, ext = os.path.splitext(mkey)
mpath = f"{now_dir}/assets/uvr5_weights/{mkey}"
if not os.path.exists(f"{now_dir}/assets/uvr5_weights/{mkey}"):
print("Downloading model...", end=" ")
subprocess.run(["python", "-m", "wget", "-o", mpath, __s + mkey])
print(f"saved to {mpath}")
return model_name
else:
return model_name
else:
return None
def update_model_choices(select_value):
model_ids = get_model_list()
model_ids_list = list(model_ids)
demucs_model_ids = get_demucs_model_list()
demucs_model_ids_list = list(demucs_model_ids)
if select_value == "VR":
return {"choices": uvr5_names, "__type__": "update"}
elif select_value == "MDX":
return {"choices": model_ids_list, "__type__": "update"}
elif select_value == "Demucs (Beta)":
return {"choices": demucs_model_ids_list, "__type__": "update"}
def update_dataset_list(name):
new_datasets = []
for foldername in os.listdir(os.path.join(now_dir, datasets_root)):
if os.path.isdir(os.path.join(now_dir, "datasets", foldername)):
new_datasets.append(
os.path.join(
now_dir,
"datasets",
foldername,
)
)
return gr.Dropdown.update(choices=new_datasets)
def get_indexes():
indexes_list = [
os.path.join(dirpath, filename)
for dirpath, _, filenames in os.walk(index_root)
for filename in filenames
if filename.endswith(".index") and "trained" not in filename
]
return indexes_list if indexes_list else ""
def get_fshift_presets():
fshift_presets_list = [
os.path.join(dirpath, filename)
for dirpath, _, filenames in os.walk(fshift_root)
for filename in filenames
if filename.endswith(".txt")
]
return fshift_presets_list if fshift_presets_list else ""
def uvr(
model_name,
inp_root,
save_root_vocal,
paths,
save_root_ins,
agg,
format0,
architecture,
):
infos = []
if architecture == "VR":
try:
inp_root = inp_root.strip(" ").strip('"').strip("\n").strip('"').strip(" ")
save_root_vocal = (
save_root_vocal.strip(" ").strip('"').strip("\n").strip('"').strip(" ")
)
save_root_ins = (
save_root_ins.strip(" ").strip('"').strip("\n").strip('"').strip(" ")
)
model_name = id_(model_name)
if model_name == None:
return ""
else:
pass
infos.append(
i18n("Starting audio conversion... (This might take a moment)")
)
if model_name == "onnx_dereverb_By_FoxJoy":
pre_fun = MDXNetDereverb(15, config.device)
else:
func = AudioPre if "DeEcho" not in model_name else AudioPreDeEcho
pre_fun = func(
agg=int(agg),
model_path=os.path.join(
os.getenv("weight_uvr5_root"), model_name + ".pth"
),
device=config.device,
is_half=config.is_half,
)
if inp_root != "":
paths = [
os.path.join(inp_root, name)
for root, _, files in os.walk(inp_root, topdown=False)
for name in files
if name.endswith(tuple(sup_audioext)) and root == inp_root
]
else:
paths = [path.name for path in paths]
for path in paths:
inp_path = os.path.join(inp_root, path)
need_reformat = 1
done = 0
try:
info = ffmpeg.probe(inp_path, cmd="ffprobe")
if (
info["streams"][0]["channels"] == 2
and info["streams"][0]["sample_rate"] == "44100"
):
need_reformat = 0
pre_fun._path_audio_(
inp_path, save_root_ins, save_root_vocal, format0
)
done = 1
except:
need_reformat = 1
traceback.print_exc()
if need_reformat == 1:
tmp_path = "%s/%s.reformatted.wav" % (
os.path.join(os.environ["tmp"]),
os.path.basename(inp_path),
)
os.system(
"ffmpeg -i %s -vn -acodec pcm_s16le -ac 2 -ar 44100 %s -y"
% (inp_path, tmp_path)
)
inp_path = tmp_path
try:
if done == 0:
pre_fun.path_audio(
inp_path, save_root_ins, save_root_vocal, format0
)
infos.append("%s->Success" % (os.path.basename(inp_path)))
yield "\n".join(infos)
except:
try:
if done == 0:
pre_fun._path_audio_(
inp_path, save_root_ins, save_root_vocal, format0
)
infos.append("%s->Success" % (os.path.basename(inp_path)))
yield "\n".join(infos)
except:
infos.append(
"%s->%s"
% (os.path.basename(inp_path), traceback.format_exc())
)
yield "\n".join(infos)
except:
infos.append(traceback.format_exc())
yield "\n".join(infos)
finally:
try:
if model_name == "onnx_dereverb_By_FoxJoy":
del pre_fun.pred.model
del pre_fun.pred.model_
else:
del pre_fun.model
del pre_fun
except:
traceback.print_exc()
if torch.cuda.is_available():
torch.cuda.empty_cache()
logger.info("Executed torch.cuda.empty_cache()")
yield "\n".join(infos)
elif architecture == "MDX":
try:
infos.append(
i18n("Starting audio conversion... (This might take a moment)")
)
yield "\n".join(infos)
inp_root, save_root_vocal, save_root_ins = [
x.strip(" ").strip('"').strip("\n").strip('"').strip(" ")
for x in [inp_root, save_root_vocal, save_root_ins]
]
if inp_root != "":
paths = [
os.path.join(inp_root, name)
for root, _, files in os.walk(inp_root, topdown=False)
for name in files
if name.endswith(tuple(sup_audioext)) and root == inp_root
]
else:
paths = [path.name for path in paths]
print(paths)
invert = True
denoise = True
use_custom_parameter = True
dim_f = 3072
dim_t = 256
n_fft = 7680
use_custom_compensation = True
compensation = 1.025
suffix = "Vocals_custom" # @param ["Vocals", "Drums", "Bass", "Other"]{allow-input: true}
suffix_invert = "Instrumental_custom" # @param ["Instrumental", "Drumless", "Bassless", "Instruments"]{allow-input: true}
print_settings = True # @param{type:"boolean"}
onnx = id_to_ptm(model_name)
compensation = (
compensation
if use_custom_compensation or use_custom_parameter
else None
)
mdx_model = prepare_mdx(
onnx,
use_custom_parameter,
dim_f,
dim_t,
n_fft,
compensation=compensation,
)
for path in paths:
# inp_path = os.path.join(inp_root, path)
suffix_naming = suffix if use_custom_parameter else None
diff_suffix_naming = suffix_invert if use_custom_parameter else None
run_mdx(
onnx,
mdx_model,
path,
format0,
diff=invert,
suffix=suffix_naming,
diff_suffix=diff_suffix_naming,
denoise=denoise,
)
if print_settings:
print()
print("[MDX-Net_Colab settings used]")
print(f"Model used: {onnx}")
print(f"Model MD5: {mdx.MDX.get_hash(onnx)}")
print(f"Model parameters:")
print(f" -dim_f: {mdx_model.dim_f}")
print(f" -dim_t: {mdx_model.dim_t}")
print(f" -n_fft: {mdx_model.n_fft}")
print(f" -compensation: {mdx_model.compensation}")
print()
print("[Input file]")
print("filename(s): ")
for filename in paths:
print(f" -{filename}")
infos.append(f"{os.path.basename(filename)}->Success")
yield "\n".join(infos)
except:
infos.append(traceback.format_exc())
yield "\n".join(infos)
finally:
try:
del mdx_model
except:
traceback.print_exc()
print("clean_empty_cache")
if torch.cuda.is_available():
torch.cuda.empty_cache()
elif architecture == "Demucs (Beta)":
try:
infos.append(
i18n("Starting audio conversion... (This might take a moment)")
)
yield "\n".join(infos)
inp_root, save_root_vocal, save_root_ins = [
x.strip(" ").strip('"').strip("\n").strip('"').strip(" ")
for x in [inp_root, save_root_vocal, save_root_ins]
]
if inp_root != "":
paths = [
os.path.join(inp_root, name)
for root, _, files in os.walk(inp_root, topdown=False)
for name in files
if name.endswith(tuple(sup_audioext)) and root == inp_root
]
else:
paths = [path.name for path in paths]
# Loop through the audio files and separate sources
for path in paths:
input_audio_path = os.path.join(inp_root, path)
filename_without_extension = os.path.splitext(
os.path.basename(input_audio_path)
)[0]
_output_dir = os.path.join(tmp, model_name, filename_without_extension)
vocals = os.path.join(_output_dir, "vocals.wav")
no_vocals = os.path.join(_output_dir, "no_vocals.wav")
os.makedirs(tmp, exist_ok=True)
if torch.cuda.is_available():
cpu_insted = ""
else:
cpu_insted = "-d cpu"
print(cpu_insted)
# Use with os.system to separate audio sources becuase at invoking from the command line it is faster than invoking from python
os.system(
f"python -m .separate --two-stems=vocals -n {model_name} {cpu_insted} {input_audio_path} -o {tmp}"
)
# Move vocals and no_vocals to the output directory assets/audios for the vocal and assets/audios/audio-others for the instrumental
shutil.move(vocals, save_root_vocal)
shutil.move(no_vocals, save_root_ins)
# And now rename the vocals and no vocals with the name of the input audio file and the suffix vocals or instrumental
os.rename(
os.path.join(save_root_vocal, "vocals.wav"),
os.path.join(
save_root_vocal, f"{filename_without_extension}_vocals.wav"
),
)
os.rename(
os.path.join(save_root_ins, "no_vocals.wav"),
os.path.join(
save_root_ins, f"{filename_without_extension}_instrumental.wav"
),
)
# Remove the temporary directory
os.rmdir(tmp, model_name)
infos.append(f"{os.path.basename(input_audio_path)}->Success")
yield "\n".join(infos)
except:
infos.append(traceback.format_exc())
yield "\n".join(infos)
def change_choices():
names = [
os.path.join(root, file)
for root, _, files in os.walk(weight_root)
for file in files
if file.endswith((".pth", ".onnx"))
]
indexes_list = [
os.path.join(root, name)
for root, _, files in os.walk(index_root, topdown=False)
for name in files
if name.endswith(".index") and "trained" not in name
]
audio_paths = [
os.path.join(root, name)
for root, _, files in os.walk(audio_root, topdown=False)
for name in files
if name.endswith(tuple(sup_audioext)) and root == audio_root
]
return (
{"choices": sorted(names), "__type__": "update"},
{"choices": sorted(indexes_list), "__type__": "update"},
{"choices": sorted(audio_paths), "__type__": "update"},
)
def change_choices2():
names = [
os.path.join(root, file)
for root, _, files in os.walk(weight_root)
for file in files
if file.endswith((".pth", ".onnx"))
]
indexes_list = [
os.path.join(root, name)
for root, _, files in os.walk(index_root, topdown=False)
for name in files
if name.endswith(".index") and "trained" not in name
]
return (
{"choices": sorted(names), "__type__": "update"},
{"choices": sorted(indexes_list), "__type__": "update"},
)
def clean():
return {"value": "", "__type__": "update"}
def export_onnx():
from lib.modules.onnx.export import export_onnx as eo
eo()
sr_dict = {
"32k": 32000,
"40k": 40000,
"48k": 48000,
}
def if_done(done, p):
while 1:
if p.poll() is None:
sleep(0.5)
else:
break
done[0] = True
def if_done_multi(done, ps):
while 1:
# poll==None代表进程未结束
# 只要有一个进程未结束都不停
flag = 1
for p in ps:
if p.poll() is None:
flag = 0
sleep(0.5)
break
if flag == 1:
break
done[0] = True
def formant_enabled(
cbox, qfrency, tmbre, frmntapply, formantpreset, formant_refresh_button
):
if cbox:
DoFormant = True
CSVutil(
"lib/csvdb/formanting.csv", "w+", "formanting", DoFormant, qfrency, tmbre
)
# print(f"is checked? - {cbox}\ngot {DoFormant}")
return (
{"value": True, "__type__": "update"},
{"visible": True, "__type__": "update"},
{"visible": True, "__type__": "update"},
{"visible": True, "__type__": "update"},
{"visible": True, "__type__": "update"},
{"visible": True, "__type__": "update"},
)
else:
DoFormant = False
CSVutil(
"lib/csvdb/formanting.csv", "w+", "formanting", DoFormant, qfrency, tmbre
)
# print(f"is checked? - {cbox}\ngot {DoFormant}")
return (
{"value": False, "__type__": "update"},
{"visible": False, "__type__": "update"},
{"visible": False, "__type__": "update"},
{"visible": False, "__type__": "update"},
{"visible": False, "__type__": "update"},
{"visible": False, "__type__": "update"},
{"visible": False, "__type__": "update"},
)
def formant_apply(qfrency, tmbre):
Quefrency = qfrency
Timbre = tmbre
DoFormant = True
CSVutil("lib/csvdb/formanting.csv", "w+", "formanting", DoFormant, qfrency, tmbre)
return (
{"value": Quefrency, "__type__": "update"},
{"value": Timbre, "__type__": "update"},
)
def update_fshift_presets(preset, qfrency, tmbre):
if preset:
with open(preset, "r") as p:
content = p.readlines()
qfrency, tmbre = content[0].strip(), content[1]
formant_apply(qfrency, tmbre)
else:
qfrency, tmbre = preset_apply(preset, qfrency, tmbre)
return (
{"choices": get_fshift_presets(), "__type__": "update"},
{"value": qfrency, "__type__": "update"},
{"value": tmbre, "__type__": "update"},
)
def preprocess_dataset(trainset_dir, exp_dir, sr, n_p, dataset_path):
if re.search(r"[^0-9a-zA-Z !@#$%^&\(\)_+=\-`~\[\]\{\};',.]", exp_dir):
raise gr.Error("Model name contains non-ASCII characters!")
if not dataset_path.strip() == "":
trainset_dir = dataset_path
else:
trainset_dir = os.path.join(now_dir, "datasets", trainset_dir)
sr = sr_dict[sr]
os.makedirs("%s/logs/%s" % (now_dir, exp_dir), exist_ok=True)
f = open("%s/logs/%s/preprocess.log" % (now_dir, exp_dir), "w")
f.close()
per = 3.0 if config.is_half else 3.7
cmd = '"%s" lib/modules/train/preprocess.py "%s" %s %s "%s/logs/%s" %s %.1f' % (
config.python_cmd,
trainset_dir,
sr,
n_p,
now_dir,
exp_dir,
config.noparallel,
per,
)
logger.info(cmd)
p = Popen(cmd, shell=True) # , stdin=PIPE, stdout=PIPE,stderr=PIPE,cwd=now_dir
###煞笔gr, popen read都非得全跑完了再一次性读取, 不用gr就正常读一句输出一句;只能额外弄出一个文本流定时读
done = [False]
threading.Thread(
target=if_done,
args=(
done,
p,
),
).start()
while 1:
with open("%s/logs/%s/preprocess.log" % (now_dir, exp_dir), "r") as f:
yield (f.read())
sleep(1)
if done[0]:
break
with open("%s/logs/%s/preprocess.log" % (now_dir, exp_dir), "r") as f:
log = f.read()
logger.info(log)
yield log
def extract_f0_feature(gpus, n_p, f0method, if_f0, exp_dir, version19, echl):
if re.search(r"[^0-9a-zA-Z !@#$%^&\(\)_+=\-`~\[\]\{\};',.]", exp_dir):
raise gr.Error("Model name contains non-ASCII characters!")
gpus_rmvpe = gpus
gpus = gpus.split("-")
os.makedirs("%s/logs/%s" % (now_dir, exp_dir), exist_ok=True)
f = open("%s/logs/%s/extract_f0_feature.log" % (now_dir, exp_dir), "w")
f.close()
if if_f0:
if f0method != "rmvpe_gpu":
cmd = (
'"%s" lib/modules/train/extract/extract_f0_print.py "%s/logs/%s" %s %s %s'
% (config.python_cmd, now_dir, exp_dir, n_p, f0method, RQuote(echl))
)
logger.info(cmd)
p = Popen(
cmd, shell=True, cwd=now_dir
) # , stdin=PIPE, stdout=PIPE,stderr=PIPE
###煞笔gr, popen read都非得全跑完了再一次性读取, 不用gr就正常读一句输出一句;只能额外弄出一个文本流定时读
done = [False]
threading.Thread(
target=if_done,
args=(
done,
p,
),
).start()
else:
if gpus_rmvpe != "-":
gpus_rmvpe = gpus_rmvpe.split("-")
leng = len(gpus_rmvpe)
ps = []
for idx, n_g in enumerate(gpus_rmvpe):
cmd = (
'"%s" lib/modules/train/extract/extract_f0_rmvpe.py %s %s %s "%s/logs/%s" %s '
% (
config.python_cmd,
leng,
idx,
n_g,
now_dir,
exp_dir,
config.is_half,
)
)
logger.info(cmd)
p = Popen(
cmd, shell=True, cwd=now_dir
) # , shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE, cwd=now_dir
ps.append(p)
###煞笔gr, popen read都非得全跑完了再一次性读取, 不用gr就正常读一句输出一句;只能额外弄出一个文本流定时读
done = [False]
threading.Thread(
target=if_done_multi, #
args=(
done,
ps,
),
).start()
else:
cmd = (
config.python_cmd
+ ' lib/modules/train/extract/extract_f0_rmvpe_dml.py "%s/logs/%s" '
% (
now_dir,
exp_dir,
)
)
logger.info(cmd)
p = Popen(
cmd, shell=True, cwd=now_dir
) # , shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE, cwd=now_dir
p.wait()
done = [True]
while 1:
with open(
"%s/logs/%s/extract_f0_feature.log" % (now_dir, exp_dir), "r"
) as f:
yield (f.read())
sleep(1)
if done[0]:
break
with open("%s/logs/%s/extract_f0_feature.log" % (now_dir, exp_dir), "r") as f:
log = f.read()
logger.info(log)
yield log
leng = len(gpus)
ps = []
for idx, n_g in enumerate(gpus):
cmd = (
'"%s" lib/modules/train/extract_feature_print.py %s %s %s %s "%s/logs/%s" %s %s'
% (
config.python_cmd,
config.device,
leng,
idx,
n_g,
now_dir,
exp_dir,
version19,
config.is_half,
)
)
logger.info(cmd)
p = Popen(
cmd, shell=True, cwd=now_dir
) # , shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE, cwd=now_dir
ps.append(p)
###煞笔gr, popen read都非得全跑完了再一次性读取, 不用gr就正常读一句输出一句;只能额外弄出一个文本流定时读
done = [False]
threading.Thread(
target=if_done_multi,
args=(
done,
ps,
),
).start()
while 1:
with open("%s/logs/%s/extract_f0_feature.log" % (now_dir, exp_dir), "r") as f:
yield (f.read())
sleep(1)
if done[0]:
break
with open("%s/logs/%s/extract_f0_feature.log" % (now_dir, exp_dir), "r") as f:
log = f.read()
logger.info(log)
yield log
def get_pretrained_models(path_str, f0_str, sr2):
if_pretrained_generator_exist = os.access(
"assets/pretrained%s/%sG%s.pth" % (path_str, f0_str, sr2), os.F_OK
)
if_pretrained_discriminator_exist = os.access(
"assets/pretrained%s/%sD%s.pth" % (path_str, f0_str, sr2), os.F_OK
)
if not if_pretrained_generator_exist:
logger.warn(
"assets/pretrained%s/%sG%s.pth not exist, will not use pretrained model",
path_str,
f0_str,
sr2,
)
if not if_pretrained_discriminator_exist:
logger.warn(
"assets/pretrained%s/%sD%s.pth not exist, will not use pretrained model",
path_str,
f0_str,
sr2,
)
return (
"assets/pretrained%s/%sG%s.pth" % (path_str, f0_str, sr2)
if if_pretrained_generator_exist
else "",
"assets/pretrained%s/%sD%s.pth" % (path_str, f0_str, sr2)
if if_pretrained_discriminator_exist
else "",