Eempostor commited on
Commit
36656a5
·
verified ·
1 Parent(s): 188d16b

Delete lib/modules.py

Browse files
Files changed (1) hide show
  1. lib/modules.py +0 -577
lib/modules.py DELETED
@@ -1,577 +0,0 @@
1
- import os, sys
2
- import traceback
3
- import logging
4
- now_dir = os.getcwd()
5
- sys.path.append(now_dir)
6
- logger = logging.getLogger(__name__)
7
- import numpy as np
8
- import soundfile as sf
9
- import torch
10
- from io import BytesIO
11
- from lib.infer_libs.audio import load_audio
12
- from lib.infer_libs.audio import wav2
13
- from lib.infer_libs.infer_pack.models import (
14
- SynthesizerTrnMs256NSFsid,
15
- SynthesizerTrnMs256NSFsid_nono,
16
- SynthesizerTrnMs768NSFsid,
17
- SynthesizerTrnMs768NSFsid_nono,
18
- )
19
- from lib.pipeline import Pipeline
20
- import time
21
- import glob
22
- from shutil import move
23
- from fairseq import checkpoint_utils
24
-
25
- sup_audioext = {
26
- "wav",
27
- "mp3",
28
- "flac",
29
- "ogg",
30
- "opus",
31
- "m4a",
32
- "mp4",
33
- "aac",
34
- "alac",
35
- "wma",
36
- "aiff",
37
- "webm",
38
- "ac3",
39
- }
40
-
41
- def note_to_hz(note_name):
42
- try:
43
- SEMITONES = {'C': -9, 'C#': -8, 'D': -7, 'D#': -6, 'E': -5, 'F': -4, 'F#': -3, 'G': -2, 'G#': -1, 'A': 0, 'A#': 1, 'B': 2}
44
- pitch_class, octave = note_name[:-1], int(note_name[-1])
45
- semitone = SEMITONES[pitch_class]
46
- note_number = 12 * (octave - 4) + semitone
47
- frequency = 440.0 * (2.0 ** (1.0/12)) ** note_number
48
- return frequency
49
- except:
50
- return None
51
-
52
- def load_hubert(hubert_model_path, config):
53
- models, _, _ = checkpoint_utils.load_model_ensemble_and_task(
54
- [hubert_model_path],
55
- suffix="",
56
- )
57
- hubert_model = models[0]
58
- hubert_model = hubert_model.to(config.device)
59
- if config.is_half:
60
- hubert_model = hubert_model.half()
61
- else:
62
- hubert_model = hubert_model.float()
63
- return hubert_model.eval()
64
-
65
- class VC:
66
- def __init__(self, config):
67
- self.n_spk = None
68
- self.tgt_sr = None
69
- self.net_g = None
70
- self.pipeline = None
71
- self.cpt = None
72
- self.version = None
73
- self.if_f0 = None
74
- self.version = None
75
- self.hubert_model = None
76
-
77
- self.config = config
78
-
79
- def get_vc(self, sid, *to_return_protect):
80
- logger.info("Get sid: " + sid)
81
-
82
- to_return_protect0 = {
83
- "visible": self.if_f0 != 0,
84
- "value": to_return_protect[0]
85
- if self.if_f0 != 0 and to_return_protect
86
- else 0.5,
87
- "__type__": "update",
88
- }
89
- to_return_protect1 = {
90
- "visible": self.if_f0 != 0,
91
- "value": to_return_protect[1]
92
- if self.if_f0 != 0 and to_return_protect
93
- else 0.33,
94
- "__type__": "update",
95
- }
96
-
97
- if sid == "" or sid == []:
98
- if self.hubert_model is not None: # 考虑到轮询, 需要加个判断看是否 sid 是由有模型切换到无模型的
99
- logger.info("Clean model cache")
100
- del (
101
- self.net_g,
102
- self.n_spk,
103
- self.vc,
104
- self.hubert_model,
105
- self.tgt_sr,
106
- ) # ,cpt
107
- self.hubert_model = (
108
- self.net_g
109
- ) = self.n_spk = self.vc = self.hubert_model = self.tgt_sr = None
110
- if torch.cuda.is_available():
111
- torch.cuda.empty_cache()
112
- ###楼下不这么折腾清理不干净
113
- self.if_f0 = self.cpt.get("f0", 1)
114
- self.version = self.cpt.get("version", "v1")
115
- if self.version == "v1":
116
- if self.if_f0 == 1:
117
- self.net_g = SynthesizerTrnMs256NSFsid(
118
- *self.cpt["config"], is_half=self.config.is_half
119
- )
120
- else:
121
- self.net_g = SynthesizerTrnMs256NSFsid_nono(*self.cpt["config"])
122
- elif self.version == "v2":
123
- if self.if_f0 == 1:
124
- self.net_g = SynthesizerTrnMs768NSFsid(
125
- *self.cpt["config"], is_half=self.config.is_half
126
- )
127
- else:
128
- self.net_g = SynthesizerTrnMs768NSFsid_nono(*self.cpt["config"])
129
- del self.net_g, self.cpt
130
- if torch.cuda.is_available():
131
- torch.cuda.empty_cache()
132
- return (
133
- {"visible": False, "__type__": "update"},
134
- {
135
- "visible": True,
136
- "value": to_return_protect0,
137
- "__type__": "update",
138
- },
139
- {
140
- "visible": True,
141
- "value": to_return_protect1,
142
- "__type__": "update",
143
- },
144
- "",
145
- "",
146
- )
147
- #person = f'{os.getenv("weight_root")}/{sid}'
148
- person = f'{sid}'
149
- #logger.info(f"Loading: {person}")
150
- logger.info(f"Loading...")
151
- self.cpt = torch.load(person, map_location="cpu")
152
- self.tgt_sr = self.cpt["config"][-1]
153
- self.cpt["config"][-3] = self.cpt["weight"]["emb_g.weight"].shape[0] # n_spk
154
- self.if_f0 = self.cpt.get("f0", 1)
155
- self.version = self.cpt.get("version", "v1")
156
-
157
- synthesizer_class = {
158
- ("v1", 1): SynthesizerTrnMs256NSFsid,
159
- ("v1", 0): SynthesizerTrnMs256NSFsid_nono,
160
- ("v2", 1): SynthesizerTrnMs768NSFsid,
161
- ("v2", 0): SynthesizerTrnMs768NSFsid_nono,
162
- }
163
-
164
- self.net_g = synthesizer_class.get(
165
- (self.version, self.if_f0), SynthesizerTrnMs256NSFsid
166
- )(*self.cpt["config"], is_half=self.config.is_half)
167
-
168
- del self.net_g.enc_q
169
-
170
- self.net_g.load_state_dict(self.cpt["weight"], strict=False)
171
- self.net_g.eval().to(self.config.device)
172
- if self.config.is_half:
173
- self.net_g = self.net_g.half()
174
- else:
175
- self.net_g = self.net_g.float()
176
-
177
- self.pipeline = Pipeline(self.tgt_sr, self.config)
178
- n_spk = self.cpt["config"][-3]
179
- #index = {"value": get_index_path_from_model(sid), "__type__": "update"}
180
- #logger.info("Select index: " + index["value"])
181
-
182
- return (
183
- (
184
- {"visible": False, "maximum": n_spk, "__type__": "update"},
185
- to_return_protect0,
186
- to_return_protect1
187
- )
188
- if to_return_protect
189
- else {"visible": False, "maximum": n_spk, "__type__": "update"}
190
- )
191
-
192
- def vc_single_dont_save(
193
- self,
194
- sid,
195
- input_audio_path1,
196
- f0_up_key,
197
- f0_method,
198
- file_index,
199
- file_index2,
200
- index_rate,
201
- filter_radius,
202
- resample_sr,
203
- rms_mix_rate,
204
- protect,
205
- crepe_hop_length,
206
- do_formant,
207
- quefrency,
208
- timbre,
209
- f0_min,
210
- f0_max,
211
- f0_autotune,
212
- hubert_model_path = "assets/hubert/hubert_base.pt"
213
- ):
214
- """
215
- Performs inference without saving
216
-
217
- Parameters:
218
- - sid (int)
219
- - input_audio_path1 (str)
220
- - f0_up_key (int)
221
- - f0_method (str)
222
- - file_index (str)
223
- - file_index2 (str)
224
- - index_rate (float)
225
- - filter_radius (int)
226
- - resample_sr (int)
227
- - rms_mix_rate (float)
228
- - protect (float)
229
- - crepe_hop_length (int)
230
- - do_formant (bool)
231
- - quefrency (float)
232
- - timbre (float)
233
- - f0_min (str)
234
- - f0_max (str)
235
- - f0_autotune (bool)
236
- - hubert_model_path (str)
237
-
238
- Returns:
239
- Tuple(Tuple(status, index_info, times), Tuple(sr, data)):
240
- - Tuple(status, index_info, times):
241
- - status (str): either "Success." or an error
242
- - index_info (str): index path if used
243
- - times (list): [npy_time, f0_time, infer_time, total_time]
244
- - Tuple(sr, data): Audio data results.
245
- """
246
- global total_time
247
- total_time = 0
248
- start_time = time.time()
249
-
250
- if not input_audio_path1:
251
- return "You need to upload an audio", None
252
-
253
- if not os.path.exists(input_audio_path1):
254
- return "Audio was not properly selected or doesn't exist", None
255
-
256
- f0_up_key = int(f0_up_key)
257
- if not f0_min.isdigit():
258
- f0_min = note_to_hz(f0_min)
259
- if f0_min:
260
- print(f"Converted Min pitch: freq - {f0_min}")
261
- else:
262
- f0_min = 50
263
- print("Invalid minimum pitch note. Defaulting to 50hz.")
264
- else:
265
- f0_min = float(f0_min)
266
- if not f0_max.isdigit():
267
- f0_max = note_to_hz(f0_max)
268
- if f0_max:
269
- print(f"Converted Max pitch: freq - {f0_max}")
270
- else:
271
- f0_max = 1100
272
- print("Invalid maximum pitch note. Defaulting to 1100hz.")
273
- else:
274
- f0_max = float(f0_max)
275
-
276
- try:
277
- print(f"Attempting to load {input_audio_path1}....")
278
- audio = load_audio(file=input_audio_path1,
279
- sr=16000,
280
- DoFormant=do_formant,
281
- Quefrency=quefrency,
282
- Timbre=timbre)
283
-
284
- audio_max = np.abs(audio).max() / 0.95
285
- if audio_max > 1:
286
- audio /= audio_max
287
- times = [0, 0, 0]
288
-
289
- if self.hubert_model is None:
290
- self.hubert_model = load_hubert(hubert_model_path, self.config)
291
-
292
- try:
293
- self.if_f0 = self.cpt.get("f0", 1)
294
- except NameError:
295
- message = "Model was not properly selected"
296
- print(message)
297
- return message, None
298
-
299
- if file_index and not file_index == "" and isinstance(file_index, str):
300
- file_index = file_index.strip(" ") \
301
- .strip('"') \
302
- .strip("\n") \
303
- .strip('"') \
304
- .strip(" ") \
305
- .replace("trained", "added")
306
- elif file_index2:
307
- file_index = file_index2
308
- else:
309
- file_index = ""
310
-
311
- try:
312
- audio_opt = self.pipeline.pipeline(
313
- self.hubert_model,
314
- self.net_g,
315
- sid,
316
- audio,
317
- input_audio_path1,
318
- times,
319
- f0_up_key,
320
- f0_method,
321
- file_index,
322
- index_rate,
323
- self.if_f0,
324
- filter_radius,
325
- self.tgt_sr,
326
- resample_sr,
327
- rms_mix_rate,
328
- self.version,
329
- protect,
330
- crepe_hop_length,
331
- f0_autotune,
332
- f0_min=f0_min,
333
- f0_max=f0_max
334
- )
335
- except AssertionError:
336
- message = "Mismatching index version detected (v1 with v2, or v2 with v1)."
337
- print(message)
338
- return message, None
339
- except NameError:
340
- message = "RVC libraries are still loading. Please try again in a few seconds."
341
- print(message)
342
- return message, None
343
-
344
- if self.tgt_sr != resample_sr >= 16000:
345
- tgt_sr = resample_sr
346
- else:
347
- tgt_sr = self.tgt_sr
348
- index_info = (
349
- "Index: %s." % file_index
350
- if isinstance(file_index, str) and os.path.exists(file_index)
351
- else "Index not used."
352
- )
353
- end_time = time.time()
354
- total_time = end_time - start_time
355
- times.append(total_time)
356
- return (
357
- ("Success.", index_info, times),
358
- (tgt_sr, audio_opt),
359
- )
360
- except:
361
- info = traceback.format_exc()
362
- logger.warn(info)
363
- return (
364
- (info, None, [None, None, None, None]),
365
- (None, None)
366
- )
367
-
368
- def vc_single(
369
- self,
370
- sid,
371
- input_audio_path1,
372
- f0_up_key,
373
- f0_method,
374
- file_index,
375
- file_index2,
376
- index_rate,
377
- filter_radius,
378
- resample_sr,
379
- rms_mix_rate,
380
- protect,
381
- format1,
382
- crepe_hop_length,
383
- do_formant,
384
- quefrency,
385
- timbre,
386
- f0_min,
387
- f0_max,
388
- f0_autotune,
389
- hubert_model_path = "assets/hubert/hubert_base.pt"
390
- ):
391
- """
392
- Performs inference with saving
393
-
394
- Parameters:
395
- - sid (int)
396
- - input_audio_path1 (str)
397
- - f0_up_key (int)
398
- - f0_method (str)
399
- - file_index (str)
400
- - file_index2 (str)
401
- - index_rate (float)
402
- - filter_radius (int)
403
- - resample_sr (int)
404
- - rms_mix_rate (float)
405
- - protect (float)
406
- - format1 (str)
407
- - crepe_hop_length (int)
408
- - do_formant (bool)
409
- - quefrency (float)
410
- - timbre (float)
411
- - f0_min (str)
412
- - f0_max (str)
413
- - f0_autotune (bool)
414
- - hubert_model_path (str)
415
-
416
- Returns:
417
- Tuple(Tuple(status, index_info, times), Tuple(sr, data), output_path):
418
- - Tuple(status, index_info, times):
419
- - status (str): either "Success." or an error
420
- - index_info (str): index path if used
421
- - times (list): [npy_time, f0_time, infer_time, total_time]
422
- - Tuple(sr, data): Audio data results.
423
- - output_path (str): Audio results path
424
- """
425
- global total_time
426
- total_time = 0
427
- start_time = time.time()
428
-
429
- if not input_audio_path1:
430
- return "You need to upload an audio", None, None
431
-
432
- if not os.path.exists(input_audio_path1):
433
- return "Audio was not properly selected or doesn't exist", None, None
434
-
435
- f0_up_key = int(f0_up_key)
436
- if not f0_min.isdigit():
437
- f0_min = note_to_hz(f0_min)
438
- if f0_min:
439
- print(f"Converted Min pitch: freq - {f0_min}")
440
- else:
441
- f0_min = 50
442
- print("Invalid minimum pitch note. Defaulting to 50hz.")
443
- else:
444
- f0_min = float(f0_min)
445
- if not f0_max.isdigit():
446
- f0_max = note_to_hz(f0_max)
447
- if f0_max:
448
- print(f"Converted Max pitch: freq - {f0_max}")
449
- else:
450
- f0_max = 1100
451
- print("Invalid maximum pitch note. Defaulting to 1100hz.")
452
- else:
453
- f0_max = float(f0_max)
454
-
455
- try:
456
- print(f"Attempting to load {input_audio_path1}...")
457
- audio = load_audio(file=input_audio_path1,
458
- sr=16000,
459
- DoFormant=do_formant,
460
- Quefrency=quefrency,
461
- Timbre=timbre)
462
-
463
- audio_max = np.abs(audio).max() / 0.95
464
- if audio_max > 1:
465
- audio /= audio_max
466
- times = [0, 0, 0]
467
-
468
- if self.hubert_model is None:
469
- self.hubert_model = load_hubert(hubert_model_path, self.config)
470
-
471
- try:
472
- self.if_f0 = self.cpt.get("f0", 1)
473
- except NameError:
474
- message = "Model was not properly selected"
475
- print(message)
476
- return message, None
477
- if file_index and not file_index == "" and isinstance(file_index, str):
478
- file_index = file_index.strip(" ") \
479
- .strip('"') \
480
- .strip("\n") \
481
- .strip('"') \
482
- .strip(" ") \
483
- .replace("trained", "added")
484
- elif file_index2:
485
- file_index = file_index2
486
- else:
487
- file_index = ""
488
-
489
- try:
490
- audio_opt = self.pipeline.pipeline(
491
- self.hubert_model,
492
- self.net_g,
493
- sid,
494
- audio,
495
- input_audio_path1,
496
- times,
497
- f0_up_key,
498
- f0_method,
499
- file_index,
500
- index_rate,
501
- self.if_f0,
502
- filter_radius,
503
- self.tgt_sr,
504
- resample_sr,
505
- rms_mix_rate,
506
- self.version,
507
- protect,
508
- crepe_hop_length,
509
- f0_autotune,
510
- f0_min=f0_min,
511
- f0_max=f0_max
512
- )
513
- except AssertionError:
514
- message = "Mismatching index version detected (v1 with v2, or v2 with v1)."
515
- print(message)
516
- return message, None
517
- except NameError:
518
- message = "RVC libraries are still loading. Please try again in a few seconds."
519
- print(message)
520
- return message, None
521
-
522
- if self.tgt_sr != resample_sr >= 16000:
523
- tgt_sr = resample_sr
524
- else:
525
- tgt_sr = self.tgt_sr
526
- index_info = (
527
- "Index: %s." % file_index
528
- if isinstance(file_index, str) and os.path.exists(file_index)
529
- else "Index not used."
530
- )
531
-
532
- opt_root = os.path.join(os.getcwd(), "output")
533
- os.makedirs(opt_root, exist_ok=True)
534
- output_count = 1
535
-
536
- while True:
537
- opt_filename = f"{os.path.splitext(os.path.basename(input_audio_path1))[0]}{os.path.basename(os.path.dirname(file_index))}{f0_method.capitalize()}_{output_count}.{format1}"
538
- current_output_path = os.path.join(opt_root, opt_filename)
539
- if not os.path.exists(current_output_path):
540
- break
541
- output_count += 1
542
- try:
543
- if format1 in ["wav", "flac"]:
544
- sf.write(
545
- current_output_path,
546
- audio_opt,
547
- self.tgt_sr,
548
- )
549
- else:
550
- with BytesIO() as wavf:
551
- sf.write(
552
- wavf,
553
- audio_opt,
554
- self.tgt_sr,
555
- format="wav"
556
- )
557
- wavf.seek(0, 0)
558
- with open(current_output_path, "wb") as outf:
559
- wav2(wavf, outf, format1)
560
- except:
561
- info = traceback.format_exc()
562
- end_time = time.time()
563
- total_time = end_time - start_time
564
- times.append(total_time)
565
- return (
566
- ("Success.", index_info, times),
567
- (tgt_sr, audio_opt),
568
- current_output_path
569
- )
570
- except:
571
- info = traceback.format_exc()
572
- logger.warn(info)
573
- return (
574
- (info, None, [None, None, None, None]),
575
- (None, None),
576
- None
577
- )