Eempostor commited on
Commit
7620562
1 Parent(s): 5081b18

Delete lib/modules.py

Browse files
Files changed (1) hide show
  1. lib/modules.py +0 -559
lib/modules.py DELETED
@@ -1,559 +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
- audio_opt = self.pipeline.pipeline(
312
- self.hubert_model,
313
- self.net_g,
314
- sid,
315
- audio,
316
- input_audio_path1,
317
- times,
318
- f0_up_key,
319
- f0_method,
320
- file_index,
321
- index_rate,
322
- self.if_f0,
323
- filter_radius,
324
- self.tgt_sr,
325
- resample_sr,
326
- rms_mix_rate,
327
- self.version,
328
- protect,
329
- crepe_hop_length,
330
- f0_autotune,
331
- f0_min=f0_min,
332
- f0_max=f0_max
333
- )
334
-
335
- if self.tgt_sr != resample_sr >= 16000:
336
- tgt_sr = resample_sr
337
- else:
338
- tgt_sr = self.tgt_sr
339
- index_info = (
340
- "Index: %s." % file_index
341
- if isinstance(file_index, str) and os.path.exists(file_index)
342
- else "Index not used."
343
- )
344
- end_time = time.time()
345
- total_time = end_time - start_time
346
- times.append(total_time)
347
- return (
348
- ("Success.", index_info, times),
349
- (tgt_sr, audio_opt),
350
- )
351
- except:
352
- info = traceback.format_exc()
353
- logger.warn(info)
354
- return (
355
- (info, None, [None, None, None, None]),
356
- (None, None)
357
- )
358
-
359
- def vc_single(
360
- self,
361
- sid,
362
- input_audio_path1,
363
- f0_up_key,
364
- f0_method,
365
- file_index,
366
- file_index2,
367
- index_rate,
368
- filter_radius,
369
- resample_sr,
370
- rms_mix_rate,
371
- protect,
372
- format1,
373
- crepe_hop_length,
374
- do_formant,
375
- quefrency,
376
- timbre,
377
- f0_min,
378
- f0_max,
379
- f0_autotune,
380
- hubert_model_path = "assets/hubert/hubert_base.pt"
381
- ):
382
- """
383
- Performs inference with saving
384
-
385
- Parameters:
386
- - sid (int)
387
- - input_audio_path1 (str)
388
- - f0_up_key (int)
389
- - f0_method (str)
390
- - file_index (str)
391
- - file_index2 (str)
392
- - index_rate (float)
393
- - filter_radius (int)
394
- - resample_sr (int)
395
- - rms_mix_rate (float)
396
- - protect (float)
397
- - format1 (str)
398
- - crepe_hop_length (int)
399
- - do_formant (bool)
400
- - quefrency (float)
401
- - timbre (float)
402
- - f0_min (str)
403
- - f0_max (str)
404
- - f0_autotune (bool)
405
- - hubert_model_path (str)
406
-
407
- Returns:
408
- Tuple(Tuple(status, index_info, times), Tuple(sr, data), output_path):
409
- - Tuple(status, index_info, times):
410
- - status (str): either "Success." or an error
411
- - index_info (str): index path if used
412
- - times (list): [npy_time, f0_time, infer_time, total_time]
413
- - Tuple(sr, data): Audio data results.
414
- - output_path (str): Audio results path
415
- """
416
- global total_time
417
- total_time = 0
418
- start_time = time.time()
419
-
420
- if not input_audio_path1:
421
- return "You need to upload an audio", None, None
422
-
423
- if not os.path.exists(input_audio_path1):
424
- return "Audio was not properly selected or doesn't exist", None, None
425
-
426
- f0_up_key = int(f0_up_key)
427
- if not f0_min.isdigit():
428
- f0_min = note_to_hz(f0_min)
429
- if f0_min:
430
- print(f"Converted Min pitch: freq - {f0_min}")
431
- else:
432
- f0_min = 50
433
- print("Invalid minimum pitch note. Defaulting to 50hz.")
434
- else:
435
- f0_min = float(f0_min)
436
- if not f0_max.isdigit():
437
- f0_max = note_to_hz(f0_max)
438
- if f0_max:
439
- print(f"Converted Max pitch: freq - {f0_max}")
440
- else:
441
- f0_max = 1100
442
- print("Invalid maximum pitch note. Defaulting to 1100hz.")
443
- else:
444
- f0_max = float(f0_max)
445
-
446
- try:
447
- print(f"Attempting to load {input_audio_path1}...")
448
- audio = load_audio(file=input_audio_path1,
449
- sr=16000,
450
- DoFormant=do_formant,
451
- Quefrency=quefrency,
452
- Timbre=timbre)
453
-
454
- audio_max = np.abs(audio).max() / 0.95
455
- if audio_max > 1:
456
- audio /= audio_max
457
- times = [0, 0, 0]
458
-
459
- if self.hubert_model is None:
460
- self.hubert_model = load_hubert(hubert_model_path, self.config)
461
-
462
- try:
463
- self.if_f0 = self.cpt.get("f0", 1)
464
- except NameError:
465
- message = "Model was not properly selected"
466
- print(message)
467
- return message, None
468
- if file_index and not file_index == "" and isinstance(file_index, str):
469
- file_index = file_index.strip(" ") \
470
- .strip('"') \
471
- .strip("\n") \
472
- .strip('"') \
473
- .strip(" ") \
474
- .replace("trained", "added")
475
- elif file_index2:
476
- file_index = file_index2
477
- else:
478
- file_index = ""
479
-
480
- audio_opt = self.pipeline.pipeline(
481
- self.hubert_model,
482
- self.net_g,
483
- sid,
484
- audio,
485
- input_audio_path1,
486
- times,
487
- f0_up_key,
488
- f0_method,
489
- file_index,
490
- index_rate,
491
- self.if_f0,
492
- filter_radius,
493
- self.tgt_sr,
494
- resample_sr,
495
- rms_mix_rate,
496
- self.version,
497
- protect,
498
- crepe_hop_length,
499
- f0_autotune,
500
- f0_min=f0_min,
501
- f0_max=f0_max
502
- )
503
-
504
- if self.tgt_sr != resample_sr >= 16000:
505
- tgt_sr = resample_sr
506
- else:
507
- tgt_sr = self.tgt_sr
508
- index_info = (
509
- "Index: %s." % file_index
510
- if isinstance(file_index, str) and os.path.exists(file_index)
511
- else "Index not used."
512
- )
513
-
514
- opt_root = os.path.join(os.getcwd(), "output")
515
- os.makedirs(opt_root, exist_ok=True)
516
- output_count = 1
517
-
518
- while True:
519
- 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}"
520
- current_output_path = os.path.join(opt_root, opt_filename)
521
- if not os.path.exists(current_output_path):
522
- break
523
- output_count += 1
524
- try:
525
- if format1 in ["wav", "flac"]:
526
- sf.write(
527
- current_output_path,
528
- audio_opt,
529
- self.tgt_sr,
530
- )
531
- else:
532
- with BytesIO() as wavf:
533
- sf.write(
534
- wavf,
535
- audio_opt,
536
- self.tgt_sr,
537
- format="wav"
538
- )
539
- wavf.seek(0, 0)
540
- with open(current_output_path, "wb") as outf:
541
- wav2(wavf, outf, format1)
542
- except:
543
- info = traceback.format_exc()
544
- end_time = time.time()
545
- total_time = end_time - start_time
546
- times.append(total_time)
547
- return (
548
- ("Success.", index_info, times),
549
- (tgt_sr, audio_opt),
550
- current_output_path
551
- )
552
- except:
553
- info = traceback.format_exc()
554
- logger.warn(info)
555
- return (
556
- (info, None, [None, None, None, None]),
557
- (None, None),
558
- None
559
- )