Eempostor commited on
Commit
5fbc13f
·
verified ·
1 Parent(s): 25877a9

Upload infer.py

Browse files
Files changed (1) hide show
  1. lib/infer.py +211 -0
lib/infer.py ADDED
@@ -0,0 +1,211 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import torch
3
+ from multiprocessing import cpu_count
4
+ from lib.modules import VC
5
+ from lib.split_audio import split_silence_nonsilent, adjust_audio_lengths, combine_silence_nonsilent
6
+
7
+ class Configs:
8
+ def __init__(self, device, is_half):
9
+ self.device = device
10
+ self.is_half = is_half
11
+ self.n_cpu = 0
12
+ self.gpu_name = None
13
+ self.gpu_mem = None
14
+ self.x_pad, self.x_query, self.x_center, self.x_max = self.device_config()
15
+
16
+ def device_config(self) -> tuple:
17
+ if torch.cuda.is_available():
18
+ i_device = int(self.device.split(":")[-1])
19
+ self.gpu_name = torch.cuda.get_device_name(i_device)
20
+ #if (
21
+ # ("16" in self.gpu_name and "V100" not in self.gpu_name.upper())
22
+ # or "P40" in self.gpu_name.upper()
23
+ # or "1060" in self.gpu_name
24
+ # or "1070" in self.gpu_name
25
+ # or "1080" in self.gpu_name
26
+ # ):
27
+ # print("16 series/10 series P40 forced single precision")
28
+ # self.is_half = False
29
+ # for config_file in ["32k.json", "40k.json", "48k.json"]:
30
+ # with open(BASE_DIR / "src" / "configs" / config_file, "r") as f:
31
+ # strr = f.read().replace("true", "false")
32
+ # with open(BASE_DIR / "src" / "configs" / config_file, "w") as f:
33
+ # f.write(strr)
34
+ # with open(BASE_DIR / "src" / "trainset_preprocess_pipeline_print.py", "r") as f:
35
+ # strr = f.read().replace("3.7", "3.0")
36
+ # with open(BASE_DIR / "src" / "trainset_preprocess_pipeline_print.py", "w") as f:
37
+ # f.write(strr)
38
+ # else:
39
+ # self.gpu_name = None
40
+ # self.gpu_mem = int(
41
+ # torch.cuda.get_device_properties(i_device).total_memory
42
+ # / 1024
43
+ # / 1024
44
+ # / 1024
45
+ # + 0.4
46
+ # )
47
+ # if self.gpu_mem <= 4:
48
+ # with open(BASE_DIR / "src" / "trainset_preprocess_pipeline_print.py", "r") as f:
49
+ # strr = f.read().replace("3.7", "3.0")
50
+ # with open(BASE_DIR / "src" / "trainset_preprocess_pipeline_print.py", "w") as f:
51
+ # f.write(strr)
52
+ elif torch.backends.mps.is_available():
53
+ print("No supported N-card found, use MPS for inference")
54
+ self.device = "mps"
55
+ else:
56
+ print("No supported N-card found, use CPU for inference")
57
+ self.device = "cpu"
58
+ self.is_half = True
59
+
60
+ if self.n_cpu == 0:
61
+ self.n_cpu = cpu_count()
62
+
63
+ if self.is_half:
64
+ # 6G memory config
65
+ x_pad = 3
66
+ x_query = 10
67
+ x_center = 60
68
+ x_max = 65
69
+ else:
70
+ # 5G memory config
71
+ x_pad = 1
72
+ x_query = 6
73
+ x_center = 38
74
+ x_max = 41
75
+
76
+ if self.gpu_mem != None and self.gpu_mem <= 4:
77
+ x_pad = 1
78
+ x_query = 5
79
+ x_center = 30
80
+ x_max = 32
81
+
82
+ return x_pad, x_query, x_center, x_max
83
+
84
+ def get_model(voice_model):
85
+ model_dir = os.path.join(os.getcwd(), "models", voice_model)
86
+ model_filename, index_filename = None, None
87
+ for file in os.listdir(model_dir):
88
+ ext = os.path.splitext(file)[1]
89
+ if ext == '.pth':
90
+ model_filename = file
91
+ if ext == '.index':
92
+ index_filename = file
93
+
94
+ if model_filename is None:
95
+ print(f'No model file exists in {models_dir}.')
96
+ return None, None
97
+
98
+ return os.path.join(model_dir, model_filename), os.path.join(model_dir, index_filename) if index_filename else ''
99
+
100
+ def infer_audio(
101
+ model_name,
102
+ audio_path,
103
+ f0_change=0,
104
+ f0_method="rmvpe+",
105
+ min_pitch="50",
106
+ max_pitch="1100",
107
+ crepe_hop_length=128,
108
+ index_rate=0.75,
109
+ filter_radius=3,
110
+ rms_mix_rate=0.25,
111
+ protect=0.33,
112
+ split_infer=False,
113
+ min_silence=500,
114
+ silence_threshold=-50,
115
+ seek_step=1,
116
+ keep_silence=100,
117
+ do_formant=False,
118
+ quefrency=0,
119
+ timbre=1,
120
+ f0_autotune=False,
121
+ audio_format="wav",
122
+ resample_sr=0
123
+ ):
124
+ configs = Configs('cuda:0', True)
125
+ vc = VC(configs)
126
+ pth_path, index_path = get_model(model_name)
127
+ vc_data = vc.get_vc(pth_path, protect, 0.5)
128
+
129
+ if split_infer:
130
+ inferred_files = []
131
+ temp_dir = os.path.join(main_dir, "seperate", "temp")
132
+ os.makedirs(temp_dir, exist_ok=True)
133
+ print("Splitting audio to silence and nonsilent segments.")
134
+ silence_files, nonsilent_files = split_silence_nonsilent(audio_path, min_silence, silence_threshold, seek_step, keep_silence)
135
+ print(f"Total silence segments: {len(silence_files)}.\nTotal nonsilent segments: {len(nonsilent_files)}.")
136
+ for i, nonsilent_file in enumerate(nonsilent_files):
137
+ print(f"Inferring nonsilent audio {i+1}")
138
+ inference_info, audio_data, output_path = vc.vc_single(
139
+ 0,
140
+ audio_path,
141
+ f0_up_key,
142
+ f0_method,
143
+ index_path,
144
+ index_path,
145
+ index_rate,
146
+ filter_radius,
147
+ resample_sr,
148
+ rms_mix_rate,
149
+ protect,
150
+ audio_format,
151
+ crepe_hop_length,
152
+ do_formant,
153
+ quefrency,
154
+ timbre,
155
+ f0_min_pitch,
156
+ f0_max_pitch,
157
+ f0_autotune
158
+ )
159
+ if inference_info[0] == "Success.":
160
+ print("Inference ran successfully.")
161
+ print(inference_info[1])
162
+ print("Times:\nnpy: %.2fs f0: %.2fs infer: %.2fs\nTotal time: %.2fs" % (*inference_info[2],))
163
+ else:
164
+ print(f"An error occurred while processing.\n{inference_info[0]}")
165
+ return None
166
+ shutil.move(output_path, temp_dir)
167
+ inferred_files.append(os.path.join(temp_dir, os.path.basename(output_path)))
168
+ print("Adjusting inferred audio lengths.")
169
+ adjusted_inferred_files = adjust_audio_lengths(nonsilent_files, inferred_files)
170
+ print("Combining silence and inferred audios.")
171
+ output_count = 1
172
+ while True:
173
+ output_path = os.path.join(os.getcwd(), "output", f"{os.path.splitext(os.path.basename(audio_path))[0]}{model_name}{f0_method.capitalize()}_{output_count}.{audio_format}")
174
+ if not os.path.exists(output_path):
175
+ break
176
+ output_count += 1
177
+ inferred_audio = combine_silence_nonsilent(silence_files, adjusted_inferred_files, keep_silence, output_path)
178
+ shutil.rmtree(os.path.join(main_dir, "seperate", "temp"))
179
+ else:
180
+ inference_info, audio_data, output_path = vc.vc_single(
181
+ 0,
182
+ audio_path,
183
+ f0_up_key,
184
+ f0_method,
185
+ index_path,
186
+ index_path,
187
+ index_rate,
188
+ filter_radius,
189
+ resample_sr,
190
+ rms_mix_rate,
191
+ protect,
192
+ audio_format,
193
+ crepe_hop_length,
194
+ do_formant,
195
+ quefrency,
196
+ timbre,
197
+ f0_min_pitch,
198
+ f0_max_pitch,
199
+ f0_autotune
200
+ )
201
+ if inference_info[0] == "Success.":
202
+ print("Inference ran successfully.")
203
+ print(inference_info[1])
204
+ print("Times:\nnpy: %.2fs f0: %.2fs infer: %.2fs\nTotal time: %.2fs" % (*inference_info[2],))
205
+ else:
206
+ print(f"An error occurred while processing.\n{inference_info[0]}")
207
+ return None
208
+
209
+ del configs, vc
210
+ gc.collect()
211
+ return output_path