Upload folder using huggingface_hub
Browse files- .gitattributes +1 -0
- =0.2.0 +0 -0
- README.md +34 -3
- assets/fcpe/.gitkeep +0 -0
- assets/fcpe/fcpe.pt +3 -0
- assets/hubert/.gitkeep +0 -0
- assets/hubert/hubert_base.pt +3 -0
- assets/rmvpe/.gitkeep +0 -0
- assets/rmvpe/rmvpe.pt +3 -0
- audio_input/.gitkeep +0 -0
- lib/infer.py +221 -0
- lib/infer_libs/audio.py +87 -0
- lib/infer_libs/fcpe.py +873 -0
- lib/infer_libs/infer_pack/attentions.py +414 -0
- lib/infer_libs/infer_pack/commons.py +164 -0
- lib/infer_libs/infer_pack/models.py +1174 -0
- lib/infer_libs/infer_pack/modules.py +517 -0
- lib/infer_libs/infer_pack/transforms.py +207 -0
- lib/infer_libs/rmvpe.py +705 -0
- lib/modules.py +559 -0
- lib/pipeline.py +773 -0
- lib/split_audio.py +91 -0
- stftpitchshift +3 -0
.gitattributes
CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
36 |
+
stftpitchshift filter=lfs diff=lfs merge=lfs -text
|
=0.2.0
ADDED
File without changes
|
README.md
CHANGED
@@ -1,3 +1,34 @@
|
|
1 |
-
|
2 |
-
|
3 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# **Harmonify (RVC No UI Colab)**
|
2 |
+
https://colab.research.google.com/drive/1X8YR4Ruv7zzY8YAMPTfC7hkxqT_d4Q5d
|
3 |
+
|
4 |
+
## **Credits**
|
5 |
+
[Eempostor](https://discordapp.com/users/818050831034613771) - Made everything work together, Notebook creator
|
6 |
+
|
7 |
+
[Applio](https://github.com/IAHispano/Applio-RVC-Fork) by [IAHispano](https://github.com/IAHispano) - The repo this colab is based on
|
8 |
+
|
9 |
+
[CNChTu](https://github.com/CNChTu) - [FCPE](https://github.com/CNChTu/FCPE) F0 method
|
10 |
+
|
11 |
+
[So Vits SVC](https://github.com/svc-develop-team/so-vits-svc) - [FCPE](https://github.com/CNChTu/FCPE) F0 method script
|
12 |
+
|
13 |
+
[ChatGPT](https://chat.openai.com/) - Helper
|
14 |
+
|
15 |
+
[Phind](https://www.phind.com/) - Helper
|
16 |
+
|
17 |
+
If you have any suggestions or problems on this colab, dm [me](https://discordapp.com/users/818050831034613771) on discord.
|
18 |
+
|
19 |
+
## **Changelogs**
|
20 |
+
9/3/2024 | Huge changes
|
21 |
+
- Pitch extraction `fcpe` now uses the `torchfcpe` library. You can still use the previous version with `fcpe_legacy`
|
22 |
+
- `MIN_PITCH` and `MAX_PITCH` now accepts pitch notations
|
23 |
+
- Fixed error when running inference without a GPU (GPU is still recommended as its way faster and more stable)
|
24 |
+
- Fixed error when running `hybrid` with `pm`, `dio`, and `harvest`
|
25 |
+
- Overhaulled the directory structure and some code
|
26 |
+
|
27 |
+
14/1/2024 | Fixes
|
28 |
+
- Fixed `Cannot retrieve the public link of the file` issue while downloading models from google drive
|
29 |
+
|
30 |
+
10/1/2024 | Fixes
|
31 |
+
- Fixed `Cannot retrieve the public link of the file` issue on installation
|
32 |
+
|
33 |
+
12/12/2023 | Small adjustments
|
34 |
+
- Moved `DOWNLOAD` and `SAVE_TO_DRIVE` option on inference cell into a new cell
|
assets/fcpe/.gitkeep
ADDED
File without changes
|
assets/fcpe/fcpe.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:c3a8dd2dbd51baf19ed295006f2ac25dba6dd60adc7ec578ae5fbd94970951da
|
3 |
+
size 69005189
|
assets/hubert/.gitkeep
ADDED
File without changes
|
assets/hubert/hubert_base.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:f54b40fd2802423a5643779c4861af1e9ee9c1564dc9d32f54f20b5ffba7db96
|
3 |
+
size 189507909
|
assets/rmvpe/.gitkeep
ADDED
File without changes
|
assets/rmvpe/rmvpe.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:a5ed4719f59085d1affc5d81354c70828c740584f2d24e782523345a6a278962
|
3 |
+
size 181189687
|
audio_input/.gitkeep
ADDED
File without changes
|
lib/infer.py
ADDED
@@ -0,0 +1,221 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import shutil
|
3 |
+
import gc
|
4 |
+
import torch
|
5 |
+
from multiprocessing import cpu_count
|
6 |
+
from lib.modules import VC
|
7 |
+
from lib.split_audio import split_silence_nonsilent, adjust_audio_lengths, combine_silence_nonsilent
|
8 |
+
|
9 |
+
class Configs:
|
10 |
+
def __init__(self, device, is_half):
|
11 |
+
self.device = device
|
12 |
+
self.is_half = is_half
|
13 |
+
self.n_cpu = 0
|
14 |
+
self.gpu_name = None
|
15 |
+
self.gpu_mem = None
|
16 |
+
self.x_pad, self.x_query, self.x_center, self.x_max = self.device_config()
|
17 |
+
|
18 |
+
def device_config(self) -> tuple:
|
19 |
+
if torch.cuda.is_available():
|
20 |
+
i_device = int(self.device.split(":")[-1])
|
21 |
+
self.gpu_name = torch.cuda.get_device_name(i_device)
|
22 |
+
#if (
|
23 |
+
# ("16" in self.gpu_name and "V100" not in self.gpu_name.upper())
|
24 |
+
# or "P40" in self.gpu_name.upper()
|
25 |
+
# or "1060" in self.gpu_name
|
26 |
+
# or "1070" in self.gpu_name
|
27 |
+
# or "1080" in self.gpu_name
|
28 |
+
# ):
|
29 |
+
# print("16 series/10 series P40 forced single precision")
|
30 |
+
# self.is_half = False
|
31 |
+
# for config_file in ["32k.json", "40k.json", "48k.json"]:
|
32 |
+
# with open(BASE_DIR / "src" / "configs" / config_file, "r") as f:
|
33 |
+
# strr = f.read().replace("true", "false")
|
34 |
+
# with open(BASE_DIR / "src" / "configs" / config_file, "w") as f:
|
35 |
+
# f.write(strr)
|
36 |
+
# with open(BASE_DIR / "src" / "trainset_preprocess_pipeline_print.py", "r") as f:
|
37 |
+
# strr = f.read().replace("3.7", "3.0")
|
38 |
+
# with open(BASE_DIR / "src" / "trainset_preprocess_pipeline_print.py", "w") as f:
|
39 |
+
# f.write(strr)
|
40 |
+
# else:
|
41 |
+
# self.gpu_name = None
|
42 |
+
# self.gpu_mem = int(
|
43 |
+
# torch.cuda.get_device_properties(i_device).total_memory
|
44 |
+
# / 1024
|
45 |
+
# / 1024
|
46 |
+
# / 1024
|
47 |
+
# + 0.4
|
48 |
+
# )
|
49 |
+
# if self.gpu_mem <= 4:
|
50 |
+
# with open(BASE_DIR / "src" / "trainset_preprocess_pipeline_print.py", "r") as f:
|
51 |
+
# strr = f.read().replace("3.7", "3.0")
|
52 |
+
# with open(BASE_DIR / "src" / "trainset_preprocess_pipeline_print.py", "w") as f:
|
53 |
+
# f.write(strr)
|
54 |
+
elif torch.backends.mps.is_available():
|
55 |
+
print("No supported N-card found, use MPS for inference")
|
56 |
+
self.device = "mps"
|
57 |
+
else:
|
58 |
+
print("No supported N-card found, use CPU for inference")
|
59 |
+
self.device = "cpu"
|
60 |
+
|
61 |
+
if self.n_cpu == 0:
|
62 |
+
self.n_cpu = cpu_count()
|
63 |
+
|
64 |
+
if self.is_half:
|
65 |
+
# 6G memory config
|
66 |
+
x_pad = 3
|
67 |
+
x_query = 10
|
68 |
+
x_center = 60
|
69 |
+
x_max = 65
|
70 |
+
else:
|
71 |
+
# 5G memory config
|
72 |
+
x_pad = 1
|
73 |
+
x_query = 6
|
74 |
+
x_center = 38
|
75 |
+
x_max = 41
|
76 |
+
|
77 |
+
if self.gpu_mem != None and self.gpu_mem <= 4:
|
78 |
+
x_pad = 1
|
79 |
+
x_query = 5
|
80 |
+
x_center = 30
|
81 |
+
x_max = 32
|
82 |
+
|
83 |
+
return x_pad, x_query, x_center, x_max
|
84 |
+
|
85 |
+
def get_model(voice_model):
|
86 |
+
model_dir = os.path.join(os.getcwd(), "models", voice_model)
|
87 |
+
model_filename, index_filename = None, None
|
88 |
+
for file in os.listdir(model_dir):
|
89 |
+
ext = os.path.splitext(file)[1]
|
90 |
+
if ext == '.pth':
|
91 |
+
model_filename = file
|
92 |
+
if ext == '.index':
|
93 |
+
index_filename = file
|
94 |
+
|
95 |
+
if model_filename is None:
|
96 |
+
print(f'No model file exists in {models_dir}.')
|
97 |
+
return None, None
|
98 |
+
|
99 |
+
return os.path.join(model_dir, model_filename), os.path.join(model_dir, index_filename) if index_filename else ''
|
100 |
+
|
101 |
+
def infer_audio(
|
102 |
+
model_name,
|
103 |
+
audio_path,
|
104 |
+
f0_change=0,
|
105 |
+
f0_method="rmvpe+",
|
106 |
+
min_pitch="50",
|
107 |
+
max_pitch="1100",
|
108 |
+
crepe_hop_length=128,
|
109 |
+
index_rate=0.75,
|
110 |
+
filter_radius=3,
|
111 |
+
rms_mix_rate=0.25,
|
112 |
+
protect=0.33,
|
113 |
+
split_infer=False,
|
114 |
+
min_silence=500,
|
115 |
+
silence_threshold=-50,
|
116 |
+
seek_step=1,
|
117 |
+
keep_silence=100,
|
118 |
+
do_formant=False,
|
119 |
+
quefrency=0,
|
120 |
+
timbre=1,
|
121 |
+
f0_autotune=False,
|
122 |
+
audio_format="wav",
|
123 |
+
resample_sr=0,
|
124 |
+
hubert_model_path="assets/hubert/hubert_base.pt",
|
125 |
+
rmvpe_model_path="assets/rmvpe/rmvpe.pt",
|
126 |
+
fcpe_model_path="assets/fcpe/fcpe.pt"
|
127 |
+
):
|
128 |
+
os.environ["rmvpe_model_path"] = rmvpe_model_path
|
129 |
+
os.environ["fcpe_model_path"] = fcpe_model_path
|
130 |
+
configs = Configs('cuda:0', True)
|
131 |
+
vc = VC(configs)
|
132 |
+
pth_path, index_path = get_model(model_name)
|
133 |
+
vc_data = vc.get_vc(pth_path, protect, 0.5)
|
134 |
+
|
135 |
+
if split_infer:
|
136 |
+
inferred_files = []
|
137 |
+
temp_dir = os.path.join(os.getcwd(), "seperate", "temp")
|
138 |
+
os.makedirs(temp_dir, exist_ok=True)
|
139 |
+
print("Splitting audio to silence and nonsilent segments.")
|
140 |
+
silence_files, nonsilent_files = split_silence_nonsilent(audio_path, min_silence, silence_threshold, seek_step, keep_silence)
|
141 |
+
print(f"Total silence segments: {len(silence_files)}.\nTotal nonsilent segments: {len(nonsilent_files)}.")
|
142 |
+
for i, nonsilent_file in enumerate(nonsilent_files):
|
143 |
+
print(f"Inferring nonsilent audio {i+1}")
|
144 |
+
inference_info, audio_data, output_path = vc.vc_single(
|
145 |
+
0,
|
146 |
+
nonsilent_file,
|
147 |
+
f0_change,
|
148 |
+
f0_method,
|
149 |
+
index_path,
|
150 |
+
index_path,
|
151 |
+
index_rate,
|
152 |
+
filter_radius,
|
153 |
+
resample_sr,
|
154 |
+
rms_mix_rate,
|
155 |
+
protect,
|
156 |
+
audio_format,
|
157 |
+
crepe_hop_length,
|
158 |
+
do_formant,
|
159 |
+
quefrency,
|
160 |
+
timbre,
|
161 |
+
min_pitch,
|
162 |
+
max_pitch,
|
163 |
+
f0_autotune,
|
164 |
+
hubert_model_path
|
165 |
+
)
|
166 |
+
if inference_info[0] == "Success.":
|
167 |
+
print("Inference ran successfully.")
|
168 |
+
print(inference_info[1])
|
169 |
+
print("Times:\nnpy: %.2fs f0: %.2fs infer: %.2fs\nTotal time: %.2fs" % (*inference_info[2],))
|
170 |
+
else:
|
171 |
+
print(f"An error occurred while processing.\n{inference_info[0]}")
|
172 |
+
return None
|
173 |
+
inferred_files.append(output_path)
|
174 |
+
print("Adjusting inferred audio lengths.")
|
175 |
+
adjusted_inferred_files = adjust_audio_lengths(nonsilent_files, inferred_files)
|
176 |
+
print("Combining silence and inferred audios.")
|
177 |
+
output_count = 1
|
178 |
+
while True:
|
179 |
+
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}")
|
180 |
+
if not os.path.exists(output_path):
|
181 |
+
break
|
182 |
+
output_count += 1
|
183 |
+
output_path = combine_silence_nonsilent(silence_files, adjusted_inferred_files, keep_silence, output_path)
|
184 |
+
[shutil.move(inferred_file, temp_dir) for inferred_file in inferred_files]
|
185 |
+
shutil.rmtree(temp_dir)
|
186 |
+
else:
|
187 |
+
inference_info, audio_data, output_path = vc.vc_single(
|
188 |
+
0,
|
189 |
+
audio_path,
|
190 |
+
f0_change,
|
191 |
+
f0_method,
|
192 |
+
index_path,
|
193 |
+
index_path,
|
194 |
+
index_rate,
|
195 |
+
filter_radius,
|
196 |
+
resample_sr,
|
197 |
+
rms_mix_rate,
|
198 |
+
protect,
|
199 |
+
audio_format,
|
200 |
+
crepe_hop_length,
|
201 |
+
do_formant,
|
202 |
+
quefrency,
|
203 |
+
timbre,
|
204 |
+
min_pitch,
|
205 |
+
max_pitch,
|
206 |
+
f0_autotune,
|
207 |
+
hubert_model_path
|
208 |
+
)
|
209 |
+
if inference_info[0] == "Success.":
|
210 |
+
print("Inference ran successfully.")
|
211 |
+
print(inference_info[1])
|
212 |
+
print("Times:\nnpy: %.2fs f0: %.2fs infer: %.2fs\nTotal time: %.2fs" % (*inference_info[2],))
|
213 |
+
else:
|
214 |
+
print(f"An error occurred while processing.\n{inference_info[0]}")
|
215 |
+
del configs, vc
|
216 |
+
gc.collect()
|
217 |
+
return inference_info[0]
|
218 |
+
|
219 |
+
del configs, vc
|
220 |
+
gc.collect()
|
221 |
+
return output_path
|
lib/infer_libs/audio.py
ADDED
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
import av
|
3 |
+
import ffmpeg
|
4 |
+
import os
|
5 |
+
import traceback
|
6 |
+
import sys
|
7 |
+
import subprocess
|
8 |
+
|
9 |
+
platform_stft_mapping = {
|
10 |
+
'linux': os.path.join(os.getcwd(), 'stftpitchshift'),
|
11 |
+
'darwin': os.path.join(os.getcwd(), 'stftpitchshift'),
|
12 |
+
'win32': os.path.join(os.getcwd(), 'stftpitchshift.exe'),
|
13 |
+
}
|
14 |
+
|
15 |
+
stft = platform_stft_mapping.get(sys.platform)
|
16 |
+
|
17 |
+
def wav2(i, o, format):
|
18 |
+
inp = av.open(i, 'rb')
|
19 |
+
if format == "m4a": format = "mp4"
|
20 |
+
out = av.open(o, 'wb', format=format)
|
21 |
+
if format == "ogg": format = "libvorbis"
|
22 |
+
if format == "mp4": format = "aac"
|
23 |
+
|
24 |
+
ostream = out.add_stream(format)
|
25 |
+
|
26 |
+
for frame in inp.decode(audio=0):
|
27 |
+
for p in ostream.encode(frame): out.mux(p)
|
28 |
+
|
29 |
+
for p in ostream.encode(None): out.mux(p)
|
30 |
+
|
31 |
+
out.close()
|
32 |
+
inp.close()
|
33 |
+
|
34 |
+
def load_audio(file, sr, DoFormant=False, Quefrency=1.0, Timbre=1.0):
|
35 |
+
formanted = False
|
36 |
+
file = file.strip(' \n"')
|
37 |
+
if not os.path.exists(file):
|
38 |
+
raise RuntimeError(
|
39 |
+
"Wrong audio path, that does not exist."
|
40 |
+
)
|
41 |
+
|
42 |
+
try:
|
43 |
+
if DoFormant:
|
44 |
+
print("Starting formant shift. Please wait as this process takes a while.")
|
45 |
+
formanted_file = f"{os.path.splitext(os.path.basename(file))[0]}_formanted{os.path.splitext(os.path.basename(file))[1]}"
|
46 |
+
command = (
|
47 |
+
f'{stft} -i "{file}" -q "{Quefrency}" '
|
48 |
+
f'-t "{Timbre}" -o "{formanted_file}"'
|
49 |
+
)
|
50 |
+
subprocess.run(command, shell=True)
|
51 |
+
file = formanted_file
|
52 |
+
print(f"Formanted {file}\n")
|
53 |
+
|
54 |
+
# https://github.com/openai/whisper/blob/main/whisper/audio.py#L26
|
55 |
+
# This launches a subprocess to decode audio while down-mixing and resampling as necessary.
|
56 |
+
# Requires the ffmpeg CLI and `ffmpeg-python` package to be installed.
|
57 |
+
file = (
|
58 |
+
file.strip(" ").strip('"').strip("\n").strip('"').strip(" ")
|
59 |
+
) # Prevent small white copy path head and tail with spaces and " and return
|
60 |
+
out, _ = (
|
61 |
+
ffmpeg.input(file, threads=0)
|
62 |
+
.output("-", format="f32le", acodec="pcm_f32le", ac=1, ar=sr)
|
63 |
+
.run(cmd=["ffmpeg", "-nostdin"], capture_stdout=True, capture_stderr=True)
|
64 |
+
)
|
65 |
+
|
66 |
+
return np.frombuffer(out, np.float32).flatten()
|
67 |
+
|
68 |
+
except Exception as e:
|
69 |
+
raise RuntimeError(f"Failed to load audio: {e}")
|
70 |
+
|
71 |
+
def check_audio_duration(file):
|
72 |
+
try:
|
73 |
+
file = file.strip(" ").strip('"').strip("\n").strip('"').strip(" ")
|
74 |
+
|
75 |
+
probe = ffmpeg.probe(file)
|
76 |
+
|
77 |
+
duration = float(probe['streams'][0]['duration'])
|
78 |
+
|
79 |
+
if duration < 0.76:
|
80 |
+
print(
|
81 |
+
f"Audio file, {file.split('/')[-1]}, under ~0.76s detected - file is too short. Target at least 1-2s for best results."
|
82 |
+
)
|
83 |
+
return False
|
84 |
+
|
85 |
+
return True
|
86 |
+
except Exception as e:
|
87 |
+
raise RuntimeError(f"Failed to check audio duration: {e}")
|
lib/infer_libs/fcpe.py
ADDED
@@ -0,0 +1,873 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import Union
|
2 |
+
|
3 |
+
import torch.nn.functional as F
|
4 |
+
import numpy as np
|
5 |
+
import torch
|
6 |
+
import torch.nn as nn
|
7 |
+
from torch.nn.utils import weight_norm
|
8 |
+
from torchaudio.transforms import Resample
|
9 |
+
import os
|
10 |
+
import librosa
|
11 |
+
import soundfile as sf
|
12 |
+
import torch.utils.data
|
13 |
+
from librosa.filters import mel as librosa_mel_fn
|
14 |
+
import math
|
15 |
+
from functools import partial
|
16 |
+
|
17 |
+
from einops import rearrange, repeat
|
18 |
+
from local_attention import LocalAttention
|
19 |
+
from torch import nn
|
20 |
+
|
21 |
+
os.environ["LRU_CACHE_CAPACITY"] = "3"
|
22 |
+
|
23 |
+
def load_wav_to_torch(full_path, target_sr=None, return_empty_on_exception=False):
|
24 |
+
sampling_rate = None
|
25 |
+
try:
|
26 |
+
data, sampling_rate = sf.read(full_path, always_2d=True)# than soundfile.
|
27 |
+
except Exception as ex:
|
28 |
+
print(f"'{full_path}' failed to load.\nException:")
|
29 |
+
print(ex)
|
30 |
+
if return_empty_on_exception:
|
31 |
+
return [], sampling_rate or target_sr or 48000
|
32 |
+
else:
|
33 |
+
raise Exception(ex)
|
34 |
+
|
35 |
+
if len(data.shape) > 1:
|
36 |
+
data = data[:, 0]
|
37 |
+
assert len(data) > 2# check duration of audio file is > 2 samples (because otherwise the slice operation was on the wrong dimension)
|
38 |
+
|
39 |
+
if np.issubdtype(data.dtype, np.integer): # if audio data is type int
|
40 |
+
max_mag = -np.iinfo(data.dtype).min # maximum magnitude = min possible value of intXX
|
41 |
+
else: # if audio data is type fp32
|
42 |
+
max_mag = max(np.amax(data), -np.amin(data))
|
43 |
+
max_mag = (2**31)+1 if max_mag > (2**15) else ((2**15)+1 if max_mag > 1.01 else 1.0) # data should be either 16-bit INT, 32-bit INT or [-1 to 1] float32
|
44 |
+
|
45 |
+
data = torch.FloatTensor(data.astype(np.float32))/max_mag
|
46 |
+
|
47 |
+
if (torch.isinf(data) | torch.isnan(data)).any() and return_empty_on_exception:# resample will crash with inf/NaN inputs. return_empty_on_exception will return empty arr instead of except
|
48 |
+
return [], sampling_rate or target_sr or 48000
|
49 |
+
if target_sr is not None and sampling_rate != target_sr:
|
50 |
+
data = torch.from_numpy(librosa.core.resample(data.numpy(), orig_sr=sampling_rate, target_sr=target_sr))
|
51 |
+
sampling_rate = target_sr
|
52 |
+
|
53 |
+
return data, sampling_rate
|
54 |
+
|
55 |
+
def dynamic_range_compression(x, C=1, clip_val=1e-5):
|
56 |
+
return np.log(np.clip(x, a_min=clip_val, a_max=None) * C)
|
57 |
+
|
58 |
+
def dynamic_range_decompression(x, C=1):
|
59 |
+
return np.exp(x) / C
|
60 |
+
|
61 |
+
def dynamic_range_compression_torch(x, C=1, clip_val=1e-5):
|
62 |
+
return torch.log(torch.clamp(x, min=clip_val) * C)
|
63 |
+
|
64 |
+
def dynamic_range_decompression_torch(x, C=1):
|
65 |
+
return torch.exp(x) / C
|
66 |
+
|
67 |
+
class STFT():
|
68 |
+
def __init__(self, sr=22050, n_mels=80, n_fft=1024, win_size=1024, hop_length=256, fmin=20, fmax=11025, clip_val=1e-5):
|
69 |
+
self.target_sr = sr
|
70 |
+
|
71 |
+
self.n_mels = n_mels
|
72 |
+
self.n_fft = n_fft
|
73 |
+
self.win_size = win_size
|
74 |
+
self.hop_length = hop_length
|
75 |
+
self.fmin = fmin
|
76 |
+
self.fmax = fmax
|
77 |
+
self.clip_val = clip_val
|
78 |
+
self.mel_basis = {}
|
79 |
+
self.hann_window = {}
|
80 |
+
|
81 |
+
def get_mel(self, y, keyshift=0, speed=1, center=False, train=False):
|
82 |
+
sampling_rate = self.target_sr
|
83 |
+
n_mels = self.n_mels
|
84 |
+
n_fft = self.n_fft
|
85 |
+
win_size = self.win_size
|
86 |
+
hop_length = self.hop_length
|
87 |
+
fmin = self.fmin
|
88 |
+
fmax = self.fmax
|
89 |
+
clip_val = self.clip_val
|
90 |
+
|
91 |
+
factor = 2 ** (keyshift / 12)
|
92 |
+
n_fft_new = int(np.round(n_fft * factor))
|
93 |
+
win_size_new = int(np.round(win_size * factor))
|
94 |
+
hop_length_new = int(np.round(hop_length * speed))
|
95 |
+
if not train:
|
96 |
+
mel_basis = self.mel_basis
|
97 |
+
hann_window = self.hann_window
|
98 |
+
else:
|
99 |
+
mel_basis = {}
|
100 |
+
hann_window = {}
|
101 |
+
|
102 |
+
if torch.min(y) < -1.:
|
103 |
+
print('min value is ', torch.min(y))
|
104 |
+
if torch.max(y) > 1.:
|
105 |
+
print('max value is ', torch.max(y))
|
106 |
+
|
107 |
+
mel_basis_key = str(fmax)+'_'+str(y.device)
|
108 |
+
if mel_basis_key not in mel_basis:
|
109 |
+
mel = librosa_mel_fn(sr=sampling_rate, n_fft=n_fft, n_mels=n_mels, fmin=fmin, fmax=fmax)
|
110 |
+
mel_basis[mel_basis_key] = torch.from_numpy(mel).float().to(y.device)
|
111 |
+
|
112 |
+
keyshift_key = str(keyshift)+'_'+str(y.device)
|
113 |
+
if keyshift_key not in hann_window:
|
114 |
+
hann_window[keyshift_key] = torch.hann_window(win_size_new).to(y.device)
|
115 |
+
|
116 |
+
pad_left = (win_size_new - hop_length_new) //2
|
117 |
+
pad_right = max((win_size_new- hop_length_new + 1) //2, win_size_new - y.size(-1) - pad_left)
|
118 |
+
if pad_right < y.size(-1):
|
119 |
+
mode = 'reflect'
|
120 |
+
else:
|
121 |
+
mode = 'constant'
|
122 |
+
y = torch.nn.functional.pad(y.unsqueeze(1), (pad_left, pad_right), mode = mode)
|
123 |
+
y = y.squeeze(1)
|
124 |
+
|
125 |
+
spec = torch.stft(y, n_fft_new, hop_length=hop_length_new, win_length=win_size_new, window=hann_window[keyshift_key],
|
126 |
+
center=center, pad_mode='reflect', normalized=False, onesided=True, return_complex=True)
|
127 |
+
spec = torch.sqrt(spec.real.pow(2) + spec.imag.pow(2) + (1e-9))
|
128 |
+
if keyshift != 0:
|
129 |
+
size = n_fft // 2 + 1
|
130 |
+
resize = spec.size(1)
|
131 |
+
if resize < size:
|
132 |
+
spec = F.pad(spec, (0, 0, 0, size-resize))
|
133 |
+
spec = spec[:, :size, :] * win_size / win_size_new
|
134 |
+
spec = torch.matmul(mel_basis[mel_basis_key], spec)
|
135 |
+
spec = dynamic_range_compression_torch(spec, clip_val=clip_val)
|
136 |
+
return spec
|
137 |
+
|
138 |
+
def __call__(self, audiopath):
|
139 |
+
audio, sr = load_wav_to_torch(audiopath, target_sr=self.target_sr)
|
140 |
+
spect = self.get_mel(audio.unsqueeze(0)).squeeze(0)
|
141 |
+
return spect
|
142 |
+
|
143 |
+
stft = STFT()
|
144 |
+
|
145 |
+
#import fast_transformers.causal_product.causal_product_cuda
|
146 |
+
|
147 |
+
def softmax_kernel(data, *, projection_matrix, is_query, normalize_data=True, eps=1e-4, device = None):
|
148 |
+
b, h, *_ = data.shape
|
149 |
+
# (batch size, head, length, model_dim)
|
150 |
+
|
151 |
+
# normalize model dim
|
152 |
+
data_normalizer = (data.shape[-1] ** -0.25) if normalize_data else 1.
|
153 |
+
|
154 |
+
# what is ration?, projection_matrix.shape[0] --> 266
|
155 |
+
|
156 |
+
ratio = (projection_matrix.shape[0] ** -0.5)
|
157 |
+
|
158 |
+
projection = repeat(projection_matrix, 'j d -> b h j d', b = b, h = h)
|
159 |
+
projection = projection.type_as(data)
|
160 |
+
|
161 |
+
#data_dash = w^T x
|
162 |
+
data_dash = torch.einsum('...id,...jd->...ij', (data_normalizer * data), projection)
|
163 |
+
|
164 |
+
|
165 |
+
# diag_data = D**2
|
166 |
+
diag_data = data ** 2
|
167 |
+
diag_data = torch.sum(diag_data, dim=-1)
|
168 |
+
diag_data = (diag_data / 2.0) * (data_normalizer ** 2)
|
169 |
+
diag_data = diag_data.unsqueeze(dim=-1)
|
170 |
+
|
171 |
+
#print ()
|
172 |
+
if is_query:
|
173 |
+
data_dash = ratio * (
|
174 |
+
torch.exp(data_dash - diag_data -
|
175 |
+
torch.max(data_dash, dim=-1, keepdim=True).values) + eps)
|
176 |
+
else:
|
177 |
+
data_dash = ratio * (
|
178 |
+
torch.exp(data_dash - diag_data + eps))#- torch.max(data_dash)) + eps)
|
179 |
+
|
180 |
+
return data_dash.type_as(data)
|
181 |
+
|
182 |
+
def orthogonal_matrix_chunk(cols, qr_uniform_q = False, device = None):
|
183 |
+
unstructured_block = torch.randn((cols, cols), device = device)
|
184 |
+
q, r = torch.linalg.qr(unstructured_block.cpu(), mode='reduced')
|
185 |
+
q, r = map(lambda t: t.to(device), (q, r))
|
186 |
+
|
187 |
+
# proposed by @Parskatt
|
188 |
+
# to make sure Q is uniform https://arxiv.org/pdf/math-ph/0609050.pdf
|
189 |
+
if qr_uniform_q:
|
190 |
+
d = torch.diag(r, 0)
|
191 |
+
q *= d.sign()
|
192 |
+
return q.t()
|
193 |
+
def exists(val):
|
194 |
+
return val is not None
|
195 |
+
|
196 |
+
def empty(tensor):
|
197 |
+
return tensor.numel() == 0
|
198 |
+
|
199 |
+
def default(val, d):
|
200 |
+
return val if exists(val) else d
|
201 |
+
|
202 |
+
def cast_tuple(val):
|
203 |
+
return (val,) if not isinstance(val, tuple) else val
|
204 |
+
|
205 |
+
class PCmer(nn.Module):
|
206 |
+
"""The encoder that is used in the Transformer model."""
|
207 |
+
|
208 |
+
def __init__(self,
|
209 |
+
num_layers,
|
210 |
+
num_heads,
|
211 |
+
dim_model,
|
212 |
+
dim_keys,
|
213 |
+
dim_values,
|
214 |
+
residual_dropout,
|
215 |
+
attention_dropout):
|
216 |
+
super().__init__()
|
217 |
+
self.num_layers = num_layers
|
218 |
+
self.num_heads = num_heads
|
219 |
+
self.dim_model = dim_model
|
220 |
+
self.dim_values = dim_values
|
221 |
+
self.dim_keys = dim_keys
|
222 |
+
self.residual_dropout = residual_dropout
|
223 |
+
self.attention_dropout = attention_dropout
|
224 |
+
|
225 |
+
self._layers = nn.ModuleList([_EncoderLayer(self) for _ in range(num_layers)])
|
226 |
+
|
227 |
+
# METHODS ########################################################################################################
|
228 |
+
|
229 |
+
def forward(self, phone, mask=None):
|
230 |
+
|
231 |
+
# apply all layers to the input
|
232 |
+
for (i, layer) in enumerate(self._layers):
|
233 |
+
phone = layer(phone, mask)
|
234 |
+
# provide the final sequence
|
235 |
+
return phone
|
236 |
+
|
237 |
+
|
238 |
+
# ==================================================================================================================== #
|
239 |
+
# CLASS _ E N C O D E R L A Y E R #
|
240 |
+
# ==================================================================================================================== #
|
241 |
+
|
242 |
+
|
243 |
+
class _EncoderLayer(nn.Module):
|
244 |
+
"""One layer of the encoder.
|
245 |
+
|
246 |
+
Attributes:
|
247 |
+
attn: (:class:`mha.MultiHeadAttention`): The attention mechanism that is used to read the input sequence.
|
248 |
+
feed_forward (:class:`ffl.FeedForwardLayer`): The feed-forward layer on top of the attention mechanism.
|
249 |
+
"""
|
250 |
+
|
251 |
+
def __init__(self, parent: PCmer):
|
252 |
+
"""Creates a new instance of ``_EncoderLayer``.
|
253 |
+
|
254 |
+
Args:
|
255 |
+
parent (Encoder): The encoder that the layers is created for.
|
256 |
+
"""
|
257 |
+
super().__init__()
|
258 |
+
|
259 |
+
|
260 |
+
self.conformer = ConformerConvModule(parent.dim_model)
|
261 |
+
self.norm = nn.LayerNorm(parent.dim_model)
|
262 |
+
self.dropout = nn.Dropout(parent.residual_dropout)
|
263 |
+
|
264 |
+
# selfatt -> fastatt: performer!
|
265 |
+
self.attn = SelfAttention(dim = parent.dim_model,
|
266 |
+
heads = parent.num_heads,
|
267 |
+
causal = False)
|
268 |
+
|
269 |
+
# METHODS ########################################################################################################
|
270 |
+
|
271 |
+
def forward(self, phone, mask=None):
|
272 |
+
|
273 |
+
# compute attention sub-layer
|
274 |
+
phone = phone + (self.attn(self.norm(phone), mask=mask))
|
275 |
+
|
276 |
+
phone = phone + (self.conformer(phone))
|
277 |
+
|
278 |
+
return phone
|
279 |
+
|
280 |
+
def calc_same_padding(kernel_size):
|
281 |
+
pad = kernel_size // 2
|
282 |
+
return (pad, pad - (kernel_size + 1) % 2)
|
283 |
+
|
284 |
+
# helper classes
|
285 |
+
|
286 |
+
class Swish(nn.Module):
|
287 |
+
def forward(self, x):
|
288 |
+
return x * x.sigmoid()
|
289 |
+
|
290 |
+
class Transpose(nn.Module):
|
291 |
+
def __init__(self, dims):
|
292 |
+
super().__init__()
|
293 |
+
assert len(dims) == 2, 'dims must be a tuple of two dimensions'
|
294 |
+
self.dims = dims
|
295 |
+
|
296 |
+
def forward(self, x):
|
297 |
+
return x.transpose(*self.dims)
|
298 |
+
|
299 |
+
class GLU(nn.Module):
|
300 |
+
def __init__(self, dim):
|
301 |
+
super().__init__()
|
302 |
+
self.dim = dim
|
303 |
+
|
304 |
+
def forward(self, x):
|
305 |
+
out, gate = x.chunk(2, dim=self.dim)
|
306 |
+
return out * gate.sigmoid()
|
307 |
+
|
308 |
+
class DepthWiseConv1d(nn.Module):
|
309 |
+
def __init__(self, chan_in, chan_out, kernel_size, padding):
|
310 |
+
super().__init__()
|
311 |
+
self.padding = padding
|
312 |
+
self.conv = nn.Conv1d(chan_in, chan_out, kernel_size, groups = chan_in)
|
313 |
+
|
314 |
+
def forward(self, x):
|
315 |
+
x = F.pad(x, self.padding)
|
316 |
+
return self.conv(x)
|
317 |
+
|
318 |
+
class ConformerConvModule(nn.Module):
|
319 |
+
def __init__(
|
320 |
+
self,
|
321 |
+
dim,
|
322 |
+
causal = False,
|
323 |
+
expansion_factor = 2,
|
324 |
+
kernel_size = 31,
|
325 |
+
dropout = 0.):
|
326 |
+
super().__init__()
|
327 |
+
|
328 |
+
inner_dim = dim * expansion_factor
|
329 |
+
padding = calc_same_padding(kernel_size) if not causal else (kernel_size - 1, 0)
|
330 |
+
|
331 |
+
self.net = nn.Sequential(
|
332 |
+
nn.LayerNorm(dim),
|
333 |
+
Transpose((1, 2)),
|
334 |
+
nn.Conv1d(dim, inner_dim * 2, 1),
|
335 |
+
GLU(dim=1),
|
336 |
+
DepthWiseConv1d(inner_dim, inner_dim, kernel_size = kernel_size, padding = padding),
|
337 |
+
#nn.BatchNorm1d(inner_dim) if not causal else nn.Identity(),
|
338 |
+
Swish(),
|
339 |
+
nn.Conv1d(inner_dim, dim, 1),
|
340 |
+
Transpose((1, 2)),
|
341 |
+
nn.Dropout(dropout)
|
342 |
+
)
|
343 |
+
|
344 |
+
def forward(self, x):
|
345 |
+
return self.net(x)
|
346 |
+
|
347 |
+
def linear_attention(q, k, v):
|
348 |
+
if v is None:
|
349 |
+
#print (k.size(), q.size())
|
350 |
+
out = torch.einsum('...ed,...nd->...ne', k, q)
|
351 |
+
return out
|
352 |
+
|
353 |
+
else:
|
354 |
+
k_cumsum = k.sum(dim = -2)
|
355 |
+
#k_cumsum = k.sum(dim = -2)
|
356 |
+
D_inv = 1. / (torch.einsum('...nd,...d->...n', q, k_cumsum.type_as(q)) + 1e-8)
|
357 |
+
|
358 |
+
context = torch.einsum('...nd,...ne->...de', k, v)
|
359 |
+
#print ("TRUEEE: ", context.size(), q.size(), D_inv.size())
|
360 |
+
out = torch.einsum('...de,...nd,...n->...ne', context, q, D_inv)
|
361 |
+
return out
|
362 |
+
|
363 |
+
def gaussian_orthogonal_random_matrix(nb_rows, nb_columns, scaling = 0, qr_uniform_q = False, device = None):
|
364 |
+
nb_full_blocks = int(nb_rows / nb_columns)
|
365 |
+
#print (nb_full_blocks)
|
366 |
+
block_list = []
|
367 |
+
|
368 |
+
for _ in range(nb_full_blocks):
|
369 |
+
q = orthogonal_matrix_chunk(nb_columns, qr_uniform_q = qr_uniform_q, device = device)
|
370 |
+
block_list.append(q)
|
371 |
+
# block_list[n] is a orthogonal matrix ... (model_dim * model_dim)
|
372 |
+
#print (block_list[0].size(), torch.einsum('...nd,...nd->...n', block_list[0], torch.roll(block_list[0],1,1)))
|
373 |
+
#print (nb_rows, nb_full_blocks, nb_columns)
|
374 |
+
remaining_rows = nb_rows - nb_full_blocks * nb_columns
|
375 |
+
#print (remaining_rows)
|
376 |
+
if remaining_rows > 0:
|
377 |
+
q = orthogonal_matrix_chunk(nb_columns, qr_uniform_q = qr_uniform_q, device = device)
|
378 |
+
#print (q[:remaining_rows].size())
|
379 |
+
block_list.append(q[:remaining_rows])
|
380 |
+
|
381 |
+
final_matrix = torch.cat(block_list)
|
382 |
+
|
383 |
+
if scaling == 0:
|
384 |
+
multiplier = torch.randn((nb_rows, nb_columns), device = device).norm(dim = 1)
|
385 |
+
elif scaling == 1:
|
386 |
+
multiplier = math.sqrt((float(nb_columns))) * torch.ones((nb_rows,), device = device)
|
387 |
+
else:
|
388 |
+
raise ValueError(f'Invalid scaling {scaling}')
|
389 |
+
|
390 |
+
return torch.diag(multiplier) @ final_matrix
|
391 |
+
|
392 |
+
class FastAttention(nn.Module):
|
393 |
+
def __init__(self, dim_heads, nb_features = None, ortho_scaling = 0, causal = False, generalized_attention = False, kernel_fn = nn.ReLU(), qr_uniform_q = False, no_projection = False):
|
394 |
+
super().__init__()
|
395 |
+
nb_features = default(nb_features, int(dim_heads * math.log(dim_heads)))
|
396 |
+
|
397 |
+
self.dim_heads = dim_heads
|
398 |
+
self.nb_features = nb_features
|
399 |
+
self.ortho_scaling = ortho_scaling
|
400 |
+
|
401 |
+
self.create_projection = partial(gaussian_orthogonal_random_matrix, nb_rows = self.nb_features, nb_columns = dim_heads, scaling = ortho_scaling, qr_uniform_q = qr_uniform_q)
|
402 |
+
projection_matrix = self.create_projection()
|
403 |
+
self.register_buffer('projection_matrix', projection_matrix)
|
404 |
+
|
405 |
+
self.generalized_attention = generalized_attention
|
406 |
+
self.kernel_fn = kernel_fn
|
407 |
+
|
408 |
+
# if this is turned on, no projection will be used
|
409 |
+
# queries and keys will be softmax-ed as in the original efficient attention paper
|
410 |
+
self.no_projection = no_projection
|
411 |
+
|
412 |
+
self.causal = causal
|
413 |
+
|
414 |
+
@torch.no_grad()
|
415 |
+
def redraw_projection_matrix(self):
|
416 |
+
projections = self.create_projection()
|
417 |
+
self.projection_matrix.copy_(projections)
|
418 |
+
del projections
|
419 |
+
|
420 |
+
def forward(self, q, k, v):
|
421 |
+
device = q.device
|
422 |
+
|
423 |
+
if self.no_projection:
|
424 |
+
q = q.softmax(dim = -1)
|
425 |
+
k = torch.exp(k) if self.causal else k.softmax(dim = -2)
|
426 |
+
else:
|
427 |
+
create_kernel = partial(softmax_kernel, projection_matrix = self.projection_matrix, device = device)
|
428 |
+
|
429 |
+
q = create_kernel(q, is_query = True)
|
430 |
+
k = create_kernel(k, is_query = False)
|
431 |
+
|
432 |
+
attn_fn = linear_attention if not self.causal else self.causal_linear_fn
|
433 |
+
if v is None:
|
434 |
+
out = attn_fn(q, k, None)
|
435 |
+
return out
|
436 |
+
else:
|
437 |
+
out = attn_fn(q, k, v)
|
438 |
+
return out
|
439 |
+
class SelfAttention(nn.Module):
|
440 |
+
def __init__(self, dim, causal = False, heads = 8, dim_head = 64, local_heads = 0, local_window_size = 256, nb_features = None, feature_redraw_interval = 1000, generalized_attention = False, kernel_fn = nn.ReLU(), qr_uniform_q = False, dropout = 0., no_projection = False):
|
441 |
+
super().__init__()
|
442 |
+
assert dim % heads == 0, 'dimension must be divisible by number of heads'
|
443 |
+
dim_head = default(dim_head, dim // heads)
|
444 |
+
inner_dim = dim_head * heads
|
445 |
+
self.fast_attention = FastAttention(dim_head, nb_features, causal = causal, generalized_attention = generalized_attention, kernel_fn = kernel_fn, qr_uniform_q = qr_uniform_q, no_projection = no_projection)
|
446 |
+
|
447 |
+
self.heads = heads
|
448 |
+
self.global_heads = heads - local_heads
|
449 |
+
self.local_attn = LocalAttention(window_size = local_window_size, causal = causal, autopad = True, dropout = dropout, look_forward = int(not causal), rel_pos_emb_config = (dim_head, local_heads)) if local_heads > 0 else None
|
450 |
+
|
451 |
+
#print (heads, nb_features, dim_head)
|
452 |
+
#name_embedding = torch.zeros(110, heads, dim_head, dim_head)
|
453 |
+
#self.name_embedding = nn.Parameter(name_embedding, requires_grad=True)
|
454 |
+
|
455 |
+
|
456 |
+
self.to_q = nn.Linear(dim, inner_dim)
|
457 |
+
self.to_k = nn.Linear(dim, inner_dim)
|
458 |
+
self.to_v = nn.Linear(dim, inner_dim)
|
459 |
+
self.to_out = nn.Linear(inner_dim, dim)
|
460 |
+
self.dropout = nn.Dropout(dropout)
|
461 |
+
|
462 |
+
@torch.no_grad()
|
463 |
+
def redraw_projection_matrix(self):
|
464 |
+
self.fast_attention.redraw_projection_matrix()
|
465 |
+
#torch.nn.init.zeros_(self.name_embedding)
|
466 |
+
#print (torch.sum(self.name_embedding))
|
467 |
+
def forward(self, x, context = None, mask = None, context_mask = None, name=None, inference=False, **kwargs):
|
468 |
+
_, _, _, h, gh = *x.shape, self.heads, self.global_heads
|
469 |
+
|
470 |
+
cross_attend = exists(context)
|
471 |
+
|
472 |
+
context = default(context, x)
|
473 |
+
context_mask = default(context_mask, mask) if not cross_attend else context_mask
|
474 |
+
#print (torch.sum(self.name_embedding))
|
475 |
+
q, k, v = self.to_q(x), self.to_k(context), self.to_v(context)
|
476 |
+
|
477 |
+
q, k, v = map(lambda t: rearrange(t, 'b n (h d) -> b h n d', h = h), (q, k, v))
|
478 |
+
(q, lq), (k, lk), (v, lv) = map(lambda t: (t[:, :gh], t[:, gh:]), (q, k, v))
|
479 |
+
|
480 |
+
attn_outs = []
|
481 |
+
#print (name)
|
482 |
+
#print (self.name_embedding[name].size())
|
483 |
+
if not empty(q):
|
484 |
+
if exists(context_mask):
|
485 |
+
global_mask = context_mask[:, None, :, None]
|
486 |
+
v.masked_fill_(~global_mask, 0.)
|
487 |
+
if cross_attend:
|
488 |
+
pass
|
489 |
+
#print (torch.sum(self.name_embedding))
|
490 |
+
#out = self.fast_attention(q,self.name_embedding[name],None)
|
491 |
+
#print (torch.sum(self.name_embedding[...,-1:]))
|
492 |
+
else:
|
493 |
+
out = self.fast_attention(q, k, v)
|
494 |
+
attn_outs.append(out)
|
495 |
+
|
496 |
+
if not empty(lq):
|
497 |
+
assert not cross_attend, 'local attention is not compatible with cross attention'
|
498 |
+
out = self.local_attn(lq, lk, lv, input_mask = mask)
|
499 |
+
attn_outs.append(out)
|
500 |
+
|
501 |
+
out = torch.cat(attn_outs, dim = 1)
|
502 |
+
out = rearrange(out, 'b h n d -> b n (h d)')
|
503 |
+
out = self.to_out(out)
|
504 |
+
return self.dropout(out)
|
505 |
+
|
506 |
+
def l2_regularization(model, l2_alpha):
|
507 |
+
l2_loss = []
|
508 |
+
for module in model.modules():
|
509 |
+
if type(module) is nn.Conv2d:
|
510 |
+
l2_loss.append((module.weight ** 2).sum() / 2.0)
|
511 |
+
return l2_alpha * sum(l2_loss)
|
512 |
+
|
513 |
+
|
514 |
+
class FCPEModel(nn.Module):
|
515 |
+
def __init__(
|
516 |
+
self,
|
517 |
+
input_channel=128,
|
518 |
+
out_dims=360,
|
519 |
+
n_layers=12,
|
520 |
+
n_chans=512,
|
521 |
+
use_siren=False,
|
522 |
+
use_full=False,
|
523 |
+
loss_mse_scale=10,
|
524 |
+
loss_l2_regularization=False,
|
525 |
+
loss_l2_regularization_scale=1,
|
526 |
+
loss_grad1_mse=False,
|
527 |
+
loss_grad1_mse_scale=1,
|
528 |
+
f0_max=1975.5,
|
529 |
+
f0_min=32.70,
|
530 |
+
confidence=False,
|
531 |
+
threshold=0.05,
|
532 |
+
use_input_conv=True
|
533 |
+
):
|
534 |
+
super().__init__()
|
535 |
+
if use_siren is True:
|
536 |
+
raise ValueError("Siren is not supported yet.")
|
537 |
+
if use_full is True:
|
538 |
+
raise ValueError("Full model is not supported yet.")
|
539 |
+
|
540 |
+
self.loss_mse_scale = loss_mse_scale if (loss_mse_scale is not None) else 10
|
541 |
+
self.loss_l2_regularization = loss_l2_regularization if (loss_l2_regularization is not None) else False
|
542 |
+
self.loss_l2_regularization_scale = loss_l2_regularization_scale if (loss_l2_regularization_scale
|
543 |
+
is not None) else 1
|
544 |
+
self.loss_grad1_mse = loss_grad1_mse if (loss_grad1_mse is not None) else False
|
545 |
+
self.loss_grad1_mse_scale = loss_grad1_mse_scale if (loss_grad1_mse_scale is not None) else 1
|
546 |
+
self.f0_max = f0_max if (f0_max is not None) else 1975.5
|
547 |
+
self.f0_min = f0_min if (f0_min is not None) else 32.70
|
548 |
+
self.confidence = confidence if (confidence is not None) else False
|
549 |
+
self.threshold = threshold if (threshold is not None) else 0.05
|
550 |
+
self.use_input_conv = use_input_conv if (use_input_conv is not None) else True
|
551 |
+
|
552 |
+
self.cent_table_b = torch.Tensor(
|
553 |
+
np.linspace(self.f0_to_cent(torch.Tensor([f0_min]))[0], self.f0_to_cent(torch.Tensor([f0_max]))[0],
|
554 |
+
out_dims))
|
555 |
+
self.register_buffer("cent_table", self.cent_table_b)
|
556 |
+
|
557 |
+
# conv in stack
|
558 |
+
_leaky = nn.LeakyReLU()
|
559 |
+
self.stack = nn.Sequential(
|
560 |
+
nn.Conv1d(input_channel, n_chans, 3, 1, 1),
|
561 |
+
nn.GroupNorm(4, n_chans),
|
562 |
+
_leaky,
|
563 |
+
nn.Conv1d(n_chans, n_chans, 3, 1, 1))
|
564 |
+
|
565 |
+
# transformer
|
566 |
+
self.decoder = PCmer(
|
567 |
+
num_layers=n_layers,
|
568 |
+
num_heads=8,
|
569 |
+
dim_model=n_chans,
|
570 |
+
dim_keys=n_chans,
|
571 |
+
dim_values=n_chans,
|
572 |
+
residual_dropout=0.1,
|
573 |
+
attention_dropout=0.1)
|
574 |
+
self.norm = nn.LayerNorm(n_chans)
|
575 |
+
|
576 |
+
# out
|
577 |
+
self.n_out = out_dims
|
578 |
+
self.dense_out = weight_norm(
|
579 |
+
nn.Linear(n_chans, self.n_out))
|
580 |
+
|
581 |
+
def forward(self, mel, infer=True, gt_f0=None, return_hz_f0=False, cdecoder = "local_argmax"):
|
582 |
+
"""
|
583 |
+
input:
|
584 |
+
B x n_frames x n_unit
|
585 |
+
return:
|
586 |
+
dict of B x n_frames x feat
|
587 |
+
"""
|
588 |
+
if cdecoder == "argmax":
|
589 |
+
self.cdecoder = self.cents_decoder
|
590 |
+
elif cdecoder == "local_argmax":
|
591 |
+
self.cdecoder = self.cents_local_decoder
|
592 |
+
if self.use_input_conv:
|
593 |
+
x = self.stack(mel.transpose(1, 2)).transpose(1, 2)
|
594 |
+
else:
|
595 |
+
x = mel
|
596 |
+
x = self.decoder(x)
|
597 |
+
x = self.norm(x)
|
598 |
+
x = self.dense_out(x) # [B,N,D]
|
599 |
+
x = torch.sigmoid(x)
|
600 |
+
if not infer:
|
601 |
+
gt_cent_f0 = self.f0_to_cent(gt_f0) # mel f0 #[B,N,1]
|
602 |
+
gt_cent_f0 = self.gaussian_blurred_cent(gt_cent_f0) # #[B,N,out_dim]
|
603 |
+
loss_all = self.loss_mse_scale * F.binary_cross_entropy(x, gt_cent_f0) # bce loss
|
604 |
+
# l2 regularization
|
605 |
+
if self.loss_l2_regularization:
|
606 |
+
loss_all = loss_all + l2_regularization(model=self, l2_alpha=self.loss_l2_regularization_scale)
|
607 |
+
x = loss_all
|
608 |
+
if infer:
|
609 |
+
x = self.cdecoder(x)
|
610 |
+
x = self.cent_to_f0(x)
|
611 |
+
if not return_hz_f0:
|
612 |
+
x = (1 + x / 700).log()
|
613 |
+
return x
|
614 |
+
|
615 |
+
def cents_decoder(self, y, mask=True):
|
616 |
+
B, N, _ = y.size()
|
617 |
+
ci = self.cent_table[None, None, :].expand(B, N, -1)
|
618 |
+
rtn = torch.sum(ci * y, dim=-1, keepdim=True) / torch.sum(y, dim=-1, keepdim=True) # cents: [B,N,1]
|
619 |
+
if mask:
|
620 |
+
confident = torch.max(y, dim=-1, keepdim=True)[0]
|
621 |
+
confident_mask = torch.ones_like(confident)
|
622 |
+
confident_mask[confident <= self.threshold] = float("-INF")
|
623 |
+
rtn = rtn * confident_mask
|
624 |
+
if self.confidence:
|
625 |
+
return rtn, confident
|
626 |
+
else:
|
627 |
+
return rtn
|
628 |
+
|
629 |
+
def cents_local_decoder(self, y, mask=True):
|
630 |
+
B, N, _ = y.size()
|
631 |
+
ci = self.cent_table[None, None, :].expand(B, N, -1)
|
632 |
+
confident, max_index = torch.max(y, dim=-1, keepdim=True)
|
633 |
+
local_argmax_index = torch.arange(0,9).to(max_index.device) + (max_index - 4)
|
634 |
+
local_argmax_index[local_argmax_index<0] = 0
|
635 |
+
local_argmax_index[local_argmax_index>=self.n_out] = self.n_out - 1
|
636 |
+
ci_l = torch.gather(ci,-1,local_argmax_index)
|
637 |
+
y_l = torch.gather(y,-1,local_argmax_index)
|
638 |
+
rtn = torch.sum(ci_l * y_l, dim=-1, keepdim=True) / torch.sum(y_l, dim=-1, keepdim=True) # cents: [B,N,1]
|
639 |
+
if mask:
|
640 |
+
confident_mask = torch.ones_like(confident)
|
641 |
+
confident_mask[confident <= self.threshold] = float("-INF")
|
642 |
+
rtn = rtn * confident_mask
|
643 |
+
if self.confidence:
|
644 |
+
return rtn, confident
|
645 |
+
else:
|
646 |
+
return rtn
|
647 |
+
|
648 |
+
def cent_to_f0(self, cent):
|
649 |
+
return 10. * 2 ** (cent / 1200.)
|
650 |
+
|
651 |
+
def f0_to_cent(self, f0):
|
652 |
+
return 1200. * torch.log2(f0 / 10.)
|
653 |
+
|
654 |
+
def gaussian_blurred_cent(self, cents): # cents: [B,N,1]
|
655 |
+
mask = (cents > 0.1) & (cents < (1200. * np.log2(self.f0_max / 10.)))
|
656 |
+
B, N, _ = cents.size()
|
657 |
+
ci = self.cent_table[None, None, :].expand(B, N, -1)
|
658 |
+
return torch.exp(-torch.square(ci - cents) / 1250) * mask.float()
|
659 |
+
|
660 |
+
|
661 |
+
class FCPEInfer:
|
662 |
+
def __init__(self, model_path, device=None, dtype=torch.float32):
|
663 |
+
if device is None:
|
664 |
+
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
665 |
+
self.device = device
|
666 |
+
ckpt = torch.load(model_path, map_location=torch.device(self.device))
|
667 |
+
self.args = DotDict(ckpt["config"])
|
668 |
+
self.dtype = dtype
|
669 |
+
model = FCPEModel(
|
670 |
+
input_channel=self.args.model.input_channel,
|
671 |
+
out_dims=self.args.model.out_dims,
|
672 |
+
n_layers=self.args.model.n_layers,
|
673 |
+
n_chans=self.args.model.n_chans,
|
674 |
+
use_siren=self.args.model.use_siren,
|
675 |
+
use_full=self.args.model.use_full,
|
676 |
+
loss_mse_scale=self.args.loss.loss_mse_scale,
|
677 |
+
loss_l2_regularization=self.args.loss.loss_l2_regularization,
|
678 |
+
loss_l2_regularization_scale=self.args.loss.loss_l2_regularization_scale,
|
679 |
+
loss_grad1_mse=self.args.loss.loss_grad1_mse,
|
680 |
+
loss_grad1_mse_scale=self.args.loss.loss_grad1_mse_scale,
|
681 |
+
f0_max=self.args.model.f0_max,
|
682 |
+
f0_min=self.args.model.f0_min,
|
683 |
+
confidence=self.args.model.confidence,
|
684 |
+
)
|
685 |
+
model.to(self.device).to(self.dtype)
|
686 |
+
model.load_state_dict(ckpt['model'])
|
687 |
+
model.eval()
|
688 |
+
self.model = model
|
689 |
+
self.wav2mel = Wav2Mel(self.args, dtype=self.dtype, device=self.device)
|
690 |
+
|
691 |
+
@torch.no_grad()
|
692 |
+
def __call__(self, audio, sr, threshold=0.05):
|
693 |
+
self.model.threshold = threshold
|
694 |
+
audio = audio[None,:]
|
695 |
+
mel = self.wav2mel(audio=audio, sample_rate=sr).to(self.dtype)
|
696 |
+
f0 = self.model(mel=mel, infer=True, return_hz_f0=True)
|
697 |
+
return f0
|
698 |
+
|
699 |
+
|
700 |
+
class Wav2Mel:
|
701 |
+
|
702 |
+
def __init__(self, args, device=None, dtype=torch.float32):
|
703 |
+
# self.args = args
|
704 |
+
self.sampling_rate = args.mel.sampling_rate
|
705 |
+
self.hop_size = args.mel.hop_size
|
706 |
+
if device is None:
|
707 |
+
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
708 |
+
self.device = device
|
709 |
+
self.dtype = dtype
|
710 |
+
self.stft = STFT(
|
711 |
+
args.mel.sampling_rate,
|
712 |
+
args.mel.num_mels,
|
713 |
+
args.mel.n_fft,
|
714 |
+
args.mel.win_size,
|
715 |
+
args.mel.hop_size,
|
716 |
+
args.mel.fmin,
|
717 |
+
args.mel.fmax
|
718 |
+
)
|
719 |
+
self.resample_kernel = {}
|
720 |
+
|
721 |
+
def extract_nvstft(self, audio, keyshift=0, train=False):
|
722 |
+
mel = self.stft.get_mel(audio, keyshift=keyshift, train=train).transpose(1, 2) # B, n_frames, bins
|
723 |
+
return mel
|
724 |
+
|
725 |
+
def extract_mel(self, audio, sample_rate, keyshift=0, train=False):
|
726 |
+
audio = audio.to(self.dtype).to(self.device)
|
727 |
+
# resample
|
728 |
+
if sample_rate == self.sampling_rate:
|
729 |
+
audio_res = audio
|
730 |
+
else:
|
731 |
+
key_str = str(sample_rate)
|
732 |
+
if key_str not in self.resample_kernel:
|
733 |
+
self.resample_kernel[key_str] = Resample(sample_rate, self.sampling_rate, lowpass_filter_width=128)
|
734 |
+
self.resample_kernel[key_str] = self.resample_kernel[key_str].to(self.dtype).to(self.device)
|
735 |
+
audio_res = self.resample_kernel[key_str](audio)
|
736 |
+
|
737 |
+
# extract
|
738 |
+
mel = self.extract_nvstft(audio_res, keyshift=keyshift, train=train) # B, n_frames, bins
|
739 |
+
n_frames = int(audio.shape[1] // self.hop_size) + 1
|
740 |
+
if n_frames > int(mel.shape[1]):
|
741 |
+
mel = torch.cat((mel, mel[:, -1:, :]), 1)
|
742 |
+
if n_frames < int(mel.shape[1]):
|
743 |
+
mel = mel[:, :n_frames, :]
|
744 |
+
return mel
|
745 |
+
|
746 |
+
def __call__(self, audio, sample_rate, keyshift=0, train=False):
|
747 |
+
return self.extract_mel(audio, sample_rate, keyshift=keyshift, train=train)
|
748 |
+
|
749 |
+
|
750 |
+
class DotDict(dict):
|
751 |
+
def __getattr__(*args):
|
752 |
+
val = dict.get(*args)
|
753 |
+
return DotDict(val) if type(val) is dict else val
|
754 |
+
|
755 |
+
__setattr__ = dict.__setitem__
|
756 |
+
__delattr__ = dict.__delitem__
|
757 |
+
|
758 |
+
class F0Predictor(object):
|
759 |
+
def compute_f0(self,wav,p_len):
|
760 |
+
'''
|
761 |
+
input: wav:[signal_length]
|
762 |
+
p_len:int
|
763 |
+
output: f0:[signal_length//hop_length]
|
764 |
+
'''
|
765 |
+
pass
|
766 |
+
|
767 |
+
def compute_f0_uv(self,wav,p_len):
|
768 |
+
'''
|
769 |
+
input: wav:[signal_length]
|
770 |
+
p_len:int
|
771 |
+
output: f0:[signal_length//hop_length],uv:[signal_length//hop_length]
|
772 |
+
'''
|
773 |
+
pass
|
774 |
+
|
775 |
+
class FCPE(F0Predictor):
|
776 |
+
def __init__(self, model_path, hop_length=512, f0_min=50, f0_max=1100, dtype=torch.float32, device=None, sampling_rate=44100,
|
777 |
+
threshold=0.05):
|
778 |
+
self.fcpe = FCPEInfer(model_path, device=device, dtype=dtype)
|
779 |
+
self.hop_length = hop_length
|
780 |
+
self.f0_min = f0_min
|
781 |
+
self.f0_max = f0_max
|
782 |
+
if device is None:
|
783 |
+
self.device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
784 |
+
else:
|
785 |
+
self.device = device
|
786 |
+
self.threshold = threshold
|
787 |
+
self.sampling_rate = sampling_rate
|
788 |
+
self.dtype = dtype
|
789 |
+
self.name = "fcpe"
|
790 |
+
|
791 |
+
def repeat_expand(
|
792 |
+
self, content: Union[torch.Tensor, np.ndarray], target_len: int, mode: str = "nearest"
|
793 |
+
):
|
794 |
+
ndim = content.ndim
|
795 |
+
|
796 |
+
if content.ndim == 1:
|
797 |
+
content = content[None, None]
|
798 |
+
elif content.ndim == 2:
|
799 |
+
content = content[None]
|
800 |
+
|
801 |
+
assert content.ndim == 3
|
802 |
+
|
803 |
+
is_np = isinstance(content, np.ndarray)
|
804 |
+
if is_np:
|
805 |
+
content = torch.from_numpy(content)
|
806 |
+
|
807 |
+
results = torch.nn.functional.interpolate(content, size=target_len, mode=mode)
|
808 |
+
|
809 |
+
if is_np:
|
810 |
+
results = results.numpy()
|
811 |
+
|
812 |
+
if ndim == 1:
|
813 |
+
return results[0, 0]
|
814 |
+
elif ndim == 2:
|
815 |
+
return results[0]
|
816 |
+
|
817 |
+
def post_process(self, x, sampling_rate, f0, pad_to):
|
818 |
+
if isinstance(f0, np.ndarray):
|
819 |
+
f0 = torch.from_numpy(f0).float().to(x.device)
|
820 |
+
|
821 |
+
if pad_to is None:
|
822 |
+
return f0
|
823 |
+
|
824 |
+
f0 = self.repeat_expand(f0, pad_to)
|
825 |
+
|
826 |
+
vuv_vector = torch.zeros_like(f0)
|
827 |
+
vuv_vector[f0 > 0.0] = 1.0
|
828 |
+
vuv_vector[f0 <= 0.0] = 0.0
|
829 |
+
|
830 |
+
# 去掉0频率, 并线性插值
|
831 |
+
nzindex = torch.nonzero(f0).squeeze()
|
832 |
+
f0 = torch.index_select(f0, dim=0, index=nzindex).cpu().numpy()
|
833 |
+
time_org = self.hop_length / sampling_rate * nzindex.cpu().numpy()
|
834 |
+
time_frame = np.arange(pad_to) * self.hop_length / sampling_rate
|
835 |
+
|
836 |
+
vuv_vector = F.interpolate(vuv_vector[None, None, :], size=pad_to)[0][0]
|
837 |
+
|
838 |
+
if f0.shape[0] <= 0:
|
839 |
+
return torch.zeros(pad_to, dtype=torch.float, device=x.device).cpu().numpy(), vuv_vector.cpu().numpy()
|
840 |
+
if f0.shape[0] == 1:
|
841 |
+
return (torch.ones(pad_to, dtype=torch.float, device=x.device) * f0[
|
842 |
+
0]).cpu().numpy(), vuv_vector.cpu().numpy()
|
843 |
+
|
844 |
+
# 大概可以用 torch 重写?
|
845 |
+
f0 = np.interp(time_frame, time_org, f0, left=f0[0], right=f0[-1])
|
846 |
+
# vuv_vector = np.ceil(scipy.ndimage.zoom(vuv_vector,pad_to/len(vuv_vector),order = 0))
|
847 |
+
|
848 |
+
return f0, vuv_vector.cpu().numpy()
|
849 |
+
|
850 |
+
def compute_f0(self, wav, p_len=None):
|
851 |
+
x = torch.FloatTensor(wav).to(self.dtype).to(self.device)
|
852 |
+
if p_len is None:
|
853 |
+
print("fcpe p_len is None")
|
854 |
+
p_len = x.shape[0] // self.hop_length
|
855 |
+
#else:
|
856 |
+
# assert abs(p_len - x.shape[0] // self.hop_length) < 4, "pad length error"
|
857 |
+
f0 = self.fcpe(x, sr=self.sampling_rate, threshold=self.threshold)[0,:,0]
|
858 |
+
if torch.all(f0 == 0):
|
859 |
+
rtn = f0.cpu().numpy() if p_len is None else np.zeros(p_len)
|
860 |
+
return rtn, rtn
|
861 |
+
return self.post_process(x, self.sampling_rate, f0, p_len)[0]
|
862 |
+
|
863 |
+
def compute_f0_uv(self, wav, p_len=None):
|
864 |
+
x = torch.FloatTensor(wav).to(self.dtype).to(self.device)
|
865 |
+
if p_len is None:
|
866 |
+
p_len = x.shape[0] // self.hop_length
|
867 |
+
#else:
|
868 |
+
# assert abs(p_len - x.shape[0] // self.hop_length) < 4, "pad length error"
|
869 |
+
f0 = self.fcpe(x, sr=self.sampling_rate, threshold=self.threshold)[0,:,0]
|
870 |
+
if torch.all(f0 == 0):
|
871 |
+
rtn = f0.cpu().numpy() if p_len is None else np.zeros(p_len)
|
872 |
+
return rtn, rtn
|
873 |
+
return self.post_process(x, self.sampling_rate, f0, p_len)
|
lib/infer_libs/infer_pack/attentions.py
ADDED
@@ -0,0 +1,414 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import math
|
2 |
+
import torch
|
3 |
+
from torch import nn
|
4 |
+
from torch.nn import functional as F
|
5 |
+
|
6 |
+
from lib.infer_libs.infer_pack import commons
|
7 |
+
from lib.infer_libs.infer_pack.modules import LayerNorm
|
8 |
+
|
9 |
+
|
10 |
+
class Encoder(nn.Module):
|
11 |
+
def __init__(
|
12 |
+
self,
|
13 |
+
hidden_channels,
|
14 |
+
filter_channels,
|
15 |
+
n_heads,
|
16 |
+
n_layers,
|
17 |
+
kernel_size=1,
|
18 |
+
p_dropout=0.0,
|
19 |
+
window_size=10,
|
20 |
+
**kwargs
|
21 |
+
):
|
22 |
+
super().__init__()
|
23 |
+
self.hidden_channels = hidden_channels
|
24 |
+
self.filter_channels = filter_channels
|
25 |
+
self.n_heads = n_heads
|
26 |
+
self.n_layers = n_layers
|
27 |
+
self.kernel_size = kernel_size
|
28 |
+
self.p_dropout = p_dropout
|
29 |
+
self.window_size = window_size
|
30 |
+
|
31 |
+
self.drop = nn.Dropout(p_dropout)
|
32 |
+
self.attn_layers = nn.ModuleList()
|
33 |
+
self.norm_layers_1 = nn.ModuleList()
|
34 |
+
self.ffn_layers = nn.ModuleList()
|
35 |
+
self.norm_layers_2 = nn.ModuleList()
|
36 |
+
for i in range(self.n_layers):
|
37 |
+
self.attn_layers.append(
|
38 |
+
MultiHeadAttention(
|
39 |
+
hidden_channels,
|
40 |
+
hidden_channels,
|
41 |
+
n_heads,
|
42 |
+
p_dropout=p_dropout,
|
43 |
+
window_size=window_size,
|
44 |
+
)
|
45 |
+
)
|
46 |
+
self.norm_layers_1.append(LayerNorm(hidden_channels))
|
47 |
+
self.ffn_layers.append(
|
48 |
+
FFN(
|
49 |
+
hidden_channels,
|
50 |
+
hidden_channels,
|
51 |
+
filter_channels,
|
52 |
+
kernel_size,
|
53 |
+
p_dropout=p_dropout,
|
54 |
+
)
|
55 |
+
)
|
56 |
+
self.norm_layers_2.append(LayerNorm(hidden_channels))
|
57 |
+
|
58 |
+
def forward(self, x, x_mask):
|
59 |
+
attn_mask = x_mask.unsqueeze(2) * x_mask.unsqueeze(-1)
|
60 |
+
x = x * x_mask
|
61 |
+
for i in range(self.n_layers):
|
62 |
+
y = self.attn_layers[i](x, x, attn_mask)
|
63 |
+
y = self.drop(y)
|
64 |
+
x = self.norm_layers_1[i](x + y)
|
65 |
+
|
66 |
+
y = self.ffn_layers[i](x, x_mask)
|
67 |
+
y = self.drop(y)
|
68 |
+
x = self.norm_layers_2[i](x + y)
|
69 |
+
x = x * x_mask
|
70 |
+
return x
|
71 |
+
|
72 |
+
|
73 |
+
class Decoder(nn.Module):
|
74 |
+
def __init__(
|
75 |
+
self,
|
76 |
+
hidden_channels,
|
77 |
+
filter_channels,
|
78 |
+
n_heads,
|
79 |
+
n_layers,
|
80 |
+
kernel_size=1,
|
81 |
+
p_dropout=0.0,
|
82 |
+
proximal_bias=False,
|
83 |
+
proximal_init=True,
|
84 |
+
**kwargs
|
85 |
+
):
|
86 |
+
super().__init__()
|
87 |
+
self.hidden_channels = hidden_channels
|
88 |
+
self.filter_channels = filter_channels
|
89 |
+
self.n_heads = n_heads
|
90 |
+
self.n_layers = n_layers
|
91 |
+
self.kernel_size = kernel_size
|
92 |
+
self.p_dropout = p_dropout
|
93 |
+
self.proximal_bias = proximal_bias
|
94 |
+
self.proximal_init = proximal_init
|
95 |
+
|
96 |
+
self.drop = nn.Dropout(p_dropout)
|
97 |
+
self.self_attn_layers = nn.ModuleList()
|
98 |
+
self.norm_layers_0 = nn.ModuleList()
|
99 |
+
self.encdec_attn_layers = nn.ModuleList()
|
100 |
+
self.norm_layers_1 = nn.ModuleList()
|
101 |
+
self.ffn_layers = nn.ModuleList()
|
102 |
+
self.norm_layers_2 = nn.ModuleList()
|
103 |
+
for i in range(self.n_layers):
|
104 |
+
self.self_attn_layers.append(
|
105 |
+
MultiHeadAttention(
|
106 |
+
hidden_channels,
|
107 |
+
hidden_channels,
|
108 |
+
n_heads,
|
109 |
+
p_dropout=p_dropout,
|
110 |
+
proximal_bias=proximal_bias,
|
111 |
+
proximal_init=proximal_init,
|
112 |
+
)
|
113 |
+
)
|
114 |
+
self.norm_layers_0.append(LayerNorm(hidden_channels))
|
115 |
+
self.encdec_attn_layers.append(
|
116 |
+
MultiHeadAttention(
|
117 |
+
hidden_channels, hidden_channels, n_heads, p_dropout=p_dropout
|
118 |
+
)
|
119 |
+
)
|
120 |
+
self.norm_layers_1.append(LayerNorm(hidden_channels))
|
121 |
+
self.ffn_layers.append(
|
122 |
+
FFN(
|
123 |
+
hidden_channels,
|
124 |
+
hidden_channels,
|
125 |
+
filter_channels,
|
126 |
+
kernel_size,
|
127 |
+
p_dropout=p_dropout,
|
128 |
+
causal=True,
|
129 |
+
)
|
130 |
+
)
|
131 |
+
self.norm_layers_2.append(LayerNorm(hidden_channels))
|
132 |
+
|
133 |
+
def forward(self, x, x_mask, h, h_mask):
|
134 |
+
"""
|
135 |
+
x: decoder input
|
136 |
+
h: encoder output
|
137 |
+
"""
|
138 |
+
self_attn_mask = commons.subsequent_mask(x_mask.size(2)).to(
|
139 |
+
device=x.device, dtype=x.dtype
|
140 |
+
)
|
141 |
+
encdec_attn_mask = h_mask.unsqueeze(2) * x_mask.unsqueeze(-1)
|
142 |
+
x = x * x_mask
|
143 |
+
for i in range(self.n_layers):
|
144 |
+
y = self.self_attn_layers[i](x, x, self_attn_mask)
|
145 |
+
y = self.drop(y)
|
146 |
+
x = self.norm_layers_0[i](x + y)
|
147 |
+
|
148 |
+
y = self.encdec_attn_layers[i](x, h, encdec_attn_mask)
|
149 |
+
y = self.drop(y)
|
150 |
+
x = self.norm_layers_1[i](x + y)
|
151 |
+
|
152 |
+
y = self.ffn_layers[i](x, x_mask)
|
153 |
+
y = self.drop(y)
|
154 |
+
x = self.norm_layers_2[i](x + y)
|
155 |
+
x = x * x_mask
|
156 |
+
return x
|
157 |
+
|
158 |
+
|
159 |
+
class MultiHeadAttention(nn.Module):
|
160 |
+
def __init__(
|
161 |
+
self,
|
162 |
+
channels,
|
163 |
+
out_channels,
|
164 |
+
n_heads,
|
165 |
+
p_dropout=0.0,
|
166 |
+
window_size=None,
|
167 |
+
heads_share=True,
|
168 |
+
block_length=None,
|
169 |
+
proximal_bias=False,
|
170 |
+
proximal_init=False,
|
171 |
+
):
|
172 |
+
super().__init__()
|
173 |
+
assert channels % n_heads == 0
|
174 |
+
|
175 |
+
self.channels = channels
|
176 |
+
self.out_channels = out_channels
|
177 |
+
self.n_heads = n_heads
|
178 |
+
self.p_dropout = p_dropout
|
179 |
+
self.window_size = window_size
|
180 |
+
self.heads_share = heads_share
|
181 |
+
self.block_length = block_length
|
182 |
+
self.proximal_bias = proximal_bias
|
183 |
+
self.proximal_init = proximal_init
|
184 |
+
self.attn = None
|
185 |
+
|
186 |
+
self.k_channels = channels // n_heads
|
187 |
+
self.conv_q = nn.Conv1d(channels, channels, 1)
|
188 |
+
self.conv_k = nn.Conv1d(channels, channels, 1)
|
189 |
+
self.conv_v = nn.Conv1d(channels, channels, 1)
|
190 |
+
self.conv_o = nn.Conv1d(channels, out_channels, 1)
|
191 |
+
self.drop = nn.Dropout(p_dropout)
|
192 |
+
|
193 |
+
if window_size is not None:
|
194 |
+
n_heads_rel = 1 if heads_share else n_heads
|
195 |
+
rel_stddev = self.k_channels**-0.5
|
196 |
+
self.emb_rel_k = nn.Parameter(
|
197 |
+
torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels)
|
198 |
+
* rel_stddev
|
199 |
+
)
|
200 |
+
self.emb_rel_v = nn.Parameter(
|
201 |
+
torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels)
|
202 |
+
* rel_stddev
|
203 |
+
)
|
204 |
+
|
205 |
+
nn.init.xavier_uniform_(self.conv_q.weight)
|
206 |
+
nn.init.xavier_uniform_(self.conv_k.weight)
|
207 |
+
nn.init.xavier_uniform_(self.conv_v.weight)
|
208 |
+
if proximal_init:
|
209 |
+
with torch.no_grad():
|
210 |
+
self.conv_k.weight.copy_(self.conv_q.weight)
|
211 |
+
self.conv_k.bias.copy_(self.conv_q.bias)
|
212 |
+
|
213 |
+
def forward(self, x, c, attn_mask=None):
|
214 |
+
q = self.conv_q(x)
|
215 |
+
k = self.conv_k(c)
|
216 |
+
v = self.conv_v(c)
|
217 |
+
|
218 |
+
x, self.attn = self.attention(q, k, v, mask=attn_mask)
|
219 |
+
|
220 |
+
x = self.conv_o(x)
|
221 |
+
return x
|
222 |
+
|
223 |
+
def attention(self, query, key, value, mask=None):
|
224 |
+
# reshape [b, d, t] -> [b, n_h, t, d_k]
|
225 |
+
b, d, t_s, t_t = (*key.size(), query.size(2))
|
226 |
+
query = query.view(b, self.n_heads, self.k_channels, t_t).transpose(2, 3)
|
227 |
+
key = key.view(b, self.n_heads, self.k_channels, t_s).transpose(2, 3)
|
228 |
+
value = value.view(b, self.n_heads, self.k_channels, t_s).transpose(2, 3)
|
229 |
+
|
230 |
+
scores = torch.matmul(query / math.sqrt(self.k_channels), key.transpose(-2, -1))
|
231 |
+
if self.window_size is not None:
|
232 |
+
assert (
|
233 |
+
t_s == t_t
|
234 |
+
), "Relative attention is only available for self-attention."
|
235 |
+
key_relative_embeddings = self._get_relative_embeddings(self.emb_rel_k, t_s)
|
236 |
+
rel_logits = self._matmul_with_relative_keys(
|
237 |
+
query / math.sqrt(self.k_channels), key_relative_embeddings
|
238 |
+
)
|
239 |
+
scores_local = self._relative_position_to_absolute_position(rel_logits)
|
240 |
+
scores = scores + scores_local
|
241 |
+
if self.proximal_bias:
|
242 |
+
assert t_s == t_t, "Proximal bias is only available for self-attention."
|
243 |
+
scores = scores + self._attention_bias_proximal(t_s).to(
|
244 |
+
device=scores.device, dtype=scores.dtype
|
245 |
+
)
|
246 |
+
if mask is not None:
|
247 |
+
scores = scores.masked_fill(mask == 0, -1e4)
|
248 |
+
if self.block_length is not None:
|
249 |
+
assert (
|
250 |
+
t_s == t_t
|
251 |
+
), "Local attention is only available for self-attention."
|
252 |
+
block_mask = (
|
253 |
+
torch.ones_like(scores)
|
254 |
+
.triu(-self.block_length)
|
255 |
+
.tril(self.block_length)
|
256 |
+
)
|
257 |
+
scores = scores.masked_fill(block_mask == 0, -1e4)
|
258 |
+
p_attn = F.softmax(scores, dim=-1) # [b, n_h, t_t, t_s]
|
259 |
+
p_attn = self.drop(p_attn)
|
260 |
+
output = torch.matmul(p_attn, value)
|
261 |
+
if self.window_size is not None:
|
262 |
+
relative_weights = self._absolute_position_to_relative_position(p_attn)
|
263 |
+
value_relative_embeddings = self._get_relative_embeddings(
|
264 |
+
self.emb_rel_v, t_s
|
265 |
+
)
|
266 |
+
output = output + self._matmul_with_relative_values(
|
267 |
+
relative_weights, value_relative_embeddings
|
268 |
+
)
|
269 |
+
output = (
|
270 |
+
output.transpose(2, 3).contiguous().view(b, d, t_t)
|
271 |
+
) # [b, n_h, t_t, d_k] -> [b, d, t_t]
|
272 |
+
return output, p_attn
|
273 |
+
|
274 |
+
def _matmul_with_relative_values(self, x, y):
|
275 |
+
"""
|
276 |
+
x: [b, h, l, m]
|
277 |
+
y: [h or 1, m, d]
|
278 |
+
ret: [b, h, l, d]
|
279 |
+
"""
|
280 |
+
ret = torch.matmul(x, y.unsqueeze(0))
|
281 |
+
return ret
|
282 |
+
|
283 |
+
def _matmul_with_relative_keys(self, x, y):
|
284 |
+
"""
|
285 |
+
x: [b, h, l, d]
|
286 |
+
y: [h or 1, m, d]
|
287 |
+
ret: [b, h, l, m]
|
288 |
+
"""
|
289 |
+
ret = torch.matmul(x, y.unsqueeze(0).transpose(-2, -1))
|
290 |
+
return ret
|
291 |
+
|
292 |
+
def _get_relative_embeddings(self, relative_embeddings, length):
|
293 |
+
max_relative_position = 2 * self.window_size + 1
|
294 |
+
# Pad first before slice to avoid using cond ops.
|
295 |
+
pad_length = max(length - (self.window_size + 1), 0)
|
296 |
+
slice_start_position = max((self.window_size + 1) - length, 0)
|
297 |
+
slice_end_position = slice_start_position + 2 * length - 1
|
298 |
+
if pad_length > 0:
|
299 |
+
padded_relative_embeddings = F.pad(
|
300 |
+
relative_embeddings,
|
301 |
+
commons.convert_pad_shape([[0, 0], [pad_length, pad_length], [0, 0]]),
|
302 |
+
)
|
303 |
+
else:
|
304 |
+
padded_relative_embeddings = relative_embeddings
|
305 |
+
used_relative_embeddings = padded_relative_embeddings[
|
306 |
+
:, slice_start_position:slice_end_position
|
307 |
+
]
|
308 |
+
return used_relative_embeddings
|
309 |
+
|
310 |
+
def _relative_position_to_absolute_position(self, x):
|
311 |
+
"""
|
312 |
+
x: [b, h, l, 2*l-1]
|
313 |
+
ret: [b, h, l, l]
|
314 |
+
"""
|
315 |
+
batch, heads, length, _ = x.size()
|
316 |
+
# Concat columns of pad to shift from relative to absolute indexing.
|
317 |
+
x = F.pad(x, commons.convert_pad_shape([[0, 0], [0, 0], [0, 0], [0, 1]]))
|
318 |
+
|
319 |
+
# Concat extra elements so to add up to shape (len+1, 2*len-1).
|
320 |
+
x_flat = x.view([batch, heads, length * 2 * length])
|
321 |
+
x_flat = F.pad(
|
322 |
+
x_flat, commons.convert_pad_shape([[0, 0], [0, 0], [0, length - 1]])
|
323 |
+
)
|
324 |
+
|
325 |
+
# Reshape and slice out the padded elements.
|
326 |
+
x_final = x_flat.view([batch, heads, length + 1, 2 * length - 1])[
|
327 |
+
:, :, :length, length - 1 :
|
328 |
+
]
|
329 |
+
return x_final
|
330 |
+
|
331 |
+
def _absolute_position_to_relative_position(self, x):
|
332 |
+
"""
|
333 |
+
x: [b, h, l, l]
|
334 |
+
ret: [b, h, l, 2*l-1]
|
335 |
+
"""
|
336 |
+
batch, heads, length, _ = x.size()
|
337 |
+
# padd along column
|
338 |
+
x = F.pad(
|
339 |
+
x, commons.convert_pad_shape([[0, 0], [0, 0], [0, 0], [0, length - 1]])
|
340 |
+
)
|
341 |
+
x_flat = x.view([batch, heads, length**2 + length * (length - 1)])
|
342 |
+
# add 0's in the beginning that will skew the elements after reshape
|
343 |
+
x_flat = F.pad(x_flat, commons.convert_pad_shape([[0, 0], [0, 0], [length, 0]]))
|
344 |
+
x_final = x_flat.view([batch, heads, length, 2 * length])[:, :, :, 1:]
|
345 |
+
return x_final
|
346 |
+
|
347 |
+
def _attention_bias_proximal(self, length):
|
348 |
+
"""Bias for self-attention to encourage attention to close positions.
|
349 |
+
Args:
|
350 |
+
length: an integer scalar.
|
351 |
+
Returns:
|
352 |
+
a Tensor with shape [1, 1, length, length]
|
353 |
+
"""
|
354 |
+
r = torch.arange(length, dtype=torch.float32)
|
355 |
+
diff = torch.unsqueeze(r, 0) - torch.unsqueeze(r, 1)
|
356 |
+
return torch.unsqueeze(torch.unsqueeze(-torch.log1p(torch.abs(diff)), 0), 0)
|
357 |
+
|
358 |
+
|
359 |
+
class FFN(nn.Module):
|
360 |
+
def __init__(
|
361 |
+
self,
|
362 |
+
in_channels,
|
363 |
+
out_channels,
|
364 |
+
filter_channels,
|
365 |
+
kernel_size,
|
366 |
+
p_dropout=0.0,
|
367 |
+
activation=None,
|
368 |
+
causal=False,
|
369 |
+
):
|
370 |
+
super().__init__()
|
371 |
+
self.in_channels = in_channels
|
372 |
+
self.out_channels = out_channels
|
373 |
+
self.filter_channels = filter_channels
|
374 |
+
self.kernel_size = kernel_size
|
375 |
+
self.p_dropout = p_dropout
|
376 |
+
self.activation = activation
|
377 |
+
self.causal = causal
|
378 |
+
|
379 |
+
if causal:
|
380 |
+
self.padding = self._causal_padding
|
381 |
+
else:
|
382 |
+
self.padding = self._same_padding
|
383 |
+
|
384 |
+
self.conv_1 = nn.Conv1d(in_channels, filter_channels, kernel_size)
|
385 |
+
self.conv_2 = nn.Conv1d(filter_channels, out_channels, kernel_size)
|
386 |
+
self.drop = nn.Dropout(p_dropout)
|
387 |
+
|
388 |
+
def forward(self, x, x_mask):
|
389 |
+
x = self.conv_1(self.padding(x * x_mask))
|
390 |
+
if self.activation == "gelu":
|
391 |
+
x = x * torch.sigmoid(1.702 * x)
|
392 |
+
else:
|
393 |
+
x = torch.relu(x)
|
394 |
+
x = self.drop(x)
|
395 |
+
x = self.conv_2(self.padding(x * x_mask))
|
396 |
+
return x * x_mask
|
397 |
+
|
398 |
+
def _causal_padding(self, x):
|
399 |
+
if self.kernel_size == 1:
|
400 |
+
return x
|
401 |
+
pad_l = self.kernel_size - 1
|
402 |
+
pad_r = 0
|
403 |
+
padding = [[0, 0], [0, 0], [pad_l, pad_r]]
|
404 |
+
x = F.pad(x, commons.convert_pad_shape(padding))
|
405 |
+
return x
|
406 |
+
|
407 |
+
def _same_padding(self, x):
|
408 |
+
if self.kernel_size == 1:
|
409 |
+
return x
|
410 |
+
pad_l = (self.kernel_size - 1) // 2
|
411 |
+
pad_r = self.kernel_size // 2
|
412 |
+
padding = [[0, 0], [0, 0], [pad_l, pad_r]]
|
413 |
+
x = F.pad(x, commons.convert_pad_shape(padding))
|
414 |
+
return x
|
lib/infer_libs/infer_pack/commons.py
ADDED
@@ -0,0 +1,164 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import math
|
2 |
+
import torch
|
3 |
+
from torch.nn import functional as F
|
4 |
+
|
5 |
+
|
6 |
+
def init_weights(m, mean=0.0, std=0.01):
|
7 |
+
classname = m.__class__.__name__
|
8 |
+
if classname.find("Conv") != -1:
|
9 |
+
m.weight.data.normal_(mean, std)
|
10 |
+
|
11 |
+
|
12 |
+
def get_padding(kernel_size, dilation=1):
|
13 |
+
return int((kernel_size * dilation - dilation) / 2)
|
14 |
+
|
15 |
+
|
16 |
+
def convert_pad_shape(pad_shape):
|
17 |
+
l = pad_shape[::-1]
|
18 |
+
pad_shape = [item for sublist in l for item in sublist]
|
19 |
+
return pad_shape
|
20 |
+
|
21 |
+
|
22 |
+
def kl_divergence(m_p, logs_p, m_q, logs_q):
|
23 |
+
"""KL(P||Q)"""
|
24 |
+
kl = (logs_q - logs_p) - 0.5
|
25 |
+
kl += (
|
26 |
+
0.5 * (torch.exp(2.0 * logs_p) + ((m_p - m_q) ** 2)) * torch.exp(-2.0 * logs_q)
|
27 |
+
)
|
28 |
+
return kl
|
29 |
+
|
30 |
+
|
31 |
+
def rand_gumbel(shape):
|
32 |
+
"""Sample from the Gumbel distribution, protect from overflows."""
|
33 |
+
uniform_samples = torch.rand(shape) * 0.99998 + 0.00001
|
34 |
+
return -torch.log(-torch.log(uniform_samples))
|
35 |
+
|
36 |
+
|
37 |
+
def rand_gumbel_like(x):
|
38 |
+
g = rand_gumbel(x.size()).to(dtype=x.dtype, device=x.device)
|
39 |
+
return g
|
40 |
+
|
41 |
+
|
42 |
+
def slice_segments(x, ids_str, segment_size=4):
|
43 |
+
ret = torch.zeros_like(x[:, :, :segment_size])
|
44 |
+
for i in range(x.size(0)):
|
45 |
+
idx_str = ids_str[i]
|
46 |
+
idx_end = idx_str + segment_size
|
47 |
+
ret[i] = x[i, :, idx_str:idx_end]
|
48 |
+
return ret
|
49 |
+
|
50 |
+
|
51 |
+
def slice_segments2(x, ids_str, segment_size=4):
|
52 |
+
ret = torch.zeros_like(x[:, :segment_size])
|
53 |
+
for i in range(x.size(0)):
|
54 |
+
idx_str = ids_str[i]
|
55 |
+
idx_end = idx_str + segment_size
|
56 |
+
ret[i] = x[i, idx_str:idx_end]
|
57 |
+
return ret
|
58 |
+
|
59 |
+
|
60 |
+
def rand_slice_segments(x, x_lengths=None, segment_size=4):
|
61 |
+
b, d, t = x.size()
|
62 |
+
if x_lengths is None:
|
63 |
+
x_lengths = t
|
64 |
+
ids_str_max = x_lengths - segment_size + 1
|
65 |
+
ids_str = (torch.rand([b]).to(device=x.device) * ids_str_max).to(dtype=torch.long)
|
66 |
+
ret = slice_segments(x, ids_str, segment_size)
|
67 |
+
return ret, ids_str
|
68 |
+
|
69 |
+
|
70 |
+
def get_timing_signal_1d(length, channels, min_timescale=1.0, max_timescale=1.0e4):
|
71 |
+
position = torch.arange(length, dtype=torch.float)
|
72 |
+
num_timescales = channels // 2
|
73 |
+
log_timescale_increment = math.log(float(max_timescale) / float(min_timescale)) / (
|
74 |
+
num_timescales - 1
|
75 |
+
)
|
76 |
+
inv_timescales = min_timescale * torch.exp(
|
77 |
+
torch.arange(num_timescales, dtype=torch.float) * -log_timescale_increment
|
78 |
+
)
|
79 |
+
scaled_time = position.unsqueeze(0) * inv_timescales.unsqueeze(1)
|
80 |
+
signal = torch.cat([torch.sin(scaled_time), torch.cos(scaled_time)], 0)
|
81 |
+
signal = F.pad(signal, [0, 0, 0, channels % 2])
|
82 |
+
signal = signal.view(1, channels, length)
|
83 |
+
return signal
|
84 |
+
|
85 |
+
|
86 |
+
def add_timing_signal_1d(x, min_timescale=1.0, max_timescale=1.0e4):
|
87 |
+
b, channels, length = x.size()
|
88 |
+
signal = get_timing_signal_1d(length, channels, min_timescale, max_timescale)
|
89 |
+
return x + signal.to(dtype=x.dtype, device=x.device)
|
90 |
+
|
91 |
+
|
92 |
+
def cat_timing_signal_1d(x, min_timescale=1.0, max_timescale=1.0e4, axis=1):
|
93 |
+
b, channels, length = x.size()
|
94 |
+
signal = get_timing_signal_1d(length, channels, min_timescale, max_timescale)
|
95 |
+
return torch.cat([x, signal.to(dtype=x.dtype, device=x.device)], axis)
|
96 |
+
|
97 |
+
|
98 |
+
def subsequent_mask(length):
|
99 |
+
mask = torch.tril(torch.ones(length, length)).unsqueeze(0).unsqueeze(0)
|
100 |
+
return mask
|
101 |
+
|
102 |
+
|
103 |
+
@torch.jit.script
|
104 |
+
def fused_add_tanh_sigmoid_multiply(input_a, input_b, n_channels):
|
105 |
+
n_channels_int = n_channels[0]
|
106 |
+
in_act = input_a + input_b
|
107 |
+
t_act = torch.tanh(in_act[:, :n_channels_int, :])
|
108 |
+
s_act = torch.sigmoid(in_act[:, n_channels_int:, :])
|
109 |
+
acts = t_act * s_act
|
110 |
+
return acts
|
111 |
+
|
112 |
+
|
113 |
+
def convert_pad_shape(pad_shape):
|
114 |
+
l = pad_shape[::-1]
|
115 |
+
pad_shape = [item for sublist in l for item in sublist]
|
116 |
+
return pad_shape
|
117 |
+
|
118 |
+
|
119 |
+
def shift_1d(x):
|
120 |
+
x = F.pad(x, convert_pad_shape([[0, 0], [0, 0], [1, 0]]))[:, :, :-1]
|
121 |
+
return x
|
122 |
+
|
123 |
+
|
124 |
+
def sequence_mask(length, max_length=None):
|
125 |
+
if max_length is None:
|
126 |
+
max_length = length.max()
|
127 |
+
x = torch.arange(max_length, dtype=length.dtype, device=length.device)
|
128 |
+
return x.unsqueeze(0) < length.unsqueeze(1)
|
129 |
+
|
130 |
+
|
131 |
+
def generate_path(duration, mask):
|
132 |
+
"""
|
133 |
+
duration: [b, 1, t_x]
|
134 |
+
mask: [b, 1, t_y, t_x]
|
135 |
+
"""
|
136 |
+
device = duration.device
|
137 |
+
|
138 |
+
b, _, t_y, t_x = mask.shape
|
139 |
+
cum_duration = torch.cumsum(duration, -1)
|
140 |
+
|
141 |
+
cum_duration_flat = cum_duration.view(b * t_x)
|
142 |
+
path = sequence_mask(cum_duration_flat, t_y).to(mask.dtype)
|
143 |
+
path = path.view(b, t_x, t_y)
|
144 |
+
path = path - F.pad(path, convert_pad_shape([[0, 0], [1, 0], [0, 0]]))[:, :-1]
|
145 |
+
path = path.unsqueeze(1).transpose(2, 3) * mask
|
146 |
+
return path
|
147 |
+
|
148 |
+
|
149 |
+
def clip_grad_value_(parameters, clip_value, norm_type=2):
|
150 |
+
if isinstance(parameters, torch.Tensor):
|
151 |
+
parameters = [parameters]
|
152 |
+
parameters = list(filter(lambda p: p.grad is not None, parameters))
|
153 |
+
norm_type = float(norm_type)
|
154 |
+
if clip_value is not None:
|
155 |
+
clip_value = float(clip_value)
|
156 |
+
|
157 |
+
total_norm = 0
|
158 |
+
for p in parameters:
|
159 |
+
param_norm = p.grad.data.norm(norm_type)
|
160 |
+
total_norm += param_norm.item() ** norm_type
|
161 |
+
if clip_value is not None:
|
162 |
+
p.grad.data.clamp_(min=-clip_value, max=clip_value)
|
163 |
+
total_norm = total_norm ** (1.0 / norm_type)
|
164 |
+
return total_norm
|
lib/infer_libs/infer_pack/models.py
ADDED
@@ -0,0 +1,1174 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import math
|
2 |
+
import logging
|
3 |
+
|
4 |
+
logger = logging.getLogger(__name__)
|
5 |
+
|
6 |
+
import numpy as np
|
7 |
+
import torch
|
8 |
+
from torch import nn
|
9 |
+
from torch.nn import Conv1d, Conv2d, ConvTranspose1d
|
10 |
+
from torch.nn import functional as F
|
11 |
+
from torch.nn.utils import remove_weight_norm, spectral_norm, weight_norm
|
12 |
+
|
13 |
+
from lib.infer_libs.infer_pack import attentions, commons, modules
|
14 |
+
from lib.infer_libs.infer_pack.commons import get_padding, init_weights
|
15 |
+
has_xpu = bool(hasattr(torch, "xpu") and torch.xpu.is_available())
|
16 |
+
|
17 |
+
class TextEncoder256(nn.Module):
|
18 |
+
def __init__(
|
19 |
+
self,
|
20 |
+
out_channels,
|
21 |
+
hidden_channels,
|
22 |
+
filter_channels,
|
23 |
+
n_heads,
|
24 |
+
n_layers,
|
25 |
+
kernel_size,
|
26 |
+
p_dropout,
|
27 |
+
f0=True,
|
28 |
+
):
|
29 |
+
super().__init__()
|
30 |
+
self.out_channels = out_channels
|
31 |
+
self.hidden_channels = hidden_channels
|
32 |
+
self.filter_channels = filter_channels
|
33 |
+
self.n_heads = n_heads
|
34 |
+
self.n_layers = n_layers
|
35 |
+
self.kernel_size = kernel_size
|
36 |
+
self.p_dropout = p_dropout
|
37 |
+
self.emb_phone = nn.Linear(256, hidden_channels)
|
38 |
+
self.lrelu = nn.LeakyReLU(0.1, inplace=True)
|
39 |
+
if f0 == True:
|
40 |
+
self.emb_pitch = nn.Embedding(256, hidden_channels) # pitch 256
|
41 |
+
self.encoder = attentions.Encoder(
|
42 |
+
hidden_channels, filter_channels, n_heads, n_layers, kernel_size, p_dropout
|
43 |
+
)
|
44 |
+
self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1)
|
45 |
+
|
46 |
+
def forward(self, phone, pitch, lengths):
|
47 |
+
if pitch == None:
|
48 |
+
x = self.emb_phone(phone)
|
49 |
+
else:
|
50 |
+
x = self.emb_phone(phone) + self.emb_pitch(pitch)
|
51 |
+
x = x * math.sqrt(self.hidden_channels) # [b, t, h]
|
52 |
+
x = self.lrelu(x)
|
53 |
+
x = torch.transpose(x, 1, -1) # [b, h, t]
|
54 |
+
x_mask = torch.unsqueeze(commons.sequence_mask(lengths, x.size(2)), 1).to(
|
55 |
+
x.dtype
|
56 |
+
)
|
57 |
+
x = self.encoder(x * x_mask, x_mask)
|
58 |
+
stats = self.proj(x) * x_mask
|
59 |
+
|
60 |
+
m, logs = torch.split(stats, self.out_channels, dim=1)
|
61 |
+
return m, logs, x_mask
|
62 |
+
|
63 |
+
|
64 |
+
class TextEncoder768(nn.Module):
|
65 |
+
def __init__(
|
66 |
+
self,
|
67 |
+
out_channels,
|
68 |
+
hidden_channels,
|
69 |
+
filter_channels,
|
70 |
+
n_heads,
|
71 |
+
n_layers,
|
72 |
+
kernel_size,
|
73 |
+
p_dropout,
|
74 |
+
f0=True,
|
75 |
+
):
|
76 |
+
super().__init__()
|
77 |
+
self.out_channels = out_channels
|
78 |
+
self.hidden_channels = hidden_channels
|
79 |
+
self.filter_channels = filter_channels
|
80 |
+
self.n_heads = n_heads
|
81 |
+
self.n_layers = n_layers
|
82 |
+
self.kernel_size = kernel_size
|
83 |
+
self.p_dropout = p_dropout
|
84 |
+
self.emb_phone = nn.Linear(768, hidden_channels)
|
85 |
+
self.lrelu = nn.LeakyReLU(0.1, inplace=True)
|
86 |
+
if f0 == True:
|
87 |
+
self.emb_pitch = nn.Embedding(256, hidden_channels) # pitch 256
|
88 |
+
self.encoder = attentions.Encoder(
|
89 |
+
hidden_channels, filter_channels, n_heads, n_layers, kernel_size, p_dropout
|
90 |
+
)
|
91 |
+
self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1)
|
92 |
+
|
93 |
+
def forward(self, phone, pitch, lengths):
|
94 |
+
if pitch == None:
|
95 |
+
x = self.emb_phone(phone)
|
96 |
+
else:
|
97 |
+
x = self.emb_phone(phone) + self.emb_pitch(pitch)
|
98 |
+
x = x * math.sqrt(self.hidden_channels) # [b, t, h]
|
99 |
+
x = self.lrelu(x)
|
100 |
+
x = torch.transpose(x, 1, -1) # [b, h, t]
|
101 |
+
x_mask = torch.unsqueeze(commons.sequence_mask(lengths, x.size(2)), 1).to(
|
102 |
+
x.dtype
|
103 |
+
)
|
104 |
+
x = self.encoder(x * x_mask, x_mask)
|
105 |
+
stats = self.proj(x) * x_mask
|
106 |
+
|
107 |
+
m, logs = torch.split(stats, self.out_channels, dim=1)
|
108 |
+
return m, logs, x_mask
|
109 |
+
|
110 |
+
|
111 |
+
class ResidualCouplingBlock(nn.Module):
|
112 |
+
def __init__(
|
113 |
+
self,
|
114 |
+
channels,
|
115 |
+
hidden_channels,
|
116 |
+
kernel_size,
|
117 |
+
dilation_rate,
|
118 |
+
n_layers,
|
119 |
+
n_flows=4,
|
120 |
+
gin_channels=0,
|
121 |
+
):
|
122 |
+
super().__init__()
|
123 |
+
self.channels = channels
|
124 |
+
self.hidden_channels = hidden_channels
|
125 |
+
self.kernel_size = kernel_size
|
126 |
+
self.dilation_rate = dilation_rate
|
127 |
+
self.n_layers = n_layers
|
128 |
+
self.n_flows = n_flows
|
129 |
+
self.gin_channels = gin_channels
|
130 |
+
|
131 |
+
self.flows = nn.ModuleList()
|
132 |
+
for i in range(n_flows):
|
133 |
+
self.flows.append(
|
134 |
+
modules.ResidualCouplingLayer(
|
135 |
+
channels,
|
136 |
+
hidden_channels,
|
137 |
+
kernel_size,
|
138 |
+
dilation_rate,
|
139 |
+
n_layers,
|
140 |
+
gin_channels=gin_channels,
|
141 |
+
mean_only=True,
|
142 |
+
)
|
143 |
+
)
|
144 |
+
self.flows.append(modules.Flip())
|
145 |
+
|
146 |
+
def forward(self, x, x_mask, g=None, reverse=False):
|
147 |
+
if not reverse:
|
148 |
+
for flow in self.flows:
|
149 |
+
x, _ = flow(x, x_mask, g=g, reverse=reverse)
|
150 |
+
else:
|
151 |
+
for flow in reversed(self.flows):
|
152 |
+
x = flow(x, x_mask, g=g, reverse=reverse)
|
153 |
+
return x
|
154 |
+
|
155 |
+
def remove_weight_norm(self):
|
156 |
+
for i in range(self.n_flows):
|
157 |
+
self.flows[i * 2].remove_weight_norm()
|
158 |
+
|
159 |
+
|
160 |
+
class PosteriorEncoder(nn.Module):
|
161 |
+
def __init__(
|
162 |
+
self,
|
163 |
+
in_channels,
|
164 |
+
out_channels,
|
165 |
+
hidden_channels,
|
166 |
+
kernel_size,
|
167 |
+
dilation_rate,
|
168 |
+
n_layers,
|
169 |
+
gin_channels=0,
|
170 |
+
):
|
171 |
+
super().__init__()
|
172 |
+
self.in_channels = in_channels
|
173 |
+
self.out_channels = out_channels
|
174 |
+
self.hidden_channels = hidden_channels
|
175 |
+
self.kernel_size = kernel_size
|
176 |
+
self.dilation_rate = dilation_rate
|
177 |
+
self.n_layers = n_layers
|
178 |
+
self.gin_channels = gin_channels
|
179 |
+
|
180 |
+
self.pre = nn.Conv1d(in_channels, hidden_channels, 1)
|
181 |
+
self.enc = modules.WN(
|
182 |
+
hidden_channels,
|
183 |
+
kernel_size,
|
184 |
+
dilation_rate,
|
185 |
+
n_layers,
|
186 |
+
gin_channels=gin_channels,
|
187 |
+
)
|
188 |
+
self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1)
|
189 |
+
|
190 |
+
def forward(self, x, x_lengths, g=None):
|
191 |
+
x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to(
|
192 |
+
x.dtype
|
193 |
+
)
|
194 |
+
x = self.pre(x) * x_mask
|
195 |
+
x = self.enc(x, x_mask, g=g)
|
196 |
+
stats = self.proj(x) * x_mask
|
197 |
+
m, logs = torch.split(stats, self.out_channels, dim=1)
|
198 |
+
z = (m + torch.randn_like(m) * torch.exp(logs)) * x_mask
|
199 |
+
return z, m, logs, x_mask
|
200 |
+
|
201 |
+
def remove_weight_norm(self):
|
202 |
+
self.enc.remove_weight_norm()
|
203 |
+
|
204 |
+
|
205 |
+
class Generator(torch.nn.Module):
|
206 |
+
def __init__(
|
207 |
+
self,
|
208 |
+
initial_channel,
|
209 |
+
resblock,
|
210 |
+
resblock_kernel_sizes,
|
211 |
+
resblock_dilation_sizes,
|
212 |
+
upsample_rates,
|
213 |
+
upsample_initial_channel,
|
214 |
+
upsample_kernel_sizes,
|
215 |
+
gin_channels=0,
|
216 |
+
):
|
217 |
+
super(Generator, self).__init__()
|
218 |
+
self.num_kernels = len(resblock_kernel_sizes)
|
219 |
+
self.num_upsamples = len(upsample_rates)
|
220 |
+
self.conv_pre = Conv1d(
|
221 |
+
initial_channel, upsample_initial_channel, 7, 1, padding=3
|
222 |
+
)
|
223 |
+
resblock = modules.ResBlock1 if resblock == "1" else modules.ResBlock2
|
224 |
+
|
225 |
+
self.ups = nn.ModuleList()
|
226 |
+
for i, (u, k) in enumerate(zip(upsample_rates, upsample_kernel_sizes)):
|
227 |
+
self.ups.append(
|
228 |
+
weight_norm(
|
229 |
+
ConvTranspose1d(
|
230 |
+
upsample_initial_channel // (2**i),
|
231 |
+
upsample_initial_channel // (2 ** (i + 1)),
|
232 |
+
k,
|
233 |
+
u,
|
234 |
+
padding=(k - u) // 2,
|
235 |
+
)
|
236 |
+
)
|
237 |
+
)
|
238 |
+
|
239 |
+
self.resblocks = nn.ModuleList()
|
240 |
+
for i in range(len(self.ups)):
|
241 |
+
ch = upsample_initial_channel // (2 ** (i + 1))
|
242 |
+
for j, (k, d) in enumerate(
|
243 |
+
zip(resblock_kernel_sizes, resblock_dilation_sizes)
|
244 |
+
):
|
245 |
+
self.resblocks.append(resblock(ch, k, d))
|
246 |
+
|
247 |
+
self.conv_post = Conv1d(ch, 1, 7, 1, padding=3, bias=False)
|
248 |
+
self.ups.apply(init_weights)
|
249 |
+
|
250 |
+
if gin_channels != 0:
|
251 |
+
self.cond = nn.Conv1d(gin_channels, upsample_initial_channel, 1)
|
252 |
+
|
253 |
+
def forward(self, x, g=None):
|
254 |
+
x = self.conv_pre(x)
|
255 |
+
if g is not None:
|
256 |
+
x = x + self.cond(g)
|
257 |
+
|
258 |
+
for i in range(self.num_upsamples):
|
259 |
+
x = F.leaky_relu(x, modules.LRELU_SLOPE)
|
260 |
+
x = self.ups[i](x)
|
261 |
+
xs = None
|
262 |
+
for j in range(self.num_kernels):
|
263 |
+
if xs is None:
|
264 |
+
xs = self.resblocks[i * self.num_kernels + j](x)
|
265 |
+
else:
|
266 |
+
xs += self.resblocks[i * self.num_kernels + j](x)
|
267 |
+
x = xs / self.num_kernels
|
268 |
+
x = F.leaky_relu(x)
|
269 |
+
x = self.conv_post(x)
|
270 |
+
x = torch.tanh(x)
|
271 |
+
|
272 |
+
return x
|
273 |
+
|
274 |
+
def remove_weight_norm(self):
|
275 |
+
for l in self.ups:
|
276 |
+
remove_weight_norm(l)
|
277 |
+
for l in self.resblocks:
|
278 |
+
l.remove_weight_norm()
|
279 |
+
|
280 |
+
|
281 |
+
class SineGen(torch.nn.Module):
|
282 |
+
"""Definition of sine generator
|
283 |
+
SineGen(samp_rate, harmonic_num = 0,
|
284 |
+
sine_amp = 0.1, noise_std = 0.003,
|
285 |
+
voiced_threshold = 0,
|
286 |
+
flag_for_pulse=False)
|
287 |
+
samp_rate: sampling rate in Hz
|
288 |
+
harmonic_num: number of harmonic overtones (default 0)
|
289 |
+
sine_amp: amplitude of sine-wavefrom (default 0.1)
|
290 |
+
noise_std: std of Gaussian noise (default 0.003)
|
291 |
+
voiced_thoreshold: F0 threshold for U/V classification (default 0)
|
292 |
+
flag_for_pulse: this SinGen is used inside PulseGen (default False)
|
293 |
+
Note: when flag_for_pulse is True, the first time step of a voiced
|
294 |
+
segment is always sin(np.pi) or cos(0)
|
295 |
+
"""
|
296 |
+
|
297 |
+
def __init__(
|
298 |
+
self,
|
299 |
+
samp_rate,
|
300 |
+
harmonic_num=0,
|
301 |
+
sine_amp=0.1,
|
302 |
+
noise_std=0.003,
|
303 |
+
voiced_threshold=0,
|
304 |
+
flag_for_pulse=False,
|
305 |
+
):
|
306 |
+
super(SineGen, self).__init__()
|
307 |
+
self.sine_amp = sine_amp
|
308 |
+
self.noise_std = noise_std
|
309 |
+
self.harmonic_num = harmonic_num
|
310 |
+
self.dim = self.harmonic_num + 1
|
311 |
+
self.sampling_rate = samp_rate
|
312 |
+
self.voiced_threshold = voiced_threshold
|
313 |
+
|
314 |
+
def _f02uv(self, f0):
|
315 |
+
# generate uv signal
|
316 |
+
uv = torch.ones_like(f0)
|
317 |
+
uv = uv * (f0 > self.voiced_threshold)
|
318 |
+
if uv.device.type == "privateuseone": # for DirectML
|
319 |
+
uv = uv.float()
|
320 |
+
return uv
|
321 |
+
|
322 |
+
def forward(self, f0, upp):
|
323 |
+
"""sine_tensor, uv = forward(f0)
|
324 |
+
input F0: tensor(batchsize=1, length, dim=1)
|
325 |
+
f0 for unvoiced steps should be 0
|
326 |
+
output sine_tensor: tensor(batchsize=1, length, dim)
|
327 |
+
output uv: tensor(batchsize=1, length, 1)
|
328 |
+
"""
|
329 |
+
with torch.no_grad():
|
330 |
+
f0 = f0[:, None].transpose(1, 2)
|
331 |
+
f0_buf = torch.zeros(f0.shape[0], f0.shape[1], self.dim, device=f0.device)
|
332 |
+
# fundamental component
|
333 |
+
f0_buf[:, :, 0] = f0[:, :, 0]
|
334 |
+
for idx in np.arange(self.harmonic_num):
|
335 |
+
f0_buf[:, :, idx + 1] = f0_buf[:, :, 0] * (
|
336 |
+
idx + 2
|
337 |
+
) # idx + 2: the (idx+1)-th overtone, (idx+2)-th harmonic
|
338 |
+
rad_values = (f0_buf / self.sampling_rate) % 1 ###%1意味着n_har的乘积无法后处理优化
|
339 |
+
rand_ini = torch.rand(
|
340 |
+
f0_buf.shape[0], f0_buf.shape[2], device=f0_buf.device
|
341 |
+
)
|
342 |
+
rand_ini[:, 0] = 0
|
343 |
+
rad_values[:, 0, :] = rad_values[:, 0, :] + rand_ini
|
344 |
+
tmp_over_one = torch.cumsum(rad_values, 1) # % 1 #####%1意味着后面的cumsum无法再优化
|
345 |
+
tmp_over_one *= upp
|
346 |
+
tmp_over_one = F.interpolate(
|
347 |
+
tmp_over_one.transpose(2, 1),
|
348 |
+
scale_factor=upp,
|
349 |
+
mode="linear",
|
350 |
+
align_corners=True,
|
351 |
+
).transpose(2, 1)
|
352 |
+
rad_values = F.interpolate(
|
353 |
+
rad_values.transpose(2, 1), scale_factor=upp, mode="nearest"
|
354 |
+
).transpose(
|
355 |
+
2, 1
|
356 |
+
) #######
|
357 |
+
tmp_over_one %= 1
|
358 |
+
tmp_over_one_idx = (tmp_over_one[:, 1:, :] - tmp_over_one[:, :-1, :]) < 0
|
359 |
+
cumsum_shift = torch.zeros_like(rad_values)
|
360 |
+
cumsum_shift[:, 1:, :] = tmp_over_one_idx * -1.0
|
361 |
+
sine_waves = torch.sin(
|
362 |
+
torch.cumsum(rad_values + cumsum_shift, dim=1) * 2 * np.pi
|
363 |
+
)
|
364 |
+
sine_waves = sine_waves * self.sine_amp
|
365 |
+
uv = self._f02uv(f0)
|
366 |
+
uv = F.interpolate(
|
367 |
+
uv.transpose(2, 1), scale_factor=upp, mode="nearest"
|
368 |
+
).transpose(2, 1)
|
369 |
+
noise_amp = uv * self.noise_std + (1 - uv) * self.sine_amp / 3
|
370 |
+
noise = noise_amp * torch.randn_like(sine_waves)
|
371 |
+
sine_waves = sine_waves * uv + noise
|
372 |
+
return sine_waves, uv, noise
|
373 |
+
|
374 |
+
|
375 |
+
class SourceModuleHnNSF(torch.nn.Module):
|
376 |
+
"""SourceModule for hn-nsf
|
377 |
+
SourceModule(sampling_rate, harmonic_num=0, sine_amp=0.1,
|
378 |
+
add_noise_std=0.003, voiced_threshod=0)
|
379 |
+
sampling_rate: sampling_rate in Hz
|
380 |
+
harmonic_num: number of harmonic above F0 (default: 0)
|
381 |
+
sine_amp: amplitude of sine source signal (default: 0.1)
|
382 |
+
add_noise_std: std of additive Gaussian noise (default: 0.003)
|
383 |
+
note that amplitude of noise in unvoiced is decided
|
384 |
+
by sine_amp
|
385 |
+
voiced_threshold: threhold to set U/V given F0 (default: 0)
|
386 |
+
Sine_source, noise_source = SourceModuleHnNSF(F0_sampled)
|
387 |
+
F0_sampled (batchsize, length, 1)
|
388 |
+
Sine_source (batchsize, length, 1)
|
389 |
+
noise_source (batchsize, length 1)
|
390 |
+
uv (batchsize, length, 1)
|
391 |
+
"""
|
392 |
+
|
393 |
+
def __init__(
|
394 |
+
self,
|
395 |
+
sampling_rate,
|
396 |
+
harmonic_num=0,
|
397 |
+
sine_amp=0.1,
|
398 |
+
add_noise_std=0.003,
|
399 |
+
voiced_threshod=0,
|
400 |
+
is_half=True,
|
401 |
+
):
|
402 |
+
super(SourceModuleHnNSF, self).__init__()
|
403 |
+
|
404 |
+
self.sine_amp = sine_amp
|
405 |
+
self.noise_std = add_noise_std
|
406 |
+
self.is_half = is_half
|
407 |
+
# to produce sine waveforms
|
408 |
+
self.l_sin_gen = SineGen(
|
409 |
+
sampling_rate, harmonic_num, sine_amp, add_noise_std, voiced_threshod
|
410 |
+
)
|
411 |
+
|
412 |
+
# to merge source harmonics into a single excitation
|
413 |
+
self.l_linear = torch.nn.Linear(harmonic_num + 1, 1)
|
414 |
+
self.l_tanh = torch.nn.Tanh()
|
415 |
+
|
416 |
+
def forward(self, x, upp=None):
|
417 |
+
if hasattr(self, "ddtype") == False:
|
418 |
+
self.ddtype = self.l_linear.weight.dtype
|
419 |
+
sine_wavs, uv, _ = self.l_sin_gen(x, upp)
|
420 |
+
# print(x.dtype,sine_wavs.dtype,self.l_linear.weight.dtype)
|
421 |
+
# if self.is_half:
|
422 |
+
# sine_wavs = sine_wavs.half()
|
423 |
+
# sine_merge = self.l_tanh(self.l_linear(sine_wavs.to(x)))
|
424 |
+
# print(sine_wavs.dtype,self.ddtype)
|
425 |
+
if sine_wavs.dtype != self.ddtype:
|
426 |
+
sine_wavs = sine_wavs.to(self.ddtype)
|
427 |
+
sine_merge = self.l_tanh(self.l_linear(sine_wavs))
|
428 |
+
return sine_merge, None, None # noise, uv
|
429 |
+
|
430 |
+
|
431 |
+
class GeneratorNSF(torch.nn.Module):
|
432 |
+
def __init__(
|
433 |
+
self,
|
434 |
+
initial_channel,
|
435 |
+
resblock,
|
436 |
+
resblock_kernel_sizes,
|
437 |
+
resblock_dilation_sizes,
|
438 |
+
upsample_rates,
|
439 |
+
upsample_initial_channel,
|
440 |
+
upsample_kernel_sizes,
|
441 |
+
gin_channels,
|
442 |
+
sr,
|
443 |
+
is_half=False,
|
444 |
+
):
|
445 |
+
super(GeneratorNSF, self).__init__()
|
446 |
+
self.num_kernels = len(resblock_kernel_sizes)
|
447 |
+
self.num_upsamples = len(upsample_rates)
|
448 |
+
|
449 |
+
self.f0_upsamp = torch.nn.Upsample(scale_factor=np.prod(upsample_rates))
|
450 |
+
self.m_source = SourceModuleHnNSF(
|
451 |
+
sampling_rate=sr, harmonic_num=0, is_half=is_half
|
452 |
+
)
|
453 |
+
self.noise_convs = nn.ModuleList()
|
454 |
+
self.conv_pre = Conv1d(
|
455 |
+
initial_channel, upsample_initial_channel, 7, 1, padding=3
|
456 |
+
)
|
457 |
+
resblock = modules.ResBlock1 if resblock == "1" else modules.ResBlock2
|
458 |
+
|
459 |
+
self.ups = nn.ModuleList()
|
460 |
+
for i, (u, k) in enumerate(zip(upsample_rates, upsample_kernel_sizes)):
|
461 |
+
c_cur = upsample_initial_channel // (2 ** (i + 1))
|
462 |
+
self.ups.append(
|
463 |
+
weight_norm(
|
464 |
+
ConvTranspose1d(
|
465 |
+
upsample_initial_channel // (2**i),
|
466 |
+
upsample_initial_channel // (2 ** (i + 1)),
|
467 |
+
k,
|
468 |
+
u,
|
469 |
+
padding=(k - u) // 2,
|
470 |
+
)
|
471 |
+
)
|
472 |
+
)
|
473 |
+
if i + 1 < len(upsample_rates):
|
474 |
+
stride_f0 = np.prod(upsample_rates[i + 1 :])
|
475 |
+
self.noise_convs.append(
|
476 |
+
Conv1d(
|
477 |
+
1,
|
478 |
+
c_cur,
|
479 |
+
kernel_size=stride_f0 * 2,
|
480 |
+
stride=stride_f0,
|
481 |
+
padding=stride_f0 // 2,
|
482 |
+
)
|
483 |
+
)
|
484 |
+
else:
|
485 |
+
self.noise_convs.append(Conv1d(1, c_cur, kernel_size=1))
|
486 |
+
|
487 |
+
self.resblocks = nn.ModuleList()
|
488 |
+
for i in range(len(self.ups)):
|
489 |
+
ch = upsample_initial_channel // (2 ** (i + 1))
|
490 |
+
for j, (k, d) in enumerate(
|
491 |
+
zip(resblock_kernel_sizes, resblock_dilation_sizes)
|
492 |
+
):
|
493 |
+
self.resblocks.append(resblock(ch, k, d))
|
494 |
+
|
495 |
+
self.conv_post = Conv1d(ch, 1, 7, 1, padding=3, bias=False)
|
496 |
+
self.ups.apply(init_weights)
|
497 |
+
|
498 |
+
if gin_channels != 0:
|
499 |
+
self.cond = nn.Conv1d(gin_channels, upsample_initial_channel, 1)
|
500 |
+
|
501 |
+
self.upp = np.prod(upsample_rates)
|
502 |
+
|
503 |
+
def forward(self, x, f0, g=None):
|
504 |
+
har_source, noi_source, uv = self.m_source(f0, self.upp)
|
505 |
+
har_source = har_source.transpose(1, 2)
|
506 |
+
x = self.conv_pre(x)
|
507 |
+
if g is not None:
|
508 |
+
x = x + self.cond(g)
|
509 |
+
|
510 |
+
for i in range(self.num_upsamples):
|
511 |
+
x = F.leaky_relu(x, modules.LRELU_SLOPE)
|
512 |
+
x = self.ups[i](x)
|
513 |
+
x_source = self.noise_convs[i](har_source)
|
514 |
+
x = x + x_source
|
515 |
+
xs = None
|
516 |
+
for j in range(self.num_kernels):
|
517 |
+
if xs is None:
|
518 |
+
xs = self.resblocks[i * self.num_kernels + j](x)
|
519 |
+
else:
|
520 |
+
xs += self.resblocks[i * self.num_kernels + j](x)
|
521 |
+
x = xs / self.num_kernels
|
522 |
+
x = F.leaky_relu(x)
|
523 |
+
x = self.conv_post(x)
|
524 |
+
x = torch.tanh(x)
|
525 |
+
return x
|
526 |
+
|
527 |
+
def remove_weight_norm(self):
|
528 |
+
for l in self.ups:
|
529 |
+
remove_weight_norm(l)
|
530 |
+
for l in self.resblocks:
|
531 |
+
l.remove_weight_norm()
|
532 |
+
|
533 |
+
|
534 |
+
sr2sr = {
|
535 |
+
"32k": 32000,
|
536 |
+
"40k": 40000,
|
537 |
+
"48k": 48000,
|
538 |
+
}
|
539 |
+
|
540 |
+
|
541 |
+
class SynthesizerTrnMs256NSFsid(nn.Module):
|
542 |
+
def __init__(
|
543 |
+
self,
|
544 |
+
spec_channels,
|
545 |
+
segment_size,
|
546 |
+
inter_channels,
|
547 |
+
hidden_channels,
|
548 |
+
filter_channels,
|
549 |
+
n_heads,
|
550 |
+
n_layers,
|
551 |
+
kernel_size,
|
552 |
+
p_dropout,
|
553 |
+
resblock,
|
554 |
+
resblock_kernel_sizes,
|
555 |
+
resblock_dilation_sizes,
|
556 |
+
upsample_rates,
|
557 |
+
upsample_initial_channel,
|
558 |
+
upsample_kernel_sizes,
|
559 |
+
spk_embed_dim,
|
560 |
+
gin_channels,
|
561 |
+
sr,
|
562 |
+
**kwargs
|
563 |
+
):
|
564 |
+
super().__init__()
|
565 |
+
if type(sr) == type("strr"):
|
566 |
+
sr = sr2sr[sr]
|
567 |
+
self.spec_channels = spec_channels
|
568 |
+
self.inter_channels = inter_channels
|
569 |
+
self.hidden_channels = hidden_channels
|
570 |
+
self.filter_channels = filter_channels
|
571 |
+
self.n_heads = n_heads
|
572 |
+
self.n_layers = n_layers
|
573 |
+
self.kernel_size = kernel_size
|
574 |
+
self.p_dropout = p_dropout
|
575 |
+
self.resblock = resblock
|
576 |
+
self.resblock_kernel_sizes = resblock_kernel_sizes
|
577 |
+
self.resblock_dilation_sizes = resblock_dilation_sizes
|
578 |
+
self.upsample_rates = upsample_rates
|
579 |
+
self.upsample_initial_channel = upsample_initial_channel
|
580 |
+
self.upsample_kernel_sizes = upsample_kernel_sizes
|
581 |
+
self.segment_size = segment_size
|
582 |
+
self.gin_channels = gin_channels
|
583 |
+
# self.hop_length = hop_length#
|
584 |
+
self.spk_embed_dim = spk_embed_dim
|
585 |
+
self.enc_p = TextEncoder256(
|
586 |
+
inter_channels,
|
587 |
+
hidden_channels,
|
588 |
+
filter_channels,
|
589 |
+
n_heads,
|
590 |
+
n_layers,
|
591 |
+
kernel_size,
|
592 |
+
p_dropout,
|
593 |
+
)
|
594 |
+
self.dec = GeneratorNSF(
|
595 |
+
inter_channels,
|
596 |
+
resblock,
|
597 |
+
resblock_kernel_sizes,
|
598 |
+
resblock_dilation_sizes,
|
599 |
+
upsample_rates,
|
600 |
+
upsample_initial_channel,
|
601 |
+
upsample_kernel_sizes,
|
602 |
+
gin_channels=gin_channels,
|
603 |
+
sr=sr,
|
604 |
+
is_half=kwargs["is_half"],
|
605 |
+
)
|
606 |
+
self.enc_q = PosteriorEncoder(
|
607 |
+
spec_channels,
|
608 |
+
inter_channels,
|
609 |
+
hidden_channels,
|
610 |
+
5,
|
611 |
+
1,
|
612 |
+
16,
|
613 |
+
gin_channels=gin_channels,
|
614 |
+
)
|
615 |
+
self.flow = ResidualCouplingBlock(
|
616 |
+
inter_channels, hidden_channels, 5, 1, 3, gin_channels=gin_channels
|
617 |
+
)
|
618 |
+
self.emb_g = nn.Embedding(self.spk_embed_dim, gin_channels)
|
619 |
+
logger.debug(
|
620 |
+
"gin_channels: "
|
621 |
+
+ str(gin_channels)
|
622 |
+
+ ", self.spk_embed_dim: "
|
623 |
+
+ str(self.spk_embed_dim)
|
624 |
+
)
|
625 |
+
|
626 |
+
def remove_weight_norm(self):
|
627 |
+
self.dec.remove_weight_norm()
|
628 |
+
self.flow.remove_weight_norm()
|
629 |
+
self.enc_q.remove_weight_norm()
|
630 |
+
|
631 |
+
def forward(
|
632 |
+
self, phone, phone_lengths, pitch, pitchf, y, y_lengths, ds
|
633 |
+
): # 这里ds是id,[bs,1]
|
634 |
+
# print(1,pitch.shape)#[bs,t]
|
635 |
+
g = self.emb_g(ds).unsqueeze(-1) # [b, 256, 1]##1是t,广播的
|
636 |
+
m_p, logs_p, x_mask = self.enc_p(phone, pitch, phone_lengths)
|
637 |
+
z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g)
|
638 |
+
z_p = self.flow(z, y_mask, g=g)
|
639 |
+
z_slice, ids_slice = commons.rand_slice_segments(
|
640 |
+
z, y_lengths, self.segment_size
|
641 |
+
)
|
642 |
+
# print(-1,pitchf.shape,ids_slice,self.segment_size,self.hop_length,self.segment_size//self.hop_length)
|
643 |
+
pitchf = commons.slice_segments2(pitchf, ids_slice, self.segment_size)
|
644 |
+
# print(-2,pitchf.shape,z_slice.shape)
|
645 |
+
o = self.dec(z_slice, pitchf, g=g)
|
646 |
+
return o, ids_slice, x_mask, y_mask, (z, z_p, m_p, logs_p, m_q, logs_q)
|
647 |
+
|
648 |
+
def infer(self, phone, phone_lengths, pitch, nsff0, sid, rate=None):
|
649 |
+
g = self.emb_g(sid).unsqueeze(-1)
|
650 |
+
m_p, logs_p, x_mask = self.enc_p(phone, pitch, phone_lengths)
|
651 |
+
z_p = (m_p + torch.exp(logs_p) * torch.randn_like(m_p) * 0.66666) * x_mask
|
652 |
+
if rate:
|
653 |
+
head = int(z_p.shape[2] * rate)
|
654 |
+
z_p = z_p[:, :, -head:]
|
655 |
+
x_mask = x_mask[:, :, -head:]
|
656 |
+
nsff0 = nsff0[:, -head:]
|
657 |
+
z = self.flow(z_p, x_mask, g=g, reverse=True)
|
658 |
+
o = self.dec(z * x_mask, nsff0, g=g)
|
659 |
+
return o, x_mask, (z, z_p, m_p, logs_p)
|
660 |
+
|
661 |
+
|
662 |
+
class SynthesizerTrnMs768NSFsid(nn.Module):
|
663 |
+
def __init__(
|
664 |
+
self,
|
665 |
+
spec_channels,
|
666 |
+
segment_size,
|
667 |
+
inter_channels,
|
668 |
+
hidden_channels,
|
669 |
+
filter_channels,
|
670 |
+
n_heads,
|
671 |
+
n_layers,
|
672 |
+
kernel_size,
|
673 |
+
p_dropout,
|
674 |
+
resblock,
|
675 |
+
resblock_kernel_sizes,
|
676 |
+
resblock_dilation_sizes,
|
677 |
+
upsample_rates,
|
678 |
+
upsample_initial_channel,
|
679 |
+
upsample_kernel_sizes,
|
680 |
+
spk_embed_dim,
|
681 |
+
gin_channels,
|
682 |
+
sr,
|
683 |
+
**kwargs
|
684 |
+
):
|
685 |
+
super().__init__()
|
686 |
+
if type(sr) == type("strr"):
|
687 |
+
sr = sr2sr[sr]
|
688 |
+
self.spec_channels = spec_channels
|
689 |
+
self.inter_channels = inter_channels
|
690 |
+
self.hidden_channels = hidden_channels
|
691 |
+
self.filter_channels = filter_channels
|
692 |
+
self.n_heads = n_heads
|
693 |
+
self.n_layers = n_layers
|
694 |
+
self.kernel_size = kernel_size
|
695 |
+
self.p_dropout = p_dropout
|
696 |
+
self.resblock = resblock
|
697 |
+
self.resblock_kernel_sizes = resblock_kernel_sizes
|
698 |
+
self.resblock_dilation_sizes = resblock_dilation_sizes
|
699 |
+
self.upsample_rates = upsample_rates
|
700 |
+
self.upsample_initial_channel = upsample_initial_channel
|
701 |
+
self.upsample_kernel_sizes = upsample_kernel_sizes
|
702 |
+
self.segment_size = segment_size
|
703 |
+
self.gin_channels = gin_channels
|
704 |
+
# self.hop_length = hop_length#
|
705 |
+
self.spk_embed_dim = spk_embed_dim
|
706 |
+
self.enc_p = TextEncoder768(
|
707 |
+
inter_channels,
|
708 |
+
hidden_channels,
|
709 |
+
filter_channels,
|
710 |
+
n_heads,
|
711 |
+
n_layers,
|
712 |
+
kernel_size,
|
713 |
+
p_dropout,
|
714 |
+
)
|
715 |
+
self.dec = GeneratorNSF(
|
716 |
+
inter_channels,
|
717 |
+
resblock,
|
718 |
+
resblock_kernel_sizes,
|
719 |
+
resblock_dilation_sizes,
|
720 |
+
upsample_rates,
|
721 |
+
upsample_initial_channel,
|
722 |
+
upsample_kernel_sizes,
|
723 |
+
gin_channels=gin_channels,
|
724 |
+
sr=sr,
|
725 |
+
is_half=kwargs["is_half"],
|
726 |
+
)
|
727 |
+
self.enc_q = PosteriorEncoder(
|
728 |
+
spec_channels,
|
729 |
+
inter_channels,
|
730 |
+
hidden_channels,
|
731 |
+
5,
|
732 |
+
1,
|
733 |
+
16,
|
734 |
+
gin_channels=gin_channels,
|
735 |
+
)
|
736 |
+
self.flow = ResidualCouplingBlock(
|
737 |
+
inter_channels, hidden_channels, 5, 1, 3, gin_channels=gin_channels
|
738 |
+
)
|
739 |
+
self.emb_g = nn.Embedding(self.spk_embed_dim, gin_channels)
|
740 |
+
logger.debug(
|
741 |
+
"gin_channels: "
|
742 |
+
+ str(gin_channels)
|
743 |
+
+ ", self.spk_embed_dim: "
|
744 |
+
+ str(self.spk_embed_dim)
|
745 |
+
)
|
746 |
+
|
747 |
+
def remove_weight_norm(self):
|
748 |
+
self.dec.remove_weight_norm()
|
749 |
+
self.flow.remove_weight_norm()
|
750 |
+
self.enc_q.remove_weight_norm()
|
751 |
+
|
752 |
+
def forward(
|
753 |
+
self, phone, phone_lengths, pitch, pitchf, y, y_lengths, ds
|
754 |
+
): # 这里ds是id,[bs,1]
|
755 |
+
# print(1,pitch.shape)#[bs,t]
|
756 |
+
g = self.emb_g(ds).unsqueeze(-1) # [b, 256, 1]##1是t,广播的
|
757 |
+
m_p, logs_p, x_mask = self.enc_p(phone, pitch, phone_lengths)
|
758 |
+
z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g)
|
759 |
+
z_p = self.flow(z, y_mask, g=g)
|
760 |
+
z_slice, ids_slice = commons.rand_slice_segments(
|
761 |
+
z, y_lengths, self.segment_size
|
762 |
+
)
|
763 |
+
# print(-1,pitchf.shape,ids_slice,self.segment_size,self.hop_length,self.segment_size//self.hop_length)
|
764 |
+
pitchf = commons.slice_segments2(pitchf, ids_slice, self.segment_size)
|
765 |
+
# print(-2,pitchf.shape,z_slice.shape)
|
766 |
+
o = self.dec(z_slice, pitchf, g=g)
|
767 |
+
return o, ids_slice, x_mask, y_mask, (z, z_p, m_p, logs_p, m_q, logs_q)
|
768 |
+
|
769 |
+
def infer(self, phone, phone_lengths, pitch, nsff0, sid, rate=None):
|
770 |
+
g = self.emb_g(sid).unsqueeze(-1)
|
771 |
+
m_p, logs_p, x_mask = self.enc_p(phone, pitch, phone_lengths)
|
772 |
+
z_p = (m_p + torch.exp(logs_p) * torch.randn_like(m_p) * 0.66666) * x_mask
|
773 |
+
if rate:
|
774 |
+
head = int(z_p.shape[2] * rate)
|
775 |
+
z_p = z_p[:, :, -head:]
|
776 |
+
x_mask = x_mask[:, :, -head:]
|
777 |
+
nsff0 = nsff0[:, -head:]
|
778 |
+
z = self.flow(z_p, x_mask, g=g, reverse=True)
|
779 |
+
o = self.dec(z * x_mask, nsff0, g=g)
|
780 |
+
return o, x_mask, (z, z_p, m_p, logs_p)
|
781 |
+
|
782 |
+
|
783 |
+
class SynthesizerTrnMs256NSFsid_nono(nn.Module):
|
784 |
+
def __init__(
|
785 |
+
self,
|
786 |
+
spec_channels,
|
787 |
+
segment_size,
|
788 |
+
inter_channels,
|
789 |
+
hidden_channels,
|
790 |
+
filter_channels,
|
791 |
+
n_heads,
|
792 |
+
n_layers,
|
793 |
+
kernel_size,
|
794 |
+
p_dropout,
|
795 |
+
resblock,
|
796 |
+
resblock_kernel_sizes,
|
797 |
+
resblock_dilation_sizes,
|
798 |
+
upsample_rates,
|
799 |
+
upsample_initial_channel,
|
800 |
+
upsample_kernel_sizes,
|
801 |
+
spk_embed_dim,
|
802 |
+
gin_channels,
|
803 |
+
sr=None,
|
804 |
+
**kwargs
|
805 |
+
):
|
806 |
+
super().__init__()
|
807 |
+
self.spec_channels = spec_channels
|
808 |
+
self.inter_channels = inter_channels
|
809 |
+
self.hidden_channels = hidden_channels
|
810 |
+
self.filter_channels = filter_channels
|
811 |
+
self.n_heads = n_heads
|
812 |
+
self.n_layers = n_layers
|
813 |
+
self.kernel_size = kernel_size
|
814 |
+
self.p_dropout = p_dropout
|
815 |
+
self.resblock = resblock
|
816 |
+
self.resblock_kernel_sizes = resblock_kernel_sizes
|
817 |
+
self.resblock_dilation_sizes = resblock_dilation_sizes
|
818 |
+
self.upsample_rates = upsample_rates
|
819 |
+
self.upsample_initial_channel = upsample_initial_channel
|
820 |
+
self.upsample_kernel_sizes = upsample_kernel_sizes
|
821 |
+
self.segment_size = segment_size
|
822 |
+
self.gin_channels = gin_channels
|
823 |
+
# self.hop_length = hop_length#
|
824 |
+
self.spk_embed_dim = spk_embed_dim
|
825 |
+
self.enc_p = TextEncoder256(
|
826 |
+
inter_channels,
|
827 |
+
hidden_channels,
|
828 |
+
filter_channels,
|
829 |
+
n_heads,
|
830 |
+
n_layers,
|
831 |
+
kernel_size,
|
832 |
+
p_dropout,
|
833 |
+
f0=False,
|
834 |
+
)
|
835 |
+
self.dec = Generator(
|
836 |
+
inter_channels,
|
837 |
+
resblock,
|
838 |
+
resblock_kernel_sizes,
|
839 |
+
resblock_dilation_sizes,
|
840 |
+
upsample_rates,
|
841 |
+
upsample_initial_channel,
|
842 |
+
upsample_kernel_sizes,
|
843 |
+
gin_channels=gin_channels,
|
844 |
+
)
|
845 |
+
self.enc_q = PosteriorEncoder(
|
846 |
+
spec_channels,
|
847 |
+
inter_channels,
|
848 |
+
hidden_channels,
|
849 |
+
5,
|
850 |
+
1,
|
851 |
+
16,
|
852 |
+
gin_channels=gin_channels,
|
853 |
+
)
|
854 |
+
self.flow = ResidualCouplingBlock(
|
855 |
+
inter_channels, hidden_channels, 5, 1, 3, gin_channels=gin_channels
|
856 |
+
)
|
857 |
+
self.emb_g = nn.Embedding(self.spk_embed_dim, gin_channels)
|
858 |
+
logger.debug(
|
859 |
+
"gin_channels: "
|
860 |
+
+ str(gin_channels)
|
861 |
+
+ ", self.spk_embed_dim: "
|
862 |
+
+ str(self.spk_embed_dim)
|
863 |
+
)
|
864 |
+
|
865 |
+
def remove_weight_norm(self):
|
866 |
+
self.dec.remove_weight_norm()
|
867 |
+
self.flow.remove_weight_norm()
|
868 |
+
self.enc_q.remove_weight_norm()
|
869 |
+
|
870 |
+
def forward(self, phone, phone_lengths, y, y_lengths, ds): # 这里ds是id,[bs,1]
|
871 |
+
g = self.emb_g(ds).unsqueeze(-1) # [b, 256, 1]##1是t,广播的
|
872 |
+
m_p, logs_p, x_mask = self.enc_p(phone, None, phone_lengths)
|
873 |
+
z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g)
|
874 |
+
z_p = self.flow(z, y_mask, g=g)
|
875 |
+
z_slice, ids_slice = commons.rand_slice_segments(
|
876 |
+
z, y_lengths, self.segment_size
|
877 |
+
)
|
878 |
+
o = self.dec(z_slice, g=g)
|
879 |
+
return o, ids_slice, x_mask, y_mask, (z, z_p, m_p, logs_p, m_q, logs_q)
|
880 |
+
|
881 |
+
def infer(self, phone, phone_lengths, sid, rate=None):
|
882 |
+
g = self.emb_g(sid).unsqueeze(-1)
|
883 |
+
m_p, logs_p, x_mask = self.enc_p(phone, None, phone_lengths)
|
884 |
+
z_p = (m_p + torch.exp(logs_p) * torch.randn_like(m_p) * 0.66666) * x_mask
|
885 |
+
if rate:
|
886 |
+
head = int(z_p.shape[2] * rate)
|
887 |
+
z_p = z_p[:, :, -head:]
|
888 |
+
x_mask = x_mask[:, :, -head:]
|
889 |
+
z = self.flow(z_p, x_mask, g=g, reverse=True)
|
890 |
+
o = self.dec(z * x_mask, g=g)
|
891 |
+
return o, x_mask, (z, z_p, m_p, logs_p)
|
892 |
+
|
893 |
+
|
894 |
+
class SynthesizerTrnMs768NSFsid_nono(nn.Module):
|
895 |
+
def __init__(
|
896 |
+
self,
|
897 |
+
spec_channels,
|
898 |
+
segment_size,
|
899 |
+
inter_channels,
|
900 |
+
hidden_channels,
|
901 |
+
filter_channels,
|
902 |
+
n_heads,
|
903 |
+
n_layers,
|
904 |
+
kernel_size,
|
905 |
+
p_dropout,
|
906 |
+
resblock,
|
907 |
+
resblock_kernel_sizes,
|
908 |
+
resblock_dilation_sizes,
|
909 |
+
upsample_rates,
|
910 |
+
upsample_initial_channel,
|
911 |
+
upsample_kernel_sizes,
|
912 |
+
spk_embed_dim,
|
913 |
+
gin_channels,
|
914 |
+
sr=None,
|
915 |
+
**kwargs
|
916 |
+
):
|
917 |
+
super().__init__()
|
918 |
+
self.spec_channels = spec_channels
|
919 |
+
self.inter_channels = inter_channels
|
920 |
+
self.hidden_channels = hidden_channels
|
921 |
+
self.filter_channels = filter_channels
|
922 |
+
self.n_heads = n_heads
|
923 |
+
self.n_layers = n_layers
|
924 |
+
self.kernel_size = kernel_size
|
925 |
+
self.p_dropout = p_dropout
|
926 |
+
self.resblock = resblock
|
927 |
+
self.resblock_kernel_sizes = resblock_kernel_sizes
|
928 |
+
self.resblock_dilation_sizes = resblock_dilation_sizes
|
929 |
+
self.upsample_rates = upsample_rates
|
930 |
+
self.upsample_initial_channel = upsample_initial_channel
|
931 |
+
self.upsample_kernel_sizes = upsample_kernel_sizes
|
932 |
+
self.segment_size = segment_size
|
933 |
+
self.gin_channels = gin_channels
|
934 |
+
# self.hop_length = hop_length#
|
935 |
+
self.spk_embed_dim = spk_embed_dim
|
936 |
+
self.enc_p = TextEncoder768(
|
937 |
+
inter_channels,
|
938 |
+
hidden_channels,
|
939 |
+
filter_channels,
|
940 |
+
n_heads,
|
941 |
+
n_layers,
|
942 |
+
kernel_size,
|
943 |
+
p_dropout,
|
944 |
+
f0=False,
|
945 |
+
)
|
946 |
+
self.dec = Generator(
|
947 |
+
inter_channels,
|
948 |
+
resblock,
|
949 |
+
resblock_kernel_sizes,
|
950 |
+
resblock_dilation_sizes,
|
951 |
+
upsample_rates,
|
952 |
+
upsample_initial_channel,
|
953 |
+
upsample_kernel_sizes,
|
954 |
+
gin_channels=gin_channels,
|
955 |
+
)
|
956 |
+
self.enc_q = PosteriorEncoder(
|
957 |
+
spec_channels,
|
958 |
+
inter_channels,
|
959 |
+
hidden_channels,
|
960 |
+
5,
|
961 |
+
1,
|
962 |
+
16,
|
963 |
+
gin_channels=gin_channels,
|
964 |
+
)
|
965 |
+
self.flow = ResidualCouplingBlock(
|
966 |
+
inter_channels, hidden_channels, 5, 1, 3, gin_channels=gin_channels
|
967 |
+
)
|
968 |
+
self.emb_g = nn.Embedding(self.spk_embed_dim, gin_channels)
|
969 |
+
logger.debug(
|
970 |
+
"gin_channels: "
|
971 |
+
+ str(gin_channels)
|
972 |
+
+ ", self.spk_embed_dim: "
|
973 |
+
+ str(self.spk_embed_dim)
|
974 |
+
)
|
975 |
+
|
976 |
+
def remove_weight_norm(self):
|
977 |
+
self.dec.remove_weight_norm()
|
978 |
+
self.flow.remove_weight_norm()
|
979 |
+
self.enc_q.remove_weight_norm()
|
980 |
+
|
981 |
+
def forward(self, phone, phone_lengths, y, y_lengths, ds): # 这里ds是id,[bs,1]
|
982 |
+
g = self.emb_g(ds).unsqueeze(-1) # [b, 256, 1]##1是t,广播的
|
983 |
+
m_p, logs_p, x_mask = self.enc_p(phone, None, phone_lengths)
|
984 |
+
z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g)
|
985 |
+
z_p = self.flow(z, y_mask, g=g)
|
986 |
+
z_slice, ids_slice = commons.rand_slice_segments(
|
987 |
+
z, y_lengths, self.segment_size
|
988 |
+
)
|
989 |
+
o = self.dec(z_slice, g=g)
|
990 |
+
return o, ids_slice, x_mask, y_mask, (z, z_p, m_p, logs_p, m_q, logs_q)
|
991 |
+
|
992 |
+
def infer(self, phone, phone_lengths, sid, rate=None):
|
993 |
+
g = self.emb_g(sid).unsqueeze(-1)
|
994 |
+
m_p, logs_p, x_mask = self.enc_p(phone, None, phone_lengths)
|
995 |
+
z_p = (m_p + torch.exp(logs_p) * torch.randn_like(m_p) * 0.66666) * x_mask
|
996 |
+
if rate:
|
997 |
+
head = int(z_p.shape[2] * rate)
|
998 |
+
z_p = z_p[:, :, -head:]
|
999 |
+
x_mask = x_mask[:, :, -head:]
|
1000 |
+
z = self.flow(z_p, x_mask, g=g, reverse=True)
|
1001 |
+
o = self.dec(z * x_mask, g=g)
|
1002 |
+
return o, x_mask, (z, z_p, m_p, logs_p)
|
1003 |
+
|
1004 |
+
|
1005 |
+
class MultiPeriodDiscriminator(torch.nn.Module):
|
1006 |
+
def __init__(self, use_spectral_norm=False):
|
1007 |
+
super(MultiPeriodDiscriminator, self).__init__()
|
1008 |
+
periods = [2, 3, 5, 7, 11, 17]
|
1009 |
+
# periods = [3, 5, 7, 11, 17, 23, 37]
|
1010 |
+
|
1011 |
+
discs = [DiscriminatorS(use_spectral_norm=use_spectral_norm)]
|
1012 |
+
discs = discs + [
|
1013 |
+
DiscriminatorP(i, use_spectral_norm=use_spectral_norm) for i in periods
|
1014 |
+
]
|
1015 |
+
self.discriminators = nn.ModuleList(discs)
|
1016 |
+
|
1017 |
+
def forward(self, y, y_hat):
|
1018 |
+
y_d_rs = [] #
|
1019 |
+
y_d_gs = []
|
1020 |
+
fmap_rs = []
|
1021 |
+
fmap_gs = []
|
1022 |
+
for i, d in enumerate(self.discriminators):
|
1023 |
+
y_d_r, fmap_r = d(y)
|
1024 |
+
y_d_g, fmap_g = d(y_hat)
|
1025 |
+
# for j in range(len(fmap_r)):
|
1026 |
+
# print(i,j,y.shape,y_hat.shape,fmap_r[j].shape,fmap_g[j].shape)
|
1027 |
+
y_d_rs.append(y_d_r)
|
1028 |
+
y_d_gs.append(y_d_g)
|
1029 |
+
fmap_rs.append(fmap_r)
|
1030 |
+
fmap_gs.append(fmap_g)
|
1031 |
+
|
1032 |
+
return y_d_rs, y_d_gs, fmap_rs, fmap_gs
|
1033 |
+
|
1034 |
+
|
1035 |
+
class MultiPeriodDiscriminatorV2(torch.nn.Module):
|
1036 |
+
def __init__(self, use_spectral_norm=False):
|
1037 |
+
super(MultiPeriodDiscriminatorV2, self).__init__()
|
1038 |
+
# periods = [2, 3, 5, 7, 11, 17]
|
1039 |
+
periods = [2, 3, 5, 7, 11, 17, 23, 37]
|
1040 |
+
|
1041 |
+
discs = [DiscriminatorS(use_spectral_norm=use_spectral_norm)]
|
1042 |
+
discs = discs + [
|
1043 |
+
DiscriminatorP(i, use_spectral_norm=use_spectral_norm) for i in periods
|
1044 |
+
]
|
1045 |
+
self.discriminators = nn.ModuleList(discs)
|
1046 |
+
|
1047 |
+
def forward(self, y, y_hat):
|
1048 |
+
y_d_rs = [] #
|
1049 |
+
y_d_gs = []
|
1050 |
+
fmap_rs = []
|
1051 |
+
fmap_gs = []
|
1052 |
+
for i, d in enumerate(self.discriminators):
|
1053 |
+
y_d_r, fmap_r = d(y)
|
1054 |
+
y_d_g, fmap_g = d(y_hat)
|
1055 |
+
# for j in range(len(fmap_r)):
|
1056 |
+
# print(i,j,y.shape,y_hat.shape,fmap_r[j].shape,fmap_g[j].shape)
|
1057 |
+
y_d_rs.append(y_d_r)
|
1058 |
+
y_d_gs.append(y_d_g)
|
1059 |
+
fmap_rs.append(fmap_r)
|
1060 |
+
fmap_gs.append(fmap_g)
|
1061 |
+
|
1062 |
+
return y_d_rs, y_d_gs, fmap_rs, fmap_gs
|
1063 |
+
|
1064 |
+
|
1065 |
+
class DiscriminatorS(torch.nn.Module):
|
1066 |
+
def __init__(self, use_spectral_norm=False):
|
1067 |
+
super(DiscriminatorS, self).__init__()
|
1068 |
+
norm_f = weight_norm if use_spectral_norm == False else spectral_norm
|
1069 |
+
self.convs = nn.ModuleList(
|
1070 |
+
[
|
1071 |
+
norm_f(Conv1d(1, 16, 15, 1, padding=7)),
|
1072 |
+
norm_f(Conv1d(16, 64, 41, 4, groups=4, padding=20)),
|
1073 |
+
norm_f(Conv1d(64, 256, 41, 4, groups=16, padding=20)),
|
1074 |
+
norm_f(Conv1d(256, 1024, 41, 4, groups=64, padding=20)),
|
1075 |
+
norm_f(Conv1d(1024, 1024, 41, 4, groups=256, padding=20)),
|
1076 |
+
norm_f(Conv1d(1024, 1024, 5, 1, padding=2)),
|
1077 |
+
]
|
1078 |
+
)
|
1079 |
+
self.conv_post = norm_f(Conv1d(1024, 1, 3, 1, padding=1))
|
1080 |
+
|
1081 |
+
def forward(self, x):
|
1082 |
+
fmap = []
|
1083 |
+
|
1084 |
+
for l in self.convs:
|
1085 |
+
x = l(x)
|
1086 |
+
x = F.leaky_relu(x, modules.LRELU_SLOPE)
|
1087 |
+
fmap.append(x)
|
1088 |
+
x = self.conv_post(x)
|
1089 |
+
fmap.append(x)
|
1090 |
+
x = torch.flatten(x, 1, -1)
|
1091 |
+
|
1092 |
+
return x, fmap
|
1093 |
+
|
1094 |
+
|
1095 |
+
class DiscriminatorP(torch.nn.Module):
|
1096 |
+
def __init__(self, period, kernel_size=5, stride=3, use_spectral_norm=False):
|
1097 |
+
super(DiscriminatorP, self).__init__()
|
1098 |
+
self.period = period
|
1099 |
+
self.use_spectral_norm = use_spectral_norm
|
1100 |
+
norm_f = weight_norm if use_spectral_norm == False else spectral_norm
|
1101 |
+
self.convs = nn.ModuleList(
|
1102 |
+
[
|
1103 |
+
norm_f(
|
1104 |
+
Conv2d(
|
1105 |
+
1,
|
1106 |
+
32,
|
1107 |
+
(kernel_size, 1),
|
1108 |
+
(stride, 1),
|
1109 |
+
padding=(get_padding(kernel_size, 1), 0),
|
1110 |
+
)
|
1111 |
+
),
|
1112 |
+
norm_f(
|
1113 |
+
Conv2d(
|
1114 |
+
32,
|
1115 |
+
128,
|
1116 |
+
(kernel_size, 1),
|
1117 |
+
(stride, 1),
|
1118 |
+
padding=(get_padding(kernel_size, 1), 0),
|
1119 |
+
)
|
1120 |
+
),
|
1121 |
+
norm_f(
|
1122 |
+
Conv2d(
|
1123 |
+
128,
|
1124 |
+
512,
|
1125 |
+
(kernel_size, 1),
|
1126 |
+
(stride, 1),
|
1127 |
+
padding=(get_padding(kernel_size, 1), 0),
|
1128 |
+
)
|
1129 |
+
),
|
1130 |
+
norm_f(
|
1131 |
+
Conv2d(
|
1132 |
+
512,
|
1133 |
+
1024,
|
1134 |
+
(kernel_size, 1),
|
1135 |
+
(stride, 1),
|
1136 |
+
padding=(get_padding(kernel_size, 1), 0),
|
1137 |
+
)
|
1138 |
+
),
|
1139 |
+
norm_f(
|
1140 |
+
Conv2d(
|
1141 |
+
1024,
|
1142 |
+
1024,
|
1143 |
+
(kernel_size, 1),
|
1144 |
+
1,
|
1145 |
+
padding=(get_padding(kernel_size, 1), 0),
|
1146 |
+
)
|
1147 |
+
),
|
1148 |
+
]
|
1149 |
+
)
|
1150 |
+
self.conv_post = norm_f(Conv2d(1024, 1, (3, 1), 1, padding=(1, 0)))
|
1151 |
+
|
1152 |
+
def forward(self, x):
|
1153 |
+
fmap = []
|
1154 |
+
|
1155 |
+
# 1d to 2d
|
1156 |
+
b, c, t = x.shape
|
1157 |
+
if t % self.period != 0: # pad first
|
1158 |
+
n_pad = self.period - (t % self.period)
|
1159 |
+
if has_xpu and x.dtype == torch.bfloat16:
|
1160 |
+
x = F.pad(x.to(dtype=torch.float16), (0, n_pad), "reflect").to(dtype=torch.bfloat16)
|
1161 |
+
else:
|
1162 |
+
x = F.pad(x, (0, n_pad), "reflect")
|
1163 |
+
t = t + n_pad
|
1164 |
+
x = x.view(b, c, t // self.period, self.period)
|
1165 |
+
|
1166 |
+
for l in self.convs:
|
1167 |
+
x = l(x)
|
1168 |
+
x = F.leaky_relu(x, modules.LRELU_SLOPE)
|
1169 |
+
fmap.append(x)
|
1170 |
+
x = self.conv_post(x)
|
1171 |
+
fmap.append(x)
|
1172 |
+
x = torch.flatten(x, 1, -1)
|
1173 |
+
|
1174 |
+
return x, fmap
|
lib/infer_libs/infer_pack/modules.py
ADDED
@@ -0,0 +1,517 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import math
|
2 |
+
import torch
|
3 |
+
from torch import nn
|
4 |
+
from torch.nn import Conv1d
|
5 |
+
from torch.nn import functional as F
|
6 |
+
from torch.nn.utils import remove_weight_norm, weight_norm
|
7 |
+
|
8 |
+
from lib.infer_libs.infer_pack import commons
|
9 |
+
from lib.infer_libs.infer_pack.commons import get_padding, init_weights
|
10 |
+
from lib.infer_libs.infer_pack.transforms import piecewise_rational_quadratic_transform
|
11 |
+
|
12 |
+
LRELU_SLOPE = 0.1
|
13 |
+
|
14 |
+
|
15 |
+
class LayerNorm(nn.Module):
|
16 |
+
def __init__(self, channels, eps=1e-5):
|
17 |
+
super().__init__()
|
18 |
+
self.channels = channels
|
19 |
+
self.eps = eps
|
20 |
+
|
21 |
+
self.gamma = nn.Parameter(torch.ones(channels))
|
22 |
+
self.beta = nn.Parameter(torch.zeros(channels))
|
23 |
+
|
24 |
+
def forward(self, x):
|
25 |
+
x = x.transpose(1, -1)
|
26 |
+
x = F.layer_norm(x, (self.channels,), self.gamma, self.beta, self.eps)
|
27 |
+
return x.transpose(1, -1)
|
28 |
+
|
29 |
+
|
30 |
+
class ConvReluNorm(nn.Module):
|
31 |
+
def __init__(
|
32 |
+
self,
|
33 |
+
in_channels,
|
34 |
+
hidden_channels,
|
35 |
+
out_channels,
|
36 |
+
kernel_size,
|
37 |
+
n_layers,
|
38 |
+
p_dropout,
|
39 |
+
):
|
40 |
+
super().__init__()
|
41 |
+
self.in_channels = in_channels
|
42 |
+
self.hidden_channels = hidden_channels
|
43 |
+
self.out_channels = out_channels
|
44 |
+
self.kernel_size = kernel_size
|
45 |
+
self.n_layers = n_layers
|
46 |
+
self.p_dropout = p_dropout
|
47 |
+
assert n_layers > 1, "Number of layers should be larger than 0."
|
48 |
+
|
49 |
+
self.conv_layers = nn.ModuleList()
|
50 |
+
self.norm_layers = nn.ModuleList()
|
51 |
+
self.conv_layers.append(
|
52 |
+
nn.Conv1d(
|
53 |
+
in_channels, hidden_channels, kernel_size, padding=kernel_size // 2
|
54 |
+
)
|
55 |
+
)
|
56 |
+
self.norm_layers.append(LayerNorm(hidden_channels))
|
57 |
+
self.relu_drop = nn.Sequential(nn.ReLU(), nn.Dropout(p_dropout))
|
58 |
+
for _ in range(n_layers - 1):
|
59 |
+
self.conv_layers.append(
|
60 |
+
nn.Conv1d(
|
61 |
+
hidden_channels,
|
62 |
+
hidden_channels,
|
63 |
+
kernel_size,
|
64 |
+
padding=kernel_size // 2,
|
65 |
+
)
|
66 |
+
)
|
67 |
+
self.norm_layers.append(LayerNorm(hidden_channels))
|
68 |
+
self.proj = nn.Conv1d(hidden_channels, out_channels, 1)
|
69 |
+
self.proj.weight.data.zero_()
|
70 |
+
self.proj.bias.data.zero_()
|
71 |
+
|
72 |
+
def forward(self, x, x_mask):
|
73 |
+
x_org = x
|
74 |
+
for i in range(self.n_layers):
|
75 |
+
x = self.conv_layers[i](x * x_mask)
|
76 |
+
x = self.norm_layers[i](x)
|
77 |
+
x = self.relu_drop(x)
|
78 |
+
x = x_org + self.proj(x)
|
79 |
+
return x * x_mask
|
80 |
+
|
81 |
+
|
82 |
+
class DDSConv(nn.Module):
|
83 |
+
"""
|
84 |
+
Dialted and Depth-Separable Convolution
|
85 |
+
"""
|
86 |
+
|
87 |
+
def __init__(self, channels, kernel_size, n_layers, p_dropout=0.0):
|
88 |
+
super().__init__()
|
89 |
+
self.channels = channels
|
90 |
+
self.kernel_size = kernel_size
|
91 |
+
self.n_layers = n_layers
|
92 |
+
self.p_dropout = p_dropout
|
93 |
+
|
94 |
+
self.drop = nn.Dropout(p_dropout)
|
95 |
+
self.convs_sep = nn.ModuleList()
|
96 |
+
self.convs_1x1 = nn.ModuleList()
|
97 |
+
self.norms_1 = nn.ModuleList()
|
98 |
+
self.norms_2 = nn.ModuleList()
|
99 |
+
for i in range(n_layers):
|
100 |
+
dilation = kernel_size**i
|
101 |
+
padding = (kernel_size * dilation - dilation) // 2
|
102 |
+
self.convs_sep.append(
|
103 |
+
nn.Conv1d(
|
104 |
+
channels,
|
105 |
+
channels,
|
106 |
+
kernel_size,
|
107 |
+
groups=channels,
|
108 |
+
dilation=dilation,
|
109 |
+
padding=padding,
|
110 |
+
)
|
111 |
+
)
|
112 |
+
self.convs_1x1.append(nn.Conv1d(channels, channels, 1))
|
113 |
+
self.norms_1.append(LayerNorm(channels))
|
114 |
+
self.norms_2.append(LayerNorm(channels))
|
115 |
+
|
116 |
+
def forward(self, x, x_mask, g=None):
|
117 |
+
if g is not None:
|
118 |
+
x = x + g
|
119 |
+
for i in range(self.n_layers):
|
120 |
+
y = self.convs_sep[i](x * x_mask)
|
121 |
+
y = self.norms_1[i](y)
|
122 |
+
y = F.gelu(y)
|
123 |
+
y = self.convs_1x1[i](y)
|
124 |
+
y = self.norms_2[i](y)
|
125 |
+
y = F.gelu(y)
|
126 |
+
y = self.drop(y)
|
127 |
+
x = x + y
|
128 |
+
return x * x_mask
|
129 |
+
|
130 |
+
|
131 |
+
class WN(torch.nn.Module):
|
132 |
+
def __init__(
|
133 |
+
self,
|
134 |
+
hidden_channels,
|
135 |
+
kernel_size,
|
136 |
+
dilation_rate,
|
137 |
+
n_layers,
|
138 |
+
gin_channels=0,
|
139 |
+
p_dropout=0,
|
140 |
+
):
|
141 |
+
super(WN, self).__init__()
|
142 |
+
assert kernel_size % 2 == 1
|
143 |
+
self.hidden_channels = hidden_channels
|
144 |
+
self.kernel_size = (kernel_size,)
|
145 |
+
self.dilation_rate = dilation_rate
|
146 |
+
self.n_layers = n_layers
|
147 |
+
self.gin_channels = gin_channels
|
148 |
+
self.p_dropout = p_dropout
|
149 |
+
|
150 |
+
self.in_layers = torch.nn.ModuleList()
|
151 |
+
self.res_skip_layers = torch.nn.ModuleList()
|
152 |
+
self.drop = nn.Dropout(p_dropout)
|
153 |
+
|
154 |
+
if gin_channels != 0:
|
155 |
+
cond_layer = torch.nn.Conv1d(
|
156 |
+
gin_channels, 2 * hidden_channels * n_layers, 1
|
157 |
+
)
|
158 |
+
self.cond_layer = torch.nn.utils.weight_norm(cond_layer, name="weight")
|
159 |
+
|
160 |
+
for i in range(n_layers):
|
161 |
+
dilation = dilation_rate**i
|
162 |
+
padding = int((kernel_size * dilation - dilation) / 2)
|
163 |
+
in_layer = torch.nn.Conv1d(
|
164 |
+
hidden_channels,
|
165 |
+
2 * hidden_channels,
|
166 |
+
kernel_size,
|
167 |
+
dilation=dilation,
|
168 |
+
padding=padding,
|
169 |
+
)
|
170 |
+
in_layer = torch.nn.utils.weight_norm(in_layer, name="weight")
|
171 |
+
self.in_layers.append(in_layer)
|
172 |
+
|
173 |
+
# last one is not necessary
|
174 |
+
if i < n_layers - 1:
|
175 |
+
res_skip_channels = 2 * hidden_channels
|
176 |
+
else:
|
177 |
+
res_skip_channels = hidden_channels
|
178 |
+
|
179 |
+
res_skip_layer = torch.nn.Conv1d(hidden_channels, res_skip_channels, 1)
|
180 |
+
res_skip_layer = torch.nn.utils.weight_norm(res_skip_layer, name="weight")
|
181 |
+
self.res_skip_layers.append(res_skip_layer)
|
182 |
+
|
183 |
+
def forward(self, x, x_mask, g=None, **kwargs):
|
184 |
+
output = torch.zeros_like(x)
|
185 |
+
n_channels_tensor = torch.IntTensor([self.hidden_channels])
|
186 |
+
|
187 |
+
if g is not None:
|
188 |
+
g = self.cond_layer(g)
|
189 |
+
|
190 |
+
for i in range(self.n_layers):
|
191 |
+
x_in = self.in_layers[i](x)
|
192 |
+
if g is not None:
|
193 |
+
cond_offset = i * 2 * self.hidden_channels
|
194 |
+
g_l = g[:, cond_offset : cond_offset + 2 * self.hidden_channels, :]
|
195 |
+
else:
|
196 |
+
g_l = torch.zeros_like(x_in)
|
197 |
+
|
198 |
+
acts = commons.fused_add_tanh_sigmoid_multiply(x_in, g_l, n_channels_tensor)
|
199 |
+
acts = self.drop(acts)
|
200 |
+
|
201 |
+
res_skip_acts = self.res_skip_layers[i](acts)
|
202 |
+
if i < self.n_layers - 1:
|
203 |
+
res_acts = res_skip_acts[:, : self.hidden_channels, :]
|
204 |
+
x = (x + res_acts) * x_mask
|
205 |
+
output = output + res_skip_acts[:, self.hidden_channels :, :]
|
206 |
+
else:
|
207 |
+
output = output + res_skip_acts
|
208 |
+
return output * x_mask
|
209 |
+
|
210 |
+
def remove_weight_norm(self):
|
211 |
+
if self.gin_channels != 0:
|
212 |
+
torch.nn.utils.remove_weight_norm(self.cond_layer)
|
213 |
+
for l in self.in_layers:
|
214 |
+
torch.nn.utils.remove_weight_norm(l)
|
215 |
+
for l in self.res_skip_layers:
|
216 |
+
torch.nn.utils.remove_weight_norm(l)
|
217 |
+
|
218 |
+
|
219 |
+
class ResBlock1(torch.nn.Module):
|
220 |
+
def __init__(self, channels, kernel_size=3, dilation=(1, 3, 5)):
|
221 |
+
super(ResBlock1, self).__init__()
|
222 |
+
self.convs1 = nn.ModuleList(
|
223 |
+
[
|
224 |
+
weight_norm(
|
225 |
+
Conv1d(
|
226 |
+
channels,
|
227 |
+
channels,
|
228 |
+
kernel_size,
|
229 |
+
1,
|
230 |
+
dilation=dilation[0],
|
231 |
+
padding=get_padding(kernel_size, dilation[0]),
|
232 |
+
)
|
233 |
+
),
|
234 |
+
weight_norm(
|
235 |
+
Conv1d(
|
236 |
+
channels,
|
237 |
+
channels,
|
238 |
+
kernel_size,
|
239 |
+
1,
|
240 |
+
dilation=dilation[1],
|
241 |
+
padding=get_padding(kernel_size, dilation[1]),
|
242 |
+
)
|
243 |
+
),
|
244 |
+
weight_norm(
|
245 |
+
Conv1d(
|
246 |
+
channels,
|
247 |
+
channels,
|
248 |
+
kernel_size,
|
249 |
+
1,
|
250 |
+
dilation=dilation[2],
|
251 |
+
padding=get_padding(kernel_size, dilation[2]),
|
252 |
+
)
|
253 |
+
),
|
254 |
+
]
|
255 |
+
)
|
256 |
+
self.convs1.apply(init_weights)
|
257 |
+
|
258 |
+
self.convs2 = nn.ModuleList(
|
259 |
+
[
|
260 |
+
weight_norm(
|
261 |
+
Conv1d(
|
262 |
+
channels,
|
263 |
+
channels,
|
264 |
+
kernel_size,
|
265 |
+
1,
|
266 |
+
dilation=1,
|
267 |
+
padding=get_padding(kernel_size, 1),
|
268 |
+
)
|
269 |
+
),
|
270 |
+
weight_norm(
|
271 |
+
Conv1d(
|
272 |
+
channels,
|
273 |
+
channels,
|
274 |
+
kernel_size,
|
275 |
+
1,
|
276 |
+
dilation=1,
|
277 |
+
padding=get_padding(kernel_size, 1),
|
278 |
+
)
|
279 |
+
),
|
280 |
+
weight_norm(
|
281 |
+
Conv1d(
|
282 |
+
channels,
|
283 |
+
channels,
|
284 |
+
kernel_size,
|
285 |
+
1,
|
286 |
+
dilation=1,
|
287 |
+
padding=get_padding(kernel_size, 1),
|
288 |
+
)
|
289 |
+
),
|
290 |
+
]
|
291 |
+
)
|
292 |
+
self.convs2.apply(init_weights)
|
293 |
+
|
294 |
+
def forward(self, x, x_mask=None):
|
295 |
+
for c1, c2 in zip(self.convs1, self.convs2):
|
296 |
+
xt = F.leaky_relu(x, LRELU_SLOPE)
|
297 |
+
if x_mask is not None:
|
298 |
+
xt = xt * x_mask
|
299 |
+
xt = c1(xt)
|
300 |
+
xt = F.leaky_relu(xt, LRELU_SLOPE)
|
301 |
+
if x_mask is not None:
|
302 |
+
xt = xt * x_mask
|
303 |
+
xt = c2(xt)
|
304 |
+
x = xt + x
|
305 |
+
if x_mask is not None:
|
306 |
+
x = x * x_mask
|
307 |
+
return x
|
308 |
+
|
309 |
+
def remove_weight_norm(self):
|
310 |
+
for l in self.convs1:
|
311 |
+
remove_weight_norm(l)
|
312 |
+
for l in self.convs2:
|
313 |
+
remove_weight_norm(l)
|
314 |
+
|
315 |
+
|
316 |
+
class ResBlock2(torch.nn.Module):
|
317 |
+
def __init__(self, channels, kernel_size=3, dilation=(1, 3)):
|
318 |
+
super(ResBlock2, self).__init__()
|
319 |
+
self.convs = nn.ModuleList(
|
320 |
+
[
|
321 |
+
weight_norm(
|
322 |
+
Conv1d(
|
323 |
+
channels,
|
324 |
+
channels,
|
325 |
+
kernel_size,
|
326 |
+
1,
|
327 |
+
dilation=dilation[0],
|
328 |
+
padding=get_padding(kernel_size, dilation[0]),
|
329 |
+
)
|
330 |
+
),
|
331 |
+
weight_norm(
|
332 |
+
Conv1d(
|
333 |
+
channels,
|
334 |
+
channels,
|
335 |
+
kernel_size,
|
336 |
+
1,
|
337 |
+
dilation=dilation[1],
|
338 |
+
padding=get_padding(kernel_size, dilation[1]),
|
339 |
+
)
|
340 |
+
),
|
341 |
+
]
|
342 |
+
)
|
343 |
+
self.convs.apply(init_weights)
|
344 |
+
|
345 |
+
def forward(self, x, x_mask=None):
|
346 |
+
for c in self.convs:
|
347 |
+
xt = F.leaky_relu(x, LRELU_SLOPE)
|
348 |
+
if x_mask is not None:
|
349 |
+
xt = xt * x_mask
|
350 |
+
xt = c(xt)
|
351 |
+
x = xt + x
|
352 |
+
if x_mask is not None:
|
353 |
+
x = x * x_mask
|
354 |
+
return x
|
355 |
+
|
356 |
+
def remove_weight_norm(self):
|
357 |
+
for l in self.convs:
|
358 |
+
remove_weight_norm(l)
|
359 |
+
|
360 |
+
|
361 |
+
class Log(nn.Module):
|
362 |
+
def forward(self, x, x_mask, reverse=False, **kwargs):
|
363 |
+
if not reverse:
|
364 |
+
y = torch.log(torch.clamp_min(x, 1e-5)) * x_mask
|
365 |
+
logdet = torch.sum(-y, [1, 2])
|
366 |
+
return y, logdet
|
367 |
+
else:
|
368 |
+
x = torch.exp(x) * x_mask
|
369 |
+
return x
|
370 |
+
|
371 |
+
|
372 |
+
class Flip(nn.Module):
|
373 |
+
def forward(self, x, *args, reverse=False, **kwargs):
|
374 |
+
x = torch.flip(x, [1])
|
375 |
+
if not reverse:
|
376 |
+
logdet = torch.zeros(x.size(0)).to(dtype=x.dtype, device=x.device)
|
377 |
+
return x, logdet
|
378 |
+
else:
|
379 |
+
return x
|
380 |
+
|
381 |
+
|
382 |
+
class ElementwiseAffine(nn.Module):
|
383 |
+
def __init__(self, channels):
|
384 |
+
super().__init__()
|
385 |
+
self.channels = channels
|
386 |
+
self.m = nn.Parameter(torch.zeros(channels, 1))
|
387 |
+
self.logs = nn.Parameter(torch.zeros(channels, 1))
|
388 |
+
|
389 |
+
def forward(self, x, x_mask, reverse=False, **kwargs):
|
390 |
+
if not reverse:
|
391 |
+
y = self.m + torch.exp(self.logs) * x
|
392 |
+
y = y * x_mask
|
393 |
+
logdet = torch.sum(self.logs * x_mask, [1, 2])
|
394 |
+
return y, logdet
|
395 |
+
else:
|
396 |
+
x = (x - self.m) * torch.exp(-self.logs) * x_mask
|
397 |
+
return x
|
398 |
+
|
399 |
+
|
400 |
+
class ResidualCouplingLayer(nn.Module):
|
401 |
+
def __init__(
|
402 |
+
self,
|
403 |
+
channels,
|
404 |
+
hidden_channels,
|
405 |
+
kernel_size,
|
406 |
+
dilation_rate,
|
407 |
+
n_layers,
|
408 |
+
p_dropout=0,
|
409 |
+
gin_channels=0,
|
410 |
+
mean_only=False,
|
411 |
+
):
|
412 |
+
assert channels % 2 == 0, "channels should be divisible by 2"
|
413 |
+
super().__init__()
|
414 |
+
self.channels = channels
|
415 |
+
self.hidden_channels = hidden_channels
|
416 |
+
self.kernel_size = kernel_size
|
417 |
+
self.dilation_rate = dilation_rate
|
418 |
+
self.n_layers = n_layers
|
419 |
+
self.half_channels = channels // 2
|
420 |
+
self.mean_only = mean_only
|
421 |
+
|
422 |
+
self.pre = nn.Conv1d(self.half_channels, hidden_channels, 1)
|
423 |
+
self.enc = WN(
|
424 |
+
hidden_channels,
|
425 |
+
kernel_size,
|
426 |
+
dilation_rate,
|
427 |
+
n_layers,
|
428 |
+
p_dropout=p_dropout,
|
429 |
+
gin_channels=gin_channels,
|
430 |
+
)
|
431 |
+
self.post = nn.Conv1d(hidden_channels, self.half_channels * (2 - mean_only), 1)
|
432 |
+
self.post.weight.data.zero_()
|
433 |
+
self.post.bias.data.zero_()
|
434 |
+
|
435 |
+
def forward(self, x, x_mask, g=None, reverse=False):
|
436 |
+
x0, x1 = torch.split(x, [self.half_channels] * 2, 1)
|
437 |
+
h = self.pre(x0) * x_mask
|
438 |
+
h = self.enc(h, x_mask, g=g)
|
439 |
+
stats = self.post(h) * x_mask
|
440 |
+
if not self.mean_only:
|
441 |
+
m, logs = torch.split(stats, [self.half_channels] * 2, 1)
|
442 |
+
else:
|
443 |
+
m = stats
|
444 |
+
logs = torch.zeros_like(m)
|
445 |
+
|
446 |
+
if not reverse:
|
447 |
+
x1 = m + x1 * torch.exp(logs) * x_mask
|
448 |
+
x = torch.cat([x0, x1], 1)
|
449 |
+
logdet = torch.sum(logs, [1, 2])
|
450 |
+
return x, logdet
|
451 |
+
else:
|
452 |
+
x1 = (x1 - m) * torch.exp(-logs) * x_mask
|
453 |
+
x = torch.cat([x0, x1], 1)
|
454 |
+
return x
|
455 |
+
|
456 |
+
def remove_weight_norm(self):
|
457 |
+
self.enc.remove_weight_norm()
|
458 |
+
|
459 |
+
|
460 |
+
class ConvFlow(nn.Module):
|
461 |
+
def __init__(
|
462 |
+
self,
|
463 |
+
in_channels,
|
464 |
+
filter_channels,
|
465 |
+
kernel_size,
|
466 |
+
n_layers,
|
467 |
+
num_bins=10,
|
468 |
+
tail_bound=5.0,
|
469 |
+
):
|
470 |
+
super().__init__()
|
471 |
+
self.in_channels = in_channels
|
472 |
+
self.filter_channels = filter_channels
|
473 |
+
self.kernel_size = kernel_size
|
474 |
+
self.n_layers = n_layers
|
475 |
+
self.num_bins = num_bins
|
476 |
+
self.tail_bound = tail_bound
|
477 |
+
self.half_channels = in_channels // 2
|
478 |
+
|
479 |
+
self.pre = nn.Conv1d(self.half_channels, filter_channels, 1)
|
480 |
+
self.convs = DDSConv(filter_channels, kernel_size, n_layers, p_dropout=0.0)
|
481 |
+
self.proj = nn.Conv1d(
|
482 |
+
filter_channels, self.half_channels * (num_bins * 3 - 1), 1
|
483 |
+
)
|
484 |
+
self.proj.weight.data.zero_()
|
485 |
+
self.proj.bias.data.zero_()
|
486 |
+
|
487 |
+
def forward(self, x, x_mask, g=None, reverse=False):
|
488 |
+
x0, x1 = torch.split(x, [self.half_channels] * 2, 1)
|
489 |
+
h = self.pre(x0)
|
490 |
+
h = self.convs(h, x_mask, g=g)
|
491 |
+
h = self.proj(h) * x_mask
|
492 |
+
|
493 |
+
b, c, t = x0.shape
|
494 |
+
h = h.reshape(b, c, -1, t).permute(0, 1, 3, 2) # [b, cx?, t] -> [b, c, t, ?]
|
495 |
+
|
496 |
+
unnormalized_widths = h[..., : self.num_bins] / math.sqrt(self.filter_channels)
|
497 |
+
unnormalized_heights = h[..., self.num_bins : 2 * self.num_bins] / math.sqrt(
|
498 |
+
self.filter_channels
|
499 |
+
)
|
500 |
+
unnormalized_derivatives = h[..., 2 * self.num_bins :]
|
501 |
+
|
502 |
+
x1, logabsdet = piecewise_rational_quadratic_transform(
|
503 |
+
x1,
|
504 |
+
unnormalized_widths,
|
505 |
+
unnormalized_heights,
|
506 |
+
unnormalized_derivatives,
|
507 |
+
inverse=reverse,
|
508 |
+
tails="linear",
|
509 |
+
tail_bound=self.tail_bound,
|
510 |
+
)
|
511 |
+
|
512 |
+
x = torch.cat([x0, x1], 1) * x_mask
|
513 |
+
logdet = torch.sum(logabsdet * x_mask, [1, 2])
|
514 |
+
if not reverse:
|
515 |
+
return x, logdet
|
516 |
+
else:
|
517 |
+
return x
|
lib/infer_libs/infer_pack/transforms.py
ADDED
@@ -0,0 +1,207 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
import torch
|
3 |
+
from torch.nn import functional as F
|
4 |
+
|
5 |
+
DEFAULT_MIN_BIN_WIDTH = 1e-3
|
6 |
+
DEFAULT_MIN_BIN_HEIGHT = 1e-3
|
7 |
+
DEFAULT_MIN_DERIVATIVE = 1e-3
|
8 |
+
|
9 |
+
|
10 |
+
def piecewise_rational_quadratic_transform(
|
11 |
+
inputs,
|
12 |
+
unnormalized_widths,
|
13 |
+
unnormalized_heights,
|
14 |
+
unnormalized_derivatives,
|
15 |
+
inverse=False,
|
16 |
+
tails=None,
|
17 |
+
tail_bound=1.0,
|
18 |
+
min_bin_width=DEFAULT_MIN_BIN_WIDTH,
|
19 |
+
min_bin_height=DEFAULT_MIN_BIN_HEIGHT,
|
20 |
+
min_derivative=DEFAULT_MIN_DERIVATIVE,
|
21 |
+
):
|
22 |
+
if tails is None:
|
23 |
+
spline_fn = rational_quadratic_spline
|
24 |
+
spline_kwargs = {}
|
25 |
+
else:
|
26 |
+
spline_fn = unconstrained_rational_quadratic_spline
|
27 |
+
spline_kwargs = {"tails": tails, "tail_bound": tail_bound}
|
28 |
+
|
29 |
+
outputs, logabsdet = spline_fn(
|
30 |
+
inputs=inputs,
|
31 |
+
unnormalized_widths=unnormalized_widths,
|
32 |
+
unnormalized_heights=unnormalized_heights,
|
33 |
+
unnormalized_derivatives=unnormalized_derivatives,
|
34 |
+
inverse=inverse,
|
35 |
+
min_bin_width=min_bin_width,
|
36 |
+
min_bin_height=min_bin_height,
|
37 |
+
min_derivative=min_derivative,
|
38 |
+
**spline_kwargs
|
39 |
+
)
|
40 |
+
return outputs, logabsdet
|
41 |
+
|
42 |
+
|
43 |
+
def searchsorted(bin_locations, inputs, eps=1e-6):
|
44 |
+
bin_locations[..., -1] += eps
|
45 |
+
return torch.sum(inputs[..., None] >= bin_locations, dim=-1) - 1
|
46 |
+
|
47 |
+
|
48 |
+
def unconstrained_rational_quadratic_spline(
|
49 |
+
inputs,
|
50 |
+
unnormalized_widths,
|
51 |
+
unnormalized_heights,
|
52 |
+
unnormalized_derivatives,
|
53 |
+
inverse=False,
|
54 |
+
tails="linear",
|
55 |
+
tail_bound=1.0,
|
56 |
+
min_bin_width=DEFAULT_MIN_BIN_WIDTH,
|
57 |
+
min_bin_height=DEFAULT_MIN_BIN_HEIGHT,
|
58 |
+
min_derivative=DEFAULT_MIN_DERIVATIVE,
|
59 |
+
):
|
60 |
+
inside_interval_mask = (inputs >= -tail_bound) & (inputs <= tail_bound)
|
61 |
+
outside_interval_mask = ~inside_interval_mask
|
62 |
+
|
63 |
+
outputs = torch.zeros_like(inputs)
|
64 |
+
logabsdet = torch.zeros_like(inputs)
|
65 |
+
|
66 |
+
if tails == "linear":
|
67 |
+
unnormalized_derivatives = F.pad(unnormalized_derivatives, pad=(1, 1))
|
68 |
+
constant = np.log(np.exp(1 - min_derivative) - 1)
|
69 |
+
unnormalized_derivatives[..., 0] = constant
|
70 |
+
unnormalized_derivatives[..., -1] = constant
|
71 |
+
|
72 |
+
outputs[outside_interval_mask] = inputs[outside_interval_mask]
|
73 |
+
logabsdet[outside_interval_mask] = 0
|
74 |
+
else:
|
75 |
+
raise RuntimeError("{} tails are not implemented.".format(tails))
|
76 |
+
|
77 |
+
(
|
78 |
+
outputs[inside_interval_mask],
|
79 |
+
logabsdet[inside_interval_mask],
|
80 |
+
) = rational_quadratic_spline(
|
81 |
+
inputs=inputs[inside_interval_mask],
|
82 |
+
unnormalized_widths=unnormalized_widths[inside_interval_mask, :],
|
83 |
+
unnormalized_heights=unnormalized_heights[inside_interval_mask, :],
|
84 |
+
unnormalized_derivatives=unnormalized_derivatives[inside_interval_mask, :],
|
85 |
+
inverse=inverse,
|
86 |
+
left=-tail_bound,
|
87 |
+
right=tail_bound,
|
88 |
+
bottom=-tail_bound,
|
89 |
+
top=tail_bound,
|
90 |
+
min_bin_width=min_bin_width,
|
91 |
+
min_bin_height=min_bin_height,
|
92 |
+
min_derivative=min_derivative,
|
93 |
+
)
|
94 |
+
|
95 |
+
return outputs, logabsdet
|
96 |
+
|
97 |
+
|
98 |
+
def rational_quadratic_spline(
|
99 |
+
inputs,
|
100 |
+
unnormalized_widths,
|
101 |
+
unnormalized_heights,
|
102 |
+
unnormalized_derivatives,
|
103 |
+
inverse=False,
|
104 |
+
left=0.0,
|
105 |
+
right=1.0,
|
106 |
+
bottom=0.0,
|
107 |
+
top=1.0,
|
108 |
+
min_bin_width=DEFAULT_MIN_BIN_WIDTH,
|
109 |
+
min_bin_height=DEFAULT_MIN_BIN_HEIGHT,
|
110 |
+
min_derivative=DEFAULT_MIN_DERIVATIVE,
|
111 |
+
):
|
112 |
+
if torch.min(inputs) < left or torch.max(inputs) > right:
|
113 |
+
raise ValueError("Input to a transform is not within its domain")
|
114 |
+
|
115 |
+
num_bins = unnormalized_widths.shape[-1]
|
116 |
+
|
117 |
+
if min_bin_width * num_bins > 1.0:
|
118 |
+
raise ValueError("Minimal bin width too large for the number of bins")
|
119 |
+
if min_bin_height * num_bins > 1.0:
|
120 |
+
raise ValueError("Minimal bin height too large for the number of bins")
|
121 |
+
|
122 |
+
widths = F.softmax(unnormalized_widths, dim=-1)
|
123 |
+
widths = min_bin_width + (1 - min_bin_width * num_bins) * widths
|
124 |
+
cumwidths = torch.cumsum(widths, dim=-1)
|
125 |
+
cumwidths = F.pad(cumwidths, pad=(1, 0), mode="constant", value=0.0)
|
126 |
+
cumwidths = (right - left) * cumwidths + left
|
127 |
+
cumwidths[..., 0] = left
|
128 |
+
cumwidths[..., -1] = right
|
129 |
+
widths = cumwidths[..., 1:] - cumwidths[..., :-1]
|
130 |
+
|
131 |
+
derivatives = min_derivative + F.softplus(unnormalized_derivatives)
|
132 |
+
|
133 |
+
heights = F.softmax(unnormalized_heights, dim=-1)
|
134 |
+
heights = min_bin_height + (1 - min_bin_height * num_bins) * heights
|
135 |
+
cumheights = torch.cumsum(heights, dim=-1)
|
136 |
+
cumheights = F.pad(cumheights, pad=(1, 0), mode="constant", value=0.0)
|
137 |
+
cumheights = (top - bottom) * cumheights + bottom
|
138 |
+
cumheights[..., 0] = bottom
|
139 |
+
cumheights[..., -1] = top
|
140 |
+
heights = cumheights[..., 1:] - cumheights[..., :-1]
|
141 |
+
|
142 |
+
if inverse:
|
143 |
+
bin_idx = searchsorted(cumheights, inputs)[..., None]
|
144 |
+
else:
|
145 |
+
bin_idx = searchsorted(cumwidths, inputs)[..., None]
|
146 |
+
|
147 |
+
input_cumwidths = cumwidths.gather(-1, bin_idx)[..., 0]
|
148 |
+
input_bin_widths = widths.gather(-1, bin_idx)[..., 0]
|
149 |
+
|
150 |
+
input_cumheights = cumheights.gather(-1, bin_idx)[..., 0]
|
151 |
+
delta = heights / widths
|
152 |
+
input_delta = delta.gather(-1, bin_idx)[..., 0]
|
153 |
+
|
154 |
+
input_derivatives = derivatives.gather(-1, bin_idx)[..., 0]
|
155 |
+
input_derivatives_plus_one = derivatives[..., 1:].gather(-1, bin_idx)[..., 0]
|
156 |
+
|
157 |
+
input_heights = heights.gather(-1, bin_idx)[..., 0]
|
158 |
+
|
159 |
+
if inverse:
|
160 |
+
a = (inputs - input_cumheights) * (
|
161 |
+
input_derivatives + input_derivatives_plus_one - 2 * input_delta
|
162 |
+
) + input_heights * (input_delta - input_derivatives)
|
163 |
+
b = input_heights * input_derivatives - (inputs - input_cumheights) * (
|
164 |
+
input_derivatives + input_derivatives_plus_one - 2 * input_delta
|
165 |
+
)
|
166 |
+
c = -input_delta * (inputs - input_cumheights)
|
167 |
+
|
168 |
+
discriminant = b.pow(2) - 4 * a * c
|
169 |
+
assert (discriminant >= 0).all()
|
170 |
+
|
171 |
+
root = (2 * c) / (-b - torch.sqrt(discriminant))
|
172 |
+
outputs = root * input_bin_widths + input_cumwidths
|
173 |
+
|
174 |
+
theta_one_minus_theta = root * (1 - root)
|
175 |
+
denominator = input_delta + (
|
176 |
+
(input_derivatives + input_derivatives_plus_one - 2 * input_delta)
|
177 |
+
* theta_one_minus_theta
|
178 |
+
)
|
179 |
+
derivative_numerator = input_delta.pow(2) * (
|
180 |
+
input_derivatives_plus_one * root.pow(2)
|
181 |
+
+ 2 * input_delta * theta_one_minus_theta
|
182 |
+
+ input_derivatives * (1 - root).pow(2)
|
183 |
+
)
|
184 |
+
logabsdet = torch.log(derivative_numerator) - 2 * torch.log(denominator)
|
185 |
+
|
186 |
+
return outputs, -logabsdet
|
187 |
+
else:
|
188 |
+
theta = (inputs - input_cumwidths) / input_bin_widths
|
189 |
+
theta_one_minus_theta = theta * (1 - theta)
|
190 |
+
|
191 |
+
numerator = input_heights * (
|
192 |
+
input_delta * theta.pow(2) + input_derivatives * theta_one_minus_theta
|
193 |
+
)
|
194 |
+
denominator = input_delta + (
|
195 |
+
(input_derivatives + input_derivatives_plus_one - 2 * input_delta)
|
196 |
+
* theta_one_minus_theta
|
197 |
+
)
|
198 |
+
outputs = input_cumheights + numerator / denominator
|
199 |
+
|
200 |
+
derivative_numerator = input_delta.pow(2) * (
|
201 |
+
input_derivatives_plus_one * theta.pow(2)
|
202 |
+
+ 2 * input_delta * theta_one_minus_theta
|
203 |
+
+ input_derivatives * (1 - theta).pow(2)
|
204 |
+
)
|
205 |
+
logabsdet = torch.log(derivative_numerator) - 2 * torch.log(denominator)
|
206 |
+
|
207 |
+
return outputs, logabsdet
|
lib/infer_libs/rmvpe.py
ADDED
@@ -0,0 +1,705 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
|
3 |
+
import numpy as np
|
4 |
+
import torch
|
5 |
+
try:
|
6 |
+
#Fix "Torch not compiled with CUDA enabled"
|
7 |
+
import intel_extension_for_pytorch as ipex # pylint: disable=import-error, unused-import
|
8 |
+
if torch.xpu.is_available():
|
9 |
+
from lib.infer.modules.ipex import ipex_init
|
10 |
+
ipex_init()
|
11 |
+
except Exception:
|
12 |
+
pass
|
13 |
+
import torch.nn as nn
|
14 |
+
import torch.nn.functional as F
|
15 |
+
from librosa.util import normalize, pad_center, tiny
|
16 |
+
from scipy.signal import get_window
|
17 |
+
|
18 |
+
import logging
|
19 |
+
|
20 |
+
logger = logging.getLogger(__name__)
|
21 |
+
|
22 |
+
|
23 |
+
###stft codes from https://github.com/pseeth/torch-stft/blob/master/torch_stft/util.py
|
24 |
+
def window_sumsquare(
|
25 |
+
window,
|
26 |
+
n_frames,
|
27 |
+
hop_length=200,
|
28 |
+
win_length=800,
|
29 |
+
n_fft=800,
|
30 |
+
dtype=np.float32,
|
31 |
+
norm=None,
|
32 |
+
):
|
33 |
+
"""
|
34 |
+
# from librosa 0.6
|
35 |
+
Compute the sum-square envelope of a window function at a given hop length.
|
36 |
+
This is used to estimate modulation effects induced by windowing
|
37 |
+
observations in short-time fourier transforms.
|
38 |
+
Parameters
|
39 |
+
----------
|
40 |
+
window : string, tuple, number, callable, or list-like
|
41 |
+
Window specification, as in `get_window`
|
42 |
+
n_frames : int > 0
|
43 |
+
The number of analysis frames
|
44 |
+
hop_length : int > 0
|
45 |
+
The number of samples to advance between frames
|
46 |
+
win_length : [optional]
|
47 |
+
The length of the window function. By default, this matches `n_fft`.
|
48 |
+
n_fft : int > 0
|
49 |
+
The length of each analysis frame.
|
50 |
+
dtype : np.dtype
|
51 |
+
The data type of the output
|
52 |
+
Returns
|
53 |
+
-------
|
54 |
+
wss : np.ndarray, shape=`(n_fft + hop_length * (n_frames - 1))`
|
55 |
+
The sum-squared envelope of the window function
|
56 |
+
"""
|
57 |
+
if win_length is None:
|
58 |
+
win_length = n_fft
|
59 |
+
|
60 |
+
n = n_fft + hop_length * (n_frames - 1)
|
61 |
+
x = np.zeros(n, dtype=dtype)
|
62 |
+
|
63 |
+
# Compute the squared window at the desired length
|
64 |
+
win_sq = get_window(window, win_length, fftbins=True)
|
65 |
+
win_sq = normalize(win_sq, norm=norm) ** 2
|
66 |
+
win_sq = pad_center(win_sq, n_fft)
|
67 |
+
|
68 |
+
# Fill the envelope
|
69 |
+
for i in range(n_frames):
|
70 |
+
sample = i * hop_length
|
71 |
+
x[sample : min(n, sample + n_fft)] += win_sq[: max(0, min(n_fft, n - sample))]
|
72 |
+
return x
|
73 |
+
|
74 |
+
|
75 |
+
class STFT(torch.nn.Module):
|
76 |
+
def __init__(
|
77 |
+
self, filter_length=1024, hop_length=512, win_length=None, window="hann"
|
78 |
+
):
|
79 |
+
"""
|
80 |
+
This module implements an STFT using 1D convolution and 1D transpose convolutions.
|
81 |
+
This is a bit tricky so there are some cases that probably won't work as working
|
82 |
+
out the same sizes before and after in all overlap add setups is tough. Right now,
|
83 |
+
this code should work with hop lengths that are half the filter length (50% overlap
|
84 |
+
between frames).
|
85 |
+
|
86 |
+
Keyword Arguments:
|
87 |
+
filter_length {int} -- Length of filters used (default: {1024})
|
88 |
+
hop_length {int} -- Hop length of STFT (restrict to 50% overlap between frames) (default: {512})
|
89 |
+
win_length {[type]} -- Length of the window function applied to each frame (if not specified, it
|
90 |
+
equals the filter length). (default: {None})
|
91 |
+
window {str} -- Type of window to use (options are bartlett, hann, hamming, blackman, blackmanharris)
|
92 |
+
(default: {'hann'})
|
93 |
+
"""
|
94 |
+
super(STFT, self).__init__()
|
95 |
+
self.filter_length = filter_length
|
96 |
+
self.hop_length = hop_length
|
97 |
+
self.win_length = win_length if win_length else filter_length
|
98 |
+
self.window = window
|
99 |
+
self.forward_transform = None
|
100 |
+
self.pad_amount = int(self.filter_length / 2)
|
101 |
+
#scale = self.filter_length / self.hop_length
|
102 |
+
fourier_basis = np.fft.fft(np.eye(self.filter_length))
|
103 |
+
|
104 |
+
cutoff = int((self.filter_length / 2 + 1))
|
105 |
+
fourier_basis = np.vstack(
|
106 |
+
[np.real(fourier_basis[:cutoff, :]), np.imag(fourier_basis[:cutoff, :])]
|
107 |
+
)
|
108 |
+
forward_basis = torch.FloatTensor(fourier_basis)
|
109 |
+
inverse_basis = torch.FloatTensor(
|
110 |
+
np.linalg.pinv(fourier_basis)
|
111 |
+
)
|
112 |
+
|
113 |
+
assert filter_length >= self.win_length
|
114 |
+
# get window and zero center pad it to filter_length
|
115 |
+
fft_window = get_window(window, self.win_length, fftbins=True)
|
116 |
+
fft_window = pad_center(fft_window, size=filter_length)
|
117 |
+
fft_window = torch.from_numpy(fft_window).float()
|
118 |
+
|
119 |
+
# window the bases
|
120 |
+
forward_basis *= fft_window
|
121 |
+
inverse_basis = (inverse_basis.T * fft_window).T
|
122 |
+
|
123 |
+
self.register_buffer("forward_basis", forward_basis.float())
|
124 |
+
self.register_buffer("inverse_basis", inverse_basis.float())
|
125 |
+
self.register_buffer("fft_window", fft_window.float())
|
126 |
+
|
127 |
+
def transform(self, input_data, return_phase=False):
|
128 |
+
"""Take input data (audio) to STFT domain.
|
129 |
+
|
130 |
+
Arguments:
|
131 |
+
input_data {tensor} -- Tensor of floats, with shape (num_batch, num_samples)
|
132 |
+
|
133 |
+
Returns:
|
134 |
+
magnitude {tensor} -- Magnitude of STFT with shape (num_batch,
|
135 |
+
num_frequencies, num_frames)
|
136 |
+
phase {tensor} -- Phase of STFT with shape (num_batch,
|
137 |
+
num_frequencies, num_frames)
|
138 |
+
"""
|
139 |
+
# num_batches = input_data.shape[0]
|
140 |
+
# num_samples = input_data.shape[-1]
|
141 |
+
|
142 |
+
# self.num_samples = num_samples
|
143 |
+
|
144 |
+
# similar to librosa, reflect-pad the input
|
145 |
+
# input_data = input_data.view(num_batches, 1, num_samples)
|
146 |
+
# print(1234,input_data.shape)
|
147 |
+
input_data = F.pad(
|
148 |
+
input_data,
|
149 |
+
(self.pad_amount, self.pad_amount),
|
150 |
+
mode="reflect",
|
151 |
+
)
|
152 |
+
|
153 |
+
forward_transform = input_data.unfold(1, self.filter_length, self.hop_length).permute(0, 2, 1)
|
154 |
+
forward_transform = torch.matmul(self.forward_basis, forward_transform)
|
155 |
+
|
156 |
+
cutoff = int((self.filter_length / 2) + 1)
|
157 |
+
real_part = forward_transform[:, :cutoff, :]
|
158 |
+
imag_part = forward_transform[:, cutoff:, :]
|
159 |
+
|
160 |
+
magnitude = torch.sqrt(real_part**2 + imag_part**2)
|
161 |
+
# phase = torch.atan2(imag_part.data, real_part.data)
|
162 |
+
|
163 |
+
if return_phase:
|
164 |
+
phase = torch.atan2(imag_part.data, real_part.data)
|
165 |
+
return magnitude, phase
|
166 |
+
else:
|
167 |
+
return magnitude
|
168 |
+
|
169 |
+
def inverse(self, magnitude, phase):
|
170 |
+
"""Call the inverse STFT (iSTFT), given magnitude and phase tensors produced
|
171 |
+
by the ```transform``` function.
|
172 |
+
|
173 |
+
Arguments:
|
174 |
+
magnitude {tensor} -- Magnitude of STFT with shape (num_batch,
|
175 |
+
num_frequencies, num_frames)
|
176 |
+
phase {tensor} -- Phase of STFT with shape (num_batch,
|
177 |
+
num_frequencies, num_frames)
|
178 |
+
|
179 |
+
Returns:
|
180 |
+
inverse_transform {tensor} -- Reconstructed audio given magnitude and phase. Of
|
181 |
+
shape (num_batch, num_samples)
|
182 |
+
"""
|
183 |
+
cat = torch.cat(
|
184 |
+
[magnitude * torch.cos(phase), magnitude * torch.sin(phase)], dim=1
|
185 |
+
)
|
186 |
+
|
187 |
+
fold = torch.nn.Fold(
|
188 |
+
output_size=(1, (cat.size(-1) - 1) * self.hop_length + self.filter_length),
|
189 |
+
kernel_size=(1, self.filter_length),
|
190 |
+
stride=(1, self.hop_length))
|
191 |
+
inverse_transform = torch.matmul(self.inverse_basis, cat)
|
192 |
+
inverse_transform = fold(inverse_transform)[:, 0, 0, self.pad_amount : -self.pad_amount]
|
193 |
+
window_square_sum = self.fft_window.pow(2).repeat(cat.size(-1), 1).T.unsqueeze(0)
|
194 |
+
window_square_sum = fold(window_square_sum)[:, 0, 0, self.pad_amount : -self.pad_amount]
|
195 |
+
inverse_transform /= window_square_sum
|
196 |
+
|
197 |
+
return inverse_transform
|
198 |
+
|
199 |
+
def forward(self, input_data):
|
200 |
+
"""Take input data (audio) to STFT domain and then back to audio.
|
201 |
+
|
202 |
+
Arguments:
|
203 |
+
input_data {tensor} -- Tensor of floats, with shape (num_batch, num_samples)
|
204 |
+
|
205 |
+
Returns:
|
206 |
+
reconstruction {tensor} -- Reconstructed audio given magnitude and phase. Of
|
207 |
+
shape (num_batch, num_samples)
|
208 |
+
"""
|
209 |
+
self.magnitude, self.phase = self.transform(input_data, return_phase=True)
|
210 |
+
reconstruction = self.inverse(self.magnitude, self.phase)
|
211 |
+
return reconstruction
|
212 |
+
|
213 |
+
|
214 |
+
from time import time as ttime
|
215 |
+
|
216 |
+
|
217 |
+
class BiGRU(nn.Module):
|
218 |
+
def __init__(self, input_features, hidden_features, num_layers):
|
219 |
+
super(BiGRU, self).__init__()
|
220 |
+
self.gru = nn.GRU(
|
221 |
+
input_features,
|
222 |
+
hidden_features,
|
223 |
+
num_layers=num_layers,
|
224 |
+
batch_first=True,
|
225 |
+
bidirectional=True,
|
226 |
+
)
|
227 |
+
|
228 |
+
def forward(self, x):
|
229 |
+
return self.gru(x)[0]
|
230 |
+
|
231 |
+
|
232 |
+
class ConvBlockRes(nn.Module):
|
233 |
+
def __init__(self, in_channels, out_channels, momentum=0.01):
|
234 |
+
super(ConvBlockRes, self).__init__()
|
235 |
+
self.conv = nn.Sequential(
|
236 |
+
nn.Conv2d(
|
237 |
+
in_channels=in_channels,
|
238 |
+
out_channels=out_channels,
|
239 |
+
kernel_size=(3, 3),
|
240 |
+
stride=(1, 1),
|
241 |
+
padding=(1, 1),
|
242 |
+
bias=False,
|
243 |
+
),
|
244 |
+
nn.BatchNorm2d(out_channels, momentum=momentum),
|
245 |
+
nn.ReLU(),
|
246 |
+
nn.Conv2d(
|
247 |
+
in_channels=out_channels,
|
248 |
+
out_channels=out_channels,
|
249 |
+
kernel_size=(3, 3),
|
250 |
+
stride=(1, 1),
|
251 |
+
padding=(1, 1),
|
252 |
+
bias=False,
|
253 |
+
),
|
254 |
+
nn.BatchNorm2d(out_channels, momentum=momentum),
|
255 |
+
nn.ReLU(),
|
256 |
+
)
|
257 |
+
if in_channels != out_channels:
|
258 |
+
self.shortcut = nn.Conv2d(in_channels, out_channels, (1, 1))
|
259 |
+
self.is_shortcut = True
|
260 |
+
else:
|
261 |
+
self.is_shortcut = False
|
262 |
+
|
263 |
+
def forward(self, x):
|
264 |
+
if self.is_shortcut:
|
265 |
+
return self.conv(x) + self.shortcut(x)
|
266 |
+
else:
|
267 |
+
return self.conv(x) + x
|
268 |
+
|
269 |
+
|
270 |
+
class Encoder(nn.Module):
|
271 |
+
def __init__(
|
272 |
+
self,
|
273 |
+
in_channels,
|
274 |
+
in_size,
|
275 |
+
n_encoders,
|
276 |
+
kernel_size,
|
277 |
+
n_blocks,
|
278 |
+
out_channels=16,
|
279 |
+
momentum=0.01,
|
280 |
+
):
|
281 |
+
super(Encoder, self).__init__()
|
282 |
+
self.n_encoders = n_encoders
|
283 |
+
self.bn = nn.BatchNorm2d(in_channels, momentum=momentum)
|
284 |
+
self.layers = nn.ModuleList()
|
285 |
+
self.latent_channels = []
|
286 |
+
for i in range(self.n_encoders):
|
287 |
+
self.layers.append(
|
288 |
+
ResEncoderBlock(
|
289 |
+
in_channels, out_channels, kernel_size, n_blocks, momentum=momentum
|
290 |
+
)
|
291 |
+
)
|
292 |
+
self.latent_channels.append([out_channels, in_size])
|
293 |
+
in_channels = out_channels
|
294 |
+
out_channels *= 2
|
295 |
+
in_size //= 2
|
296 |
+
self.out_size = in_size
|
297 |
+
self.out_channel = out_channels
|
298 |
+
|
299 |
+
def forward(self, x):
|
300 |
+
concat_tensors = []
|
301 |
+
x = self.bn(x)
|
302 |
+
for i in range(self.n_encoders):
|
303 |
+
_, x = self.layers[i](x)
|
304 |
+
concat_tensors.append(_)
|
305 |
+
return x, concat_tensors
|
306 |
+
|
307 |
+
|
308 |
+
class ResEncoderBlock(nn.Module):
|
309 |
+
def __init__(
|
310 |
+
self, in_channels, out_channels, kernel_size, n_blocks=1, momentum=0.01
|
311 |
+
):
|
312 |
+
super(ResEncoderBlock, self).__init__()
|
313 |
+
self.n_blocks = n_blocks
|
314 |
+
self.conv = nn.ModuleList()
|
315 |
+
self.conv.append(ConvBlockRes(in_channels, out_channels, momentum))
|
316 |
+
for i in range(n_blocks - 1):
|
317 |
+
self.conv.append(ConvBlockRes(out_channels, out_channels, momentum))
|
318 |
+
self.kernel_size = kernel_size
|
319 |
+
if self.kernel_size is not None:
|
320 |
+
self.pool = nn.AvgPool2d(kernel_size=kernel_size)
|
321 |
+
|
322 |
+
def forward(self, x):
|
323 |
+
for i in range(self.n_blocks):
|
324 |
+
x = self.conv[i](x)
|
325 |
+
if self.kernel_size is not None:
|
326 |
+
return x, self.pool(x)
|
327 |
+
else:
|
328 |
+
return x
|
329 |
+
|
330 |
+
|
331 |
+
class Intermediate(nn.Module): #
|
332 |
+
def __init__(self, in_channels, out_channels, n_inters, n_blocks, momentum=0.01):
|
333 |
+
super(Intermediate, self).__init__()
|
334 |
+
self.n_inters = n_inters
|
335 |
+
self.layers = nn.ModuleList()
|
336 |
+
self.layers.append(
|
337 |
+
ResEncoderBlock(in_channels, out_channels, None, n_blocks, momentum)
|
338 |
+
)
|
339 |
+
for i in range(self.n_inters - 1):
|
340 |
+
self.layers.append(
|
341 |
+
ResEncoderBlock(out_channels, out_channels, None, n_blocks, momentum)
|
342 |
+
)
|
343 |
+
|
344 |
+
def forward(self, x):
|
345 |
+
for i in range(self.n_inters):
|
346 |
+
x = self.layers[i](x)
|
347 |
+
return x
|
348 |
+
|
349 |
+
|
350 |
+
class ResDecoderBlock(nn.Module):
|
351 |
+
def __init__(self, in_channels, out_channels, stride, n_blocks=1, momentum=0.01):
|
352 |
+
super(ResDecoderBlock, self).__init__()
|
353 |
+
out_padding = (0, 1) if stride == (1, 2) else (1, 1)
|
354 |
+
self.n_blocks = n_blocks
|
355 |
+
self.conv1 = nn.Sequential(
|
356 |
+
nn.ConvTranspose2d(
|
357 |
+
in_channels=in_channels,
|
358 |
+
out_channels=out_channels,
|
359 |
+
kernel_size=(3, 3),
|
360 |
+
stride=stride,
|
361 |
+
padding=(1, 1),
|
362 |
+
output_padding=out_padding,
|
363 |
+
bias=False,
|
364 |
+
),
|
365 |
+
nn.BatchNorm2d(out_channels, momentum=momentum),
|
366 |
+
nn.ReLU(),
|
367 |
+
)
|
368 |
+
self.conv2 = nn.ModuleList()
|
369 |
+
self.conv2.append(ConvBlockRes(out_channels * 2, out_channels, momentum))
|
370 |
+
for i in range(n_blocks - 1):
|
371 |
+
self.conv2.append(ConvBlockRes(out_channels, out_channels, momentum))
|
372 |
+
|
373 |
+
def forward(self, x, concat_tensor):
|
374 |
+
x = self.conv1(x)
|
375 |
+
x = torch.cat((x, concat_tensor), dim=1)
|
376 |
+
for i in range(self.n_blocks):
|
377 |
+
x = self.conv2[i](x)
|
378 |
+
return x
|
379 |
+
|
380 |
+
|
381 |
+
class Decoder(nn.Module):
|
382 |
+
def __init__(self, in_channels, n_decoders, stride, n_blocks, momentum=0.01):
|
383 |
+
super(Decoder, self).__init__()
|
384 |
+
self.layers = nn.ModuleList()
|
385 |
+
self.n_decoders = n_decoders
|
386 |
+
for i in range(self.n_decoders):
|
387 |
+
out_channels = in_channels // 2
|
388 |
+
self.layers.append(
|
389 |
+
ResDecoderBlock(in_channels, out_channels, stride, n_blocks, momentum)
|
390 |
+
)
|
391 |
+
in_channels = out_channels
|
392 |
+
|
393 |
+
def forward(self, x, concat_tensors):
|
394 |
+
for i in range(self.n_decoders):
|
395 |
+
x = self.layers[i](x, concat_tensors[-1 - i])
|
396 |
+
return x
|
397 |
+
|
398 |
+
|
399 |
+
class DeepUnet(nn.Module):
|
400 |
+
def __init__(
|
401 |
+
self,
|
402 |
+
kernel_size,
|
403 |
+
n_blocks,
|
404 |
+
en_de_layers=5,
|
405 |
+
inter_layers=4,
|
406 |
+
in_channels=1,
|
407 |
+
en_out_channels=16,
|
408 |
+
):
|
409 |
+
super(DeepUnet, self).__init__()
|
410 |
+
self.encoder = Encoder(
|
411 |
+
in_channels, 128, en_de_layers, kernel_size, n_blocks, en_out_channels
|
412 |
+
)
|
413 |
+
self.intermediate = Intermediate(
|
414 |
+
self.encoder.out_channel // 2,
|
415 |
+
self.encoder.out_channel,
|
416 |
+
inter_layers,
|
417 |
+
n_blocks,
|
418 |
+
)
|
419 |
+
self.decoder = Decoder(
|
420 |
+
self.encoder.out_channel, en_de_layers, kernel_size, n_blocks
|
421 |
+
)
|
422 |
+
|
423 |
+
def forward(self, x):
|
424 |
+
x, concat_tensors = self.encoder(x)
|
425 |
+
x = self.intermediate(x)
|
426 |
+
x = self.decoder(x, concat_tensors)
|
427 |
+
return x
|
428 |
+
|
429 |
+
|
430 |
+
class E2E(nn.Module):
|
431 |
+
def __init__(
|
432 |
+
self,
|
433 |
+
n_blocks,
|
434 |
+
n_gru,
|
435 |
+
kernel_size,
|
436 |
+
en_de_layers=5,
|
437 |
+
inter_layers=4,
|
438 |
+
in_channels=1,
|
439 |
+
en_out_channels=16,
|
440 |
+
):
|
441 |
+
super(E2E, self).__init__()
|
442 |
+
self.unet = DeepUnet(
|
443 |
+
kernel_size,
|
444 |
+
n_blocks,
|
445 |
+
en_de_layers,
|
446 |
+
inter_layers,
|
447 |
+
in_channels,
|
448 |
+
en_out_channels,
|
449 |
+
)
|
450 |
+
self.cnn = nn.Conv2d(en_out_channels, 3, (3, 3), padding=(1, 1))
|
451 |
+
if n_gru:
|
452 |
+
self.fc = nn.Sequential(
|
453 |
+
BiGRU(3 * 128, 256, n_gru),
|
454 |
+
nn.Linear(512, 360),
|
455 |
+
nn.Dropout(0.25),
|
456 |
+
nn.Sigmoid(),
|
457 |
+
)
|
458 |
+
else:
|
459 |
+
self.fc = nn.Sequential(
|
460 |
+
nn.Linear(3 * nn.N_MELS, nn.N_CLASS), nn.Dropout(0.25), nn.Sigmoid()
|
461 |
+
)
|
462 |
+
|
463 |
+
def forward(self, mel):
|
464 |
+
# print(mel.shape)
|
465 |
+
mel = mel.transpose(-1, -2).unsqueeze(1)
|
466 |
+
x = self.cnn(self.unet(mel)).transpose(1, 2).flatten(-2)
|
467 |
+
x = self.fc(x)
|
468 |
+
# print(x.shape)
|
469 |
+
return x
|
470 |
+
|
471 |
+
|
472 |
+
from librosa.filters import mel
|
473 |
+
|
474 |
+
|
475 |
+
class MelSpectrogram(torch.nn.Module):
|
476 |
+
def __init__(
|
477 |
+
self,
|
478 |
+
is_half,
|
479 |
+
n_mel_channels,
|
480 |
+
sampling_rate,
|
481 |
+
win_length,
|
482 |
+
hop_length,
|
483 |
+
n_fft=None,
|
484 |
+
mel_fmin=0,
|
485 |
+
mel_fmax=None,
|
486 |
+
clamp=1e-5,
|
487 |
+
):
|
488 |
+
super().__init__()
|
489 |
+
n_fft = win_length if n_fft is None else n_fft
|
490 |
+
self.hann_window = {}
|
491 |
+
mel_basis = mel(
|
492 |
+
sr=sampling_rate,
|
493 |
+
n_fft=n_fft,
|
494 |
+
n_mels=n_mel_channels,
|
495 |
+
fmin=mel_fmin,
|
496 |
+
fmax=mel_fmax,
|
497 |
+
htk=True,
|
498 |
+
)
|
499 |
+
mel_basis = torch.from_numpy(mel_basis).float()
|
500 |
+
self.register_buffer("mel_basis", mel_basis)
|
501 |
+
self.n_fft = win_length if n_fft is None else n_fft
|
502 |
+
self.hop_length = hop_length
|
503 |
+
self.win_length = win_length
|
504 |
+
self.sampling_rate = sampling_rate
|
505 |
+
self.n_mel_channels = n_mel_channels
|
506 |
+
self.clamp = clamp
|
507 |
+
self.is_half = is_half
|
508 |
+
|
509 |
+
def forward(self, audio, keyshift=0, speed=1, center=True):
|
510 |
+
factor = 2 ** (keyshift / 12)
|
511 |
+
n_fft_new = int(np.round(self.n_fft * factor))
|
512 |
+
win_length_new = int(np.round(self.win_length * factor))
|
513 |
+
hop_length_new = int(np.round(self.hop_length * speed))
|
514 |
+
keyshift_key = str(keyshift) + "_" + str(audio.device)
|
515 |
+
if keyshift_key not in self.hann_window:
|
516 |
+
self.hann_window[keyshift_key] = torch.hann_window(win_length_new).to(
|
517 |
+
# "cpu"if(audio.device.type=="privateuseone") else audio.device
|
518 |
+
audio.device
|
519 |
+
)
|
520 |
+
if "privateuseone" in str(audio.device):
|
521 |
+
if not hasattr(self, "stft"):
|
522 |
+
self.stft = STFT(
|
523 |
+
filter_length=n_fft_new,
|
524 |
+
hop_length=hop_length_new,
|
525 |
+
win_length=win_length_new,
|
526 |
+
window="hann",
|
527 |
+
).to(audio.device)
|
528 |
+
magnitude = self.stft.transform(audio)
|
529 |
+
else:
|
530 |
+
fft = torch.stft(
|
531 |
+
audio,
|
532 |
+
n_fft=n_fft_new,
|
533 |
+
hop_length=hop_length_new,
|
534 |
+
win_length=win_length_new,
|
535 |
+
window=self.hann_window[keyshift_key],
|
536 |
+
center=center,
|
537 |
+
return_complex=True,
|
538 |
+
)
|
539 |
+
magnitude = torch.sqrt(fft.real.pow(2) + fft.imag.pow(2))
|
540 |
+
# if (audio.device.type == "privateuseone"):
|
541 |
+
# magnitude=magnitude.to(audio.device)
|
542 |
+
if keyshift != 0:
|
543 |
+
size = self.n_fft // 2 + 1
|
544 |
+
resize = magnitude.size(1)
|
545 |
+
if resize < size:
|
546 |
+
magnitude = F.pad(magnitude, (0, 0, 0, size - resize))
|
547 |
+
magnitude = magnitude[:, :size, :] * self.win_length / win_length_new
|
548 |
+
mel_output = torch.matmul(self.mel_basis, magnitude)
|
549 |
+
if self.is_half == True:
|
550 |
+
mel_output = mel_output.half()
|
551 |
+
log_mel_spec = torch.log(torch.clamp(mel_output, min=self.clamp))
|
552 |
+
# print(log_mel_spec.device.type)
|
553 |
+
return log_mel_spec
|
554 |
+
|
555 |
+
|
556 |
+
class RMVPE:
|
557 |
+
def __init__(self, model_path, is_half, device=None):
|
558 |
+
self.resample_kernel = {}
|
559 |
+
self.resample_kernel = {}
|
560 |
+
self.is_half = is_half
|
561 |
+
if device is None:
|
562 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
563 |
+
self.device = device
|
564 |
+
self.mel_extractor = MelSpectrogram(
|
565 |
+
is_half, 128, 16000, 1024, 160, None, 30, 8000
|
566 |
+
).to(device)
|
567 |
+
if "privateuseone" in str(device):
|
568 |
+
import onnxruntime as ort
|
569 |
+
|
570 |
+
ort_session = ort.InferenceSession(
|
571 |
+
"%s/rmvpe.onnx" % os.environ["rmvpe_root"],
|
572 |
+
providers=["DmlExecutionProvider"],
|
573 |
+
)
|
574 |
+
self.model = ort_session
|
575 |
+
else:
|
576 |
+
model = E2E(4, 1, (2, 2))
|
577 |
+
ckpt = torch.load(model_path, map_location="cpu")
|
578 |
+
model.load_state_dict(ckpt)
|
579 |
+
model.eval()
|
580 |
+
if is_half == True:
|
581 |
+
model = model.half()
|
582 |
+
self.model = model
|
583 |
+
self.model = self.model.to(device)
|
584 |
+
cents_mapping = 20 * np.arange(360) + 1997.3794084376191
|
585 |
+
self.cents_mapping = np.pad(cents_mapping, (4, 4)) # 368
|
586 |
+
|
587 |
+
def mel2hidden(self, mel):
|
588 |
+
with torch.no_grad():
|
589 |
+
n_frames = mel.shape[-1]
|
590 |
+
n_pad = 32 * ((n_frames - 1) // 32 + 1) - n_frames
|
591 |
+
if n_pad > 0:
|
592 |
+
mel = F.pad(
|
593 |
+
mel, (0, n_pad), mode="constant"
|
594 |
+
)
|
595 |
+
if "privateuseone" in str(self.device):
|
596 |
+
onnx_input_name = self.model.get_inputs()[0].name
|
597 |
+
onnx_outputs_names = self.model.get_outputs()[0].name
|
598 |
+
hidden = self.model.run(
|
599 |
+
[onnx_outputs_names],
|
600 |
+
input_feed={onnx_input_name: mel.cpu().numpy()},
|
601 |
+
)[0]
|
602 |
+
else:
|
603 |
+
hidden = self.model(mel)
|
604 |
+
return hidden[:, :n_frames]
|
605 |
+
|
606 |
+
def decode(self, hidden, thred=0.03):
|
607 |
+
cents_pred = self.to_local_average_cents(hidden, thred=thred)
|
608 |
+
f0 = 10 * (2 ** (cents_pred / 1200))
|
609 |
+
f0[f0 == 10] = 0
|
610 |
+
# f0 = np.array([10 * (2 ** (cent_pred / 1200)) if cent_pred else 0 for cent_pred in cents_pred])
|
611 |
+
return f0
|
612 |
+
|
613 |
+
def infer_from_audio(self, audio, thred=0.03):
|
614 |
+
# torch.cuda.synchronize()
|
615 |
+
t0 = ttime()
|
616 |
+
mel = self.mel_extractor(
|
617 |
+
torch.from_numpy(audio).float().to(self.device).unsqueeze(0), center=True
|
618 |
+
)
|
619 |
+
# print(123123123,mel.device.type)
|
620 |
+
# torch.cuda.synchronize()
|
621 |
+
t1 = ttime()
|
622 |
+
hidden = self.mel2hidden(mel)
|
623 |
+
# torch.cuda.synchronize()
|
624 |
+
t2 = ttime()
|
625 |
+
# print(234234,hidden.device.type)
|
626 |
+
if "privateuseone" not in str(self.device):
|
627 |
+
hidden = hidden.squeeze(0).cpu().numpy()
|
628 |
+
else:
|
629 |
+
hidden = hidden[0]
|
630 |
+
if self.is_half == True:
|
631 |
+
hidden = hidden.astype("float32")
|
632 |
+
|
633 |
+
f0 = self.decode(hidden, thred=thred)
|
634 |
+
# torch.cuda.synchronize()
|
635 |
+
t3 = ttime()
|
636 |
+
# print("hmvpe:%s\t%s\t%s\t%s"%(t1-t0,t2-t1,t3-t2,t3-t0))
|
637 |
+
return f0
|
638 |
+
|
639 |
+
def infer_from_audio_with_pitch(self, audio, thred=0.03, f0_min=50, f0_max=1100):
|
640 |
+
t0 = ttime()
|
641 |
+
audio = torch.from_numpy(audio).float().to(self.device).unsqueeze(0)
|
642 |
+
mel = self.mel_extractor(audio, center=True)
|
643 |
+
t1 = ttime()
|
644 |
+
hidden = self.mel2hidden(mel)
|
645 |
+
t2 = ttime()
|
646 |
+
if "privateuseone" not in str(self.device):
|
647 |
+
hidden = hidden.squeeze(0).cpu().numpy()
|
648 |
+
else:
|
649 |
+
hidden = hidden[0]
|
650 |
+
if self.is_half == True:
|
651 |
+
hidden = hidden.astype("float32")
|
652 |
+
f0 = self.decode(hidden, thred=thred)
|
653 |
+
f0[(f0 < f0_min) | (f0 > f0_max)] = 0
|
654 |
+
t3 = ttime()
|
655 |
+
return f0
|
656 |
+
|
657 |
+
def to_local_average_cents(self, salience, thred=0.05):
|
658 |
+
# t0 = ttime()
|
659 |
+
center = np.argmax(salience, axis=1) # 帧长#index
|
660 |
+
salience = np.pad(salience, ((0, 0), (4, 4))) # 帧长,368
|
661 |
+
# t1 = ttime()
|
662 |
+
center += 4
|
663 |
+
todo_salience = []
|
664 |
+
todo_cents_mapping = []
|
665 |
+
starts = center - 4
|
666 |
+
ends = center + 5
|
667 |
+
for idx in range(salience.shape[0]):
|
668 |
+
todo_salience.append(salience[:, starts[idx] : ends[idx]][idx])
|
669 |
+
todo_cents_mapping.append(self.cents_mapping[starts[idx] : ends[idx]])
|
670 |
+
# t2 = ttime()
|
671 |
+
todo_salience = np.array(todo_salience) # 帧长,9
|
672 |
+
todo_cents_mapping = np.array(todo_cents_mapping) # 帧长,9
|
673 |
+
product_sum = np.sum(todo_salience * todo_cents_mapping, 1)
|
674 |
+
weight_sum = np.sum(todo_salience, 1) # 帧长
|
675 |
+
devided = product_sum / weight_sum # 帧长
|
676 |
+
# t3 = ttime()
|
677 |
+
maxx = np.max(salience, axis=1) # 帧长
|
678 |
+
devided[maxx <= thred] = 0
|
679 |
+
# t4 = ttime()
|
680 |
+
# print("decode:%s\t%s\t%s\t%s" % (t1 - t0, t2 - t1, t3 - t2, t4 - t3))
|
681 |
+
return devided
|
682 |
+
|
683 |
+
|
684 |
+
if __name__ == "__main__":
|
685 |
+
import librosa
|
686 |
+
import soundfile as sf
|
687 |
+
|
688 |
+
audio, sampling_rate = sf.read(r"C:\Users\liujing04\Desktop\Z\冬之花clip1.wav")
|
689 |
+
if len(audio.shape) > 1:
|
690 |
+
audio = librosa.to_mono(audio.transpose(1, 0))
|
691 |
+
audio_bak = audio.copy()
|
692 |
+
if sampling_rate != 16000:
|
693 |
+
audio = librosa.resample(audio, orig_sr=sampling_rate, target_sr=16000)
|
694 |
+
model_path = r"D:\BaiduNetdiskDownload\RVC-beta-v2-0727AMD_realtime\rmvpe.pt"
|
695 |
+
thred = 0.03 # 0.01
|
696 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
697 |
+
rmvpe = RMVPE(model_path, is_half=False, device=device)
|
698 |
+
t0 = ttime()
|
699 |
+
f0 = rmvpe.infer_from_audio(audio, thred=thred)
|
700 |
+
# f0 = rmvpe.infer_from_audio(audio, thred=thred)
|
701 |
+
# f0 = rmvpe.infer_from_audio(audio, thred=thred)
|
702 |
+
# f0 = rmvpe.infer_from_audio(audio, thred=thred)
|
703 |
+
# f0 = rmvpe.infer_from_audio(audio, thred=thred)
|
704 |
+
t1 = ttime()
|
705 |
+
logger.info("%s %.2f", f0.shape, t1 - t0)
|
lib/modules.py
ADDED
@@ -0,0 +1,559 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
)
|
lib/pipeline.py
ADDED
@@ -0,0 +1,773 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import sys
|
3 |
+
import gc
|
4 |
+
import traceback
|
5 |
+
import logging
|
6 |
+
|
7 |
+
logger = logging.getLogger(__name__)
|
8 |
+
|
9 |
+
from functools import lru_cache
|
10 |
+
from time import time as ttime
|
11 |
+
from torch import Tensor
|
12 |
+
import faiss
|
13 |
+
import librosa
|
14 |
+
import numpy as np
|
15 |
+
import parselmouth
|
16 |
+
import pyworld
|
17 |
+
import torch.nn.functional as F
|
18 |
+
from scipy import signal
|
19 |
+
from tqdm import tqdm
|
20 |
+
|
21 |
+
import random
|
22 |
+
now_dir = os.getcwd()
|
23 |
+
sys.path.append(now_dir)
|
24 |
+
import re
|
25 |
+
from functools import partial
|
26 |
+
bh, ah = signal.butter(N=5, Wn=48, btype="high", fs=16000)
|
27 |
+
|
28 |
+
input_audio_path2wav = {}
|
29 |
+
import torchcrepe # Fork Feature. Crepe algo for training and preprocess
|
30 |
+
from torchfcpe import spawn_bundled_infer_model
|
31 |
+
import torch
|
32 |
+
from lib.infer_libs.rmvpe import RMVPE
|
33 |
+
from lib.infer_libs.fcpe import FCPE
|
34 |
+
|
35 |
+
@lru_cache
|
36 |
+
def cache_harvest_f0(input_audio_path, fs, f0max, f0min, frame_period):
|
37 |
+
audio = input_audio_path2wav[input_audio_path]
|
38 |
+
f0, t = pyworld.harvest(
|
39 |
+
audio,
|
40 |
+
fs=fs,
|
41 |
+
f0_ceil=f0max,
|
42 |
+
f0_floor=f0min,
|
43 |
+
frame_period=frame_period,
|
44 |
+
)
|
45 |
+
f0 = pyworld.stonemask(audio, f0, t, fs)
|
46 |
+
return f0
|
47 |
+
|
48 |
+
|
49 |
+
def change_rms(data1, sr1, data2, sr2, rate): # 1是输入音频,2是输出音频,rate是2的占比
|
50 |
+
# print(data1.max(),data2.max())
|
51 |
+
rms1 = librosa.feature.rms(
|
52 |
+
y=data1, frame_length=sr1 // 2 * 2, hop_length=sr1 // 2
|
53 |
+
) # 每半秒一个点
|
54 |
+
rms2 = librosa.feature.rms(y=data2, frame_length=sr2 // 2 * 2, hop_length=sr2 // 2)
|
55 |
+
rms1 = torch.from_numpy(rms1)
|
56 |
+
rms1 = F.interpolate(
|
57 |
+
rms1.unsqueeze(0), size=data2.shape[0], mode="linear"
|
58 |
+
).squeeze()
|
59 |
+
rms2 = torch.from_numpy(rms2)
|
60 |
+
rms2 = F.interpolate(
|
61 |
+
rms2.unsqueeze(0), size=data2.shape[0], mode="linear"
|
62 |
+
).squeeze()
|
63 |
+
rms2 = torch.max(rms2, torch.zeros_like(rms2) + 1e-6)
|
64 |
+
data2 *= (
|
65 |
+
torch.pow(rms1, torch.tensor(1 - rate))
|
66 |
+
* torch.pow(rms2, torch.tensor(rate - 1))
|
67 |
+
).numpy()
|
68 |
+
return data2
|
69 |
+
|
70 |
+
|
71 |
+
class Pipeline(object):
|
72 |
+
def __init__(self, tgt_sr, config):
|
73 |
+
self.x_pad, self.x_query, self.x_center, self.x_max, self.is_half = (
|
74 |
+
config.x_pad,
|
75 |
+
config.x_query,
|
76 |
+
config.x_center,
|
77 |
+
config.x_max,
|
78 |
+
config.is_half,
|
79 |
+
)
|
80 |
+
self.sr = 16000 # hubert输入采样率
|
81 |
+
self.window = 160 # 每帧点数
|
82 |
+
self.t_pad = self.sr * self.x_pad # 每条前后pad时间
|
83 |
+
self.t_pad_tgt = tgt_sr * self.x_pad
|
84 |
+
self.t_pad2 = self.t_pad * 2
|
85 |
+
self.t_query = self.sr * self.x_query # 查询切点前后查询时间
|
86 |
+
self.t_center = self.sr * self.x_center # 查询切点位置
|
87 |
+
self.t_max = self.sr * self.x_max # 免查询时长阈值
|
88 |
+
self.device = config.device
|
89 |
+
self.model_rmvpe = RMVPE(os.environ["rmvpe_model_path"], is_half=self.is_half, device=self.device)
|
90 |
+
|
91 |
+
self.note_dict = [
|
92 |
+
65.41, 69.30, 73.42, 77.78, 82.41, 87.31,
|
93 |
+
92.50, 98.00, 103.83, 110.00, 116.54, 123.47,
|
94 |
+
130.81, 138.59, 146.83, 155.56, 164.81, 174.61,
|
95 |
+
185.00, 196.00, 207.65, 220.00, 233.08, 246.94,
|
96 |
+
261.63, 277.18, 293.66, 311.13, 329.63, 349.23,
|
97 |
+
369.99, 392.00, 415.30, 440.00, 466.16, 493.88,
|
98 |
+
523.25, 554.37, 587.33, 622.25, 659.25, 698.46,
|
99 |
+
739.99, 783.99, 830.61, 880.00, 932.33, 987.77,
|
100 |
+
1046.50, 1108.73, 1174.66, 1244.51, 1318.51, 1396.91,
|
101 |
+
1479.98, 1567.98, 1661.22, 1760.00, 1864.66, 1975.53,
|
102 |
+
2093.00, 2217.46, 2349.32, 2489.02, 2637.02, 2793.83,
|
103 |
+
2959.96, 3135.96, 3322.44, 3520.00, 3729.31, 3951.07
|
104 |
+
]
|
105 |
+
|
106 |
+
# Fork Feature: Get the best torch device to use for f0 algorithms that require a torch device. Will return the type (torch.device)
|
107 |
+
def get_optimal_torch_device(self, index: int = 0) -> torch.device:
|
108 |
+
if torch.cuda.is_available():
|
109 |
+
return torch.device(
|
110 |
+
f"cuda:{index % torch.cuda.device_count()}"
|
111 |
+
) # Very fast
|
112 |
+
elif torch.backends.mps.is_available():
|
113 |
+
return torch.device("mps")
|
114 |
+
return torch.device("cpu")
|
115 |
+
|
116 |
+
# Fork Feature: Compute f0 with the crepe method
|
117 |
+
def get_f0_crepe_computation(
|
118 |
+
self,
|
119 |
+
x,
|
120 |
+
f0_min,
|
121 |
+
f0_max,
|
122 |
+
p_len,
|
123 |
+
*args, # 512 before. Hop length changes the speed that the voice jumps to a different dramatic pitch. Lower hop lengths means more pitch accuracy but longer inference time.
|
124 |
+
**kwargs, # Either use crepe-tiny "tiny" or crepe "full". Default is full
|
125 |
+
):
|
126 |
+
x = x.astype(
|
127 |
+
np.float32
|
128 |
+
) # fixes the F.conv2D exception. We needed to convert double to float.
|
129 |
+
x /= np.quantile(np.abs(x), 0.999)
|
130 |
+
torch_device = self.get_optimal_torch_device()
|
131 |
+
audio = torch.from_numpy(x).to(torch_device, copy=True)
|
132 |
+
audio = torch.unsqueeze(audio, dim=0)
|
133 |
+
if audio.ndim == 2 and audio.shape[0] > 1:
|
134 |
+
audio = torch.mean(audio, dim=0, keepdim=True).detach()
|
135 |
+
audio = audio.detach()
|
136 |
+
hop_length = kwargs.get('crepe_hop_length', 160)
|
137 |
+
model = kwargs.get('model', 'full')
|
138 |
+
print("Initiating prediction with a crepe_hop_length of: " + str(hop_length))
|
139 |
+
pitch: Tensor = torchcrepe.predict(
|
140 |
+
audio,
|
141 |
+
self.sr,
|
142 |
+
hop_length,
|
143 |
+
f0_min,
|
144 |
+
f0_max,
|
145 |
+
model,
|
146 |
+
batch_size=hop_length * 2,
|
147 |
+
device=torch_device,
|
148 |
+
pad=True,
|
149 |
+
)
|
150 |
+
p_len = p_len or x.shape[0] // hop_length
|
151 |
+
# Resize the pitch for final f0
|
152 |
+
source = np.array(pitch.squeeze(0).cpu().float().numpy())
|
153 |
+
source[source < 0.001] = np.nan
|
154 |
+
target = np.interp(
|
155 |
+
np.arange(0, len(source) * p_len, len(source)) / p_len,
|
156 |
+
np.arange(0, len(source)),
|
157 |
+
source,
|
158 |
+
)
|
159 |
+
f0 = np.nan_to_num(target)
|
160 |
+
return f0 # Resized f0
|
161 |
+
|
162 |
+
def get_f0_official_crepe_computation(
|
163 |
+
self,
|
164 |
+
x,
|
165 |
+
f0_min,
|
166 |
+
f0_max,
|
167 |
+
*args,
|
168 |
+
**kwargs
|
169 |
+
):
|
170 |
+
# Pick a batch size that doesn't cause memory errors on your gpu
|
171 |
+
batch_size = 512
|
172 |
+
# Compute pitch using first gpu
|
173 |
+
audio = torch.tensor(np.copy(x))[None].float()
|
174 |
+
model = kwargs.get('model', 'full')
|
175 |
+
f0, pd = torchcrepe.predict(
|
176 |
+
audio,
|
177 |
+
self.sr,
|
178 |
+
self.window,
|
179 |
+
f0_min,
|
180 |
+
f0_max,
|
181 |
+
model,
|
182 |
+
batch_size=batch_size,
|
183 |
+
device=self.device,
|
184 |
+
return_periodicity=True,
|
185 |
+
)
|
186 |
+
pd = torchcrepe.filter.median(pd, 3)
|
187 |
+
f0 = torchcrepe.filter.mean(f0, 3)
|
188 |
+
f0[pd < 0.1] = 0
|
189 |
+
f0 = f0[0].cpu().numpy()
|
190 |
+
return f0
|
191 |
+
|
192 |
+
# Fork Feature: Compute pYIN f0 method
|
193 |
+
def get_f0_pyin_computation(self, x, f0_min, f0_max):
|
194 |
+
y, sr = librosa.load(x, sr=self.sr, mono=True)
|
195 |
+
f0, _, _ = librosa.pyin(y, fmin=f0_min, fmax=f0_max, sr=self.sr)
|
196 |
+
f0 = f0[1:] # Get rid of extra first frame
|
197 |
+
return f0
|
198 |
+
|
199 |
+
def get_rmvpe(self, x, *args, **kwargs):
|
200 |
+
if not hasattr(self, "model_rmvpe"):
|
201 |
+
from lib.infer.infer_libs.rmvpe import RMVPE
|
202 |
+
|
203 |
+
logger.info(
|
204 |
+
f"Loading rmvpe model, {os.environ['rmvpe_model_path']}"
|
205 |
+
)
|
206 |
+
self.model_rmvpe = RMVPE(
|
207 |
+
os.environ["rmvpe_model_path"],
|
208 |
+
is_half=self.is_half,
|
209 |
+
device=self.device,
|
210 |
+
)
|
211 |
+
f0 = self.model_rmvpe.infer_from_audio(x, thred=0.03)
|
212 |
+
|
213 |
+
if "privateuseone" in str(self.device): # clean ortruntime memory
|
214 |
+
del self.model_rmvpe.model
|
215 |
+
del self.model_rmvpe
|
216 |
+
logger.info("Cleaning ortruntime memory")
|
217 |
+
|
218 |
+
return f0
|
219 |
+
|
220 |
+
|
221 |
+
def get_pitch_dependant_rmvpe(self, x, f0_min=1, f0_max=40000, *args, **kwargs):
|
222 |
+
if not hasattr(self, "model_rmvpe"):
|
223 |
+
from lib.infer.infer_libs.rmvpe import RMVPE
|
224 |
+
|
225 |
+
logger.info(
|
226 |
+
f"Loading rmvpe model, {os.environ['rmvpe_model_path']}"
|
227 |
+
)
|
228 |
+
self.model_rmvpe = RMVPE(
|
229 |
+
os.environ["rmvpe_model_path"],
|
230 |
+
is_half=self.is_half,
|
231 |
+
device=self.device,
|
232 |
+
)
|
233 |
+
f0 = self.model_rmvpe.infer_from_audio_with_pitch(x, thred=0.03, f0_min=f0_min, f0_max=f0_max)
|
234 |
+
if "privateuseone" in str(self.device): # clean ortruntime memory
|
235 |
+
del self.model_rmvpe.model
|
236 |
+
del self.model_rmvpe
|
237 |
+
logger.info("Cleaning ortruntime memory")
|
238 |
+
|
239 |
+
return f0
|
240 |
+
|
241 |
+
def get_fcpe(self, x, f0_min, f0_max, p_len, *args, **kwargs):
|
242 |
+
self.model_fcpe = FCPE(os.environ["fcpe_model_path"], f0_min=f0_min, f0_max=f0_max, dtype=torch.float32, device=self.device, sampling_rate=self.sr, threshold=0.03)
|
243 |
+
f0 = self.model_fcpe.compute_f0(x, p_len=p_len)
|
244 |
+
del self.model_fcpe
|
245 |
+
gc.collect()
|
246 |
+
return f0
|
247 |
+
|
248 |
+
def get_torchfcpe(self, x, sr, f0_min, f0_max, p_len, *args, **kwargs):
|
249 |
+
self.model_torchfcpe = spawn_bundled_infer_model(device=self.device)
|
250 |
+
f0 = self.model_torchfcpe.infer(
|
251 |
+
torch.from_numpy(x).float().unsqueeze(0).unsqueeze(-1).to(self.device),
|
252 |
+
sr=sr,
|
253 |
+
decoder_mode="local_argmax",
|
254 |
+
threshold=0.006,
|
255 |
+
f0_min=f0_min,
|
256 |
+
f0_max=f0_max,
|
257 |
+
output_interp_target_length=p_len
|
258 |
+
)
|
259 |
+
return f0.squeeze().cpu().numpy()
|
260 |
+
|
261 |
+
def autotune_f0(self, f0):
|
262 |
+
autotuned_f0 = []
|
263 |
+
for freq in f0:
|
264 |
+
closest_notes = [x for x in self.note_dict if abs(x - freq) == min(abs(n - freq) for n in self.note_dict)]
|
265 |
+
autotuned_f0.append(random.choice(closest_notes))
|
266 |
+
return np.array(autotuned_f0, np.float64)
|
267 |
+
|
268 |
+
|
269 |
+
# Fork Feature: Acquire median hybrid f0 estimation calculation
|
270 |
+
def get_f0_hybrid_computation(
|
271 |
+
self,
|
272 |
+
methods_str,
|
273 |
+
input_audio_path,
|
274 |
+
x,
|
275 |
+
f0_min,
|
276 |
+
f0_max,
|
277 |
+
p_len,
|
278 |
+
filter_radius,
|
279 |
+
crepe_hop_length,
|
280 |
+
time_step,
|
281 |
+
):
|
282 |
+
# Get various f0 methods from input to use in the computation stack
|
283 |
+
methods_str = re.search('hybrid\[(.+)\]', methods_str)
|
284 |
+
if methods_str: # Ensure a match was found
|
285 |
+
methods = [method.strip() for method in methods_str.group(1).split('+')]
|
286 |
+
f0_computation_stack = []
|
287 |
+
|
288 |
+
print("Calculating f0 pitch estimations for methods: %s" % str(methods))
|
289 |
+
x = x.astype(np.float32)
|
290 |
+
x /= np.quantile(np.abs(x), 0.999)
|
291 |
+
# Get f0 calculations for all methods specified
|
292 |
+
for method in methods:
|
293 |
+
f0 = None
|
294 |
+
if method == "pm":
|
295 |
+
f0 = (
|
296 |
+
parselmouth.Sound(x, self.sr)
|
297 |
+
.to_pitch_ac(
|
298 |
+
time_step=time_step / 1000,
|
299 |
+
voicing_threshold=0.6,
|
300 |
+
pitch_floor=f0_min,
|
301 |
+
pitch_ceiling=f0_max,
|
302 |
+
)
|
303 |
+
.selected_array["frequency"]
|
304 |
+
)
|
305 |
+
pad_size = (p_len - len(f0) + 1) // 2
|
306 |
+
if pad_size > 0 or p_len - len(f0) - pad_size > 0:
|
307 |
+
f0 = np.pad(
|
308 |
+
f0, [[pad_size, p_len - len(f0) - pad_size]], mode="constant"
|
309 |
+
)
|
310 |
+
elif method == "crepe":
|
311 |
+
f0 = self.get_f0_official_crepe_computation(x, f0_min, f0_max, model="full")
|
312 |
+
f0 = f0[1:]
|
313 |
+
elif method == "crepe-tiny":
|
314 |
+
f0 = self.get_f0_official_crepe_computation(x, f0_min, f0_max, model="tiny")
|
315 |
+
f0 = f0[1:] # Get rid of extra first frame
|
316 |
+
elif method == "mangio-crepe":
|
317 |
+
f0 = self.get_f0_crepe_computation(
|
318 |
+
x, f0_min, f0_max, p_len, crepe_hop_length=crepe_hop_length
|
319 |
+
)
|
320 |
+
elif method == "mangio-crepe-tiny":
|
321 |
+
f0 = self.get_f0_crepe_computation(
|
322 |
+
x, f0_min, f0_max, p_len, crepe_hop_length=crepe_hop_length, model="tiny"
|
323 |
+
)
|
324 |
+
elif method == "harvest":
|
325 |
+
input_audio_path2wav[input_audio_path] = x.astype(np.double)
|
326 |
+
f0 = cache_harvest_f0(input_audio_path, self.sr, f0_max, f0_min, 10)
|
327 |
+
if filter_radius > 2:
|
328 |
+
f0 = signal.medfilt(f0, 3)
|
329 |
+
elif method == "dio":
|
330 |
+
f0, t = pyworld.dio(
|
331 |
+
x.astype(np.double),
|
332 |
+
fs=self.sr,
|
333 |
+
f0_ceil=f0_max,
|
334 |
+
f0_floor=f0_min,
|
335 |
+
frame_period=10,
|
336 |
+
)
|
337 |
+
f0 = pyworld.stonemask(x.astype(np.double), f0, t, self.sr)
|
338 |
+
f0 = signal.medfilt(f0, 3)
|
339 |
+
f0 = f0[1:]
|
340 |
+
elif method == "rmvpe":
|
341 |
+
f0 = self.get_rmvpe(x)
|
342 |
+
f0 = f0[1:]
|
343 |
+
elif method == "fcpe_legacy":
|
344 |
+
f0 = self.get_fcpe(x, f0_min=f0_min, f0_max=f0_max, p_len=p_len)
|
345 |
+
elif method == "fcpe":
|
346 |
+
f0 = self.get_torchfcpe(x, self.sr, f0_min, f0_max, p_len)
|
347 |
+
elif method == "pyin":
|
348 |
+
f0 = self.get_f0_pyin_computation(input_audio_path, f0_min, f0_max)
|
349 |
+
# Push method to the stack
|
350 |
+
f0_computation_stack.append(f0)
|
351 |
+
|
352 |
+
for fc in f0_computation_stack:
|
353 |
+
print(len(fc))
|
354 |
+
|
355 |
+
print("Calculating hybrid median f0 from the stack of: %s" % str(methods))
|
356 |
+
f0_median_hybrid = None
|
357 |
+
if len(f0_computation_stack) == 1:
|
358 |
+
f0_median_hybrid = f0_computation_stack[0]
|
359 |
+
else:
|
360 |
+
f0_median_hybrid = np.nanmedian(f0_computation_stack, axis=0)
|
361 |
+
return f0_median_hybrid
|
362 |
+
|
363 |
+
def get_f0(
|
364 |
+
self,
|
365 |
+
input_audio_path,
|
366 |
+
x,
|
367 |
+
p_len,
|
368 |
+
f0_up_key,
|
369 |
+
f0_method,
|
370 |
+
filter_radius,
|
371 |
+
crepe_hop_length,
|
372 |
+
f0_autotune,
|
373 |
+
inp_f0=None,
|
374 |
+
f0_min=50,
|
375 |
+
f0_max=1100,
|
376 |
+
):
|
377 |
+
global input_audio_path2wav
|
378 |
+
time_step = self.window / self.sr * 1000
|
379 |
+
f0_min = f0_min
|
380 |
+
f0_max = f0_max
|
381 |
+
f0_mel_min = 1127 * np.log(1 + f0_min / 700)
|
382 |
+
f0_mel_max = 1127 * np.log(1 + f0_max / 700)
|
383 |
+
|
384 |
+
if f0_method == "pm":
|
385 |
+
f0 = (
|
386 |
+
parselmouth.Sound(x, self.sr)
|
387 |
+
.to_pitch_ac(
|
388 |
+
time_step=time_step / 1000,
|
389 |
+
voicing_threshold=0.6,
|
390 |
+
pitch_floor=f0_min,
|
391 |
+
pitch_ceiling=f0_max,
|
392 |
+
)
|
393 |
+
.selected_array["frequency"]
|
394 |
+
)
|
395 |
+
pad_size = (p_len - len(f0) + 1) // 2
|
396 |
+
if pad_size > 0 or p_len - len(f0) - pad_size > 0:
|
397 |
+
f0 = np.pad(
|
398 |
+
f0, [[pad_size, p_len - len(f0) - pad_size]], mode="constant"
|
399 |
+
)
|
400 |
+
elif f0_method == "harvest":
|
401 |
+
input_audio_path2wav[input_audio_path] = x.astype(np.double)
|
402 |
+
f0 = cache_harvest_f0(input_audio_path, self.sr, f0_max, f0_min, 10)
|
403 |
+
if filter_radius > 2:
|
404 |
+
f0 = signal.medfilt(f0, 3)
|
405 |
+
elif f0_method == "dio": # Potentially Buggy?
|
406 |
+
f0, t = pyworld.dio(
|
407 |
+
x.astype(np.double),
|
408 |
+
fs=self.sr,
|
409 |
+
f0_ceil=f0_max,
|
410 |
+
f0_floor=f0_min,
|
411 |
+
frame_period=10,
|
412 |
+
)
|
413 |
+
f0 = pyworld.stonemask(x.astype(np.double), f0, t, self.sr)
|
414 |
+
f0 = signal.medfilt(f0, 3)
|
415 |
+
elif f0_method == "crepe":
|
416 |
+
model = "full"
|
417 |
+
# Pick a batch size that doesn't cause memory errors on your gpu
|
418 |
+
batch_size = 512
|
419 |
+
# Compute pitch using first gpu
|
420 |
+
audio = torch.tensor(np.copy(x))[None].float()
|
421 |
+
f0, pd = torchcrepe.predict(
|
422 |
+
audio,
|
423 |
+
self.sr,
|
424 |
+
self.window,
|
425 |
+
f0_min,
|
426 |
+
f0_max,
|
427 |
+
model,
|
428 |
+
batch_size=batch_size,
|
429 |
+
device=self.device,
|
430 |
+
return_periodicity=True,
|
431 |
+
)
|
432 |
+
pd = torchcrepe.filter.median(pd, 3)
|
433 |
+
f0 = torchcrepe.filter.mean(f0, 3)
|
434 |
+
f0[pd < 0.1] = 0
|
435 |
+
f0 = f0[0].cpu().numpy()
|
436 |
+
elif f0_method == "crepe-tiny":
|
437 |
+
f0 = self.get_f0_official_crepe_computation(x, f0_min, f0_max, model="tiny")
|
438 |
+
elif f0_method == "mangio-crepe":
|
439 |
+
f0 = self.get_f0_crepe_computation(
|
440 |
+
x, f0_min, f0_max, p_len, crepe_hop_length=crepe_hop_length
|
441 |
+
)
|
442 |
+
elif f0_method == "mangio-crepe-tiny":
|
443 |
+
f0 = self.get_f0_crepe_computation(
|
444 |
+
x, f0_min, f0_max, p_len, crepe_hop_length=crepe_hop_length, model="tiny"
|
445 |
+
)
|
446 |
+
elif f0_method == "rmvpe":
|
447 |
+
if not hasattr(self, "model_rmvpe"):
|
448 |
+
from lib.infer.infer_libs.rmvpe import RMVPE
|
449 |
+
|
450 |
+
logger.info(
|
451 |
+
f"Loading rmvpe model, {os.environ['rmvpe_model_path']}"
|
452 |
+
)
|
453 |
+
self.model_rmvpe = RMVPE(
|
454 |
+
os.environ["rmvpe_model_path"],
|
455 |
+
is_half=self.is_half,
|
456 |
+
device=self.device,
|
457 |
+
)
|
458 |
+
f0 = self.model_rmvpe.infer_from_audio(x, thred=0.03)
|
459 |
+
|
460 |
+
if "privateuseone" in str(self.device): # clean ortruntime memory
|
461 |
+
del self.model_rmvpe.model
|
462 |
+
del self.model_rmvpe
|
463 |
+
logger.info("Cleaning ortruntime memory")
|
464 |
+
elif f0_method == "rmvpe+":
|
465 |
+
params = {'x': x, 'p_len': p_len, 'f0_up_key': f0_up_key, 'f0_min': f0_min,
|
466 |
+
'f0_max': f0_max, 'time_step': time_step, 'filter_radius': filter_radius,
|
467 |
+
'crepe_hop_length': crepe_hop_length, 'model': "full"
|
468 |
+
}
|
469 |
+
f0 = self.get_pitch_dependant_rmvpe(**params)
|
470 |
+
elif f0_method == "pyin":
|
471 |
+
f0 = self.get_f0_pyin_computation(input_audio_path, f0_min, f0_max)
|
472 |
+
elif f0_method == "fcpe_legacy":
|
473 |
+
f0 = self.get_fcpe(x, f0_min=f0_min, f0_max=f0_max, p_len=p_len)
|
474 |
+
elif f0_method == "fcpe":
|
475 |
+
f0 = self.get_torchfcpe(x, self.sr, f0_min, f0_max, p_len)
|
476 |
+
elif "hybrid" in f0_method:
|
477 |
+
# Perform hybrid median pitch estimation
|
478 |
+
input_audio_path2wav[input_audio_path] = x.astype(np.double)
|
479 |
+
f0 = self.get_f0_hybrid_computation(
|
480 |
+
f0_method,
|
481 |
+
input_audio_path,
|
482 |
+
x,
|
483 |
+
f0_min,
|
484 |
+
f0_max,
|
485 |
+
p_len,
|
486 |
+
filter_radius,
|
487 |
+
crepe_hop_length,
|
488 |
+
time_step,
|
489 |
+
)
|
490 |
+
#print("Autotune:", f0_autotune)
|
491 |
+
if f0_autotune == True:
|
492 |
+
print("Autotune:", f0_autotune)
|
493 |
+
f0 = self.autotune_f0(f0)
|
494 |
+
|
495 |
+
f0 *= pow(2, f0_up_key / 12)
|
496 |
+
# with open("test.txt","w")as f:f.write("\n".join([str(i)for i in f0.tolist()]))
|
497 |
+
tf0 = self.sr // self.window # 每秒f0点数
|
498 |
+
if inp_f0 is not None:
|
499 |
+
delta_t = np.round(
|
500 |
+
(inp_f0[:, 0].max() - inp_f0[:, 0].min()) * tf0 + 1
|
501 |
+
).astype("int16")
|
502 |
+
replace_f0 = np.interp(
|
503 |
+
list(range(delta_t)), inp_f0[:, 0] * 100, inp_f0[:, 1]
|
504 |
+
)
|
505 |
+
shape = f0[self.x_pad * tf0 : self.x_pad * tf0 + len(replace_f0)].shape[0]
|
506 |
+
f0[self.x_pad * tf0 : self.x_pad * tf0 + len(replace_f0)] = replace_f0[
|
507 |
+
:shape
|
508 |
+
]
|
509 |
+
# with open("test_opt.txt","w")as f:f.write("\n".join([str(i)for i in f0.tolist()]))
|
510 |
+
f0bak = f0.copy()
|
511 |
+
f0_mel = 1127 * np.log(1 + f0 / 700)
|
512 |
+
f0_mel[f0_mel > 0] = (f0_mel[f0_mel > 0] - f0_mel_min) * 254 / (
|
513 |
+
f0_mel_max - f0_mel_min
|
514 |
+
) + 1
|
515 |
+
f0_mel[f0_mel <= 1] = 1
|
516 |
+
f0_mel[f0_mel > 255] = 255
|
517 |
+
f0_coarse = np.rint(f0_mel).astype(np.int32)
|
518 |
+
return f0_coarse, f0bak # 1-0
|
519 |
+
|
520 |
+
def vc(
|
521 |
+
self,
|
522 |
+
model,
|
523 |
+
net_g,
|
524 |
+
sid,
|
525 |
+
audio0,
|
526 |
+
pitch,
|
527 |
+
pitchf,
|
528 |
+
times,
|
529 |
+
index,
|
530 |
+
big_npy,
|
531 |
+
index_rate,
|
532 |
+
version,
|
533 |
+
protect,
|
534 |
+
): # ,file_index,file_big_npy
|
535 |
+
feats = torch.from_numpy(audio0)
|
536 |
+
if self.is_half:
|
537 |
+
feats = feats.half()
|
538 |
+
else:
|
539 |
+
feats = feats.float()
|
540 |
+
if feats.dim() == 2: # double channels
|
541 |
+
feats = feats.mean(-1)
|
542 |
+
assert feats.dim() == 1, feats.dim()
|
543 |
+
feats = feats.view(1, -1)
|
544 |
+
padding_mask = torch.BoolTensor(feats.shape).to(self.device).fill_(False)
|
545 |
+
|
546 |
+
inputs = {
|
547 |
+
"source": feats.to(self.device),
|
548 |
+
"padding_mask": padding_mask,
|
549 |
+
"output_layer": 9 if version == "v1" else 12,
|
550 |
+
}
|
551 |
+
t0 = ttime()
|
552 |
+
with torch.no_grad():
|
553 |
+
logits = model.extract_features(**inputs)
|
554 |
+
feats = model.final_proj(logits[0]) if version == "v1" else logits[0]
|
555 |
+
if protect < 0.5 and pitch is not None and pitchf is not None:
|
556 |
+
feats0 = feats.clone()
|
557 |
+
if (
|
558 |
+
not isinstance(index, type(None))
|
559 |
+
and not isinstance(big_npy, type(None))
|
560 |
+
and index_rate != 0
|
561 |
+
):
|
562 |
+
npy = feats[0].cpu().numpy()
|
563 |
+
if self.is_half:
|
564 |
+
npy = npy.astype("float32")
|
565 |
+
|
566 |
+
# _, I = index.search(npy, 1)
|
567 |
+
# npy = big_npy[I.squeeze()]
|
568 |
+
|
569 |
+
score, ix = index.search(npy, k=8)
|
570 |
+
weight = np.square(1 / score)
|
571 |
+
weight /= weight.sum(axis=1, keepdims=True)
|
572 |
+
npy = np.sum(big_npy[ix] * np.expand_dims(weight, axis=2), axis=1)
|
573 |
+
|
574 |
+
if self.is_half:
|
575 |
+
npy = npy.astype("float16")
|
576 |
+
feats = (
|
577 |
+
torch.from_numpy(npy).unsqueeze(0).to(self.device) * index_rate
|
578 |
+
+ (1 - index_rate) * feats
|
579 |
+
)
|
580 |
+
|
581 |
+
feats = F.interpolate(feats.permute(0, 2, 1), scale_factor=2).permute(0, 2, 1)
|
582 |
+
if protect < 0.5 and pitch is not None and pitchf is not None:
|
583 |
+
feats0 = F.interpolate(feats0.permute(0, 2, 1), scale_factor=2).permute(
|
584 |
+
0, 2, 1
|
585 |
+
)
|
586 |
+
t1 = ttime()
|
587 |
+
p_len = audio0.shape[0] // self.window
|
588 |
+
if feats.shape[1] < p_len:
|
589 |
+
p_len = feats.shape[1]
|
590 |
+
if pitch is not None and pitchf is not None:
|
591 |
+
pitch = pitch[:, :p_len]
|
592 |
+
pitchf = pitchf[:, :p_len]
|
593 |
+
|
594 |
+
if protect < 0.5 and pitch is not None and pitchf is not None:
|
595 |
+
pitchff = pitchf.clone()
|
596 |
+
pitchff[pitchf > 0] = 1
|
597 |
+
pitchff[pitchf < 1] = protect
|
598 |
+
pitchff = pitchff.unsqueeze(-1)
|
599 |
+
feats = feats * pitchff + feats0 * (1 - pitchff)
|
600 |
+
feats = feats.to(feats0.dtype)
|
601 |
+
p_len = torch.tensor([p_len], device=self.device).long()
|
602 |
+
with torch.no_grad():
|
603 |
+
hasp = pitch is not None and pitchf is not None
|
604 |
+
arg = (feats, p_len, pitch, pitchf, sid) if hasp else (feats, p_len, sid)
|
605 |
+
audio1 = (net_g.infer(*arg)[0][0, 0]).data.cpu().float().numpy()
|
606 |
+
del hasp, arg
|
607 |
+
del feats, p_len, padding_mask
|
608 |
+
if torch.cuda.is_available():
|
609 |
+
torch.cuda.empty_cache()
|
610 |
+
t2 = ttime()
|
611 |
+
times[0] += t1 - t0
|
612 |
+
times[2] += t2 - t1
|
613 |
+
return audio1
|
614 |
+
def process_t(self, t, s, window, audio_pad, pitch, pitchf, times, index, big_npy, index_rate, version, protect, t_pad_tgt, if_f0, sid, model, net_g):
|
615 |
+
t = t // window * window
|
616 |
+
if if_f0 == 1:
|
617 |
+
return self.vc(
|
618 |
+
model,
|
619 |
+
net_g,
|
620 |
+
sid,
|
621 |
+
audio_pad[s : t + t_pad_tgt + window],
|
622 |
+
pitch[:, s // window : (t + t_pad_tgt) // window],
|
623 |
+
pitchf[:, s // window : (t + t_pad_tgt) // window],
|
624 |
+
times,
|
625 |
+
index,
|
626 |
+
big_npy,
|
627 |
+
index_rate,
|
628 |
+
version,
|
629 |
+
protect,
|
630 |
+
)[t_pad_tgt : -t_pad_tgt]
|
631 |
+
else:
|
632 |
+
return self.vc(
|
633 |
+
model,
|
634 |
+
net_g,
|
635 |
+
sid,
|
636 |
+
audio_pad[s : t + t_pad_tgt + window],
|
637 |
+
None,
|
638 |
+
None,
|
639 |
+
times,
|
640 |
+
index,
|
641 |
+
big_npy,
|
642 |
+
index_rate,
|
643 |
+
version,
|
644 |
+
protect,
|
645 |
+
)[t_pad_tgt : -t_pad_tgt]
|
646 |
+
|
647 |
+
|
648 |
+
def pipeline(
|
649 |
+
self,
|
650 |
+
model,
|
651 |
+
net_g,
|
652 |
+
sid,
|
653 |
+
audio,
|
654 |
+
input_audio_path,
|
655 |
+
times,
|
656 |
+
f0_up_key,
|
657 |
+
f0_method,
|
658 |
+
file_index,
|
659 |
+
index_rate,
|
660 |
+
if_f0,
|
661 |
+
filter_radius,
|
662 |
+
tgt_sr,
|
663 |
+
resample_sr,
|
664 |
+
rms_mix_rate,
|
665 |
+
version,
|
666 |
+
protect,
|
667 |
+
crepe_hop_length,
|
668 |
+
f0_autotune,
|
669 |
+
f0_min=50,
|
670 |
+
f0_max=1100
|
671 |
+
):
|
672 |
+
if (
|
673 |
+
file_index != ""
|
674 |
+
and isinstance(file_index, str)
|
675 |
+
# and file_big_npy != ""
|
676 |
+
# and os.path.exists(file_big_npy) == True
|
677 |
+
and os.path.exists(file_index)
|
678 |
+
and index_rate != 0
|
679 |
+
):
|
680 |
+
try:
|
681 |
+
index = faiss.read_index(file_index)
|
682 |
+
# big_npy = np.load(file_big_npy)
|
683 |
+
big_npy = index.reconstruct_n(0, index.ntotal)
|
684 |
+
except:
|
685 |
+
traceback.print_exc()
|
686 |
+
index = big_npy = None
|
687 |
+
else:
|
688 |
+
index = big_npy = None
|
689 |
+
audio = signal.filtfilt(bh, ah, audio)
|
690 |
+
audio_pad = np.pad(audio, (self.window // 2, self.window // 2), mode="reflect")
|
691 |
+
opt_ts = []
|
692 |
+
if audio_pad.shape[0] > self.t_max:
|
693 |
+
audio_sum = np.zeros_like(audio)
|
694 |
+
for i in range(self.window):
|
695 |
+
audio_sum += audio_pad[i : i - self.window]
|
696 |
+
for t in range(self.t_center, audio.shape[0], self.t_center):
|
697 |
+
opt_ts.append(
|
698 |
+
t
|
699 |
+
- self.t_query
|
700 |
+
+ np.where(
|
701 |
+
np.abs(audio_sum[t - self.t_query : t + self.t_query])
|
702 |
+
== np.abs(audio_sum[t - self.t_query : t + self.t_query]).min()
|
703 |
+
)[0][0]
|
704 |
+
)
|
705 |
+
s = 0
|
706 |
+
audio_opt = []
|
707 |
+
t = None
|
708 |
+
t1 = ttime()
|
709 |
+
audio_pad = np.pad(audio, (self.t_pad, self.t_pad), mode="reflect")
|
710 |
+
p_len = audio_pad.shape[0] // self.window
|
711 |
+
inp_f0 = None
|
712 |
+
|
713 |
+
sid = torch.tensor(sid, device=self.device).unsqueeze(0).long()
|
714 |
+
pitch, pitchf = None, None
|
715 |
+
if if_f0:
|
716 |
+
pitch, pitchf = self.get_f0(
|
717 |
+
input_audio_path,
|
718 |
+
audio_pad,
|
719 |
+
p_len,
|
720 |
+
f0_up_key,
|
721 |
+
f0_method,
|
722 |
+
filter_radius,
|
723 |
+
crepe_hop_length,
|
724 |
+
f0_autotune,
|
725 |
+
inp_f0,
|
726 |
+
f0_min,
|
727 |
+
f0_max
|
728 |
+
)
|
729 |
+
pitch = pitch[:p_len]
|
730 |
+
pitchf = pitchf[:p_len]
|
731 |
+
if "mps" not in str(self.device) or "xpu" not in str(self.device):
|
732 |
+
pitchf = pitchf.astype(np.float32)
|
733 |
+
pitch = torch.tensor(pitch, device=self.device).unsqueeze(0).long()
|
734 |
+
pitchf = torch.tensor(pitchf, device=self.device).unsqueeze(0).float()
|
735 |
+
t2 = ttime()
|
736 |
+
times[1] += t2 - t1
|
737 |
+
|
738 |
+
with tqdm(total=len(opt_ts), desc="Processing", unit="window") as pbar:
|
739 |
+
for i, t in enumerate(opt_ts):
|
740 |
+
t = t // self.window * self.window
|
741 |
+
start = s
|
742 |
+
end = t + self.t_pad2 + self.window
|
743 |
+
audio_slice = audio_pad[start:end]
|
744 |
+
pitch_slice = pitch[:, start // self.window:end // self.window] if if_f0 else None
|
745 |
+
pitchf_slice = pitchf[:, start // self.window:end // self.window] if if_f0 else None
|
746 |
+
audio_opt.append(self.vc(model, net_g, sid, audio_slice, pitch_slice, pitchf_slice, times, index, big_npy, index_rate, version, protect)[self.t_pad_tgt : -self.t_pad_tgt])
|
747 |
+
s = t
|
748 |
+
pbar.update(1)
|
749 |
+
pbar.refresh()
|
750 |
+
|
751 |
+
audio_slice = audio_pad[t:]
|
752 |
+
pitch_slice = pitch[:, t // self.window:] if if_f0 and t is not None else pitch
|
753 |
+
pitchf_slice = pitchf[:, t // self.window:] if if_f0 and t is not None else pitchf
|
754 |
+
audio_opt.append(self.vc(model, net_g, sid, audio_slice, pitch_slice, pitchf_slice, times, index, big_npy, index_rate, version, protect)[self.t_pad_tgt : -self.t_pad_tgt])
|
755 |
+
|
756 |
+
audio_opt = np.concatenate(audio_opt)
|
757 |
+
if rms_mix_rate != 1:
|
758 |
+
audio_opt = change_rms(audio, 16000, audio_opt, tgt_sr, rms_mix_rate)
|
759 |
+
if tgt_sr != resample_sr >= 16000:
|
760 |
+
audio_opt = librosa.resample(
|
761 |
+
audio_opt, orig_sr=tgt_sr, target_sr=resample_sr
|
762 |
+
)
|
763 |
+
audio_max = np.abs(audio_opt).max() / 0.99
|
764 |
+
max_int16 = 32768
|
765 |
+
if audio_max > 1:
|
766 |
+
max_int16 /= audio_max
|
767 |
+
audio_opt = (audio_opt * max_int16).astype(np.int16)
|
768 |
+
del pitch, pitchf, sid
|
769 |
+
if torch.cuda.is_available():
|
770 |
+
torch.cuda.empty_cache()
|
771 |
+
|
772 |
+
print("Returning completed audio...")
|
773 |
+
return audio_opt
|
lib/split_audio.py
ADDED
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
from pydub import AudioSegment
|
3 |
+
from pydub.silence import detect_silence, detect_nonsilent
|
4 |
+
|
5 |
+
SEPERATE_DIR = os.path.join(os.getcwd(), "seperate")
|
6 |
+
TEMP_DIR = os.path.join(SEPERATE_DIR, "temp")
|
7 |
+
cache = {}
|
8 |
+
|
9 |
+
os.makedirs(SEPERATE_DIR, exist_ok=True)
|
10 |
+
os.makedirs(TEMP_DIR, exist_ok=True)
|
11 |
+
|
12 |
+
def cache_result(func):
|
13 |
+
def wrapper(*args, **kwargs):
|
14 |
+
key = (args, frozenset(kwargs.items()))
|
15 |
+
if key in cache:
|
16 |
+
return cache[key]
|
17 |
+
else:
|
18 |
+
result = func(*args, **kwargs)
|
19 |
+
cache[key] = result
|
20 |
+
return result
|
21 |
+
return wrapper
|
22 |
+
|
23 |
+
def get_non_silent(audio_name, audio, min_silence, silence_thresh, seek_step, keep_silence):
|
24 |
+
"""
|
25 |
+
Function to get non-silent parts of the audio.
|
26 |
+
"""
|
27 |
+
nonsilent_ranges = detect_nonsilent(audio, min_silence_len=min_silence, silence_thresh=silence_thresh, seek_step=seek_step)
|
28 |
+
nonsilent_files = []
|
29 |
+
for index, range in enumerate(nonsilent_ranges):
|
30 |
+
nonsilent_name = os.path.join(SEPERATE_DIR, f"{audio_name}_min{min_silence}_t{silence_thresh}_ss{seek_step}_ks{keep_silence}", f"nonsilent{index}-{audio_name}.wav")
|
31 |
+
start, end = range[0] - keep_silence, range[1] + keep_silence
|
32 |
+
audio[start:end].export(nonsilent_name, format="wav")
|
33 |
+
nonsilent_files.append(nonsilent_name)
|
34 |
+
return nonsilent_files
|
35 |
+
|
36 |
+
def get_silence(audio_name, audio, min_silence, silence_thresh, seek_step, keep_silence):
|
37 |
+
"""
|
38 |
+
Function to get silent parts of the audio.
|
39 |
+
"""
|
40 |
+
silence_ranges = detect_silence(audio, min_silence_len=min_silence, silence_thresh=silence_thresh, seek_step=seek_step)
|
41 |
+
silence_files = []
|
42 |
+
for index, range in enumerate(silence_ranges):
|
43 |
+
silence_name = os.path.join(SEPERATE_DIR, f"{audio_name}_min{min_silence}_t{silence_thresh}_ss{seek_step}_ks{keep_silence}", f"silence{index}-{audio_name}.wav")
|
44 |
+
start, end = range[0] + keep_silence, range[1] - keep_silence
|
45 |
+
audio[start:end].export(silence_name, format="wav")
|
46 |
+
silence_files.append(silence_name)
|
47 |
+
return silence_files
|
48 |
+
|
49 |
+
@cache_result
|
50 |
+
def split_silence_nonsilent(input_path, min_silence=500, silence_thresh=-40, seek_step=1, keep_silence=100):
|
51 |
+
"""
|
52 |
+
Function to split the audio into silent and non-silent parts.
|
53 |
+
"""
|
54 |
+
audio_name = os.path.splitext(os.path.basename(input_path))[0]
|
55 |
+
os.makedirs(os.path.join(SEPERATE_DIR, f"{audio_name}_min{min_silence}_t{silence_thresh}_ss{seek_step}_ks{keep_silence}"), exist_ok=True)
|
56 |
+
audio = AudioSegment.silent(duration=1000) + AudioSegment.from_file(input_path) + AudioSegment.silent(duration=1000)
|
57 |
+
silence_files = get_silence(audio_name, audio, min_silence, silence_thresh, seek_step, keep_silence)
|
58 |
+
nonsilent_files = get_non_silent(audio_name, audio, min_silence, silence_thresh, seek_step, keep_silence)
|
59 |
+
return silence_files, nonsilent_files
|
60 |
+
|
61 |
+
def adjust_audio_lengths(original_audios, inferred_audios):
|
62 |
+
"""
|
63 |
+
Function to adjust the lengths of the inferred audio files list to match the original audio files length.
|
64 |
+
"""
|
65 |
+
adjusted_audios = []
|
66 |
+
for original_audio, inferred_audio in zip(original_audios, inferred_audios):
|
67 |
+
audio_1 = AudioSegment.from_file(original_audio)
|
68 |
+
audio_2 = AudioSegment.from_file(inferred_audio)
|
69 |
+
|
70 |
+
if len(audio_1) > len(audio_2):
|
71 |
+
audio_2 += AudioSegment.silent(duration=len(audio_1) - len(audio_2))
|
72 |
+
else:
|
73 |
+
audio_2 = audio_2[:len(audio_1)]
|
74 |
+
|
75 |
+
adjusted_file = os.path.join(TEMP_DIR, f"adjusted-{os.path.basename(inferred_audio)}")
|
76 |
+
audio_2.export(adjusted_file, format="wav")
|
77 |
+
adjusted_audios.append(adjusted_file)
|
78 |
+
|
79 |
+
return adjusted_audios
|
80 |
+
|
81 |
+
def combine_silence_nonsilent(silence_files, nonsilent_files, keep_silence, output):
|
82 |
+
"""
|
83 |
+
Function to combine the silent and non-silent parts of the audio.
|
84 |
+
"""
|
85 |
+
combined = AudioSegment.empty()
|
86 |
+
for silence, nonsilent in zip(silence_files, nonsilent_files):
|
87 |
+
combined += AudioSegment.from_wav(silence) + AudioSegment.from_wav(nonsilent)
|
88 |
+
combined += AudioSegment.from_wav(silence_files[-1])
|
89 |
+
combined = AudioSegment.silent(duration=keep_silence) + combined[1000:-1000] + AudioSegment.silent(duration=keep_silence)
|
90 |
+
combined.export(output, format="wav")
|
91 |
+
return output
|
stftpitchshift
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:eb2f50ea8e5ca1a11a587f11f25ba9182f9b24e2367ac480f430b3f04062782e
|
3 |
+
size 1822104
|