Spaces:
No application file
No application file
constinic@gmail.com commited on
Commit ·
662d11f
1
Parent(s): 9be6ea4
frist commit
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitignore +5 -0
- LICENSE +21 -0
- app.py +372 -0
- assets/screenshot.jpg +0 -0
- client.js +37 -0
- client.py +99 -0
- config.py +115 -0
- lib/infer_pack/attentions.py +417 -0
- lib/infer_pack/commons.py +166 -0
- lib/infer_pack/models.py +1142 -0
- lib/infer_pack/models_dml.py +1124 -0
- lib/infer_pack/models_onnx.py +819 -0
- lib/infer_pack/modules.py +522 -0
- lib/infer_pack/modules/F0Predictor/DioF0Predictor.py +90 -0
- lib/infer_pack/modules/F0Predictor/F0Predictor.py +16 -0
- lib/infer_pack/modules/F0Predictor/HarvestF0Predictor.py +86 -0
- lib/infer_pack/modules/F0Predictor/PMF0Predictor.py +97 -0
- lib/infer_pack/modules/F0Predictor/__init__.py +0 -0
- lib/infer_pack/onnx_inference.py +145 -0
- lib/infer_pack/transforms.py +209 -0
- node_modules/.bin/node-gyp-build +12 -0
- node_modules/.bin/node-gyp-build-optional +12 -0
- node_modules/.bin/node-gyp-build-optional.cmd +17 -0
- node_modules/.bin/node-gyp-build-optional.ps1 +28 -0
- node_modules/.bin/node-gyp-build-test +12 -0
- node_modules/.bin/node-gyp-build-test.cmd +17 -0
- node_modules/.bin/node-gyp-build-test.ps1 +28 -0
- node_modules/.bin/node-gyp-build.cmd +17 -0
- node_modules/.bin/node-gyp-build.ps1 +28 -0
- node_modules/.package-lock.json +70 -0
- node_modules/@gradio/client/CHANGELOG.md +192 -0
- node_modules/@gradio/client/LICENSE +201 -0
- node_modules/@gradio/client/README.md +339 -0
- node_modules/@gradio/client/dist/client.d.ts +76 -0
- node_modules/@gradio/client/dist/client.d.ts.map +1 -0
- node_modules/@gradio/client/dist/index.d.ts +4 -0
- node_modules/@gradio/client/dist/index.d.ts.map +1 -0
- node_modules/@gradio/client/dist/index.js +1388 -0
- node_modules/@gradio/client/dist/types.d.ts +105 -0
- node_modules/@gradio/client/dist/types.d.ts.map +1 -0
- node_modules/@gradio/client/dist/upload.d.ts +29 -0
- node_modules/@gradio/client/dist/upload.d.ts.map +1 -0
- node_modules/@gradio/client/dist/utils.d.ts +32 -0
- node_modules/@gradio/client/dist/utils.d.ts.map +1 -0
- node_modules/@gradio/client/dist/wrapper-6f348d45.js +0 -0
- node_modules/@gradio/client/package.json +33 -0
- node_modules/@gradio/client/src/client.node-test.ts +172 -0
- node_modules/@gradio/client/src/client.ts +1507 -0
- node_modules/@gradio/client/src/globals.d.ts +29 -0
- node_modules/@gradio/client/src/index.ts +15 -0
.gitignore
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
venv/
|
| 2 |
+
__pycache__/
|
| 3 |
+
*.mp3
|
| 4 |
+
hubert_base.pt
|
| 5 |
+
rmvpe.pt
|
LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
MIT License
|
| 2 |
+
|
| 3 |
+
Copyright (c) 2023 litagin02
|
| 4 |
+
|
| 5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 6 |
+
of this software and associated documentation files (the "Software"), to deal
|
| 7 |
+
in the Software without restriction, including without limitation the rights
|
| 8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 9 |
+
copies of the Software, and to permit persons to whom the Software is
|
| 10 |
+
furnished to do so, subject to the following conditions:
|
| 11 |
+
|
| 12 |
+
The above copyright notice and this permission notice shall be included in all
|
| 13 |
+
copies or substantial portions of the Software.
|
| 14 |
+
|
| 15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 21 |
+
SOFTWARE.
|
app.py
ADDED
|
@@ -0,0 +1,372 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import asyncio
|
| 2 |
+
import datetime
|
| 3 |
+
import logging
|
| 4 |
+
import os
|
| 5 |
+
import time
|
| 6 |
+
import traceback
|
| 7 |
+
|
| 8 |
+
import edge_tts
|
| 9 |
+
import gradio as gr
|
| 10 |
+
import librosa
|
| 11 |
+
import torch
|
| 12 |
+
from fairseq import checkpoint_utils
|
| 13 |
+
from config import Config
|
| 14 |
+
from lib.infer_pack.models import (
|
| 15 |
+
SynthesizerTrnMs256NSFsid,
|
| 16 |
+
SynthesizerTrnMs256NSFsid_nono,
|
| 17 |
+
SynthesizerTrnMs768NSFsid,
|
| 18 |
+
SynthesizerTrnMs768NSFsid_nono,
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
from rmvpe import RMVPE
|
| 22 |
+
from vc_infer_pipeline import VC
|
| 23 |
+
import os
|
| 24 |
+
os.environ['CURL_CA_BUNDLE'] = ''
|
| 25 |
+
logging.getLogger("fairseq").setLevel(logging.WARNING)
|
| 26 |
+
logging.getLogger("numba").setLevel(logging.WARNING)
|
| 27 |
+
logging.getLogger("markdown_it").setLevel(logging.WARNING)
|
| 28 |
+
logging.getLogger("urllib3").setLevel(logging.WARNING)
|
| 29 |
+
logging.getLogger("matplotlib").setLevel(logging.WARNING)
|
| 30 |
+
|
| 31 |
+
limitation = os.getenv("SYSTEM") == "spaces"
|
| 32 |
+
|
| 33 |
+
config = Config()
|
| 34 |
+
|
| 35 |
+
edge_output_filename = "edge_output.mp3"
|
| 36 |
+
tts_voice_list = asyncio.get_event_loop().run_until_complete(edge_tts.list_voices())
|
| 37 |
+
tts_voices = [f"{v['ShortName']}-{v['Gender']}" for v in tts_voice_list]
|
| 38 |
+
|
| 39 |
+
model_root = "weights"
|
| 40 |
+
models = [
|
| 41 |
+
d for d in os.listdir(model_root) if os.path.isdir(os.path.join(model_root, d))
|
| 42 |
+
]
|
| 43 |
+
if len(models) == 0:
|
| 44 |
+
raise ValueError("No model found in `weights` folder")
|
| 45 |
+
models.sort()
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def model_data(model_name):
|
| 49 |
+
# global n_spk, tgt_sr, net_g, vc, cpt, version, index_file
|
| 50 |
+
pth_files = [
|
| 51 |
+
os.path.join(model_root, model_name, f)
|
| 52 |
+
for f in os.listdir(os.path.join(model_root, model_name))
|
| 53 |
+
if f.endswith(".pth")
|
| 54 |
+
]
|
| 55 |
+
if len(pth_files) == 0:
|
| 56 |
+
raise ValueError(f"No pth file found in {model_root}/{model_name}")
|
| 57 |
+
pth_path = pth_files[0]
|
| 58 |
+
print(f"Loading {pth_path}")
|
| 59 |
+
cpt = torch.load(pth_path, map_location="cpu")
|
| 60 |
+
tgt_sr = cpt["config"][-1]
|
| 61 |
+
cpt["config"][-3] = cpt["weight"]["emb_g.weight"].shape[0] # n_spk
|
| 62 |
+
if_f0 = cpt.get("f0", 1)
|
| 63 |
+
version = cpt.get("version", "v1")
|
| 64 |
+
if version == "v1":
|
| 65 |
+
if if_f0 == 1:
|
| 66 |
+
net_g = SynthesizerTrnMs256NSFsid(*cpt["config"], is_half=config.is_half)
|
| 67 |
+
else:
|
| 68 |
+
net_g = SynthesizerTrnMs256NSFsid_nono(*cpt["config"])
|
| 69 |
+
elif version == "v2":
|
| 70 |
+
if if_f0 == 1:
|
| 71 |
+
net_g = SynthesizerTrnMs768NSFsid(*cpt["config"], is_half=config.is_half)
|
| 72 |
+
else:
|
| 73 |
+
net_g = SynthesizerTrnMs768NSFsid_nono(*cpt["config"])
|
| 74 |
+
else:
|
| 75 |
+
raise ValueError("Unknown version")
|
| 76 |
+
del net_g.enc_q
|
| 77 |
+
net_g.load_state_dict(cpt["weight"], strict=False)
|
| 78 |
+
print("Model loaded")
|
| 79 |
+
net_g.eval().to(config.device)
|
| 80 |
+
if config.is_half:
|
| 81 |
+
net_g = net_g.half()
|
| 82 |
+
else:
|
| 83 |
+
net_g = net_g.float()
|
| 84 |
+
vc = VC(tgt_sr, config)
|
| 85 |
+
# n_spk = cpt["config"][-3]
|
| 86 |
+
|
| 87 |
+
index_files = [
|
| 88 |
+
os.path.join(model_root, model_name, f)
|
| 89 |
+
for f in os.listdir(os.path.join(model_root, model_name))
|
| 90 |
+
if f.endswith(".index")
|
| 91 |
+
]
|
| 92 |
+
if len(index_files) == 0:
|
| 93 |
+
print("No index file found")
|
| 94 |
+
index_file = ""
|
| 95 |
+
else:
|
| 96 |
+
index_file = index_files[0]
|
| 97 |
+
print(f"Index file found: {index_file}")
|
| 98 |
+
|
| 99 |
+
return tgt_sr, net_g, vc, version, index_file, if_f0
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def load_hubert():
|
| 103 |
+
global hubert_model
|
| 104 |
+
models, _, _ = checkpoint_utils.load_model_ensemble_and_task(
|
| 105 |
+
["hubert_base.pt"],
|
| 106 |
+
suffix="",
|
| 107 |
+
)
|
| 108 |
+
hubert_model = models[0]
|
| 109 |
+
hubert_model = hubert_model.to(config.device)
|
| 110 |
+
if config.is_half:
|
| 111 |
+
hubert_model = hubert_model.half()
|
| 112 |
+
else:
|
| 113 |
+
hubert_model = hubert_model.float()
|
| 114 |
+
return hubert_model.eval()
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
print("Loading hubert model...")
|
| 118 |
+
hubert_model = load_hubert()
|
| 119 |
+
print("Hubert model loaded.")
|
| 120 |
+
|
| 121 |
+
print("Loading rmvpe model...")
|
| 122 |
+
rmvpe_model = RMVPE("rmvpe.pt", config.is_half, config.device)
|
| 123 |
+
print("rmvpe model loaded.")
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def tts(
|
| 127 |
+
model_name,
|
| 128 |
+
speed,
|
| 129 |
+
tts_text,
|
| 130 |
+
tts_voice,
|
| 131 |
+
f0_up_key,
|
| 132 |
+
f0_method,
|
| 133 |
+
index_rate,
|
| 134 |
+
protect,
|
| 135 |
+
filter_radius=3,
|
| 136 |
+
resample_sr=0,
|
| 137 |
+
rms_mix_rate=0.25,
|
| 138 |
+
):
|
| 139 |
+
print("------------------")
|
| 140 |
+
print(datetime.datetime.now())
|
| 141 |
+
print("tts_text:")
|
| 142 |
+
print(tts_text)
|
| 143 |
+
print(f"tts_voice: {tts_voice}")
|
| 144 |
+
print(f"Model name: {model_name}")
|
| 145 |
+
print(f"F0: {f0_method}, Key: {f0_up_key}, Index: {index_rate}, Protect: {protect}")
|
| 146 |
+
try:
|
| 147 |
+
if limitation and len(tts_text) > 280:
|
| 148 |
+
print("Error: Text too long")
|
| 149 |
+
return (
|
| 150 |
+
f"Text characters should be at most 280 in this huggingface space, but got {len(tts_text)} characters.",
|
| 151 |
+
None,
|
| 152 |
+
None,
|
| 153 |
+
)
|
| 154 |
+
tgt_sr, net_g, vc, version, index_file, if_f0 = model_data(model_name)
|
| 155 |
+
t0 = time.time()
|
| 156 |
+
if speed >= 0:
|
| 157 |
+
speed_str = f"+{speed}%"
|
| 158 |
+
else:
|
| 159 |
+
speed_str = f"{speed}%"
|
| 160 |
+
asyncio.run(
|
| 161 |
+
edge_tts.Communicate(
|
| 162 |
+
tts_text, "-".join(tts_voice.split("-")[:-1]), rate=speed_str
|
| 163 |
+
).save(edge_output_filename)
|
| 164 |
+
)
|
| 165 |
+
t1 = time.time()
|
| 166 |
+
edge_time = t1 - t0
|
| 167 |
+
audio, sr = librosa.load(edge_output_filename, sr=16000, mono=True)
|
| 168 |
+
duration = len(audio) / sr
|
| 169 |
+
print(f"Audio duration: {duration}s")
|
| 170 |
+
if limitation and duration >= 20:
|
| 171 |
+
print("Error: Audio too long")
|
| 172 |
+
return (
|
| 173 |
+
f"Audio should be less than 20 seconds in this huggingface space, but got {duration}s.",
|
| 174 |
+
edge_output_filename,
|
| 175 |
+
None,
|
| 176 |
+
)
|
| 177 |
+
|
| 178 |
+
f0_up_key = int(f0_up_key)
|
| 179 |
+
|
| 180 |
+
if not hubert_model:
|
| 181 |
+
load_hubert()
|
| 182 |
+
if f0_method == "rmvpe":
|
| 183 |
+
vc.model_rmvpe = rmvpe_model
|
| 184 |
+
times = [0, 0, 0]
|
| 185 |
+
audio_opt = vc.pipeline(
|
| 186 |
+
hubert_model,
|
| 187 |
+
net_g,
|
| 188 |
+
0,
|
| 189 |
+
audio,
|
| 190 |
+
edge_output_filename,
|
| 191 |
+
times,
|
| 192 |
+
f0_up_key,
|
| 193 |
+
f0_method,
|
| 194 |
+
index_file,
|
| 195 |
+
# file_big_npy,
|
| 196 |
+
index_rate,
|
| 197 |
+
if_f0,
|
| 198 |
+
filter_radius,
|
| 199 |
+
tgt_sr,
|
| 200 |
+
resample_sr,
|
| 201 |
+
rms_mix_rate,
|
| 202 |
+
version,
|
| 203 |
+
protect,
|
| 204 |
+
None,
|
| 205 |
+
)
|
| 206 |
+
if tgt_sr != resample_sr >= 16000:
|
| 207 |
+
tgt_sr = resample_sr
|
| 208 |
+
info = f"Success. Time: edge-tts: {edge_time}s, npy: {times[0]}s, f0: {times[1]}s, infer: {times[2]}s"
|
| 209 |
+
print(info)
|
| 210 |
+
return (
|
| 211 |
+
info,
|
| 212 |
+
edge_output_filename,
|
| 213 |
+
(tgt_sr, audio_opt),
|
| 214 |
+
)
|
| 215 |
+
except EOFError:
|
| 216 |
+
info = (
|
| 217 |
+
"It seems that the edge-tts output is not valid. "
|
| 218 |
+
"This may occur when the input text and the speaker do not match. "
|
| 219 |
+
"For example, maybe you entered Japanese (without alphabets) text but chose non-Japanese speaker?"
|
| 220 |
+
)
|
| 221 |
+
print(info)
|
| 222 |
+
return info, None, None
|
| 223 |
+
except:
|
| 224 |
+
info = traceback.format_exc()
|
| 225 |
+
print(info)
|
| 226 |
+
return info, None, None
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
initial_md = """
|
| 231 |
+
# RVC text-to-speech webui
|
| 232 |
+
|
| 233 |
+
This is a text-to-speech webui of RVC models.
|
| 234 |
+
|
| 235 |
+
Input text ➡[(edge-tts)](https://github.com/rany2/edge-tts)➡ Speech mp3 file ➡[(RVC)](https://github.com/RVC-Project/Retrieval-based-Voice-Conversion-WebUI)➡ Final output
|
| 236 |
+
"""
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
app = gr.Blocks()
|
| 243 |
+
with app:
|
| 244 |
+
gr.Markdown(initial_md)
|
| 245 |
+
with gr.Row():
|
| 246 |
+
with gr.Column():
|
| 247 |
+
model_name = gr.Dropdown(label="Modelos", choices=models, value=models[1])
|
| 248 |
+
f0_key_up = gr.Number(
|
| 249 |
+
label="Transpose (the best value depends on the models and speakers)",
|
| 250 |
+
value=7,
|
| 251 |
+
)
|
| 252 |
+
with gr.Column():
|
| 253 |
+
f0_method = gr.Radio(
|
| 254 |
+
label="Pitch extraction method (pm: very fast, low quality, rmvpe: a little slow, high quality)",
|
| 255 |
+
choices=["pm", "rmvpe"], # harvest and crepe is too slow
|
| 256 |
+
value="rmvpe",
|
| 257 |
+
interactive=True,
|
| 258 |
+
)
|
| 259 |
+
index_rate = gr.Slider(
|
| 260 |
+
minimum=0,
|
| 261 |
+
maximum=1,
|
| 262 |
+
label="Index rate",
|
| 263 |
+
value=1,
|
| 264 |
+
interactive=True,
|
| 265 |
+
)
|
| 266 |
+
protect0 = gr.Slider(
|
| 267 |
+
minimum=0,
|
| 268 |
+
maximum=0.5,
|
| 269 |
+
label="Protect",
|
| 270 |
+
value=0.33,
|
| 271 |
+
step=0.01,
|
| 272 |
+
interactive=True,
|
| 273 |
+
)
|
| 274 |
+
with gr.Row():
|
| 275 |
+
with gr.Column():
|
| 276 |
+
tts_voice = gr.Dropdown(
|
| 277 |
+
label="Edge-tts speaker (format: language-Country-Name-Gender)",
|
| 278 |
+
choices=tts_voices,
|
| 279 |
+
allow_custom_value=False,
|
| 280 |
+
value="es-AR-ElenaNeural-Female",
|
| 281 |
+
)
|
| 282 |
+
speed = gr.Slider(
|
| 283 |
+
minimum=-100,
|
| 284 |
+
maximum=100,
|
| 285 |
+
label="Speech speed (%)",
|
| 286 |
+
value=0,
|
| 287 |
+
step=10,
|
| 288 |
+
interactive=True,
|
| 289 |
+
)
|
| 290 |
+
tts_text = gr.Textbox(label="Input Text", value="これは日本語テキストから音声への変換デモです。")
|
| 291 |
+
with gr.Column():
|
| 292 |
+
but0 = gr.Button("Convert", variant="primary")
|
| 293 |
+
info_text = gr.Textbox(label="Output info")
|
| 294 |
+
with gr.Column():
|
| 295 |
+
edge_tts_output = gr.Audio(label="Edge Voice", type="filepath")
|
| 296 |
+
tts_output = gr.Audio(label="Result",)
|
| 297 |
+
but0.click(
|
| 298 |
+
tts,
|
| 299 |
+
[
|
| 300 |
+
model_name,
|
| 301 |
+
speed,
|
| 302 |
+
tts_text,
|
| 303 |
+
tts_voice,
|
| 304 |
+
f0_key_up,
|
| 305 |
+
f0_method,
|
| 306 |
+
index_rate,
|
| 307 |
+
protect0,
|
| 308 |
+
],
|
| 309 |
+
[info_text, edge_tts_output, tts_output],
|
| 310 |
+
)
|
| 311 |
+
with gr.Row():
|
| 312 |
+
examples = gr.Examples(
|
| 313 |
+
examples_per_page=100,
|
| 314 |
+
examples=[
|
| 315 |
+
["これは日本語テキストから音声への変換デモです。", "ja-JP-NanamiNeural-Female"],
|
| 316 |
+
[
|
| 317 |
+
"This is an English text to speech conversation demo.",
|
| 318 |
+
"en-US-AriaNeural-Female",
|
| 319 |
+
],
|
| 320 |
+
["这是��个中文文本到语音的转换演示。", "zh-CN-XiaoxiaoNeural-Female"],
|
| 321 |
+
["한국어 텍스트에서 음성으로 변환하는 데모입니다.", "ko-KR-SunHiNeural-Female"],
|
| 322 |
+
[
|
| 323 |
+
"Il s'agit d'une démo de conversion du texte français à la parole.",
|
| 324 |
+
"fr-FR-DeniseNeural-Female",
|
| 325 |
+
],
|
| 326 |
+
[
|
| 327 |
+
"Dies ist eine Demo zur Umwandlung von Deutsch in Sprache.",
|
| 328 |
+
"de-DE-AmalaNeural-Female",
|
| 329 |
+
],
|
| 330 |
+
[
|
| 331 |
+
"Tämä on suomenkielinen tekstistä puheeksi -esittely.",
|
| 332 |
+
"fi-FI-NooraNeural-Female",
|
| 333 |
+
],
|
| 334 |
+
[
|
| 335 |
+
"Это демонстрационный пример преобразования русского текста в речь.",
|
| 336 |
+
"ru-RU-SvetlanaNeural-Female",
|
| 337 |
+
],
|
| 338 |
+
[
|
| 339 |
+
"Αυτή είναι μια επίδειξη μετατροπής ελληνικού κειμένου σε ομιλία.",
|
| 340 |
+
"el-GR-AthinaNeural-Female",
|
| 341 |
+
],
|
| 342 |
+
[
|
| 343 |
+
"Esta es una demostración de conversión de texto a voz en español.",
|
| 344 |
+
"es-ES-ElviraNeural-Female",
|
| 345 |
+
],
|
| 346 |
+
[
|
| 347 |
+
"Questa è una dimostrazione di sintesi vocale in italiano.",
|
| 348 |
+
"it-IT-ElsaNeural-Female",
|
| 349 |
+
],
|
| 350 |
+
[
|
| 351 |
+
"Esta é uma demonstração de conversão de texto em fala em português.",
|
| 352 |
+
"pt-PT-RaquelNeural-Female",
|
| 353 |
+
],
|
| 354 |
+
[
|
| 355 |
+
"Це демонстрація тексту до мовлення українською мовою.",
|
| 356 |
+
"uk-UA-PolinaNeural-Female",
|
| 357 |
+
],
|
| 358 |
+
[
|
| 359 |
+
"هذا عرض توضيحي عربي لتحويل النص إلى كلام.",
|
| 360 |
+
"ar-EG-SalmaNeural-Female",
|
| 361 |
+
],
|
| 362 |
+
[
|
| 363 |
+
"இது தமிழ் உரையிலிருந்து பேச்சு மாற்ற டெமோ.",
|
| 364 |
+
"ta-IN-PallaviNeural-Female",
|
| 365 |
+
],
|
| 366 |
+
],
|
| 367 |
+
inputs=[tts_text, tts_voice],
|
| 368 |
+
)
|
| 369 |
+
app.queue()
|
| 370 |
+
|
| 371 |
+
# gradio en principal
|
| 372 |
+
app.launch(inbrowser=True)
|
assets/screenshot.jpg
ADDED
|
client.js
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
|
| 3 |
+
const dgram = require('dgram');
|
| 4 |
+
const { client } = require("@gradio/client");
|
| 5 |
+
|
| 6 |
+
const app = client("https://dprogrammer-tts-vrc.hf.space/--replicas/xsp7c/", hf_token="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",
|
| 7 |
+
output_dir='D:\\vrc to tts\\audios')
|
| 8 |
+
const UDP_IP = '127.0.0.1'; // IP to listen on
|
| 9 |
+
const UDP_PORT = 5000; // Port to listen on
|
| 10 |
+
|
| 11 |
+
const udpServer = dgram.createSocket('udp4');
|
| 12 |
+
|
| 13 |
+
udpServer.on('listening', () => {
|
| 14 |
+
const address = udpServer.address();
|
| 15 |
+
console.log(`UDP server listening on ${address.address}:${address.port}`);
|
| 16 |
+
});
|
| 17 |
+
|
| 18 |
+
udpServer.on('message', (msg, info) => {
|
| 19 |
+
const receivedMessage = msg.toString('utf8');
|
| 20 |
+
console.log(`Received UDP message: ${receivedMessage}`);
|
| 21 |
+
app.predict("/tts",["mikuDefault",1,"hola soy la miku javascript","es-AR-ElenaNeural-Female",7,"pm",0,0])
|
| 22 |
+
// Send confirmation message back to the sender's address and port
|
| 23 |
+
const confirmationMessage = 'Message received successfully';
|
| 24 |
+
udpServer.send(Buffer.from(confirmationMessage), 8080, info.address, (err) => {
|
| 25 |
+
if (err) {
|
| 26 |
+
console.error('Error sending response:', err);
|
| 27 |
+
} else {
|
| 28 |
+
console.log(`Confirmation message sent to ${info.address}:${info.port}`);
|
| 29 |
+
}
|
| 30 |
+
});
|
| 31 |
+
});
|
| 32 |
+
|
| 33 |
+
udpServer.on('error', (err) => {
|
| 34 |
+
console.error('UDP server error:', err);
|
| 35 |
+
});
|
| 36 |
+
|
| 37 |
+
udpServer.bind(UDP_PORT, UDP_IP);
|
client.py
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from gradio_client import Client
|
| 2 |
+
|
| 3 |
+
# import socket, select, queue
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
# app = Flask(__name__)
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
# client = Client("http://127.0.0.1:7860/")
|
| 12 |
+
client = Client("https://dprogrammer-tts-vrc.hf.space/--replicas/x8rlv",
|
| 13 |
+
output_dir='D:\\vrc to tts\\audios')
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
result = client.predict(
|
| 18 |
+
"mikuDefault", # Literal[MikuDiva, mikuDefault] in 'Modelos' Dropdown component
|
| 19 |
+
1, # float (numeric value between -100 and 100) in 'Speech speed (%)' Slider component
|
| 20 |
+
"soy cordobes me gusta el vino y la joda y lo tomo sin soda porque asi pega mas pega mas pega mas, soy cordobes me gusta el vino y la joda y lo tomo sin soda porque asi pega mas pega mas pega mas, soy cordobes me gusta el vino y la joda y lo tomo sin soda porque asi pega mas pega ", # str in 'Input Text' Textbox component
|
| 21 |
+
"es-AR-ElenaNeural-Female", # Literal[af-ZA-AdriNeural-Female, af-ZA-WillemNeural-Male, sq-AL-AnilaNeural-Female, sq-AL-IlirNeural-Male, am-ET-AmehaNeural-Male, am-ET-MekdesNeural-Female, ar-DZ-AminaNeural-Female, ar-DZ-IsmaelNeural-Male, ar-BH-AliNeural-Male, ar-BH-LailaNeural-Female, ar-EG-SalmaNeural-Female, ar-EG-ShakirNeural-Male, ar-IQ-BasselNeural-Male, ar-IQ-RanaNeural-Female, ar-JO-SanaNeural-Female, ar-JO-TaimNeural-Male, ar-KW-FahedNeural-Male, ar-KW-NouraNeural-Female, ar-LB-LaylaNeural-Female, ar-LB-RamiNeural-Male, ar-LY-ImanNeural-Female, ar-LY-OmarNeural-Male, ar-MA-JamalNeural-Male, ar-MA-MounaNeural-Female, ar-OM-AbdullahNeural-Male, ar-OM-AyshaNeural-Female, ar-QA-AmalNeural-Female, ar-QA-MoazNeural-Male, ar-SA-HamedNeural-Male, ar-SA-ZariyahNeural-Female, ar-SY-AmanyNeural-Female, ar-SY-LaithNeural-Male, ar-TN-HediNeural-Male, ar-TN-ReemNeural-Female, ar-AE-FatimaNeural-Female, ar-AE-HamdanNeural-Male, ar-YE-MaryamNeural-Female, ar-YE-SalehNeural-Male, az-AZ-BabekNeural-Male, az-AZ-BanuNeural-Female, bn-BD-NabanitaNeural-Female, bn-BD-PradeepNeural-Male, bn-IN-BashkarNeural-Male, bn-IN-TanishaaNeural-Female, bs-BA-GoranNeural-Male, bs-BA-VesnaNeural-Female, bg-BG-BorislavNeural-Male, bg-BG-KalinaNeural-Female, my-MM-NilarNeural-Female, my-MM-ThihaNeural-Male, ca-ES-EnricNeural-Male, ca-ES-JoanaNeural-Female, zh-HK-HiuGaaiNeural-Female, zh-HK-HiuMaanNeural-Female, zh-HK-WanLungNeural-Male, zh-CN-XiaoxiaoNeural-Female, zh-CN-XiaoyiNeural-Female, zh-CN-YunjianNeural-Male, zh-CN-YunxiNeural-Male, zh-CN-YunxiaNeural-Male, zh-CN-YunyangNeural-Male, zh-CN-liaoning-XiaobeiNeural-Female, zh-TW-HsiaoChenNeural-Female, zh-TW-YunJheNeural-Male, zh-TW-HsiaoYuNeural-Female, zh-CN-shaanxi-XiaoniNeural-Female, hr-HR-GabrijelaNeural-Female, hr-HR-SreckoNeural-Male, cs-CZ-AntoninNeural-Male, cs-CZ-VlastaNeural-Female, da-DK-ChristelNeural-Female, da-DK-JeppeNeural-Male, nl-BE-ArnaudNeural-Male, nl-BE-DenaNeural-Female, nl-NL-ColetteNeural-Female, nl-NL-FennaNeural-Female, nl-NL-MaartenNeural-Male, en-AU-NatashaNeural-Female, en-AU-WilliamNeural-Male, en-CA-ClaraNeural-Female, en-CA-LiamNeural-Male, en-HK-SamNeural-Male, en-HK-YanNeural-Female, en-IN-NeerjaExpressiveNeural-Female, en-IN-NeerjaNeural-Female, en-IN-PrabhatNeural-Male, en-IE-ConnorNeural-Male, en-IE-EmilyNeural-Female, en-KE-AsiliaNeural-Female, en-KE-ChilembaNeural-Male, en-NZ-MitchellNeural-Male, en-NZ-MollyNeural-Female, en-NG-AbeoNeural-Male, en-NG-EzinneNeural-Female, en-PH-JamesNeural-Male, en-PH-RosaNeural-Female, en-SG-LunaNeural-Female, en-SG-WayneNeural-Male, en-ZA-LeahNeural-Female, en-ZA-LukeNeural-Male, en-TZ-ElimuNeural-Male, en-TZ-ImaniNeural-Female, en-GB-LibbyNeural-Female, en-GB-MaisieNeural-Female, en-GB-RyanNeural-Male, en-GB-SoniaNeural-Female, en-GB-ThomasNeural-Male, en-US-AriaNeural-Female, en-US-AnaNeural-Female, en-US-ChristopherNeural-Male, en-US-EricNeural-Male, en-US-GuyNeural-Male, en-US-JennyNeural-Female, en-US-MichelleNeural-Female, en-US-RogerNeural-Male, en-US-SteffanNeural-Male, et-EE-AnuNeural-Female, et-EE-KertNeural-Male, fil-PH-AngeloNeural-Male, fil-PH-BlessicaNeural-Female, fi-FI-HarriNeural-Male, fi-FI-NooraNeural-Female, fr-BE-CharlineNeural-Female, fr-BE-GerardNeural-Male, fr-CA-AntoineNeural-Male, fr-CA-JeanNeural-Male, fr-CA-SylvieNeural-Female, fr-FR-DeniseNeural-Female, fr-FR-EloiseNeural-Female, fr-FR-HenriNeural-Male, fr-CH-ArianeNeural-Female, fr-CH-FabriceNeural-Male, gl-ES-RoiNeural-Male, gl-ES-SabelaNeural-Female, ka-GE-EkaNeural-Female, ka-GE-GiorgiNeural-Male, de-AT-IngridNeural-Female, de-AT-JonasNeural-Male, de-DE-AmalaNeural-Female, de-DE-ConradNeural-Male, de-DE-KatjaNeural-Female, de-DE-KillianNeural-Male, de-CH-JanNeural-Male, de-CH-LeniNeural-Female, el-GR-AthinaNeural-Female, el-GR-NestorasNeural-Male, gu-IN-DhwaniNeural-Female, gu-IN-NiranjanNeural-Male, he-IL-AvriNeural-Male, he-IL-HilaNeural-Female, hi-IN-MadhurNeural-Male, hi-IN-SwaraNeural-Female, hu-HU-NoemiNeural-Female, hu-HU-TamasNeural-Male, is-IS-GudrunNeural-Female, is-IS-GunnarNeural-Male, id-ID-ArdiNeural-Male, id-ID-GadisNeural-Female, ga-IE-ColmNeural-Male, ga-IE-OrlaNeural-Female, it-IT-DiegoNeural-Male, it-IT-ElsaNeural-Female, it-IT-IsabellaNeural-Female, ja-JP-KeitaNeural-Male, ja-JP-NanamiNeural-Female, jv-ID-DimasNeural-Male, jv-ID-SitiNeural-Female, kn-IN-GaganNeural-Male, kn-IN-SapnaNeural-Female, kk-KZ-AigulNeural-Female, kk-KZ-DauletNeural-Male, km-KH-PisethNeural-Male, km-KH-SreymomNeural-Female, ko-KR-InJoonNeural-Male, ko-KR-SunHiNeural-Female, lo-LA-ChanthavongNeural-Male, lo-LA-KeomanyNeural-Female, lv-LV-EveritaNeural-Female, lv-LV-NilsNeural-Male, lt-LT-LeonasNeural-Male, lt-LT-OnaNeural-Female, mk-MK-AleksandarNeural-Male, mk-MK-MarijaNeural-Female, ms-MY-OsmanNeural-Male, ms-MY-YasminNeural-Female, ml-IN-MidhunNeural-Male, ml-IN-SobhanaNeural-Female, mt-MT-GraceNeural-Female, mt-MT-JosephNeural-Male, mr-IN-AarohiNeural-Female, mr-IN-ManoharNeural-Male, mn-MN-BataaNeural-Male, mn-MN-YesuiNeural-Female, ne-NP-HemkalaNeural-Female, ne-NP-SagarNeural-Male, nb-NO-FinnNeural-Male, nb-NO-PernilleNeural-Female, ps-AF-GulNawazNeural-Male, ps-AF-LatifaNeural-Female, fa-IR-DilaraNeural-Female, fa-IR-FaridNeural-Male, pl-PL-MarekNeural-Male, pl-PL-ZofiaNeural-Female, pt-BR-AntonioNeural-Male, pt-BR-FranciscaNeural-Female, pt-PT-DuarteNeural-Male, pt-PT-RaquelNeural-Female, ro-RO-AlinaNeural-Female, ro-RO-EmilNeural-Male, ru-RU-DmitryNeural-Male, ru-RU-SvetlanaNeural-Female, sr-RS-NicholasNeural-Male, sr-RS-SophieNeural-Female, si-LK-SameeraNeural-Male, si-LK-ThiliniNeural-Female, sk-SK-LukasNeural-Male, sk-SK-ViktoriaNeural-Female, sl-SI-PetraNeural-Female, sl-SI-RokNeural-Male, so-SO-MuuseNeural-Male, so-SO-UbaxNeural-Female, es-AR-ElenaNeural-Female, es-AR-TomasNeural-Male, es-BO-MarceloNeural-Male, es-BO-SofiaNeural-Female, es-CL-CatalinaNeural-Female, es-CL-LorenzoNeural-Male, es-CO-GonzaloNeural-Male, es-CO-SalomeNeural-Female, es-CR-JuanNeural-Male, es-CR-MariaNeural-Female, es-CU-BelkysNeural-Female, es-CU-ManuelNeural-Male, es-DO-EmilioNeural-Male, es-DO-RamonaNeural-Female, es-EC-AndreaNeural-Female, es-EC-LuisNeural-Male, es-SV-LorenaNeural-Female, es-SV-RodrigoNeural-Male, es-GQ-JavierNeural-Male, es-GQ-TeresaNeural-Female, es-GT-AndresNeural-Male, es-GT-MartaNeural-Female, es-HN-CarlosNeural-Male, es-HN-KarlaNeural-Female, es-MX-DaliaNeural-Female, es-MX-JorgeNeural-Male, es-NI-FedericoNeural-Male, es-NI-YolandaNeural-Female, es-PA-MargaritaNeural-Female, es-PA-RobertoNeural-Male, es-PY-MarioNeural-Male, es-PY-TaniaNeural-Female, es-PE-AlexNeural-Male, es-PE-CamilaNeural-Female, es-PR-KarinaNeural-Female, es-PR-VictorNeural-Male, es-ES-AlvaroNeural-Male, es-ES-ElviraNeural-Female, es-US-AlonsoNeural-Male, es-US-PalomaNeural-Female, es-UY-MateoNeural-Male, es-UY-ValentinaNeural-Female, es-VE-PaolaNeural-Female, es-VE-SebastianNeural-Male, su-ID-JajangNeural-Male, su-ID-TutiNeural-Female, sw-KE-RafikiNeural-Male, sw-KE-ZuriNeural-Female, sw-TZ-DaudiNeural-Male, sw-TZ-RehemaNeural-Female, sv-SE-MattiasNeural-Male, sv-SE-SofieNeural-Female, ta-IN-PallaviNeural-Female, ta-IN-ValluvarNeural-Male, ta-MY-KaniNeural-Female, ta-MY-SuryaNeural-Male, ta-SG-AnbuNeural-Male, ta-SG-VenbaNeural-Female, ta-LK-KumarNeural-Male, ta-LK-SaranyaNeural-Female, te-IN-MohanNeural-Male, te-IN-ShrutiNeural-Female, th-TH-NiwatNeural-Male, th-TH-PremwadeeNeural-Female, tr-TR-AhmetNeural-Male, tr-TR-EmelNeural-Female, uk-UA-OstapNeural-Male, uk-UA-PolinaNeural-Female, ur-IN-GulNeural-Female, ur-IN-SalmanNeural-Male, ur-PK-AsadNeural-Male, ur-PK-UzmaNeural-Female, uz-UZ-MadinaNeural-Female, uz-UZ-SardorNeural-Male, vi-VN-HoaiMyNeural-Female, vi-VN-NamMinhNeural-Male, cy-GB-AledNeural-Male, cy-GB-NiaNeural-Female, zu-ZA-ThandoNeural-Female, zu-ZA-ThembaNeural-Male] in 'Edge-tts speaker (format: language-Country-Name-Gender)' Dropdown component
|
| 22 |
+
7, # float in 'Transpose (the best value depends on the models and speakers)' Number component
|
| 23 |
+
"pm", # Literal[pm, rmvpe] in 'Pitch extraction method (pm: very fast, low quality, rmvpe: a little slow, high quality)' Radio component
|
| 24 |
+
0, # float (numeric value between 0 and 1) in 'Index rate' Slider component
|
| 25 |
+
0, # float (numeric value between 0 and 0.5) in 'Protect' Slider component
|
| 26 |
+
api_name="/tts"
|
| 27 |
+
# fn_index=0
|
| 28 |
+
)
|
| 29 |
+
print(result)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
# import socket
|
| 34 |
+
# from gradio_client import Client
|
| 35 |
+
# import requests
|
| 36 |
+
|
| 37 |
+
# # Set a custom timeout for all requests (adjust the timeout as needed)
|
| 38 |
+
# requests.adapters.DEFAULT_RETRIES = 5 # Number of retries on failure
|
| 39 |
+
# requests.adapters.DEFAULT_TIMEOUT = 120
|
| 40 |
+
# UDP_IP = "127.0.0.1" # IP to listen on
|
| 41 |
+
# UDP_PORT = 5000 # Port to listen on
|
| 42 |
+
# TIMEOUT_SECONDS = 70 # Timeout duration in seconds
|
| 43 |
+
|
| 44 |
+
# # Create a UDP socket
|
| 45 |
+
# udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
| 46 |
+
# udp_socket.bind((UDP_IP, UDP_PORT))
|
| 47 |
+
|
| 48 |
+
# # client = Client("http://127.0.0.1:7860")
|
| 49 |
+
# client = Client("https://dprogrammer-tts-vrc.hf.space/--replicas/5bwrc/", hf_token="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",
|
| 50 |
+
# output_dir='D:\\vrc to tts\\audios')
|
| 51 |
+
# def chat(message):
|
| 52 |
+
# result = client.predict(
|
| 53 |
+
# "mikuDefault", # Literal[MikuDiva, mikuDefault] in 'Modelos' Dropdown component
|
| 54 |
+
# 0, # float (numeric value between -100 and 100) in 'Speech speed (%)' Slider component
|
| 55 |
+
# message, # str in 'Input Text' Textbox component
|
| 56 |
+
# "es-AR-ElenaNeural-Female", # Literal[af-ZA-AdriNeural-Female, af-ZA-WillemNeural-Male, sq-AL-AnilaNeural-Female, sq-AL-IlirNeural-Male, am-ET-AmehaNeural-Male, am-ET-MekdesNeural-Female, ar-DZ-AminaNeural-Female, ar-DZ-IsmaelNeural-Male, ar-BH-AliNeural-Male, ar-BH-LailaNeural-Female, ar-EG-SalmaNeural-Female, ar-EG-ShakirNeural-Male, ar-IQ-BasselNeural-Male, ar-IQ-RanaNeural-Female, ar-JO-SanaNeural-Female, ar-JO-TaimNeural-Male, ar-KW-FahedNeural-Male, ar-KW-NouraNeural-Female, ar-LB-LaylaNeural-Female, ar-LB-RamiNeural-Male, ar-LY-ImanNeural-Female, ar-LY-OmarNeural-Male, ar-MA-JamalNeural-Male, ar-MA-MounaNeural-Female, ar-OM-AbdullahNeural-Male, ar-OM-AyshaNeural-Female, ar-QA-AmalNeural-Female, ar-QA-MoazNeural-Male, ar-SA-HamedNeural-Male, ar-SA-ZariyahNeural-Female, ar-SY-AmanyNeural-Female, ar-SY-LaithNeural-Male, ar-TN-HediNeural-Male, ar-TN-ReemNeural-Female, ar-AE-FatimaNeural-Female, ar-AE-HamdanNeural-Male, ar-YE-MaryamNeural-Female, ar-YE-SalehNeural-Male, az-AZ-BabekNeural-Male, az-AZ-BanuNeural-Female, bn-BD-NabanitaNeural-Female, bn-BD-PradeepNeural-Male, bn-IN-BashkarNeural-Male, bn-IN-TanishaaNeural-Female, bs-BA-GoranNeural-Male, bs-BA-VesnaNeural-Female, bg-BG-BorislavNeural-Male, bg-BG-KalinaNeural-Female, my-MM-NilarNeural-Female, my-MM-ThihaNeural-Male, ca-ES-EnricNeural-Male, ca-ES-JoanaNeural-Female, zh-HK-HiuGaaiNeural-Female, zh-HK-HiuMaanNeural-Female, zh-HK-WanLungNeural-Male, zh-CN-XiaoxiaoNeural-Female, zh-CN-XiaoyiNeural-Female, zh-CN-YunjianNeural-Male, zh-CN-YunxiNeural-Male, zh-CN-YunxiaNeural-Male, zh-CN-YunyangNeural-Male, zh-CN-liaoning-XiaobeiNeural-Female, zh-TW-HsiaoChenNeural-Female, zh-TW-YunJheNeural-Male, zh-TW-HsiaoYuNeural-Female, zh-CN-shaanxi-XiaoniNeural-Female, hr-HR-GabrijelaNeural-Female, hr-HR-SreckoNeural-Male, cs-CZ-AntoninNeural-Male, cs-CZ-VlastaNeural-Female, da-DK-ChristelNeural-Female, da-DK-JeppeNeural-Male, nl-BE-ArnaudNeural-Male, nl-BE-DenaNeural-Female, nl-NL-ColetteNeural-Female, nl-NL-FennaNeural-Female, nl-NL-MaartenNeural-Male, en-AU-NatashaNeural-Female, en-AU-WilliamNeural-Male, en-CA-ClaraNeural-Female, en-CA-LiamNeural-Male, en-HK-SamNeural-Male, en-HK-YanNeural-Female, en-IN-NeerjaExpressiveNeural-Female, en-IN-NeerjaNeural-Female, en-IN-PrabhatNeural-Male, en-IE-ConnorNeural-Male, en-IE-EmilyNeural-Female, en-KE-AsiliaNeural-Female, en-KE-ChilembaNeural-Male, en-NZ-MitchellNeural-Male, en-NZ-MollyNeural-Female, en-NG-AbeoNeural-Male, en-NG-EzinneNeural-Female, en-PH-JamesNeural-Male, en-PH-RosaNeural-Female, en-SG-LunaNeural-Female, en-SG-WayneNeural-Male, en-ZA-LeahNeural-Female, en-ZA-LukeNeural-Male, en-TZ-ElimuNeural-Male, en-TZ-ImaniNeural-Female, en-GB-LibbyNeural-Female, en-GB-MaisieNeural-Female, en-GB-RyanNeural-Male, en-GB-SoniaNeural-Female, en-GB-ThomasNeural-Male, en-US-AriaNeural-Female, en-US-AnaNeural-Female, en-US-ChristopherNeural-Male, en-US-EricNeural-Male, en-US-GuyNeural-Male, en-US-JennyNeural-Female, en-US-MichelleNeural-Female, en-US-RogerNeural-Male, en-US-SteffanNeural-Male, et-EE-AnuNeural-Female, et-EE-KertNeural-Male, fil-PH-AngeloNeural-Male, fil-PH-BlessicaNeural-Female, fi-FI-HarriNeural-Male, fi-FI-NooraNeural-Female, fr-BE-CharlineNeural-Female, fr-BE-GerardNeural-Male, fr-CA-AntoineNeural-Male, fr-CA-JeanNeural-Male, fr-CA-SylvieNeural-Female, fr-FR-DeniseNeural-Female, fr-FR-EloiseNeural-Female, fr-FR-HenriNeural-Male, fr-CH-ArianeNeural-Female, fr-CH-FabriceNeural-Male, gl-ES-RoiNeural-Male, gl-ES-SabelaNeural-Female, ka-GE-EkaNeural-Female, ka-GE-GiorgiNeural-Male, de-AT-IngridNeural-Female, de-AT-JonasNeural-Male, de-DE-AmalaNeural-Female, de-DE-ConradNeural-Male, de-DE-KatjaNeural-Female, de-DE-KillianNeural-Male, de-CH-JanNeural-Male, de-CH-LeniNeural-Female, el-GR-AthinaNeural-Female, el-GR-NestorasNeural-Male, gu-IN-DhwaniNeural-Female, gu-IN-NiranjanNeural-Male, he-IL-AvriNeural-Male, he-IL-HilaNeural-Female, hi-IN-MadhurNeural-Male, hi-IN-SwaraNeural-Female, hu-HU-NoemiNeural-Female, hu-HU-TamasNeural-Male, is-IS-GudrunNeural-Female, is-IS-GunnarNeural-Male, id-ID-ArdiNeural-Male, id-ID-GadisNeural-Female, ga-IE-ColmNeural-Male, ga-IE-OrlaNeural-Female, it-IT-DiegoNeural-Male, it-IT-ElsaNeural-Female, it-IT-IsabellaNeural-Female, ja-JP-KeitaNeural-Male, ja-JP-NanamiNeural-Female, jv-ID-DimasNeural-Male, jv-ID-SitiNeural-Female, kn-IN-GaganNeural-Male, kn-IN-SapnaNeural-Female, kk-KZ-AigulNeural-Female, kk-KZ-DauletNeural-Male, km-KH-PisethNeural-Male, km-KH-SreymomNeural-Female, ko-KR-InJoonNeural-Male, ko-KR-SunHiNeural-Female, lo-LA-ChanthavongNeural-Male, lo-LA-KeomanyNeural-Female, lv-LV-EveritaNeural-Female, lv-LV-NilsNeural-Male, lt-LT-LeonasNeural-Male, lt-LT-OnaNeural-Female, mk-MK-AleksandarNeural-Male, mk-MK-MarijaNeural-Female, ms-MY-OsmanNeural-Male, ms-MY-YasminNeural-Female, ml-IN-MidhunNeural-Male, ml-IN-SobhanaNeural-Female, mt-MT-GraceNeural-Female, mt-MT-JosephNeural-Male, mr-IN-AarohiNeural-Female, mr-IN-ManoharNeural-Male, mn-MN-BataaNeural-Male, mn-MN-YesuiNeural-Female, ne-NP-HemkalaNeural-Female, ne-NP-SagarNeural-Male, nb-NO-FinnNeural-Male, nb-NO-PernilleNeural-Female, ps-AF-GulNawazNeural-Male, ps-AF-LatifaNeural-Female, fa-IR-DilaraNeural-Female, fa-IR-FaridNeural-Male, pl-PL-MarekNeural-Male, pl-PL-ZofiaNeural-Female, pt-BR-AntonioNeural-Male, pt-BR-FranciscaNeural-Female, pt-PT-DuarteNeural-Male, pt-PT-RaquelNeural-Female, ro-RO-AlinaNeural-Female, ro-RO-EmilNeural-Male, ru-RU-DmitryNeural-Male, ru-RU-SvetlanaNeural-Female, sr-RS-NicholasNeural-Male, sr-RS-SophieNeural-Female, si-LK-SameeraNeural-Male, si-LK-ThiliniNeural-Female, sk-SK-LukasNeural-Male, sk-SK-ViktoriaNeural-Female, sl-SI-PetraNeural-Female, sl-SI-RokNeural-Male, so-SO-MuuseNeural-Male, so-SO-UbaxNeural-Female, es-AR-ElenaNeural-Female, es-AR-TomasNeural-Male, es-BO-MarceloNeural-Male, es-BO-SofiaNeural-Female, es-CL-CatalinaNeural-Female, es-CL-LorenzoNeural-Male, es-CO-GonzaloNeural-Male, es-CO-SalomeNeural-Female, es-CR-JuanNeural-Male, es-CR-MariaNeural-Female, es-CU-BelkysNeural-Female, es-CU-ManuelNeural-Male, es-DO-EmilioNeural-Male, es-DO-RamonaNeural-Female, es-EC-AndreaNeural-Female, es-EC-LuisNeural-Male, es-SV-LorenaNeural-Female, es-SV-RodrigoNeural-Male, es-GQ-JavierNeural-Male, es-GQ-TeresaNeural-Female, es-GT-AndresNeural-Male, es-GT-MartaNeural-Female, es-HN-CarlosNeural-Male, es-HN-KarlaNeural-Female, es-MX-DaliaNeural-Female, es-MX-JorgeNeural-Male, es-NI-FedericoNeural-Male, es-NI-YolandaNeural-Female, es-PA-MargaritaNeural-Female, es-PA-RobertoNeural-Male, es-PY-MarioNeural-Male, es-PY-TaniaNeural-Female, es-PE-AlexNeural-Male, es-PE-CamilaNeural-Female, es-PR-KarinaNeural-Female, es-PR-VictorNeural-Male, es-ES-AlvaroNeural-Male, es-ES-ElviraNeural-Female, es-US-AlonsoNeural-Male, es-US-PalomaNeural-Female, es-UY-MateoNeural-Male, es-UY-ValentinaNeural-Female, es-VE-PaolaNeural-Female, es-VE-SebastianNeural-Male, su-ID-JajangNeural-Male, su-ID-TutiNeural-Female, sw-KE-RafikiNeural-Male, sw-KE-ZuriNeural-Female, sw-TZ-DaudiNeural-Male, sw-TZ-RehemaNeural-Female, sv-SE-MattiasNeural-Male, sv-SE-SofieNeural-Female, ta-IN-PallaviNeural-Female, ta-IN-ValluvarNeural-Male, ta-MY-KaniNeural-Female, ta-MY-SuryaNeural-Male, ta-SG-AnbuNeural-Male, ta-SG-VenbaNeural-Female, ta-LK-KumarNeural-Male, ta-LK-SaranyaNeural-Female, te-IN-MohanNeural-Male, te-IN-ShrutiNeural-Female, th-TH-NiwatNeural-Male, th-TH-PremwadeeNeural-Female, tr-TR-AhmetNeural-Male, tr-TR-EmelNeural-Female, uk-UA-OstapNeural-Male, uk-UA-PolinaNeural-Female, ur-IN-GulNeural-Female, ur-IN-SalmanNeural-Male, ur-PK-AsadNeural-Male, ur-PK-UzmaNeural-Female, uz-UZ-MadinaNeural-Female, uz-UZ-SardorNeural-Male, vi-VN-HoaiMyNeural-Female, vi-VN-NamMinhNeural-Male, cy-GB-AledNeural-Male, cy-GB-NiaNeural-Female, zu-ZA-ThandoNeural-Female, zu-ZA-ThembaNeural-Male] in 'Edge-tts speaker (format: language-Country-Name-Gender)' Dropdown component
|
| 57 |
+
# 8, # float in 'Transpose (the best value depends on the models and speakers)' Number component
|
| 58 |
+
# "pm", # Literal[pm, rmvpe] in 'Pitch extraction method (pm: very fast, low quality, rmvpe: a little slow, high quality)' Radio component
|
| 59 |
+
# 0, # float (numeric value between 0 and 1) in 'Index rate' Slider component
|
| 60 |
+
# 0, # float (numeric value between 0 and 0.5) in 'Protect' Slider component
|
| 61 |
+
# # fn_index=0
|
| 62 |
+
# api_name="/tts"
|
| 63 |
+
# )
|
| 64 |
+
# print(result)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
# print(f"UDP server listening on {UDP_IP}:{UDP_PORT}")
|
| 69 |
+
|
| 70 |
+
# try:
|
| 71 |
+
# # Set timeout for recvfrom() to 10 seconds
|
| 72 |
+
# udp_socket.settimeout(TIMEOUT_SECONDS)
|
| 73 |
+
|
| 74 |
+
# while True:
|
| 75 |
+
# try:
|
| 76 |
+
# # Receive UDP packet within the timeout duration
|
| 77 |
+
# data, addr = udp_socket.recvfrom(1024) # Buffer size is 1024 bytes, change as needed
|
| 78 |
+
# received_message = data.decode('utf-8') # Decode bytes to string
|
| 79 |
+
|
| 80 |
+
# # Process the received message
|
| 81 |
+
# print(f"Received UDP message: {received_message}")
|
| 82 |
+
# chat(received_message)
|
| 83 |
+
|
| 84 |
+
# # Send confirmation message back to the client
|
| 85 |
+
# confirmation_message = "Message received successfully"
|
| 86 |
+
# udp_socket.sendto(confirmation_message.encode('utf-8'), ("127.0.0.1",8080))
|
| 87 |
+
# print("Confirmation message sent")
|
| 88 |
+
# print("")
|
| 89 |
+
# print("Waiting chat message")
|
| 90 |
+
# except socket.timeout:
|
| 91 |
+
# print(f"No message received within {TIMEOUT_SECONDS} seconds. Closing the UDP server...")
|
| 92 |
+
# break
|
| 93 |
+
|
| 94 |
+
# except NameError as e:
|
| 95 |
+
# print(f"Error occurred: {e}")
|
| 96 |
+
# udp_socket.sendto("error ocurred".encode('utf-8'), ("127.0.0.1",8080))
|
| 97 |
+
# finally:
|
| 98 |
+
# print("\nClosing the UDP server...")
|
| 99 |
+
# udp_socket.close()
|
config.py
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import sys
|
| 3 |
+
import torch
|
| 4 |
+
from multiprocessing import cpu_count
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class Config:
|
| 8 |
+
def __init__(self):
|
| 9 |
+
self.device = "cuda:0"
|
| 10 |
+
self.is_half = True
|
| 11 |
+
self.n_cpu = 0
|
| 12 |
+
self.gpu_name = None
|
| 13 |
+
self.gpu_mem = None
|
| 14 |
+
(
|
| 15 |
+
self.python_cmd,
|
| 16 |
+
self.listen_port,
|
| 17 |
+
self.iscolab,
|
| 18 |
+
self.noparallel,
|
| 19 |
+
self.noautoopen,
|
| 20 |
+
) = self.arg_parse()
|
| 21 |
+
self.x_pad, self.x_query, self.x_center, self.x_max = self.device_config()
|
| 22 |
+
|
| 23 |
+
@staticmethod
|
| 24 |
+
def arg_parse() -> tuple:
|
| 25 |
+
exe = sys.executable or "python"
|
| 26 |
+
parser = argparse.ArgumentParser()
|
| 27 |
+
parser.add_argument("--port", type=int, default=7865, help="Listen port")
|
| 28 |
+
parser.add_argument("--pycmd", type=str, default=exe, help="Python command")
|
| 29 |
+
parser.add_argument("--colab", action="store_true", help="Launch in colab")
|
| 30 |
+
parser.add_argument(
|
| 31 |
+
"--noparallel", action="store_true", help="Disable parallel processing"
|
| 32 |
+
)
|
| 33 |
+
parser.add_argument(
|
| 34 |
+
"--noautoopen",
|
| 35 |
+
action="store_true",
|
| 36 |
+
help="Do not open in browser automatically",
|
| 37 |
+
)
|
| 38 |
+
cmd_opts = parser.parse_args()
|
| 39 |
+
|
| 40 |
+
cmd_opts.port = cmd_opts.port if 0 <= cmd_opts.port <= 65535 else 7865
|
| 41 |
+
|
| 42 |
+
return (
|
| 43 |
+
cmd_opts.pycmd,
|
| 44 |
+
cmd_opts.port,
|
| 45 |
+
cmd_opts.colab,
|
| 46 |
+
cmd_opts.noparallel,
|
| 47 |
+
cmd_opts.noautoopen,
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
# has_mps is only available in nightly pytorch (for now) and MasOS 12.3+.
|
| 51 |
+
# check `getattr` and try it for compatibility
|
| 52 |
+
@staticmethod
|
| 53 |
+
def has_mps() -> bool:
|
| 54 |
+
if not torch.backends.mps.is_available():
|
| 55 |
+
return False
|
| 56 |
+
try:
|
| 57 |
+
torch.zeros(1).to(torch.device("mps"))
|
| 58 |
+
return True
|
| 59 |
+
except Exception:
|
| 60 |
+
return False
|
| 61 |
+
|
| 62 |
+
def device_config(self) -> tuple:
|
| 63 |
+
if torch.cuda.is_available():
|
| 64 |
+
i_device = int(self.device.split(":")[-1])
|
| 65 |
+
self.gpu_name = torch.cuda.get_device_name(i_device)
|
| 66 |
+
if (
|
| 67 |
+
("16" in self.gpu_name and "V100" not in self.gpu_name.upper())
|
| 68 |
+
or "P40" in self.gpu_name.upper()
|
| 69 |
+
or "1060" in self.gpu_name
|
| 70 |
+
or "1070" in self.gpu_name
|
| 71 |
+
or "1080" in self.gpu_name
|
| 72 |
+
):
|
| 73 |
+
print("Found GPU", self.gpu_name, ", force to fp32")
|
| 74 |
+
self.is_half = False
|
| 75 |
+
else:
|
| 76 |
+
print("Found GPU", self.gpu_name)
|
| 77 |
+
self.gpu_mem = int(
|
| 78 |
+
torch.cuda.get_device_properties(i_device).total_memory
|
| 79 |
+
/ 1024
|
| 80 |
+
/ 1024
|
| 81 |
+
/ 1024
|
| 82 |
+
+ 0.4
|
| 83 |
+
)
|
| 84 |
+
elif self.has_mps():
|
| 85 |
+
print("No supported Nvidia GPU found, use MPS instead")
|
| 86 |
+
self.device = "mps"
|
| 87 |
+
self.is_half = False
|
| 88 |
+
else:
|
| 89 |
+
print("No supported Nvidia GPU found, use CPU instead")
|
| 90 |
+
self.device = "cpu"
|
| 91 |
+
self.is_half = False
|
| 92 |
+
|
| 93 |
+
if self.n_cpu == 0:
|
| 94 |
+
self.n_cpu = cpu_count()
|
| 95 |
+
|
| 96 |
+
if self.is_half:
|
| 97 |
+
# 6G显存配置
|
| 98 |
+
x_pad = 3
|
| 99 |
+
x_query = 10
|
| 100 |
+
x_center = 60
|
| 101 |
+
x_max = 65
|
| 102 |
+
else:
|
| 103 |
+
# 5G显存配置
|
| 104 |
+
x_pad = 1
|
| 105 |
+
x_query = 6
|
| 106 |
+
x_center = 38
|
| 107 |
+
x_max = 41
|
| 108 |
+
|
| 109 |
+
if self.gpu_mem != None and self.gpu_mem <= 4:
|
| 110 |
+
x_pad = 1
|
| 111 |
+
x_query = 5
|
| 112 |
+
x_center = 30
|
| 113 |
+
x_max = 32
|
| 114 |
+
|
| 115 |
+
return x_pad, x_query, x_center, x_max
|
lib/infer_pack/attentions.py
ADDED
|
@@ -0,0 +1,417 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import copy
|
| 2 |
+
import math
|
| 3 |
+
import numpy as np
|
| 4 |
+
import torch
|
| 5 |
+
from torch import nn
|
| 6 |
+
from torch.nn import functional as F
|
| 7 |
+
|
| 8 |
+
from lib.infer_pack import commons
|
| 9 |
+
from lib.infer_pack import modules
|
| 10 |
+
from lib.infer_pack.modules import LayerNorm
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class Encoder(nn.Module):
|
| 14 |
+
def __init__(
|
| 15 |
+
self,
|
| 16 |
+
hidden_channels,
|
| 17 |
+
filter_channels,
|
| 18 |
+
n_heads,
|
| 19 |
+
n_layers,
|
| 20 |
+
kernel_size=1,
|
| 21 |
+
p_dropout=0.0,
|
| 22 |
+
window_size=10,
|
| 23 |
+
**kwargs
|
| 24 |
+
):
|
| 25 |
+
super().__init__()
|
| 26 |
+
self.hidden_channels = hidden_channels
|
| 27 |
+
self.filter_channels = filter_channels
|
| 28 |
+
self.n_heads = n_heads
|
| 29 |
+
self.n_layers = n_layers
|
| 30 |
+
self.kernel_size = kernel_size
|
| 31 |
+
self.p_dropout = p_dropout
|
| 32 |
+
self.window_size = window_size
|
| 33 |
+
|
| 34 |
+
self.drop = nn.Dropout(p_dropout)
|
| 35 |
+
self.attn_layers = nn.ModuleList()
|
| 36 |
+
self.norm_layers_1 = nn.ModuleList()
|
| 37 |
+
self.ffn_layers = nn.ModuleList()
|
| 38 |
+
self.norm_layers_2 = nn.ModuleList()
|
| 39 |
+
for i in range(self.n_layers):
|
| 40 |
+
self.attn_layers.append(
|
| 41 |
+
MultiHeadAttention(
|
| 42 |
+
hidden_channels,
|
| 43 |
+
hidden_channels,
|
| 44 |
+
n_heads,
|
| 45 |
+
p_dropout=p_dropout,
|
| 46 |
+
window_size=window_size,
|
| 47 |
+
)
|
| 48 |
+
)
|
| 49 |
+
self.norm_layers_1.append(LayerNorm(hidden_channels))
|
| 50 |
+
self.ffn_layers.append(
|
| 51 |
+
FFN(
|
| 52 |
+
hidden_channels,
|
| 53 |
+
hidden_channels,
|
| 54 |
+
filter_channels,
|
| 55 |
+
kernel_size,
|
| 56 |
+
p_dropout=p_dropout,
|
| 57 |
+
)
|
| 58 |
+
)
|
| 59 |
+
self.norm_layers_2.append(LayerNorm(hidden_channels))
|
| 60 |
+
|
| 61 |
+
def forward(self, x, x_mask):
|
| 62 |
+
attn_mask = x_mask.unsqueeze(2) * x_mask.unsqueeze(-1)
|
| 63 |
+
x = x * x_mask
|
| 64 |
+
for i in range(self.n_layers):
|
| 65 |
+
y = self.attn_layers[i](x, x, attn_mask)
|
| 66 |
+
y = self.drop(y)
|
| 67 |
+
x = self.norm_layers_1[i](x + y)
|
| 68 |
+
|
| 69 |
+
y = self.ffn_layers[i](x, x_mask)
|
| 70 |
+
y = self.drop(y)
|
| 71 |
+
x = self.norm_layers_2[i](x + y)
|
| 72 |
+
x = x * x_mask
|
| 73 |
+
return x
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
class Decoder(nn.Module):
|
| 77 |
+
def __init__(
|
| 78 |
+
self,
|
| 79 |
+
hidden_channels,
|
| 80 |
+
filter_channels,
|
| 81 |
+
n_heads,
|
| 82 |
+
n_layers,
|
| 83 |
+
kernel_size=1,
|
| 84 |
+
p_dropout=0.0,
|
| 85 |
+
proximal_bias=False,
|
| 86 |
+
proximal_init=True,
|
| 87 |
+
**kwargs
|
| 88 |
+
):
|
| 89 |
+
super().__init__()
|
| 90 |
+
self.hidden_channels = hidden_channels
|
| 91 |
+
self.filter_channels = filter_channels
|
| 92 |
+
self.n_heads = n_heads
|
| 93 |
+
self.n_layers = n_layers
|
| 94 |
+
self.kernel_size = kernel_size
|
| 95 |
+
self.p_dropout = p_dropout
|
| 96 |
+
self.proximal_bias = proximal_bias
|
| 97 |
+
self.proximal_init = proximal_init
|
| 98 |
+
|
| 99 |
+
self.drop = nn.Dropout(p_dropout)
|
| 100 |
+
self.self_attn_layers = nn.ModuleList()
|
| 101 |
+
self.norm_layers_0 = nn.ModuleList()
|
| 102 |
+
self.encdec_attn_layers = nn.ModuleList()
|
| 103 |
+
self.norm_layers_1 = nn.ModuleList()
|
| 104 |
+
self.ffn_layers = nn.ModuleList()
|
| 105 |
+
self.norm_layers_2 = nn.ModuleList()
|
| 106 |
+
for i in range(self.n_layers):
|
| 107 |
+
self.self_attn_layers.append(
|
| 108 |
+
MultiHeadAttention(
|
| 109 |
+
hidden_channels,
|
| 110 |
+
hidden_channels,
|
| 111 |
+
n_heads,
|
| 112 |
+
p_dropout=p_dropout,
|
| 113 |
+
proximal_bias=proximal_bias,
|
| 114 |
+
proximal_init=proximal_init,
|
| 115 |
+
)
|
| 116 |
+
)
|
| 117 |
+
self.norm_layers_0.append(LayerNorm(hidden_channels))
|
| 118 |
+
self.encdec_attn_layers.append(
|
| 119 |
+
MultiHeadAttention(
|
| 120 |
+
hidden_channels, hidden_channels, n_heads, p_dropout=p_dropout
|
| 121 |
+
)
|
| 122 |
+
)
|
| 123 |
+
self.norm_layers_1.append(LayerNorm(hidden_channels))
|
| 124 |
+
self.ffn_layers.append(
|
| 125 |
+
FFN(
|
| 126 |
+
hidden_channels,
|
| 127 |
+
hidden_channels,
|
| 128 |
+
filter_channels,
|
| 129 |
+
kernel_size,
|
| 130 |
+
p_dropout=p_dropout,
|
| 131 |
+
causal=True,
|
| 132 |
+
)
|
| 133 |
+
)
|
| 134 |
+
self.norm_layers_2.append(LayerNorm(hidden_channels))
|
| 135 |
+
|
| 136 |
+
def forward(self, x, x_mask, h, h_mask):
|
| 137 |
+
"""
|
| 138 |
+
x: decoder input
|
| 139 |
+
h: encoder output
|
| 140 |
+
"""
|
| 141 |
+
self_attn_mask = commons.subsequent_mask(x_mask.size(2)).to(
|
| 142 |
+
device=x.device, dtype=x.dtype
|
| 143 |
+
)
|
| 144 |
+
encdec_attn_mask = h_mask.unsqueeze(2) * x_mask.unsqueeze(-1)
|
| 145 |
+
x = x * x_mask
|
| 146 |
+
for i in range(self.n_layers):
|
| 147 |
+
y = self.self_attn_layers[i](x, x, self_attn_mask)
|
| 148 |
+
y = self.drop(y)
|
| 149 |
+
x = self.norm_layers_0[i](x + y)
|
| 150 |
+
|
| 151 |
+
y = self.encdec_attn_layers[i](x, h, encdec_attn_mask)
|
| 152 |
+
y = self.drop(y)
|
| 153 |
+
x = self.norm_layers_1[i](x + y)
|
| 154 |
+
|
| 155 |
+
y = self.ffn_layers[i](x, x_mask)
|
| 156 |
+
y = self.drop(y)
|
| 157 |
+
x = self.norm_layers_2[i](x + y)
|
| 158 |
+
x = x * x_mask
|
| 159 |
+
return x
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
class MultiHeadAttention(nn.Module):
|
| 163 |
+
def __init__(
|
| 164 |
+
self,
|
| 165 |
+
channels,
|
| 166 |
+
out_channels,
|
| 167 |
+
n_heads,
|
| 168 |
+
p_dropout=0.0,
|
| 169 |
+
window_size=None,
|
| 170 |
+
heads_share=True,
|
| 171 |
+
block_length=None,
|
| 172 |
+
proximal_bias=False,
|
| 173 |
+
proximal_init=False,
|
| 174 |
+
):
|
| 175 |
+
super().__init__()
|
| 176 |
+
assert channels % n_heads == 0
|
| 177 |
+
|
| 178 |
+
self.channels = channels
|
| 179 |
+
self.out_channels = out_channels
|
| 180 |
+
self.n_heads = n_heads
|
| 181 |
+
self.p_dropout = p_dropout
|
| 182 |
+
self.window_size = window_size
|
| 183 |
+
self.heads_share = heads_share
|
| 184 |
+
self.block_length = block_length
|
| 185 |
+
self.proximal_bias = proximal_bias
|
| 186 |
+
self.proximal_init = proximal_init
|
| 187 |
+
self.attn = None
|
| 188 |
+
|
| 189 |
+
self.k_channels = channels // n_heads
|
| 190 |
+
self.conv_q = nn.Conv1d(channels, channels, 1)
|
| 191 |
+
self.conv_k = nn.Conv1d(channels, channels, 1)
|
| 192 |
+
self.conv_v = nn.Conv1d(channels, channels, 1)
|
| 193 |
+
self.conv_o = nn.Conv1d(channels, out_channels, 1)
|
| 194 |
+
self.drop = nn.Dropout(p_dropout)
|
| 195 |
+
|
| 196 |
+
if window_size is not None:
|
| 197 |
+
n_heads_rel = 1 if heads_share else n_heads
|
| 198 |
+
rel_stddev = self.k_channels**-0.5
|
| 199 |
+
self.emb_rel_k = nn.Parameter(
|
| 200 |
+
torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels)
|
| 201 |
+
* rel_stddev
|
| 202 |
+
)
|
| 203 |
+
self.emb_rel_v = nn.Parameter(
|
| 204 |
+
torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels)
|
| 205 |
+
* rel_stddev
|
| 206 |
+
)
|
| 207 |
+
|
| 208 |
+
nn.init.xavier_uniform_(self.conv_q.weight)
|
| 209 |
+
nn.init.xavier_uniform_(self.conv_k.weight)
|
| 210 |
+
nn.init.xavier_uniform_(self.conv_v.weight)
|
| 211 |
+
if proximal_init:
|
| 212 |
+
with torch.no_grad():
|
| 213 |
+
self.conv_k.weight.copy_(self.conv_q.weight)
|
| 214 |
+
self.conv_k.bias.copy_(self.conv_q.bias)
|
| 215 |
+
|
| 216 |
+
def forward(self, x, c, attn_mask=None):
|
| 217 |
+
q = self.conv_q(x)
|
| 218 |
+
k = self.conv_k(c)
|
| 219 |
+
v = self.conv_v(c)
|
| 220 |
+
|
| 221 |
+
x, self.attn = self.attention(q, k, v, mask=attn_mask)
|
| 222 |
+
|
| 223 |
+
x = self.conv_o(x)
|
| 224 |
+
return x
|
| 225 |
+
|
| 226 |
+
def attention(self, query, key, value, mask=None):
|
| 227 |
+
# reshape [b, d, t] -> [b, n_h, t, d_k]
|
| 228 |
+
b, d, t_s, t_t = (*key.size(), query.size(2))
|
| 229 |
+
query = query.view(b, self.n_heads, self.k_channels, t_t).transpose(2, 3)
|
| 230 |
+
key = key.view(b, self.n_heads, self.k_channels, t_s).transpose(2, 3)
|
| 231 |
+
value = value.view(b, self.n_heads, self.k_channels, t_s).transpose(2, 3)
|
| 232 |
+
|
| 233 |
+
scores = torch.matmul(query / math.sqrt(self.k_channels), key.transpose(-2, -1))
|
| 234 |
+
if self.window_size is not None:
|
| 235 |
+
assert (
|
| 236 |
+
t_s == t_t
|
| 237 |
+
), "Relative attention is only available for self-attention."
|
| 238 |
+
key_relative_embeddings = self._get_relative_embeddings(self.emb_rel_k, t_s)
|
| 239 |
+
rel_logits = self._matmul_with_relative_keys(
|
| 240 |
+
query / math.sqrt(self.k_channels), key_relative_embeddings
|
| 241 |
+
)
|
| 242 |
+
scores_local = self._relative_position_to_absolute_position(rel_logits)
|
| 243 |
+
scores = scores + scores_local
|
| 244 |
+
if self.proximal_bias:
|
| 245 |
+
assert t_s == t_t, "Proximal bias is only available for self-attention."
|
| 246 |
+
scores = scores + self._attention_bias_proximal(t_s).to(
|
| 247 |
+
device=scores.device, dtype=scores.dtype
|
| 248 |
+
)
|
| 249 |
+
if mask is not None:
|
| 250 |
+
scores = scores.masked_fill(mask == 0, -1e4)
|
| 251 |
+
if self.block_length is not None:
|
| 252 |
+
assert (
|
| 253 |
+
t_s == t_t
|
| 254 |
+
), "Local attention is only available for self-attention."
|
| 255 |
+
block_mask = (
|
| 256 |
+
torch.ones_like(scores)
|
| 257 |
+
.triu(-self.block_length)
|
| 258 |
+
.tril(self.block_length)
|
| 259 |
+
)
|
| 260 |
+
scores = scores.masked_fill(block_mask == 0, -1e4)
|
| 261 |
+
p_attn = F.softmax(scores, dim=-1) # [b, n_h, t_t, t_s]
|
| 262 |
+
p_attn = self.drop(p_attn)
|
| 263 |
+
output = torch.matmul(p_attn, value)
|
| 264 |
+
if self.window_size is not None:
|
| 265 |
+
relative_weights = self._absolute_position_to_relative_position(p_attn)
|
| 266 |
+
value_relative_embeddings = self._get_relative_embeddings(
|
| 267 |
+
self.emb_rel_v, t_s
|
| 268 |
+
)
|
| 269 |
+
output = output + self._matmul_with_relative_values(
|
| 270 |
+
relative_weights, value_relative_embeddings
|
| 271 |
+
)
|
| 272 |
+
output = (
|
| 273 |
+
output.transpose(2, 3).contiguous().view(b, d, t_t)
|
| 274 |
+
) # [b, n_h, t_t, d_k] -> [b, d, t_t]
|
| 275 |
+
return output, p_attn
|
| 276 |
+
|
| 277 |
+
def _matmul_with_relative_values(self, x, y):
|
| 278 |
+
"""
|
| 279 |
+
x: [b, h, l, m]
|
| 280 |
+
y: [h or 1, m, d]
|
| 281 |
+
ret: [b, h, l, d]
|
| 282 |
+
"""
|
| 283 |
+
ret = torch.matmul(x, y.unsqueeze(0))
|
| 284 |
+
return ret
|
| 285 |
+
|
| 286 |
+
def _matmul_with_relative_keys(self, x, y):
|
| 287 |
+
"""
|
| 288 |
+
x: [b, h, l, d]
|
| 289 |
+
y: [h or 1, m, d]
|
| 290 |
+
ret: [b, h, l, m]
|
| 291 |
+
"""
|
| 292 |
+
ret = torch.matmul(x, y.unsqueeze(0).transpose(-2, -1))
|
| 293 |
+
return ret
|
| 294 |
+
|
| 295 |
+
def _get_relative_embeddings(self, relative_embeddings, length):
|
| 296 |
+
max_relative_position = 2 * self.window_size + 1
|
| 297 |
+
# Pad first before slice to avoid using cond ops.
|
| 298 |
+
pad_length = max(length - (self.window_size + 1), 0)
|
| 299 |
+
slice_start_position = max((self.window_size + 1) - length, 0)
|
| 300 |
+
slice_end_position = slice_start_position + 2 * length - 1
|
| 301 |
+
if pad_length > 0:
|
| 302 |
+
padded_relative_embeddings = F.pad(
|
| 303 |
+
relative_embeddings,
|
| 304 |
+
commons.convert_pad_shape([[0, 0], [pad_length, pad_length], [0, 0]]),
|
| 305 |
+
)
|
| 306 |
+
else:
|
| 307 |
+
padded_relative_embeddings = relative_embeddings
|
| 308 |
+
used_relative_embeddings = padded_relative_embeddings[
|
| 309 |
+
:, slice_start_position:slice_end_position
|
| 310 |
+
]
|
| 311 |
+
return used_relative_embeddings
|
| 312 |
+
|
| 313 |
+
def _relative_position_to_absolute_position(self, x):
|
| 314 |
+
"""
|
| 315 |
+
x: [b, h, l, 2*l-1]
|
| 316 |
+
ret: [b, h, l, l]
|
| 317 |
+
"""
|
| 318 |
+
batch, heads, length, _ = x.size()
|
| 319 |
+
# Concat columns of pad to shift from relative to absolute indexing.
|
| 320 |
+
x = F.pad(x, commons.convert_pad_shape([[0, 0], [0, 0], [0, 0], [0, 1]]))
|
| 321 |
+
|
| 322 |
+
# Concat extra elements so to add up to shape (len+1, 2*len-1).
|
| 323 |
+
x_flat = x.view([batch, heads, length * 2 * length])
|
| 324 |
+
x_flat = F.pad(
|
| 325 |
+
x_flat, commons.convert_pad_shape([[0, 0], [0, 0], [0, length - 1]])
|
| 326 |
+
)
|
| 327 |
+
|
| 328 |
+
# Reshape and slice out the padded elements.
|
| 329 |
+
x_final = x_flat.view([batch, heads, length + 1, 2 * length - 1])[
|
| 330 |
+
:, :, :length, length - 1 :
|
| 331 |
+
]
|
| 332 |
+
return x_final
|
| 333 |
+
|
| 334 |
+
def _absolute_position_to_relative_position(self, x):
|
| 335 |
+
"""
|
| 336 |
+
x: [b, h, l, l]
|
| 337 |
+
ret: [b, h, l, 2*l-1]
|
| 338 |
+
"""
|
| 339 |
+
batch, heads, length, _ = x.size()
|
| 340 |
+
# padd along column
|
| 341 |
+
x = F.pad(
|
| 342 |
+
x, commons.convert_pad_shape([[0, 0], [0, 0], [0, 0], [0, length - 1]])
|
| 343 |
+
)
|
| 344 |
+
x_flat = x.view([batch, heads, length**2 + length * (length - 1)])
|
| 345 |
+
# add 0's in the beginning that will skew the elements after reshape
|
| 346 |
+
x_flat = F.pad(x_flat, commons.convert_pad_shape([[0, 0], [0, 0], [length, 0]]))
|
| 347 |
+
x_final = x_flat.view([batch, heads, length, 2 * length])[:, :, :, 1:]
|
| 348 |
+
return x_final
|
| 349 |
+
|
| 350 |
+
def _attention_bias_proximal(self, length):
|
| 351 |
+
"""Bias for self-attention to encourage attention to close positions.
|
| 352 |
+
Args:
|
| 353 |
+
length: an integer scalar.
|
| 354 |
+
Returns:
|
| 355 |
+
a Tensor with shape [1, 1, length, length]
|
| 356 |
+
"""
|
| 357 |
+
r = torch.arange(length, dtype=torch.float32)
|
| 358 |
+
diff = torch.unsqueeze(r, 0) - torch.unsqueeze(r, 1)
|
| 359 |
+
return torch.unsqueeze(torch.unsqueeze(-torch.log1p(torch.abs(diff)), 0), 0)
|
| 360 |
+
|
| 361 |
+
|
| 362 |
+
class FFN(nn.Module):
|
| 363 |
+
def __init__(
|
| 364 |
+
self,
|
| 365 |
+
in_channels,
|
| 366 |
+
out_channels,
|
| 367 |
+
filter_channels,
|
| 368 |
+
kernel_size,
|
| 369 |
+
p_dropout=0.0,
|
| 370 |
+
activation=None,
|
| 371 |
+
causal=False,
|
| 372 |
+
):
|
| 373 |
+
super().__init__()
|
| 374 |
+
self.in_channels = in_channels
|
| 375 |
+
self.out_channels = out_channels
|
| 376 |
+
self.filter_channels = filter_channels
|
| 377 |
+
self.kernel_size = kernel_size
|
| 378 |
+
self.p_dropout = p_dropout
|
| 379 |
+
self.activation = activation
|
| 380 |
+
self.causal = causal
|
| 381 |
+
|
| 382 |
+
if causal:
|
| 383 |
+
self.padding = self._causal_padding
|
| 384 |
+
else:
|
| 385 |
+
self.padding = self._same_padding
|
| 386 |
+
|
| 387 |
+
self.conv_1 = nn.Conv1d(in_channels, filter_channels, kernel_size)
|
| 388 |
+
self.conv_2 = nn.Conv1d(filter_channels, out_channels, kernel_size)
|
| 389 |
+
self.drop = nn.Dropout(p_dropout)
|
| 390 |
+
|
| 391 |
+
def forward(self, x, x_mask):
|
| 392 |
+
x = self.conv_1(self.padding(x * x_mask))
|
| 393 |
+
if self.activation == "gelu":
|
| 394 |
+
x = x * torch.sigmoid(1.702 * x)
|
| 395 |
+
else:
|
| 396 |
+
x = torch.relu(x)
|
| 397 |
+
x = self.drop(x)
|
| 398 |
+
x = self.conv_2(self.padding(x * x_mask))
|
| 399 |
+
return x * x_mask
|
| 400 |
+
|
| 401 |
+
def _causal_padding(self, x):
|
| 402 |
+
if self.kernel_size == 1:
|
| 403 |
+
return x
|
| 404 |
+
pad_l = self.kernel_size - 1
|
| 405 |
+
pad_r = 0
|
| 406 |
+
padding = [[0, 0], [0, 0], [pad_l, pad_r]]
|
| 407 |
+
x = F.pad(x, commons.convert_pad_shape(padding))
|
| 408 |
+
return x
|
| 409 |
+
|
| 410 |
+
def _same_padding(self, x):
|
| 411 |
+
if self.kernel_size == 1:
|
| 412 |
+
return x
|
| 413 |
+
pad_l = (self.kernel_size - 1) // 2
|
| 414 |
+
pad_r = self.kernel_size // 2
|
| 415 |
+
padding = [[0, 0], [0, 0], [pad_l, pad_r]]
|
| 416 |
+
x = F.pad(x, commons.convert_pad_shape(padding))
|
| 417 |
+
return x
|
lib/infer_pack/commons.py
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
import numpy as np
|
| 3 |
+
import torch
|
| 4 |
+
from torch import nn
|
| 5 |
+
from torch.nn import functional as F
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def init_weights(m, mean=0.0, std=0.01):
|
| 9 |
+
classname = m.__class__.__name__
|
| 10 |
+
if classname.find("Conv") != -1:
|
| 11 |
+
m.weight.data.normal_(mean, std)
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def get_padding(kernel_size, dilation=1):
|
| 15 |
+
return int((kernel_size * dilation - dilation) / 2)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def convert_pad_shape(pad_shape):
|
| 19 |
+
l = pad_shape[::-1]
|
| 20 |
+
pad_shape = [item for sublist in l for item in sublist]
|
| 21 |
+
return pad_shape
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def kl_divergence(m_p, logs_p, m_q, logs_q):
|
| 25 |
+
"""KL(P||Q)"""
|
| 26 |
+
kl = (logs_q - logs_p) - 0.5
|
| 27 |
+
kl += (
|
| 28 |
+
0.5 * (torch.exp(2.0 * logs_p) + ((m_p - m_q) ** 2)) * torch.exp(-2.0 * logs_q)
|
| 29 |
+
)
|
| 30 |
+
return kl
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def rand_gumbel(shape):
|
| 34 |
+
"""Sample from the Gumbel distribution, protect from overflows."""
|
| 35 |
+
uniform_samples = torch.rand(shape) * 0.99998 + 0.00001
|
| 36 |
+
return -torch.log(-torch.log(uniform_samples))
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def rand_gumbel_like(x):
|
| 40 |
+
g = rand_gumbel(x.size()).to(dtype=x.dtype, device=x.device)
|
| 41 |
+
return g
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def slice_segments(x, ids_str, segment_size=4):
|
| 45 |
+
ret = torch.zeros_like(x[:, :, :segment_size])
|
| 46 |
+
for i in range(x.size(0)):
|
| 47 |
+
idx_str = ids_str[i]
|
| 48 |
+
idx_end = idx_str + segment_size
|
| 49 |
+
ret[i] = x[i, :, idx_str:idx_end]
|
| 50 |
+
return ret
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def slice_segments2(x, ids_str, segment_size=4):
|
| 54 |
+
ret = torch.zeros_like(x[:, :segment_size])
|
| 55 |
+
for i in range(x.size(0)):
|
| 56 |
+
idx_str = ids_str[i]
|
| 57 |
+
idx_end = idx_str + segment_size
|
| 58 |
+
ret[i] = x[i, idx_str:idx_end]
|
| 59 |
+
return ret
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def rand_slice_segments(x, x_lengths=None, segment_size=4):
|
| 63 |
+
b, d, t = x.size()
|
| 64 |
+
if x_lengths is None:
|
| 65 |
+
x_lengths = t
|
| 66 |
+
ids_str_max = x_lengths - segment_size + 1
|
| 67 |
+
ids_str = (torch.rand([b]).to(device=x.device) * ids_str_max).to(dtype=torch.long)
|
| 68 |
+
ret = slice_segments(x, ids_str, segment_size)
|
| 69 |
+
return ret, ids_str
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def get_timing_signal_1d(length, channels, min_timescale=1.0, max_timescale=1.0e4):
|
| 73 |
+
position = torch.arange(length, dtype=torch.float)
|
| 74 |
+
num_timescales = channels // 2
|
| 75 |
+
log_timescale_increment = math.log(float(max_timescale) / float(min_timescale)) / (
|
| 76 |
+
num_timescales - 1
|
| 77 |
+
)
|
| 78 |
+
inv_timescales = min_timescale * torch.exp(
|
| 79 |
+
torch.arange(num_timescales, dtype=torch.float) * -log_timescale_increment
|
| 80 |
+
)
|
| 81 |
+
scaled_time = position.unsqueeze(0) * inv_timescales.unsqueeze(1)
|
| 82 |
+
signal = torch.cat([torch.sin(scaled_time), torch.cos(scaled_time)], 0)
|
| 83 |
+
signal = F.pad(signal, [0, 0, 0, channels % 2])
|
| 84 |
+
signal = signal.view(1, channels, length)
|
| 85 |
+
return signal
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def add_timing_signal_1d(x, min_timescale=1.0, max_timescale=1.0e4):
|
| 89 |
+
b, channels, length = x.size()
|
| 90 |
+
signal = get_timing_signal_1d(length, channels, min_timescale, max_timescale)
|
| 91 |
+
return x + signal.to(dtype=x.dtype, device=x.device)
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def cat_timing_signal_1d(x, min_timescale=1.0, max_timescale=1.0e4, axis=1):
|
| 95 |
+
b, channels, length = x.size()
|
| 96 |
+
signal = get_timing_signal_1d(length, channels, min_timescale, max_timescale)
|
| 97 |
+
return torch.cat([x, signal.to(dtype=x.dtype, device=x.device)], axis)
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def subsequent_mask(length):
|
| 101 |
+
mask = torch.tril(torch.ones(length, length)).unsqueeze(0).unsqueeze(0)
|
| 102 |
+
return mask
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
@torch.jit.script
|
| 106 |
+
def fused_add_tanh_sigmoid_multiply(input_a, input_b, n_channels):
|
| 107 |
+
n_channels_int = n_channels[0]
|
| 108 |
+
in_act = input_a + input_b
|
| 109 |
+
t_act = torch.tanh(in_act[:, :n_channels_int, :])
|
| 110 |
+
s_act = torch.sigmoid(in_act[:, n_channels_int:, :])
|
| 111 |
+
acts = t_act * s_act
|
| 112 |
+
return acts
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def convert_pad_shape(pad_shape):
|
| 116 |
+
l = pad_shape[::-1]
|
| 117 |
+
pad_shape = [item for sublist in l for item in sublist]
|
| 118 |
+
return pad_shape
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def shift_1d(x):
|
| 122 |
+
x = F.pad(x, convert_pad_shape([[0, 0], [0, 0], [1, 0]]))[:, :, :-1]
|
| 123 |
+
return x
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def sequence_mask(length, max_length=None):
|
| 127 |
+
if max_length is None:
|
| 128 |
+
max_length = length.max()
|
| 129 |
+
x = torch.arange(max_length, dtype=length.dtype, device=length.device)
|
| 130 |
+
return x.unsqueeze(0) < length.unsqueeze(1)
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def generate_path(duration, mask):
|
| 134 |
+
"""
|
| 135 |
+
duration: [b, 1, t_x]
|
| 136 |
+
mask: [b, 1, t_y, t_x]
|
| 137 |
+
"""
|
| 138 |
+
device = duration.device
|
| 139 |
+
|
| 140 |
+
b, _, t_y, t_x = mask.shape
|
| 141 |
+
cum_duration = torch.cumsum(duration, -1)
|
| 142 |
+
|
| 143 |
+
cum_duration_flat = cum_duration.view(b * t_x)
|
| 144 |
+
path = sequence_mask(cum_duration_flat, t_y).to(mask.dtype)
|
| 145 |
+
path = path.view(b, t_x, t_y)
|
| 146 |
+
path = path - F.pad(path, convert_pad_shape([[0, 0], [1, 0], [0, 0]]))[:, :-1]
|
| 147 |
+
path = path.unsqueeze(1).transpose(2, 3) * mask
|
| 148 |
+
return path
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def clip_grad_value_(parameters, clip_value, norm_type=2):
|
| 152 |
+
if isinstance(parameters, torch.Tensor):
|
| 153 |
+
parameters = [parameters]
|
| 154 |
+
parameters = list(filter(lambda p: p.grad is not None, parameters))
|
| 155 |
+
norm_type = float(norm_type)
|
| 156 |
+
if clip_value is not None:
|
| 157 |
+
clip_value = float(clip_value)
|
| 158 |
+
|
| 159 |
+
total_norm = 0
|
| 160 |
+
for p in parameters:
|
| 161 |
+
param_norm = p.grad.data.norm(norm_type)
|
| 162 |
+
total_norm += param_norm.item() ** norm_type
|
| 163 |
+
if clip_value is not None:
|
| 164 |
+
p.grad.data.clamp_(min=-clip_value, max=clip_value)
|
| 165 |
+
total_norm = total_norm ** (1.0 / norm_type)
|
| 166 |
+
return total_norm
|
lib/infer_pack/models.py
ADDED
|
@@ -0,0 +1,1142 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
+
from lib.infer_pack import modules
|
| 7 |
+
from lib.infer_pack import attentions
|
| 8 |
+
from lib.infer_pack import commons
|
| 9 |
+
from lib.infer_pack.commons import init_weights, get_padding
|
| 10 |
+
from torch.nn import Conv1d, ConvTranspose1d, AvgPool1d, Conv2d
|
| 11 |
+
from torch.nn.utils import weight_norm, remove_weight_norm, spectral_norm
|
| 12 |
+
from lib.infer_pack.commons import init_weights
|
| 13 |
+
import numpy as np
|
| 14 |
+
from lib.infer_pack import commons
|
| 15 |
+
|
| 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 |
+
return uv
|
| 319 |
+
|
| 320 |
+
def forward(self, f0, upp):
|
| 321 |
+
"""sine_tensor, uv = forward(f0)
|
| 322 |
+
input F0: tensor(batchsize=1, length, dim=1)
|
| 323 |
+
f0 for unvoiced steps should be 0
|
| 324 |
+
output sine_tensor: tensor(batchsize=1, length, dim)
|
| 325 |
+
output uv: tensor(batchsize=1, length, 1)
|
| 326 |
+
"""
|
| 327 |
+
with torch.no_grad():
|
| 328 |
+
f0 = f0[:, None].transpose(1, 2)
|
| 329 |
+
f0_buf = torch.zeros(f0.shape[0], f0.shape[1], self.dim, device=f0.device)
|
| 330 |
+
# fundamental component
|
| 331 |
+
f0_buf[:, :, 0] = f0[:, :, 0]
|
| 332 |
+
for idx in np.arange(self.harmonic_num):
|
| 333 |
+
f0_buf[:, :, idx + 1] = f0_buf[:, :, 0] * (
|
| 334 |
+
idx + 2
|
| 335 |
+
) # idx + 2: the (idx+1)-th overtone, (idx+2)-th harmonic
|
| 336 |
+
rad_values = (f0_buf / self.sampling_rate) % 1 ###%1意味着n_har的乘积无法后处理优化
|
| 337 |
+
rand_ini = torch.rand(
|
| 338 |
+
f0_buf.shape[0], f0_buf.shape[2], device=f0_buf.device
|
| 339 |
+
)
|
| 340 |
+
rand_ini[:, 0] = 0
|
| 341 |
+
rad_values[:, 0, :] = rad_values[:, 0, :] + rand_ini
|
| 342 |
+
tmp_over_one = torch.cumsum(rad_values, 1) # % 1 #####%1意味着后面的cumsum无法再优化
|
| 343 |
+
tmp_over_one *= upp
|
| 344 |
+
tmp_over_one = F.interpolate(
|
| 345 |
+
tmp_over_one.transpose(2, 1),
|
| 346 |
+
scale_factor=upp,
|
| 347 |
+
mode="linear",
|
| 348 |
+
align_corners=True,
|
| 349 |
+
).transpose(2, 1)
|
| 350 |
+
rad_values = F.interpolate(
|
| 351 |
+
rad_values.transpose(2, 1), scale_factor=upp, mode="nearest"
|
| 352 |
+
).transpose(
|
| 353 |
+
2, 1
|
| 354 |
+
) #######
|
| 355 |
+
tmp_over_one %= 1
|
| 356 |
+
tmp_over_one_idx = (tmp_over_one[:, 1:, :] - tmp_over_one[:, :-1, :]) < 0
|
| 357 |
+
cumsum_shift = torch.zeros_like(rad_values)
|
| 358 |
+
cumsum_shift[:, 1:, :] = tmp_over_one_idx * -1.0
|
| 359 |
+
sine_waves = torch.sin(
|
| 360 |
+
torch.cumsum(rad_values + cumsum_shift, dim=1) * 2 * np.pi
|
| 361 |
+
)
|
| 362 |
+
sine_waves = sine_waves * self.sine_amp
|
| 363 |
+
uv = self._f02uv(f0)
|
| 364 |
+
uv = F.interpolate(
|
| 365 |
+
uv.transpose(2, 1), scale_factor=upp, mode="nearest"
|
| 366 |
+
).transpose(2, 1)
|
| 367 |
+
noise_amp = uv * self.noise_std + (1 - uv) * self.sine_amp / 3
|
| 368 |
+
noise = noise_amp * torch.randn_like(sine_waves)
|
| 369 |
+
sine_waves = sine_waves * uv + noise
|
| 370 |
+
return sine_waves, uv, noise
|
| 371 |
+
|
| 372 |
+
|
| 373 |
+
class SourceModuleHnNSF(torch.nn.Module):
|
| 374 |
+
"""SourceModule for hn-nsf
|
| 375 |
+
SourceModule(sampling_rate, harmonic_num=0, sine_amp=0.1,
|
| 376 |
+
add_noise_std=0.003, voiced_threshod=0)
|
| 377 |
+
sampling_rate: sampling_rate in Hz
|
| 378 |
+
harmonic_num: number of harmonic above F0 (default: 0)
|
| 379 |
+
sine_amp: amplitude of sine source signal (default: 0.1)
|
| 380 |
+
add_noise_std: std of additive Gaussian noise (default: 0.003)
|
| 381 |
+
note that amplitude of noise in unvoiced is decided
|
| 382 |
+
by sine_amp
|
| 383 |
+
voiced_threshold: threhold to set U/V given F0 (default: 0)
|
| 384 |
+
Sine_source, noise_source = SourceModuleHnNSF(F0_sampled)
|
| 385 |
+
F0_sampled (batchsize, length, 1)
|
| 386 |
+
Sine_source (batchsize, length, 1)
|
| 387 |
+
noise_source (batchsize, length 1)
|
| 388 |
+
uv (batchsize, length, 1)
|
| 389 |
+
"""
|
| 390 |
+
|
| 391 |
+
def __init__(
|
| 392 |
+
self,
|
| 393 |
+
sampling_rate,
|
| 394 |
+
harmonic_num=0,
|
| 395 |
+
sine_amp=0.1,
|
| 396 |
+
add_noise_std=0.003,
|
| 397 |
+
voiced_threshod=0,
|
| 398 |
+
is_half=True,
|
| 399 |
+
):
|
| 400 |
+
super(SourceModuleHnNSF, self).__init__()
|
| 401 |
+
|
| 402 |
+
self.sine_amp = sine_amp
|
| 403 |
+
self.noise_std = add_noise_std
|
| 404 |
+
self.is_half = is_half
|
| 405 |
+
# to produce sine waveforms
|
| 406 |
+
self.l_sin_gen = SineGen(
|
| 407 |
+
sampling_rate, harmonic_num, sine_amp, add_noise_std, voiced_threshod
|
| 408 |
+
)
|
| 409 |
+
|
| 410 |
+
# to merge source harmonics into a single excitation
|
| 411 |
+
self.l_linear = torch.nn.Linear(harmonic_num + 1, 1)
|
| 412 |
+
self.l_tanh = torch.nn.Tanh()
|
| 413 |
+
|
| 414 |
+
def forward(self, x, upp=None):
|
| 415 |
+
sine_wavs, uv, _ = self.l_sin_gen(x, upp)
|
| 416 |
+
if self.is_half:
|
| 417 |
+
sine_wavs = sine_wavs.half()
|
| 418 |
+
sine_merge = self.l_tanh(self.l_linear(sine_wavs))
|
| 419 |
+
return sine_merge, None, None # noise, uv
|
| 420 |
+
|
| 421 |
+
|
| 422 |
+
class GeneratorNSF(torch.nn.Module):
|
| 423 |
+
def __init__(
|
| 424 |
+
self,
|
| 425 |
+
initial_channel,
|
| 426 |
+
resblock,
|
| 427 |
+
resblock_kernel_sizes,
|
| 428 |
+
resblock_dilation_sizes,
|
| 429 |
+
upsample_rates,
|
| 430 |
+
upsample_initial_channel,
|
| 431 |
+
upsample_kernel_sizes,
|
| 432 |
+
gin_channels,
|
| 433 |
+
sr,
|
| 434 |
+
is_half=False,
|
| 435 |
+
):
|
| 436 |
+
super(GeneratorNSF, self).__init__()
|
| 437 |
+
self.num_kernels = len(resblock_kernel_sizes)
|
| 438 |
+
self.num_upsamples = len(upsample_rates)
|
| 439 |
+
|
| 440 |
+
self.f0_upsamp = torch.nn.Upsample(scale_factor=np.prod(upsample_rates))
|
| 441 |
+
self.m_source = SourceModuleHnNSF(
|
| 442 |
+
sampling_rate=sr, harmonic_num=0, is_half=is_half
|
| 443 |
+
)
|
| 444 |
+
self.noise_convs = nn.ModuleList()
|
| 445 |
+
self.conv_pre = Conv1d(
|
| 446 |
+
initial_channel, upsample_initial_channel, 7, 1, padding=3
|
| 447 |
+
)
|
| 448 |
+
resblock = modules.ResBlock1 if resblock == "1" else modules.ResBlock2
|
| 449 |
+
|
| 450 |
+
self.ups = nn.ModuleList()
|
| 451 |
+
for i, (u, k) in enumerate(zip(upsample_rates, upsample_kernel_sizes)):
|
| 452 |
+
c_cur = upsample_initial_channel // (2 ** (i + 1))
|
| 453 |
+
self.ups.append(
|
| 454 |
+
weight_norm(
|
| 455 |
+
ConvTranspose1d(
|
| 456 |
+
upsample_initial_channel // (2**i),
|
| 457 |
+
upsample_initial_channel // (2 ** (i + 1)),
|
| 458 |
+
k,
|
| 459 |
+
u,
|
| 460 |
+
padding=(k - u) // 2,
|
| 461 |
+
)
|
| 462 |
+
)
|
| 463 |
+
)
|
| 464 |
+
if i + 1 < len(upsample_rates):
|
| 465 |
+
stride_f0 = np.prod(upsample_rates[i + 1 :])
|
| 466 |
+
self.noise_convs.append(
|
| 467 |
+
Conv1d(
|
| 468 |
+
1,
|
| 469 |
+
c_cur,
|
| 470 |
+
kernel_size=stride_f0 * 2,
|
| 471 |
+
stride=stride_f0,
|
| 472 |
+
padding=stride_f0 // 2,
|
| 473 |
+
)
|
| 474 |
+
)
|
| 475 |
+
else:
|
| 476 |
+
self.noise_convs.append(Conv1d(1, c_cur, kernel_size=1))
|
| 477 |
+
|
| 478 |
+
self.resblocks = nn.ModuleList()
|
| 479 |
+
for i in range(len(self.ups)):
|
| 480 |
+
ch = upsample_initial_channel // (2 ** (i + 1))
|
| 481 |
+
for j, (k, d) in enumerate(
|
| 482 |
+
zip(resblock_kernel_sizes, resblock_dilation_sizes)
|
| 483 |
+
):
|
| 484 |
+
self.resblocks.append(resblock(ch, k, d))
|
| 485 |
+
|
| 486 |
+
self.conv_post = Conv1d(ch, 1, 7, 1, padding=3, bias=False)
|
| 487 |
+
self.ups.apply(init_weights)
|
| 488 |
+
|
| 489 |
+
if gin_channels != 0:
|
| 490 |
+
self.cond = nn.Conv1d(gin_channels, upsample_initial_channel, 1)
|
| 491 |
+
|
| 492 |
+
self.upp = np.prod(upsample_rates)
|
| 493 |
+
|
| 494 |
+
def forward(self, x, f0, g=None):
|
| 495 |
+
har_source, noi_source, uv = self.m_source(f0, self.upp)
|
| 496 |
+
har_source = har_source.transpose(1, 2)
|
| 497 |
+
x = self.conv_pre(x)
|
| 498 |
+
if g is not None:
|
| 499 |
+
x = x + self.cond(g)
|
| 500 |
+
|
| 501 |
+
for i in range(self.num_upsamples):
|
| 502 |
+
x = F.leaky_relu(x, modules.LRELU_SLOPE)
|
| 503 |
+
x = self.ups[i](x)
|
| 504 |
+
x_source = self.noise_convs[i](har_source)
|
| 505 |
+
x = x + x_source
|
| 506 |
+
xs = None
|
| 507 |
+
for j in range(self.num_kernels):
|
| 508 |
+
if xs is None:
|
| 509 |
+
xs = self.resblocks[i * self.num_kernels + j](x)
|
| 510 |
+
else:
|
| 511 |
+
xs += self.resblocks[i * self.num_kernels + j](x)
|
| 512 |
+
x = xs / self.num_kernels
|
| 513 |
+
x = F.leaky_relu(x)
|
| 514 |
+
x = self.conv_post(x)
|
| 515 |
+
x = torch.tanh(x)
|
| 516 |
+
return x
|
| 517 |
+
|
| 518 |
+
def remove_weight_norm(self):
|
| 519 |
+
for l in self.ups:
|
| 520 |
+
remove_weight_norm(l)
|
| 521 |
+
for l in self.resblocks:
|
| 522 |
+
l.remove_weight_norm()
|
| 523 |
+
|
| 524 |
+
|
| 525 |
+
sr2sr = {
|
| 526 |
+
"32k": 32000,
|
| 527 |
+
"40k": 40000,
|
| 528 |
+
"48k": 48000,
|
| 529 |
+
}
|
| 530 |
+
|
| 531 |
+
|
| 532 |
+
class SynthesizerTrnMs256NSFsid(nn.Module):
|
| 533 |
+
def __init__(
|
| 534 |
+
self,
|
| 535 |
+
spec_channels,
|
| 536 |
+
segment_size,
|
| 537 |
+
inter_channels,
|
| 538 |
+
hidden_channels,
|
| 539 |
+
filter_channels,
|
| 540 |
+
n_heads,
|
| 541 |
+
n_layers,
|
| 542 |
+
kernel_size,
|
| 543 |
+
p_dropout,
|
| 544 |
+
resblock,
|
| 545 |
+
resblock_kernel_sizes,
|
| 546 |
+
resblock_dilation_sizes,
|
| 547 |
+
upsample_rates,
|
| 548 |
+
upsample_initial_channel,
|
| 549 |
+
upsample_kernel_sizes,
|
| 550 |
+
spk_embed_dim,
|
| 551 |
+
gin_channels,
|
| 552 |
+
sr,
|
| 553 |
+
**kwargs
|
| 554 |
+
):
|
| 555 |
+
super().__init__()
|
| 556 |
+
if type(sr) == type("strr"):
|
| 557 |
+
sr = sr2sr[sr]
|
| 558 |
+
self.spec_channels = spec_channels
|
| 559 |
+
self.inter_channels = inter_channels
|
| 560 |
+
self.hidden_channels = hidden_channels
|
| 561 |
+
self.filter_channels = filter_channels
|
| 562 |
+
self.n_heads = n_heads
|
| 563 |
+
self.n_layers = n_layers
|
| 564 |
+
self.kernel_size = kernel_size
|
| 565 |
+
self.p_dropout = p_dropout
|
| 566 |
+
self.resblock = resblock
|
| 567 |
+
self.resblock_kernel_sizes = resblock_kernel_sizes
|
| 568 |
+
self.resblock_dilation_sizes = resblock_dilation_sizes
|
| 569 |
+
self.upsample_rates = upsample_rates
|
| 570 |
+
self.upsample_initial_channel = upsample_initial_channel
|
| 571 |
+
self.upsample_kernel_sizes = upsample_kernel_sizes
|
| 572 |
+
self.segment_size = segment_size
|
| 573 |
+
self.gin_channels = gin_channels
|
| 574 |
+
# self.hop_length = hop_length#
|
| 575 |
+
self.spk_embed_dim = spk_embed_dim
|
| 576 |
+
self.enc_p = TextEncoder256(
|
| 577 |
+
inter_channels,
|
| 578 |
+
hidden_channels,
|
| 579 |
+
filter_channels,
|
| 580 |
+
n_heads,
|
| 581 |
+
n_layers,
|
| 582 |
+
kernel_size,
|
| 583 |
+
p_dropout,
|
| 584 |
+
)
|
| 585 |
+
self.dec = GeneratorNSF(
|
| 586 |
+
inter_channels,
|
| 587 |
+
resblock,
|
| 588 |
+
resblock_kernel_sizes,
|
| 589 |
+
resblock_dilation_sizes,
|
| 590 |
+
upsample_rates,
|
| 591 |
+
upsample_initial_channel,
|
| 592 |
+
upsample_kernel_sizes,
|
| 593 |
+
gin_channels=gin_channels,
|
| 594 |
+
sr=sr,
|
| 595 |
+
is_half=kwargs["is_half"],
|
| 596 |
+
)
|
| 597 |
+
self.enc_q = PosteriorEncoder(
|
| 598 |
+
spec_channels,
|
| 599 |
+
inter_channels,
|
| 600 |
+
hidden_channels,
|
| 601 |
+
5,
|
| 602 |
+
1,
|
| 603 |
+
16,
|
| 604 |
+
gin_channels=gin_channels,
|
| 605 |
+
)
|
| 606 |
+
self.flow = ResidualCouplingBlock(
|
| 607 |
+
inter_channels, hidden_channels, 5, 1, 3, gin_channels=gin_channels
|
| 608 |
+
)
|
| 609 |
+
self.emb_g = nn.Embedding(self.spk_embed_dim, gin_channels)
|
| 610 |
+
print("gin_channels:", gin_channels, "self.spk_embed_dim:", self.spk_embed_dim)
|
| 611 |
+
|
| 612 |
+
def remove_weight_norm(self):
|
| 613 |
+
self.dec.remove_weight_norm()
|
| 614 |
+
self.flow.remove_weight_norm()
|
| 615 |
+
self.enc_q.remove_weight_norm()
|
| 616 |
+
|
| 617 |
+
def forward(
|
| 618 |
+
self, phone, phone_lengths, pitch, pitchf, y, y_lengths, ds
|
| 619 |
+
): # 这里ds是id,[bs,1]
|
| 620 |
+
# print(1,pitch.shape)#[bs,t]
|
| 621 |
+
g = self.emb_g(ds).unsqueeze(-1) # [b, 256, 1]##1是t,广播的
|
| 622 |
+
m_p, logs_p, x_mask = self.enc_p(phone, pitch, phone_lengths)
|
| 623 |
+
z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g)
|
| 624 |
+
z_p = self.flow(z, y_mask, g=g)
|
| 625 |
+
z_slice, ids_slice = commons.rand_slice_segments(
|
| 626 |
+
z, y_lengths, self.segment_size
|
| 627 |
+
)
|
| 628 |
+
# print(-1,pitchf.shape,ids_slice,self.segment_size,self.hop_length,self.segment_size//self.hop_length)
|
| 629 |
+
pitchf = commons.slice_segments2(pitchf, ids_slice, self.segment_size)
|
| 630 |
+
# print(-2,pitchf.shape,z_slice.shape)
|
| 631 |
+
o = self.dec(z_slice, pitchf, g=g)
|
| 632 |
+
return o, ids_slice, x_mask, y_mask, (z, z_p, m_p, logs_p, m_q, logs_q)
|
| 633 |
+
|
| 634 |
+
def infer(self, phone, phone_lengths, pitch, nsff0, sid, rate=None):
|
| 635 |
+
g = self.emb_g(sid).unsqueeze(-1)
|
| 636 |
+
m_p, logs_p, x_mask = self.enc_p(phone, pitch, phone_lengths)
|
| 637 |
+
z_p = (m_p + torch.exp(logs_p) * torch.randn_like(m_p) * 0.66666) * x_mask
|
| 638 |
+
if rate:
|
| 639 |
+
head = int(z_p.shape[2] * rate)
|
| 640 |
+
z_p = z_p[:, :, -head:]
|
| 641 |
+
x_mask = x_mask[:, :, -head:]
|
| 642 |
+
nsff0 = nsff0[:, -head:]
|
| 643 |
+
z = self.flow(z_p, x_mask, g=g, reverse=True)
|
| 644 |
+
o = self.dec(z * x_mask, nsff0, g=g)
|
| 645 |
+
return o, x_mask, (z, z_p, m_p, logs_p)
|
| 646 |
+
|
| 647 |
+
|
| 648 |
+
class SynthesizerTrnMs768NSFsid(nn.Module):
|
| 649 |
+
def __init__(
|
| 650 |
+
self,
|
| 651 |
+
spec_channels,
|
| 652 |
+
segment_size,
|
| 653 |
+
inter_channels,
|
| 654 |
+
hidden_channels,
|
| 655 |
+
filter_channels,
|
| 656 |
+
n_heads,
|
| 657 |
+
n_layers,
|
| 658 |
+
kernel_size,
|
| 659 |
+
p_dropout,
|
| 660 |
+
resblock,
|
| 661 |
+
resblock_kernel_sizes,
|
| 662 |
+
resblock_dilation_sizes,
|
| 663 |
+
upsample_rates,
|
| 664 |
+
upsample_initial_channel,
|
| 665 |
+
upsample_kernel_sizes,
|
| 666 |
+
spk_embed_dim,
|
| 667 |
+
gin_channels,
|
| 668 |
+
sr,
|
| 669 |
+
**kwargs
|
| 670 |
+
):
|
| 671 |
+
super().__init__()
|
| 672 |
+
if type(sr) == type("strr"):
|
| 673 |
+
sr = sr2sr[sr]
|
| 674 |
+
self.spec_channels = spec_channels
|
| 675 |
+
self.inter_channels = inter_channels
|
| 676 |
+
self.hidden_channels = hidden_channels
|
| 677 |
+
self.filter_channels = filter_channels
|
| 678 |
+
self.n_heads = n_heads
|
| 679 |
+
self.n_layers = n_layers
|
| 680 |
+
self.kernel_size = kernel_size
|
| 681 |
+
self.p_dropout = p_dropout
|
| 682 |
+
self.resblock = resblock
|
| 683 |
+
self.resblock_kernel_sizes = resblock_kernel_sizes
|
| 684 |
+
self.resblock_dilation_sizes = resblock_dilation_sizes
|
| 685 |
+
self.upsample_rates = upsample_rates
|
| 686 |
+
self.upsample_initial_channel = upsample_initial_channel
|
| 687 |
+
self.upsample_kernel_sizes = upsample_kernel_sizes
|
| 688 |
+
self.segment_size = segment_size
|
| 689 |
+
self.gin_channels = gin_channels
|
| 690 |
+
# self.hop_length = hop_length#
|
| 691 |
+
self.spk_embed_dim = spk_embed_dim
|
| 692 |
+
self.enc_p = TextEncoder768(
|
| 693 |
+
inter_channels,
|
| 694 |
+
hidden_channels,
|
| 695 |
+
filter_channels,
|
| 696 |
+
n_heads,
|
| 697 |
+
n_layers,
|
| 698 |
+
kernel_size,
|
| 699 |
+
p_dropout,
|
| 700 |
+
)
|
| 701 |
+
self.dec = GeneratorNSF(
|
| 702 |
+
inter_channels,
|
| 703 |
+
resblock,
|
| 704 |
+
resblock_kernel_sizes,
|
| 705 |
+
resblock_dilation_sizes,
|
| 706 |
+
upsample_rates,
|
| 707 |
+
upsample_initial_channel,
|
| 708 |
+
upsample_kernel_sizes,
|
| 709 |
+
gin_channels=gin_channels,
|
| 710 |
+
sr=sr,
|
| 711 |
+
is_half=kwargs["is_half"],
|
| 712 |
+
)
|
| 713 |
+
self.enc_q = PosteriorEncoder(
|
| 714 |
+
spec_channels,
|
| 715 |
+
inter_channels,
|
| 716 |
+
hidden_channels,
|
| 717 |
+
5,
|
| 718 |
+
1,
|
| 719 |
+
16,
|
| 720 |
+
gin_channels=gin_channels,
|
| 721 |
+
)
|
| 722 |
+
self.flow = ResidualCouplingBlock(
|
| 723 |
+
inter_channels, hidden_channels, 5, 1, 3, gin_channels=gin_channels
|
| 724 |
+
)
|
| 725 |
+
self.emb_g = nn.Embedding(self.spk_embed_dim, gin_channels)
|
| 726 |
+
print("gin_channels:", gin_channels, "self.spk_embed_dim:", self.spk_embed_dim)
|
| 727 |
+
|
| 728 |
+
def remove_weight_norm(self):
|
| 729 |
+
self.dec.remove_weight_norm()
|
| 730 |
+
self.flow.remove_weight_norm()
|
| 731 |
+
self.enc_q.remove_weight_norm()
|
| 732 |
+
|
| 733 |
+
def forward(
|
| 734 |
+
self, phone, phone_lengths, pitch, pitchf, y, y_lengths, ds
|
| 735 |
+
): # 这里ds是id,[bs,1]
|
| 736 |
+
# print(1,pitch.shape)#[bs,t]
|
| 737 |
+
g = self.emb_g(ds).unsqueeze(-1) # [b, 256, 1]##1是t,广播的
|
| 738 |
+
m_p, logs_p, x_mask = self.enc_p(phone, pitch, phone_lengths)
|
| 739 |
+
z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g)
|
| 740 |
+
z_p = self.flow(z, y_mask, g=g)
|
| 741 |
+
z_slice, ids_slice = commons.rand_slice_segments(
|
| 742 |
+
z, y_lengths, self.segment_size
|
| 743 |
+
)
|
| 744 |
+
# print(-1,pitchf.shape,ids_slice,self.segment_size,self.hop_length,self.segment_size//self.hop_length)
|
| 745 |
+
pitchf = commons.slice_segments2(pitchf, ids_slice, self.segment_size)
|
| 746 |
+
# print(-2,pitchf.shape,z_slice.shape)
|
| 747 |
+
o = self.dec(z_slice, pitchf, g=g)
|
| 748 |
+
return o, ids_slice, x_mask, y_mask, (z, z_p, m_p, logs_p, m_q, logs_q)
|
| 749 |
+
|
| 750 |
+
def infer(self, phone, phone_lengths, pitch, nsff0, sid, rate=None):
|
| 751 |
+
g = self.emb_g(sid).unsqueeze(-1)
|
| 752 |
+
m_p, logs_p, x_mask = self.enc_p(phone, pitch, phone_lengths)
|
| 753 |
+
z_p = (m_p + torch.exp(logs_p) * torch.randn_like(m_p) * 0.66666) * x_mask
|
| 754 |
+
if rate:
|
| 755 |
+
head = int(z_p.shape[2] * rate)
|
| 756 |
+
z_p = z_p[:, :, -head:]
|
| 757 |
+
x_mask = x_mask[:, :, -head:]
|
| 758 |
+
nsff0 = nsff0[:, -head:]
|
| 759 |
+
z = self.flow(z_p, x_mask, g=g, reverse=True)
|
| 760 |
+
o = self.dec(z * x_mask, nsff0, g=g)
|
| 761 |
+
return o, x_mask, (z, z_p, m_p, logs_p)
|
| 762 |
+
|
| 763 |
+
|
| 764 |
+
class SynthesizerTrnMs256NSFsid_nono(nn.Module):
|
| 765 |
+
def __init__(
|
| 766 |
+
self,
|
| 767 |
+
spec_channels,
|
| 768 |
+
segment_size,
|
| 769 |
+
inter_channels,
|
| 770 |
+
hidden_channels,
|
| 771 |
+
filter_channels,
|
| 772 |
+
n_heads,
|
| 773 |
+
n_layers,
|
| 774 |
+
kernel_size,
|
| 775 |
+
p_dropout,
|
| 776 |
+
resblock,
|
| 777 |
+
resblock_kernel_sizes,
|
| 778 |
+
resblock_dilation_sizes,
|
| 779 |
+
upsample_rates,
|
| 780 |
+
upsample_initial_channel,
|
| 781 |
+
upsample_kernel_sizes,
|
| 782 |
+
spk_embed_dim,
|
| 783 |
+
gin_channels,
|
| 784 |
+
sr=None,
|
| 785 |
+
**kwargs
|
| 786 |
+
):
|
| 787 |
+
super().__init__()
|
| 788 |
+
self.spec_channels = spec_channels
|
| 789 |
+
self.inter_channels = inter_channels
|
| 790 |
+
self.hidden_channels = hidden_channels
|
| 791 |
+
self.filter_channels = filter_channels
|
| 792 |
+
self.n_heads = n_heads
|
| 793 |
+
self.n_layers = n_layers
|
| 794 |
+
self.kernel_size = kernel_size
|
| 795 |
+
self.p_dropout = p_dropout
|
| 796 |
+
self.resblock = resblock
|
| 797 |
+
self.resblock_kernel_sizes = resblock_kernel_sizes
|
| 798 |
+
self.resblock_dilation_sizes = resblock_dilation_sizes
|
| 799 |
+
self.upsample_rates = upsample_rates
|
| 800 |
+
self.upsample_initial_channel = upsample_initial_channel
|
| 801 |
+
self.upsample_kernel_sizes = upsample_kernel_sizes
|
| 802 |
+
self.segment_size = segment_size
|
| 803 |
+
self.gin_channels = gin_channels
|
| 804 |
+
# self.hop_length = hop_length#
|
| 805 |
+
self.spk_embed_dim = spk_embed_dim
|
| 806 |
+
self.enc_p = TextEncoder256(
|
| 807 |
+
inter_channels,
|
| 808 |
+
hidden_channels,
|
| 809 |
+
filter_channels,
|
| 810 |
+
n_heads,
|
| 811 |
+
n_layers,
|
| 812 |
+
kernel_size,
|
| 813 |
+
p_dropout,
|
| 814 |
+
f0=False,
|
| 815 |
+
)
|
| 816 |
+
self.dec = Generator(
|
| 817 |
+
inter_channels,
|
| 818 |
+
resblock,
|
| 819 |
+
resblock_kernel_sizes,
|
| 820 |
+
resblock_dilation_sizes,
|
| 821 |
+
upsample_rates,
|
| 822 |
+
upsample_initial_channel,
|
| 823 |
+
upsample_kernel_sizes,
|
| 824 |
+
gin_channels=gin_channels,
|
| 825 |
+
)
|
| 826 |
+
self.enc_q = PosteriorEncoder(
|
| 827 |
+
spec_channels,
|
| 828 |
+
inter_channels,
|
| 829 |
+
hidden_channels,
|
| 830 |
+
5,
|
| 831 |
+
1,
|
| 832 |
+
16,
|
| 833 |
+
gin_channels=gin_channels,
|
| 834 |
+
)
|
| 835 |
+
self.flow = ResidualCouplingBlock(
|
| 836 |
+
inter_channels, hidden_channels, 5, 1, 3, gin_channels=gin_channels
|
| 837 |
+
)
|
| 838 |
+
self.emb_g = nn.Embedding(self.spk_embed_dim, gin_channels)
|
| 839 |
+
print("gin_channels:", gin_channels, "self.spk_embed_dim:", self.spk_embed_dim)
|
| 840 |
+
|
| 841 |
+
def remove_weight_norm(self):
|
| 842 |
+
self.dec.remove_weight_norm()
|
| 843 |
+
self.flow.remove_weight_norm()
|
| 844 |
+
self.enc_q.remove_weight_norm()
|
| 845 |
+
|
| 846 |
+
def forward(self, phone, phone_lengths, y, y_lengths, ds): # 这里ds是id,[bs,1]
|
| 847 |
+
g = self.emb_g(ds).unsqueeze(-1) # [b, 256, 1]##1是t,广播的
|
| 848 |
+
m_p, logs_p, x_mask = self.enc_p(phone, None, phone_lengths)
|
| 849 |
+
z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g)
|
| 850 |
+
z_p = self.flow(z, y_mask, g=g)
|
| 851 |
+
z_slice, ids_slice = commons.rand_slice_segments(
|
| 852 |
+
z, y_lengths, self.segment_size
|
| 853 |
+
)
|
| 854 |
+
o = self.dec(z_slice, g=g)
|
| 855 |
+
return o, ids_slice, x_mask, y_mask, (z, z_p, m_p, logs_p, m_q, logs_q)
|
| 856 |
+
|
| 857 |
+
def infer(self, phone, phone_lengths, sid, rate=None):
|
| 858 |
+
g = self.emb_g(sid).unsqueeze(-1)
|
| 859 |
+
m_p, logs_p, x_mask = self.enc_p(phone, None, phone_lengths)
|
| 860 |
+
z_p = (m_p + torch.exp(logs_p) * torch.randn_like(m_p) * 0.66666) * x_mask
|
| 861 |
+
if rate:
|
| 862 |
+
head = int(z_p.shape[2] * rate)
|
| 863 |
+
z_p = z_p[:, :, -head:]
|
| 864 |
+
x_mask = x_mask[:, :, -head:]
|
| 865 |
+
z = self.flow(z_p, x_mask, g=g, reverse=True)
|
| 866 |
+
o = self.dec(z * x_mask, g=g)
|
| 867 |
+
return o, x_mask, (z, z_p, m_p, logs_p)
|
| 868 |
+
|
| 869 |
+
|
| 870 |
+
class SynthesizerTrnMs768NSFsid_nono(nn.Module):
|
| 871 |
+
def __init__(
|
| 872 |
+
self,
|
| 873 |
+
spec_channels,
|
| 874 |
+
segment_size,
|
| 875 |
+
inter_channels,
|
| 876 |
+
hidden_channels,
|
| 877 |
+
filter_channels,
|
| 878 |
+
n_heads,
|
| 879 |
+
n_layers,
|
| 880 |
+
kernel_size,
|
| 881 |
+
p_dropout,
|
| 882 |
+
resblock,
|
| 883 |
+
resblock_kernel_sizes,
|
| 884 |
+
resblock_dilation_sizes,
|
| 885 |
+
upsample_rates,
|
| 886 |
+
upsample_initial_channel,
|
| 887 |
+
upsample_kernel_sizes,
|
| 888 |
+
spk_embed_dim,
|
| 889 |
+
gin_channels,
|
| 890 |
+
sr=None,
|
| 891 |
+
**kwargs
|
| 892 |
+
):
|
| 893 |
+
super().__init__()
|
| 894 |
+
self.spec_channels = spec_channels
|
| 895 |
+
self.inter_channels = inter_channels
|
| 896 |
+
self.hidden_channels = hidden_channels
|
| 897 |
+
self.filter_channels = filter_channels
|
| 898 |
+
self.n_heads = n_heads
|
| 899 |
+
self.n_layers = n_layers
|
| 900 |
+
self.kernel_size = kernel_size
|
| 901 |
+
self.p_dropout = p_dropout
|
| 902 |
+
self.resblock = resblock
|
| 903 |
+
self.resblock_kernel_sizes = resblock_kernel_sizes
|
| 904 |
+
self.resblock_dilation_sizes = resblock_dilation_sizes
|
| 905 |
+
self.upsample_rates = upsample_rates
|
| 906 |
+
self.upsample_initial_channel = upsample_initial_channel
|
| 907 |
+
self.upsample_kernel_sizes = upsample_kernel_sizes
|
| 908 |
+
self.segment_size = segment_size
|
| 909 |
+
self.gin_channels = gin_channels
|
| 910 |
+
# self.hop_length = hop_length#
|
| 911 |
+
self.spk_embed_dim = spk_embed_dim
|
| 912 |
+
self.enc_p = TextEncoder768(
|
| 913 |
+
inter_channels,
|
| 914 |
+
hidden_channels,
|
| 915 |
+
filter_channels,
|
| 916 |
+
n_heads,
|
| 917 |
+
n_layers,
|
| 918 |
+
kernel_size,
|
| 919 |
+
p_dropout,
|
| 920 |
+
f0=False,
|
| 921 |
+
)
|
| 922 |
+
self.dec = Generator(
|
| 923 |
+
inter_channels,
|
| 924 |
+
resblock,
|
| 925 |
+
resblock_kernel_sizes,
|
| 926 |
+
resblock_dilation_sizes,
|
| 927 |
+
upsample_rates,
|
| 928 |
+
upsample_initial_channel,
|
| 929 |
+
upsample_kernel_sizes,
|
| 930 |
+
gin_channels=gin_channels,
|
| 931 |
+
)
|
| 932 |
+
self.enc_q = PosteriorEncoder(
|
| 933 |
+
spec_channels,
|
| 934 |
+
inter_channels,
|
| 935 |
+
hidden_channels,
|
| 936 |
+
5,
|
| 937 |
+
1,
|
| 938 |
+
16,
|
| 939 |
+
gin_channels=gin_channels,
|
| 940 |
+
)
|
| 941 |
+
self.flow = ResidualCouplingBlock(
|
| 942 |
+
inter_channels, hidden_channels, 5, 1, 3, gin_channels=gin_channels
|
| 943 |
+
)
|
| 944 |
+
self.emb_g = nn.Embedding(self.spk_embed_dim, gin_channels)
|
| 945 |
+
print("gin_channels:", gin_channels, "self.spk_embed_dim:", self.spk_embed_dim)
|
| 946 |
+
|
| 947 |
+
def remove_weight_norm(self):
|
| 948 |
+
self.dec.remove_weight_norm()
|
| 949 |
+
self.flow.remove_weight_norm()
|
| 950 |
+
self.enc_q.remove_weight_norm()
|
| 951 |
+
|
| 952 |
+
def forward(self, phone, phone_lengths, y, y_lengths, ds): # 这里ds是id,[bs,1]
|
| 953 |
+
g = self.emb_g(ds).unsqueeze(-1) # [b, 256, 1]##1是t,广播的
|
| 954 |
+
m_p, logs_p, x_mask = self.enc_p(phone, None, phone_lengths)
|
| 955 |
+
z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g)
|
| 956 |
+
z_p = self.flow(z, y_mask, g=g)
|
| 957 |
+
z_slice, ids_slice = commons.rand_slice_segments(
|
| 958 |
+
z, y_lengths, self.segment_size
|
| 959 |
+
)
|
| 960 |
+
o = self.dec(z_slice, g=g)
|
| 961 |
+
return o, ids_slice, x_mask, y_mask, (z, z_p, m_p, logs_p, m_q, logs_q)
|
| 962 |
+
|
| 963 |
+
def infer(self, phone, phone_lengths, sid, rate=None):
|
| 964 |
+
g = self.emb_g(sid).unsqueeze(-1)
|
| 965 |
+
m_p, logs_p, x_mask = self.enc_p(phone, None, phone_lengths)
|
| 966 |
+
z_p = (m_p + torch.exp(logs_p) * torch.randn_like(m_p) * 0.66666) * x_mask
|
| 967 |
+
if rate:
|
| 968 |
+
head = int(z_p.shape[2] * rate)
|
| 969 |
+
z_p = z_p[:, :, -head:]
|
| 970 |
+
x_mask = x_mask[:, :, -head:]
|
| 971 |
+
z = self.flow(z_p, x_mask, g=g, reverse=True)
|
| 972 |
+
o = self.dec(z * x_mask, g=g)
|
| 973 |
+
return o, x_mask, (z, z_p, m_p, logs_p)
|
| 974 |
+
|
| 975 |
+
|
| 976 |
+
class MultiPeriodDiscriminator(torch.nn.Module):
|
| 977 |
+
def __init__(self, use_spectral_norm=False):
|
| 978 |
+
super(MultiPeriodDiscriminator, self).__init__()
|
| 979 |
+
periods = [2, 3, 5, 7, 11, 17]
|
| 980 |
+
# periods = [3, 5, 7, 11, 17, 23, 37]
|
| 981 |
+
|
| 982 |
+
discs = [DiscriminatorS(use_spectral_norm=use_spectral_norm)]
|
| 983 |
+
discs = discs + [
|
| 984 |
+
DiscriminatorP(i, use_spectral_norm=use_spectral_norm) for i in periods
|
| 985 |
+
]
|
| 986 |
+
self.discriminators = nn.ModuleList(discs)
|
| 987 |
+
|
| 988 |
+
def forward(self, y, y_hat):
|
| 989 |
+
y_d_rs = [] #
|
| 990 |
+
y_d_gs = []
|
| 991 |
+
fmap_rs = []
|
| 992 |
+
fmap_gs = []
|
| 993 |
+
for i, d in enumerate(self.discriminators):
|
| 994 |
+
y_d_r, fmap_r = d(y)
|
| 995 |
+
y_d_g, fmap_g = d(y_hat)
|
| 996 |
+
# for j in range(len(fmap_r)):
|
| 997 |
+
# print(i,j,y.shape,y_hat.shape,fmap_r[j].shape,fmap_g[j].shape)
|
| 998 |
+
y_d_rs.append(y_d_r)
|
| 999 |
+
y_d_gs.append(y_d_g)
|
| 1000 |
+
fmap_rs.append(fmap_r)
|
| 1001 |
+
fmap_gs.append(fmap_g)
|
| 1002 |
+
|
| 1003 |
+
return y_d_rs, y_d_gs, fmap_rs, fmap_gs
|
| 1004 |
+
|
| 1005 |
+
|
| 1006 |
+
class MultiPeriodDiscriminatorV2(torch.nn.Module):
|
| 1007 |
+
def __init__(self, use_spectral_norm=False):
|
| 1008 |
+
super(MultiPeriodDiscriminatorV2, self).__init__()
|
| 1009 |
+
# periods = [2, 3, 5, 7, 11, 17]
|
| 1010 |
+
periods = [2, 3, 5, 7, 11, 17, 23, 37]
|
| 1011 |
+
|
| 1012 |
+
discs = [DiscriminatorS(use_spectral_norm=use_spectral_norm)]
|
| 1013 |
+
discs = discs + [
|
| 1014 |
+
DiscriminatorP(i, use_spectral_norm=use_spectral_norm) for i in periods
|
| 1015 |
+
]
|
| 1016 |
+
self.discriminators = nn.ModuleList(discs)
|
| 1017 |
+
|
| 1018 |
+
def forward(self, y, y_hat):
|
| 1019 |
+
y_d_rs = [] #
|
| 1020 |
+
y_d_gs = []
|
| 1021 |
+
fmap_rs = []
|
| 1022 |
+
fmap_gs = []
|
| 1023 |
+
for i, d in enumerate(self.discriminators):
|
| 1024 |
+
y_d_r, fmap_r = d(y)
|
| 1025 |
+
y_d_g, fmap_g = d(y_hat)
|
| 1026 |
+
# for j in range(len(fmap_r)):
|
| 1027 |
+
# print(i,j,y.shape,y_hat.shape,fmap_r[j].shape,fmap_g[j].shape)
|
| 1028 |
+
y_d_rs.append(y_d_r)
|
| 1029 |
+
y_d_gs.append(y_d_g)
|
| 1030 |
+
fmap_rs.append(fmap_r)
|
| 1031 |
+
fmap_gs.append(fmap_g)
|
| 1032 |
+
|
| 1033 |
+
return y_d_rs, y_d_gs, fmap_rs, fmap_gs
|
| 1034 |
+
|
| 1035 |
+
|
| 1036 |
+
class DiscriminatorS(torch.nn.Module):
|
| 1037 |
+
def __init__(self, use_spectral_norm=False):
|
| 1038 |
+
super(DiscriminatorS, self).__init__()
|
| 1039 |
+
norm_f = weight_norm if use_spectral_norm == False else spectral_norm
|
| 1040 |
+
self.convs = nn.ModuleList(
|
| 1041 |
+
[
|
| 1042 |
+
norm_f(Conv1d(1, 16, 15, 1, padding=7)),
|
| 1043 |
+
norm_f(Conv1d(16, 64, 41, 4, groups=4, padding=20)),
|
| 1044 |
+
norm_f(Conv1d(64, 256, 41, 4, groups=16, padding=20)),
|
| 1045 |
+
norm_f(Conv1d(256, 1024, 41, 4, groups=64, padding=20)),
|
| 1046 |
+
norm_f(Conv1d(1024, 1024, 41, 4, groups=256, padding=20)),
|
| 1047 |
+
norm_f(Conv1d(1024, 1024, 5, 1, padding=2)),
|
| 1048 |
+
]
|
| 1049 |
+
)
|
| 1050 |
+
self.conv_post = norm_f(Conv1d(1024, 1, 3, 1, padding=1))
|
| 1051 |
+
|
| 1052 |
+
def forward(self, x):
|
| 1053 |
+
fmap = []
|
| 1054 |
+
|
| 1055 |
+
for l in self.convs:
|
| 1056 |
+
x = l(x)
|
| 1057 |
+
x = F.leaky_relu(x, modules.LRELU_SLOPE)
|
| 1058 |
+
fmap.append(x)
|
| 1059 |
+
x = self.conv_post(x)
|
| 1060 |
+
fmap.append(x)
|
| 1061 |
+
x = torch.flatten(x, 1, -1)
|
| 1062 |
+
|
| 1063 |
+
return x, fmap
|
| 1064 |
+
|
| 1065 |
+
|
| 1066 |
+
class DiscriminatorP(torch.nn.Module):
|
| 1067 |
+
def __init__(self, period, kernel_size=5, stride=3, use_spectral_norm=False):
|
| 1068 |
+
super(DiscriminatorP, self).__init__()
|
| 1069 |
+
self.period = period
|
| 1070 |
+
self.use_spectral_norm = use_spectral_norm
|
| 1071 |
+
norm_f = weight_norm if use_spectral_norm == False else spectral_norm
|
| 1072 |
+
self.convs = nn.ModuleList(
|
| 1073 |
+
[
|
| 1074 |
+
norm_f(
|
| 1075 |
+
Conv2d(
|
| 1076 |
+
1,
|
| 1077 |
+
32,
|
| 1078 |
+
(kernel_size, 1),
|
| 1079 |
+
(stride, 1),
|
| 1080 |
+
padding=(get_padding(kernel_size, 1), 0),
|
| 1081 |
+
)
|
| 1082 |
+
),
|
| 1083 |
+
norm_f(
|
| 1084 |
+
Conv2d(
|
| 1085 |
+
32,
|
| 1086 |
+
128,
|
| 1087 |
+
(kernel_size, 1),
|
| 1088 |
+
(stride, 1),
|
| 1089 |
+
padding=(get_padding(kernel_size, 1), 0),
|
| 1090 |
+
)
|
| 1091 |
+
),
|
| 1092 |
+
norm_f(
|
| 1093 |
+
Conv2d(
|
| 1094 |
+
128,
|
| 1095 |
+
512,
|
| 1096 |
+
(kernel_size, 1),
|
| 1097 |
+
(stride, 1),
|
| 1098 |
+
padding=(get_padding(kernel_size, 1), 0),
|
| 1099 |
+
)
|
| 1100 |
+
),
|
| 1101 |
+
norm_f(
|
| 1102 |
+
Conv2d(
|
| 1103 |
+
512,
|
| 1104 |
+
1024,
|
| 1105 |
+
(kernel_size, 1),
|
| 1106 |
+
(stride, 1),
|
| 1107 |
+
padding=(get_padding(kernel_size, 1), 0),
|
| 1108 |
+
)
|
| 1109 |
+
),
|
| 1110 |
+
norm_f(
|
| 1111 |
+
Conv2d(
|
| 1112 |
+
1024,
|
| 1113 |
+
1024,
|
| 1114 |
+
(kernel_size, 1),
|
| 1115 |
+
1,
|
| 1116 |
+
padding=(get_padding(kernel_size, 1), 0),
|
| 1117 |
+
)
|
| 1118 |
+
),
|
| 1119 |
+
]
|
| 1120 |
+
)
|
| 1121 |
+
self.conv_post = norm_f(Conv2d(1024, 1, (3, 1), 1, padding=(1, 0)))
|
| 1122 |
+
|
| 1123 |
+
def forward(self, x):
|
| 1124 |
+
fmap = []
|
| 1125 |
+
|
| 1126 |
+
# 1d to 2d
|
| 1127 |
+
b, c, t = x.shape
|
| 1128 |
+
if t % self.period != 0: # pad first
|
| 1129 |
+
n_pad = self.period - (t % self.period)
|
| 1130 |
+
x = F.pad(x, (0, n_pad), "reflect")
|
| 1131 |
+
t = t + n_pad
|
| 1132 |
+
x = x.view(b, c, t // self.period, self.period)
|
| 1133 |
+
|
| 1134 |
+
for l in self.convs:
|
| 1135 |
+
x = l(x)
|
| 1136 |
+
x = F.leaky_relu(x, modules.LRELU_SLOPE)
|
| 1137 |
+
fmap.append(x)
|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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math, pdb, os
|
| 2 |
+
from time import time as ttime
|
| 3 |
+
import torch
|
| 4 |
+
from torch import nn
|
| 5 |
+
from torch.nn import functional as F
|
| 6 |
+
from lib.infer_pack import modules
|
| 7 |
+
from lib.infer_pack import attentions
|
| 8 |
+
from lib.infer_pack import commons
|
| 9 |
+
from lib.infer_pack.commons import init_weights, get_padding
|
| 10 |
+
from torch.nn import Conv1d, ConvTranspose1d, AvgPool1d, Conv2d
|
| 11 |
+
from torch.nn.utils import weight_norm, remove_weight_norm, spectral_norm
|
| 12 |
+
from lib.infer_pack.commons import init_weights
|
| 13 |
+
import numpy as np
|
| 14 |
+
from lib.infer_pack import commons
|
| 15 |
+
|
| 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 |
+
return uv.float()
|
| 319 |
+
|
| 320 |
+
def forward(self, f0, upp):
|
| 321 |
+
"""sine_tensor, uv = forward(f0)
|
| 322 |
+
input F0: tensor(batchsize=1, length, dim=1)
|
| 323 |
+
f0 for unvoiced steps should be 0
|
| 324 |
+
output sine_tensor: tensor(batchsize=1, length, dim)
|
| 325 |
+
output uv: tensor(batchsize=1, length, 1)
|
| 326 |
+
"""
|
| 327 |
+
with torch.no_grad():
|
| 328 |
+
f0 = f0[:, None].transpose(1, 2)
|
| 329 |
+
f0_buf = torch.zeros(f0.shape[0], f0.shape[1], self.dim, device=f0.device)
|
| 330 |
+
# fundamental component
|
| 331 |
+
f0_buf[:, :, 0] = f0[:, :, 0]
|
| 332 |
+
for idx in np.arange(self.harmonic_num):
|
| 333 |
+
f0_buf[:, :, idx + 1] = f0_buf[:, :, 0] * (
|
| 334 |
+
idx + 2
|
| 335 |
+
) # idx + 2: the (idx+1)-th overtone, (idx+2)-th harmonic
|
| 336 |
+
rad_values = (f0_buf / self.sampling_rate) % 1 ###%1意味着n_har的乘积无法后处理优化
|
| 337 |
+
rand_ini = torch.rand(
|
| 338 |
+
f0_buf.shape[0], f0_buf.shape[2], device=f0_buf.device
|
| 339 |
+
)
|
| 340 |
+
rand_ini[:, 0] = 0
|
| 341 |
+
rad_values[:, 0, :] = rad_values[:, 0, :] + rand_ini
|
| 342 |
+
tmp_over_one = torch.cumsum(rad_values, 1) # % 1 #####%1意味着后面的cumsum无法再优化
|
| 343 |
+
tmp_over_one *= upp
|
| 344 |
+
tmp_over_one = F.interpolate(
|
| 345 |
+
tmp_over_one.transpose(2, 1),
|
| 346 |
+
scale_factor=upp,
|
| 347 |
+
mode="linear",
|
| 348 |
+
align_corners=True,
|
| 349 |
+
).transpose(2, 1)
|
| 350 |
+
rad_values = F.interpolate(
|
| 351 |
+
rad_values.transpose(2, 1), scale_factor=upp, mode="nearest"
|
| 352 |
+
).transpose(
|
| 353 |
+
2, 1
|
| 354 |
+
) #######
|
| 355 |
+
tmp_over_one %= 1
|
| 356 |
+
tmp_over_one_idx = (tmp_over_one[:, 1:, :] - tmp_over_one[:, :-1, :]) < 0
|
| 357 |
+
cumsum_shift = torch.zeros_like(rad_values)
|
| 358 |
+
cumsum_shift[:, 1:, :] = tmp_over_one_idx * -1.0
|
| 359 |
+
sine_waves = torch.sin(
|
| 360 |
+
torch.cumsum(rad_values + cumsum_shift, dim=1) * 2 * np.pi
|
| 361 |
+
)
|
| 362 |
+
sine_waves = sine_waves * self.sine_amp
|
| 363 |
+
uv = self._f02uv(f0)
|
| 364 |
+
uv = F.interpolate(
|
| 365 |
+
uv.transpose(2, 1), scale_factor=upp, mode="nearest"
|
| 366 |
+
).transpose(2, 1)
|
| 367 |
+
noise_amp = uv * self.noise_std + (1 - uv) * self.sine_amp / 3
|
| 368 |
+
noise = noise_amp * torch.randn_like(sine_waves)
|
| 369 |
+
sine_waves = sine_waves * uv + noise
|
| 370 |
+
return sine_waves, uv, noise
|
| 371 |
+
|
| 372 |
+
|
| 373 |
+
class SourceModuleHnNSF(torch.nn.Module):
|
| 374 |
+
"""SourceModule for hn-nsf
|
| 375 |
+
SourceModule(sampling_rate, harmonic_num=0, sine_amp=0.1,
|
| 376 |
+
add_noise_std=0.003, voiced_threshod=0)
|
| 377 |
+
sampling_rate: sampling_rate in Hz
|
| 378 |
+
harmonic_num: number of harmonic above F0 (default: 0)
|
| 379 |
+
sine_amp: amplitude of sine source signal (default: 0.1)
|
| 380 |
+
add_noise_std: std of additive Gaussian noise (default: 0.003)
|
| 381 |
+
note that amplitude of noise in unvoiced is decided
|
| 382 |
+
by sine_amp
|
| 383 |
+
voiced_threshold: threhold to set U/V given F0 (default: 0)
|
| 384 |
+
Sine_source, noise_source = SourceModuleHnNSF(F0_sampled)
|
| 385 |
+
F0_sampled (batchsize, length, 1)
|
| 386 |
+
Sine_source (batchsize, length, 1)
|
| 387 |
+
noise_source (batchsize, length 1)
|
| 388 |
+
uv (batchsize, length, 1)
|
| 389 |
+
"""
|
| 390 |
+
|
| 391 |
+
def __init__(
|
| 392 |
+
self,
|
| 393 |
+
sampling_rate,
|
| 394 |
+
harmonic_num=0,
|
| 395 |
+
sine_amp=0.1,
|
| 396 |
+
add_noise_std=0.003,
|
| 397 |
+
voiced_threshod=0,
|
| 398 |
+
is_half=True,
|
| 399 |
+
):
|
| 400 |
+
super(SourceModuleHnNSF, self).__init__()
|
| 401 |
+
|
| 402 |
+
self.sine_amp = sine_amp
|
| 403 |
+
self.noise_std = add_noise_std
|
| 404 |
+
self.is_half = is_half
|
| 405 |
+
# to produce sine waveforms
|
| 406 |
+
self.l_sin_gen = SineGen(
|
| 407 |
+
sampling_rate, harmonic_num, sine_amp, add_noise_std, voiced_threshod
|
| 408 |
+
)
|
| 409 |
+
|
| 410 |
+
# to merge source harmonics into a single excitation
|
| 411 |
+
self.l_linear = torch.nn.Linear(harmonic_num + 1, 1)
|
| 412 |
+
self.l_tanh = torch.nn.Tanh()
|
| 413 |
+
|
| 414 |
+
def forward(self, x, upp=None):
|
| 415 |
+
sine_wavs, uv, _ = self.l_sin_gen(x, upp)
|
| 416 |
+
if self.is_half:
|
| 417 |
+
sine_wavs = sine_wavs.half()
|
| 418 |
+
sine_merge = self.l_tanh(self.l_linear(sine_wavs))
|
| 419 |
+
return sine_merge, None, None # noise, uv
|
| 420 |
+
|
| 421 |
+
|
| 422 |
+
class GeneratorNSF(torch.nn.Module):
|
| 423 |
+
def __init__(
|
| 424 |
+
self,
|
| 425 |
+
initial_channel,
|
| 426 |
+
resblock,
|
| 427 |
+
resblock_kernel_sizes,
|
| 428 |
+
resblock_dilation_sizes,
|
| 429 |
+
upsample_rates,
|
| 430 |
+
upsample_initial_channel,
|
| 431 |
+
upsample_kernel_sizes,
|
| 432 |
+
gin_channels,
|
| 433 |
+
sr,
|
| 434 |
+
is_half=False,
|
| 435 |
+
):
|
| 436 |
+
super(GeneratorNSF, self).__init__()
|
| 437 |
+
self.num_kernels = len(resblock_kernel_sizes)
|
| 438 |
+
self.num_upsamples = len(upsample_rates)
|
| 439 |
+
|
| 440 |
+
self.f0_upsamp = torch.nn.Upsample(scale_factor=np.prod(upsample_rates))
|
| 441 |
+
self.m_source = SourceModuleHnNSF(
|
| 442 |
+
sampling_rate=sr, harmonic_num=0, is_half=is_half
|
| 443 |
+
)
|
| 444 |
+
self.noise_convs = nn.ModuleList()
|
| 445 |
+
self.conv_pre = Conv1d(
|
| 446 |
+
initial_channel, upsample_initial_channel, 7, 1, padding=3
|
| 447 |
+
)
|
| 448 |
+
resblock = modules.ResBlock1 if resblock == "1" else modules.ResBlock2
|
| 449 |
+
|
| 450 |
+
self.ups = nn.ModuleList()
|
| 451 |
+
for i, (u, k) in enumerate(zip(upsample_rates, upsample_kernel_sizes)):
|
| 452 |
+
c_cur = upsample_initial_channel // (2 ** (i + 1))
|
| 453 |
+
self.ups.append(
|
| 454 |
+
weight_norm(
|
| 455 |
+
ConvTranspose1d(
|
| 456 |
+
upsample_initial_channel // (2**i),
|
| 457 |
+
upsample_initial_channel // (2 ** (i + 1)),
|
| 458 |
+
k,
|
| 459 |
+
u,
|
| 460 |
+
padding=(k - u) // 2,
|
| 461 |
+
)
|
| 462 |
+
)
|
| 463 |
+
)
|
| 464 |
+
if i + 1 < len(upsample_rates):
|
| 465 |
+
stride_f0 = np.prod(upsample_rates[i + 1 :])
|
| 466 |
+
self.noise_convs.append(
|
| 467 |
+
Conv1d(
|
| 468 |
+
1,
|
| 469 |
+
c_cur,
|
| 470 |
+
kernel_size=stride_f0 * 2,
|
| 471 |
+
stride=stride_f0,
|
| 472 |
+
padding=stride_f0 // 2,
|
| 473 |
+
)
|
| 474 |
+
)
|
| 475 |
+
else:
|
| 476 |
+
self.noise_convs.append(Conv1d(1, c_cur, kernel_size=1))
|
| 477 |
+
|
| 478 |
+
self.resblocks = nn.ModuleList()
|
| 479 |
+
for i in range(len(self.ups)):
|
| 480 |
+
ch = upsample_initial_channel // (2 ** (i + 1))
|
| 481 |
+
for j, (k, d) in enumerate(
|
| 482 |
+
zip(resblock_kernel_sizes, resblock_dilation_sizes)
|
| 483 |
+
):
|
| 484 |
+
self.resblocks.append(resblock(ch, k, d))
|
| 485 |
+
|
| 486 |
+
self.conv_post = Conv1d(ch, 1, 7, 1, padding=3, bias=False)
|
| 487 |
+
self.ups.apply(init_weights)
|
| 488 |
+
|
| 489 |
+
if gin_channels != 0:
|
| 490 |
+
self.cond = nn.Conv1d(gin_channels, upsample_initial_channel, 1)
|
| 491 |
+
|
| 492 |
+
self.upp = np.prod(upsample_rates)
|
| 493 |
+
|
| 494 |
+
def forward(self, x, f0, g=None):
|
| 495 |
+
har_source, noi_source, uv = self.m_source(f0, self.upp)
|
| 496 |
+
har_source = har_source.transpose(1, 2)
|
| 497 |
+
x = self.conv_pre(x)
|
| 498 |
+
if g is not None:
|
| 499 |
+
x = x + self.cond(g)
|
| 500 |
+
|
| 501 |
+
for i in range(self.num_upsamples):
|
| 502 |
+
x = F.leaky_relu(x, modules.LRELU_SLOPE)
|
| 503 |
+
x = self.ups[i](x)
|
| 504 |
+
x_source = self.noise_convs[i](har_source)
|
| 505 |
+
x = x + x_source
|
| 506 |
+
xs = None
|
| 507 |
+
for j in range(self.num_kernels):
|
| 508 |
+
if xs is None:
|
| 509 |
+
xs = self.resblocks[i * self.num_kernels + j](x)
|
| 510 |
+
else:
|
| 511 |
+
xs += self.resblocks[i * self.num_kernels + j](x)
|
| 512 |
+
x = xs / self.num_kernels
|
| 513 |
+
x = F.leaky_relu(x)
|
| 514 |
+
x = self.conv_post(x)
|
| 515 |
+
x = torch.tanh(x)
|
| 516 |
+
return x
|
| 517 |
+
|
| 518 |
+
def remove_weight_norm(self):
|
| 519 |
+
for l in self.ups:
|
| 520 |
+
remove_weight_norm(l)
|
| 521 |
+
for l in self.resblocks:
|
| 522 |
+
l.remove_weight_norm()
|
| 523 |
+
|
| 524 |
+
|
| 525 |
+
sr2sr = {
|
| 526 |
+
"32k": 32000,
|
| 527 |
+
"40k": 40000,
|
| 528 |
+
"48k": 48000,
|
| 529 |
+
}
|
| 530 |
+
|
| 531 |
+
|
| 532 |
+
class SynthesizerTrnMs256NSFsid(nn.Module):
|
| 533 |
+
def __init__(
|
| 534 |
+
self,
|
| 535 |
+
spec_channels,
|
| 536 |
+
segment_size,
|
| 537 |
+
inter_channels,
|
| 538 |
+
hidden_channels,
|
| 539 |
+
filter_channels,
|
| 540 |
+
n_heads,
|
| 541 |
+
n_layers,
|
| 542 |
+
kernel_size,
|
| 543 |
+
p_dropout,
|
| 544 |
+
resblock,
|
| 545 |
+
resblock_kernel_sizes,
|
| 546 |
+
resblock_dilation_sizes,
|
| 547 |
+
upsample_rates,
|
| 548 |
+
upsample_initial_channel,
|
| 549 |
+
upsample_kernel_sizes,
|
| 550 |
+
spk_embed_dim,
|
| 551 |
+
gin_channels,
|
| 552 |
+
sr,
|
| 553 |
+
**kwargs
|
| 554 |
+
):
|
| 555 |
+
super().__init__()
|
| 556 |
+
if type(sr) == type("strr"):
|
| 557 |
+
sr = sr2sr[sr]
|
| 558 |
+
self.spec_channels = spec_channels
|
| 559 |
+
self.inter_channels = inter_channels
|
| 560 |
+
self.hidden_channels = hidden_channels
|
| 561 |
+
self.filter_channels = filter_channels
|
| 562 |
+
self.n_heads = n_heads
|
| 563 |
+
self.n_layers = n_layers
|
| 564 |
+
self.kernel_size = kernel_size
|
| 565 |
+
self.p_dropout = p_dropout
|
| 566 |
+
self.resblock = resblock
|
| 567 |
+
self.resblock_kernel_sizes = resblock_kernel_sizes
|
| 568 |
+
self.resblock_dilation_sizes = resblock_dilation_sizes
|
| 569 |
+
self.upsample_rates = upsample_rates
|
| 570 |
+
self.upsample_initial_channel = upsample_initial_channel
|
| 571 |
+
self.upsample_kernel_sizes = upsample_kernel_sizes
|
| 572 |
+
self.segment_size = segment_size
|
| 573 |
+
self.gin_channels = gin_channels
|
| 574 |
+
# self.hop_length = hop_length#
|
| 575 |
+
self.spk_embed_dim = spk_embed_dim
|
| 576 |
+
self.enc_p = TextEncoder256(
|
| 577 |
+
inter_channels,
|
| 578 |
+
hidden_channels,
|
| 579 |
+
filter_channels,
|
| 580 |
+
n_heads,
|
| 581 |
+
n_layers,
|
| 582 |
+
kernel_size,
|
| 583 |
+
p_dropout,
|
| 584 |
+
)
|
| 585 |
+
self.dec = GeneratorNSF(
|
| 586 |
+
inter_channels,
|
| 587 |
+
resblock,
|
| 588 |
+
resblock_kernel_sizes,
|
| 589 |
+
resblock_dilation_sizes,
|
| 590 |
+
upsample_rates,
|
| 591 |
+
upsample_initial_channel,
|
| 592 |
+
upsample_kernel_sizes,
|
| 593 |
+
gin_channels=gin_channels,
|
| 594 |
+
sr=sr,
|
| 595 |
+
is_half=kwargs["is_half"],
|
| 596 |
+
)
|
| 597 |
+
self.enc_q = PosteriorEncoder(
|
| 598 |
+
spec_channels,
|
| 599 |
+
inter_channels,
|
| 600 |
+
hidden_channels,
|
| 601 |
+
5,
|
| 602 |
+
1,
|
| 603 |
+
16,
|
| 604 |
+
gin_channels=gin_channels,
|
| 605 |
+
)
|
| 606 |
+
self.flow = ResidualCouplingBlock(
|
| 607 |
+
inter_channels, hidden_channels, 5, 1, 3, gin_channels=gin_channels
|
| 608 |
+
)
|
| 609 |
+
self.emb_g = nn.Embedding(self.spk_embed_dim, gin_channels)
|
| 610 |
+
print("gin_channels:", gin_channels, "self.spk_embed_dim:", self.spk_embed_dim)
|
| 611 |
+
|
| 612 |
+
def remove_weight_norm(self):
|
| 613 |
+
self.dec.remove_weight_norm()
|
| 614 |
+
self.flow.remove_weight_norm()
|
| 615 |
+
self.enc_q.remove_weight_norm()
|
| 616 |
+
|
| 617 |
+
def forward(
|
| 618 |
+
self, phone, phone_lengths, pitch, pitchf, y, y_lengths, ds
|
| 619 |
+
): # 这里ds是id,[bs,1]
|
| 620 |
+
# print(1,pitch.shape)#[bs,t]
|
| 621 |
+
g = self.emb_g(ds).unsqueeze(-1) # [b, 256, 1]##1是t,广播的
|
| 622 |
+
m_p, logs_p, x_mask = self.enc_p(phone, pitch, phone_lengths)
|
| 623 |
+
z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g)
|
| 624 |
+
z_p = self.flow(z, y_mask, g=g)
|
| 625 |
+
z_slice, ids_slice = commons.rand_slice_segments(
|
| 626 |
+
z, y_lengths, self.segment_size
|
| 627 |
+
)
|
| 628 |
+
# print(-1,pitchf.shape,ids_slice,self.segment_size,self.hop_length,self.segment_size//self.hop_length)
|
| 629 |
+
pitchf = commons.slice_segments2(pitchf, ids_slice, self.segment_size)
|
| 630 |
+
# print(-2,pitchf.shape,z_slice.shape)
|
| 631 |
+
o = self.dec(z_slice, pitchf, g=g)
|
| 632 |
+
return o, ids_slice, x_mask, y_mask, (z, z_p, m_p, logs_p, m_q, logs_q)
|
| 633 |
+
|
| 634 |
+
def infer(self, phone, phone_lengths, pitch, nsff0, sid, max_len=None):
|
| 635 |
+
g = self.emb_g(sid).unsqueeze(-1)
|
| 636 |
+
m_p, logs_p, x_mask = self.enc_p(phone, pitch, phone_lengths)
|
| 637 |
+
z_p = (m_p + torch.exp(logs_p) * torch.randn_like(m_p) * 0.66666) * x_mask
|
| 638 |
+
z = self.flow(z_p, x_mask, g=g, reverse=True)
|
| 639 |
+
o = self.dec((z * x_mask)[:, :, :max_len], nsff0, g=g)
|
| 640 |
+
return o, x_mask, (z, z_p, m_p, logs_p)
|
| 641 |
+
|
| 642 |
+
|
| 643 |
+
class SynthesizerTrnMs768NSFsid(nn.Module):
|
| 644 |
+
def __init__(
|
| 645 |
+
self,
|
| 646 |
+
spec_channels,
|
| 647 |
+
segment_size,
|
| 648 |
+
inter_channels,
|
| 649 |
+
hidden_channels,
|
| 650 |
+
filter_channels,
|
| 651 |
+
n_heads,
|
| 652 |
+
n_layers,
|
| 653 |
+
kernel_size,
|
| 654 |
+
p_dropout,
|
| 655 |
+
resblock,
|
| 656 |
+
resblock_kernel_sizes,
|
| 657 |
+
resblock_dilation_sizes,
|
| 658 |
+
upsample_rates,
|
| 659 |
+
upsample_initial_channel,
|
| 660 |
+
upsample_kernel_sizes,
|
| 661 |
+
spk_embed_dim,
|
| 662 |
+
gin_channels,
|
| 663 |
+
sr,
|
| 664 |
+
**kwargs
|
| 665 |
+
):
|
| 666 |
+
super().__init__()
|
| 667 |
+
if type(sr) == type("strr"):
|
| 668 |
+
sr = sr2sr[sr]
|
| 669 |
+
self.spec_channels = spec_channels
|
| 670 |
+
self.inter_channels = inter_channels
|
| 671 |
+
self.hidden_channels = hidden_channels
|
| 672 |
+
self.filter_channels = filter_channels
|
| 673 |
+
self.n_heads = n_heads
|
| 674 |
+
self.n_layers = n_layers
|
| 675 |
+
self.kernel_size = kernel_size
|
| 676 |
+
self.p_dropout = p_dropout
|
| 677 |
+
self.resblock = resblock
|
| 678 |
+
self.resblock_kernel_sizes = resblock_kernel_sizes
|
| 679 |
+
self.resblock_dilation_sizes = resblock_dilation_sizes
|
| 680 |
+
self.upsample_rates = upsample_rates
|
| 681 |
+
self.upsample_initial_channel = upsample_initial_channel
|
| 682 |
+
self.upsample_kernel_sizes = upsample_kernel_sizes
|
| 683 |
+
self.segment_size = segment_size
|
| 684 |
+
self.gin_channels = gin_channels
|
| 685 |
+
# self.hop_length = hop_length#
|
| 686 |
+
self.spk_embed_dim = spk_embed_dim
|
| 687 |
+
self.enc_p = TextEncoder768(
|
| 688 |
+
inter_channels,
|
| 689 |
+
hidden_channels,
|
| 690 |
+
filter_channels,
|
| 691 |
+
n_heads,
|
| 692 |
+
n_layers,
|
| 693 |
+
kernel_size,
|
| 694 |
+
p_dropout,
|
| 695 |
+
)
|
| 696 |
+
self.dec = GeneratorNSF(
|
| 697 |
+
inter_channels,
|
| 698 |
+
resblock,
|
| 699 |
+
resblock_kernel_sizes,
|
| 700 |
+
resblock_dilation_sizes,
|
| 701 |
+
upsample_rates,
|
| 702 |
+
upsample_initial_channel,
|
| 703 |
+
upsample_kernel_sizes,
|
| 704 |
+
gin_channels=gin_channels,
|
| 705 |
+
sr=sr,
|
| 706 |
+
is_half=kwargs["is_half"],
|
| 707 |
+
)
|
| 708 |
+
self.enc_q = PosteriorEncoder(
|
| 709 |
+
spec_channels,
|
| 710 |
+
inter_channels,
|
| 711 |
+
hidden_channels,
|
| 712 |
+
5,
|
| 713 |
+
1,
|
| 714 |
+
16,
|
| 715 |
+
gin_channels=gin_channels,
|
| 716 |
+
)
|
| 717 |
+
self.flow = ResidualCouplingBlock(
|
| 718 |
+
inter_channels, hidden_channels, 5, 1, 3, gin_channels=gin_channels
|
| 719 |
+
)
|
| 720 |
+
self.emb_g = nn.Embedding(self.spk_embed_dim, gin_channels)
|
| 721 |
+
print("gin_channels:", gin_channels, "self.spk_embed_dim:", self.spk_embed_dim)
|
| 722 |
+
|
| 723 |
+
def remove_weight_norm(self):
|
| 724 |
+
self.dec.remove_weight_norm()
|
| 725 |
+
self.flow.remove_weight_norm()
|
| 726 |
+
self.enc_q.remove_weight_norm()
|
| 727 |
+
|
| 728 |
+
def forward(
|
| 729 |
+
self, phone, phone_lengths, pitch, pitchf, y, y_lengths, ds
|
| 730 |
+
): # 这里ds是id,[bs,1]
|
| 731 |
+
# print(1,pitch.shape)#[bs,t]
|
| 732 |
+
g = self.emb_g(ds).unsqueeze(-1) # [b, 256, 1]##1是t,广播的
|
| 733 |
+
m_p, logs_p, x_mask = self.enc_p(phone, pitch, phone_lengths)
|
| 734 |
+
z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g)
|
| 735 |
+
z_p = self.flow(z, y_mask, g=g)
|
| 736 |
+
z_slice, ids_slice = commons.rand_slice_segments(
|
| 737 |
+
z, y_lengths, self.segment_size
|
| 738 |
+
)
|
| 739 |
+
# print(-1,pitchf.shape,ids_slice,self.segment_size,self.hop_length,self.segment_size//self.hop_length)
|
| 740 |
+
pitchf = commons.slice_segments2(pitchf, ids_slice, self.segment_size)
|
| 741 |
+
# print(-2,pitchf.shape,z_slice.shape)
|
| 742 |
+
o = self.dec(z_slice, pitchf, g=g)
|
| 743 |
+
return o, ids_slice, x_mask, y_mask, (z, z_p, m_p, logs_p, m_q, logs_q)
|
| 744 |
+
|
| 745 |
+
def infer(self, phone, phone_lengths, pitch, nsff0, sid, max_len=None):
|
| 746 |
+
g = self.emb_g(sid).unsqueeze(-1)
|
| 747 |
+
m_p, logs_p, x_mask = self.enc_p(phone, pitch, phone_lengths)
|
| 748 |
+
z_p = (m_p + torch.exp(logs_p) * torch.randn_like(m_p) * 0.66666) * x_mask
|
| 749 |
+
z = self.flow(z_p, x_mask, g=g, reverse=True)
|
| 750 |
+
o = self.dec((z * x_mask)[:, :, :max_len], nsff0, g=g)
|
| 751 |
+
return o, x_mask, (z, z_p, m_p, logs_p)
|
| 752 |
+
|
| 753 |
+
|
| 754 |
+
class SynthesizerTrnMs256NSFsid_nono(nn.Module):
|
| 755 |
+
def __init__(
|
| 756 |
+
self,
|
| 757 |
+
spec_channels,
|
| 758 |
+
segment_size,
|
| 759 |
+
inter_channels,
|
| 760 |
+
hidden_channels,
|
| 761 |
+
filter_channels,
|
| 762 |
+
n_heads,
|
| 763 |
+
n_layers,
|
| 764 |
+
kernel_size,
|
| 765 |
+
p_dropout,
|
| 766 |
+
resblock,
|
| 767 |
+
resblock_kernel_sizes,
|
| 768 |
+
resblock_dilation_sizes,
|
| 769 |
+
upsample_rates,
|
| 770 |
+
upsample_initial_channel,
|
| 771 |
+
upsample_kernel_sizes,
|
| 772 |
+
spk_embed_dim,
|
| 773 |
+
gin_channels,
|
| 774 |
+
sr=None,
|
| 775 |
+
**kwargs
|
| 776 |
+
):
|
| 777 |
+
super().__init__()
|
| 778 |
+
self.spec_channels = spec_channels
|
| 779 |
+
self.inter_channels = inter_channels
|
| 780 |
+
self.hidden_channels = hidden_channels
|
| 781 |
+
self.filter_channels = filter_channels
|
| 782 |
+
self.n_heads = n_heads
|
| 783 |
+
self.n_layers = n_layers
|
| 784 |
+
self.kernel_size = kernel_size
|
| 785 |
+
self.p_dropout = p_dropout
|
| 786 |
+
self.resblock = resblock
|
| 787 |
+
self.resblock_kernel_sizes = resblock_kernel_sizes
|
| 788 |
+
self.resblock_dilation_sizes = resblock_dilation_sizes
|
| 789 |
+
self.upsample_rates = upsample_rates
|
| 790 |
+
self.upsample_initial_channel = upsample_initial_channel
|
| 791 |
+
self.upsample_kernel_sizes = upsample_kernel_sizes
|
| 792 |
+
self.segment_size = segment_size
|
| 793 |
+
self.gin_channels = gin_channels
|
| 794 |
+
# self.hop_length = hop_length#
|
| 795 |
+
self.spk_embed_dim = spk_embed_dim
|
| 796 |
+
self.enc_p = TextEncoder256(
|
| 797 |
+
inter_channels,
|
| 798 |
+
hidden_channels,
|
| 799 |
+
filter_channels,
|
| 800 |
+
n_heads,
|
| 801 |
+
n_layers,
|
| 802 |
+
kernel_size,
|
| 803 |
+
p_dropout,
|
| 804 |
+
f0=False,
|
| 805 |
+
)
|
| 806 |
+
self.dec = Generator(
|
| 807 |
+
inter_channels,
|
| 808 |
+
resblock,
|
| 809 |
+
resblock_kernel_sizes,
|
| 810 |
+
resblock_dilation_sizes,
|
| 811 |
+
upsample_rates,
|
| 812 |
+
upsample_initial_channel,
|
| 813 |
+
upsample_kernel_sizes,
|
| 814 |
+
gin_channels=gin_channels,
|
| 815 |
+
)
|
| 816 |
+
self.enc_q = PosteriorEncoder(
|
| 817 |
+
spec_channels,
|
| 818 |
+
inter_channels,
|
| 819 |
+
hidden_channels,
|
| 820 |
+
5,
|
| 821 |
+
1,
|
| 822 |
+
16,
|
| 823 |
+
gin_channels=gin_channels,
|
| 824 |
+
)
|
| 825 |
+
self.flow = ResidualCouplingBlock(
|
| 826 |
+
inter_channels, hidden_channels, 5, 1, 3, gin_channels=gin_channels
|
| 827 |
+
)
|
| 828 |
+
self.emb_g = nn.Embedding(self.spk_embed_dim, gin_channels)
|
| 829 |
+
print("gin_channels:", gin_channels, "self.spk_embed_dim:", self.spk_embed_dim)
|
| 830 |
+
|
| 831 |
+
def remove_weight_norm(self):
|
| 832 |
+
self.dec.remove_weight_norm()
|
| 833 |
+
self.flow.remove_weight_norm()
|
| 834 |
+
self.enc_q.remove_weight_norm()
|
| 835 |
+
|
| 836 |
+
def forward(self, phone, phone_lengths, y, y_lengths, ds): # 这里ds是id,[bs,1]
|
| 837 |
+
g = self.emb_g(ds).unsqueeze(-1) # [b, 256, 1]##1是t,广播的
|
| 838 |
+
m_p, logs_p, x_mask = self.enc_p(phone, None, phone_lengths)
|
| 839 |
+
z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g)
|
| 840 |
+
z_p = self.flow(z, y_mask, g=g)
|
| 841 |
+
z_slice, ids_slice = commons.rand_slice_segments(
|
| 842 |
+
z, y_lengths, self.segment_size
|
| 843 |
+
)
|
| 844 |
+
o = self.dec(z_slice, g=g)
|
| 845 |
+
return o, ids_slice, x_mask, y_mask, (z, z_p, m_p, logs_p, m_q, logs_q)
|
| 846 |
+
|
| 847 |
+
def infer(self, phone, phone_lengths, sid, max_len=None):
|
| 848 |
+
g = self.emb_g(sid).unsqueeze(-1)
|
| 849 |
+
m_p, logs_p, x_mask = self.enc_p(phone, None, phone_lengths)
|
| 850 |
+
z_p = (m_p + torch.exp(logs_p) * torch.randn_like(m_p) * 0.66666) * x_mask
|
| 851 |
+
z = self.flow(z_p, x_mask, g=g, reverse=True)
|
| 852 |
+
o = self.dec((z * x_mask)[:, :, :max_len], g=g)
|
| 853 |
+
return o, x_mask, (z, z_p, m_p, logs_p)
|
| 854 |
+
|
| 855 |
+
|
| 856 |
+
class SynthesizerTrnMs768NSFsid_nono(nn.Module):
|
| 857 |
+
def __init__(
|
| 858 |
+
self,
|
| 859 |
+
spec_channels,
|
| 860 |
+
segment_size,
|
| 861 |
+
inter_channels,
|
| 862 |
+
hidden_channels,
|
| 863 |
+
filter_channels,
|
| 864 |
+
n_heads,
|
| 865 |
+
n_layers,
|
| 866 |
+
kernel_size,
|
| 867 |
+
p_dropout,
|
| 868 |
+
resblock,
|
| 869 |
+
resblock_kernel_sizes,
|
| 870 |
+
resblock_dilation_sizes,
|
| 871 |
+
upsample_rates,
|
| 872 |
+
upsample_initial_channel,
|
| 873 |
+
upsample_kernel_sizes,
|
| 874 |
+
spk_embed_dim,
|
| 875 |
+
gin_channels,
|
| 876 |
+
sr=None,
|
| 877 |
+
**kwargs
|
| 878 |
+
):
|
| 879 |
+
super().__init__()
|
| 880 |
+
self.spec_channels = spec_channels
|
| 881 |
+
self.inter_channels = inter_channels
|
| 882 |
+
self.hidden_channels = hidden_channels
|
| 883 |
+
self.filter_channels = filter_channels
|
| 884 |
+
self.n_heads = n_heads
|
| 885 |
+
self.n_layers = n_layers
|
| 886 |
+
self.kernel_size = kernel_size
|
| 887 |
+
self.p_dropout = p_dropout
|
| 888 |
+
self.resblock = resblock
|
| 889 |
+
self.resblock_kernel_sizes = resblock_kernel_sizes
|
| 890 |
+
self.resblock_dilation_sizes = resblock_dilation_sizes
|
| 891 |
+
self.upsample_rates = upsample_rates
|
| 892 |
+
self.upsample_initial_channel = upsample_initial_channel
|
| 893 |
+
self.upsample_kernel_sizes = upsample_kernel_sizes
|
| 894 |
+
self.segment_size = segment_size
|
| 895 |
+
self.gin_channels = gin_channels
|
| 896 |
+
# self.hop_length = hop_length#
|
| 897 |
+
self.spk_embed_dim = spk_embed_dim
|
| 898 |
+
self.enc_p = TextEncoder768(
|
| 899 |
+
inter_channels,
|
| 900 |
+
hidden_channels,
|
| 901 |
+
filter_channels,
|
| 902 |
+
n_heads,
|
| 903 |
+
n_layers,
|
| 904 |
+
kernel_size,
|
| 905 |
+
p_dropout,
|
| 906 |
+
f0=False,
|
| 907 |
+
)
|
| 908 |
+
self.dec = Generator(
|
| 909 |
+
inter_channels,
|
| 910 |
+
resblock,
|
| 911 |
+
resblock_kernel_sizes,
|
| 912 |
+
resblock_dilation_sizes,
|
| 913 |
+
upsample_rates,
|
| 914 |
+
upsample_initial_channel,
|
| 915 |
+
upsample_kernel_sizes,
|
| 916 |
+
gin_channels=gin_channels,
|
| 917 |
+
)
|
| 918 |
+
self.enc_q = PosteriorEncoder(
|
| 919 |
+
spec_channels,
|
| 920 |
+
inter_channels,
|
| 921 |
+
hidden_channels,
|
| 922 |
+
5,
|
| 923 |
+
1,
|
| 924 |
+
16,
|
| 925 |
+
gin_channels=gin_channels,
|
| 926 |
+
)
|
| 927 |
+
self.flow = ResidualCouplingBlock(
|
| 928 |
+
inter_channels, hidden_channels, 5, 1, 3, gin_channels=gin_channels
|
| 929 |
+
)
|
| 930 |
+
self.emb_g = nn.Embedding(self.spk_embed_dim, gin_channels)
|
| 931 |
+
print("gin_channels:", gin_channels, "self.spk_embed_dim:", self.spk_embed_dim)
|
| 932 |
+
|
| 933 |
+
def remove_weight_norm(self):
|
| 934 |
+
self.dec.remove_weight_norm()
|
| 935 |
+
self.flow.remove_weight_norm()
|
| 936 |
+
self.enc_q.remove_weight_norm()
|
| 937 |
+
|
| 938 |
+
def forward(self, phone, phone_lengths, y, y_lengths, ds): # 这里ds是id,[bs,1]
|
| 939 |
+
g = self.emb_g(ds).unsqueeze(-1) # [b, 256, 1]##1是t,广播的
|
| 940 |
+
m_p, logs_p, x_mask = self.enc_p(phone, None, phone_lengths)
|
| 941 |
+
z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g)
|
| 942 |
+
z_p = self.flow(z, y_mask, g=g)
|
| 943 |
+
z_slice, ids_slice = commons.rand_slice_segments(
|
| 944 |
+
z, y_lengths, self.segment_size
|
| 945 |
+
)
|
| 946 |
+
o = self.dec(z_slice, g=g)
|
| 947 |
+
return o, ids_slice, x_mask, y_mask, (z, z_p, m_p, logs_p, m_q, logs_q)
|
| 948 |
+
|
| 949 |
+
def infer(self, phone, phone_lengths, sid, max_len=None):
|
| 950 |
+
g = self.emb_g(sid).unsqueeze(-1)
|
| 951 |
+
m_p, logs_p, x_mask = self.enc_p(phone, None, phone_lengths)
|
| 952 |
+
z_p = (m_p + torch.exp(logs_p) * torch.randn_like(m_p) * 0.66666) * x_mask
|
| 953 |
+
z = self.flow(z_p, x_mask, g=g, reverse=True)
|
| 954 |
+
o = self.dec((z * x_mask)[:, :, :max_len], g=g)
|
| 955 |
+
return o, x_mask, (z, z_p, m_p, logs_p)
|
| 956 |
+
|
| 957 |
+
|
| 958 |
+
class MultiPeriodDiscriminator(torch.nn.Module):
|
| 959 |
+
def __init__(self, use_spectral_norm=False):
|
| 960 |
+
super(MultiPeriodDiscriminator, self).__init__()
|
| 961 |
+
periods = [2, 3, 5, 7, 11, 17]
|
| 962 |
+
# periods = [3, 5, 7, 11, 17, 23, 37]
|
| 963 |
+
|
| 964 |
+
discs = [DiscriminatorS(use_spectral_norm=use_spectral_norm)]
|
| 965 |
+
discs = discs + [
|
| 966 |
+
DiscriminatorP(i, use_spectral_norm=use_spectral_norm) for i in periods
|
| 967 |
+
]
|
| 968 |
+
self.discriminators = nn.ModuleList(discs)
|
| 969 |
+
|
| 970 |
+
def forward(self, y, y_hat):
|
| 971 |
+
y_d_rs = [] #
|
| 972 |
+
y_d_gs = []
|
| 973 |
+
fmap_rs = []
|
| 974 |
+
fmap_gs = []
|
| 975 |
+
for i, d in enumerate(self.discriminators):
|
| 976 |
+
y_d_r, fmap_r = d(y)
|
| 977 |
+
y_d_g, fmap_g = d(y_hat)
|
| 978 |
+
# for j in range(len(fmap_r)):
|
| 979 |
+
# print(i,j,y.shape,y_hat.shape,fmap_r[j].shape,fmap_g[j].shape)
|
| 980 |
+
y_d_rs.append(y_d_r)
|
| 981 |
+
y_d_gs.append(y_d_g)
|
| 982 |
+
fmap_rs.append(fmap_r)
|
| 983 |
+
fmap_gs.append(fmap_g)
|
| 984 |
+
|
| 985 |
+
return y_d_rs, y_d_gs, fmap_rs, fmap_gs
|
| 986 |
+
|
| 987 |
+
|
| 988 |
+
class MultiPeriodDiscriminatorV2(torch.nn.Module):
|
| 989 |
+
def __init__(self, use_spectral_norm=False):
|
| 990 |
+
super(MultiPeriodDiscriminatorV2, self).__init__()
|
| 991 |
+
# periods = [2, 3, 5, 7, 11, 17]
|
| 992 |
+
periods = [2, 3, 5, 7, 11, 17, 23, 37]
|
| 993 |
+
|
| 994 |
+
discs = [DiscriminatorS(use_spectral_norm=use_spectral_norm)]
|
| 995 |
+
discs = discs + [
|
| 996 |
+
DiscriminatorP(i, use_spectral_norm=use_spectral_norm) for i in periods
|
| 997 |
+
]
|
| 998 |
+
self.discriminators = nn.ModuleList(discs)
|
| 999 |
+
|
| 1000 |
+
def forward(self, y, y_hat):
|
| 1001 |
+
y_d_rs = [] #
|
| 1002 |
+
y_d_gs = []
|
| 1003 |
+
fmap_rs = []
|
| 1004 |
+
fmap_gs = []
|
| 1005 |
+
for i, d in enumerate(self.discriminators):
|
| 1006 |
+
y_d_r, fmap_r = d(y)
|
| 1007 |
+
y_d_g, fmap_g = d(y_hat)
|
| 1008 |
+
# for j in range(len(fmap_r)):
|
| 1009 |
+
# print(i,j,y.shape,y_hat.shape,fmap_r[j].shape,fmap_g[j].shape)
|
| 1010 |
+
y_d_rs.append(y_d_r)
|
| 1011 |
+
y_d_gs.append(y_d_g)
|
| 1012 |
+
fmap_rs.append(fmap_r)
|
| 1013 |
+
fmap_gs.append(fmap_g)
|
| 1014 |
+
|
| 1015 |
+
return y_d_rs, y_d_gs, fmap_rs, fmap_gs
|
| 1016 |
+
|
| 1017 |
+
|
| 1018 |
+
class DiscriminatorS(torch.nn.Module):
|
| 1019 |
+
def __init__(self, use_spectral_norm=False):
|
| 1020 |
+
super(DiscriminatorS, self).__init__()
|
| 1021 |
+
norm_f = weight_norm if use_spectral_norm == False else spectral_norm
|
| 1022 |
+
self.convs = nn.ModuleList(
|
| 1023 |
+
[
|
| 1024 |
+
norm_f(Conv1d(1, 16, 15, 1, padding=7)),
|
| 1025 |
+
norm_f(Conv1d(16, 64, 41, 4, groups=4, padding=20)),
|
| 1026 |
+
norm_f(Conv1d(64, 256, 41, 4, groups=16, padding=20)),
|
| 1027 |
+
norm_f(Conv1d(256, 1024, 41, 4, groups=64, padding=20)),
|
| 1028 |
+
norm_f(Conv1d(1024, 1024, 41, 4, groups=256, padding=20)),
|
| 1029 |
+
norm_f(Conv1d(1024, 1024, 5, 1, padding=2)),
|
| 1030 |
+
]
|
| 1031 |
+
)
|
| 1032 |
+
self.conv_post = norm_f(Conv1d(1024, 1, 3, 1, padding=1))
|
| 1033 |
+
|
| 1034 |
+
def forward(self, x):
|
| 1035 |
+
fmap = []
|
| 1036 |
+
|
| 1037 |
+
for l in self.convs:
|
| 1038 |
+
x = l(x)
|
| 1039 |
+
x = F.leaky_relu(x, modules.LRELU_SLOPE)
|
| 1040 |
+
fmap.append(x)
|
| 1041 |
+
x = self.conv_post(x)
|
| 1042 |
+
fmap.append(x)
|
| 1043 |
+
x = torch.flatten(x, 1, -1)
|
| 1044 |
+
|
| 1045 |
+
return x, fmap
|
| 1046 |
+
|
| 1047 |
+
|
| 1048 |
+
class DiscriminatorP(torch.nn.Module):
|
| 1049 |
+
def __init__(self, period, kernel_size=5, stride=3, use_spectral_norm=False):
|
| 1050 |
+
super(DiscriminatorP, self).__init__()
|
| 1051 |
+
self.period = period
|
| 1052 |
+
self.use_spectral_norm = use_spectral_norm
|
| 1053 |
+
norm_f = weight_norm if use_spectral_norm == False else spectral_norm
|
| 1054 |
+
self.convs = nn.ModuleList(
|
| 1055 |
+
[
|
| 1056 |
+
norm_f(
|
| 1057 |
+
Conv2d(
|
| 1058 |
+
1,
|
| 1059 |
+
32,
|
| 1060 |
+
(kernel_size, 1),
|
| 1061 |
+
(stride, 1),
|
| 1062 |
+
padding=(get_padding(kernel_size, 1), 0),
|
| 1063 |
+
)
|
| 1064 |
+
),
|
| 1065 |
+
norm_f(
|
| 1066 |
+
Conv2d(
|
| 1067 |
+
32,
|
| 1068 |
+
128,
|
| 1069 |
+
(kernel_size, 1),
|
| 1070 |
+
(stride, 1),
|
| 1071 |
+
padding=(get_padding(kernel_size, 1), 0),
|
| 1072 |
+
)
|
| 1073 |
+
),
|
| 1074 |
+
norm_f(
|
| 1075 |
+
Conv2d(
|
| 1076 |
+
128,
|
| 1077 |
+
512,
|
| 1078 |
+
(kernel_size, 1),
|
| 1079 |
+
(stride, 1),
|
| 1080 |
+
padding=(get_padding(kernel_size, 1), 0),
|
| 1081 |
+
)
|
| 1082 |
+
),
|
| 1083 |
+
norm_f(
|
| 1084 |
+
Conv2d(
|
| 1085 |
+
512,
|
| 1086 |
+
1024,
|
| 1087 |
+
(kernel_size, 1),
|
| 1088 |
+
(stride, 1),
|
| 1089 |
+
padding=(get_padding(kernel_size, 1), 0),
|
| 1090 |
+
)
|
| 1091 |
+
),
|
| 1092 |
+
norm_f(
|
| 1093 |
+
Conv2d(
|
| 1094 |
+
1024,
|
| 1095 |
+
1024,
|
| 1096 |
+
(kernel_size, 1),
|
| 1097 |
+
1,
|
| 1098 |
+
padding=(get_padding(kernel_size, 1), 0),
|
| 1099 |
+
)
|
| 1100 |
+
),
|
| 1101 |
+
]
|
| 1102 |
+
)
|
| 1103 |
+
self.conv_post = norm_f(Conv2d(1024, 1, (3, 1), 1, padding=(1, 0)))
|
| 1104 |
+
|
| 1105 |
+
def forward(self, x):
|
| 1106 |
+
fmap = []
|
| 1107 |
+
|
| 1108 |
+
# 1d to 2d
|
| 1109 |
+
b, c, t = x.shape
|
| 1110 |
+
if t % self.period != 0: # pad first
|
| 1111 |
+
n_pad = self.period - (t % self.period)
|
| 1112 |
+
x = F.pad(x, (0, n_pad), "reflect")
|
| 1113 |
+
t = t + n_pad
|
| 1114 |
+
x = x.view(b, c, t // self.period, self.period)
|
| 1115 |
+
|
| 1116 |
+
for l in self.convs:
|
| 1117 |
+
x = l(x)
|
| 1118 |
+
x = F.leaky_relu(x, modules.LRELU_SLOPE)
|
| 1119 |
+
fmap.append(x)
|
| 1120 |
+
x = self.conv_post(x)
|
| 1121 |
+
fmap.append(x)
|
| 1122 |
+
x = torch.flatten(x, 1, -1)
|
| 1123 |
+
|
| 1124 |
+
return x, fmap
|
lib/infer_pack/models_onnx.py
ADDED
|
@@ -0,0 +1,819 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math, pdb, os
|
| 2 |
+
from time import time as ttime
|
| 3 |
+
import torch
|
| 4 |
+
from torch import nn
|
| 5 |
+
from torch.nn import functional as F
|
| 6 |
+
from lib.infer_pack import modules
|
| 7 |
+
from lib.infer_pack import attentions
|
| 8 |
+
from lib.infer_pack import commons
|
| 9 |
+
from lib.infer_pack.commons import init_weights, get_padding
|
| 10 |
+
from torch.nn import Conv1d, ConvTranspose1d, AvgPool1d, Conv2d
|
| 11 |
+
from torch.nn.utils import weight_norm, remove_weight_norm, spectral_norm
|
| 12 |
+
from lib.infer_pack.commons import init_weights
|
| 13 |
+
import numpy as np
|
| 14 |
+
from lib.infer_pack import commons
|
| 15 |
+
|
| 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 |
+
return uv
|
| 319 |
+
|
| 320 |
+
def forward(self, f0, upp):
|
| 321 |
+
"""sine_tensor, uv = forward(f0)
|
| 322 |
+
input F0: tensor(batchsize=1, length, dim=1)
|
| 323 |
+
f0 for unvoiced steps should be 0
|
| 324 |
+
output sine_tensor: tensor(batchsize=1, length, dim)
|
| 325 |
+
output uv: tensor(batchsize=1, length, 1)
|
| 326 |
+
"""
|
| 327 |
+
with torch.no_grad():
|
| 328 |
+
f0 = f0[:, None].transpose(1, 2)
|
| 329 |
+
f0_buf = torch.zeros(f0.shape[0], f0.shape[1], self.dim, device=f0.device)
|
| 330 |
+
# fundamental component
|
| 331 |
+
f0_buf[:, :, 0] = f0[:, :, 0]
|
| 332 |
+
for idx in np.arange(self.harmonic_num):
|
| 333 |
+
f0_buf[:, :, idx + 1] = f0_buf[:, :, 0] * (
|
| 334 |
+
idx + 2
|
| 335 |
+
) # idx + 2: the (idx+1)-th overtone, (idx+2)-th harmonic
|
| 336 |
+
rad_values = (f0_buf / self.sampling_rate) % 1 ###%1意味着n_har的乘积无法后处理优化
|
| 337 |
+
rand_ini = torch.rand(
|
| 338 |
+
f0_buf.shape[0], f0_buf.shape[2], device=f0_buf.device
|
| 339 |
+
)
|
| 340 |
+
rand_ini[:, 0] = 0
|
| 341 |
+
rad_values[:, 0, :] = rad_values[:, 0, :] + rand_ini
|
| 342 |
+
tmp_over_one = torch.cumsum(rad_values, 1) # % 1 #####%1意味着后面的cumsum无法再优化
|
| 343 |
+
tmp_over_one *= upp
|
| 344 |
+
tmp_over_one = F.interpolate(
|
| 345 |
+
tmp_over_one.transpose(2, 1),
|
| 346 |
+
scale_factor=upp,
|
| 347 |
+
mode="linear",
|
| 348 |
+
align_corners=True,
|
| 349 |
+
).transpose(2, 1)
|
| 350 |
+
rad_values = F.interpolate(
|
| 351 |
+
rad_values.transpose(2, 1), scale_factor=upp, mode="nearest"
|
| 352 |
+
).transpose(
|
| 353 |
+
2, 1
|
| 354 |
+
) #######
|
| 355 |
+
tmp_over_one %= 1
|
| 356 |
+
tmp_over_one_idx = (tmp_over_one[:, 1:, :] - tmp_over_one[:, :-1, :]) < 0
|
| 357 |
+
cumsum_shift = torch.zeros_like(rad_values)
|
| 358 |
+
cumsum_shift[:, 1:, :] = tmp_over_one_idx * -1.0
|
| 359 |
+
sine_waves = torch.sin(
|
| 360 |
+
torch.cumsum(rad_values + cumsum_shift, dim=1) * 2 * np.pi
|
| 361 |
+
)
|
| 362 |
+
sine_waves = sine_waves * self.sine_amp
|
| 363 |
+
uv = self._f02uv(f0)
|
| 364 |
+
uv = F.interpolate(
|
| 365 |
+
uv.transpose(2, 1), scale_factor=upp, mode="nearest"
|
| 366 |
+
).transpose(2, 1)
|
| 367 |
+
noise_amp = uv * self.noise_std + (1 - uv) * self.sine_amp / 3
|
| 368 |
+
noise = noise_amp * torch.randn_like(sine_waves)
|
| 369 |
+
sine_waves = sine_waves * uv + noise
|
| 370 |
+
return sine_waves, uv, noise
|
| 371 |
+
|
| 372 |
+
|
| 373 |
+
class SourceModuleHnNSF(torch.nn.Module):
|
| 374 |
+
"""SourceModule for hn-nsf
|
| 375 |
+
SourceModule(sampling_rate, harmonic_num=0, sine_amp=0.1,
|
| 376 |
+
add_noise_std=0.003, voiced_threshod=0)
|
| 377 |
+
sampling_rate: sampling_rate in Hz
|
| 378 |
+
harmonic_num: number of harmonic above F0 (default: 0)
|
| 379 |
+
sine_amp: amplitude of sine source signal (default: 0.1)
|
| 380 |
+
add_noise_std: std of additive Gaussian noise (default: 0.003)
|
| 381 |
+
note that amplitude of noise in unvoiced is decided
|
| 382 |
+
by sine_amp
|
| 383 |
+
voiced_threshold: threhold to set U/V given F0 (default: 0)
|
| 384 |
+
Sine_source, noise_source = SourceModuleHnNSF(F0_sampled)
|
| 385 |
+
F0_sampled (batchsize, length, 1)
|
| 386 |
+
Sine_source (batchsize, length, 1)
|
| 387 |
+
noise_source (batchsize, length 1)
|
| 388 |
+
uv (batchsize, length, 1)
|
| 389 |
+
"""
|
| 390 |
+
|
| 391 |
+
def __init__(
|
| 392 |
+
self,
|
| 393 |
+
sampling_rate,
|
| 394 |
+
harmonic_num=0,
|
| 395 |
+
sine_amp=0.1,
|
| 396 |
+
add_noise_std=0.003,
|
| 397 |
+
voiced_threshod=0,
|
| 398 |
+
is_half=True,
|
| 399 |
+
):
|
| 400 |
+
super(SourceModuleHnNSF, self).__init__()
|
| 401 |
+
|
| 402 |
+
self.sine_amp = sine_amp
|
| 403 |
+
self.noise_std = add_noise_std
|
| 404 |
+
self.is_half = is_half
|
| 405 |
+
# to produce sine waveforms
|
| 406 |
+
self.l_sin_gen = SineGen(
|
| 407 |
+
sampling_rate, harmonic_num, sine_amp, add_noise_std, voiced_threshod
|
| 408 |
+
)
|
| 409 |
+
|
| 410 |
+
# to merge source harmonics into a single excitation
|
| 411 |
+
self.l_linear = torch.nn.Linear(harmonic_num + 1, 1)
|
| 412 |
+
self.l_tanh = torch.nn.Tanh()
|
| 413 |
+
|
| 414 |
+
def forward(self, x, upp=None):
|
| 415 |
+
sine_wavs, uv, _ = self.l_sin_gen(x, upp)
|
| 416 |
+
if self.is_half:
|
| 417 |
+
sine_wavs = sine_wavs.half()
|
| 418 |
+
sine_merge = self.l_tanh(self.l_linear(sine_wavs))
|
| 419 |
+
return sine_merge, None, None # noise, uv
|
| 420 |
+
|
| 421 |
+
|
| 422 |
+
class GeneratorNSF(torch.nn.Module):
|
| 423 |
+
def __init__(
|
| 424 |
+
self,
|
| 425 |
+
initial_channel,
|
| 426 |
+
resblock,
|
| 427 |
+
resblock_kernel_sizes,
|
| 428 |
+
resblock_dilation_sizes,
|
| 429 |
+
upsample_rates,
|
| 430 |
+
upsample_initial_channel,
|
| 431 |
+
upsample_kernel_sizes,
|
| 432 |
+
gin_channels,
|
| 433 |
+
sr,
|
| 434 |
+
is_half=False,
|
| 435 |
+
):
|
| 436 |
+
super(GeneratorNSF, self).__init__()
|
| 437 |
+
self.num_kernels = len(resblock_kernel_sizes)
|
| 438 |
+
self.num_upsamples = len(upsample_rates)
|
| 439 |
+
|
| 440 |
+
self.f0_upsamp = torch.nn.Upsample(scale_factor=np.prod(upsample_rates))
|
| 441 |
+
self.m_source = SourceModuleHnNSF(
|
| 442 |
+
sampling_rate=sr, harmonic_num=0, is_half=is_half
|
| 443 |
+
)
|
| 444 |
+
self.noise_convs = nn.ModuleList()
|
| 445 |
+
self.conv_pre = Conv1d(
|
| 446 |
+
initial_channel, upsample_initial_channel, 7, 1, padding=3
|
| 447 |
+
)
|
| 448 |
+
resblock = modules.ResBlock1 if resblock == "1" else modules.ResBlock2
|
| 449 |
+
|
| 450 |
+
self.ups = nn.ModuleList()
|
| 451 |
+
for i, (u, k) in enumerate(zip(upsample_rates, upsample_kernel_sizes)):
|
| 452 |
+
c_cur = upsample_initial_channel // (2 ** (i + 1))
|
| 453 |
+
self.ups.append(
|
| 454 |
+
weight_norm(
|
| 455 |
+
ConvTranspose1d(
|
| 456 |
+
upsample_initial_channel // (2**i),
|
| 457 |
+
upsample_initial_channel // (2 ** (i + 1)),
|
| 458 |
+
k,
|
| 459 |
+
u,
|
| 460 |
+
padding=(k - u) // 2,
|
| 461 |
+
)
|
| 462 |
+
)
|
| 463 |
+
)
|
| 464 |
+
if i + 1 < len(upsample_rates):
|
| 465 |
+
stride_f0 = np.prod(upsample_rates[i + 1 :])
|
| 466 |
+
self.noise_convs.append(
|
| 467 |
+
Conv1d(
|
| 468 |
+
1,
|
| 469 |
+
c_cur,
|
| 470 |
+
kernel_size=stride_f0 * 2,
|
| 471 |
+
stride=stride_f0,
|
| 472 |
+
padding=stride_f0 // 2,
|
| 473 |
+
)
|
| 474 |
+
)
|
| 475 |
+
else:
|
| 476 |
+
self.noise_convs.append(Conv1d(1, c_cur, kernel_size=1))
|
| 477 |
+
|
| 478 |
+
self.resblocks = nn.ModuleList()
|
| 479 |
+
for i in range(len(self.ups)):
|
| 480 |
+
ch = upsample_initial_channel // (2 ** (i + 1))
|
| 481 |
+
for j, (k, d) in enumerate(
|
| 482 |
+
zip(resblock_kernel_sizes, resblock_dilation_sizes)
|
| 483 |
+
):
|
| 484 |
+
self.resblocks.append(resblock(ch, k, d))
|
| 485 |
+
|
| 486 |
+
self.conv_post = Conv1d(ch, 1, 7, 1, padding=3, bias=False)
|
| 487 |
+
self.ups.apply(init_weights)
|
| 488 |
+
|
| 489 |
+
if gin_channels != 0:
|
| 490 |
+
self.cond = nn.Conv1d(gin_channels, upsample_initial_channel, 1)
|
| 491 |
+
|
| 492 |
+
self.upp = np.prod(upsample_rates)
|
| 493 |
+
|
| 494 |
+
def forward(self, x, f0, g=None):
|
| 495 |
+
har_source, noi_source, uv = self.m_source(f0, self.upp)
|
| 496 |
+
har_source = har_source.transpose(1, 2)
|
| 497 |
+
x = self.conv_pre(x)
|
| 498 |
+
if g is not None:
|
| 499 |
+
x = x + self.cond(g)
|
| 500 |
+
|
| 501 |
+
for i in range(self.num_upsamples):
|
| 502 |
+
x = F.leaky_relu(x, modules.LRELU_SLOPE)
|
| 503 |
+
x = self.ups[i](x)
|
| 504 |
+
x_source = self.noise_convs[i](har_source)
|
| 505 |
+
x = x + x_source
|
| 506 |
+
xs = None
|
| 507 |
+
for j in range(self.num_kernels):
|
| 508 |
+
if xs is None:
|
| 509 |
+
xs = self.resblocks[i * self.num_kernels + j](x)
|
| 510 |
+
else:
|
| 511 |
+
xs += self.resblocks[i * self.num_kernels + j](x)
|
| 512 |
+
x = xs / self.num_kernels
|
| 513 |
+
x = F.leaky_relu(x)
|
| 514 |
+
x = self.conv_post(x)
|
| 515 |
+
x = torch.tanh(x)
|
| 516 |
+
return x
|
| 517 |
+
|
| 518 |
+
def remove_weight_norm(self):
|
| 519 |
+
for l in self.ups:
|
| 520 |
+
remove_weight_norm(l)
|
| 521 |
+
for l in self.resblocks:
|
| 522 |
+
l.remove_weight_norm()
|
| 523 |
+
|
| 524 |
+
|
| 525 |
+
sr2sr = {
|
| 526 |
+
"32k": 32000,
|
| 527 |
+
"40k": 40000,
|
| 528 |
+
"48k": 48000,
|
| 529 |
+
}
|
| 530 |
+
|
| 531 |
+
|
| 532 |
+
class SynthesizerTrnMsNSFsidM(nn.Module):
|
| 533 |
+
def __init__(
|
| 534 |
+
self,
|
| 535 |
+
spec_channels,
|
| 536 |
+
segment_size,
|
| 537 |
+
inter_channels,
|
| 538 |
+
hidden_channels,
|
| 539 |
+
filter_channels,
|
| 540 |
+
n_heads,
|
| 541 |
+
n_layers,
|
| 542 |
+
kernel_size,
|
| 543 |
+
p_dropout,
|
| 544 |
+
resblock,
|
| 545 |
+
resblock_kernel_sizes,
|
| 546 |
+
resblock_dilation_sizes,
|
| 547 |
+
upsample_rates,
|
| 548 |
+
upsample_initial_channel,
|
| 549 |
+
upsample_kernel_sizes,
|
| 550 |
+
spk_embed_dim,
|
| 551 |
+
gin_channels,
|
| 552 |
+
sr,
|
| 553 |
+
version,
|
| 554 |
+
**kwargs
|
| 555 |
+
):
|
| 556 |
+
super().__init__()
|
| 557 |
+
if type(sr) == type("strr"):
|
| 558 |
+
sr = sr2sr[sr]
|
| 559 |
+
self.spec_channels = spec_channels
|
| 560 |
+
self.inter_channels = inter_channels
|
| 561 |
+
self.hidden_channels = hidden_channels
|
| 562 |
+
self.filter_channels = filter_channels
|
| 563 |
+
self.n_heads = n_heads
|
| 564 |
+
self.n_layers = n_layers
|
| 565 |
+
self.kernel_size = kernel_size
|
| 566 |
+
self.p_dropout = p_dropout
|
| 567 |
+
self.resblock = resblock
|
| 568 |
+
self.resblock_kernel_sizes = resblock_kernel_sizes
|
| 569 |
+
self.resblock_dilation_sizes = resblock_dilation_sizes
|
| 570 |
+
self.upsample_rates = upsample_rates
|
| 571 |
+
self.upsample_initial_channel = upsample_initial_channel
|
| 572 |
+
self.upsample_kernel_sizes = upsample_kernel_sizes
|
| 573 |
+
self.segment_size = segment_size
|
| 574 |
+
self.gin_channels = gin_channels
|
| 575 |
+
# self.hop_length = hop_length#
|
| 576 |
+
self.spk_embed_dim = spk_embed_dim
|
| 577 |
+
if version == "v1":
|
| 578 |
+
self.enc_p = TextEncoder256(
|
| 579 |
+
inter_channels,
|
| 580 |
+
hidden_channels,
|
| 581 |
+
filter_channels,
|
| 582 |
+
n_heads,
|
| 583 |
+
n_layers,
|
| 584 |
+
kernel_size,
|
| 585 |
+
p_dropout,
|
| 586 |
+
)
|
| 587 |
+
else:
|
| 588 |
+
self.enc_p = TextEncoder768(
|
| 589 |
+
inter_channels,
|
| 590 |
+
hidden_channels,
|
| 591 |
+
filter_channels,
|
| 592 |
+
n_heads,
|
| 593 |
+
n_layers,
|
| 594 |
+
kernel_size,
|
| 595 |
+
p_dropout,
|
| 596 |
+
)
|
| 597 |
+
self.dec = GeneratorNSF(
|
| 598 |
+
inter_channels,
|
| 599 |
+
resblock,
|
| 600 |
+
resblock_kernel_sizes,
|
| 601 |
+
resblock_dilation_sizes,
|
| 602 |
+
upsample_rates,
|
| 603 |
+
upsample_initial_channel,
|
| 604 |
+
upsample_kernel_sizes,
|
| 605 |
+
gin_channels=gin_channels,
|
| 606 |
+
sr=sr,
|
| 607 |
+
is_half=kwargs["is_half"],
|
| 608 |
+
)
|
| 609 |
+
self.enc_q = PosteriorEncoder(
|
| 610 |
+
spec_channels,
|
| 611 |
+
inter_channels,
|
| 612 |
+
hidden_channels,
|
| 613 |
+
5,
|
| 614 |
+
1,
|
| 615 |
+
16,
|
| 616 |
+
gin_channels=gin_channels,
|
| 617 |
+
)
|
| 618 |
+
self.flow = ResidualCouplingBlock(
|
| 619 |
+
inter_channels, hidden_channels, 5, 1, 3, gin_channels=gin_channels
|
| 620 |
+
)
|
| 621 |
+
self.emb_g = nn.Embedding(self.spk_embed_dim, gin_channels)
|
| 622 |
+
self.speaker_map = None
|
| 623 |
+
print("gin_channels:", gin_channels, "self.spk_embed_dim:", self.spk_embed_dim)
|
| 624 |
+
|
| 625 |
+
def remove_weight_norm(self):
|
| 626 |
+
self.dec.remove_weight_norm()
|
| 627 |
+
self.flow.remove_weight_norm()
|
| 628 |
+
self.enc_q.remove_weight_norm()
|
| 629 |
+
|
| 630 |
+
def construct_spkmixmap(self, n_speaker):
|
| 631 |
+
self.speaker_map = torch.zeros((n_speaker, 1, 1, self.gin_channels))
|
| 632 |
+
for i in range(n_speaker):
|
| 633 |
+
self.speaker_map[i] = self.emb_g(torch.LongTensor([[i]]))
|
| 634 |
+
self.speaker_map = self.speaker_map.unsqueeze(0)
|
| 635 |
+
|
| 636 |
+
def forward(self, phone, phone_lengths, pitch, nsff0, g, rnd, max_len=None):
|
| 637 |
+
if self.speaker_map is not None: # [N, S] * [S, B, 1, H]
|
| 638 |
+
g = g.reshape((g.shape[0], g.shape[1], 1, 1, 1)) # [N, S, B, 1, 1]
|
| 639 |
+
g = g * self.speaker_map # [N, S, B, 1, H]
|
| 640 |
+
g = torch.sum(g, dim=1) # [N, 1, B, 1, H]
|
| 641 |
+
g = g.transpose(0, -1).transpose(0, -2).squeeze(0) # [B, H, N]
|
| 642 |
+
else:
|
| 643 |
+
g = g.unsqueeze(0)
|
| 644 |
+
g = self.emb_g(g).transpose(1, 2)
|
| 645 |
+
|
| 646 |
+
m_p, logs_p, x_mask = self.enc_p(phone, pitch, phone_lengths)
|
| 647 |
+
z_p = (m_p + torch.exp(logs_p) * rnd) * x_mask
|
| 648 |
+
z = self.flow(z_p, x_mask, g=g, reverse=True)
|
| 649 |
+
o = self.dec((z * x_mask)[:, :, :max_len], nsff0, g=g)
|
| 650 |
+
return o
|
| 651 |
+
|
| 652 |
+
|
| 653 |
+
class MultiPeriodDiscriminator(torch.nn.Module):
|
| 654 |
+
def __init__(self, use_spectral_norm=False):
|
| 655 |
+
super(MultiPeriodDiscriminator, self).__init__()
|
| 656 |
+
periods = [2, 3, 5, 7, 11, 17]
|
| 657 |
+
# periods = [3, 5, 7, 11, 17, 23, 37]
|
| 658 |
+
|
| 659 |
+
discs = [DiscriminatorS(use_spectral_norm=use_spectral_norm)]
|
| 660 |
+
discs = discs + [
|
| 661 |
+
DiscriminatorP(i, use_spectral_norm=use_spectral_norm) for i in periods
|
| 662 |
+
]
|
| 663 |
+
self.discriminators = nn.ModuleList(discs)
|
| 664 |
+
|
| 665 |
+
def forward(self, y, y_hat):
|
| 666 |
+
y_d_rs = [] #
|
| 667 |
+
y_d_gs = []
|
| 668 |
+
fmap_rs = []
|
| 669 |
+
fmap_gs = []
|
| 670 |
+
for i, d in enumerate(self.discriminators):
|
| 671 |
+
y_d_r, fmap_r = d(y)
|
| 672 |
+
y_d_g, fmap_g = d(y_hat)
|
| 673 |
+
# for j in range(len(fmap_r)):
|
| 674 |
+
# print(i,j,y.shape,y_hat.shape,fmap_r[j].shape,fmap_g[j].shape)
|
| 675 |
+
y_d_rs.append(y_d_r)
|
| 676 |
+
y_d_gs.append(y_d_g)
|
| 677 |
+
fmap_rs.append(fmap_r)
|
| 678 |
+
fmap_gs.append(fmap_g)
|
| 679 |
+
|
| 680 |
+
return y_d_rs, y_d_gs, fmap_rs, fmap_gs
|
| 681 |
+
|
| 682 |
+
|
| 683 |
+
class MultiPeriodDiscriminatorV2(torch.nn.Module):
|
| 684 |
+
def __init__(self, use_spectral_norm=False):
|
| 685 |
+
super(MultiPeriodDiscriminatorV2, self).__init__()
|
| 686 |
+
# periods = [2, 3, 5, 7, 11, 17]
|
| 687 |
+
periods = [2, 3, 5, 7, 11, 17, 23, 37]
|
| 688 |
+
|
| 689 |
+
discs = [DiscriminatorS(use_spectral_norm=use_spectral_norm)]
|
| 690 |
+
discs = discs + [
|
| 691 |
+
DiscriminatorP(i, use_spectral_norm=use_spectral_norm) for i in periods
|
| 692 |
+
]
|
| 693 |
+
self.discriminators = nn.ModuleList(discs)
|
| 694 |
+
|
| 695 |
+
def forward(self, y, y_hat):
|
| 696 |
+
y_d_rs = [] #
|
| 697 |
+
y_d_gs = []
|
| 698 |
+
fmap_rs = []
|
| 699 |
+
fmap_gs = []
|
| 700 |
+
for i, d in enumerate(self.discriminators):
|
| 701 |
+
y_d_r, fmap_r = d(y)
|
| 702 |
+
y_d_g, fmap_g = d(y_hat)
|
| 703 |
+
# for j in range(len(fmap_r)):
|
| 704 |
+
# print(i,j,y.shape,y_hat.shape,fmap_r[j].shape,fmap_g[j].shape)
|
| 705 |
+
y_d_rs.append(y_d_r)
|
| 706 |
+
y_d_gs.append(y_d_g)
|
| 707 |
+
fmap_rs.append(fmap_r)
|
| 708 |
+
fmap_gs.append(fmap_g)
|
| 709 |
+
|
| 710 |
+
return y_d_rs, y_d_gs, fmap_rs, fmap_gs
|
| 711 |
+
|
| 712 |
+
|
| 713 |
+
class DiscriminatorS(torch.nn.Module):
|
| 714 |
+
def __init__(self, use_spectral_norm=False):
|
| 715 |
+
super(DiscriminatorS, self).__init__()
|
| 716 |
+
norm_f = weight_norm if use_spectral_norm == False else spectral_norm
|
| 717 |
+
self.convs = nn.ModuleList(
|
| 718 |
+
[
|
| 719 |
+
norm_f(Conv1d(1, 16, 15, 1, padding=7)),
|
| 720 |
+
norm_f(Conv1d(16, 64, 41, 4, groups=4, padding=20)),
|
| 721 |
+
norm_f(Conv1d(64, 256, 41, 4, groups=16, padding=20)),
|
| 722 |
+
norm_f(Conv1d(256, 1024, 41, 4, groups=64, padding=20)),
|
| 723 |
+
norm_f(Conv1d(1024, 1024, 41, 4, groups=256, padding=20)),
|
| 724 |
+
norm_f(Conv1d(1024, 1024, 5, 1, padding=2)),
|
| 725 |
+
]
|
| 726 |
+
)
|
| 727 |
+
self.conv_post = norm_f(Conv1d(1024, 1, 3, 1, padding=1))
|
| 728 |
+
|
| 729 |
+
def forward(self, x):
|
| 730 |
+
fmap = []
|
| 731 |
+
|
| 732 |
+
for l in self.convs:
|
| 733 |
+
x = l(x)
|
| 734 |
+
x = F.leaky_relu(x, modules.LRELU_SLOPE)
|
| 735 |
+
fmap.append(x)
|
| 736 |
+
x = self.conv_post(x)
|
| 737 |
+
fmap.append(x)
|
| 738 |
+
x = torch.flatten(x, 1, -1)
|
| 739 |
+
|
| 740 |
+
return x, fmap
|
| 741 |
+
|
| 742 |
+
|
| 743 |
+
class DiscriminatorP(torch.nn.Module):
|
| 744 |
+
def __init__(self, period, kernel_size=5, stride=3, use_spectral_norm=False):
|
| 745 |
+
super(DiscriminatorP, self).__init__()
|
| 746 |
+
self.period = period
|
| 747 |
+
self.use_spectral_norm = use_spectral_norm
|
| 748 |
+
norm_f = weight_norm if use_spectral_norm == False else spectral_norm
|
| 749 |
+
self.convs = nn.ModuleList(
|
| 750 |
+
[
|
| 751 |
+
norm_f(
|
| 752 |
+
Conv2d(
|
| 753 |
+
1,
|
| 754 |
+
32,
|
| 755 |
+
(kernel_size, 1),
|
| 756 |
+
(stride, 1),
|
| 757 |
+
padding=(get_padding(kernel_size, 1), 0),
|
| 758 |
+
)
|
| 759 |
+
),
|
| 760 |
+
norm_f(
|
| 761 |
+
Conv2d(
|
| 762 |
+
32,
|
| 763 |
+
128,
|
| 764 |
+
(kernel_size, 1),
|
| 765 |
+
(stride, 1),
|
| 766 |
+
padding=(get_padding(kernel_size, 1), 0),
|
| 767 |
+
)
|
| 768 |
+
),
|
| 769 |
+
norm_f(
|
| 770 |
+
Conv2d(
|
| 771 |
+
128,
|
| 772 |
+
512,
|
| 773 |
+
(kernel_size, 1),
|
| 774 |
+
(stride, 1),
|
| 775 |
+
padding=(get_padding(kernel_size, 1), 0),
|
| 776 |
+
)
|
| 777 |
+
),
|
| 778 |
+
norm_f(
|
| 779 |
+
Conv2d(
|
| 780 |
+
512,
|
| 781 |
+
1024,
|
| 782 |
+
(kernel_size, 1),
|
| 783 |
+
(stride, 1),
|
| 784 |
+
padding=(get_padding(kernel_size, 1), 0),
|
| 785 |
+
)
|
| 786 |
+
),
|
| 787 |
+
norm_f(
|
| 788 |
+
Conv2d(
|
| 789 |
+
1024,
|
| 790 |
+
1024,
|
| 791 |
+
(kernel_size, 1),
|
| 792 |
+
1,
|
| 793 |
+
padding=(get_padding(kernel_size, 1), 0),
|
| 794 |
+
)
|
| 795 |
+
),
|
| 796 |
+
]
|
| 797 |
+
)
|
| 798 |
+
self.conv_post = norm_f(Conv2d(1024, 1, (3, 1), 1, padding=(1, 0)))
|
| 799 |
+
|
| 800 |
+
def forward(self, x):
|
| 801 |
+
fmap = []
|
| 802 |
+
|
| 803 |
+
# 1d to 2d
|
| 804 |
+
b, c, t = x.shape
|
| 805 |
+
if t % self.period != 0: # pad first
|
| 806 |
+
n_pad = self.period - (t % self.period)
|
| 807 |
+
x = F.pad(x, (0, n_pad), "reflect")
|
| 808 |
+
t = t + n_pad
|
| 809 |
+
x = x.view(b, c, t // self.period, self.period)
|
| 810 |
+
|
| 811 |
+
for l in self.convs:
|
| 812 |
+
x = l(x)
|
| 813 |
+
x = F.leaky_relu(x, modules.LRELU_SLOPE)
|
| 814 |
+
fmap.append(x)
|
| 815 |
+
x = self.conv_post(x)
|
| 816 |
+
fmap.append(x)
|
| 817 |
+
x = torch.flatten(x, 1, -1)
|
| 818 |
+
|
| 819 |
+
return x, fmap
|
lib/infer_pack/modules.py
ADDED
|
@@ -0,0 +1,522 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import copy
|
| 2 |
+
import math
|
| 3 |
+
import numpy as np
|
| 4 |
+
import scipy
|
| 5 |
+
import torch
|
| 6 |
+
from torch import nn
|
| 7 |
+
from torch.nn import functional as F
|
| 8 |
+
|
| 9 |
+
from torch.nn import Conv1d, ConvTranspose1d, AvgPool1d, Conv2d
|
| 10 |
+
from torch.nn.utils import weight_norm, remove_weight_norm
|
| 11 |
+
|
| 12 |
+
from lib.infer_pack import commons
|
| 13 |
+
from lib.infer_pack.commons import init_weights, get_padding
|
| 14 |
+
from lib.infer_pack.transforms import piecewise_rational_quadratic_transform
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
LRELU_SLOPE = 0.1
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class LayerNorm(nn.Module):
|
| 21 |
+
def __init__(self, channels, eps=1e-5):
|
| 22 |
+
super().__init__()
|
| 23 |
+
self.channels = channels
|
| 24 |
+
self.eps = eps
|
| 25 |
+
|
| 26 |
+
self.gamma = nn.Parameter(torch.ones(channels))
|
| 27 |
+
self.beta = nn.Parameter(torch.zeros(channels))
|
| 28 |
+
|
| 29 |
+
def forward(self, x):
|
| 30 |
+
x = x.transpose(1, -1)
|
| 31 |
+
x = F.layer_norm(x, (self.channels,), self.gamma, self.beta, self.eps)
|
| 32 |
+
return x.transpose(1, -1)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class ConvReluNorm(nn.Module):
|
| 36 |
+
def __init__(
|
| 37 |
+
self,
|
| 38 |
+
in_channels,
|
| 39 |
+
hidden_channels,
|
| 40 |
+
out_channels,
|
| 41 |
+
kernel_size,
|
| 42 |
+
n_layers,
|
| 43 |
+
p_dropout,
|
| 44 |
+
):
|
| 45 |
+
super().__init__()
|
| 46 |
+
self.in_channels = in_channels
|
| 47 |
+
self.hidden_channels = hidden_channels
|
| 48 |
+
self.out_channels = out_channels
|
| 49 |
+
self.kernel_size = kernel_size
|
| 50 |
+
self.n_layers = n_layers
|
| 51 |
+
self.p_dropout = p_dropout
|
| 52 |
+
assert n_layers > 1, "Number of layers should be larger than 0."
|
| 53 |
+
|
| 54 |
+
self.conv_layers = nn.ModuleList()
|
| 55 |
+
self.norm_layers = nn.ModuleList()
|
| 56 |
+
self.conv_layers.append(
|
| 57 |
+
nn.Conv1d(
|
| 58 |
+
in_channels, hidden_channels, kernel_size, padding=kernel_size // 2
|
| 59 |
+
)
|
| 60 |
+
)
|
| 61 |
+
self.norm_layers.append(LayerNorm(hidden_channels))
|
| 62 |
+
self.relu_drop = nn.Sequential(nn.ReLU(), nn.Dropout(p_dropout))
|
| 63 |
+
for _ in range(n_layers - 1):
|
| 64 |
+
self.conv_layers.append(
|
| 65 |
+
nn.Conv1d(
|
| 66 |
+
hidden_channels,
|
| 67 |
+
hidden_channels,
|
| 68 |
+
kernel_size,
|
| 69 |
+
padding=kernel_size // 2,
|
| 70 |
+
)
|
| 71 |
+
)
|
| 72 |
+
self.norm_layers.append(LayerNorm(hidden_channels))
|
| 73 |
+
self.proj = nn.Conv1d(hidden_channels, out_channels, 1)
|
| 74 |
+
self.proj.weight.data.zero_()
|
| 75 |
+
self.proj.bias.data.zero_()
|
| 76 |
+
|
| 77 |
+
def forward(self, x, x_mask):
|
| 78 |
+
x_org = x
|
| 79 |
+
for i in range(self.n_layers):
|
| 80 |
+
x = self.conv_layers[i](x * x_mask)
|
| 81 |
+
x = self.norm_layers[i](x)
|
| 82 |
+
x = self.relu_drop(x)
|
| 83 |
+
x = x_org + self.proj(x)
|
| 84 |
+
return x * x_mask
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
class DDSConv(nn.Module):
|
| 88 |
+
"""
|
| 89 |
+
Dialted and Depth-Separable Convolution
|
| 90 |
+
"""
|
| 91 |
+
|
| 92 |
+
def __init__(self, channels, kernel_size, n_layers, p_dropout=0.0):
|
| 93 |
+
super().__init__()
|
| 94 |
+
self.channels = channels
|
| 95 |
+
self.kernel_size = kernel_size
|
| 96 |
+
self.n_layers = n_layers
|
| 97 |
+
self.p_dropout = p_dropout
|
| 98 |
+
|
| 99 |
+
self.drop = nn.Dropout(p_dropout)
|
| 100 |
+
self.convs_sep = nn.ModuleList()
|
| 101 |
+
self.convs_1x1 = nn.ModuleList()
|
| 102 |
+
self.norms_1 = nn.ModuleList()
|
| 103 |
+
self.norms_2 = nn.ModuleList()
|
| 104 |
+
for i in range(n_layers):
|
| 105 |
+
dilation = kernel_size**i
|
| 106 |
+
padding = (kernel_size * dilation - dilation) // 2
|
| 107 |
+
self.convs_sep.append(
|
| 108 |
+
nn.Conv1d(
|
| 109 |
+
channels,
|
| 110 |
+
channels,
|
| 111 |
+
kernel_size,
|
| 112 |
+
groups=channels,
|
| 113 |
+
dilation=dilation,
|
| 114 |
+
padding=padding,
|
| 115 |
+
)
|
| 116 |
+
)
|
| 117 |
+
self.convs_1x1.append(nn.Conv1d(channels, channels, 1))
|
| 118 |
+
self.norms_1.append(LayerNorm(channels))
|
| 119 |
+
self.norms_2.append(LayerNorm(channels))
|
| 120 |
+
|
| 121 |
+
def forward(self, x, x_mask, g=None):
|
| 122 |
+
if g is not None:
|
| 123 |
+
x = x + g
|
| 124 |
+
for i in range(self.n_layers):
|
| 125 |
+
y = self.convs_sep[i](x * x_mask)
|
| 126 |
+
y = self.norms_1[i](y)
|
| 127 |
+
y = F.gelu(y)
|
| 128 |
+
y = self.convs_1x1[i](y)
|
| 129 |
+
y = self.norms_2[i](y)
|
| 130 |
+
y = F.gelu(y)
|
| 131 |
+
y = self.drop(y)
|
| 132 |
+
x = x + y
|
| 133 |
+
return x * x_mask
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
class WN(torch.nn.Module):
|
| 137 |
+
def __init__(
|
| 138 |
+
self,
|
| 139 |
+
hidden_channels,
|
| 140 |
+
kernel_size,
|
| 141 |
+
dilation_rate,
|
| 142 |
+
n_layers,
|
| 143 |
+
gin_channels=0,
|
| 144 |
+
p_dropout=0,
|
| 145 |
+
):
|
| 146 |
+
super(WN, self).__init__()
|
| 147 |
+
assert kernel_size % 2 == 1
|
| 148 |
+
self.hidden_channels = hidden_channels
|
| 149 |
+
self.kernel_size = (kernel_size,)
|
| 150 |
+
self.dilation_rate = dilation_rate
|
| 151 |
+
self.n_layers = n_layers
|
| 152 |
+
self.gin_channels = gin_channels
|
| 153 |
+
self.p_dropout = p_dropout
|
| 154 |
+
|
| 155 |
+
self.in_layers = torch.nn.ModuleList()
|
| 156 |
+
self.res_skip_layers = torch.nn.ModuleList()
|
| 157 |
+
self.drop = nn.Dropout(p_dropout)
|
| 158 |
+
|
| 159 |
+
if gin_channels != 0:
|
| 160 |
+
cond_layer = torch.nn.Conv1d(
|
| 161 |
+
gin_channels, 2 * hidden_channels * n_layers, 1
|
| 162 |
+
)
|
| 163 |
+
self.cond_layer = torch.nn.utils.weight_norm(cond_layer, name="weight")
|
| 164 |
+
|
| 165 |
+
for i in range(n_layers):
|
| 166 |
+
dilation = dilation_rate**i
|
| 167 |
+
padding = int((kernel_size * dilation - dilation) / 2)
|
| 168 |
+
in_layer = torch.nn.Conv1d(
|
| 169 |
+
hidden_channels,
|
| 170 |
+
2 * hidden_channels,
|
| 171 |
+
kernel_size,
|
| 172 |
+
dilation=dilation,
|
| 173 |
+
padding=padding,
|
| 174 |
+
)
|
| 175 |
+
in_layer = torch.nn.utils.weight_norm(in_layer, name="weight")
|
| 176 |
+
self.in_layers.append(in_layer)
|
| 177 |
+
|
| 178 |
+
# last one is not necessary
|
| 179 |
+
if i < n_layers - 1:
|
| 180 |
+
res_skip_channels = 2 * hidden_channels
|
| 181 |
+
else:
|
| 182 |
+
res_skip_channels = hidden_channels
|
| 183 |
+
|
| 184 |
+
res_skip_layer = torch.nn.Conv1d(hidden_channels, res_skip_channels, 1)
|
| 185 |
+
res_skip_layer = torch.nn.utils.weight_norm(res_skip_layer, name="weight")
|
| 186 |
+
self.res_skip_layers.append(res_skip_layer)
|
| 187 |
+
|
| 188 |
+
def forward(self, x, x_mask, g=None, **kwargs):
|
| 189 |
+
output = torch.zeros_like(x)
|
| 190 |
+
n_channels_tensor = torch.IntTensor([self.hidden_channels])
|
| 191 |
+
|
| 192 |
+
if g is not None:
|
| 193 |
+
g = self.cond_layer(g)
|
| 194 |
+
|
| 195 |
+
for i in range(self.n_layers):
|
| 196 |
+
x_in = self.in_layers[i](x)
|
| 197 |
+
if g is not None:
|
| 198 |
+
cond_offset = i * 2 * self.hidden_channels
|
| 199 |
+
g_l = g[:, cond_offset : cond_offset + 2 * self.hidden_channels, :]
|
| 200 |
+
else:
|
| 201 |
+
g_l = torch.zeros_like(x_in)
|
| 202 |
+
|
| 203 |
+
acts = commons.fused_add_tanh_sigmoid_multiply(x_in, g_l, n_channels_tensor)
|
| 204 |
+
acts = self.drop(acts)
|
| 205 |
+
|
| 206 |
+
res_skip_acts = self.res_skip_layers[i](acts)
|
| 207 |
+
if i < self.n_layers - 1:
|
| 208 |
+
res_acts = res_skip_acts[:, : self.hidden_channels, :]
|
| 209 |
+
x = (x + res_acts) * x_mask
|
| 210 |
+
output = output + res_skip_acts[:, self.hidden_channels :, :]
|
| 211 |
+
else:
|
| 212 |
+
output = output + res_skip_acts
|
| 213 |
+
return output * x_mask
|
| 214 |
+
|
| 215 |
+
def remove_weight_norm(self):
|
| 216 |
+
if self.gin_channels != 0:
|
| 217 |
+
torch.nn.utils.remove_weight_norm(self.cond_layer)
|
| 218 |
+
for l in self.in_layers:
|
| 219 |
+
torch.nn.utils.remove_weight_norm(l)
|
| 220 |
+
for l in self.res_skip_layers:
|
| 221 |
+
torch.nn.utils.remove_weight_norm(l)
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
class ResBlock1(torch.nn.Module):
|
| 225 |
+
def __init__(self, channels, kernel_size=3, dilation=(1, 3, 5)):
|
| 226 |
+
super(ResBlock1, self).__init__()
|
| 227 |
+
self.convs1 = nn.ModuleList(
|
| 228 |
+
[
|
| 229 |
+
weight_norm(
|
| 230 |
+
Conv1d(
|
| 231 |
+
channels,
|
| 232 |
+
channels,
|
| 233 |
+
kernel_size,
|
| 234 |
+
1,
|
| 235 |
+
dilation=dilation[0],
|
| 236 |
+
padding=get_padding(kernel_size, dilation[0]),
|
| 237 |
+
)
|
| 238 |
+
),
|
| 239 |
+
weight_norm(
|
| 240 |
+
Conv1d(
|
| 241 |
+
channels,
|
| 242 |
+
channels,
|
| 243 |
+
kernel_size,
|
| 244 |
+
1,
|
| 245 |
+
dilation=dilation[1],
|
| 246 |
+
padding=get_padding(kernel_size, dilation[1]),
|
| 247 |
+
)
|
| 248 |
+
),
|
| 249 |
+
weight_norm(
|
| 250 |
+
Conv1d(
|
| 251 |
+
channels,
|
| 252 |
+
channels,
|
| 253 |
+
kernel_size,
|
| 254 |
+
1,
|
| 255 |
+
dilation=dilation[2],
|
| 256 |
+
padding=get_padding(kernel_size, dilation[2]),
|
| 257 |
+
)
|
| 258 |
+
),
|
| 259 |
+
]
|
| 260 |
+
)
|
| 261 |
+
self.convs1.apply(init_weights)
|
| 262 |
+
|
| 263 |
+
self.convs2 = nn.ModuleList(
|
| 264 |
+
[
|
| 265 |
+
weight_norm(
|
| 266 |
+
Conv1d(
|
| 267 |
+
channels,
|
| 268 |
+
channels,
|
| 269 |
+
kernel_size,
|
| 270 |
+
1,
|
| 271 |
+
dilation=1,
|
| 272 |
+
padding=get_padding(kernel_size, 1),
|
| 273 |
+
)
|
| 274 |
+
),
|
| 275 |
+
weight_norm(
|
| 276 |
+
Conv1d(
|
| 277 |
+
channels,
|
| 278 |
+
channels,
|
| 279 |
+
kernel_size,
|
| 280 |
+
1,
|
| 281 |
+
dilation=1,
|
| 282 |
+
padding=get_padding(kernel_size, 1),
|
| 283 |
+
)
|
| 284 |
+
),
|
| 285 |
+
weight_norm(
|
| 286 |
+
Conv1d(
|
| 287 |
+
channels,
|
| 288 |
+
channels,
|
| 289 |
+
kernel_size,
|
| 290 |
+
1,
|
| 291 |
+
dilation=1,
|
| 292 |
+
padding=get_padding(kernel_size, 1),
|
| 293 |
+
)
|
| 294 |
+
),
|
| 295 |
+
]
|
| 296 |
+
)
|
| 297 |
+
self.convs2.apply(init_weights)
|
| 298 |
+
|
| 299 |
+
def forward(self, x, x_mask=None):
|
| 300 |
+
for c1, c2 in zip(self.convs1, self.convs2):
|
| 301 |
+
xt = F.leaky_relu(x, LRELU_SLOPE)
|
| 302 |
+
if x_mask is not None:
|
| 303 |
+
xt = xt * x_mask
|
| 304 |
+
xt = c1(xt)
|
| 305 |
+
xt = F.leaky_relu(xt, LRELU_SLOPE)
|
| 306 |
+
if x_mask is not None:
|
| 307 |
+
xt = xt * x_mask
|
| 308 |
+
xt = c2(xt)
|
| 309 |
+
x = xt + x
|
| 310 |
+
if x_mask is not None:
|
| 311 |
+
x = x * x_mask
|
| 312 |
+
return x
|
| 313 |
+
|
| 314 |
+
def remove_weight_norm(self):
|
| 315 |
+
for l in self.convs1:
|
| 316 |
+
remove_weight_norm(l)
|
| 317 |
+
for l in self.convs2:
|
| 318 |
+
remove_weight_norm(l)
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
class ResBlock2(torch.nn.Module):
|
| 322 |
+
def __init__(self, channels, kernel_size=3, dilation=(1, 3)):
|
| 323 |
+
super(ResBlock2, self).__init__()
|
| 324 |
+
self.convs = nn.ModuleList(
|
| 325 |
+
[
|
| 326 |
+
weight_norm(
|
| 327 |
+
Conv1d(
|
| 328 |
+
channels,
|
| 329 |
+
channels,
|
| 330 |
+
kernel_size,
|
| 331 |
+
1,
|
| 332 |
+
dilation=dilation[0],
|
| 333 |
+
padding=get_padding(kernel_size, dilation[0]),
|
| 334 |
+
)
|
| 335 |
+
),
|
| 336 |
+
weight_norm(
|
| 337 |
+
Conv1d(
|
| 338 |
+
channels,
|
| 339 |
+
channels,
|
| 340 |
+
kernel_size,
|
| 341 |
+
1,
|
| 342 |
+
dilation=dilation[1],
|
| 343 |
+
padding=get_padding(kernel_size, dilation[1]),
|
| 344 |
+
)
|
| 345 |
+
),
|
| 346 |
+
]
|
| 347 |
+
)
|
| 348 |
+
self.convs.apply(init_weights)
|
| 349 |
+
|
| 350 |
+
def forward(self, x, x_mask=None):
|
| 351 |
+
for c in self.convs:
|
| 352 |
+
xt = F.leaky_relu(x, LRELU_SLOPE)
|
| 353 |
+
if x_mask is not None:
|
| 354 |
+
xt = xt * x_mask
|
| 355 |
+
xt = c(xt)
|
| 356 |
+
x = xt + x
|
| 357 |
+
if x_mask is not None:
|
| 358 |
+
x = x * x_mask
|
| 359 |
+
return x
|
| 360 |
+
|
| 361 |
+
def remove_weight_norm(self):
|
| 362 |
+
for l in self.convs:
|
| 363 |
+
remove_weight_norm(l)
|
| 364 |
+
|
| 365 |
+
|
| 366 |
+
class Log(nn.Module):
|
| 367 |
+
def forward(self, x, x_mask, reverse=False, **kwargs):
|
| 368 |
+
if not reverse:
|
| 369 |
+
y = torch.log(torch.clamp_min(x, 1e-5)) * x_mask
|
| 370 |
+
logdet = torch.sum(-y, [1, 2])
|
| 371 |
+
return y, logdet
|
| 372 |
+
else:
|
| 373 |
+
x = torch.exp(x) * x_mask
|
| 374 |
+
return x
|
| 375 |
+
|
| 376 |
+
|
| 377 |
+
class Flip(nn.Module):
|
| 378 |
+
def forward(self, x, *args, reverse=False, **kwargs):
|
| 379 |
+
x = torch.flip(x, [1])
|
| 380 |
+
if not reverse:
|
| 381 |
+
logdet = torch.zeros(x.size(0)).to(dtype=x.dtype, device=x.device)
|
| 382 |
+
return x, logdet
|
| 383 |
+
else:
|
| 384 |
+
return x
|
| 385 |
+
|
| 386 |
+
|
| 387 |
+
class ElementwiseAffine(nn.Module):
|
| 388 |
+
def __init__(self, channels):
|
| 389 |
+
super().__init__()
|
| 390 |
+
self.channels = channels
|
| 391 |
+
self.m = nn.Parameter(torch.zeros(channels, 1))
|
| 392 |
+
self.logs = nn.Parameter(torch.zeros(channels, 1))
|
| 393 |
+
|
| 394 |
+
def forward(self, x, x_mask, reverse=False, **kwargs):
|
| 395 |
+
if not reverse:
|
| 396 |
+
y = self.m + torch.exp(self.logs) * x
|
| 397 |
+
y = y * x_mask
|
| 398 |
+
logdet = torch.sum(self.logs * x_mask, [1, 2])
|
| 399 |
+
return y, logdet
|
| 400 |
+
else:
|
| 401 |
+
x = (x - self.m) * torch.exp(-self.logs) * x_mask
|
| 402 |
+
return x
|
| 403 |
+
|
| 404 |
+
|
| 405 |
+
class ResidualCouplingLayer(nn.Module):
|
| 406 |
+
def __init__(
|
| 407 |
+
self,
|
| 408 |
+
channels,
|
| 409 |
+
hidden_channels,
|
| 410 |
+
kernel_size,
|
| 411 |
+
dilation_rate,
|
| 412 |
+
n_layers,
|
| 413 |
+
p_dropout=0,
|
| 414 |
+
gin_channels=0,
|
| 415 |
+
mean_only=False,
|
| 416 |
+
):
|
| 417 |
+
assert channels % 2 == 0, "channels should be divisible by 2"
|
| 418 |
+
super().__init__()
|
| 419 |
+
self.channels = channels
|
| 420 |
+
self.hidden_channels = hidden_channels
|
| 421 |
+
self.kernel_size = kernel_size
|
| 422 |
+
self.dilation_rate = dilation_rate
|
| 423 |
+
self.n_layers = n_layers
|
| 424 |
+
self.half_channels = channels // 2
|
| 425 |
+
self.mean_only = mean_only
|
| 426 |
+
|
| 427 |
+
self.pre = nn.Conv1d(self.half_channels, hidden_channels, 1)
|
| 428 |
+
self.enc = WN(
|
| 429 |
+
hidden_channels,
|
| 430 |
+
kernel_size,
|
| 431 |
+
dilation_rate,
|
| 432 |
+
n_layers,
|
| 433 |
+
p_dropout=p_dropout,
|
| 434 |
+
gin_channels=gin_channels,
|
| 435 |
+
)
|
| 436 |
+
self.post = nn.Conv1d(hidden_channels, self.half_channels * (2 - mean_only), 1)
|
| 437 |
+
self.post.weight.data.zero_()
|
| 438 |
+
self.post.bias.data.zero_()
|
| 439 |
+
|
| 440 |
+
def forward(self, x, x_mask, g=None, reverse=False):
|
| 441 |
+
x0, x1 = torch.split(x, [self.half_channels] * 2, 1)
|
| 442 |
+
h = self.pre(x0) * x_mask
|
| 443 |
+
h = self.enc(h, x_mask, g=g)
|
| 444 |
+
stats = self.post(h) * x_mask
|
| 445 |
+
if not self.mean_only:
|
| 446 |
+
m, logs = torch.split(stats, [self.half_channels] * 2, 1)
|
| 447 |
+
else:
|
| 448 |
+
m = stats
|
| 449 |
+
logs = torch.zeros_like(m)
|
| 450 |
+
|
| 451 |
+
if not reverse:
|
| 452 |
+
x1 = m + x1 * torch.exp(logs) * x_mask
|
| 453 |
+
x = torch.cat([x0, x1], 1)
|
| 454 |
+
logdet = torch.sum(logs, [1, 2])
|
| 455 |
+
return x, logdet
|
| 456 |
+
else:
|
| 457 |
+
x1 = (x1 - m) * torch.exp(-logs) * x_mask
|
| 458 |
+
x = torch.cat([x0, x1], 1)
|
| 459 |
+
return x
|
| 460 |
+
|
| 461 |
+
def remove_weight_norm(self):
|
| 462 |
+
self.enc.remove_weight_norm()
|
| 463 |
+
|
| 464 |
+
|
| 465 |
+
class ConvFlow(nn.Module):
|
| 466 |
+
def __init__(
|
| 467 |
+
self,
|
| 468 |
+
in_channels,
|
| 469 |
+
filter_channels,
|
| 470 |
+
kernel_size,
|
| 471 |
+
n_layers,
|
| 472 |
+
num_bins=10,
|
| 473 |
+
tail_bound=5.0,
|
| 474 |
+
):
|
| 475 |
+
super().__init__()
|
| 476 |
+
self.in_channels = in_channels
|
| 477 |
+
self.filter_channels = filter_channels
|
| 478 |
+
self.kernel_size = kernel_size
|
| 479 |
+
self.n_layers = n_layers
|
| 480 |
+
self.num_bins = num_bins
|
| 481 |
+
self.tail_bound = tail_bound
|
| 482 |
+
self.half_channels = in_channels // 2
|
| 483 |
+
|
| 484 |
+
self.pre = nn.Conv1d(self.half_channels, filter_channels, 1)
|
| 485 |
+
self.convs = DDSConv(filter_channels, kernel_size, n_layers, p_dropout=0.0)
|
| 486 |
+
self.proj = nn.Conv1d(
|
| 487 |
+
filter_channels, self.half_channels * (num_bins * 3 - 1), 1
|
| 488 |
+
)
|
| 489 |
+
self.proj.weight.data.zero_()
|
| 490 |
+
self.proj.bias.data.zero_()
|
| 491 |
+
|
| 492 |
+
def forward(self, x, x_mask, g=None, reverse=False):
|
| 493 |
+
x0, x1 = torch.split(x, [self.half_channels] * 2, 1)
|
| 494 |
+
h = self.pre(x0)
|
| 495 |
+
h = self.convs(h, x_mask, g=g)
|
| 496 |
+
h = self.proj(h) * x_mask
|
| 497 |
+
|
| 498 |
+
b, c, t = x0.shape
|
| 499 |
+
h = h.reshape(b, c, -1, t).permute(0, 1, 3, 2) # [b, cx?, t] -> [b, c, t, ?]
|
| 500 |
+
|
| 501 |
+
unnormalized_widths = h[..., : self.num_bins] / math.sqrt(self.filter_channels)
|
| 502 |
+
unnormalized_heights = h[..., self.num_bins : 2 * self.num_bins] / math.sqrt(
|
| 503 |
+
self.filter_channels
|
| 504 |
+
)
|
| 505 |
+
unnormalized_derivatives = h[..., 2 * self.num_bins :]
|
| 506 |
+
|
| 507 |
+
x1, logabsdet = piecewise_rational_quadratic_transform(
|
| 508 |
+
x1,
|
| 509 |
+
unnormalized_widths,
|
| 510 |
+
unnormalized_heights,
|
| 511 |
+
unnormalized_derivatives,
|
| 512 |
+
inverse=reverse,
|
| 513 |
+
tails="linear",
|
| 514 |
+
tail_bound=self.tail_bound,
|
| 515 |
+
)
|
| 516 |
+
|
| 517 |
+
x = torch.cat([x0, x1], 1) * x_mask
|
| 518 |
+
logdet = torch.sum(logabsdet * x_mask, [1, 2])
|
| 519 |
+
if not reverse:
|
| 520 |
+
return x, logdet
|
| 521 |
+
else:
|
| 522 |
+
return x
|
lib/infer_pack/modules/F0Predictor/DioF0Predictor.py
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from lib.infer_pack.modules.F0Predictor.F0Predictor import F0Predictor
|
| 2 |
+
import pyworld
|
| 3 |
+
import numpy as np
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class DioF0Predictor(F0Predictor):
|
| 7 |
+
def __init__(self, hop_length=512, f0_min=50, f0_max=1100, sampling_rate=44100):
|
| 8 |
+
self.hop_length = hop_length
|
| 9 |
+
self.f0_min = f0_min
|
| 10 |
+
self.f0_max = f0_max
|
| 11 |
+
self.sampling_rate = sampling_rate
|
| 12 |
+
|
| 13 |
+
def interpolate_f0(self, f0):
|
| 14 |
+
"""
|
| 15 |
+
对F0进行插值处理
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
data = np.reshape(f0, (f0.size, 1))
|
| 19 |
+
|
| 20 |
+
vuv_vector = np.zeros((data.size, 1), dtype=np.float32)
|
| 21 |
+
vuv_vector[data > 0.0] = 1.0
|
| 22 |
+
vuv_vector[data <= 0.0] = 0.0
|
| 23 |
+
|
| 24 |
+
ip_data = data
|
| 25 |
+
|
| 26 |
+
frame_number = data.size
|
| 27 |
+
last_value = 0.0
|
| 28 |
+
for i in range(frame_number):
|
| 29 |
+
if data[i] <= 0.0:
|
| 30 |
+
j = i + 1
|
| 31 |
+
for j in range(i + 1, frame_number):
|
| 32 |
+
if data[j] > 0.0:
|
| 33 |
+
break
|
| 34 |
+
if j < frame_number - 1:
|
| 35 |
+
if last_value > 0.0:
|
| 36 |
+
step = (data[j] - data[i - 1]) / float(j - i)
|
| 37 |
+
for k in range(i, j):
|
| 38 |
+
ip_data[k] = data[i - 1] + step * (k - i + 1)
|
| 39 |
+
else:
|
| 40 |
+
for k in range(i, j):
|
| 41 |
+
ip_data[k] = data[j]
|
| 42 |
+
else:
|
| 43 |
+
for k in range(i, frame_number):
|
| 44 |
+
ip_data[k] = last_value
|
| 45 |
+
else:
|
| 46 |
+
ip_data[i] = data[i] # 这里可能存在一个没有必要的拷贝
|
| 47 |
+
last_value = data[i]
|
| 48 |
+
|
| 49 |
+
return ip_data[:, 0], vuv_vector[:, 0]
|
| 50 |
+
|
| 51 |
+
def resize_f0(self, x, target_len):
|
| 52 |
+
source = np.array(x)
|
| 53 |
+
source[source < 0.001] = np.nan
|
| 54 |
+
target = np.interp(
|
| 55 |
+
np.arange(0, len(source) * target_len, len(source)) / target_len,
|
| 56 |
+
np.arange(0, len(source)),
|
| 57 |
+
source,
|
| 58 |
+
)
|
| 59 |
+
res = np.nan_to_num(target)
|
| 60 |
+
return res
|
| 61 |
+
|
| 62 |
+
def compute_f0(self, wav, p_len=None):
|
| 63 |
+
if p_len is None:
|
| 64 |
+
p_len = wav.shape[0] // self.hop_length
|
| 65 |
+
f0, t = pyworld.dio(
|
| 66 |
+
wav.astype(np.double),
|
| 67 |
+
fs=self.sampling_rate,
|
| 68 |
+
f0_floor=self.f0_min,
|
| 69 |
+
f0_ceil=self.f0_max,
|
| 70 |
+
frame_period=1000 * self.hop_length / self.sampling_rate,
|
| 71 |
+
)
|
| 72 |
+
f0 = pyworld.stonemask(wav.astype(np.double), f0, t, self.sampling_rate)
|
| 73 |
+
for index, pitch in enumerate(f0):
|
| 74 |
+
f0[index] = round(pitch, 1)
|
| 75 |
+
return self.interpolate_f0(self.resize_f0(f0, p_len))[0]
|
| 76 |
+
|
| 77 |
+
def compute_f0_uv(self, wav, p_len=None):
|
| 78 |
+
if p_len is None:
|
| 79 |
+
p_len = wav.shape[0] // self.hop_length
|
| 80 |
+
f0, t = pyworld.dio(
|
| 81 |
+
wav.astype(np.double),
|
| 82 |
+
fs=self.sampling_rate,
|
| 83 |
+
f0_floor=self.f0_min,
|
| 84 |
+
f0_ceil=self.f0_max,
|
| 85 |
+
frame_period=1000 * self.hop_length / self.sampling_rate,
|
| 86 |
+
)
|
| 87 |
+
f0 = pyworld.stonemask(wav.astype(np.double), f0, t, self.sampling_rate)
|
| 88 |
+
for index, pitch in enumerate(f0):
|
| 89 |
+
f0[index] = round(pitch, 1)
|
| 90 |
+
return self.interpolate_f0(self.resize_f0(f0, p_len))
|
lib/infer_pack/modules/F0Predictor/F0Predictor.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
class F0Predictor(object):
|
| 2 |
+
def compute_f0(self, wav, p_len):
|
| 3 |
+
"""
|
| 4 |
+
input: wav:[signal_length]
|
| 5 |
+
p_len:int
|
| 6 |
+
output: f0:[signal_length//hop_length]
|
| 7 |
+
"""
|
| 8 |
+
pass
|
| 9 |
+
|
| 10 |
+
def compute_f0_uv(self, wav, p_len):
|
| 11 |
+
"""
|
| 12 |
+
input: wav:[signal_length]
|
| 13 |
+
p_len:int
|
| 14 |
+
output: f0:[signal_length//hop_length],uv:[signal_length//hop_length]
|
| 15 |
+
"""
|
| 16 |
+
pass
|
lib/infer_pack/modules/F0Predictor/HarvestF0Predictor.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from lib.infer_pack.modules.F0Predictor.F0Predictor import F0Predictor
|
| 2 |
+
import pyworld
|
| 3 |
+
import numpy as np
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class HarvestF0Predictor(F0Predictor):
|
| 7 |
+
def __init__(self, hop_length=512, f0_min=50, f0_max=1100, sampling_rate=44100):
|
| 8 |
+
self.hop_length = hop_length
|
| 9 |
+
self.f0_min = f0_min
|
| 10 |
+
self.f0_max = f0_max
|
| 11 |
+
self.sampling_rate = sampling_rate
|
| 12 |
+
|
| 13 |
+
def interpolate_f0(self, f0):
|
| 14 |
+
"""
|
| 15 |
+
对F0进行插值处理
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
data = np.reshape(f0, (f0.size, 1))
|
| 19 |
+
|
| 20 |
+
vuv_vector = np.zeros((data.size, 1), dtype=np.float32)
|
| 21 |
+
vuv_vector[data > 0.0] = 1.0
|
| 22 |
+
vuv_vector[data <= 0.0] = 0.0
|
| 23 |
+
|
| 24 |
+
ip_data = data
|
| 25 |
+
|
| 26 |
+
frame_number = data.size
|
| 27 |
+
last_value = 0.0
|
| 28 |
+
for i in range(frame_number):
|
| 29 |
+
if data[i] <= 0.0:
|
| 30 |
+
j = i + 1
|
| 31 |
+
for j in range(i + 1, frame_number):
|
| 32 |
+
if data[j] > 0.0:
|
| 33 |
+
break
|
| 34 |
+
if j < frame_number - 1:
|
| 35 |
+
if last_value > 0.0:
|
| 36 |
+
step = (data[j] - data[i - 1]) / float(j - i)
|
| 37 |
+
for k in range(i, j):
|
| 38 |
+
ip_data[k] = data[i - 1] + step * (k - i + 1)
|
| 39 |
+
else:
|
| 40 |
+
for k in range(i, j):
|
| 41 |
+
ip_data[k] = data[j]
|
| 42 |
+
else:
|
| 43 |
+
for k in range(i, frame_number):
|
| 44 |
+
ip_data[k] = last_value
|
| 45 |
+
else:
|
| 46 |
+
ip_data[i] = data[i] # 这里可能存在一个没有必要的拷贝
|
| 47 |
+
last_value = data[i]
|
| 48 |
+
|
| 49 |
+
return ip_data[:, 0], vuv_vector[:, 0]
|
| 50 |
+
|
| 51 |
+
def resize_f0(self, x, target_len):
|
| 52 |
+
source = np.array(x)
|
| 53 |
+
source[source < 0.001] = np.nan
|
| 54 |
+
target = np.interp(
|
| 55 |
+
np.arange(0, len(source) * target_len, len(source)) / target_len,
|
| 56 |
+
np.arange(0, len(source)),
|
| 57 |
+
source,
|
| 58 |
+
)
|
| 59 |
+
res = np.nan_to_num(target)
|
| 60 |
+
return res
|
| 61 |
+
|
| 62 |
+
def compute_f0(self, wav, p_len=None):
|
| 63 |
+
if p_len is None:
|
| 64 |
+
p_len = wav.shape[0] // self.hop_length
|
| 65 |
+
f0, t = pyworld.harvest(
|
| 66 |
+
wav.astype(np.double),
|
| 67 |
+
fs=self.hop_length,
|
| 68 |
+
f0_ceil=self.f0_max,
|
| 69 |
+
f0_floor=self.f0_min,
|
| 70 |
+
frame_period=1000 * self.hop_length / self.sampling_rate,
|
| 71 |
+
)
|
| 72 |
+
f0 = pyworld.stonemask(wav.astype(np.double), f0, t, self.fs)
|
| 73 |
+
return self.interpolate_f0(self.resize_f0(f0, p_len))[0]
|
| 74 |
+
|
| 75 |
+
def compute_f0_uv(self, wav, p_len=None):
|
| 76 |
+
if p_len is None:
|
| 77 |
+
p_len = wav.shape[0] // self.hop_length
|
| 78 |
+
f0, t = pyworld.harvest(
|
| 79 |
+
wav.astype(np.double),
|
| 80 |
+
fs=self.sampling_rate,
|
| 81 |
+
f0_floor=self.f0_min,
|
| 82 |
+
f0_ceil=self.f0_max,
|
| 83 |
+
frame_period=1000 * self.hop_length / self.sampling_rate,
|
| 84 |
+
)
|
| 85 |
+
f0 = pyworld.stonemask(wav.astype(np.double), f0, t, self.sampling_rate)
|
| 86 |
+
return self.interpolate_f0(self.resize_f0(f0, p_len))
|
lib/infer_pack/modules/F0Predictor/PMF0Predictor.py
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from lib.infer_pack.modules.F0Predictor.F0Predictor import F0Predictor
|
| 2 |
+
import parselmouth
|
| 3 |
+
import numpy as np
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class PMF0Predictor(F0Predictor):
|
| 7 |
+
def __init__(self, hop_length=512, f0_min=50, f0_max=1100, sampling_rate=44100):
|
| 8 |
+
self.hop_length = hop_length
|
| 9 |
+
self.f0_min = f0_min
|
| 10 |
+
self.f0_max = f0_max
|
| 11 |
+
self.sampling_rate = sampling_rate
|
| 12 |
+
|
| 13 |
+
def interpolate_f0(self, f0):
|
| 14 |
+
"""
|
| 15 |
+
对F0进行插值处理
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
data = np.reshape(f0, (f0.size, 1))
|
| 19 |
+
|
| 20 |
+
vuv_vector = np.zeros((data.size, 1), dtype=np.float32)
|
| 21 |
+
vuv_vector[data > 0.0] = 1.0
|
| 22 |
+
vuv_vector[data <= 0.0] = 0.0
|
| 23 |
+
|
| 24 |
+
ip_data = data
|
| 25 |
+
|
| 26 |
+
frame_number = data.size
|
| 27 |
+
last_value = 0.0
|
| 28 |
+
for i in range(frame_number):
|
| 29 |
+
if data[i] <= 0.0:
|
| 30 |
+
j = i + 1
|
| 31 |
+
for j in range(i + 1, frame_number):
|
| 32 |
+
if data[j] > 0.0:
|
| 33 |
+
break
|
| 34 |
+
if j < frame_number - 1:
|
| 35 |
+
if last_value > 0.0:
|
| 36 |
+
step = (data[j] - data[i - 1]) / float(j - i)
|
| 37 |
+
for k in range(i, j):
|
| 38 |
+
ip_data[k] = data[i - 1] + step * (k - i + 1)
|
| 39 |
+
else:
|
| 40 |
+
for k in range(i, j):
|
| 41 |
+
ip_data[k] = data[j]
|
| 42 |
+
else:
|
| 43 |
+
for k in range(i, frame_number):
|
| 44 |
+
ip_data[k] = last_value
|
| 45 |
+
else:
|
| 46 |
+
ip_data[i] = data[i] # 这里可能存在一个没有必要的拷贝
|
| 47 |
+
last_value = data[i]
|
| 48 |
+
|
| 49 |
+
return ip_data[:, 0], vuv_vector[:, 0]
|
| 50 |
+
|
| 51 |
+
def compute_f0(self, wav, p_len=None):
|
| 52 |
+
x = wav
|
| 53 |
+
if p_len is None:
|
| 54 |
+
p_len = x.shape[0] // self.hop_length
|
| 55 |
+
else:
|
| 56 |
+
assert abs(p_len - x.shape[0] // self.hop_length) < 4, "pad length error"
|
| 57 |
+
time_step = self.hop_length / self.sampling_rate * 1000
|
| 58 |
+
f0 = (
|
| 59 |
+
parselmouth.Sound(x, self.sampling_rate)
|
| 60 |
+
.to_pitch_ac(
|
| 61 |
+
time_step=time_step / 1000,
|
| 62 |
+
voicing_threshold=0.6,
|
| 63 |
+
pitch_floor=self.f0_min,
|
| 64 |
+
pitch_ceiling=self.f0_max,
|
| 65 |
+
)
|
| 66 |
+
.selected_array["frequency"]
|
| 67 |
+
)
|
| 68 |
+
|
| 69 |
+
pad_size = (p_len - len(f0) + 1) // 2
|
| 70 |
+
if pad_size > 0 or p_len - len(f0) - pad_size > 0:
|
| 71 |
+
f0 = np.pad(f0, [[pad_size, p_len - len(f0) - pad_size]], mode="constant")
|
| 72 |
+
f0, uv = self.interpolate_f0(f0)
|
| 73 |
+
return f0
|
| 74 |
+
|
| 75 |
+
def compute_f0_uv(self, wav, p_len=None):
|
| 76 |
+
x = wav
|
| 77 |
+
if p_len is None:
|
| 78 |
+
p_len = x.shape[0] // self.hop_length
|
| 79 |
+
else:
|
| 80 |
+
assert abs(p_len - x.shape[0] // self.hop_length) < 4, "pad length error"
|
| 81 |
+
time_step = self.hop_length / self.sampling_rate * 1000
|
| 82 |
+
f0 = (
|
| 83 |
+
parselmouth.Sound(x, self.sampling_rate)
|
| 84 |
+
.to_pitch_ac(
|
| 85 |
+
time_step=time_step / 1000,
|
| 86 |
+
voicing_threshold=0.6,
|
| 87 |
+
pitch_floor=self.f0_min,
|
| 88 |
+
pitch_ceiling=self.f0_max,
|
| 89 |
+
)
|
| 90 |
+
.selected_array["frequency"]
|
| 91 |
+
)
|
| 92 |
+
|
| 93 |
+
pad_size = (p_len - len(f0) + 1) // 2
|
| 94 |
+
if pad_size > 0 or p_len - len(f0) - pad_size > 0:
|
| 95 |
+
f0 = np.pad(f0, [[pad_size, p_len - len(f0) - pad_size]], mode="constant")
|
| 96 |
+
f0, uv = self.interpolate_f0(f0)
|
| 97 |
+
return f0, uv
|
lib/infer_pack/modules/F0Predictor/__init__.py
ADDED
|
File without changes
|
lib/infer_pack/onnx_inference.py
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import onnxruntime
|
| 2 |
+
import librosa
|
| 3 |
+
import numpy as np
|
| 4 |
+
import soundfile
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class ContentVec:
|
| 8 |
+
def __init__(self, vec_path="pretrained/vec-768-layer-12.onnx", device=None):
|
| 9 |
+
print("load model(s) from {}".format(vec_path))
|
| 10 |
+
if device == "cpu" or device is None:
|
| 11 |
+
providers = ["CPUExecutionProvider"]
|
| 12 |
+
elif device == "cuda":
|
| 13 |
+
providers = ["CUDAExecutionProvider", "CPUExecutionProvider"]
|
| 14 |
+
elif device == "dml":
|
| 15 |
+
providers = ["DmlExecutionProvider"]
|
| 16 |
+
else:
|
| 17 |
+
raise RuntimeError("Unsportted Device")
|
| 18 |
+
self.model = onnxruntime.InferenceSession(vec_path, providers=providers)
|
| 19 |
+
|
| 20 |
+
def __call__(self, wav):
|
| 21 |
+
return self.forward(wav)
|
| 22 |
+
|
| 23 |
+
def forward(self, wav):
|
| 24 |
+
feats = wav
|
| 25 |
+
if feats.ndim == 2: # double channels
|
| 26 |
+
feats = feats.mean(-1)
|
| 27 |
+
assert feats.ndim == 1, feats.ndim
|
| 28 |
+
feats = np.expand_dims(np.expand_dims(feats, 0), 0)
|
| 29 |
+
onnx_input = {self.model.get_inputs()[0].name: feats}
|
| 30 |
+
logits = self.model.run(None, onnx_input)[0]
|
| 31 |
+
return logits.transpose(0, 2, 1)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def get_f0_predictor(f0_predictor, hop_length, sampling_rate, **kargs):
|
| 35 |
+
if f0_predictor == "pm":
|
| 36 |
+
from lib.infer_pack.modules.F0Predictor.PMF0Predictor import PMF0Predictor
|
| 37 |
+
|
| 38 |
+
f0_predictor_object = PMF0Predictor(
|
| 39 |
+
hop_length=hop_length, sampling_rate=sampling_rate
|
| 40 |
+
)
|
| 41 |
+
elif f0_predictor == "harvest":
|
| 42 |
+
from lib.infer_pack.modules.F0Predictor.HarvestF0Predictor import (
|
| 43 |
+
HarvestF0Predictor,
|
| 44 |
+
)
|
| 45 |
+
|
| 46 |
+
f0_predictor_object = HarvestF0Predictor(
|
| 47 |
+
hop_length=hop_length, sampling_rate=sampling_rate
|
| 48 |
+
)
|
| 49 |
+
elif f0_predictor == "dio":
|
| 50 |
+
from lib.infer_pack.modules.F0Predictor.DioF0Predictor import DioF0Predictor
|
| 51 |
+
|
| 52 |
+
f0_predictor_object = DioF0Predictor(
|
| 53 |
+
hop_length=hop_length, sampling_rate=sampling_rate
|
| 54 |
+
)
|
| 55 |
+
else:
|
| 56 |
+
raise Exception("Unknown f0 predictor")
|
| 57 |
+
return f0_predictor_object
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
class OnnxRVC:
|
| 61 |
+
def __init__(
|
| 62 |
+
self,
|
| 63 |
+
model_path,
|
| 64 |
+
sr=40000,
|
| 65 |
+
hop_size=512,
|
| 66 |
+
vec_path="vec-768-layer-12",
|
| 67 |
+
device="cpu",
|
| 68 |
+
):
|
| 69 |
+
vec_path = f"pretrained/{vec_path}.onnx"
|
| 70 |
+
self.vec_model = ContentVec(vec_path, device)
|
| 71 |
+
if device == "cpu" or device is None:
|
| 72 |
+
providers = ["CPUExecutionProvider"]
|
| 73 |
+
elif device == "cuda":
|
| 74 |
+
providers = ["CUDAExecutionProvider", "CPUExecutionProvider"]
|
| 75 |
+
elif device == "dml":
|
| 76 |
+
providers = ["DmlExecutionProvider"]
|
| 77 |
+
else:
|
| 78 |
+
raise RuntimeError("Unsportted Device")
|
| 79 |
+
self.model = onnxruntime.InferenceSession(model_path, providers=providers)
|
| 80 |
+
self.sampling_rate = sr
|
| 81 |
+
self.hop_size = hop_size
|
| 82 |
+
|
| 83 |
+
def forward(self, hubert, hubert_length, pitch, pitchf, ds, rnd):
|
| 84 |
+
onnx_input = {
|
| 85 |
+
self.model.get_inputs()[0].name: hubert,
|
| 86 |
+
self.model.get_inputs()[1].name: hubert_length,
|
| 87 |
+
self.model.get_inputs()[2].name: pitch,
|
| 88 |
+
self.model.get_inputs()[3].name: pitchf,
|
| 89 |
+
self.model.get_inputs()[4].name: ds,
|
| 90 |
+
self.model.get_inputs()[5].name: rnd,
|
| 91 |
+
}
|
| 92 |
+
return (self.model.run(None, onnx_input)[0] * 32767).astype(np.int16)
|
| 93 |
+
|
| 94 |
+
def inference(
|
| 95 |
+
self,
|
| 96 |
+
raw_path,
|
| 97 |
+
sid,
|
| 98 |
+
f0_method="dio",
|
| 99 |
+
f0_up_key=0,
|
| 100 |
+
pad_time=0.5,
|
| 101 |
+
cr_threshold=0.02,
|
| 102 |
+
):
|
| 103 |
+
f0_min = 50
|
| 104 |
+
f0_max = 1100
|
| 105 |
+
f0_mel_min = 1127 * np.log(1 + f0_min / 700)
|
| 106 |
+
f0_mel_max = 1127 * np.log(1 + f0_max / 700)
|
| 107 |
+
f0_predictor = get_f0_predictor(
|
| 108 |
+
f0_method,
|
| 109 |
+
hop_length=self.hop_size,
|
| 110 |
+
sampling_rate=self.sampling_rate,
|
| 111 |
+
threshold=cr_threshold,
|
| 112 |
+
)
|
| 113 |
+
wav, sr = librosa.load(raw_path, sr=self.sampling_rate)
|
| 114 |
+
org_length = len(wav)
|
| 115 |
+
if org_length / sr > 50.0:
|
| 116 |
+
raise RuntimeError("Reached Max Length")
|
| 117 |
+
|
| 118 |
+
wav16k = librosa.resample(wav, orig_sr=self.sampling_rate, target_sr=16000)
|
| 119 |
+
wav16k = wav16k
|
| 120 |
+
|
| 121 |
+
hubert = self.vec_model(wav16k)
|
| 122 |
+
hubert = np.repeat(hubert, 2, axis=2).transpose(0, 2, 1).astype(np.float32)
|
| 123 |
+
hubert_length = hubert.shape[1]
|
| 124 |
+
|
| 125 |
+
pitchf = f0_predictor.compute_f0(wav, hubert_length)
|
| 126 |
+
pitchf = pitchf * 2 ** (f0_up_key / 12)
|
| 127 |
+
pitch = pitchf.copy()
|
| 128 |
+
f0_mel = 1127 * np.log(1 + pitch / 700)
|
| 129 |
+
f0_mel[f0_mel > 0] = (f0_mel[f0_mel > 0] - f0_mel_min) * 254 / (
|
| 130 |
+
f0_mel_max - f0_mel_min
|
| 131 |
+
) + 1
|
| 132 |
+
f0_mel[f0_mel <= 1] = 1
|
| 133 |
+
f0_mel[f0_mel > 255] = 255
|
| 134 |
+
pitch = np.rint(f0_mel).astype(np.int64)
|
| 135 |
+
|
| 136 |
+
pitchf = pitchf.reshape(1, len(pitchf)).astype(np.float32)
|
| 137 |
+
pitch = pitch.reshape(1, len(pitch))
|
| 138 |
+
ds = np.array([sid]).astype(np.int64)
|
| 139 |
+
|
| 140 |
+
rnd = np.random.randn(1, 192, hubert_length).astype(np.float32)
|
| 141 |
+
hubert_length = np.array([hubert_length]).astype(np.int64)
|
| 142 |
+
|
| 143 |
+
out_wav = self.forward(hubert, hubert_length, pitch, pitchf, ds, rnd).squeeze()
|
| 144 |
+
out_wav = np.pad(out_wav, (0, 2 * self.hop_size), "constant")
|
| 145 |
+
return out_wav[0:org_length]
|
lib/infer_pack/transforms.py
ADDED
|
@@ -0,0 +1,209 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from torch.nn import functional as F
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
DEFAULT_MIN_BIN_WIDTH = 1e-3
|
| 8 |
+
DEFAULT_MIN_BIN_HEIGHT = 1e-3
|
| 9 |
+
DEFAULT_MIN_DERIVATIVE = 1e-3
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def piecewise_rational_quadratic_transform(
|
| 13 |
+
inputs,
|
| 14 |
+
unnormalized_widths,
|
| 15 |
+
unnormalized_heights,
|
| 16 |
+
unnormalized_derivatives,
|
| 17 |
+
inverse=False,
|
| 18 |
+
tails=None,
|
| 19 |
+
tail_bound=1.0,
|
| 20 |
+
min_bin_width=DEFAULT_MIN_BIN_WIDTH,
|
| 21 |
+
min_bin_height=DEFAULT_MIN_BIN_HEIGHT,
|
| 22 |
+
min_derivative=DEFAULT_MIN_DERIVATIVE,
|
| 23 |
+
):
|
| 24 |
+
if tails is None:
|
| 25 |
+
spline_fn = rational_quadratic_spline
|
| 26 |
+
spline_kwargs = {}
|
| 27 |
+
else:
|
| 28 |
+
spline_fn = unconstrained_rational_quadratic_spline
|
| 29 |
+
spline_kwargs = {"tails": tails, "tail_bound": tail_bound}
|
| 30 |
+
|
| 31 |
+
outputs, logabsdet = spline_fn(
|
| 32 |
+
inputs=inputs,
|
| 33 |
+
unnormalized_widths=unnormalized_widths,
|
| 34 |
+
unnormalized_heights=unnormalized_heights,
|
| 35 |
+
unnormalized_derivatives=unnormalized_derivatives,
|
| 36 |
+
inverse=inverse,
|
| 37 |
+
min_bin_width=min_bin_width,
|
| 38 |
+
min_bin_height=min_bin_height,
|
| 39 |
+
min_derivative=min_derivative,
|
| 40 |
+
**spline_kwargs
|
| 41 |
+
)
|
| 42 |
+
return outputs, logabsdet
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def searchsorted(bin_locations, inputs, eps=1e-6):
|
| 46 |
+
bin_locations[..., -1] += eps
|
| 47 |
+
return torch.sum(inputs[..., None] >= bin_locations, dim=-1) - 1
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def unconstrained_rational_quadratic_spline(
|
| 51 |
+
inputs,
|
| 52 |
+
unnormalized_widths,
|
| 53 |
+
unnormalized_heights,
|
| 54 |
+
unnormalized_derivatives,
|
| 55 |
+
inverse=False,
|
| 56 |
+
tails="linear",
|
| 57 |
+
tail_bound=1.0,
|
| 58 |
+
min_bin_width=DEFAULT_MIN_BIN_WIDTH,
|
| 59 |
+
min_bin_height=DEFAULT_MIN_BIN_HEIGHT,
|
| 60 |
+
min_derivative=DEFAULT_MIN_DERIVATIVE,
|
| 61 |
+
):
|
| 62 |
+
inside_interval_mask = (inputs >= -tail_bound) & (inputs <= tail_bound)
|
| 63 |
+
outside_interval_mask = ~inside_interval_mask
|
| 64 |
+
|
| 65 |
+
outputs = torch.zeros_like(inputs)
|
| 66 |
+
logabsdet = torch.zeros_like(inputs)
|
| 67 |
+
|
| 68 |
+
if tails == "linear":
|
| 69 |
+
unnormalized_derivatives = F.pad(unnormalized_derivatives, pad=(1, 1))
|
| 70 |
+
constant = np.log(np.exp(1 - min_derivative) - 1)
|
| 71 |
+
unnormalized_derivatives[..., 0] = constant
|
| 72 |
+
unnormalized_derivatives[..., -1] = constant
|
| 73 |
+
|
| 74 |
+
outputs[outside_interval_mask] = inputs[outside_interval_mask]
|
| 75 |
+
logabsdet[outside_interval_mask] = 0
|
| 76 |
+
else:
|
| 77 |
+
raise RuntimeError("{} tails are not implemented.".format(tails))
|
| 78 |
+
|
| 79 |
+
(
|
| 80 |
+
outputs[inside_interval_mask],
|
| 81 |
+
logabsdet[inside_interval_mask],
|
| 82 |
+
) = rational_quadratic_spline(
|
| 83 |
+
inputs=inputs[inside_interval_mask],
|
| 84 |
+
unnormalized_widths=unnormalized_widths[inside_interval_mask, :],
|
| 85 |
+
unnormalized_heights=unnormalized_heights[inside_interval_mask, :],
|
| 86 |
+
unnormalized_derivatives=unnormalized_derivatives[inside_interval_mask, :],
|
| 87 |
+
inverse=inverse,
|
| 88 |
+
left=-tail_bound,
|
| 89 |
+
right=tail_bound,
|
| 90 |
+
bottom=-tail_bound,
|
| 91 |
+
top=tail_bound,
|
| 92 |
+
min_bin_width=min_bin_width,
|
| 93 |
+
min_bin_height=min_bin_height,
|
| 94 |
+
min_derivative=min_derivative,
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
return outputs, logabsdet
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def rational_quadratic_spline(
|
| 101 |
+
inputs,
|
| 102 |
+
unnormalized_widths,
|
| 103 |
+
unnormalized_heights,
|
| 104 |
+
unnormalized_derivatives,
|
| 105 |
+
inverse=False,
|
| 106 |
+
left=0.0,
|
| 107 |
+
right=1.0,
|
| 108 |
+
bottom=0.0,
|
| 109 |
+
top=1.0,
|
| 110 |
+
min_bin_width=DEFAULT_MIN_BIN_WIDTH,
|
| 111 |
+
min_bin_height=DEFAULT_MIN_BIN_HEIGHT,
|
| 112 |
+
min_derivative=DEFAULT_MIN_DERIVATIVE,
|
| 113 |
+
):
|
| 114 |
+
if torch.min(inputs) < left or torch.max(inputs) > right:
|
| 115 |
+
raise ValueError("Input to a transform is not within its domain")
|
| 116 |
+
|
| 117 |
+
num_bins = unnormalized_widths.shape[-1]
|
| 118 |
+
|
| 119 |
+
if min_bin_width * num_bins > 1.0:
|
| 120 |
+
raise ValueError("Minimal bin width too large for the number of bins")
|
| 121 |
+
if min_bin_height * num_bins > 1.0:
|
| 122 |
+
raise ValueError("Minimal bin height too large for the number of bins")
|
| 123 |
+
|
| 124 |
+
widths = F.softmax(unnormalized_widths, dim=-1)
|
| 125 |
+
widths = min_bin_width + (1 - min_bin_width * num_bins) * widths
|
| 126 |
+
cumwidths = torch.cumsum(widths, dim=-1)
|
| 127 |
+
cumwidths = F.pad(cumwidths, pad=(1, 0), mode="constant", value=0.0)
|
| 128 |
+
cumwidths = (right - left) * cumwidths + left
|
| 129 |
+
cumwidths[..., 0] = left
|
| 130 |
+
cumwidths[..., -1] = right
|
| 131 |
+
widths = cumwidths[..., 1:] - cumwidths[..., :-1]
|
| 132 |
+
|
| 133 |
+
derivatives = min_derivative + F.softplus(unnormalized_derivatives)
|
| 134 |
+
|
| 135 |
+
heights = F.softmax(unnormalized_heights, dim=-1)
|
| 136 |
+
heights = min_bin_height + (1 - min_bin_height * num_bins) * heights
|
| 137 |
+
cumheights = torch.cumsum(heights, dim=-1)
|
| 138 |
+
cumheights = F.pad(cumheights, pad=(1, 0), mode="constant", value=0.0)
|
| 139 |
+
cumheights = (top - bottom) * cumheights + bottom
|
| 140 |
+
cumheights[..., 0] = bottom
|
| 141 |
+
cumheights[..., -1] = top
|
| 142 |
+
heights = cumheights[..., 1:] - cumheights[..., :-1]
|
| 143 |
+
|
| 144 |
+
if inverse:
|
| 145 |
+
bin_idx = searchsorted(cumheights, inputs)[..., None]
|
| 146 |
+
else:
|
| 147 |
+
bin_idx = searchsorted(cumwidths, inputs)[..., None]
|
| 148 |
+
|
| 149 |
+
input_cumwidths = cumwidths.gather(-1, bin_idx)[..., 0]
|
| 150 |
+
input_bin_widths = widths.gather(-1, bin_idx)[..., 0]
|
| 151 |
+
|
| 152 |
+
input_cumheights = cumheights.gather(-1, bin_idx)[..., 0]
|
| 153 |
+
delta = heights / widths
|
| 154 |
+
input_delta = delta.gather(-1, bin_idx)[..., 0]
|
| 155 |
+
|
| 156 |
+
input_derivatives = derivatives.gather(-1, bin_idx)[..., 0]
|
| 157 |
+
input_derivatives_plus_one = derivatives[..., 1:].gather(-1, bin_idx)[..., 0]
|
| 158 |
+
|
| 159 |
+
input_heights = heights.gather(-1, bin_idx)[..., 0]
|
| 160 |
+
|
| 161 |
+
if inverse:
|
| 162 |
+
a = (inputs - input_cumheights) * (
|
| 163 |
+
input_derivatives + input_derivatives_plus_one - 2 * input_delta
|
| 164 |
+
) + input_heights * (input_delta - input_derivatives)
|
| 165 |
+
b = input_heights * input_derivatives - (inputs - input_cumheights) * (
|
| 166 |
+
input_derivatives + input_derivatives_plus_one - 2 * input_delta
|
| 167 |
+
)
|
| 168 |
+
c = -input_delta * (inputs - input_cumheights)
|
| 169 |
+
|
| 170 |
+
discriminant = b.pow(2) - 4 * a * c
|
| 171 |
+
assert (discriminant >= 0).all()
|
| 172 |
+
|
| 173 |
+
root = (2 * c) / (-b - torch.sqrt(discriminant))
|
| 174 |
+
outputs = root * input_bin_widths + input_cumwidths
|
| 175 |
+
|
| 176 |
+
theta_one_minus_theta = root * (1 - root)
|
| 177 |
+
denominator = input_delta + (
|
| 178 |
+
(input_derivatives + input_derivatives_plus_one - 2 * input_delta)
|
| 179 |
+
* theta_one_minus_theta
|
| 180 |
+
)
|
| 181 |
+
derivative_numerator = input_delta.pow(2) * (
|
| 182 |
+
input_derivatives_plus_one * root.pow(2)
|
| 183 |
+
+ 2 * input_delta * theta_one_minus_theta
|
| 184 |
+
+ input_derivatives * (1 - root).pow(2)
|
| 185 |
+
)
|
| 186 |
+
logabsdet = torch.log(derivative_numerator) - 2 * torch.log(denominator)
|
| 187 |
+
|
| 188 |
+
return outputs, -logabsdet
|
| 189 |
+
else:
|
| 190 |
+
theta = (inputs - input_cumwidths) / input_bin_widths
|
| 191 |
+
theta_one_minus_theta = theta * (1 - theta)
|
| 192 |
+
|
| 193 |
+
numerator = input_heights * (
|
| 194 |
+
input_delta * theta.pow(2) + input_derivatives * theta_one_minus_theta
|
| 195 |
+
)
|
| 196 |
+
denominator = input_delta + (
|
| 197 |
+
(input_derivatives + input_derivatives_plus_one - 2 * input_delta)
|
| 198 |
+
* theta_one_minus_theta
|
| 199 |
+
)
|
| 200 |
+
outputs = input_cumheights + numerator / denominator
|
| 201 |
+
|
| 202 |
+
derivative_numerator = input_delta.pow(2) * (
|
| 203 |
+
input_derivatives_plus_one * theta.pow(2)
|
| 204 |
+
+ 2 * input_delta * theta_one_minus_theta
|
| 205 |
+
+ input_derivatives * (1 - theta).pow(2)
|
| 206 |
+
)
|
| 207 |
+
logabsdet = torch.log(derivative_numerator) - 2 * torch.log(denominator)
|
| 208 |
+
|
| 209 |
+
return outputs, logabsdet
|
node_modules/.bin/node-gyp-build
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/sh
|
| 2 |
+
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
|
| 3 |
+
|
| 4 |
+
case `uname` in
|
| 5 |
+
*CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;;
|
| 6 |
+
esac
|
| 7 |
+
|
| 8 |
+
if [ -x "$basedir/node" ]; then
|
| 9 |
+
exec "$basedir/node" "$basedir/../node-gyp-build/bin.js" "$@"
|
| 10 |
+
else
|
| 11 |
+
exec node "$basedir/../node-gyp-build/bin.js" "$@"
|
| 12 |
+
fi
|
node_modules/.bin/node-gyp-build-optional
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/sh
|
| 2 |
+
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
|
| 3 |
+
|
| 4 |
+
case `uname` in
|
| 5 |
+
*CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;;
|
| 6 |
+
esac
|
| 7 |
+
|
| 8 |
+
if [ -x "$basedir/node" ]; then
|
| 9 |
+
exec "$basedir/node" "$basedir/../node-gyp-build/optional.js" "$@"
|
| 10 |
+
else
|
| 11 |
+
exec node "$basedir/../node-gyp-build/optional.js" "$@"
|
| 12 |
+
fi
|
node_modules/.bin/node-gyp-build-optional.cmd
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
@ECHO off
|
| 2 |
+
GOTO start
|
| 3 |
+
:find_dp0
|
| 4 |
+
SET dp0=%~dp0
|
| 5 |
+
EXIT /b
|
| 6 |
+
:start
|
| 7 |
+
SETLOCAL
|
| 8 |
+
CALL :find_dp0
|
| 9 |
+
|
| 10 |
+
IF EXIST "%dp0%\node.exe" (
|
| 11 |
+
SET "_prog=%dp0%\node.exe"
|
| 12 |
+
) ELSE (
|
| 13 |
+
SET "_prog=node"
|
| 14 |
+
SET PATHEXT=%PATHEXT:;.JS;=;%
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\node-gyp-build\optional.js" %*
|
node_modules/.bin/node-gyp-build-optional.ps1
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env pwsh
|
| 2 |
+
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
|
| 3 |
+
|
| 4 |
+
$exe=""
|
| 5 |
+
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
|
| 6 |
+
# Fix case when both the Windows and Linux builds of Node
|
| 7 |
+
# are installed in the same directory
|
| 8 |
+
$exe=".exe"
|
| 9 |
+
}
|
| 10 |
+
$ret=0
|
| 11 |
+
if (Test-Path "$basedir/node$exe") {
|
| 12 |
+
# Support pipeline input
|
| 13 |
+
if ($MyInvocation.ExpectingInput) {
|
| 14 |
+
$input | & "$basedir/node$exe" "$basedir/../node-gyp-build/optional.js" $args
|
| 15 |
+
} else {
|
| 16 |
+
& "$basedir/node$exe" "$basedir/../node-gyp-build/optional.js" $args
|
| 17 |
+
}
|
| 18 |
+
$ret=$LASTEXITCODE
|
| 19 |
+
} else {
|
| 20 |
+
# Support pipeline input
|
| 21 |
+
if ($MyInvocation.ExpectingInput) {
|
| 22 |
+
$input | & "node$exe" "$basedir/../node-gyp-build/optional.js" $args
|
| 23 |
+
} else {
|
| 24 |
+
& "node$exe" "$basedir/../node-gyp-build/optional.js" $args
|
| 25 |
+
}
|
| 26 |
+
$ret=$LASTEXITCODE
|
| 27 |
+
}
|
| 28 |
+
exit $ret
|
node_modules/.bin/node-gyp-build-test
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/sh
|
| 2 |
+
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
|
| 3 |
+
|
| 4 |
+
case `uname` in
|
| 5 |
+
*CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;;
|
| 6 |
+
esac
|
| 7 |
+
|
| 8 |
+
if [ -x "$basedir/node" ]; then
|
| 9 |
+
exec "$basedir/node" "$basedir/../node-gyp-build/build-test.js" "$@"
|
| 10 |
+
else
|
| 11 |
+
exec node "$basedir/../node-gyp-build/build-test.js" "$@"
|
| 12 |
+
fi
|
node_modules/.bin/node-gyp-build-test.cmd
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
@ECHO off
|
| 2 |
+
GOTO start
|
| 3 |
+
:find_dp0
|
| 4 |
+
SET dp0=%~dp0
|
| 5 |
+
EXIT /b
|
| 6 |
+
:start
|
| 7 |
+
SETLOCAL
|
| 8 |
+
CALL :find_dp0
|
| 9 |
+
|
| 10 |
+
IF EXIST "%dp0%\node.exe" (
|
| 11 |
+
SET "_prog=%dp0%\node.exe"
|
| 12 |
+
) ELSE (
|
| 13 |
+
SET "_prog=node"
|
| 14 |
+
SET PATHEXT=%PATHEXT:;.JS;=;%
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\node-gyp-build\build-test.js" %*
|
node_modules/.bin/node-gyp-build-test.ps1
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env pwsh
|
| 2 |
+
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
|
| 3 |
+
|
| 4 |
+
$exe=""
|
| 5 |
+
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
|
| 6 |
+
# Fix case when both the Windows and Linux builds of Node
|
| 7 |
+
# are installed in the same directory
|
| 8 |
+
$exe=".exe"
|
| 9 |
+
}
|
| 10 |
+
$ret=0
|
| 11 |
+
if (Test-Path "$basedir/node$exe") {
|
| 12 |
+
# Support pipeline input
|
| 13 |
+
if ($MyInvocation.ExpectingInput) {
|
| 14 |
+
$input | & "$basedir/node$exe" "$basedir/../node-gyp-build/build-test.js" $args
|
| 15 |
+
} else {
|
| 16 |
+
& "$basedir/node$exe" "$basedir/../node-gyp-build/build-test.js" $args
|
| 17 |
+
}
|
| 18 |
+
$ret=$LASTEXITCODE
|
| 19 |
+
} else {
|
| 20 |
+
# Support pipeline input
|
| 21 |
+
if ($MyInvocation.ExpectingInput) {
|
| 22 |
+
$input | & "node$exe" "$basedir/../node-gyp-build/build-test.js" $args
|
| 23 |
+
} else {
|
| 24 |
+
& "node$exe" "$basedir/../node-gyp-build/build-test.js" $args
|
| 25 |
+
}
|
| 26 |
+
$ret=$LASTEXITCODE
|
| 27 |
+
}
|
| 28 |
+
exit $ret
|
node_modules/.bin/node-gyp-build.cmd
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
@ECHO off
|
| 2 |
+
GOTO start
|
| 3 |
+
:find_dp0
|
| 4 |
+
SET dp0=%~dp0
|
| 5 |
+
EXIT /b
|
| 6 |
+
:start
|
| 7 |
+
SETLOCAL
|
| 8 |
+
CALL :find_dp0
|
| 9 |
+
|
| 10 |
+
IF EXIST "%dp0%\node.exe" (
|
| 11 |
+
SET "_prog=%dp0%\node.exe"
|
| 12 |
+
) ELSE (
|
| 13 |
+
SET "_prog=node"
|
| 14 |
+
SET PATHEXT=%PATHEXT:;.JS;=;%
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\node-gyp-build\bin.js" %*
|
node_modules/.bin/node-gyp-build.ps1
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env pwsh
|
| 2 |
+
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
|
| 3 |
+
|
| 4 |
+
$exe=""
|
| 5 |
+
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
|
| 6 |
+
# Fix case when both the Windows and Linux builds of Node
|
| 7 |
+
# are installed in the same directory
|
| 8 |
+
$exe=".exe"
|
| 9 |
+
}
|
| 10 |
+
$ret=0
|
| 11 |
+
if (Test-Path "$basedir/node$exe") {
|
| 12 |
+
# Support pipeline input
|
| 13 |
+
if ($MyInvocation.ExpectingInput) {
|
| 14 |
+
$input | & "$basedir/node$exe" "$basedir/../node-gyp-build/bin.js" $args
|
| 15 |
+
} else {
|
| 16 |
+
& "$basedir/node$exe" "$basedir/../node-gyp-build/bin.js" $args
|
| 17 |
+
}
|
| 18 |
+
$ret=$LASTEXITCODE
|
| 19 |
+
} else {
|
| 20 |
+
# Support pipeline input
|
| 21 |
+
if ($MyInvocation.ExpectingInput) {
|
| 22 |
+
$input | & "node$exe" "$basedir/../node-gyp-build/bin.js" $args
|
| 23 |
+
} else {
|
| 24 |
+
& "node$exe" "$basedir/../node-gyp-build/bin.js" $args
|
| 25 |
+
}
|
| 26 |
+
$ret=$LASTEXITCODE
|
| 27 |
+
}
|
| 28 |
+
exit $ret
|
node_modules/.package-lock.json
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"name": "tts_vrc",
|
| 3 |
+
"lockfileVersion": 3,
|
| 4 |
+
"requires": true,
|
| 5 |
+
"packages": {
|
| 6 |
+
"node_modules/@gradio/client": {
|
| 7 |
+
"version": "0.8.2",
|
| 8 |
+
"resolved": "https://registry.npmjs.org/@gradio/client/-/client-0.8.2.tgz",
|
| 9 |
+
"integrity": "sha512-ZWrkJBsVg7ioIHhGV1pqIo4MBL0GPn0SHLeA04cqrsxkWiZHZz9CB5wFtm1kaFtd68ERAgEzR8OYVzzlBd2pyQ==",
|
| 10 |
+
"dependencies": {
|
| 11 |
+
"bufferutil": "^4.0.7",
|
| 12 |
+
"semiver": "^1.1.0",
|
| 13 |
+
"ws": "^8.13.0"
|
| 14 |
+
},
|
| 15 |
+
"engines": {
|
| 16 |
+
"node": ">=18.0.0"
|
| 17 |
+
}
|
| 18 |
+
},
|
| 19 |
+
"node_modules/bufferutil": {
|
| 20 |
+
"version": "4.0.8",
|
| 21 |
+
"resolved": "https://registry.npmjs.org/bufferutil/-/bufferutil-4.0.8.tgz",
|
| 22 |
+
"integrity": "sha512-4T53u4PdgsXqKaIctwF8ifXlRTTmEPJ8iEPWFdGZvcf7sbwYo6FKFEX9eNNAnzFZ7EzJAQ3CJeOtCRA4rDp7Pw==",
|
| 23 |
+
"hasInstallScript": true,
|
| 24 |
+
"dependencies": {
|
| 25 |
+
"node-gyp-build": "^4.3.0"
|
| 26 |
+
},
|
| 27 |
+
"engines": {
|
| 28 |
+
"node": ">=6.14.2"
|
| 29 |
+
}
|
| 30 |
+
},
|
| 31 |
+
"node_modules/node-gyp-build": {
|
| 32 |
+
"version": "4.7.1",
|
| 33 |
+
"resolved": "https://registry.npmjs.org/node-gyp-build/-/node-gyp-build-4.7.1.tgz",
|
| 34 |
+
"integrity": "sha512-wTSrZ+8lsRRa3I3H8Xr65dLWSgCvY2l4AOnaeKdPA9TB/WYMPaTcrzf3rXvFoVvjKNVnu0CcWSx54qq9GKRUYg==",
|
| 35 |
+
"bin": {
|
| 36 |
+
"node-gyp-build": "bin.js",
|
| 37 |
+
"node-gyp-build-optional": "optional.js",
|
| 38 |
+
"node-gyp-build-test": "build-test.js"
|
| 39 |
+
}
|
| 40 |
+
},
|
| 41 |
+
"node_modules/semiver": {
|
| 42 |
+
"version": "1.1.0",
|
| 43 |
+
"resolved": "https://registry.npmjs.org/semiver/-/semiver-1.1.0.tgz",
|
| 44 |
+
"integrity": "sha512-QNI2ChmuioGC1/xjyYwyZYADILWyW6AmS1UH6gDj/SFUUUS4MBAWs/7mxnkRPc/F4iHezDP+O8t0dO8WHiEOdg==",
|
| 45 |
+
"engines": {
|
| 46 |
+
"node": ">=6"
|
| 47 |
+
}
|
| 48 |
+
},
|
| 49 |
+
"node_modules/ws": {
|
| 50 |
+
"version": "8.14.2",
|
| 51 |
+
"resolved": "https://registry.npmjs.org/ws/-/ws-8.14.2.tgz",
|
| 52 |
+
"integrity": "sha512-wEBG1ftX4jcglPxgFCMJmZ2PLtSbJ2Peg6TmpJFTbe9GZYOQCDPdMYu/Tm0/bGZkw8paZnJY45J4K2PZrLYq8g==",
|
| 53 |
+
"engines": {
|
| 54 |
+
"node": ">=10.0.0"
|
| 55 |
+
},
|
| 56 |
+
"peerDependencies": {
|
| 57 |
+
"bufferutil": "^4.0.1",
|
| 58 |
+
"utf-8-validate": ">=5.0.2"
|
| 59 |
+
},
|
| 60 |
+
"peerDependenciesMeta": {
|
| 61 |
+
"bufferutil": {
|
| 62 |
+
"optional": true
|
| 63 |
+
},
|
| 64 |
+
"utf-8-validate": {
|
| 65 |
+
"optional": true
|
| 66 |
+
}
|
| 67 |
+
}
|
| 68 |
+
}
|
| 69 |
+
}
|
| 70 |
+
}
|
node_modules/@gradio/client/CHANGELOG.md
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# @gradio/client
|
| 2 |
+
|
| 3 |
+
## 0.8.2
|
| 4 |
+
|
| 5 |
+
### Features
|
| 6 |
+
|
| 7 |
+
- [#6511](https://github.com/gradio-app/gradio/pull/6511) [`71f1a1f99`](https://github.com/gradio-app/gradio/commit/71f1a1f9931489d465c2c1302a5c8d768a3cd23a) - Mark `FileData.orig_name` optional on the frontend aligning the type definition on the Python side. Thanks [@whitphx](https://github.com/whitphx)!
|
| 8 |
+
|
| 9 |
+
## 0.8.1
|
| 10 |
+
|
| 11 |
+
### Fixes
|
| 12 |
+
|
| 13 |
+
- [#6383](https://github.com/gradio-app/gradio/pull/6383) [`324867f63`](https://github.com/gradio-app/gradio/commit/324867f63c920113d89a565892aa596cf8b1e486) - Fix event target. Thanks [@aliabid94](https://github.com/aliabid94)!
|
| 14 |
+
|
| 15 |
+
## 0.8.0
|
| 16 |
+
|
| 17 |
+
### Features
|
| 18 |
+
|
| 19 |
+
- [#6307](https://github.com/gradio-app/gradio/pull/6307) [`f1409f95e`](https://github.com/gradio-app/gradio/commit/f1409f95ed39c5565bed6a601e41f94e30196a57) - Provide status updates on file uploads. Thanks [@freddyaboulton](https://github.com/freddyaboulton)!
|
| 20 |
+
|
| 21 |
+
## 0.7.2
|
| 22 |
+
|
| 23 |
+
### Fixes
|
| 24 |
+
|
| 25 |
+
- [#6327](https://github.com/gradio-app/gradio/pull/6327) [`bca6c2c80`](https://github.com/gradio-app/gradio/commit/bca6c2c80f7e5062427019de45c282238388af95) - Restore query parameters in request. Thanks [@aliabid94](https://github.com/aliabid94)!
|
| 26 |
+
|
| 27 |
+
## 0.7.1
|
| 28 |
+
|
| 29 |
+
### Features
|
| 30 |
+
|
| 31 |
+
- [#6137](https://github.com/gradio-app/gradio/pull/6137) [`2ba14b284`](https://github.com/gradio-app/gradio/commit/2ba14b284f908aa13859f4337167a157075a68eb) - JS Param. Thanks [@dawoodkhan82](https://github.com/dawoodkhan82)!
|
| 32 |
+
|
| 33 |
+
## 0.7.0
|
| 34 |
+
|
| 35 |
+
### Features
|
| 36 |
+
|
| 37 |
+
- [#5498](https://github.com/gradio-app/gradio/pull/5498) [`287fe6782`](https://github.com/gradio-app/gradio/commit/287fe6782825479513e79a5cf0ba0fbfe51443d7) - fix circular dependency with client + upload. Thanks [@pngwn](https://github.com/pngwn)!
|
| 38 |
+
- [#5498](https://github.com/gradio-app/gradio/pull/5498) [`287fe6782`](https://github.com/gradio-app/gradio/commit/287fe6782825479513e79a5cf0ba0fbfe51443d7) - Image v4. Thanks [@pngwn](https://github.com/pngwn)!
|
| 39 |
+
- [#5498](https://github.com/gradio-app/gradio/pull/5498) [`287fe6782`](https://github.com/gradio-app/gradio/commit/287fe6782825479513e79a5cf0ba0fbfe51443d7) - Swap websockets for SSE. Thanks [@pngwn](https://github.com/pngwn)!
|
| 40 |
+
|
| 41 |
+
## 0.7.0-beta.1
|
| 42 |
+
|
| 43 |
+
### Features
|
| 44 |
+
|
| 45 |
+
- [#6143](https://github.com/gradio-app/gradio/pull/6143) [`e4f7b4b40`](https://github.com/gradio-app/gradio/commit/e4f7b4b409323b01aa01b39e15ce6139e29aa073) - fix circular dependency with client + upload. Thanks [@pngwn](https://github.com/pngwn)!
|
| 46 |
+
- [#6094](https://github.com/gradio-app/gradio/pull/6094) [`c476bd5a5`](https://github.com/gradio-app/gradio/commit/c476bd5a5b70836163b9c69bf4bfe068b17fbe13) - Image v4. Thanks [@pngwn](https://github.com/pngwn)!
|
| 47 |
+
- [#6069](https://github.com/gradio-app/gradio/pull/6069) [`bf127e124`](https://github.com/gradio-app/gradio/commit/bf127e1241a41401e144874ea468dff8474eb505) - Swap websockets for SSE. Thanks [@aliabid94](https://github.com/aliabid94)!
|
| 48 |
+
|
| 49 |
+
## 0.7.0-beta.0
|
| 50 |
+
|
| 51 |
+
### Features
|
| 52 |
+
|
| 53 |
+
- [#6016](https://github.com/gradio-app/gradio/pull/6016) [`83e947676`](https://github.com/gradio-app/gradio/commit/83e947676d327ca2ab6ae2a2d710c78961c771a0) - Format js in v4 branch. Thanks [@freddyaboulton](https://github.com/freddyaboulton)!
|
| 54 |
+
|
| 55 |
+
### Fixes
|
| 56 |
+
|
| 57 |
+
- [#6046](https://github.com/gradio-app/gradio/pull/6046) [`dbb7de5e0`](https://github.com/gradio-app/gradio/commit/dbb7de5e02c53fee05889d696d764d212cb96c74) - fix tests. Thanks [@pngwn](https://github.com/pngwn)!
|
| 58 |
+
|
| 59 |
+
## 0.6.0
|
| 60 |
+
|
| 61 |
+
### Features
|
| 62 |
+
|
| 63 |
+
- [#5972](https://github.com/gradio-app/gradio/pull/5972) [`11a300791`](https://github.com/gradio-app/gradio/commit/11a3007916071f0791844b0a37f0fb4cec69cea3) - Lite: Support opening the entrypoint HTML page directly in browser via the `file:` protocol. Thanks [@whitphx](https://github.com/whitphx)!
|
| 64 |
+
|
| 65 |
+
## 0.5.2
|
| 66 |
+
|
| 67 |
+
### Fixes
|
| 68 |
+
|
| 69 |
+
- [#5840](https://github.com/gradio-app/gradio/pull/5840) [`4e62b8493`](https://github.com/gradio-app/gradio/commit/4e62b8493dfce50bafafe49f1a5deb929d822103) - Ensure websocket polyfill doesn't load if there is already a `global.Webocket` property set. Thanks [@Jay2theWhy](https://github.com/Jay2theWhy)!
|
| 70 |
+
|
| 71 |
+
## 0.5.1
|
| 72 |
+
|
| 73 |
+
### Fixes
|
| 74 |
+
|
| 75 |
+
- [#5816](https://github.com/gradio-app/gradio/pull/5816) [`796145e2c`](https://github.com/gradio-app/gradio/commit/796145e2c48c4087bec17f8ec0be4ceee47170cb) - Fix calls to the component server so that `gr.FileExplorer` works on Spaces. Thanks [@abidlabs](https://github.com/abidlabs)!
|
| 76 |
+
|
| 77 |
+
## 0.5.0
|
| 78 |
+
|
| 79 |
+
### Highlights
|
| 80 |
+
|
| 81 |
+
#### new `FileExplorer` component ([#5672](https://github.com/gradio-app/gradio/pull/5672) [`e4a307ed6`](https://github.com/gradio-app/gradio/commit/e4a307ed6cde3bbdf4ff2f17655739addeec941e))
|
| 82 |
+
|
| 83 |
+
Thanks to a new capability that allows components to communicate directly with the server _without_ passing data via the value, we have created a new `FileExplorer` component.
|
| 84 |
+
|
| 85 |
+
This component allows you to populate the explorer by passing a glob, but only provides the selected file(s) in your prediction function.
|
| 86 |
+
|
| 87 |
+
Users can then navigate the virtual filesystem and select files which will be accessible in your predict function. This component will allow developers to build more complex spaces, with more flexible input options.
|
| 88 |
+
|
| 89 |
+

|
| 90 |
+
|
| 91 |
+
For more information check the [`FileExplorer` documentation](https://gradio.app/docs/fileexplorer).
|
| 92 |
+
|
| 93 |
+
Thanks [@aliabid94](https://github.com/aliabid94)!
|
| 94 |
+
|
| 95 |
+
### Features
|
| 96 |
+
|
| 97 |
+
- [#5787](https://github.com/gradio-app/gradio/pull/5787) [`caeee8bf7`](https://github.com/gradio-app/gradio/commit/caeee8bf7821fd5fe2f936ed82483bed00f613ec) - ensure the client does not depend on `window` when running in a node environment. Thanks [@gibiee](https://github.com/gibiee)!
|
| 98 |
+
|
| 99 |
+
### Fixes
|
| 100 |
+
|
| 101 |
+
- [#5776](https://github.com/gradio-app/gradio/pull/5776) [`c0fef4454`](https://github.com/gradio-app/gradio/commit/c0fef44541bfa61568bdcfcdfc7d7d79869ab1df) - Revert replica proxy logic and instead implement using the `root` variable. Thanks [@freddyaboulton](https://github.com/freddyaboulton)!
|
| 102 |
+
|
| 103 |
+
## 0.4.2
|
| 104 |
+
|
| 105 |
+
### Features
|
| 106 |
+
|
| 107 |
+
- [#5124](https://github.com/gradio-app/gradio/pull/5124) [`6e56a0d9b`](https://github.com/gradio-app/gradio/commit/6e56a0d9b0c863e76c69e1183d9d40196922b4cd) - Lite: Websocket queueing. Thanks [@whitphx](https://github.com/whitphx)!
|
| 108 |
+
|
| 109 |
+
## 0.4.1
|
| 110 |
+
|
| 111 |
+
### Fixes
|
| 112 |
+
|
| 113 |
+
- [#5705](https://github.com/gradio-app/gradio/pull/5705) [`78e7cf516`](https://github.com/gradio-app/gradio/commit/78e7cf5163e8d205e8999428fce4c02dbdece25f) - ensure internal data has updated before dispatching `success` or `then` events. Thanks [@pngwn](https://github.com/pngwn)!
|
| 114 |
+
|
| 115 |
+
## 0.4.0
|
| 116 |
+
|
| 117 |
+
### Features
|
| 118 |
+
|
| 119 |
+
- [#5682](https://github.com/gradio-app/gradio/pull/5682) [`c57f1b75e`](https://github.com/gradio-app/gradio/commit/c57f1b75e272c76b0af4d6bd0c7f44743ff34f26) - Fix functional tests. Thanks [@abidlabs](https://github.com/abidlabs)!
|
| 120 |
+
- [#5681](https://github.com/gradio-app/gradio/pull/5681) [`40de3d217`](https://github.com/gradio-app/gradio/commit/40de3d2178b61ebe424b6f6228f94c0c6f679bea) - add query parameters to the `gr.Request` object through the `query_params` attribute. Thanks [@DarhkVoyd](https://github.com/DarhkVoyd)!
|
| 121 |
+
- [#5653](https://github.com/gradio-app/gradio/pull/5653) [`ea0e00b20`](https://github.com/gradio-app/gradio/commit/ea0e00b207b4b90a10e9d054c4202d4e705a29ba) - Prevent Clients from accessing API endpoints that set `api_name=False`. Thanks [@abidlabs](https://github.com/abidlabs)!
|
| 122 |
+
|
| 123 |
+
## 0.3.1
|
| 124 |
+
|
| 125 |
+
### Fixes
|
| 126 |
+
|
| 127 |
+
- [#5412](https://github.com/gradio-app/gradio/pull/5412) [`26fef8c7`](https://github.com/gradio-app/gradio/commit/26fef8c7f85a006c7e25cdbed1792df19c512d02) - Skip view_api request in js client when auth enabled. Thanks [@freddyaboulton](https://github.com/freddyaboulton)!
|
| 128 |
+
|
| 129 |
+
## 0.3.0
|
| 130 |
+
|
| 131 |
+
### Features
|
| 132 |
+
|
| 133 |
+
- [#5267](https://github.com/gradio-app/gradio/pull/5267) [`119c8343`](https://github.com/gradio-app/gradio/commit/119c834331bfae60d4742c8f20e9cdecdd67e8c2) - Faster reload mode. Thanks [@freddyaboulton](https://github.com/freddyaboulton)!
|
| 134 |
+
|
| 135 |
+
## 0.2.1
|
| 136 |
+
|
| 137 |
+
### Features
|
| 138 |
+
|
| 139 |
+
- [#5173](https://github.com/gradio-app/gradio/pull/5173) [`730f0c1d`](https://github.com/gradio-app/gradio/commit/730f0c1d54792eb11359e40c9f2326e8a6e39203) - Ensure gradio client works as expected for functions that return nothing. Thanks [@raymondtri](https://github.com/raymondtri)!
|
| 140 |
+
|
| 141 |
+
## 0.2.0
|
| 142 |
+
|
| 143 |
+
### Features
|
| 144 |
+
|
| 145 |
+
- [#5133](https://github.com/gradio-app/gradio/pull/5133) [`61129052`](https://github.com/gradio-app/gradio/commit/61129052ed1391a75c825c891d57fa0ad6c09fc8) - Update dependency esbuild to ^0.19.0. Thanks [@renovate](https://github.com/apps/renovate)!
|
| 146 |
+
- [#5035](https://github.com/gradio-app/gradio/pull/5035) [`8b4eb8ca`](https://github.com/gradio-app/gradio/commit/8b4eb8cac9ea07bde31b44e2006ca2b7b5f4de36) - JS Client: Fixes cannot read properties of null (reading 'is_file'). Thanks [@raymondtri](https://github.com/raymondtri)!
|
| 147 |
+
|
| 148 |
+
### Fixes
|
| 149 |
+
|
| 150 |
+
- [#5075](https://github.com/gradio-app/gradio/pull/5075) [`67265a58`](https://github.com/gradio-app/gradio/commit/67265a58027ef1f9e4c0eb849a532f72eaebde48) - Allow supporting >1000 files in `gr.File()` and `gr.UploadButton()`. Thanks [@abidlabs](https://github.com/abidlabs)!
|
| 151 |
+
|
| 152 |
+
## 0.1.4
|
| 153 |
+
|
| 154 |
+
### Patch Changes
|
| 155 |
+
|
| 156 |
+
- [#4717](https://github.com/gradio-app/gradio/pull/4717) [`ab5d1ea0`](https://github.com/gradio-app/gradio/commit/ab5d1ea0de87ed888779b66fd2a705583bd29e02) Thanks [@whitphx](https://github.com/whitphx)! - Fix the package description
|
| 157 |
+
|
| 158 |
+
## 0.1.3
|
| 159 |
+
|
| 160 |
+
### Patch Changes
|
| 161 |
+
|
| 162 |
+
- [#4357](https://github.com/gradio-app/gradio/pull/4357) [`0dbd8f7f`](https://github.com/gradio-app/gradio/commit/0dbd8f7fee4b4877f783fa7bc493f98bbfc3d01d) Thanks [@pngwn](https://github.com/pngwn)! - Various internal refactors and cleanups.
|
| 163 |
+
|
| 164 |
+
## 0.1.2
|
| 165 |
+
|
| 166 |
+
### Patch Changes
|
| 167 |
+
|
| 168 |
+
- [#4273](https://github.com/gradio-app/gradio/pull/4273) [`1d0f0a9d`](https://github.com/gradio-app/gradio/commit/1d0f0a9db096552e67eb2197c932342587e9e61e) Thanks [@pngwn](https://github.com/pngwn)! - Ensure websocket error messages are correctly handled.
|
| 169 |
+
|
| 170 |
+
- [#4315](https://github.com/gradio-app/gradio/pull/4315) [`b525b122`](https://github.com/gradio-app/gradio/commit/b525b122dd8569bbaf7e06db5b90d622d2e9073d) Thanks [@whitphx](https://github.com/whitphx)! - Refacor types.
|
| 171 |
+
|
| 172 |
+
- [#4271](https://github.com/gradio-app/gradio/pull/4271) [`1151c525`](https://github.com/gradio-app/gradio/commit/1151c5253554cb87ebd4a44a8a470ac215ff782b) Thanks [@pngwn](https://github.com/pngwn)! - Ensure the full root path is always respected when making requests to a gradio app server.
|
| 173 |
+
|
| 174 |
+
## 0.1.1
|
| 175 |
+
|
| 176 |
+
### Patch Changes
|
| 177 |
+
|
| 178 |
+
- [#4201](https://github.com/gradio-app/gradio/pull/4201) [`da5b4ee1`](https://github.com/gradio-app/gradio/commit/da5b4ee11721175858ded96e5710225369097f74) Thanks [@pngwn](https://github.com/pngwn)! - Ensure semiver is bundled so CDN links work correctly.
|
| 179 |
+
|
| 180 |
+
- [#4202](https://github.com/gradio-app/gradio/pull/4202) [`a26e9afd`](https://github.com/gradio-app/gradio/commit/a26e9afde319382993e6ddc77cc4e56337a31248) Thanks [@pngwn](https://github.com/pngwn)! - Ensure all URLs returned by the client are complete URLs with the correct host instead of an absolute path relative to a server.
|
| 181 |
+
|
| 182 |
+
## 0.1.0
|
| 183 |
+
|
| 184 |
+
### Minor Changes
|
| 185 |
+
|
| 186 |
+
- [#4185](https://github.com/gradio-app/gradio/pull/4185) [`67239ca9`](https://github.com/gradio-app/gradio/commit/67239ca9b2fe3796853fbf7bf865c9e4b383200d) Thanks [@pngwn](https://github.com/pngwn)! - Update client for initial release
|
| 187 |
+
|
| 188 |
+
### Patch Changes
|
| 189 |
+
|
| 190 |
+
- [#3692](https://github.com/gradio-app/gradio/pull/3692) [`48e8b113`](https://github.com/gradio-app/gradio/commit/48e8b113f4b55e461d9da4f153bf72aeb4adf0f1) Thanks [@pngwn](https://github.com/pngwn)! - Ensure client works in node, create ESM bundle and generate typescript declaration files.
|
| 191 |
+
|
| 192 |
+
- [#3605](https://github.com/gradio-app/gradio/pull/3605) [`ae4277a9`](https://github.com/gradio-app/gradio/commit/ae4277a9a83d49bdadfe523b0739ba988128e73b) Thanks [@pngwn](https://github.com/pngwn)! - Update readme.
|
node_modules/@gradio/client/LICENSE
ADDED
|
@@ -0,0 +1,201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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Apache License
|
| 2 |
+
Version 2.0, January 2004
|
| 3 |
+
http://www.apache.org/licenses/
|
| 4 |
+
|
| 5 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
| 6 |
+
|
| 7 |
+
1. Definitions.
|
| 8 |
+
|
| 9 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
| 10 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
| 11 |
+
|
| 12 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
| 13 |
+
the copyright owner that is granting the License.
|
| 14 |
+
|
| 15 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
| 16 |
+
other entities that control, are controlled by, or are under common
|
| 17 |
+
control with that entity. For the purposes of this definition,
|
| 18 |
+
"control" means (i) the power, direct or indirect, to cause the
|
| 19 |
+
direction or management of such entity, whether by contract or
|
| 20 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
| 21 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
| 22 |
+
|
| 23 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
| 24 |
+
exercising permissions granted by this License.
|
| 25 |
+
|
| 26 |
+
"Source" form shall mean the preferred form for making modifications,
|
| 27 |
+
including but not limited to software source code, documentation
|
| 28 |
+
source, and configuration files.
|
| 29 |
+
|
| 30 |
+
"Object" form shall mean any form resulting from mechanical
|
| 31 |
+
transformation or translation of a Source form, including but
|
| 32 |
+
not limited to compiled object code, generated documentation,
|
| 33 |
+
and conversions to other media types.
|
| 34 |
+
|
| 35 |
+
"Work" shall mean the work of authorship, whether in Source or
|
| 36 |
+
Object form, made available under the License, as indicated by a
|
| 37 |
+
copyright notice that is included in or attached to the work
|
| 38 |
+
(an example is provided in the Appendix below).
|
| 39 |
+
|
| 40 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
| 41 |
+
form, that is based on (or derived from) the Work and for which the
|
| 42 |
+
editorial revisions, annotations, elaborations, or other modifications
|
| 43 |
+
represent, as a whole, an original work of authorship. For the purposes
|
| 44 |
+
of this License, Derivative Works shall not include works that remain
|
| 45 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
| 46 |
+
the Work and Derivative Works thereof.
|
| 47 |
+
|
| 48 |
+
"Contribution" shall mean any work of authorship, including
|
| 49 |
+
the original version of the Work and any modifications or additions
|
| 50 |
+
to that Work or Derivative Works thereof, that is intentionally
|
| 51 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
| 52 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
| 53 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
| 54 |
+
means any form of electronic, verbal, or written communication sent
|
| 55 |
+
to the Licensor or its representatives, including but not limited to
|
| 56 |
+
communication on electronic mailing lists, source code control systems,
|
| 57 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
| 58 |
+
Licensor for the purpose of discussing and improving the Work, but
|
| 59 |
+
excluding communication that is conspicuously marked or otherwise
|
| 60 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
| 61 |
+
|
| 62 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
| 63 |
+
on behalf of whom a Contribution has been received by Licensor and
|
| 64 |
+
subsequently incorporated within the Work.
|
| 65 |
+
|
| 66 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
| 67 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 68 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 69 |
+
copyright license to reproduce, prepare Derivative Works of,
|
| 70 |
+
publicly display, publicly perform, sublicense, and distribute the
|
| 71 |
+
Work and such Derivative Works in Source or Object form.
|
| 72 |
+
|
| 73 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
| 74 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 75 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 76 |
+
(except as stated in this section) patent license to make, have made,
|
| 77 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
| 78 |
+
where such license applies only to those patent claims licensable
|
| 79 |
+
by such Contributor that are necessarily infringed by their
|
| 80 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
| 81 |
+
with the Work to which such Contribution(s) was submitted. If You
|
| 82 |
+
institute patent litigation against any entity (including a
|
| 83 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
| 84 |
+
or a Contribution incorporated within the Work constitutes direct
|
| 85 |
+
or contributory patent infringement, then any patent licenses
|
| 86 |
+
granted to You under this License for that Work shall terminate
|
| 87 |
+
as of the date such litigation is filed.
|
| 88 |
+
|
| 89 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
| 90 |
+
Work or Derivative Works thereof in any medium, with or without
|
| 91 |
+
modifications, and in Source or Object form, provided that You
|
| 92 |
+
meet the following conditions:
|
| 93 |
+
|
| 94 |
+
(a) You must give any other recipients of the Work or
|
| 95 |
+
Derivative Works a copy of this License; and
|
| 96 |
+
|
| 97 |
+
(b) You must cause any modified files to carry prominent notices
|
| 98 |
+
stating that You changed the files; and
|
| 99 |
+
|
| 100 |
+
(c) You must retain, in the Source form of any Derivative Works
|
| 101 |
+
that You distribute, all copyright, patent, trademark, and
|
| 102 |
+
attribution notices from the Source form of the Work,
|
| 103 |
+
excluding those notices that do not pertain to any part of
|
| 104 |
+
the Derivative Works; and
|
| 105 |
+
|
| 106 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
| 107 |
+
distribution, then any Derivative Works that You distribute must
|
| 108 |
+
include a readable copy of the attribution notices contained
|
| 109 |
+
within such NOTICE file, excluding those notices that do not
|
| 110 |
+
pertain to any part of the Derivative Works, in at least one
|
| 111 |
+
of the following places: within a NOTICE text file distributed
|
| 112 |
+
as part of the Derivative Works; within the Source form or
|
| 113 |
+
documentation, if provided along with the Derivative Works; or,
|
| 114 |
+
within a display generated by the Derivative Works, if and
|
| 115 |
+
wherever such third-party notices normally appear. The contents
|
| 116 |
+
of the NOTICE file are for informational purposes only and
|
| 117 |
+
do not modify the License. You may add Your own attribution
|
| 118 |
+
notices within Derivative Works that You distribute, alongside
|
| 119 |
+
or as an addendum to the NOTICE text from the Work, provided
|
| 120 |
+
that such additional attribution notices cannot be construed
|
| 121 |
+
as modifying the License.
|
| 122 |
+
|
| 123 |
+
You may add Your own copyright statement to Your modifications and
|
| 124 |
+
may provide additional or different license terms and conditions
|
| 125 |
+
for use, reproduction, or distribution of Your modifications, or
|
| 126 |
+
for any such Derivative Works as a whole, provided Your use,
|
| 127 |
+
reproduction, and distribution of the Work otherwise complies with
|
| 128 |
+
the conditions stated in this License.
|
| 129 |
+
|
| 130 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
| 131 |
+
any Contribution intentionally submitted for inclusion in the Work
|
| 132 |
+
by You to the Licensor shall be under the terms and conditions of
|
| 133 |
+
this License, without any additional terms or conditions.
|
| 134 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
| 135 |
+
the terms of any separate license agreement you may have executed
|
| 136 |
+
with Licensor regarding such Contributions.
|
| 137 |
+
|
| 138 |
+
6. Trademarks. This License does not grant permission to use the trade
|
| 139 |
+
names, trademarks, service marks, or product names of the Licensor,
|
| 140 |
+
except as required for reasonable and customary use in describing the
|
| 141 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
| 142 |
+
|
| 143 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
| 144 |
+
agreed to in writing, Licensor provides the Work (and each
|
| 145 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
| 146 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
| 147 |
+
implied, including, without limitation, any warranties or conditions
|
| 148 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
| 149 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
| 150 |
+
appropriateness of using or redistributing the Work and assume any
|
| 151 |
+
risks associated with Your exercise of permissions under this License.
|
| 152 |
+
|
| 153 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
| 154 |
+
whether in tort (including negligence), contract, or otherwise,
|
| 155 |
+
unless required by applicable law (such as deliberate and grossly
|
| 156 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
| 157 |
+
liable to You for damages, including any direct, indirect, special,
|
| 158 |
+
incidental, or consequential damages of any character arising as a
|
| 159 |
+
result of this License or out of the use or inability to use the
|
| 160 |
+
Work (including but not limited to damages for loss of goodwill,
|
| 161 |
+
work stoppage, computer failure or malfunction, or any and all
|
| 162 |
+
other commercial damages or losses), even if such Contributor
|
| 163 |
+
has been advised of the possibility of such damages.
|
| 164 |
+
|
| 165 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
| 166 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
| 167 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
| 168 |
+
or other liability obligations and/or rights consistent with this
|
| 169 |
+
License. However, in accepting such obligations, You may act only
|
| 170 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
| 171 |
+
of any other Contributor, and only if You agree to indemnify,
|
| 172 |
+
defend, and hold each Contributor harmless for any liability
|
| 173 |
+
incurred by, or claims asserted against, such Contributor by reason
|
| 174 |
+
of your accepting any such warranty or additional liability.
|
| 175 |
+
|
| 176 |
+
END OF TERMS AND CONDITIONS
|
| 177 |
+
|
| 178 |
+
APPENDIX: How to apply the Apache License to your work.
|
| 179 |
+
|
| 180 |
+
To apply the Apache License to your work, attach the following
|
| 181 |
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
| 182 |
+
replaced with your own identifying information. (Don't include
|
| 183 |
+
the brackets!) The text should be enclosed in the appropriate
|
| 184 |
+
comment syntax for the file format. We also recommend that a
|
| 185 |
+
file or class name and description of purpose be included on the
|
| 186 |
+
same "printed page" as the copyright notice for easier
|
| 187 |
+
identification within third-party archives.
|
| 188 |
+
|
| 189 |
+
Copyright [yyyy] [name of copyright owner]
|
| 190 |
+
|
| 191 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
| 192 |
+
you may not use this file except in compliance with the License.
|
| 193 |
+
You may obtain a copy of the License at
|
| 194 |
+
|
| 195 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 196 |
+
|
| 197 |
+
Unless required by applicable law or agreed to in writing, software
|
| 198 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
| 199 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 200 |
+
See the License for the specific language governing permissions and
|
| 201 |
+
limitations under the License.
|
node_modules/@gradio/client/README.md
ADDED
|
@@ -0,0 +1,339 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
## JavaScript Client Library
|
| 2 |
+
|
| 3 |
+
A javascript (and typescript) client to call Gradio APIs.
|
| 4 |
+
|
| 5 |
+
## Installation
|
| 6 |
+
|
| 7 |
+
The Gradio JavaScript client is available on npm as `@gradio/client`. You can install it as below:
|
| 8 |
+
|
| 9 |
+
```sh
|
| 10 |
+
npm i @gradio/client
|
| 11 |
+
```
|
| 12 |
+
|
| 13 |
+
## Usage
|
| 14 |
+
|
| 15 |
+
The JavaScript Gradio Client exposes two named imports, `client` and `duplicate`.
|
| 16 |
+
|
| 17 |
+
### `client`
|
| 18 |
+
|
| 19 |
+
The client function connects to the API of a hosted Gradio space and returns an object that allows you to make calls to that API.
|
| 20 |
+
|
| 21 |
+
The simplest example looks like this:
|
| 22 |
+
|
| 23 |
+
```ts
|
| 24 |
+
import { client } from "@gradio/client";
|
| 25 |
+
|
| 26 |
+
const app = await client("user/space-name");
|
| 27 |
+
const result = await app.predict("/predict");
|
| 28 |
+
```
|
| 29 |
+
|
| 30 |
+
This function accepts two arguments: `source` and `options`:
|
| 31 |
+
|
| 32 |
+
#### `source`
|
| 33 |
+
|
| 34 |
+
This is the url or name of the gradio app whose API you wish to connect to. This parameter is required and should always be a string. For example:
|
| 35 |
+
|
| 36 |
+
```ts
|
| 37 |
+
client("user/space-name");
|
| 38 |
+
```
|
| 39 |
+
|
| 40 |
+
#### `options`
|
| 41 |
+
|
| 42 |
+
The options object can optionally be passed a second parameter. This object has two properties, `hf_token` and `status_callback`.
|
| 43 |
+
|
| 44 |
+
##### `hf_token`
|
| 45 |
+
|
| 46 |
+
This should be a Hugging Face personal access token and is required if you wish to make calls to a private gradio api. This option is optional and should be a string starting with `"hf_"`.
|
| 47 |
+
|
| 48 |
+
Example:
|
| 49 |
+
|
| 50 |
+
```ts
|
| 51 |
+
import { client } from "@gradio/client";
|
| 52 |
+
|
| 53 |
+
const app = await client("user/space-name", { hf_token: "hf_..." });
|
| 54 |
+
```
|
| 55 |
+
|
| 56 |
+
##### `status_callback`
|
| 57 |
+
|
| 58 |
+
This should be a function which will notify your of the status of a space if it is not running. If the gradio API you are connecting to is awake and running or is not hosted on Hugging Face space then this function will do nothing.
|
| 59 |
+
|
| 60 |
+
**Additional context**
|
| 61 |
+
|
| 62 |
+
Applications hosted on Hugging Face spaces can be in a number of different states. As spaces are a GitOps tool and will rebuild when new changes are pushed to the repository, they have various building, running and error states. If a space is not 'running' then the function passed as the `status_callback` will notify you of the current state of the space and the status of the space as it changes. Spaces that are building or sleeping can take longer than usual to respond, so you can use this information to give users feedback about the progress of their action.
|
| 63 |
+
|
| 64 |
+
```ts
|
| 65 |
+
import { client, type SpaceStatus } from "@gradio/client";
|
| 66 |
+
|
| 67 |
+
const app = await client("user/space-name", {
|
| 68 |
+
// The space_status parameter does not need to be manually annotated, this is just for illustration.
|
| 69 |
+
space_status: (space_status: SpaceStatus) => console.log(space_status)
|
| 70 |
+
});
|
| 71 |
+
```
|
| 72 |
+
|
| 73 |
+
```ts
|
| 74 |
+
interface SpaceStatusNormal {
|
| 75 |
+
status: "sleeping" | "running" | "building" | "error" | "stopped";
|
| 76 |
+
detail:
|
| 77 |
+
| "SLEEPING"
|
| 78 |
+
| "RUNNING"
|
| 79 |
+
| "RUNNING_BUILDING"
|
| 80 |
+
| "BUILDING"
|
| 81 |
+
| "NOT_FOUND";
|
| 82 |
+
load_status: "pending" | "error" | "complete" | "generating";
|
| 83 |
+
message: string;
|
| 84 |
+
}
|
| 85 |
+
|
| 86 |
+
interface SpaceStatusError {
|
| 87 |
+
status: "space_error";
|
| 88 |
+
detail: "NO_APP_FILE" | "CONFIG_ERROR" | "BUILD_ERROR" | "RUNTIME_ERROR";
|
| 89 |
+
load_status: "error";
|
| 90 |
+
message: string;
|
| 91 |
+
discussions_enabled: boolean;
|
| 92 |
+
|
| 93 |
+
type SpaceStatus = SpaceStatusNormal | SpaceStatusError;
|
| 94 |
+
```
|
| 95 |
+
|
| 96 |
+
The gradio client returns an object with a number of methods and properties:
|
| 97 |
+
|
| 98 |
+
#### `predict`
|
| 99 |
+
|
| 100 |
+
The `predict` method allows you to call an api endpoint and get a prediction result:
|
| 101 |
+
|
| 102 |
+
```ts
|
| 103 |
+
import { client } from "@gradio/client";
|
| 104 |
+
|
| 105 |
+
const app = await client("user/space-name");
|
| 106 |
+
const result = await app.predict("/predict");
|
| 107 |
+
```
|
| 108 |
+
|
| 109 |
+
`predict` accepts two parameters, `endpoint` and `payload`. It returns a promise that resolves to the prediction result.
|
| 110 |
+
|
| 111 |
+
##### `endpoint`
|
| 112 |
+
|
| 113 |
+
This is the endpoint for an api request and is required. The default endpoint for a `gradio.Interface` is `"/predict"`. Explicitly named endpoints have a custom name. The endpoint names can be found on the "View API" page of a space.
|
| 114 |
+
|
| 115 |
+
```ts
|
| 116 |
+
import { client } from "@gradio/client";
|
| 117 |
+
|
| 118 |
+
const app = await client("user/space-name");
|
| 119 |
+
const result = await app.predict("/predict");
|
| 120 |
+
```
|
| 121 |
+
|
| 122 |
+
##### `payload`
|
| 123 |
+
|
| 124 |
+
The `payload` argument is generally optional but this depends on the API itself. If the API endpoint depends on values being passed in then it is required for the API request to succeed. The data that should be passed in is detailed on the "View API" page of a space, or accessible via the `view_api()` method of the client.
|
| 125 |
+
|
| 126 |
+
```ts
|
| 127 |
+
import { client } from "@gradio/client";
|
| 128 |
+
|
| 129 |
+
const app = await client("user/space-name");
|
| 130 |
+
const result = await app.predict("/predict", [1, "Hello", "friends"]);
|
| 131 |
+
```
|
| 132 |
+
|
| 133 |
+
#### `submit`
|
| 134 |
+
|
| 135 |
+
The `submit` method provides a more flexible way to call an API endpoint, providing you with status updates about the current progress of the prediction as well as supporting more complex endpoint types.
|
| 136 |
+
|
| 137 |
+
```ts
|
| 138 |
+
import { client } from "@gradio/client";
|
| 139 |
+
|
| 140 |
+
const app = await client("user/space-name");
|
| 141 |
+
const submission = app.submit("/predict", payload);
|
| 142 |
+
```
|
| 143 |
+
|
| 144 |
+
The `submit` method accepts the same [`endpoint`](#endpoint) and [`payload`](#payload) arguments as `predict`.
|
| 145 |
+
|
| 146 |
+
The `submit` method does not return a promise and should not be awaited, instead it returns an object with a `on`, `off`, and `cancel` methods.
|
| 147 |
+
|
| 148 |
+
##### `on`
|
| 149 |
+
|
| 150 |
+
The `on` method allows you to subscribe to events related to the submitted API request. There are two types of event that can be subscribed to: `"data"` updates and `"status"` updates.
|
| 151 |
+
|
| 152 |
+
`"data"` updates are issued when the API computes a value, the callback provided as the second argument will be called when such a value is sent to the client. The shape of the data depends on the way the API itself is constructed. This event may fire more than once if that endpoint supports emmitting new values over time.
|
| 153 |
+
|
| 154 |
+
`"status` updates are issued when the status of a request changes. This information allows you to offer feedback to users when the queue position of the request changes, or when the request changes from queued to processing.
|
| 155 |
+
|
| 156 |
+
The status payload look like this:
|
| 157 |
+
|
| 158 |
+
```ts
|
| 159 |
+
interface Status {
|
| 160 |
+
queue: boolean;
|
| 161 |
+
code?: string;
|
| 162 |
+
success?: boolean;
|
| 163 |
+
stage: "pending" | "error" | "complete" | "generating";
|
| 164 |
+
size?: number;
|
| 165 |
+
position?: number;
|
| 166 |
+
eta?: number;
|
| 167 |
+
message?: string;
|
| 168 |
+
progress_data?: Array<{
|
| 169 |
+
progress: number | null;
|
| 170 |
+
index: number | null;
|
| 171 |
+
length: number | null;
|
| 172 |
+
unit: string | null;
|
| 173 |
+
desc: string | null;
|
| 174 |
+
}>;
|
| 175 |
+
time?: Date;
|
| 176 |
+
}
|
| 177 |
+
```
|
| 178 |
+
|
| 179 |
+
Usage of these subscribe callback looks like this:
|
| 180 |
+
|
| 181 |
+
```ts
|
| 182 |
+
import { client } from "@gradio/client";
|
| 183 |
+
|
| 184 |
+
const app = await client("user/space-name");
|
| 185 |
+
const submission = app
|
| 186 |
+
.submit("/predict", payload)
|
| 187 |
+
.on("data", (data) => console.log(data))
|
| 188 |
+
.on("status", (status: Status) => console.log(status));
|
| 189 |
+
```
|
| 190 |
+
|
| 191 |
+
##### `off`
|
| 192 |
+
|
| 193 |
+
The `off` method unsubscribes from a specific event of the submitted job and works similarly to `document.removeEventListener`; both the event name and the original callback must be passed in to successfully unsubscribe:
|
| 194 |
+
|
| 195 |
+
```ts
|
| 196 |
+
import { client } from "@gradio/client";
|
| 197 |
+
|
| 198 |
+
const app = await client("user/space-name");
|
| 199 |
+
const handle_data = (data) => console.log(data);
|
| 200 |
+
|
| 201 |
+
const submission = app.submit("/predict", payload).on("data", handle_data);
|
| 202 |
+
|
| 203 |
+
// later
|
| 204 |
+
submission.off("/predict", handle_data);
|
| 205 |
+
```
|
| 206 |
+
|
| 207 |
+
##### `destroy`
|
| 208 |
+
|
| 209 |
+
The `destroy` method will remove all subscriptions to a job, regardless of whether or not they are `"data"` or `"status"` events. This is a convenience method for when you do not want to unsubscribe use the `off` method.
|
| 210 |
+
|
| 211 |
+
```js
|
| 212 |
+
import { client } from "@gradio/client";
|
| 213 |
+
|
| 214 |
+
const app = await client("user/space-name");
|
| 215 |
+
const handle_data = (data) => console.log(data);
|
| 216 |
+
|
| 217 |
+
const submission = app.submit("/predict", payload).on("data", handle_data);
|
| 218 |
+
|
| 219 |
+
// later
|
| 220 |
+
submission.destroy();
|
| 221 |
+
```
|
| 222 |
+
|
| 223 |
+
##### `cancel`
|
| 224 |
+
|
| 225 |
+
Certain types of gradio function can run repeatedly and in some cases indefinitely. the `cancel` method will stop such an endpoints and prevent the API from issuing additional updates.
|
| 226 |
+
|
| 227 |
+
```ts
|
| 228 |
+
import { client } from "@gradio/client";
|
| 229 |
+
|
| 230 |
+
const app = await client("user/space-name");
|
| 231 |
+
const submission = app
|
| 232 |
+
.submit("/predict", payload)
|
| 233 |
+
.on("data", (data) => console.log(data));
|
| 234 |
+
|
| 235 |
+
// later
|
| 236 |
+
|
| 237 |
+
submission.cancel();
|
| 238 |
+
```
|
| 239 |
+
|
| 240 |
+
#### `view_api`
|
| 241 |
+
|
| 242 |
+
The `view_api` method provides details about the API you are connected to. It returns a JavaScript object of all named endpoints, unnamed endpoints and what values they accept and return. This method does not accept arguments.
|
| 243 |
+
|
| 244 |
+
```ts
|
| 245 |
+
import { client } from "@gradio/client";
|
| 246 |
+
|
| 247 |
+
const app = await client("user/space-name");
|
| 248 |
+
const api_info = await app.view_api();
|
| 249 |
+
|
| 250 |
+
console.log(api_info);
|
| 251 |
+
```
|
| 252 |
+
|
| 253 |
+
#### `config`
|
| 254 |
+
|
| 255 |
+
The `config` property contains the configuration for the gradio application you are connected to. This object may contain useful meta information about the application.
|
| 256 |
+
|
| 257 |
+
```ts
|
| 258 |
+
import { client } from "@gradio/client";
|
| 259 |
+
|
| 260 |
+
const app = await client("user/space-name");
|
| 261 |
+
console.log(app.config);
|
| 262 |
+
```
|
| 263 |
+
|
| 264 |
+
### `duplicate`
|
| 265 |
+
|
| 266 |
+
The duplicate function will attempt to duplicate the space that is referenced and return an instance of `client` connected to that space. If the space has already been duplicated then it will not create a new duplicate and will instead connect to the existing duplicated space. The huggingface token that is passed in will dictate the user under which the space is created.
|
| 267 |
+
|
| 268 |
+
`duplicate` accepts the same arguments as `client` with the addition of a `private` options property dictating whether the duplicated space should be private or public. A huggingface token is required for duplication to work.
|
| 269 |
+
|
| 270 |
+
```ts
|
| 271 |
+
import { duplicate } from "@gradio/client";
|
| 272 |
+
|
| 273 |
+
const app = await duplicate("user/space-name", {
|
| 274 |
+
hf_token: "hf_..."
|
| 275 |
+
});
|
| 276 |
+
```
|
| 277 |
+
|
| 278 |
+
This function accepts two arguments: `source` and `options`:
|
| 279 |
+
|
| 280 |
+
#### `source`
|
| 281 |
+
|
| 282 |
+
The space to duplicate and connect to. [See `client`'s `source` parameter](#source).
|
| 283 |
+
|
| 284 |
+
#### `options`
|
| 285 |
+
|
| 286 |
+
Accepts all options that `client` accepts, except `hf_token` is required. [See `client`'s `options` parameter](#source).
|
| 287 |
+
|
| 288 |
+
`duplicate` also accepts one additional `options` property.
|
| 289 |
+
|
| 290 |
+
##### `private`
|
| 291 |
+
|
| 292 |
+
This is an optional property specific to `duplicate`'s options object and will determine whether the space should be public or private. Spaces duplicated via the `duplicate` method are public by default.
|
| 293 |
+
|
| 294 |
+
```ts
|
| 295 |
+
import { duplicate } from "@gradio/client";
|
| 296 |
+
|
| 297 |
+
const app = await duplicate("user/space-name", {
|
| 298 |
+
hf_token: "hf_...",
|
| 299 |
+
private: true
|
| 300 |
+
});
|
| 301 |
+
```
|
| 302 |
+
|
| 303 |
+
##### `timeout`
|
| 304 |
+
|
| 305 |
+
This is an optional property specific to `duplicate`'s options object and will set the timeout in minutes before the duplicated space will go to sleep.
|
| 306 |
+
|
| 307 |
+
```ts
|
| 308 |
+
import { duplicate } from "@gradio/client";
|
| 309 |
+
|
| 310 |
+
const app = await duplicate("user/space-name", {
|
| 311 |
+
hf_token: "hf_...",
|
| 312 |
+
private: true,
|
| 313 |
+
timeout: 5
|
| 314 |
+
});
|
| 315 |
+
```
|
| 316 |
+
|
| 317 |
+
##### `hardware`
|
| 318 |
+
|
| 319 |
+
This is an optional property specific to `duplicate`'s options object and will set the hardware for the duplicated space. By default the hardware used will match that of the original space. If this cannot be obtained it will default to `"cpu-basic"`. For hardware upgrades (beyond the basic CPU tier), you may be required to provide [billing information on Hugging Face](https://huggingface.co/settings/billing).
|
| 320 |
+
|
| 321 |
+
Possible hardware options are:
|
| 322 |
+
|
| 323 |
+
- `"cpu-basic"`
|
| 324 |
+
- `"cpu-upgrade"`
|
| 325 |
+
- `"t4-small"`
|
| 326 |
+
- `"t4-medium"`
|
| 327 |
+
- `"a10g-small"`
|
| 328 |
+
- `"a10g-large"`
|
| 329 |
+
- `"a100-large"`
|
| 330 |
+
|
| 331 |
+
```ts
|
| 332 |
+
import { duplicate } from "@gradio/client";
|
| 333 |
+
|
| 334 |
+
const app = await duplicate("user/space-name", {
|
| 335 |
+
hf_token: "hf_...",
|
| 336 |
+
private: true,
|
| 337 |
+
hardware: "a10g-small"
|
| 338 |
+
});
|
| 339 |
+
```
|
node_modules/@gradio/client/dist/client.d.ts
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { hardware_types } from "./utils.js";
|
| 2 |
+
import type { EventType, EventListener, PostResponse, UploadResponse, SpaceStatusCallback } from "./types.js";
|
| 3 |
+
import type { Config } from "./types.js";
|
| 4 |
+
type event = <K extends EventType>(eventType: K, listener: EventListener<K>) => SubmitReturn;
|
| 5 |
+
type predict = (endpoint: string | number, data?: unknown[], event_data?: unknown) => Promise<unknown>;
|
| 6 |
+
type client_return = {
|
| 7 |
+
predict: predict;
|
| 8 |
+
config: Config;
|
| 9 |
+
submit: (endpoint: string | number, data?: unknown[], event_data?: unknown, trigger_id?: number | null) => SubmitReturn;
|
| 10 |
+
component_server: (component_id: number, fn_name: string, data: unknown[]) => any;
|
| 11 |
+
view_api: (c?: Config) => Promise<ApiInfo<JsApiData>>;
|
| 12 |
+
};
|
| 13 |
+
type SubmitReturn = {
|
| 14 |
+
on: event;
|
| 15 |
+
off: event;
|
| 16 |
+
cancel: () => Promise<void>;
|
| 17 |
+
destroy: () => void;
|
| 18 |
+
};
|
| 19 |
+
export declare let NodeBlob: any;
|
| 20 |
+
export declare function duplicate(app_reference: string, options: {
|
| 21 |
+
hf_token: `hf_${string}`;
|
| 22 |
+
private?: boolean;
|
| 23 |
+
status_callback: SpaceStatusCallback;
|
| 24 |
+
hardware?: (typeof hardware_types)[number];
|
| 25 |
+
timeout?: number;
|
| 26 |
+
}): Promise<client_return>;
|
| 27 |
+
interface Client {
|
| 28 |
+
post_data: (url: string, body: unknown, token?: `hf_${string}`) => Promise<[PostResponse, number]>;
|
| 29 |
+
upload_files: (root: string, files: File[], token?: `hf_${string}`, upload_id?: string) => Promise<UploadResponse>;
|
| 30 |
+
client: (app_reference: string, options: {
|
| 31 |
+
hf_token?: `hf_${string}`;
|
| 32 |
+
status_callback?: SpaceStatusCallback;
|
| 33 |
+
normalise_files?: boolean;
|
| 34 |
+
}) => Promise<client_return>;
|
| 35 |
+
handle_blob: (endpoint: string, data: unknown[], api_info: ApiInfo<JsApiData>, token?: `hf_${string}`) => Promise<unknown[]>;
|
| 36 |
+
}
|
| 37 |
+
export declare function api_factory(fetch_implementation: typeof fetch, WebSocket_factory: (url: URL) => WebSocket): Client;
|
| 38 |
+
export declare const post_data: (url: string, body: unknown, token?: `hf_${string}`) => Promise<[PostResponse, number]>, upload_files: (root: string, files: File[], token?: `hf_${string}`, upload_id?: string) => Promise<UploadResponse>, client: (app_reference: string, options: {
|
| 39 |
+
hf_token?: `hf_${string}`;
|
| 40 |
+
status_callback?: SpaceStatusCallback;
|
| 41 |
+
normalise_files?: boolean;
|
| 42 |
+
}) => Promise<client_return>, handle_blob: (endpoint: string, data: unknown[], api_info: ApiInfo<JsApiData>, token?: `hf_${string}`) => Promise<unknown[]>;
|
| 43 |
+
interface ApiData {
|
| 44 |
+
label: string;
|
| 45 |
+
type: {
|
| 46 |
+
type: any;
|
| 47 |
+
description: string;
|
| 48 |
+
};
|
| 49 |
+
component: string;
|
| 50 |
+
example_input?: any;
|
| 51 |
+
}
|
| 52 |
+
interface JsApiData {
|
| 53 |
+
label: string;
|
| 54 |
+
type: string;
|
| 55 |
+
component: string;
|
| 56 |
+
example_input: any;
|
| 57 |
+
}
|
| 58 |
+
interface EndpointInfo<T extends ApiData | JsApiData> {
|
| 59 |
+
parameters: T[];
|
| 60 |
+
returns: T[];
|
| 61 |
+
}
|
| 62 |
+
interface ApiInfo<T extends ApiData | JsApiData> {
|
| 63 |
+
named_endpoints: {
|
| 64 |
+
[key: string]: EndpointInfo<T>;
|
| 65 |
+
};
|
| 66 |
+
unnamed_endpoints: {
|
| 67 |
+
[key: string]: EndpointInfo<T>;
|
| 68 |
+
};
|
| 69 |
+
}
|
| 70 |
+
export declare function walk_and_store_blobs(param: any, type?: any, path?: any[], root?: boolean, api_info?: any): Promise<{
|
| 71 |
+
path: string[];
|
| 72 |
+
type: string;
|
| 73 |
+
blob: Blob | false;
|
| 74 |
+
}[]>;
|
| 75 |
+
export {};
|
| 76 |
+
//# sourceMappingURL=client.d.ts.map
|
node_modules/@gradio/client/dist/client.d.ts.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
{"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AA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AAM,GAAG,YAAY,CAAC,CAAC,CAAC,CAAC;KAC/B,CAAC;CACF;AAiID,wBAAsB,oBAAoB,CACzC,KAAK,KAAA,EACL,IAAI,MAAY,EAChB,IAAI,QAAK,EACT,IAAI,UAAQ,EACZ,QAAQ,MAAY,GAClB,OAAO,CACT;IACC,IAAI,EAAE,MAAM,EAAE,CAAC;IACf,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,IAAI,GAAG,KAAK,CAAC;CACnB,EAAE,CACH,CAmDA"}
|
node_modules/@gradio/client/dist/index.d.ts
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
export { client, post_data, upload_files, duplicate, api_factory } from "./client.js";
|
| 2 |
+
export type { SpaceStatus } from "./types.js";
|
| 3 |
+
export { normalise_file, FileData, upload, get_fetchable_url_or_file, prepare_files } from "./upload.js";
|
| 4 |
+
//# sourceMappingURL=index.d.ts.map
|
node_modules/@gradio/client/dist/index.d.ts.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,MAAM,EACN,SAAS,EACT,YAAY,EACZ,SAAS,EACT,WAAW,EACX,MAAM,aAAa,CAAC;AACrB,YAAY,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAC9C,OAAO,EACN,cAAc,EACd,QAAQ,EACR,MAAM,EACN,yBAAyB,EACzB,aAAa,EACb,MAAM,aAAa,CAAC"}
|
node_modules/@gradio/client/dist/index.js
ADDED
|
@@ -0,0 +1,1388 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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numeric: 1 }).compare;
|
| 2 |
+
function semiver(a, b, bool) {
|
| 3 |
+
a = a.split(".");
|
| 4 |
+
b = b.split(".");
|
| 5 |
+
return fn(a[0], b[0]) || fn(a[1], b[1]) || (b[2] = b.slice(2).join("."), bool = /[.-]/.test(a[2] = a.slice(2).join(".")), bool == /[.-]/.test(b[2]) ? fn(a[2], b[2]) : bool ? -1 : 1);
|
| 6 |
+
}
|
| 7 |
+
function resolve_root(base_url, root_path, prioritize_base) {
|
| 8 |
+
if (root_path.startsWith("http://") || root_path.startsWith("https://")) {
|
| 9 |
+
return prioritize_base ? base_url : root_path;
|
| 10 |
+
}
|
| 11 |
+
return base_url + root_path;
|
| 12 |
+
}
|
| 13 |
+
function determine_protocol(endpoint) {
|
| 14 |
+
if (endpoint.startsWith("http")) {
|
| 15 |
+
const { protocol, host } = new URL(endpoint);
|
| 16 |
+
if (host.endsWith("hf.space")) {
|
| 17 |
+
return {
|
| 18 |
+
ws_protocol: "wss",
|
| 19 |
+
host,
|
| 20 |
+
http_protocol: protocol
|
| 21 |
+
};
|
| 22 |
+
}
|
| 23 |
+
return {
|
| 24 |
+
ws_protocol: protocol === "https:" ? "wss" : "ws",
|
| 25 |
+
http_protocol: protocol,
|
| 26 |
+
host
|
| 27 |
+
};
|
| 28 |
+
} else if (endpoint.startsWith("file:")) {
|
| 29 |
+
return {
|
| 30 |
+
ws_protocol: "ws",
|
| 31 |
+
http_protocol: "http:",
|
| 32 |
+
host: "lite.local"
|
| 33 |
+
// Special fake hostname only used for this case. This matches the hostname allowed in `is_self_host()` in `js/wasm/network/host.ts`.
|
| 34 |
+
};
|
| 35 |
+
}
|
| 36 |
+
return {
|
| 37 |
+
ws_protocol: "wss",
|
| 38 |
+
http_protocol: "https:",
|
| 39 |
+
host: endpoint
|
| 40 |
+
};
|
| 41 |
+
}
|
| 42 |
+
const RE_SPACE_NAME = /^[^\/]*\/[^\/]*$/;
|
| 43 |
+
const RE_SPACE_DOMAIN = /.*hf\.space\/{0,1}$/;
|
| 44 |
+
async function process_endpoint(app_reference, token) {
|
| 45 |
+
const headers = {};
|
| 46 |
+
if (token) {
|
| 47 |
+
headers.Authorization = `Bearer ${token}`;
|
| 48 |
+
}
|
| 49 |
+
const _app_reference = app_reference.trim();
|
| 50 |
+
if (RE_SPACE_NAME.test(_app_reference)) {
|
| 51 |
+
try {
|
| 52 |
+
const res = await fetch(
|
| 53 |
+
`https://huggingface.co/api/spaces/${_app_reference}/host`,
|
| 54 |
+
{ headers }
|
| 55 |
+
);
|
| 56 |
+
if (res.status !== 200)
|
| 57 |
+
throw new Error("Space metadata could not be loaded.");
|
| 58 |
+
const _host = (await res.json()).host;
|
| 59 |
+
return {
|
| 60 |
+
space_id: app_reference,
|
| 61 |
+
...determine_protocol(_host)
|
| 62 |
+
};
|
| 63 |
+
} catch (e) {
|
| 64 |
+
throw new Error("Space metadata could not be loaded." + e.message);
|
| 65 |
+
}
|
| 66 |
+
}
|
| 67 |
+
if (RE_SPACE_DOMAIN.test(_app_reference)) {
|
| 68 |
+
const { ws_protocol, http_protocol, host } = determine_protocol(_app_reference);
|
| 69 |
+
return {
|
| 70 |
+
space_id: host.replace(".hf.space", ""),
|
| 71 |
+
ws_protocol,
|
| 72 |
+
http_protocol,
|
| 73 |
+
host
|
| 74 |
+
};
|
| 75 |
+
}
|
| 76 |
+
return {
|
| 77 |
+
space_id: false,
|
| 78 |
+
...determine_protocol(_app_reference)
|
| 79 |
+
};
|
| 80 |
+
}
|
| 81 |
+
function map_names_to_ids(fns) {
|
| 82 |
+
let apis = {};
|
| 83 |
+
fns.forEach(({ api_name }, i) => {
|
| 84 |
+
if (api_name)
|
| 85 |
+
apis[api_name] = i;
|
| 86 |
+
});
|
| 87 |
+
return apis;
|
| 88 |
+
}
|
| 89 |
+
const RE_DISABLED_DISCUSSION = /^(?=[^]*\b[dD]iscussions{0,1}\b)(?=[^]*\b[dD]isabled\b)[^]*$/;
|
| 90 |
+
async function discussions_enabled(space_id) {
|
| 91 |
+
try {
|
| 92 |
+
const r = await fetch(
|
| 93 |
+
`https://huggingface.co/api/spaces/${space_id}/discussions`,
|
| 94 |
+
{
|
| 95 |
+
method: "HEAD"
|
| 96 |
+
}
|
| 97 |
+
);
|
| 98 |
+
const error = r.headers.get("x-error-message");
|
| 99 |
+
if (error && RE_DISABLED_DISCUSSION.test(error))
|
| 100 |
+
return false;
|
| 101 |
+
return true;
|
| 102 |
+
} catch (e) {
|
| 103 |
+
return false;
|
| 104 |
+
}
|
| 105 |
+
}
|
| 106 |
+
async function get_space_hardware(space_id, token) {
|
| 107 |
+
const headers = {};
|
| 108 |
+
if (token) {
|
| 109 |
+
headers.Authorization = `Bearer ${token}`;
|
| 110 |
+
}
|
| 111 |
+
try {
|
| 112 |
+
const res = await fetch(
|
| 113 |
+
`https://huggingface.co/api/spaces/${space_id}/runtime`,
|
| 114 |
+
{ headers }
|
| 115 |
+
);
|
| 116 |
+
if (res.status !== 200)
|
| 117 |
+
throw new Error("Space hardware could not be obtained.");
|
| 118 |
+
const { hardware } = await res.json();
|
| 119 |
+
return hardware;
|
| 120 |
+
} catch (e) {
|
| 121 |
+
throw new Error(e.message);
|
| 122 |
+
}
|
| 123 |
+
}
|
| 124 |
+
async function set_space_hardware(space_id, new_hardware, token) {
|
| 125 |
+
const headers = {};
|
| 126 |
+
if (token) {
|
| 127 |
+
headers.Authorization = `Bearer ${token}`;
|
| 128 |
+
}
|
| 129 |
+
try {
|
| 130 |
+
const res = await fetch(
|
| 131 |
+
`https://huggingface.co/api/spaces/${space_id}/hardware`,
|
| 132 |
+
{ headers, body: JSON.stringify(new_hardware) }
|
| 133 |
+
);
|
| 134 |
+
if (res.status !== 200)
|
| 135 |
+
throw new Error(
|
| 136 |
+
"Space hardware could not be set. Please ensure the space hardware provided is valid and that a Hugging Face token is passed in."
|
| 137 |
+
);
|
| 138 |
+
const { hardware } = await res.json();
|
| 139 |
+
return hardware;
|
| 140 |
+
} catch (e) {
|
| 141 |
+
throw new Error(e.message);
|
| 142 |
+
}
|
| 143 |
+
}
|
| 144 |
+
async function set_space_timeout(space_id, timeout, token) {
|
| 145 |
+
const headers = {};
|
| 146 |
+
if (token) {
|
| 147 |
+
headers.Authorization = `Bearer ${token}`;
|
| 148 |
+
}
|
| 149 |
+
try {
|
| 150 |
+
const res = await fetch(
|
| 151 |
+
`https://huggingface.co/api/spaces/${space_id}/hardware`,
|
| 152 |
+
{ headers, body: JSON.stringify({ seconds: timeout }) }
|
| 153 |
+
);
|
| 154 |
+
if (res.status !== 200)
|
| 155 |
+
throw new Error(
|
| 156 |
+
"Space hardware could not be set. Please ensure the space hardware provided is valid and that a Hugging Face token is passed in."
|
| 157 |
+
);
|
| 158 |
+
const { hardware } = await res.json();
|
| 159 |
+
return hardware;
|
| 160 |
+
} catch (e) {
|
| 161 |
+
throw new Error(e.message);
|
| 162 |
+
}
|
| 163 |
+
}
|
| 164 |
+
const hardware_types = [
|
| 165 |
+
"cpu-basic",
|
| 166 |
+
"cpu-upgrade",
|
| 167 |
+
"t4-small",
|
| 168 |
+
"t4-medium",
|
| 169 |
+
"a10g-small",
|
| 170 |
+
"a10g-large",
|
| 171 |
+
"a100-large"
|
| 172 |
+
];
|
| 173 |
+
function normalise_file(file, server_url, proxy_url) {
|
| 174 |
+
if (file == null) {
|
| 175 |
+
return null;
|
| 176 |
+
}
|
| 177 |
+
if (Array.isArray(file)) {
|
| 178 |
+
const normalized_file = [];
|
| 179 |
+
for (const x of file) {
|
| 180 |
+
if (x == null) {
|
| 181 |
+
normalized_file.push(null);
|
| 182 |
+
} else {
|
| 183 |
+
normalized_file.push(normalise_file(x, server_url, proxy_url));
|
| 184 |
+
}
|
| 185 |
+
}
|
| 186 |
+
return normalized_file;
|
| 187 |
+
}
|
| 188 |
+
if (file.is_stream) {
|
| 189 |
+
if (proxy_url == null) {
|
| 190 |
+
return new FileData({
|
| 191 |
+
...file,
|
| 192 |
+
url: server_url + "/stream/" + file.path
|
| 193 |
+
});
|
| 194 |
+
}
|
| 195 |
+
return new FileData({
|
| 196 |
+
...file,
|
| 197 |
+
url: "/proxy=" + proxy_url + "stream/" + file.path
|
| 198 |
+
});
|
| 199 |
+
}
|
| 200 |
+
return new FileData({
|
| 201 |
+
...file,
|
| 202 |
+
url: get_fetchable_url_or_file(file.path, server_url, proxy_url)
|
| 203 |
+
});
|
| 204 |
+
}
|
| 205 |
+
function is_url(str) {
|
| 206 |
+
try {
|
| 207 |
+
const url = new URL(str);
|
| 208 |
+
return url.protocol === "http:" || url.protocol === "https:";
|
| 209 |
+
} catch {
|
| 210 |
+
return false;
|
| 211 |
+
}
|
| 212 |
+
}
|
| 213 |
+
function get_fetchable_url_or_file(path, server_url, proxy_url) {
|
| 214 |
+
if (path == null) {
|
| 215 |
+
return proxy_url ? `/proxy=${proxy_url}file=` : `${server_url}/file=`;
|
| 216 |
+
}
|
| 217 |
+
if (is_url(path)) {
|
| 218 |
+
return path;
|
| 219 |
+
}
|
| 220 |
+
return proxy_url ? `/proxy=${proxy_url}file=${path}` : `${server_url}/file=${path}`;
|
| 221 |
+
}
|
| 222 |
+
async function upload(file_data, root, upload_id, upload_fn = upload_files) {
|
| 223 |
+
let files = (Array.isArray(file_data) ? file_data : [file_data]).map(
|
| 224 |
+
(file_data2) => file_data2.blob
|
| 225 |
+
);
|
| 226 |
+
return await Promise.all(
|
| 227 |
+
await upload_fn(root, files, void 0, upload_id).then(
|
| 228 |
+
async (response) => {
|
| 229 |
+
if (response.error) {
|
| 230 |
+
throw new Error(response.error);
|
| 231 |
+
} else {
|
| 232 |
+
if (response.files) {
|
| 233 |
+
return response.files.map((f, i) => {
|
| 234 |
+
const file = new FileData({ ...file_data[i], path: f });
|
| 235 |
+
return normalise_file(file, root, null);
|
| 236 |
+
});
|
| 237 |
+
}
|
| 238 |
+
return [];
|
| 239 |
+
}
|
| 240 |
+
}
|
| 241 |
+
)
|
| 242 |
+
);
|
| 243 |
+
}
|
| 244 |
+
async function prepare_files(files, is_stream) {
|
| 245 |
+
return files.map(
|
| 246 |
+
(f, i) => new FileData({
|
| 247 |
+
path: f.name,
|
| 248 |
+
orig_name: f.name,
|
| 249 |
+
blob: f,
|
| 250 |
+
size: f.size,
|
| 251 |
+
mime_type: f.type,
|
| 252 |
+
is_stream
|
| 253 |
+
})
|
| 254 |
+
);
|
| 255 |
+
}
|
| 256 |
+
class FileData {
|
| 257 |
+
constructor({
|
| 258 |
+
path,
|
| 259 |
+
url,
|
| 260 |
+
orig_name,
|
| 261 |
+
size,
|
| 262 |
+
blob,
|
| 263 |
+
is_stream,
|
| 264 |
+
mime_type,
|
| 265 |
+
alt_text
|
| 266 |
+
}) {
|
| 267 |
+
this.path = path;
|
| 268 |
+
this.url = url;
|
| 269 |
+
this.orig_name = orig_name;
|
| 270 |
+
this.size = size;
|
| 271 |
+
this.blob = url ? void 0 : blob;
|
| 272 |
+
this.is_stream = is_stream;
|
| 273 |
+
this.mime_type = mime_type;
|
| 274 |
+
this.alt_text = alt_text;
|
| 275 |
+
}
|
| 276 |
+
}
|
| 277 |
+
const QUEUE_FULL_MSG = "This application is too busy. Keep trying!";
|
| 278 |
+
const BROKEN_CONNECTION_MSG = "Connection errored out.";
|
| 279 |
+
let NodeBlob;
|
| 280 |
+
async function duplicate(app_reference, options) {
|
| 281 |
+
const { hf_token, private: _private, hardware, timeout } = options;
|
| 282 |
+
if (hardware && !hardware_types.includes(hardware)) {
|
| 283 |
+
throw new Error(
|
| 284 |
+
`Invalid hardware type provided. Valid types are: ${hardware_types.map((v) => `"${v}"`).join(",")}.`
|
| 285 |
+
);
|
| 286 |
+
}
|
| 287 |
+
const headers = {
|
| 288 |
+
Authorization: `Bearer ${hf_token}`
|
| 289 |
+
};
|
| 290 |
+
const user = (await (await fetch(`https://huggingface.co/api/whoami-v2`, {
|
| 291 |
+
headers
|
| 292 |
+
})).json()).name;
|
| 293 |
+
const space_name = app_reference.split("/")[1];
|
| 294 |
+
const body = {
|
| 295 |
+
repository: `${user}/${space_name}`
|
| 296 |
+
};
|
| 297 |
+
if (_private) {
|
| 298 |
+
body.private = true;
|
| 299 |
+
}
|
| 300 |
+
try {
|
| 301 |
+
const response = await fetch(
|
| 302 |
+
`https://huggingface.co/api/spaces/${app_reference}/duplicate`,
|
| 303 |
+
{
|
| 304 |
+
method: "POST",
|
| 305 |
+
headers: { "Content-Type": "application/json", ...headers },
|
| 306 |
+
body: JSON.stringify(body)
|
| 307 |
+
}
|
| 308 |
+
);
|
| 309 |
+
if (response.status === 409) {
|
| 310 |
+
return client(`${user}/${space_name}`, options);
|
| 311 |
+
}
|
| 312 |
+
const duplicated_space = await response.json();
|
| 313 |
+
let original_hardware;
|
| 314 |
+
if (!hardware) {
|
| 315 |
+
original_hardware = await get_space_hardware(app_reference, hf_token);
|
| 316 |
+
}
|
| 317 |
+
const requested_hardware = hardware || original_hardware || "cpu-basic";
|
| 318 |
+
await set_space_hardware(
|
| 319 |
+
`${user}/${space_name}`,
|
| 320 |
+
requested_hardware,
|
| 321 |
+
hf_token
|
| 322 |
+
);
|
| 323 |
+
await set_space_timeout(`${user}/${space_name}`, timeout || 300, hf_token);
|
| 324 |
+
return client(duplicated_space.url, options);
|
| 325 |
+
} catch (e) {
|
| 326 |
+
throw new Error(e);
|
| 327 |
+
}
|
| 328 |
+
}
|
| 329 |
+
function api_factory(fetch_implementation, WebSocket_factory) {
|
| 330 |
+
return { post_data: post_data2, upload_files: upload_files2, client: client2, handle_blob: handle_blob2 };
|
| 331 |
+
async function post_data2(url, body, token) {
|
| 332 |
+
const headers = { "Content-Type": "application/json" };
|
| 333 |
+
if (token) {
|
| 334 |
+
headers.Authorization = `Bearer ${token}`;
|
| 335 |
+
}
|
| 336 |
+
try {
|
| 337 |
+
var response = await fetch_implementation(url, {
|
| 338 |
+
method: "POST",
|
| 339 |
+
body: JSON.stringify(body),
|
| 340 |
+
headers
|
| 341 |
+
});
|
| 342 |
+
} catch (e) {
|
| 343 |
+
return [{ error: BROKEN_CONNECTION_MSG }, 500];
|
| 344 |
+
}
|
| 345 |
+
const output = await response.json();
|
| 346 |
+
return [output, response.status];
|
| 347 |
+
}
|
| 348 |
+
async function upload_files2(root, files, token, upload_id) {
|
| 349 |
+
const headers = {};
|
| 350 |
+
if (token) {
|
| 351 |
+
headers.Authorization = `Bearer ${token}`;
|
| 352 |
+
}
|
| 353 |
+
const chunkSize = 1e3;
|
| 354 |
+
const uploadResponses = [];
|
| 355 |
+
for (let i = 0; i < files.length; i += chunkSize) {
|
| 356 |
+
const chunk = files.slice(i, i + chunkSize);
|
| 357 |
+
const formData = new FormData();
|
| 358 |
+
chunk.forEach((file) => {
|
| 359 |
+
formData.append("files", file);
|
| 360 |
+
});
|
| 361 |
+
try {
|
| 362 |
+
const upload_url = upload_id ? `${root}/upload?upload_id=${upload_id}` : `${root}/upload`;
|
| 363 |
+
var response = await fetch_implementation(upload_url, {
|
| 364 |
+
method: "POST",
|
| 365 |
+
body: formData,
|
| 366 |
+
headers
|
| 367 |
+
});
|
| 368 |
+
} catch (e) {
|
| 369 |
+
return { error: BROKEN_CONNECTION_MSG };
|
| 370 |
+
}
|
| 371 |
+
const output = await response.json();
|
| 372 |
+
uploadResponses.push(...output);
|
| 373 |
+
}
|
| 374 |
+
return { files: uploadResponses };
|
| 375 |
+
}
|
| 376 |
+
async function client2(app_reference, options = { normalise_files: true }) {
|
| 377 |
+
return new Promise(async (res) => {
|
| 378 |
+
const { status_callback, hf_token, normalise_files } = options;
|
| 379 |
+
const return_obj = {
|
| 380 |
+
predict,
|
| 381 |
+
submit,
|
| 382 |
+
view_api,
|
| 383 |
+
component_server
|
| 384 |
+
};
|
| 385 |
+
const transform_files = normalise_files ?? true;
|
| 386 |
+
if ((typeof window === "undefined" || !("WebSocket" in window)) && !global.Websocket) {
|
| 387 |
+
const ws = await import("./wrapper-6f348d45.js");
|
| 388 |
+
NodeBlob = (await import("node:buffer")).Blob;
|
| 389 |
+
global.WebSocket = ws.WebSocket;
|
| 390 |
+
}
|
| 391 |
+
const { ws_protocol, http_protocol, host, space_id } = await process_endpoint(app_reference, hf_token);
|
| 392 |
+
const session_hash = Math.random().toString(36).substring(2);
|
| 393 |
+
const last_status = {};
|
| 394 |
+
let config;
|
| 395 |
+
let api_map = {};
|
| 396 |
+
let jwt = false;
|
| 397 |
+
if (hf_token && space_id) {
|
| 398 |
+
jwt = await get_jwt(space_id, hf_token);
|
| 399 |
+
}
|
| 400 |
+
async function config_success(_config) {
|
| 401 |
+
config = _config;
|
| 402 |
+
api_map = map_names_to_ids((_config == null ? void 0 : _config.dependencies) || []);
|
| 403 |
+
if (config.auth_required) {
|
| 404 |
+
return {
|
| 405 |
+
config,
|
| 406 |
+
...return_obj
|
| 407 |
+
};
|
| 408 |
+
}
|
| 409 |
+
try {
|
| 410 |
+
api = await view_api(config);
|
| 411 |
+
} catch (e) {
|
| 412 |
+
console.error(`Could not get api details: ${e.message}`);
|
| 413 |
+
}
|
| 414 |
+
return {
|
| 415 |
+
config,
|
| 416 |
+
...return_obj
|
| 417 |
+
};
|
| 418 |
+
}
|
| 419 |
+
let api;
|
| 420 |
+
async function handle_space_sucess(status) {
|
| 421 |
+
if (status_callback)
|
| 422 |
+
status_callback(status);
|
| 423 |
+
if (status.status === "running")
|
| 424 |
+
try {
|
| 425 |
+
config = await resolve_config(
|
| 426 |
+
fetch_implementation,
|
| 427 |
+
`${http_protocol}//${host}`,
|
| 428 |
+
hf_token
|
| 429 |
+
);
|
| 430 |
+
const _config = await config_success(config);
|
| 431 |
+
res(_config);
|
| 432 |
+
} catch (e) {
|
| 433 |
+
console.error(e);
|
| 434 |
+
if (status_callback) {
|
| 435 |
+
status_callback({
|
| 436 |
+
status: "error",
|
| 437 |
+
message: "Could not load this space.",
|
| 438 |
+
load_status: "error",
|
| 439 |
+
detail: "NOT_FOUND"
|
| 440 |
+
});
|
| 441 |
+
}
|
| 442 |
+
}
|
| 443 |
+
}
|
| 444 |
+
try {
|
| 445 |
+
config = await resolve_config(
|
| 446 |
+
fetch_implementation,
|
| 447 |
+
`${http_protocol}//${host}`,
|
| 448 |
+
hf_token
|
| 449 |
+
);
|
| 450 |
+
const _config = await config_success(config);
|
| 451 |
+
res(_config);
|
| 452 |
+
} catch (e) {
|
| 453 |
+
console.error(e);
|
| 454 |
+
if (space_id) {
|
| 455 |
+
check_space_status(
|
| 456 |
+
space_id,
|
| 457 |
+
RE_SPACE_NAME.test(space_id) ? "space_name" : "subdomain",
|
| 458 |
+
handle_space_sucess
|
| 459 |
+
);
|
| 460 |
+
} else {
|
| 461 |
+
if (status_callback)
|
| 462 |
+
status_callback({
|
| 463 |
+
status: "error",
|
| 464 |
+
message: "Could not load this space.",
|
| 465 |
+
load_status: "error",
|
| 466 |
+
detail: "NOT_FOUND"
|
| 467 |
+
});
|
| 468 |
+
}
|
| 469 |
+
}
|
| 470 |
+
function predict(endpoint, data, event_data) {
|
| 471 |
+
let data_returned = false;
|
| 472 |
+
let status_complete = false;
|
| 473 |
+
let dependency;
|
| 474 |
+
if (typeof endpoint === "number") {
|
| 475 |
+
dependency = config.dependencies[endpoint];
|
| 476 |
+
} else {
|
| 477 |
+
const trimmed_endpoint = endpoint.replace(/^\//, "");
|
| 478 |
+
dependency = config.dependencies[api_map[trimmed_endpoint]];
|
| 479 |
+
}
|
| 480 |
+
if (dependency.types.continuous) {
|
| 481 |
+
throw new Error(
|
| 482 |
+
"Cannot call predict on this function as it may run forever. Use submit instead"
|
| 483 |
+
);
|
| 484 |
+
}
|
| 485 |
+
return new Promise((res2, rej) => {
|
| 486 |
+
const app = submit(endpoint, data, event_data);
|
| 487 |
+
let result;
|
| 488 |
+
app.on("data", (d) => {
|
| 489 |
+
if (status_complete) {
|
| 490 |
+
app.destroy();
|
| 491 |
+
res2(d);
|
| 492 |
+
}
|
| 493 |
+
data_returned = true;
|
| 494 |
+
result = d;
|
| 495 |
+
}).on("status", (status) => {
|
| 496 |
+
if (status.stage === "error")
|
| 497 |
+
rej(status);
|
| 498 |
+
if (status.stage === "complete") {
|
| 499 |
+
status_complete = true;
|
| 500 |
+
if (data_returned) {
|
| 501 |
+
app.destroy();
|
| 502 |
+
res2(result);
|
| 503 |
+
}
|
| 504 |
+
}
|
| 505 |
+
});
|
| 506 |
+
});
|
| 507 |
+
}
|
| 508 |
+
function submit(endpoint, data, event_data, trigger_id = null) {
|
| 509 |
+
let fn_index;
|
| 510 |
+
let api_info;
|
| 511 |
+
if (typeof endpoint === "number") {
|
| 512 |
+
fn_index = endpoint;
|
| 513 |
+
api_info = api.unnamed_endpoints[fn_index];
|
| 514 |
+
} else {
|
| 515 |
+
const trimmed_endpoint = endpoint.replace(/^\//, "");
|
| 516 |
+
fn_index = api_map[trimmed_endpoint];
|
| 517 |
+
api_info = api.named_endpoints[endpoint.trim()];
|
| 518 |
+
}
|
| 519 |
+
if (typeof fn_index !== "number") {
|
| 520 |
+
throw new Error(
|
| 521 |
+
"There is no endpoint matching that name of fn_index matching that number."
|
| 522 |
+
);
|
| 523 |
+
}
|
| 524 |
+
let websocket;
|
| 525 |
+
let eventSource;
|
| 526 |
+
let protocol = config.protocol ?? "sse";
|
| 527 |
+
const _endpoint = typeof endpoint === "number" ? "/predict" : endpoint;
|
| 528 |
+
let payload;
|
| 529 |
+
let event_id = null;
|
| 530 |
+
let complete = false;
|
| 531 |
+
const listener_map = {};
|
| 532 |
+
let url_params = "";
|
| 533 |
+
if (typeof window !== "undefined") {
|
| 534 |
+
url_params = new URLSearchParams(window.location.search).toString();
|
| 535 |
+
}
|
| 536 |
+
handle_blob2(
|
| 537 |
+
`${http_protocol}//${resolve_root(host, config.path, true)}`,
|
| 538 |
+
data,
|
| 539 |
+
api_info,
|
| 540 |
+
hf_token
|
| 541 |
+
).then((_payload) => {
|
| 542 |
+
payload = { data: _payload || [], event_data, fn_index, trigger_id };
|
| 543 |
+
if (skip_queue(fn_index, config)) {
|
| 544 |
+
fire_event({
|
| 545 |
+
type: "status",
|
| 546 |
+
endpoint: _endpoint,
|
| 547 |
+
stage: "pending",
|
| 548 |
+
queue: false,
|
| 549 |
+
fn_index,
|
| 550 |
+
time: /* @__PURE__ */ new Date()
|
| 551 |
+
});
|
| 552 |
+
post_data2(
|
| 553 |
+
`${http_protocol}//${resolve_root(host, config.path, true)}/run${_endpoint.startsWith("/") ? _endpoint : `/${_endpoint}`}${url_params ? "?" + url_params : ""}`,
|
| 554 |
+
{
|
| 555 |
+
...payload,
|
| 556 |
+
session_hash
|
| 557 |
+
},
|
| 558 |
+
hf_token
|
| 559 |
+
).then(([output, status_code]) => {
|
| 560 |
+
const data2 = transform_files ? transform_output(
|
| 561 |
+
output.data,
|
| 562 |
+
api_info,
|
| 563 |
+
config.root,
|
| 564 |
+
config.root_url
|
| 565 |
+
) : output.data;
|
| 566 |
+
if (status_code == 200) {
|
| 567 |
+
fire_event({
|
| 568 |
+
type: "data",
|
| 569 |
+
endpoint: _endpoint,
|
| 570 |
+
fn_index,
|
| 571 |
+
data: data2,
|
| 572 |
+
time: /* @__PURE__ */ new Date()
|
| 573 |
+
});
|
| 574 |
+
fire_event({
|
| 575 |
+
type: "status",
|
| 576 |
+
endpoint: _endpoint,
|
| 577 |
+
fn_index,
|
| 578 |
+
stage: "complete",
|
| 579 |
+
eta: output.average_duration,
|
| 580 |
+
queue: false,
|
| 581 |
+
time: /* @__PURE__ */ new Date()
|
| 582 |
+
});
|
| 583 |
+
} else {
|
| 584 |
+
fire_event({
|
| 585 |
+
type: "status",
|
| 586 |
+
stage: "error",
|
| 587 |
+
endpoint: _endpoint,
|
| 588 |
+
fn_index,
|
| 589 |
+
message: output.error,
|
| 590 |
+
queue: false,
|
| 591 |
+
time: /* @__PURE__ */ new Date()
|
| 592 |
+
});
|
| 593 |
+
}
|
| 594 |
+
}).catch((e) => {
|
| 595 |
+
fire_event({
|
| 596 |
+
type: "status",
|
| 597 |
+
stage: "error",
|
| 598 |
+
message: e.message,
|
| 599 |
+
endpoint: _endpoint,
|
| 600 |
+
fn_index,
|
| 601 |
+
queue: false,
|
| 602 |
+
time: /* @__PURE__ */ new Date()
|
| 603 |
+
});
|
| 604 |
+
});
|
| 605 |
+
} else if (protocol == "ws") {
|
| 606 |
+
fire_event({
|
| 607 |
+
type: "status",
|
| 608 |
+
stage: "pending",
|
| 609 |
+
queue: true,
|
| 610 |
+
endpoint: _endpoint,
|
| 611 |
+
fn_index,
|
| 612 |
+
time: /* @__PURE__ */ new Date()
|
| 613 |
+
});
|
| 614 |
+
let url = new URL(`${ws_protocol}://${resolve_root(
|
| 615 |
+
host,
|
| 616 |
+
config.path,
|
| 617 |
+
true
|
| 618 |
+
)}
|
| 619 |
+
/queue/join${url_params ? "?" + url_params : ""}`);
|
| 620 |
+
if (jwt) {
|
| 621 |
+
url.searchParams.set("__sign", jwt);
|
| 622 |
+
}
|
| 623 |
+
websocket = WebSocket_factory(url);
|
| 624 |
+
websocket.onclose = (evt) => {
|
| 625 |
+
if (!evt.wasClean) {
|
| 626 |
+
fire_event({
|
| 627 |
+
type: "status",
|
| 628 |
+
stage: "error",
|
| 629 |
+
broken: true,
|
| 630 |
+
message: BROKEN_CONNECTION_MSG,
|
| 631 |
+
queue: true,
|
| 632 |
+
endpoint: _endpoint,
|
| 633 |
+
fn_index,
|
| 634 |
+
time: /* @__PURE__ */ new Date()
|
| 635 |
+
});
|
| 636 |
+
}
|
| 637 |
+
};
|
| 638 |
+
websocket.onmessage = function(event) {
|
| 639 |
+
const _data = JSON.parse(event.data);
|
| 640 |
+
const { type, status, data: data2 } = handle_message(
|
| 641 |
+
_data,
|
| 642 |
+
last_status[fn_index]
|
| 643 |
+
);
|
| 644 |
+
if (type === "update" && status && !complete) {
|
| 645 |
+
fire_event({
|
| 646 |
+
type: "status",
|
| 647 |
+
endpoint: _endpoint,
|
| 648 |
+
fn_index,
|
| 649 |
+
time: /* @__PURE__ */ new Date(),
|
| 650 |
+
...status
|
| 651 |
+
});
|
| 652 |
+
if (status.stage === "error") {
|
| 653 |
+
websocket.close();
|
| 654 |
+
}
|
| 655 |
+
} else if (type === "hash") {
|
| 656 |
+
websocket.send(JSON.stringify({ fn_index, session_hash }));
|
| 657 |
+
return;
|
| 658 |
+
} else if (type === "data") {
|
| 659 |
+
websocket.send(JSON.stringify({ ...payload, session_hash }));
|
| 660 |
+
} else if (type === "complete") {
|
| 661 |
+
complete = status;
|
| 662 |
+
} else if (type === "log") {
|
| 663 |
+
fire_event({
|
| 664 |
+
type: "log",
|
| 665 |
+
log: data2.log,
|
| 666 |
+
level: data2.level,
|
| 667 |
+
endpoint: _endpoint,
|
| 668 |
+
fn_index
|
| 669 |
+
});
|
| 670 |
+
} else if (type === "generating") {
|
| 671 |
+
fire_event({
|
| 672 |
+
type: "status",
|
| 673 |
+
time: /* @__PURE__ */ new Date(),
|
| 674 |
+
...status,
|
| 675 |
+
stage: status == null ? void 0 : status.stage,
|
| 676 |
+
queue: true,
|
| 677 |
+
endpoint: _endpoint,
|
| 678 |
+
fn_index
|
| 679 |
+
});
|
| 680 |
+
}
|
| 681 |
+
if (data2) {
|
| 682 |
+
fire_event({
|
| 683 |
+
type: "data",
|
| 684 |
+
time: /* @__PURE__ */ new Date(),
|
| 685 |
+
data: transform_files ? transform_output(
|
| 686 |
+
data2.data,
|
| 687 |
+
api_info,
|
| 688 |
+
config.root,
|
| 689 |
+
config.root_url
|
| 690 |
+
) : data2.data,
|
| 691 |
+
endpoint: _endpoint,
|
| 692 |
+
fn_index
|
| 693 |
+
});
|
| 694 |
+
if (complete) {
|
| 695 |
+
fire_event({
|
| 696 |
+
type: "status",
|
| 697 |
+
time: /* @__PURE__ */ new Date(),
|
| 698 |
+
...complete,
|
| 699 |
+
stage: status == null ? void 0 : status.stage,
|
| 700 |
+
queue: true,
|
| 701 |
+
endpoint: _endpoint,
|
| 702 |
+
fn_index
|
| 703 |
+
});
|
| 704 |
+
websocket.close();
|
| 705 |
+
}
|
| 706 |
+
}
|
| 707 |
+
};
|
| 708 |
+
if (semiver(config.version || "2.0.0", "3.6") < 0) {
|
| 709 |
+
addEventListener(
|
| 710 |
+
"open",
|
| 711 |
+
() => websocket.send(JSON.stringify({ hash: session_hash }))
|
| 712 |
+
);
|
| 713 |
+
}
|
| 714 |
+
} else {
|
| 715 |
+
fire_event({
|
| 716 |
+
type: "status",
|
| 717 |
+
stage: "pending",
|
| 718 |
+
queue: true,
|
| 719 |
+
endpoint: _endpoint,
|
| 720 |
+
fn_index,
|
| 721 |
+
time: /* @__PURE__ */ new Date()
|
| 722 |
+
});
|
| 723 |
+
var params = new URLSearchParams({
|
| 724 |
+
fn_index: fn_index.toString(),
|
| 725 |
+
session_hash
|
| 726 |
+
}).toString();
|
| 727 |
+
let url = new URL(
|
| 728 |
+
`${http_protocol}//${resolve_root(
|
| 729 |
+
host,
|
| 730 |
+
config.path,
|
| 731 |
+
true
|
| 732 |
+
)}/queue/join?${url_params ? url_params + "&" : ""}${params}`
|
| 733 |
+
);
|
| 734 |
+
eventSource = new EventSource(url);
|
| 735 |
+
eventSource.onmessage = async function(event) {
|
| 736 |
+
const _data = JSON.parse(event.data);
|
| 737 |
+
const { type, status, data: data2 } = handle_message(
|
| 738 |
+
_data,
|
| 739 |
+
last_status[fn_index]
|
| 740 |
+
);
|
| 741 |
+
if (type === "update" && status && !complete) {
|
| 742 |
+
fire_event({
|
| 743 |
+
type: "status",
|
| 744 |
+
endpoint: _endpoint,
|
| 745 |
+
fn_index,
|
| 746 |
+
time: /* @__PURE__ */ new Date(),
|
| 747 |
+
...status
|
| 748 |
+
});
|
| 749 |
+
if (status.stage === "error") {
|
| 750 |
+
eventSource.close();
|
| 751 |
+
}
|
| 752 |
+
} else if (type === "data") {
|
| 753 |
+
event_id = _data.event_id;
|
| 754 |
+
let [_, status2] = await post_data2(
|
| 755 |
+
`${http_protocol}//${resolve_root(
|
| 756 |
+
host,
|
| 757 |
+
config.path,
|
| 758 |
+
true
|
| 759 |
+
)}/queue/data`,
|
| 760 |
+
{
|
| 761 |
+
...payload,
|
| 762 |
+
session_hash,
|
| 763 |
+
event_id
|
| 764 |
+
},
|
| 765 |
+
hf_token
|
| 766 |
+
);
|
| 767 |
+
if (status2 !== 200) {
|
| 768 |
+
fire_event({
|
| 769 |
+
type: "status",
|
| 770 |
+
stage: "error",
|
| 771 |
+
message: BROKEN_CONNECTION_MSG,
|
| 772 |
+
queue: true,
|
| 773 |
+
endpoint: _endpoint,
|
| 774 |
+
fn_index,
|
| 775 |
+
time: /* @__PURE__ */ new Date()
|
| 776 |
+
});
|
| 777 |
+
eventSource.close();
|
| 778 |
+
}
|
| 779 |
+
} else if (type === "complete") {
|
| 780 |
+
complete = status;
|
| 781 |
+
} else if (type === "log") {
|
| 782 |
+
fire_event({
|
| 783 |
+
type: "log",
|
| 784 |
+
log: data2.log,
|
| 785 |
+
level: data2.level,
|
| 786 |
+
endpoint: _endpoint,
|
| 787 |
+
fn_index
|
| 788 |
+
});
|
| 789 |
+
} else if (type === "generating") {
|
| 790 |
+
fire_event({
|
| 791 |
+
type: "status",
|
| 792 |
+
time: /* @__PURE__ */ new Date(),
|
| 793 |
+
...status,
|
| 794 |
+
stage: status == null ? void 0 : status.stage,
|
| 795 |
+
queue: true,
|
| 796 |
+
endpoint: _endpoint,
|
| 797 |
+
fn_index
|
| 798 |
+
});
|
| 799 |
+
}
|
| 800 |
+
if (data2) {
|
| 801 |
+
fire_event({
|
| 802 |
+
type: "data",
|
| 803 |
+
time: /* @__PURE__ */ new Date(),
|
| 804 |
+
data: transform_files ? transform_output(
|
| 805 |
+
data2.data,
|
| 806 |
+
api_info,
|
| 807 |
+
config.root,
|
| 808 |
+
config.root_url
|
| 809 |
+
) : data2.data,
|
| 810 |
+
endpoint: _endpoint,
|
| 811 |
+
fn_index
|
| 812 |
+
});
|
| 813 |
+
if (complete) {
|
| 814 |
+
fire_event({
|
| 815 |
+
type: "status",
|
| 816 |
+
time: /* @__PURE__ */ new Date(),
|
| 817 |
+
...complete,
|
| 818 |
+
stage: status == null ? void 0 : status.stage,
|
| 819 |
+
queue: true,
|
| 820 |
+
endpoint: _endpoint,
|
| 821 |
+
fn_index
|
| 822 |
+
});
|
| 823 |
+
eventSource.close();
|
| 824 |
+
}
|
| 825 |
+
}
|
| 826 |
+
};
|
| 827 |
+
}
|
| 828 |
+
});
|
| 829 |
+
function fire_event(event) {
|
| 830 |
+
const narrowed_listener_map = listener_map;
|
| 831 |
+
const listeners = narrowed_listener_map[event.type] || [];
|
| 832 |
+
listeners == null ? void 0 : listeners.forEach((l) => l(event));
|
| 833 |
+
}
|
| 834 |
+
function on(eventType, listener) {
|
| 835 |
+
const narrowed_listener_map = listener_map;
|
| 836 |
+
const listeners = narrowed_listener_map[eventType] || [];
|
| 837 |
+
narrowed_listener_map[eventType] = listeners;
|
| 838 |
+
listeners == null ? void 0 : listeners.push(listener);
|
| 839 |
+
return { on, off, cancel, destroy };
|
| 840 |
+
}
|
| 841 |
+
function off(eventType, listener) {
|
| 842 |
+
const narrowed_listener_map = listener_map;
|
| 843 |
+
let listeners = narrowed_listener_map[eventType] || [];
|
| 844 |
+
listeners = listeners == null ? void 0 : listeners.filter((l) => l !== listener);
|
| 845 |
+
narrowed_listener_map[eventType] = listeners;
|
| 846 |
+
return { on, off, cancel, destroy };
|
| 847 |
+
}
|
| 848 |
+
async function cancel() {
|
| 849 |
+
const _status = {
|
| 850 |
+
stage: "complete",
|
| 851 |
+
queue: false,
|
| 852 |
+
time: /* @__PURE__ */ new Date()
|
| 853 |
+
};
|
| 854 |
+
complete = _status;
|
| 855 |
+
fire_event({
|
| 856 |
+
..._status,
|
| 857 |
+
type: "status",
|
| 858 |
+
endpoint: _endpoint,
|
| 859 |
+
fn_index
|
| 860 |
+
});
|
| 861 |
+
let cancel_request = {};
|
| 862 |
+
if (protocol === "ws") {
|
| 863 |
+
if (websocket && websocket.readyState === 0) {
|
| 864 |
+
websocket.addEventListener("open", () => {
|
| 865 |
+
websocket.close();
|
| 866 |
+
});
|
| 867 |
+
} else {
|
| 868 |
+
websocket.close();
|
| 869 |
+
}
|
| 870 |
+
cancel_request = { fn_index, session_hash };
|
| 871 |
+
} else {
|
| 872 |
+
eventSource.close();
|
| 873 |
+
cancel_request = { event_id };
|
| 874 |
+
}
|
| 875 |
+
try {
|
| 876 |
+
await fetch_implementation(
|
| 877 |
+
`${http_protocol}//${resolve_root(
|
| 878 |
+
host,
|
| 879 |
+
config.path,
|
| 880 |
+
true
|
| 881 |
+
)}/reset`,
|
| 882 |
+
{
|
| 883 |
+
headers: { "Content-Type": "application/json" },
|
| 884 |
+
method: "POST",
|
| 885 |
+
body: JSON.stringify(cancel_request)
|
| 886 |
+
}
|
| 887 |
+
);
|
| 888 |
+
} catch (e) {
|
| 889 |
+
console.warn(
|
| 890 |
+
"The `/reset` endpoint could not be called. Subsequent endpoint results may be unreliable."
|
| 891 |
+
);
|
| 892 |
+
}
|
| 893 |
+
}
|
| 894 |
+
function destroy() {
|
| 895 |
+
for (const event_type in listener_map) {
|
| 896 |
+
listener_map[event_type].forEach((fn2) => {
|
| 897 |
+
off(event_type, fn2);
|
| 898 |
+
});
|
| 899 |
+
}
|
| 900 |
+
}
|
| 901 |
+
return {
|
| 902 |
+
on,
|
| 903 |
+
off,
|
| 904 |
+
cancel,
|
| 905 |
+
destroy
|
| 906 |
+
};
|
| 907 |
+
}
|
| 908 |
+
async function component_server(component_id, fn_name, data) {
|
| 909 |
+
var _a;
|
| 910 |
+
const headers = { "Content-Type": "application/json" };
|
| 911 |
+
if (hf_token) {
|
| 912 |
+
headers.Authorization = `Bearer ${hf_token}`;
|
| 913 |
+
}
|
| 914 |
+
let root_url;
|
| 915 |
+
let component = config.components.find(
|
| 916 |
+
(comp) => comp.id === component_id
|
| 917 |
+
);
|
| 918 |
+
if ((_a = component == null ? void 0 : component.props) == null ? void 0 : _a.root_url) {
|
| 919 |
+
root_url = component.props.root_url;
|
| 920 |
+
} else {
|
| 921 |
+
root_url = `${http_protocol}//${resolve_root(
|
| 922 |
+
host,
|
| 923 |
+
config.path,
|
| 924 |
+
true
|
| 925 |
+
)}/`;
|
| 926 |
+
}
|
| 927 |
+
const response = await fetch_implementation(
|
| 928 |
+
`${root_url}component_server/`,
|
| 929 |
+
{
|
| 930 |
+
method: "POST",
|
| 931 |
+
body: JSON.stringify({
|
| 932 |
+
data,
|
| 933 |
+
component_id,
|
| 934 |
+
fn_name,
|
| 935 |
+
session_hash
|
| 936 |
+
}),
|
| 937 |
+
headers
|
| 938 |
+
}
|
| 939 |
+
);
|
| 940 |
+
if (!response.ok) {
|
| 941 |
+
throw new Error(
|
| 942 |
+
"Could not connect to component server: " + response.statusText
|
| 943 |
+
);
|
| 944 |
+
}
|
| 945 |
+
const output = await response.json();
|
| 946 |
+
return output;
|
| 947 |
+
}
|
| 948 |
+
async function view_api(config2) {
|
| 949 |
+
if (api)
|
| 950 |
+
return api;
|
| 951 |
+
const headers = { "Content-Type": "application/json" };
|
| 952 |
+
if (hf_token) {
|
| 953 |
+
headers.Authorization = `Bearer ${hf_token}`;
|
| 954 |
+
}
|
| 955 |
+
let response;
|
| 956 |
+
if (semiver(config2.version || "2.0.0", "3.30") < 0) {
|
| 957 |
+
response = await fetch_implementation(
|
| 958 |
+
"https://gradio-space-api-fetcher-v2.hf.space/api",
|
| 959 |
+
{
|
| 960 |
+
method: "POST",
|
| 961 |
+
body: JSON.stringify({
|
| 962 |
+
serialize: false,
|
| 963 |
+
config: JSON.stringify(config2)
|
| 964 |
+
}),
|
| 965 |
+
headers
|
| 966 |
+
}
|
| 967 |
+
);
|
| 968 |
+
} else {
|
| 969 |
+
response = await fetch_implementation(`${config2.root}/info`, {
|
| 970 |
+
headers
|
| 971 |
+
});
|
| 972 |
+
}
|
| 973 |
+
if (!response.ok) {
|
| 974 |
+
throw new Error(BROKEN_CONNECTION_MSG);
|
| 975 |
+
}
|
| 976 |
+
let api_info = await response.json();
|
| 977 |
+
if ("api" in api_info) {
|
| 978 |
+
api_info = api_info.api;
|
| 979 |
+
}
|
| 980 |
+
if (api_info.named_endpoints["/predict"] && !api_info.unnamed_endpoints["0"]) {
|
| 981 |
+
api_info.unnamed_endpoints[0] = api_info.named_endpoints["/predict"];
|
| 982 |
+
}
|
| 983 |
+
const x = transform_api_info(api_info, config2, api_map);
|
| 984 |
+
return x;
|
| 985 |
+
}
|
| 986 |
+
});
|
| 987 |
+
}
|
| 988 |
+
async function handle_blob2(endpoint, data, api_info, token) {
|
| 989 |
+
const blob_refs = await walk_and_store_blobs(
|
| 990 |
+
data,
|
| 991 |
+
void 0,
|
| 992 |
+
[],
|
| 993 |
+
true,
|
| 994 |
+
api_info
|
| 995 |
+
);
|
| 996 |
+
return Promise.all(
|
| 997 |
+
blob_refs.map(async ({ path, blob, type }) => {
|
| 998 |
+
if (blob) {
|
| 999 |
+
const file_url = (await upload_files2(endpoint, [blob], token)).files[0];
|
| 1000 |
+
return { path, file_url, type, name: blob == null ? void 0 : blob.name };
|
| 1001 |
+
}
|
| 1002 |
+
return { path, type };
|
| 1003 |
+
})
|
| 1004 |
+
).then((r) => {
|
| 1005 |
+
r.forEach(({ path, file_url, type, name }) => {
|
| 1006 |
+
if (type === "Gallery") {
|
| 1007 |
+
update_object(data, file_url, path);
|
| 1008 |
+
} else if (file_url) {
|
| 1009 |
+
const file = new FileData({ path: file_url, orig_name: name });
|
| 1010 |
+
update_object(data, file, path);
|
| 1011 |
+
}
|
| 1012 |
+
});
|
| 1013 |
+
return data;
|
| 1014 |
+
});
|
| 1015 |
+
}
|
| 1016 |
+
}
|
| 1017 |
+
const { post_data, upload_files, client, handle_blob } = api_factory(
|
| 1018 |
+
fetch,
|
| 1019 |
+
(...args) => new WebSocket(...args)
|
| 1020 |
+
);
|
| 1021 |
+
function transform_output(data, api_info, root_url, remote_url) {
|
| 1022 |
+
return data.map((d, i) => {
|
| 1023 |
+
var _a, _b, _c, _d;
|
| 1024 |
+
if (((_b = (_a = api_info == null ? void 0 : api_info.returns) == null ? void 0 : _a[i]) == null ? void 0 : _b.component) === "File") {
|
| 1025 |
+
return normalise_file(d, root_url, remote_url);
|
| 1026 |
+
} else if (((_d = (_c = api_info == null ? void 0 : api_info.returns) == null ? void 0 : _c[i]) == null ? void 0 : _d.component) === "Gallery") {
|
| 1027 |
+
return d.map((img) => {
|
| 1028 |
+
return Array.isArray(img) ? [normalise_file(img[0], root_url, remote_url), img[1]] : [normalise_file(img, root_url, remote_url), null];
|
| 1029 |
+
});
|
| 1030 |
+
} else if (typeof d === "object" && d.path) {
|
| 1031 |
+
return normalise_file(d, root_url, remote_url);
|
| 1032 |
+
}
|
| 1033 |
+
return d;
|
| 1034 |
+
});
|
| 1035 |
+
}
|
| 1036 |
+
function get_type(type, component, serializer, signature_type) {
|
| 1037 |
+
switch (type.type) {
|
| 1038 |
+
case "string":
|
| 1039 |
+
return "string";
|
| 1040 |
+
case "boolean":
|
| 1041 |
+
return "boolean";
|
| 1042 |
+
case "number":
|
| 1043 |
+
return "number";
|
| 1044 |
+
}
|
| 1045 |
+
if (serializer === "JSONSerializable" || serializer === "StringSerializable") {
|
| 1046 |
+
return "any";
|
| 1047 |
+
} else if (serializer === "ListStringSerializable") {
|
| 1048 |
+
return "string[]";
|
| 1049 |
+
} else if (component === "Image") {
|
| 1050 |
+
return signature_type === "parameter" ? "Blob | File | Buffer" : "string";
|
| 1051 |
+
} else if (serializer === "FileSerializable") {
|
| 1052 |
+
if ((type == null ? void 0 : type.type) === "array") {
|
| 1053 |
+
return signature_type === "parameter" ? "(Blob | File | Buffer)[]" : `{ name: string; data: string; size?: number; is_file?: boolean; orig_name?: string}[]`;
|
| 1054 |
+
}
|
| 1055 |
+
return signature_type === "parameter" ? "Blob | File | Buffer" : `{ name: string; data: string; size?: number; is_file?: boolean; orig_name?: string}`;
|
| 1056 |
+
} else if (serializer === "GallerySerializable") {
|
| 1057 |
+
return signature_type === "parameter" ? "[(Blob | File | Buffer), (string | null)][]" : `[{ name: string; data: string; size?: number; is_file?: boolean; orig_name?: string}, (string | null))][]`;
|
| 1058 |
+
}
|
| 1059 |
+
}
|
| 1060 |
+
function get_description(type, serializer) {
|
| 1061 |
+
if (serializer === "GallerySerializable") {
|
| 1062 |
+
return "array of [file, label] tuples";
|
| 1063 |
+
} else if (serializer === "ListStringSerializable") {
|
| 1064 |
+
return "array of strings";
|
| 1065 |
+
} else if (serializer === "FileSerializable") {
|
| 1066 |
+
return "array of files or single file";
|
| 1067 |
+
}
|
| 1068 |
+
return type.description;
|
| 1069 |
+
}
|
| 1070 |
+
function transform_api_info(api_info, config, api_map) {
|
| 1071 |
+
const new_data = {
|
| 1072 |
+
named_endpoints: {},
|
| 1073 |
+
unnamed_endpoints: {}
|
| 1074 |
+
};
|
| 1075 |
+
for (const key in api_info) {
|
| 1076 |
+
const cat = api_info[key];
|
| 1077 |
+
for (const endpoint in cat) {
|
| 1078 |
+
const dep_index = config.dependencies[endpoint] ? endpoint : api_map[endpoint.replace("/", "")];
|
| 1079 |
+
const info = cat[endpoint];
|
| 1080 |
+
new_data[key][endpoint] = {};
|
| 1081 |
+
new_data[key][endpoint].parameters = {};
|
| 1082 |
+
new_data[key][endpoint].returns = {};
|
| 1083 |
+
new_data[key][endpoint].type = config.dependencies[dep_index].types;
|
| 1084 |
+
new_data[key][endpoint].parameters = info.parameters.map(
|
| 1085 |
+
({ label, component, type, serializer }) => ({
|
| 1086 |
+
label,
|
| 1087 |
+
component,
|
| 1088 |
+
type: get_type(type, component, serializer, "parameter"),
|
| 1089 |
+
description: get_description(type, serializer)
|
| 1090 |
+
})
|
| 1091 |
+
);
|
| 1092 |
+
new_data[key][endpoint].returns = info.returns.map(
|
| 1093 |
+
({ label, component, type, serializer }) => ({
|
| 1094 |
+
label,
|
| 1095 |
+
component,
|
| 1096 |
+
type: get_type(type, component, serializer, "return"),
|
| 1097 |
+
description: get_description(type, serializer)
|
| 1098 |
+
})
|
| 1099 |
+
);
|
| 1100 |
+
}
|
| 1101 |
+
}
|
| 1102 |
+
return new_data;
|
| 1103 |
+
}
|
| 1104 |
+
async function get_jwt(space, token) {
|
| 1105 |
+
try {
|
| 1106 |
+
const r = await fetch(`https://huggingface.co/api/spaces/${space}/jwt`, {
|
| 1107 |
+
headers: {
|
| 1108 |
+
Authorization: `Bearer ${token}`
|
| 1109 |
+
}
|
| 1110 |
+
});
|
| 1111 |
+
const jwt = (await r.json()).token;
|
| 1112 |
+
return jwt || false;
|
| 1113 |
+
} catch (e) {
|
| 1114 |
+
console.error(e);
|
| 1115 |
+
return false;
|
| 1116 |
+
}
|
| 1117 |
+
}
|
| 1118 |
+
function update_object(object, newValue, stack) {
|
| 1119 |
+
while (stack.length > 1) {
|
| 1120 |
+
object = object[stack.shift()];
|
| 1121 |
+
}
|
| 1122 |
+
object[stack.shift()] = newValue;
|
| 1123 |
+
}
|
| 1124 |
+
async function walk_and_store_blobs(param, type = void 0, path = [], root = false, api_info = void 0) {
|
| 1125 |
+
if (Array.isArray(param)) {
|
| 1126 |
+
let blob_refs = [];
|
| 1127 |
+
await Promise.all(
|
| 1128 |
+
param.map(async (v, i) => {
|
| 1129 |
+
var _a;
|
| 1130 |
+
let new_path = path.slice();
|
| 1131 |
+
new_path.push(i);
|
| 1132 |
+
const array_refs = await walk_and_store_blobs(
|
| 1133 |
+
param[i],
|
| 1134 |
+
root ? ((_a = api_info == null ? void 0 : api_info.parameters[i]) == null ? void 0 : _a.component) || void 0 : type,
|
| 1135 |
+
new_path,
|
| 1136 |
+
false,
|
| 1137 |
+
api_info
|
| 1138 |
+
);
|
| 1139 |
+
blob_refs = blob_refs.concat(array_refs);
|
| 1140 |
+
})
|
| 1141 |
+
);
|
| 1142 |
+
return blob_refs;
|
| 1143 |
+
} else if (globalThis.Buffer && param instanceof globalThis.Buffer) {
|
| 1144 |
+
const is_image = type === "Image";
|
| 1145 |
+
return [
|
| 1146 |
+
{
|
| 1147 |
+
path,
|
| 1148 |
+
blob: is_image ? false : new NodeBlob([param]),
|
| 1149 |
+
type
|
| 1150 |
+
}
|
| 1151 |
+
];
|
| 1152 |
+
} else if (typeof param === "object") {
|
| 1153 |
+
let blob_refs = [];
|
| 1154 |
+
for (let key in param) {
|
| 1155 |
+
if (param.hasOwnProperty(key)) {
|
| 1156 |
+
let new_path = path.slice();
|
| 1157 |
+
new_path.push(key);
|
| 1158 |
+
blob_refs = blob_refs.concat(
|
| 1159 |
+
await walk_and_store_blobs(
|
| 1160 |
+
param[key],
|
| 1161 |
+
void 0,
|
| 1162 |
+
new_path,
|
| 1163 |
+
false,
|
| 1164 |
+
api_info
|
| 1165 |
+
)
|
| 1166 |
+
);
|
| 1167 |
+
}
|
| 1168 |
+
}
|
| 1169 |
+
return blob_refs;
|
| 1170 |
+
}
|
| 1171 |
+
return [];
|
| 1172 |
+
}
|
| 1173 |
+
function skip_queue(id, config) {
|
| 1174 |
+
var _a, _b, _c, _d;
|
| 1175 |
+
return !(((_b = (_a = config == null ? void 0 : config.dependencies) == null ? void 0 : _a[id]) == null ? void 0 : _b.queue) === null ? config.enable_queue : (_d = (_c = config == null ? void 0 : config.dependencies) == null ? void 0 : _c[id]) == null ? void 0 : _d.queue) || false;
|
| 1176 |
+
}
|
| 1177 |
+
async function resolve_config(fetch_implementation, endpoint, token) {
|
| 1178 |
+
const headers = {};
|
| 1179 |
+
if (token) {
|
| 1180 |
+
headers.Authorization = `Bearer ${token}`;
|
| 1181 |
+
}
|
| 1182 |
+
if (typeof window !== "undefined" && window.gradio_config && location.origin !== "http://localhost:9876" && !window.gradio_config.dev_mode) {
|
| 1183 |
+
const path = window.gradio_config.root;
|
| 1184 |
+
const config = window.gradio_config;
|
| 1185 |
+
config.root = resolve_root(endpoint, config.root, false);
|
| 1186 |
+
return { ...config, path };
|
| 1187 |
+
} else if (endpoint) {
|
| 1188 |
+
let response = await fetch_implementation(`${endpoint}/config`, {
|
| 1189 |
+
headers
|
| 1190 |
+
});
|
| 1191 |
+
if (response.status === 200) {
|
| 1192 |
+
const config = await response.json();
|
| 1193 |
+
config.path = config.path ?? "";
|
| 1194 |
+
config.root = endpoint;
|
| 1195 |
+
return config;
|
| 1196 |
+
}
|
| 1197 |
+
throw new Error("Could not get config.");
|
| 1198 |
+
}
|
| 1199 |
+
throw new Error("No config or app endpoint found");
|
| 1200 |
+
}
|
| 1201 |
+
async function check_space_status(id, type, status_callback) {
|
| 1202 |
+
let endpoint = type === "subdomain" ? `https://huggingface.co/api/spaces/by-subdomain/${id}` : `https://huggingface.co/api/spaces/${id}`;
|
| 1203 |
+
let response;
|
| 1204 |
+
let _status;
|
| 1205 |
+
try {
|
| 1206 |
+
response = await fetch(endpoint);
|
| 1207 |
+
_status = response.status;
|
| 1208 |
+
if (_status !== 200) {
|
| 1209 |
+
throw new Error();
|
| 1210 |
+
}
|
| 1211 |
+
response = await response.json();
|
| 1212 |
+
} catch (e) {
|
| 1213 |
+
status_callback({
|
| 1214 |
+
status: "error",
|
| 1215 |
+
load_status: "error",
|
| 1216 |
+
message: "Could not get space status",
|
| 1217 |
+
detail: "NOT_FOUND"
|
| 1218 |
+
});
|
| 1219 |
+
return;
|
| 1220 |
+
}
|
| 1221 |
+
if (!response || _status !== 200)
|
| 1222 |
+
return;
|
| 1223 |
+
const {
|
| 1224 |
+
runtime: { stage },
|
| 1225 |
+
id: space_name
|
| 1226 |
+
} = response;
|
| 1227 |
+
switch (stage) {
|
| 1228 |
+
case "STOPPED":
|
| 1229 |
+
case "SLEEPING":
|
| 1230 |
+
status_callback({
|
| 1231 |
+
status: "sleeping",
|
| 1232 |
+
load_status: "pending",
|
| 1233 |
+
message: "Space is asleep. Waking it up...",
|
| 1234 |
+
detail: stage
|
| 1235 |
+
});
|
| 1236 |
+
setTimeout(() => {
|
| 1237 |
+
check_space_status(id, type, status_callback);
|
| 1238 |
+
}, 1e3);
|
| 1239 |
+
break;
|
| 1240 |
+
case "PAUSED":
|
| 1241 |
+
status_callback({
|
| 1242 |
+
status: "paused",
|
| 1243 |
+
load_status: "error",
|
| 1244 |
+
message: "This space has been paused by the author. If you would like to try this demo, consider duplicating the space.",
|
| 1245 |
+
detail: stage,
|
| 1246 |
+
discussions_enabled: await discussions_enabled(space_name)
|
| 1247 |
+
});
|
| 1248 |
+
break;
|
| 1249 |
+
case "RUNNING":
|
| 1250 |
+
case "RUNNING_BUILDING":
|
| 1251 |
+
status_callback({
|
| 1252 |
+
status: "running",
|
| 1253 |
+
load_status: "complete",
|
| 1254 |
+
message: "",
|
| 1255 |
+
detail: stage
|
| 1256 |
+
});
|
| 1257 |
+
break;
|
| 1258 |
+
case "BUILDING":
|
| 1259 |
+
status_callback({
|
| 1260 |
+
status: "building",
|
| 1261 |
+
load_status: "pending",
|
| 1262 |
+
message: "Space is building...",
|
| 1263 |
+
detail: stage
|
| 1264 |
+
});
|
| 1265 |
+
setTimeout(() => {
|
| 1266 |
+
check_space_status(id, type, status_callback);
|
| 1267 |
+
}, 1e3);
|
| 1268 |
+
break;
|
| 1269 |
+
default:
|
| 1270 |
+
status_callback({
|
| 1271 |
+
status: "space_error",
|
| 1272 |
+
load_status: "error",
|
| 1273 |
+
message: "This space is experiencing an issue.",
|
| 1274 |
+
detail: stage,
|
| 1275 |
+
discussions_enabled: await discussions_enabled(space_name)
|
| 1276 |
+
});
|
| 1277 |
+
break;
|
| 1278 |
+
}
|
| 1279 |
+
}
|
| 1280 |
+
function handle_message(data, last_status) {
|
| 1281 |
+
const queue = true;
|
| 1282 |
+
switch (data.msg) {
|
| 1283 |
+
case "send_data":
|
| 1284 |
+
return { type: "data" };
|
| 1285 |
+
case "send_hash":
|
| 1286 |
+
return { type: "hash" };
|
| 1287 |
+
case "queue_full":
|
| 1288 |
+
return {
|
| 1289 |
+
type: "update",
|
| 1290 |
+
status: {
|
| 1291 |
+
queue,
|
| 1292 |
+
message: QUEUE_FULL_MSG,
|
| 1293 |
+
stage: "error",
|
| 1294 |
+
code: data.code,
|
| 1295 |
+
success: data.success
|
| 1296 |
+
}
|
| 1297 |
+
};
|
| 1298 |
+
case "estimation":
|
| 1299 |
+
return {
|
| 1300 |
+
type: "update",
|
| 1301 |
+
status: {
|
| 1302 |
+
queue,
|
| 1303 |
+
stage: last_status || "pending",
|
| 1304 |
+
code: data.code,
|
| 1305 |
+
size: data.queue_size,
|
| 1306 |
+
position: data.rank,
|
| 1307 |
+
eta: data.rank_eta,
|
| 1308 |
+
success: data.success
|
| 1309 |
+
}
|
| 1310 |
+
};
|
| 1311 |
+
case "progress":
|
| 1312 |
+
return {
|
| 1313 |
+
type: "update",
|
| 1314 |
+
status: {
|
| 1315 |
+
queue,
|
| 1316 |
+
stage: "pending",
|
| 1317 |
+
code: data.code,
|
| 1318 |
+
progress_data: data.progress_data,
|
| 1319 |
+
success: data.success
|
| 1320 |
+
}
|
| 1321 |
+
};
|
| 1322 |
+
case "log":
|
| 1323 |
+
return { type: "log", data };
|
| 1324 |
+
case "process_generating":
|
| 1325 |
+
return {
|
| 1326 |
+
type: "generating",
|
| 1327 |
+
status: {
|
| 1328 |
+
queue,
|
| 1329 |
+
message: !data.success ? data.output.error : null,
|
| 1330 |
+
stage: data.success ? "generating" : "error",
|
| 1331 |
+
code: data.code,
|
| 1332 |
+
progress_data: data.progress_data,
|
| 1333 |
+
eta: data.average_duration
|
| 1334 |
+
},
|
| 1335 |
+
data: data.success ? data.output : null
|
| 1336 |
+
};
|
| 1337 |
+
case "process_completed":
|
| 1338 |
+
if ("error" in data.output) {
|
| 1339 |
+
return {
|
| 1340 |
+
type: "update",
|
| 1341 |
+
status: {
|
| 1342 |
+
queue,
|
| 1343 |
+
message: data.output.error,
|
| 1344 |
+
stage: "error",
|
| 1345 |
+
code: data.code,
|
| 1346 |
+
success: data.success
|
| 1347 |
+
}
|
| 1348 |
+
};
|
| 1349 |
+
}
|
| 1350 |
+
return {
|
| 1351 |
+
type: "complete",
|
| 1352 |
+
status: {
|
| 1353 |
+
queue,
|
| 1354 |
+
message: !data.success ? data.output.error : void 0,
|
| 1355 |
+
stage: data.success ? "complete" : "error",
|
| 1356 |
+
code: data.code,
|
| 1357 |
+
progress_data: data.progress_data,
|
| 1358 |
+
eta: data.output.average_duration
|
| 1359 |
+
},
|
| 1360 |
+
data: data.success ? data.output : null
|
| 1361 |
+
};
|
| 1362 |
+
case "process_starts":
|
| 1363 |
+
return {
|
| 1364 |
+
type: "update",
|
| 1365 |
+
status: {
|
| 1366 |
+
queue,
|
| 1367 |
+
stage: "pending",
|
| 1368 |
+
code: data.code,
|
| 1369 |
+
size: data.rank,
|
| 1370 |
+
position: 0,
|
| 1371 |
+
success: data.success
|
| 1372 |
+
}
|
| 1373 |
+
};
|
| 1374 |
+
}
|
| 1375 |
+
return { type: "none", status: { stage: "error", queue } };
|
| 1376 |
+
}
|
| 1377 |
+
export {
|
| 1378 |
+
FileData,
|
| 1379 |
+
api_factory,
|
| 1380 |
+
client,
|
| 1381 |
+
duplicate,
|
| 1382 |
+
get_fetchable_url_or_file,
|
| 1383 |
+
normalise_file,
|
| 1384 |
+
post_data,
|
| 1385 |
+
prepare_files,
|
| 1386 |
+
upload,
|
| 1387 |
+
upload_files
|
| 1388 |
+
};
|
node_modules/@gradio/client/dist/types.d.ts
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
export interface Config {
|
| 2 |
+
auth_required: boolean | undefined;
|
| 3 |
+
auth_message: string;
|
| 4 |
+
components: any[];
|
| 5 |
+
css: string | null;
|
| 6 |
+
js: string | null;
|
| 7 |
+
head: string | null;
|
| 8 |
+
dependencies: any[];
|
| 9 |
+
dev_mode: boolean;
|
| 10 |
+
enable_queue: boolean;
|
| 11 |
+
layout: any;
|
| 12 |
+
mode: "blocks" | "interface";
|
| 13 |
+
root: string;
|
| 14 |
+
root_url?: string;
|
| 15 |
+
theme: string;
|
| 16 |
+
title: string;
|
| 17 |
+
version: string;
|
| 18 |
+
space_id: string | null;
|
| 19 |
+
is_colab: boolean;
|
| 20 |
+
show_api: boolean;
|
| 21 |
+
stylesheets: string[];
|
| 22 |
+
path: string;
|
| 23 |
+
protocol?: "sse" | "ws";
|
| 24 |
+
}
|
| 25 |
+
export interface Payload {
|
| 26 |
+
data: unknown[];
|
| 27 |
+
fn_index?: number;
|
| 28 |
+
event_data?: unknown;
|
| 29 |
+
time?: Date;
|
| 30 |
+
}
|
| 31 |
+
export interface PostResponse {
|
| 32 |
+
error?: string;
|
| 33 |
+
[x: string]: any;
|
| 34 |
+
}
|
| 35 |
+
export interface UploadResponse {
|
| 36 |
+
error?: string;
|
| 37 |
+
files?: string[];
|
| 38 |
+
}
|
| 39 |
+
export interface Status {
|
| 40 |
+
queue: boolean;
|
| 41 |
+
code?: string;
|
| 42 |
+
success?: boolean;
|
| 43 |
+
stage: "pending" | "error" | "complete" | "generating";
|
| 44 |
+
broken?: boolean;
|
| 45 |
+
size?: number;
|
| 46 |
+
position?: number;
|
| 47 |
+
eta?: number;
|
| 48 |
+
message?: string;
|
| 49 |
+
progress_data?: {
|
| 50 |
+
progress: number | null;
|
| 51 |
+
index: number | null;
|
| 52 |
+
length: number | null;
|
| 53 |
+
unit: string | null;
|
| 54 |
+
desc: string | null;
|
| 55 |
+
}[];
|
| 56 |
+
time?: Date;
|
| 57 |
+
}
|
| 58 |
+
export interface LogMessage {
|
| 59 |
+
log: string;
|
| 60 |
+
level: "warning" | "info";
|
| 61 |
+
}
|
| 62 |
+
export interface SpaceStatusNormal {
|
| 63 |
+
status: "sleeping" | "running" | "building" | "error" | "stopped";
|
| 64 |
+
detail: "SLEEPING" | "RUNNING" | "RUNNING_BUILDING" | "BUILDING" | "NOT_FOUND";
|
| 65 |
+
load_status: "pending" | "error" | "complete" | "generating";
|
| 66 |
+
message: string;
|
| 67 |
+
}
|
| 68 |
+
export interface SpaceStatusError {
|
| 69 |
+
status: "space_error" | "paused";
|
| 70 |
+
detail: "NO_APP_FILE" | "CONFIG_ERROR" | "BUILD_ERROR" | "RUNTIME_ERROR" | "PAUSED";
|
| 71 |
+
load_status: "error";
|
| 72 |
+
message: string;
|
| 73 |
+
discussions_enabled: boolean;
|
| 74 |
+
}
|
| 75 |
+
export type SpaceStatus = SpaceStatusNormal | SpaceStatusError;
|
| 76 |
+
export type status_callback_function = (a: Status) => void;
|
| 77 |
+
export type SpaceStatusCallback = (a: SpaceStatus) => void;
|
| 78 |
+
export type EventType = "data" | "status" | "log";
|
| 79 |
+
export interface EventMap {
|
| 80 |
+
data: Payload;
|
| 81 |
+
status: Status;
|
| 82 |
+
log: LogMessage;
|
| 83 |
+
}
|
| 84 |
+
export type Event<K extends EventType> = {
|
| 85 |
+
[P in K]: EventMap[P] & {
|
| 86 |
+
type: P;
|
| 87 |
+
endpoint: string;
|
| 88 |
+
fn_index: number;
|
| 89 |
+
};
|
| 90 |
+
}[K];
|
| 91 |
+
export type EventListener<K extends EventType> = (event: Event<K>) => void;
|
| 92 |
+
export type ListenerMap<K extends EventType> = {
|
| 93 |
+
[P in K]?: EventListener<K>[];
|
| 94 |
+
};
|
| 95 |
+
export interface FileData {
|
| 96 |
+
name: string;
|
| 97 |
+
orig_name?: string;
|
| 98 |
+
size?: number;
|
| 99 |
+
data: string;
|
| 100 |
+
blob?: File;
|
| 101 |
+
is_file?: boolean;
|
| 102 |
+
mime_type?: string;
|
| 103 |
+
alt_text?: string;
|
| 104 |
+
}
|
| 105 |
+
//# sourceMappingURL=types.d.ts.map
|
node_modules/@gradio/client/dist/types.d.ts.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,MAAM;IACtB,aAAa,EAAE,OAAO,GAAG,SAAS,CAAC;IACnC,YAAY,EAAE,MAAM,CAAC;IACrB,UAAU,EAAE,GAAG,EAAE,CAAC;IAClB,GAAG,EAAE,MAAM,GAAG,IAAI,CAAC;IACnB,EAAE,EAAE,MAAM,GAAG,IAAI,CAAC;IAClB,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC;IACpB,YAAY,EAAE,GAAG,EAAE,CAAC;IACpB,QAAQ,EAAE,OAAO,CAAC;IAClB,YAAY,EAAE,OAAO,CAAC;IACtB,MAAM,EAAE,GAAG,CAAC;IACZ,IAAI,EAAE,QAAQ,GAAG,WAAW,CAAC;IAC7B,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,KAAK,EAAE,MAAM,CAAC;IACd,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,EAAE,MAAM,CAAC;IAChB,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAC;IACxB,QAAQ,EAAE,OAAO,CAAC;IAClB,QAAQ,EAAE,OAAO,CAAC;IAClB,WAAW,EAAE,MAAM,EAAE,CAAC;IACtB,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,CAAC,EAAE,KAAK,GAAG,IAAI,CAAC;CACxB;AAED,MAAM,WAAW,OAAO;IACvB,IAAI,EAAE,OAAO,EAAE,CAAC;IAChB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB,IAAI,CAAC,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,EAAE,MAAM,CAAC;IACb,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,CAAC,EAAE,IAAI,CAAC;IACZ,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,QAAQ,CAAC,EAAE,MAAM,CAAC;CAClB"}
|
node_modules/@gradio/client/dist/upload.d.ts
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { upload_files } from "./client";
|
| 2 |
+
export declare function normalise_file(file: FileData | null, server_url: string, proxy_url: string | null): FileData | null;
|
| 3 |
+
export declare function normalise_file(file: FileData[] | null, server_url: string, proxy_url: string | null): FileData[] | null;
|
| 4 |
+
export declare function normalise_file(file: FileData[] | FileData | null, server_url: string, // root: string,
|
| 5 |
+
proxy_url: string | null): FileData[] | FileData | null;
|
| 6 |
+
export declare function get_fetchable_url_or_file(path: string | null, server_url: string, proxy_url: string | null): string;
|
| 7 |
+
export declare function upload(file_data: FileData[], root: string, upload_id?: string, upload_fn?: typeof upload_files): Promise<(FileData | null)[] | null>;
|
| 8 |
+
export declare function prepare_files(files: File[], is_stream?: boolean): Promise<FileData[]>;
|
| 9 |
+
export declare class FileData {
|
| 10 |
+
path: string;
|
| 11 |
+
url?: string;
|
| 12 |
+
orig_name?: string;
|
| 13 |
+
size?: number;
|
| 14 |
+
blob?: File;
|
| 15 |
+
is_stream?: boolean;
|
| 16 |
+
mime_type?: string;
|
| 17 |
+
alt_text?: string;
|
| 18 |
+
constructor({ path, url, orig_name, size, blob, is_stream, mime_type, alt_text }: {
|
| 19 |
+
path: string;
|
| 20 |
+
url?: string;
|
| 21 |
+
orig_name?: string;
|
| 22 |
+
size?: number;
|
| 23 |
+
blob?: File;
|
| 24 |
+
is_stream?: boolean;
|
| 25 |
+
mime_type?: string;
|
| 26 |
+
alt_text?: string;
|
| 27 |
+
});
|
| 28 |
+
}
|
| 29 |
+
//# sourceMappingURL=upload.d.ts.map
|
node_modules/@gradio/client/dist/upload.d.ts.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
{"version":3,"file":"upload.d.ts","sourceRoot":"","sources":["../src/upload.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AAExC,wBAAgB,cAAc,CAC7B,IAAI,EAAE,QAAQ,GAAG,IAAI,EACrB,UAAU,EAAE,MAAM,EAClB,SAAS,EAAE,MAAM,GAAG,IAAI,GACtB,QAAQ,GAAG,IAAI,CAAC;AAEnB,wBAAgB,cAAc,CAC7B,IAAI,EAAE,QAAQ,EAAE,GAAG,IAAI,EACvB,UAAU,EAAE,MAAM,EAClB,SAAS,EAAE,MAAM,GAAG,IAAI,GACtB,QAAQ,EAAE,GAAG,IAAI,CAAC;AAErB,wBAAgB,cAAc,CAC7B,IAAI,EAAE,QAAQ,EAAE,GAAG,QAAQ,GAAG,IAAI,EAClC,UAAU,EAAE,MAAM,EAAE,gBAAgB;AACpC,SAAS,EAAE,MAAM,GAAG,IAAI,GACtB,QAAQ,EAAE,GAAG,QAAQ,GAAG,IAAI,CAAC;AAqDhC,wBAAgB,yBAAyB,CACxC,IAAI,EAAE,MAAM,GAAG,IAAI,EACnB,UAAU,EAAE,MAAM,EAClB,SAAS,EAAE,MAAM,GAAG,IAAI,GACtB,MAAM,CAUR;AAED,wBAAsB,MAAM,CAC3B,SAAS,EAAE,QAAQ,EAAE,EACrB,IAAI,EAAE,MAAM,EACZ,SAAS,CAAC,EAAE,MAAM,EAClB,SAAS,GAAE,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{ Config } from "./types.js";
|
| 2 |
+
/**
|
| 3 |
+
* This function is used to resolve the URL for making requests when the app has a root path.
|
| 4 |
+
* The root path could be a path suffix like "/app" which is appended to the end of the base URL. Or
|
| 5 |
+
* it could be a full URL like "https://abidlabs-test-client-replica--gqf2x.hf.space" which is used when hosting
|
| 6 |
+
* Gradio apps on Hugging Face Spaces.
|
| 7 |
+
* @param {string} base_url The base URL at which the Gradio server is hosted
|
| 8 |
+
* @param {string} root_path The root path, which could be a path suffix (e.g. mounted in FastAPI app) or a full URL (e.g. hosted on Hugging Face Spaces)
|
| 9 |
+
* @param {boolean} prioritize_base Whether to prioritize the base URL over the root path. This is used when both the base path and root paths are full URLs. For example, for fetching files the root path should be prioritized, but for making requests, the base URL should be prioritized.
|
| 10 |
+
* @returns {string} the resolved URL
|
| 11 |
+
*/
|
| 12 |
+
export declare function resolve_root(base_url: string, root_path: string, prioritize_base: boolean): string;
|
| 13 |
+
export declare function determine_protocol(endpoint: string): {
|
| 14 |
+
ws_protocol: "ws" | "wss";
|
| 15 |
+
http_protocol: "http:" | "https:";
|
| 16 |
+
host: string;
|
| 17 |
+
};
|
| 18 |
+
export declare const RE_SPACE_NAME: RegExp;
|
| 19 |
+
export declare const RE_SPACE_DOMAIN: RegExp;
|
| 20 |
+
export declare function process_endpoint(app_reference: string, token?: `hf_${string}`): Promise<{
|
| 21 |
+
space_id: string | false;
|
| 22 |
+
host: string;
|
| 23 |
+
ws_protocol: "ws" | "wss";
|
| 24 |
+
http_protocol: "http:" | "https:";
|
| 25 |
+
}>;
|
| 26 |
+
export declare function map_names_to_ids(fns: Config["dependencies"]): Record<string, number>;
|
| 27 |
+
export declare function discussions_enabled(space_id: string): Promise<boolean>;
|
| 28 |
+
export declare function get_space_hardware(space_id: string, token: `hf_${string}`): Promise<(typeof hardware_types)[number]>;
|
| 29 |
+
export declare function set_space_hardware(space_id: string, new_hardware: (typeof hardware_types)[number], token: `hf_${string}`): Promise<(typeof hardware_types)[number]>;
|
| 30 |
+
export declare function set_space_timeout(space_id: string, timeout: number, token: `hf_${string}`): Promise<number>;
|
| 31 |
+
export declare const hardware_types: readonly ["cpu-basic", "cpu-upgrade", "t4-small", "t4-medium", "a10g-small", "a10g-large", "a100-large"];
|
| 32 |
+
//# sourceMappingURL=utils.d.ts.map
|
node_modules/@gradio/client/dist/utils.d.ts.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,YAAY,CAAC;AAEzC;;;;;;;;;GASG;AACH,wBAAgB,YAAY,CAC3B,QAAQ,EAAE,MAAM,EAChB,SAAS,EAAE,MAAM,EACjB,eAAe,EAAE,OAAO,GACtB,MAAM,CAKR;AAED,wBAAgB,kBAAkB,CAAC,QAAQ,EAAE,MAAM,GAAG;IACrD,WAAW,EAAE,IAAI,GAAG,KAAK,CAAC;IAC1B,aAAa,EAAE,OAAO,GAAG,QAAQ,CAAC;IAClC,IAAI,EAAE,MAAM,CAAC;CACb,CAgCA;AAED,eAAO,MAAM,aAAa,QAAqB,CAAC;AAChD,eAAO,MAAM,eAAe,QAAwB,CAAC;AACrD,wBAAsB,gBAAgB,CACrC,aAAa,EAAE,MAAM,EACrB,KAAK,CAAC,EAAE,MAAM,MAAM,EAAE,GACpB,OAAO,CAAC;IACV,QAAQ,EAAE,MAAM,GAAG,KAAK,CAAC;IACzB,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,IAAI,GAAG,KAAK,CAAC;IAC1B,aAAa,EAAE,OAAO,GAAG,QAAQ,CAAC;CAClC,CAAC,CA4CD;AAED,wBAAgB,gBAAgB,CAC/B,GAAG,EAAE,MAAM,CAAC,cAAc,CAAC,GACzB,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAQxB;AAID,wBAAsB,mBAAmB,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAe5E;AAED,wBAAsB,kBAAkB,CACvC,QAAQ,EAAE,MAAM,EAChB,KAAK,EAAE,MAAM,MAAM,EAAE,GACnB,OAAO,CAAC,CAAC,OAAO,cAAc,CAAC,CAAC,MAAM,CAAC,CAAC,CAqB1C;AAED,wBAAsB,kBAAkB,CACvC,QAAQ,EAAE,MAAM,EAChB,YAAY,EAAE,CAAC,OAAO,cAAc,CAAC,CAAC,MAAM,CAAC,EAC7C,KAAK,EAAE,MAAM,MAAM,EAAE,GACnB,OAAO,CAAC,CAAC,OAAO,cAAc,CAAC,CAAC,MAAM,CAAC,CAAC,CAuB1C;AAED,wBAAsB,iBAAiB,CACtC,QAAQ,EAAE,MAAM,EAChB,OAAO,EAAE,MAAM,EACf,KAAK,EAAE,MAAM,MAAM,EAAE,GACnB,OAAO,CAAC,MAAM,CAAC,CAuBjB;AAED,eAAO,MAAM,cAAc,0GAQjB,CAAC"}
|
node_modules/@gradio/client/dist/wrapper-6f348d45.js
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
node_modules/@gradio/client/package.json
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"name": "@gradio/client",
|
| 3 |
+
"version": "0.8.2",
|
| 4 |
+
"description": "Gradio API client",
|
| 5 |
+
"type": "module",
|
| 6 |
+
"main": "dist/index.js",
|
| 7 |
+
"author": "",
|
| 8 |
+
"license": "ISC",
|
| 9 |
+
"exports": {
|
| 10 |
+
".": {
|
| 11 |
+
"import": "./dist/index.js"
|
| 12 |
+
},
|
| 13 |
+
"./package.json": "./package.json"
|
| 14 |
+
},
|
| 15 |
+
"dependencies": {
|
| 16 |
+
"bufferutil": "^4.0.7",
|
| 17 |
+
"semiver": "^1.1.0",
|
| 18 |
+
"ws": "^8.13.0"
|
| 19 |
+
},
|
| 20 |
+
"devDependencies": {
|
| 21 |
+
"@types/ws": "^8.5.4",
|
| 22 |
+
"esbuild": "^0.19.0"
|
| 23 |
+
},
|
| 24 |
+
"engines": {
|
| 25 |
+
"node": ">=18.0.0"
|
| 26 |
+
},
|
| 27 |
+
"main_changeset": true,
|
| 28 |
+
"scripts": {
|
| 29 |
+
"bundle": "vite build --ssr",
|
| 30 |
+
"generate_types": "tsc",
|
| 31 |
+
"build": "pnpm bundle && pnpm generate_types"
|
| 32 |
+
}
|
| 33 |
+
}
|
node_modules/@gradio/client/src/client.node-test.ts
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { test, describe, assert } from "vitest";
|
| 2 |
+
import { readFileSync } from "fs";
|
| 3 |
+
import { join, dirname } from "path";
|
| 4 |
+
import { fileURLToPath } from "url";
|
| 5 |
+
import { Blob } from "node:buffer";
|
| 6 |
+
|
| 7 |
+
const __dirname = dirname(fileURLToPath(import.meta.url));
|
| 8 |
+
const image_path = join(
|
| 9 |
+
__dirname,
|
| 10 |
+
"..",
|
| 11 |
+
"..",
|
| 12 |
+
"..",
|
| 13 |
+
"demo",
|
| 14 |
+
"kitchen_sink",
|
| 15 |
+
"files",
|
| 16 |
+
"lion.jpg"
|
| 17 |
+
);
|
| 18 |
+
|
| 19 |
+
import { walk_and_store_blobs, client, handle_blob } from "./client";
|
| 20 |
+
|
| 21 |
+
describe.skip("extract blob parts", () => {
|
| 22 |
+
test("convert Buffer to Blob", async () => {
|
| 23 |
+
const image = readFileSync(image_path);
|
| 24 |
+
await client("gradio/hello_world_main");
|
| 25 |
+
const parts = walk_and_store_blobs({
|
| 26 |
+
data: {
|
| 27 |
+
image
|
| 28 |
+
}
|
| 29 |
+
});
|
| 30 |
+
|
| 31 |
+
assert.isTrue(parts[0].blob instanceof Blob);
|
| 32 |
+
});
|
| 33 |
+
|
| 34 |
+
test("leave node Blob as Blob", async () => {
|
| 35 |
+
const image = new Blob([readFileSync(image_path)]);
|
| 36 |
+
|
| 37 |
+
await client("gradio/hello_world_main");
|
| 38 |
+
const parts = walk_and_store_blobs({
|
| 39 |
+
data: {
|
| 40 |
+
image
|
| 41 |
+
}
|
| 42 |
+
});
|
| 43 |
+
|
| 44 |
+
assert.isTrue(parts[0].blob instanceof Blob);
|
| 45 |
+
});
|
| 46 |
+
|
| 47 |
+
test("handle deep structures", async () => {
|
| 48 |
+
const image = new Blob([readFileSync(image_path)]);
|
| 49 |
+
|
| 50 |
+
await client("gradio/hello_world_main");
|
| 51 |
+
const parts = walk_and_store_blobs({
|
| 52 |
+
a: {
|
| 53 |
+
b: {
|
| 54 |
+
data: {
|
| 55 |
+
image
|
| 56 |
+
}
|
| 57 |
+
}
|
| 58 |
+
}
|
| 59 |
+
});
|
| 60 |
+
|
| 61 |
+
assert.isTrue(parts[0].blob instanceof Blob);
|
| 62 |
+
});
|
| 63 |
+
|
| 64 |
+
test("handle deep structures with arrays", async () => {
|
| 65 |
+
const image = new Blob([readFileSync(image_path)]);
|
| 66 |
+
|
| 67 |
+
await client("gradio/hello_world_main");
|
| 68 |
+
const parts = walk_and_store_blobs({
|
| 69 |
+
a: [
|
| 70 |
+
{
|
| 71 |
+
b: [
|
| 72 |
+
{
|
| 73 |
+
data: [
|
| 74 |
+
{
|
| 75 |
+
image
|
| 76 |
+
}
|
| 77 |
+
]
|
| 78 |
+
}
|
| 79 |
+
]
|
| 80 |
+
}
|
| 81 |
+
]
|
| 82 |
+
});
|
| 83 |
+
|
| 84 |
+
assert.isTrue(parts[0].blob instanceof Blob);
|
| 85 |
+
});
|
| 86 |
+
|
| 87 |
+
test("handle deep structures with arrays 2", async () => {
|
| 88 |
+
const image = new Blob([readFileSync(image_path)]);
|
| 89 |
+
|
| 90 |
+
await client("gradio/hello_world_main");
|
| 91 |
+
const obj = {
|
| 92 |
+
a: [
|
| 93 |
+
{
|
| 94 |
+
b: [
|
| 95 |
+
{
|
| 96 |
+
data: [[image], image, [image, [image]]]
|
| 97 |
+
}
|
| 98 |
+
]
|
| 99 |
+
}
|
| 100 |
+
]
|
| 101 |
+
};
|
| 102 |
+
const parts = walk_and_store_blobs(obj);
|
| 103 |
+
|
| 104 |
+
function map_path(
|
| 105 |
+
obj: Record<string, any>,
|
| 106 |
+
parts: { path: string[]; blob: any }[]
|
| 107 |
+
) {
|
| 108 |
+
const { path, blob } = parts[parts.length - 1];
|
| 109 |
+
let ref = obj;
|
| 110 |
+
path.forEach((p) => (ref = ref[p]));
|
| 111 |
+
|
| 112 |
+
return ref === blob;
|
| 113 |
+
}
|
| 114 |
+
|
| 115 |
+
assert.isTrue(parts[0].blob instanceof Blob);
|
| 116 |
+
// assert.isTrue(map_path(obj, parts));
|
| 117 |
+
});
|
| 118 |
+
});
|
| 119 |
+
|
| 120 |
+
describe("handle_blob", () => {
|
| 121 |
+
test("handle blobs", async () => {
|
| 122 |
+
const image = new Blob([readFileSync(image_path)]);
|
| 123 |
+
|
| 124 |
+
const app = await client("gradio/hello_world_main");
|
| 125 |
+
const obj = [
|
| 126 |
+
{
|
| 127 |
+
a: [
|
| 128 |
+
{
|
| 129 |
+
b: [
|
| 130 |
+
{
|
| 131 |
+
data: [[image], image, [image, [image]]]
|
| 132 |
+
}
|
| 133 |
+
]
|
| 134 |
+
}
|
| 135 |
+
]
|
| 136 |
+
}
|
| 137 |
+
];
|
| 138 |
+
|
| 139 |
+
const parts = await handle_blob(app.config.root, obj, undefined);
|
| 140 |
+
//@ts-ignore
|
| 141 |
+
// assert.isString(parts.data[0].a[0].b[0].data[0][0]);
|
| 142 |
+
});
|
| 143 |
+
});
|
| 144 |
+
|
| 145 |
+
describe.skip("private space", () => {
|
| 146 |
+
test("can access a private space", async () => {
|
| 147 |
+
const image = new Blob([readFileSync(image_path)]);
|
| 148 |
+
|
| 149 |
+
const app = await client("pngwn/hello_world", {
|
| 150 |
+
hf_token: "hf_"
|
| 151 |
+
});
|
| 152 |
+
|
| 153 |
+
console.log(app);
|
| 154 |
+
const obj = [
|
| 155 |
+
{
|
| 156 |
+
a: [
|
| 157 |
+
{
|
| 158 |
+
b: [
|
| 159 |
+
{
|
| 160 |
+
data: [[image], image, [image, [image]]]
|
| 161 |
+
}
|
| 162 |
+
]
|
| 163 |
+
}
|
| 164 |
+
]
|
| 165 |
+
}
|
| 166 |
+
];
|
| 167 |
+
|
| 168 |
+
const parts = await handle_blob(app.config.root, obj, "hf_");
|
| 169 |
+
//@ts-ignore
|
| 170 |
+
assert.isString(parts.data[0].a[0].b[0].data[0][0]);
|
| 171 |
+
});
|
| 172 |
+
});
|
node_modules/@gradio/client/src/client.ts
ADDED
|
@@ -0,0 +1,1507 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
//@ts-nocheck
|
| 2 |
+
|
| 3 |
+
import semiver from "semiver";
|
| 4 |
+
|
| 5 |
+
import {
|
| 6 |
+
process_endpoint,
|
| 7 |
+
RE_SPACE_NAME,
|
| 8 |
+
map_names_to_ids,
|
| 9 |
+
discussions_enabled,
|
| 10 |
+
get_space_hardware,
|
| 11 |
+
set_space_hardware,
|
| 12 |
+
set_space_timeout,
|
| 13 |
+
hardware_types,
|
| 14 |
+
resolve_root
|
| 15 |
+
} from "./utils.js";
|
| 16 |
+
|
| 17 |
+
import type {
|
| 18 |
+
EventType,
|
| 19 |
+
EventListener,
|
| 20 |
+
ListenerMap,
|
| 21 |
+
Event,
|
| 22 |
+
Payload,
|
| 23 |
+
PostResponse,
|
| 24 |
+
UploadResponse,
|
| 25 |
+
Status,
|
| 26 |
+
SpaceStatus,
|
| 27 |
+
SpaceStatusCallback
|
| 28 |
+
} from "./types.js";
|
| 29 |
+
|
| 30 |
+
import { FileData, normalise_file } from "./upload";
|
| 31 |
+
|
| 32 |
+
import type { Config } from "./types.js";
|
| 33 |
+
|
| 34 |
+
type event = <K extends EventType>(
|
| 35 |
+
eventType: K,
|
| 36 |
+
listener: EventListener<K>
|
| 37 |
+
) => SubmitReturn;
|
| 38 |
+
type predict = (
|
| 39 |
+
endpoint: string | number,
|
| 40 |
+
data?: unknown[],
|
| 41 |
+
event_data?: unknown
|
| 42 |
+
) => Promise<unknown>;
|
| 43 |
+
|
| 44 |
+
type client_return = {
|
| 45 |
+
predict: predict;
|
| 46 |
+
config: Config;
|
| 47 |
+
submit: (
|
| 48 |
+
endpoint: string | number,
|
| 49 |
+
data?: unknown[],
|
| 50 |
+
event_data?: unknown,
|
| 51 |
+
trigger_id?: number | null
|
| 52 |
+
) => SubmitReturn;
|
| 53 |
+
component_server: (
|
| 54 |
+
component_id: number,
|
| 55 |
+
fn_name: string,
|
| 56 |
+
data: unknown[]
|
| 57 |
+
) => any;
|
| 58 |
+
view_api: (c?: Config) => Promise<ApiInfo<JsApiData>>;
|
| 59 |
+
};
|
| 60 |
+
|
| 61 |
+
type SubmitReturn = {
|
| 62 |
+
on: event;
|
| 63 |
+
off: event;
|
| 64 |
+
cancel: () => Promise<void>;
|
| 65 |
+
destroy: () => void;
|
| 66 |
+
};
|
| 67 |
+
|
| 68 |
+
const QUEUE_FULL_MSG = "This application is too busy. Keep trying!";
|
| 69 |
+
const BROKEN_CONNECTION_MSG = "Connection errored out.";
|
| 70 |
+
|
| 71 |
+
export let NodeBlob;
|
| 72 |
+
|
| 73 |
+
export async function duplicate(
|
| 74 |
+
app_reference: string,
|
| 75 |
+
options: {
|
| 76 |
+
hf_token: `hf_${string}`;
|
| 77 |
+
private?: boolean;
|
| 78 |
+
status_callback: SpaceStatusCallback;
|
| 79 |
+
hardware?: (typeof hardware_types)[number];
|
| 80 |
+
timeout?: number;
|
| 81 |
+
}
|
| 82 |
+
): Promise<client_return> {
|
| 83 |
+
const { hf_token, private: _private, hardware, timeout } = options;
|
| 84 |
+
|
| 85 |
+
if (hardware && !hardware_types.includes(hardware)) {
|
| 86 |
+
throw new Error(
|
| 87 |
+
`Invalid hardware type provided. Valid types are: ${hardware_types
|
| 88 |
+
.map((v) => `"${v}"`)
|
| 89 |
+
.join(",")}.`
|
| 90 |
+
);
|
| 91 |
+
}
|
| 92 |
+
const headers = {
|
| 93 |
+
Authorization: `Bearer ${hf_token}`
|
| 94 |
+
};
|
| 95 |
+
|
| 96 |
+
const user = (
|
| 97 |
+
await (
|
| 98 |
+
await fetch(`https://huggingface.co/api/whoami-v2`, {
|
| 99 |
+
headers
|
| 100 |
+
})
|
| 101 |
+
).json()
|
| 102 |
+
).name;
|
| 103 |
+
|
| 104 |
+
const space_name = app_reference.split("/")[1];
|
| 105 |
+
const body: {
|
| 106 |
+
repository: string;
|
| 107 |
+
private?: boolean;
|
| 108 |
+
} = {
|
| 109 |
+
repository: `${user}/${space_name}`
|
| 110 |
+
};
|
| 111 |
+
|
| 112 |
+
if (_private) {
|
| 113 |
+
body.private = true;
|
| 114 |
+
}
|
| 115 |
+
|
| 116 |
+
try {
|
| 117 |
+
const response = await fetch(
|
| 118 |
+
`https://huggingface.co/api/spaces/${app_reference}/duplicate`,
|
| 119 |
+
{
|
| 120 |
+
method: "POST",
|
| 121 |
+
headers: { "Content-Type": "application/json", ...headers },
|
| 122 |
+
body: JSON.stringify(body)
|
| 123 |
+
}
|
| 124 |
+
);
|
| 125 |
+
|
| 126 |
+
if (response.status === 409) {
|
| 127 |
+
return client(`${user}/${space_name}`, options);
|
| 128 |
+
}
|
| 129 |
+
const duplicated_space = await response.json();
|
| 130 |
+
|
| 131 |
+
let original_hardware;
|
| 132 |
+
|
| 133 |
+
if (!hardware) {
|
| 134 |
+
original_hardware = await get_space_hardware(app_reference, hf_token);
|
| 135 |
+
}
|
| 136 |
+
|
| 137 |
+
const requested_hardware = hardware || original_hardware || "cpu-basic";
|
| 138 |
+
await set_space_hardware(
|
| 139 |
+
`${user}/${space_name}`,
|
| 140 |
+
requested_hardware,
|
| 141 |
+
hf_token
|
| 142 |
+
);
|
| 143 |
+
|
| 144 |
+
await set_space_timeout(`${user}/${space_name}`, timeout || 300, hf_token);
|
| 145 |
+
return client(duplicated_space.url, options);
|
| 146 |
+
} catch (e: any) {
|
| 147 |
+
throw new Error(e);
|
| 148 |
+
}
|
| 149 |
+
}
|
| 150 |
+
|
| 151 |
+
interface Client {
|
| 152 |
+
post_data: (
|
| 153 |
+
url: string,
|
| 154 |
+
body: unknown,
|
| 155 |
+
token?: `hf_${string}`
|
| 156 |
+
) => Promise<[PostResponse, number]>;
|
| 157 |
+
upload_files: (
|
| 158 |
+
root: string,
|
| 159 |
+
files: File[],
|
| 160 |
+
token?: `hf_${string}`,
|
| 161 |
+
upload_id?: string
|
| 162 |
+
) => Promise<UploadResponse>;
|
| 163 |
+
client: (
|
| 164 |
+
app_reference: string,
|
| 165 |
+
options: {
|
| 166 |
+
hf_token?: `hf_${string}`;
|
| 167 |
+
status_callback?: SpaceStatusCallback;
|
| 168 |
+
normalise_files?: boolean;
|
| 169 |
+
}
|
| 170 |
+
) => Promise<client_return>;
|
| 171 |
+
handle_blob: (
|
| 172 |
+
endpoint: string,
|
| 173 |
+
data: unknown[],
|
| 174 |
+
api_info: ApiInfo<JsApiData>,
|
| 175 |
+
token?: `hf_${string}`
|
| 176 |
+
) => Promise<unknown[]>;
|
| 177 |
+
}
|
| 178 |
+
|
| 179 |
+
export function api_factory(
|
| 180 |
+
fetch_implementation: typeof fetch,
|
| 181 |
+
WebSocket_factory: (url: URL) => WebSocket
|
| 182 |
+
): Client {
|
| 183 |
+
return { post_data, upload_files, client, handle_blob };
|
| 184 |
+
|
| 185 |
+
async function post_data(
|
| 186 |
+
url: string,
|
| 187 |
+
body: unknown,
|
| 188 |
+
token?: `hf_${string}`
|
| 189 |
+
): Promise<[PostResponse, number]> {
|
| 190 |
+
const headers: {
|
| 191 |
+
Authorization?: string;
|
| 192 |
+
"Content-Type": "application/json";
|
| 193 |
+
} = { "Content-Type": "application/json" };
|
| 194 |
+
if (token) {
|
| 195 |
+
headers.Authorization = `Bearer ${token}`;
|
| 196 |
+
}
|
| 197 |
+
try {
|
| 198 |
+
var response = await fetch_implementation(url, {
|
| 199 |
+
method: "POST",
|
| 200 |
+
body: JSON.stringify(body),
|
| 201 |
+
headers
|
| 202 |
+
});
|
| 203 |
+
} catch (e) {
|
| 204 |
+
return [{ error: BROKEN_CONNECTION_MSG }, 500];
|
| 205 |
+
}
|
| 206 |
+
const output: PostResponse = await response.json();
|
| 207 |
+
return [output, response.status];
|
| 208 |
+
}
|
| 209 |
+
|
| 210 |
+
async function upload_files(
|
| 211 |
+
root: string,
|
| 212 |
+
files: (Blob | File)[],
|
| 213 |
+
token?: `hf_${string}`,
|
| 214 |
+
upload_id?: string
|
| 215 |
+
): Promise<UploadResponse> {
|
| 216 |
+
const headers: {
|
| 217 |
+
Authorization?: string;
|
| 218 |
+
} = {};
|
| 219 |
+
if (token) {
|
| 220 |
+
headers.Authorization = `Bearer ${token}`;
|
| 221 |
+
}
|
| 222 |
+
const chunkSize = 1000;
|
| 223 |
+
const uploadResponses = [];
|
| 224 |
+
for (let i = 0; i < files.length; i += chunkSize) {
|
| 225 |
+
const chunk = files.slice(i, i + chunkSize);
|
| 226 |
+
const formData = new FormData();
|
| 227 |
+
chunk.forEach((file) => {
|
| 228 |
+
formData.append("files", file);
|
| 229 |
+
});
|
| 230 |
+
try {
|
| 231 |
+
const upload_url = upload_id
|
| 232 |
+
? `${root}/upload?upload_id=${upload_id}`
|
| 233 |
+
: `${root}/upload`;
|
| 234 |
+
var response = await fetch_implementation(upload_url, {
|
| 235 |
+
method: "POST",
|
| 236 |
+
body: formData,
|
| 237 |
+
headers
|
| 238 |
+
});
|
| 239 |
+
} catch (e) {
|
| 240 |
+
return { error: BROKEN_CONNECTION_MSG };
|
| 241 |
+
}
|
| 242 |
+
const output: UploadResponse["files"] = await response.json();
|
| 243 |
+
uploadResponses.push(...output);
|
| 244 |
+
}
|
| 245 |
+
return { files: uploadResponses };
|
| 246 |
+
}
|
| 247 |
+
|
| 248 |
+
async function client(
|
| 249 |
+
app_reference: string,
|
| 250 |
+
options: {
|
| 251 |
+
hf_token?: `hf_${string}`;
|
| 252 |
+
status_callback?: SpaceStatusCallback;
|
| 253 |
+
normalise_files?: boolean;
|
| 254 |
+
} = { normalise_files: true }
|
| 255 |
+
): Promise<client_return> {
|
| 256 |
+
return new Promise(async (res) => {
|
| 257 |
+
const { status_callback, hf_token, normalise_files } = options;
|
| 258 |
+
const return_obj = {
|
| 259 |
+
predict,
|
| 260 |
+
submit,
|
| 261 |
+
view_api,
|
| 262 |
+
component_server
|
| 263 |
+
};
|
| 264 |
+
|
| 265 |
+
const transform_files = normalise_files ?? true;
|
| 266 |
+
if (
|
| 267 |
+
(typeof window === "undefined" || !("WebSocket" in window)) &&
|
| 268 |
+
!global.Websocket
|
| 269 |
+
) {
|
| 270 |
+
const ws = await import("ws");
|
| 271 |
+
NodeBlob = (await import("node:buffer")).Blob;
|
| 272 |
+
//@ts-ignore
|
| 273 |
+
global.WebSocket = ws.WebSocket;
|
| 274 |
+
}
|
| 275 |
+
|
| 276 |
+
const { ws_protocol, http_protocol, host, space_id } =
|
| 277 |
+
await process_endpoint(app_reference, hf_token);
|
| 278 |
+
|
| 279 |
+
const session_hash = Math.random().toString(36).substring(2);
|
| 280 |
+
const last_status: Record<string, Status["stage"]> = {};
|
| 281 |
+
let config: Config;
|
| 282 |
+
let api_map: Record<string, number> = {};
|
| 283 |
+
|
| 284 |
+
let jwt: false | string = false;
|
| 285 |
+
|
| 286 |
+
if (hf_token && space_id) {
|
| 287 |
+
jwt = await get_jwt(space_id, hf_token);
|
| 288 |
+
}
|
| 289 |
+
|
| 290 |
+
async function config_success(_config: Config): Promise<client_return> {
|
| 291 |
+
config = _config;
|
| 292 |
+
api_map = map_names_to_ids(_config?.dependencies || []);
|
| 293 |
+
if (config.auth_required) {
|
| 294 |
+
return {
|
| 295 |
+
config,
|
| 296 |
+
...return_obj
|
| 297 |
+
};
|
| 298 |
+
}
|
| 299 |
+
try {
|
| 300 |
+
api = await view_api(config);
|
| 301 |
+
} catch (e) {
|
| 302 |
+
console.error(`Could not get api details: ${e.message}`);
|
| 303 |
+
}
|
| 304 |
+
|
| 305 |
+
return {
|
| 306 |
+
config,
|
| 307 |
+
...return_obj
|
| 308 |
+
};
|
| 309 |
+
}
|
| 310 |
+
let api: ApiInfo<JsApiData>;
|
| 311 |
+
async function handle_space_sucess(status: SpaceStatus): Promise<void> {
|
| 312 |
+
if (status_callback) status_callback(status);
|
| 313 |
+
if (status.status === "running")
|
| 314 |
+
try {
|
| 315 |
+
config = await resolve_config(
|
| 316 |
+
fetch_implementation,
|
| 317 |
+
`${http_protocol}//${host}`,
|
| 318 |
+
hf_token
|
| 319 |
+
);
|
| 320 |
+
|
| 321 |
+
const _config = await config_success(config);
|
| 322 |
+
res(_config);
|
| 323 |
+
} catch (e) {
|
| 324 |
+
console.error(e);
|
| 325 |
+
if (status_callback) {
|
| 326 |
+
status_callback({
|
| 327 |
+
status: "error",
|
| 328 |
+
message: "Could not load this space.",
|
| 329 |
+
load_status: "error",
|
| 330 |
+
detail: "NOT_FOUND"
|
| 331 |
+
});
|
| 332 |
+
}
|
| 333 |
+
}
|
| 334 |
+
}
|
| 335 |
+
|
| 336 |
+
try {
|
| 337 |
+
config = await resolve_config(
|
| 338 |
+
fetch_implementation,
|
| 339 |
+
`${http_protocol}//${host}`,
|
| 340 |
+
hf_token
|
| 341 |
+
);
|
| 342 |
+
|
| 343 |
+
const _config = await config_success(config);
|
| 344 |
+
res(_config);
|
| 345 |
+
} catch (e) {
|
| 346 |
+
console.error(e);
|
| 347 |
+
if (space_id) {
|
| 348 |
+
check_space_status(
|
| 349 |
+
space_id,
|
| 350 |
+
RE_SPACE_NAME.test(space_id) ? "space_name" : "subdomain",
|
| 351 |
+
handle_space_sucess
|
| 352 |
+
);
|
| 353 |
+
} else {
|
| 354 |
+
if (status_callback)
|
| 355 |
+
status_callback({
|
| 356 |
+
status: "error",
|
| 357 |
+
message: "Could not load this space.",
|
| 358 |
+
load_status: "error",
|
| 359 |
+
detail: "NOT_FOUND"
|
| 360 |
+
});
|
| 361 |
+
}
|
| 362 |
+
}
|
| 363 |
+
|
| 364 |
+
function predict(
|
| 365 |
+
endpoint: string,
|
| 366 |
+
data: unknown[],
|
| 367 |
+
event_data?: unknown
|
| 368 |
+
): Promise<unknown> {
|
| 369 |
+
let data_returned = false;
|
| 370 |
+
let status_complete = false;
|
| 371 |
+
let dependency;
|
| 372 |
+
if (typeof endpoint === "number") {
|
| 373 |
+
dependency = config.dependencies[endpoint];
|
| 374 |
+
} else {
|
| 375 |
+
const trimmed_endpoint = endpoint.replace(/^\//, "");
|
| 376 |
+
dependency = config.dependencies[api_map[trimmed_endpoint]];
|
| 377 |
+
}
|
| 378 |
+
|
| 379 |
+
if (dependency.types.continuous) {
|
| 380 |
+
throw new Error(
|
| 381 |
+
"Cannot call predict on this function as it may run forever. Use submit instead"
|
| 382 |
+
);
|
| 383 |
+
}
|
| 384 |
+
|
| 385 |
+
return new Promise((res, rej) => {
|
| 386 |
+
const app = submit(endpoint, data, event_data);
|
| 387 |
+
let result;
|
| 388 |
+
|
| 389 |
+
app
|
| 390 |
+
.on("data", (d) => {
|
| 391 |
+
// if complete message comes before data, resolve here
|
| 392 |
+
if (status_complete) {
|
| 393 |
+
app.destroy();
|
| 394 |
+
res(d);
|
| 395 |
+
}
|
| 396 |
+
data_returned = true;
|
| 397 |
+
result = d;
|
| 398 |
+
})
|
| 399 |
+
.on("status", (status) => {
|
| 400 |
+
if (status.stage === "error") rej(status);
|
| 401 |
+
if (status.stage === "complete") {
|
| 402 |
+
status_complete = true;
|
| 403 |
+
// if complete message comes after data, resolve here
|
| 404 |
+
if (data_returned) {
|
| 405 |
+
app.destroy();
|
| 406 |
+
res(result);
|
| 407 |
+
}
|
| 408 |
+
}
|
| 409 |
+
});
|
| 410 |
+
});
|
| 411 |
+
}
|
| 412 |
+
|
| 413 |
+
function submit(
|
| 414 |
+
endpoint: string | number,
|
| 415 |
+
data: unknown[],
|
| 416 |
+
event_data?: unknown,
|
| 417 |
+
trigger_id: number | null = null
|
| 418 |
+
): SubmitReturn {
|
| 419 |
+
let fn_index: number;
|
| 420 |
+
let api_info;
|
| 421 |
+
|
| 422 |
+
if (typeof endpoint === "number") {
|
| 423 |
+
fn_index = endpoint;
|
| 424 |
+
api_info = api.unnamed_endpoints[fn_index];
|
| 425 |
+
} else {
|
| 426 |
+
const trimmed_endpoint = endpoint.replace(/^\//, "");
|
| 427 |
+
|
| 428 |
+
fn_index = api_map[trimmed_endpoint];
|
| 429 |
+
api_info = api.named_endpoints[endpoint.trim()];
|
| 430 |
+
}
|
| 431 |
+
|
| 432 |
+
if (typeof fn_index !== "number") {
|
| 433 |
+
throw new Error(
|
| 434 |
+
"There is no endpoint matching that name of fn_index matching that number."
|
| 435 |
+
);
|
| 436 |
+
}
|
| 437 |
+
|
| 438 |
+
let websocket: WebSocket;
|
| 439 |
+
let eventSource: EventSource;
|
| 440 |
+
let protocol = config.protocol ?? "sse";
|
| 441 |
+
|
| 442 |
+
const _endpoint = typeof endpoint === "number" ? "/predict" : endpoint;
|
| 443 |
+
let payload: Payload;
|
| 444 |
+
let event_id: string | null = null;
|
| 445 |
+
let complete: false | Record<string, any> = false;
|
| 446 |
+
const listener_map: ListenerMap<EventType> = {};
|
| 447 |
+
let url_params = "";
|
| 448 |
+
if (typeof window !== "undefined") {
|
| 449 |
+
url_params = new URLSearchParams(window.location.search).toString();
|
| 450 |
+
}
|
| 451 |
+
|
| 452 |
+
handle_blob(
|
| 453 |
+
`${http_protocol}//${resolve_root(host, config.path, true)}`,
|
| 454 |
+
data,
|
| 455 |
+
api_info,
|
| 456 |
+
hf_token
|
| 457 |
+
).then((_payload) => {
|
| 458 |
+
payload = { data: _payload || [], event_data, fn_index, trigger_id };
|
| 459 |
+
if (skip_queue(fn_index, config)) {
|
| 460 |
+
fire_event({
|
| 461 |
+
type: "status",
|
| 462 |
+
endpoint: _endpoint,
|
| 463 |
+
stage: "pending",
|
| 464 |
+
queue: false,
|
| 465 |
+
fn_index,
|
| 466 |
+
time: new Date()
|
| 467 |
+
});
|
| 468 |
+
|
| 469 |
+
post_data(
|
| 470 |
+
`${http_protocol}//${resolve_root(host, config.path, true)}/run${
|
| 471 |
+
_endpoint.startsWith("/") ? _endpoint : `/${_endpoint}`
|
| 472 |
+
}${url_params ? "?" + url_params : ""}`,
|
| 473 |
+
{
|
| 474 |
+
...payload,
|
| 475 |
+
session_hash
|
| 476 |
+
},
|
| 477 |
+
hf_token
|
| 478 |
+
)
|
| 479 |
+
.then(([output, status_code]) => {
|
| 480 |
+
const data = transform_files
|
| 481 |
+
? transform_output(
|
| 482 |
+
output.data,
|
| 483 |
+
api_info,
|
| 484 |
+
config.root,
|
| 485 |
+
config.root_url
|
| 486 |
+
)
|
| 487 |
+
: output.data;
|
| 488 |
+
if (status_code == 200) {
|
| 489 |
+
fire_event({
|
| 490 |
+
type: "data",
|
| 491 |
+
endpoint: _endpoint,
|
| 492 |
+
fn_index,
|
| 493 |
+
data: data,
|
| 494 |
+
time: new Date()
|
| 495 |
+
});
|
| 496 |
+
|
| 497 |
+
fire_event({
|
| 498 |
+
type: "status",
|
| 499 |
+
endpoint: _endpoint,
|
| 500 |
+
fn_index,
|
| 501 |
+
stage: "complete",
|
| 502 |
+
eta: output.average_duration,
|
| 503 |
+
queue: false,
|
| 504 |
+
time: new Date()
|
| 505 |
+
});
|
| 506 |
+
} else {
|
| 507 |
+
fire_event({
|
| 508 |
+
type: "status",
|
| 509 |
+
stage: "error",
|
| 510 |
+
endpoint: _endpoint,
|
| 511 |
+
fn_index,
|
| 512 |
+
message: output.error,
|
| 513 |
+
queue: false,
|
| 514 |
+
time: new Date()
|
| 515 |
+
});
|
| 516 |
+
}
|
| 517 |
+
})
|
| 518 |
+
.catch((e) => {
|
| 519 |
+
fire_event({
|
| 520 |
+
type: "status",
|
| 521 |
+
stage: "error",
|
| 522 |
+
message: e.message,
|
| 523 |
+
endpoint: _endpoint,
|
| 524 |
+
fn_index,
|
| 525 |
+
queue: false,
|
| 526 |
+
time: new Date()
|
| 527 |
+
});
|
| 528 |
+
});
|
| 529 |
+
} else if (protocol == "ws") {
|
| 530 |
+
fire_event({
|
| 531 |
+
type: "status",
|
| 532 |
+
stage: "pending",
|
| 533 |
+
queue: true,
|
| 534 |
+
endpoint: _endpoint,
|
| 535 |
+
fn_index,
|
| 536 |
+
time: new Date()
|
| 537 |
+
});
|
| 538 |
+
let url = new URL(`${ws_protocol}://${resolve_root(
|
| 539 |
+
host,
|
| 540 |
+
config.path,
|
| 541 |
+
true
|
| 542 |
+
)}
|
| 543 |
+
/queue/join${url_params ? "?" + url_params : ""}`);
|
| 544 |
+
|
| 545 |
+
if (jwt) {
|
| 546 |
+
url.searchParams.set("__sign", jwt);
|
| 547 |
+
}
|
| 548 |
+
|
| 549 |
+
websocket = WebSocket_factory(url);
|
| 550 |
+
|
| 551 |
+
websocket.onclose = (evt) => {
|
| 552 |
+
if (!evt.wasClean) {
|
| 553 |
+
fire_event({
|
| 554 |
+
type: "status",
|
| 555 |
+
stage: "error",
|
| 556 |
+
broken: true,
|
| 557 |
+
message: BROKEN_CONNECTION_MSG,
|
| 558 |
+
queue: true,
|
| 559 |
+
endpoint: _endpoint,
|
| 560 |
+
fn_index,
|
| 561 |
+
time: new Date()
|
| 562 |
+
});
|
| 563 |
+
}
|
| 564 |
+
};
|
| 565 |
+
|
| 566 |
+
websocket.onmessage = function (event) {
|
| 567 |
+
const _data = JSON.parse(event.data);
|
| 568 |
+
const { type, status, data } = handle_message(
|
| 569 |
+
_data,
|
| 570 |
+
last_status[fn_index]
|
| 571 |
+
);
|
| 572 |
+
|
| 573 |
+
if (type === "update" && status && !complete) {
|
| 574 |
+
// call 'status' listeners
|
| 575 |
+
fire_event({
|
| 576 |
+
type: "status",
|
| 577 |
+
endpoint: _endpoint,
|
| 578 |
+
fn_index,
|
| 579 |
+
time: new Date(),
|
| 580 |
+
...status
|
| 581 |
+
});
|
| 582 |
+
if (status.stage === "error") {
|
| 583 |
+
websocket.close();
|
| 584 |
+
}
|
| 585 |
+
} else if (type === "hash") {
|
| 586 |
+
websocket.send(JSON.stringify({ fn_index, session_hash }));
|
| 587 |
+
return;
|
| 588 |
+
} else if (type === "data") {
|
| 589 |
+
websocket.send(JSON.stringify({ ...payload, session_hash }));
|
| 590 |
+
} else if (type === "complete") {
|
| 591 |
+
complete = status;
|
| 592 |
+
} else if (type === "log") {
|
| 593 |
+
fire_event({
|
| 594 |
+
type: "log",
|
| 595 |
+
log: data.log,
|
| 596 |
+
level: data.level,
|
| 597 |
+
endpoint: _endpoint,
|
| 598 |
+
fn_index
|
| 599 |
+
});
|
| 600 |
+
} else if (type === "generating") {
|
| 601 |
+
fire_event({
|
| 602 |
+
type: "status",
|
| 603 |
+
time: new Date(),
|
| 604 |
+
...status,
|
| 605 |
+
stage: status?.stage!,
|
| 606 |
+
queue: true,
|
| 607 |
+
endpoint: _endpoint,
|
| 608 |
+
fn_index
|
| 609 |
+
});
|
| 610 |
+
}
|
| 611 |
+
if (data) {
|
| 612 |
+
fire_event({
|
| 613 |
+
type: "data",
|
| 614 |
+
time: new Date(),
|
| 615 |
+
data: transform_files
|
| 616 |
+
? transform_output(
|
| 617 |
+
data.data,
|
| 618 |
+
api_info,
|
| 619 |
+
config.root,
|
| 620 |
+
config.root_url
|
| 621 |
+
)
|
| 622 |
+
: data.data,
|
| 623 |
+
endpoint: _endpoint,
|
| 624 |
+
fn_index
|
| 625 |
+
});
|
| 626 |
+
|
| 627 |
+
if (complete) {
|
| 628 |
+
fire_event({
|
| 629 |
+
type: "status",
|
| 630 |
+
time: new Date(),
|
| 631 |
+
...complete,
|
| 632 |
+
stage: status?.stage!,
|
| 633 |
+
queue: true,
|
| 634 |
+
endpoint: _endpoint,
|
| 635 |
+
fn_index
|
| 636 |
+
});
|
| 637 |
+
websocket.close();
|
| 638 |
+
}
|
| 639 |
+
}
|
| 640 |
+
};
|
| 641 |
+
|
| 642 |
+
// different ws contract for gradio versions older than 3.6.0
|
| 643 |
+
//@ts-ignore
|
| 644 |
+
if (semiver(config.version || "2.0.0", "3.6") < 0) {
|
| 645 |
+
addEventListener("open", () =>
|
| 646 |
+
websocket.send(JSON.stringify({ hash: session_hash }))
|
| 647 |
+
);
|
| 648 |
+
}
|
| 649 |
+
} else {
|
| 650 |
+
fire_event({
|
| 651 |
+
type: "status",
|
| 652 |
+
stage: "pending",
|
| 653 |
+
queue: true,
|
| 654 |
+
endpoint: _endpoint,
|
| 655 |
+
fn_index,
|
| 656 |
+
time: new Date()
|
| 657 |
+
});
|
| 658 |
+
var params = new URLSearchParams({
|
| 659 |
+
fn_index: fn_index.toString(),
|
| 660 |
+
session_hash: session_hash
|
| 661 |
+
}).toString();
|
| 662 |
+
let url = new URL(
|
| 663 |
+
`${http_protocol}//${resolve_root(
|
| 664 |
+
host,
|
| 665 |
+
config.path,
|
| 666 |
+
true
|
| 667 |
+
)}/queue/join?${url_params ? url_params + "&" : ""}${params}`
|
| 668 |
+
);
|
| 669 |
+
|
| 670 |
+
eventSource = new EventSource(url);
|
| 671 |
+
|
| 672 |
+
eventSource.onmessage = async function (event) {
|
| 673 |
+
const _data = JSON.parse(event.data);
|
| 674 |
+
const { type, status, data } = handle_message(
|
| 675 |
+
_data,
|
| 676 |
+
last_status[fn_index]
|
| 677 |
+
);
|
| 678 |
+
|
| 679 |
+
if (type === "update" && status && !complete) {
|
| 680 |
+
// call 'status' listeners
|
| 681 |
+
fire_event({
|
| 682 |
+
type: "status",
|
| 683 |
+
endpoint: _endpoint,
|
| 684 |
+
fn_index,
|
| 685 |
+
time: new Date(),
|
| 686 |
+
...status
|
| 687 |
+
});
|
| 688 |
+
if (status.stage === "error") {
|
| 689 |
+
eventSource.close();
|
| 690 |
+
}
|
| 691 |
+
} else if (type === "data") {
|
| 692 |
+
event_id = _data.event_id as string;
|
| 693 |
+
let [_, status] = await post_data(
|
| 694 |
+
`${http_protocol}//${resolve_root(
|
| 695 |
+
host,
|
| 696 |
+
config.path,
|
| 697 |
+
true
|
| 698 |
+
)}/queue/data`,
|
| 699 |
+
{
|
| 700 |
+
...payload,
|
| 701 |
+
session_hash,
|
| 702 |
+
event_id
|
| 703 |
+
},
|
| 704 |
+
hf_token
|
| 705 |
+
);
|
| 706 |
+
if (status !== 200) {
|
| 707 |
+
fire_event({
|
| 708 |
+
type: "status",
|
| 709 |
+
stage: "error",
|
| 710 |
+
message: BROKEN_CONNECTION_MSG,
|
| 711 |
+
queue: true,
|
| 712 |
+
endpoint: _endpoint,
|
| 713 |
+
fn_index,
|
| 714 |
+
time: new Date()
|
| 715 |
+
});
|
| 716 |
+
eventSource.close();
|
| 717 |
+
}
|
| 718 |
+
} else if (type === "complete") {
|
| 719 |
+
complete = status;
|
| 720 |
+
} else if (type === "log") {
|
| 721 |
+
fire_event({
|
| 722 |
+
type: "log",
|
| 723 |
+
log: data.log,
|
| 724 |
+
level: data.level,
|
| 725 |
+
endpoint: _endpoint,
|
| 726 |
+
fn_index
|
| 727 |
+
});
|
| 728 |
+
} else if (type === "generating") {
|
| 729 |
+
fire_event({
|
| 730 |
+
type: "status",
|
| 731 |
+
time: new Date(),
|
| 732 |
+
...status,
|
| 733 |
+
stage: status?.stage!,
|
| 734 |
+
queue: true,
|
| 735 |
+
endpoint: _endpoint,
|
| 736 |
+
fn_index
|
| 737 |
+
});
|
| 738 |
+
}
|
| 739 |
+
if (data) {
|
| 740 |
+
fire_event({
|
| 741 |
+
type: "data",
|
| 742 |
+
time: new Date(),
|
| 743 |
+
data: transform_files
|
| 744 |
+
? transform_output(
|
| 745 |
+
data.data,
|
| 746 |
+
api_info,
|
| 747 |
+
config.root,
|
| 748 |
+
config.root_url
|
| 749 |
+
)
|
| 750 |
+
: data.data,
|
| 751 |
+
endpoint: _endpoint,
|
| 752 |
+
fn_index
|
| 753 |
+
});
|
| 754 |
+
|
| 755 |
+
if (complete) {
|
| 756 |
+
fire_event({
|
| 757 |
+
type: "status",
|
| 758 |
+
time: new Date(),
|
| 759 |
+
...complete,
|
| 760 |
+
stage: status?.stage!,
|
| 761 |
+
queue: true,
|
| 762 |
+
endpoint: _endpoint,
|
| 763 |
+
fn_index
|
| 764 |
+
});
|
| 765 |
+
eventSource.close();
|
| 766 |
+
}
|
| 767 |
+
}
|
| 768 |
+
};
|
| 769 |
+
}
|
| 770 |
+
});
|
| 771 |
+
|
| 772 |
+
function fire_event<K extends EventType>(event: Event<K>): void {
|
| 773 |
+
const narrowed_listener_map: ListenerMap<K> = listener_map;
|
| 774 |
+
const listeners = narrowed_listener_map[event.type] || [];
|
| 775 |
+
listeners?.forEach((l) => l(event));
|
| 776 |
+
}
|
| 777 |
+
|
| 778 |
+
function on<K extends EventType>(
|
| 779 |
+
eventType: K,
|
| 780 |
+
listener: EventListener<K>
|
| 781 |
+
): SubmitReturn {
|
| 782 |
+
const narrowed_listener_map: ListenerMap<K> = listener_map;
|
| 783 |
+
const listeners = narrowed_listener_map[eventType] || [];
|
| 784 |
+
narrowed_listener_map[eventType] = listeners;
|
| 785 |
+
listeners?.push(listener);
|
| 786 |
+
|
| 787 |
+
return { on, off, cancel, destroy };
|
| 788 |
+
}
|
| 789 |
+
|
| 790 |
+
function off<K extends EventType>(
|
| 791 |
+
eventType: K,
|
| 792 |
+
listener: EventListener<K>
|
| 793 |
+
): SubmitReturn {
|
| 794 |
+
const narrowed_listener_map: ListenerMap<K> = listener_map;
|
| 795 |
+
let listeners = narrowed_listener_map[eventType] || [];
|
| 796 |
+
listeners = listeners?.filter((l) => l !== listener);
|
| 797 |
+
narrowed_listener_map[eventType] = listeners;
|
| 798 |
+
|
| 799 |
+
return { on, off, cancel, destroy };
|
| 800 |
+
}
|
| 801 |
+
|
| 802 |
+
async function cancel(): Promise<void> {
|
| 803 |
+
const _status: Status = {
|
| 804 |
+
stage: "complete",
|
| 805 |
+
queue: false,
|
| 806 |
+
time: new Date()
|
| 807 |
+
};
|
| 808 |
+
complete = _status;
|
| 809 |
+
fire_event({
|
| 810 |
+
..._status,
|
| 811 |
+
type: "status",
|
| 812 |
+
endpoint: _endpoint,
|
| 813 |
+
fn_index: fn_index
|
| 814 |
+
});
|
| 815 |
+
|
| 816 |
+
let cancel_request = {};
|
| 817 |
+
if (protocol === "ws") {
|
| 818 |
+
if (websocket && websocket.readyState === 0) {
|
| 819 |
+
websocket.addEventListener("open", () => {
|
| 820 |
+
websocket.close();
|
| 821 |
+
});
|
| 822 |
+
} else {
|
| 823 |
+
websocket.close();
|
| 824 |
+
}
|
| 825 |
+
cancel_request = { fn_index, session_hash };
|
| 826 |
+
} else {
|
| 827 |
+
eventSource.close();
|
| 828 |
+
cancel_request = { event_id };
|
| 829 |
+
}
|
| 830 |
+
|
| 831 |
+
try {
|
| 832 |
+
await fetch_implementation(
|
| 833 |
+
`${http_protocol}//${resolve_root(
|
| 834 |
+
host,
|
| 835 |
+
config.path,
|
| 836 |
+
true
|
| 837 |
+
)}/reset`,
|
| 838 |
+
{
|
| 839 |
+
headers: { "Content-Type": "application/json" },
|
| 840 |
+
method: "POST",
|
| 841 |
+
body: JSON.stringify(cancel_request)
|
| 842 |
+
}
|
| 843 |
+
);
|
| 844 |
+
} catch (e) {
|
| 845 |
+
console.warn(
|
| 846 |
+
"The `/reset` endpoint could not be called. Subsequent endpoint results may be unreliable."
|
| 847 |
+
);
|
| 848 |
+
}
|
| 849 |
+
}
|
| 850 |
+
|
| 851 |
+
function destroy(): void {
|
| 852 |
+
for (const event_type in listener_map) {
|
| 853 |
+
listener_map[event_type as "data" | "status"].forEach((fn) => {
|
| 854 |
+
off(event_type as "data" | "status", fn);
|
| 855 |
+
});
|
| 856 |
+
}
|
| 857 |
+
}
|
| 858 |
+
|
| 859 |
+
return {
|
| 860 |
+
on,
|
| 861 |
+
off,
|
| 862 |
+
cancel,
|
| 863 |
+
destroy
|
| 864 |
+
};
|
| 865 |
+
}
|
| 866 |
+
|
| 867 |
+
async function component_server(
|
| 868 |
+
component_id: number,
|
| 869 |
+
fn_name: string,
|
| 870 |
+
data: unknown[]
|
| 871 |
+
): Promise<any> {
|
| 872 |
+
const headers: {
|
| 873 |
+
Authorization?: string;
|
| 874 |
+
"Content-Type": "application/json";
|
| 875 |
+
} = { "Content-Type": "application/json" };
|
| 876 |
+
if (hf_token) {
|
| 877 |
+
headers.Authorization = `Bearer ${hf_token}`;
|
| 878 |
+
}
|
| 879 |
+
let root_url: string;
|
| 880 |
+
let component = config.components.find(
|
| 881 |
+
(comp) => comp.id === component_id
|
| 882 |
+
);
|
| 883 |
+
if (component?.props?.root_url) {
|
| 884 |
+
root_url = component.props.root_url;
|
| 885 |
+
} else {
|
| 886 |
+
root_url = `${http_protocol}//${resolve_root(
|
| 887 |
+
host,
|
| 888 |
+
config.path,
|
| 889 |
+
true
|
| 890 |
+
)}/`;
|
| 891 |
+
}
|
| 892 |
+
const response = await fetch_implementation(
|
| 893 |
+
`${root_url}component_server/`,
|
| 894 |
+
{
|
| 895 |
+
method: "POST",
|
| 896 |
+
body: JSON.stringify({
|
| 897 |
+
data: data,
|
| 898 |
+
component_id: component_id,
|
| 899 |
+
fn_name: fn_name,
|
| 900 |
+
session_hash: session_hash
|
| 901 |
+
}),
|
| 902 |
+
headers
|
| 903 |
+
}
|
| 904 |
+
);
|
| 905 |
+
|
| 906 |
+
if (!response.ok) {
|
| 907 |
+
throw new Error(
|
| 908 |
+
"Could not connect to component server: " + response.statusText
|
| 909 |
+
);
|
| 910 |
+
}
|
| 911 |
+
|
| 912 |
+
const output = await response.json();
|
| 913 |
+
return output;
|
| 914 |
+
}
|
| 915 |
+
|
| 916 |
+
async function view_api(config?: Config): Promise<ApiInfo<JsApiData>> {
|
| 917 |
+
if (api) return api;
|
| 918 |
+
|
| 919 |
+
const headers: {
|
| 920 |
+
Authorization?: string;
|
| 921 |
+
"Content-Type": "application/json";
|
| 922 |
+
} = { "Content-Type": "application/json" };
|
| 923 |
+
if (hf_token) {
|
| 924 |
+
headers.Authorization = `Bearer ${hf_token}`;
|
| 925 |
+
}
|
| 926 |
+
let response: Response;
|
| 927 |
+
// @ts-ignore
|
| 928 |
+
if (semiver(config.version || "2.0.0", "3.30") < 0) {
|
| 929 |
+
response = await fetch_implementation(
|
| 930 |
+
"https://gradio-space-api-fetcher-v2.hf.space/api",
|
| 931 |
+
{
|
| 932 |
+
method: "POST",
|
| 933 |
+
body: JSON.stringify({
|
| 934 |
+
serialize: false,
|
| 935 |
+
config: JSON.stringify(config)
|
| 936 |
+
}),
|
| 937 |
+
headers
|
| 938 |
+
}
|
| 939 |
+
);
|
| 940 |
+
} else {
|
| 941 |
+
response = await fetch_implementation(`${config.root}/info`, {
|
| 942 |
+
headers
|
| 943 |
+
});
|
| 944 |
+
}
|
| 945 |
+
|
| 946 |
+
if (!response.ok) {
|
| 947 |
+
throw new Error(BROKEN_CONNECTION_MSG);
|
| 948 |
+
}
|
| 949 |
+
|
| 950 |
+
let api_info = (await response.json()) as
|
| 951 |
+
| ApiInfo<ApiData>
|
| 952 |
+
| { api: ApiInfo<ApiData> };
|
| 953 |
+
if ("api" in api_info) {
|
| 954 |
+
api_info = api_info.api;
|
| 955 |
+
}
|
| 956 |
+
|
| 957 |
+
if (
|
| 958 |
+
api_info.named_endpoints["/predict"] &&
|
| 959 |
+
!api_info.unnamed_endpoints["0"]
|
| 960 |
+
) {
|
| 961 |
+
api_info.unnamed_endpoints[0] = api_info.named_endpoints["/predict"];
|
| 962 |
+
}
|
| 963 |
+
|
| 964 |
+
const x = transform_api_info(api_info, config, api_map);
|
| 965 |
+
return x;
|
| 966 |
+
}
|
| 967 |
+
});
|
| 968 |
+
}
|
| 969 |
+
|
| 970 |
+
async function handle_blob(
|
| 971 |
+
endpoint: string,
|
| 972 |
+
data: unknown[],
|
| 973 |
+
api_info: ApiInfo<JsApiData>,
|
| 974 |
+
token?: `hf_${string}`
|
| 975 |
+
): Promise<unknown[]> {
|
| 976 |
+
const blob_refs = await walk_and_store_blobs(
|
| 977 |
+
data,
|
| 978 |
+
undefined,
|
| 979 |
+
[],
|
| 980 |
+
true,
|
| 981 |
+
api_info
|
| 982 |
+
);
|
| 983 |
+
|
| 984 |
+
return Promise.all(
|
| 985 |
+
blob_refs.map(async ({ path, blob, type }) => {
|
| 986 |
+
if (blob) {
|
| 987 |
+
const file_url = (await upload_files(endpoint, [blob], token))
|
| 988 |
+
.files[0];
|
| 989 |
+
return { path, file_url, type, name: blob?.name };
|
| 990 |
+
}
|
| 991 |
+
return { path, type };
|
| 992 |
+
})
|
| 993 |
+
).then((r) => {
|
| 994 |
+
r.forEach(({ path, file_url, type, name }) => {
|
| 995 |
+
if (type === "Gallery") {
|
| 996 |
+
update_object(data, file_url, path);
|
| 997 |
+
} else if (file_url) {
|
| 998 |
+
const file = new FileData({ path: file_url, orig_name: name });
|
| 999 |
+
update_object(data, file, path);
|
| 1000 |
+
}
|
| 1001 |
+
});
|
| 1002 |
+
|
| 1003 |
+
return data;
|
| 1004 |
+
});
|
| 1005 |
+
}
|
| 1006 |
+
}
|
| 1007 |
+
|
| 1008 |
+
export const { post_data, upload_files, client, handle_blob } = api_factory(
|
| 1009 |
+
fetch,
|
| 1010 |
+
(...args) => new WebSocket(...args)
|
| 1011 |
+
);
|
| 1012 |
+
|
| 1013 |
+
function transform_output(
|
| 1014 |
+
data: any[],
|
| 1015 |
+
api_info: any,
|
| 1016 |
+
root_url: string,
|
| 1017 |
+
remote_url?: string
|
| 1018 |
+
): unknown[] {
|
| 1019 |
+
return data.map((d, i) => {
|
| 1020 |
+
if (api_info?.returns?.[i]?.component === "File") {
|
| 1021 |
+
return normalise_file(d, root_url, remote_url);
|
| 1022 |
+
} else if (api_info?.returns?.[i]?.component === "Gallery") {
|
| 1023 |
+
return d.map((img) => {
|
| 1024 |
+
return Array.isArray(img)
|
| 1025 |
+
? [normalise_file(img[0], root_url, remote_url), img[1]]
|
| 1026 |
+
: [normalise_file(img, root_url, remote_url), null];
|
| 1027 |
+
});
|
| 1028 |
+
} else if (typeof d === "object" && d.path) {
|
| 1029 |
+
return normalise_file(d, root_url, remote_url);
|
| 1030 |
+
}
|
| 1031 |
+
return d;
|
| 1032 |
+
});
|
| 1033 |
+
}
|
| 1034 |
+
|
| 1035 |
+
interface ApiData {
|
| 1036 |
+
label: string;
|
| 1037 |
+
type: {
|
| 1038 |
+
type: any;
|
| 1039 |
+
description: string;
|
| 1040 |
+
};
|
| 1041 |
+
component: string;
|
| 1042 |
+
example_input?: any;
|
| 1043 |
+
}
|
| 1044 |
+
|
| 1045 |
+
interface JsApiData {
|
| 1046 |
+
label: string;
|
| 1047 |
+
type: string;
|
| 1048 |
+
component: string;
|
| 1049 |
+
example_input: any;
|
| 1050 |
+
}
|
| 1051 |
+
|
| 1052 |
+
interface EndpointInfo<T extends ApiData | JsApiData> {
|
| 1053 |
+
parameters: T[];
|
| 1054 |
+
returns: T[];
|
| 1055 |
+
}
|
| 1056 |
+
interface ApiInfo<T extends ApiData | JsApiData> {
|
| 1057 |
+
named_endpoints: {
|
| 1058 |
+
[key: string]: EndpointInfo<T>;
|
| 1059 |
+
};
|
| 1060 |
+
unnamed_endpoints: {
|
| 1061 |
+
[key: string]: EndpointInfo<T>;
|
| 1062 |
+
};
|
| 1063 |
+
}
|
| 1064 |
+
|
| 1065 |
+
function get_type(
|
| 1066 |
+
type: { [key: string]: any },
|
| 1067 |
+
component: string,
|
| 1068 |
+
serializer: string,
|
| 1069 |
+
signature_type: "return" | "parameter"
|
| 1070 |
+
): string {
|
| 1071 |
+
switch (type.type) {
|
| 1072 |
+
case "string":
|
| 1073 |
+
return "string";
|
| 1074 |
+
case "boolean":
|
| 1075 |
+
return "boolean";
|
| 1076 |
+
case "number":
|
| 1077 |
+
return "number";
|
| 1078 |
+
}
|
| 1079 |
+
|
| 1080 |
+
if (
|
| 1081 |
+
serializer === "JSONSerializable" ||
|
| 1082 |
+
serializer === "StringSerializable"
|
| 1083 |
+
) {
|
| 1084 |
+
return "any";
|
| 1085 |
+
} else if (serializer === "ListStringSerializable") {
|
| 1086 |
+
return "string[]";
|
| 1087 |
+
} else if (component === "Image") {
|
| 1088 |
+
return signature_type === "parameter" ? "Blob | File | Buffer" : "string";
|
| 1089 |
+
} else if (serializer === "FileSerializable") {
|
| 1090 |
+
if (type?.type === "array") {
|
| 1091 |
+
return signature_type === "parameter"
|
| 1092 |
+
? "(Blob | File | Buffer)[]"
|
| 1093 |
+
: `{ name: string; data: string; size?: number; is_file?: boolean; orig_name?: string}[]`;
|
| 1094 |
+
}
|
| 1095 |
+
return signature_type === "parameter"
|
| 1096 |
+
? "Blob | File | Buffer"
|
| 1097 |
+
: `{ name: string; data: string; size?: number; is_file?: boolean; orig_name?: string}`;
|
| 1098 |
+
} else if (serializer === "GallerySerializable") {
|
| 1099 |
+
return signature_type === "parameter"
|
| 1100 |
+
? "[(Blob | File | Buffer), (string | null)][]"
|
| 1101 |
+
: `[{ name: string; data: string; size?: number; is_file?: boolean; orig_name?: string}, (string | null))][]`;
|
| 1102 |
+
}
|
| 1103 |
+
}
|
| 1104 |
+
|
| 1105 |
+
function get_description(
|
| 1106 |
+
type: { type: any; description: string },
|
| 1107 |
+
serializer: string
|
| 1108 |
+
): string {
|
| 1109 |
+
if (serializer === "GallerySerializable") {
|
| 1110 |
+
return "array of [file, label] tuples";
|
| 1111 |
+
} else if (serializer === "ListStringSerializable") {
|
| 1112 |
+
return "array of strings";
|
| 1113 |
+
} else if (serializer === "FileSerializable") {
|
| 1114 |
+
return "array of files or single file";
|
| 1115 |
+
}
|
| 1116 |
+
return type.description;
|
| 1117 |
+
}
|
| 1118 |
+
|
| 1119 |
+
function transform_api_info(
|
| 1120 |
+
api_info: ApiInfo<ApiData>,
|
| 1121 |
+
config: Config,
|
| 1122 |
+
api_map: Record<string, number>
|
| 1123 |
+
): ApiInfo<JsApiData> {
|
| 1124 |
+
const new_data = {
|
| 1125 |
+
named_endpoints: {},
|
| 1126 |
+
unnamed_endpoints: {}
|
| 1127 |
+
};
|
| 1128 |
+
for (const key in api_info) {
|
| 1129 |
+
const cat = api_info[key];
|
| 1130 |
+
|
| 1131 |
+
for (const endpoint in cat) {
|
| 1132 |
+
const dep_index = config.dependencies[endpoint]
|
| 1133 |
+
? endpoint
|
| 1134 |
+
: api_map[endpoint.replace("/", "")];
|
| 1135 |
+
|
| 1136 |
+
const info = cat[endpoint];
|
| 1137 |
+
new_data[key][endpoint] = {};
|
| 1138 |
+
new_data[key][endpoint].parameters = {};
|
| 1139 |
+
new_data[key][endpoint].returns = {};
|
| 1140 |
+
new_data[key][endpoint].type = config.dependencies[dep_index].types;
|
| 1141 |
+
new_data[key][endpoint].parameters = info.parameters.map(
|
| 1142 |
+
({ label, component, type, serializer }) => ({
|
| 1143 |
+
label,
|
| 1144 |
+
component,
|
| 1145 |
+
type: get_type(type, component, serializer, "parameter"),
|
| 1146 |
+
description: get_description(type, serializer)
|
| 1147 |
+
})
|
| 1148 |
+
);
|
| 1149 |
+
|
| 1150 |
+
new_data[key][endpoint].returns = info.returns.map(
|
| 1151 |
+
({ label, component, type, serializer }) => ({
|
| 1152 |
+
label,
|
| 1153 |
+
component,
|
| 1154 |
+
type: get_type(type, component, serializer, "return"),
|
| 1155 |
+
description: get_description(type, serializer)
|
| 1156 |
+
})
|
| 1157 |
+
);
|
| 1158 |
+
}
|
| 1159 |
+
}
|
| 1160 |
+
|
| 1161 |
+
return new_data;
|
| 1162 |
+
}
|
| 1163 |
+
|
| 1164 |
+
async function get_jwt(
|
| 1165 |
+
space: string,
|
| 1166 |
+
token: `hf_${string}`
|
| 1167 |
+
): Promise<string | false> {
|
| 1168 |
+
try {
|
| 1169 |
+
const r = await fetch(`https://huggingface.co/api/spaces/${space}/jwt`, {
|
| 1170 |
+
headers: {
|
| 1171 |
+
Authorization: `Bearer ${token}`
|
| 1172 |
+
}
|
| 1173 |
+
});
|
| 1174 |
+
|
| 1175 |
+
const jwt = (await r.json()).token;
|
| 1176 |
+
|
| 1177 |
+
return jwt || false;
|
| 1178 |
+
} catch (e) {
|
| 1179 |
+
console.error(e);
|
| 1180 |
+
return false;
|
| 1181 |
+
}
|
| 1182 |
+
}
|
| 1183 |
+
|
| 1184 |
+
function update_object(object, newValue, stack): void {
|
| 1185 |
+
while (stack.length > 1) {
|
| 1186 |
+
object = object[stack.shift()];
|
| 1187 |
+
}
|
| 1188 |
+
|
| 1189 |
+
object[stack.shift()] = newValue;
|
| 1190 |
+
}
|
| 1191 |
+
|
| 1192 |
+
export async function walk_and_store_blobs(
|
| 1193 |
+
param,
|
| 1194 |
+
type = undefined,
|
| 1195 |
+
path = [],
|
| 1196 |
+
root = false,
|
| 1197 |
+
api_info = undefined
|
| 1198 |
+
): Promise<
|
| 1199 |
+
{
|
| 1200 |
+
path: string[];
|
| 1201 |
+
type: string;
|
| 1202 |
+
blob: Blob | false;
|
| 1203 |
+
}[]
|
| 1204 |
+
> {
|
| 1205 |
+
if (Array.isArray(param)) {
|
| 1206 |
+
let blob_refs = [];
|
| 1207 |
+
|
| 1208 |
+
await Promise.all(
|
| 1209 |
+
param.map(async (v, i) => {
|
| 1210 |
+
let new_path = path.slice();
|
| 1211 |
+
new_path.push(i);
|
| 1212 |
+
|
| 1213 |
+
const array_refs = await walk_and_store_blobs(
|
| 1214 |
+
param[i],
|
| 1215 |
+
root ? api_info?.parameters[i]?.component || undefined : type,
|
| 1216 |
+
new_path,
|
| 1217 |
+
false,
|
| 1218 |
+
api_info
|
| 1219 |
+
);
|
| 1220 |
+
|
| 1221 |
+
blob_refs = blob_refs.concat(array_refs);
|
| 1222 |
+
})
|
| 1223 |
+
);
|
| 1224 |
+
|
| 1225 |
+
return blob_refs;
|
| 1226 |
+
} else if (globalThis.Buffer && param instanceof globalThis.Buffer) {
|
| 1227 |
+
const is_image = type === "Image";
|
| 1228 |
+
return [
|
| 1229 |
+
{
|
| 1230 |
+
path: path,
|
| 1231 |
+
blob: is_image ? false : new NodeBlob([param]),
|
| 1232 |
+
type
|
| 1233 |
+
}
|
| 1234 |
+
];
|
| 1235 |
+
} else if (typeof param === "object") {
|
| 1236 |
+
let blob_refs = [];
|
| 1237 |
+
for (let key in param) {
|
| 1238 |
+
if (param.hasOwnProperty(key)) {
|
| 1239 |
+
let new_path = path.slice();
|
| 1240 |
+
new_path.push(key);
|
| 1241 |
+
blob_refs = blob_refs.concat(
|
| 1242 |
+
await walk_and_store_blobs(
|
| 1243 |
+
param[key],
|
| 1244 |
+
undefined,
|
| 1245 |
+
new_path,
|
| 1246 |
+
false,
|
| 1247 |
+
api_info
|
| 1248 |
+
)
|
| 1249 |
+
);
|
| 1250 |
+
}
|
| 1251 |
+
}
|
| 1252 |
+
return blob_refs;
|
| 1253 |
+
}
|
| 1254 |
+
return [];
|
| 1255 |
+
}
|
| 1256 |
+
|
| 1257 |
+
function image_to_data_uri(blob: Blob): Promise<string | ArrayBuffer> {
|
| 1258 |
+
return new Promise((resolve, _) => {
|
| 1259 |
+
const reader = new FileReader();
|
| 1260 |
+
reader.onloadend = () => resolve(reader.result);
|
| 1261 |
+
reader.readAsDataURL(blob);
|
| 1262 |
+
});
|
| 1263 |
+
}
|
| 1264 |
+
|
| 1265 |
+
function skip_queue(id: number, config: Config): boolean {
|
| 1266 |
+
return (
|
| 1267 |
+
!(config?.dependencies?.[id]?.queue === null
|
| 1268 |
+
? config.enable_queue
|
| 1269 |
+
: config?.dependencies?.[id]?.queue) || false
|
| 1270 |
+
);
|
| 1271 |
+
}
|
| 1272 |
+
|
| 1273 |
+
async function resolve_config(
|
| 1274 |
+
fetch_implementation: typeof fetch,
|
| 1275 |
+
endpoint?: string,
|
| 1276 |
+
token?: `hf_${string}`
|
| 1277 |
+
): Promise<Config> {
|
| 1278 |
+
const headers: { Authorization?: string } = {};
|
| 1279 |
+
if (token) {
|
| 1280 |
+
headers.Authorization = `Bearer ${token}`;
|
| 1281 |
+
}
|
| 1282 |
+
if (
|
| 1283 |
+
typeof window !== "undefined" &&
|
| 1284 |
+
window.gradio_config &&
|
| 1285 |
+
location.origin !== "http://localhost:9876" &&
|
| 1286 |
+
!window.gradio_config.dev_mode
|
| 1287 |
+
) {
|
| 1288 |
+
const path = window.gradio_config.root;
|
| 1289 |
+
const config = window.gradio_config;
|
| 1290 |
+
config.root = resolve_root(endpoint, config.root, false);
|
| 1291 |
+
return { ...config, path: path };
|
| 1292 |
+
} else if (endpoint) {
|
| 1293 |
+
let response = await fetch_implementation(`${endpoint}/config`, {
|
| 1294 |
+
headers
|
| 1295 |
+
});
|
| 1296 |
+
|
| 1297 |
+
if (response.status === 200) {
|
| 1298 |
+
const config = await response.json();
|
| 1299 |
+
config.path = config.path ?? "";
|
| 1300 |
+
config.root = endpoint;
|
| 1301 |
+
return config;
|
| 1302 |
+
}
|
| 1303 |
+
throw new Error("Could not get config.");
|
| 1304 |
+
}
|
| 1305 |
+
|
| 1306 |
+
throw new Error("No config or app endpoint found");
|
| 1307 |
+
}
|
| 1308 |
+
|
| 1309 |
+
async function check_space_status(
|
| 1310 |
+
id: string,
|
| 1311 |
+
type: "subdomain" | "space_name",
|
| 1312 |
+
status_callback: SpaceStatusCallback
|
| 1313 |
+
): Promise<void> {
|
| 1314 |
+
let endpoint =
|
| 1315 |
+
type === "subdomain"
|
| 1316 |
+
? `https://huggingface.co/api/spaces/by-subdomain/${id}`
|
| 1317 |
+
: `https://huggingface.co/api/spaces/${id}`;
|
| 1318 |
+
let response;
|
| 1319 |
+
let _status;
|
| 1320 |
+
try {
|
| 1321 |
+
response = await fetch(endpoint);
|
| 1322 |
+
_status = response.status;
|
| 1323 |
+
if (_status !== 200) {
|
| 1324 |
+
throw new Error();
|
| 1325 |
+
}
|
| 1326 |
+
response = await response.json();
|
| 1327 |
+
} catch (e) {
|
| 1328 |
+
status_callback({
|
| 1329 |
+
status: "error",
|
| 1330 |
+
load_status: "error",
|
| 1331 |
+
message: "Could not get space status",
|
| 1332 |
+
detail: "NOT_FOUND"
|
| 1333 |
+
});
|
| 1334 |
+
return;
|
| 1335 |
+
}
|
| 1336 |
+
|
| 1337 |
+
if (!response || _status !== 200) return;
|
| 1338 |
+
const {
|
| 1339 |
+
runtime: { stage },
|
| 1340 |
+
id: space_name
|
| 1341 |
+
} = response;
|
| 1342 |
+
|
| 1343 |
+
switch (stage) {
|
| 1344 |
+
case "STOPPED":
|
| 1345 |
+
case "SLEEPING":
|
| 1346 |
+
status_callback({
|
| 1347 |
+
status: "sleeping",
|
| 1348 |
+
load_status: "pending",
|
| 1349 |
+
message: "Space is asleep. Waking it up...",
|
| 1350 |
+
detail: stage
|
| 1351 |
+
});
|
| 1352 |
+
|
| 1353 |
+
setTimeout(() => {
|
| 1354 |
+
check_space_status(id, type, status_callback);
|
| 1355 |
+
}, 1000); // poll for status
|
| 1356 |
+
break;
|
| 1357 |
+
case "PAUSED":
|
| 1358 |
+
status_callback({
|
| 1359 |
+
status: "paused",
|
| 1360 |
+
load_status: "error",
|
| 1361 |
+
message:
|
| 1362 |
+
"This space has been paused by the author. If you would like to try this demo, consider duplicating the space.",
|
| 1363 |
+
detail: stage,
|
| 1364 |
+
discussions_enabled: await discussions_enabled(space_name)
|
| 1365 |
+
});
|
| 1366 |
+
break;
|
| 1367 |
+
case "RUNNING":
|
| 1368 |
+
case "RUNNING_BUILDING":
|
| 1369 |
+
status_callback({
|
| 1370 |
+
status: "running",
|
| 1371 |
+
load_status: "complete",
|
| 1372 |
+
message: "",
|
| 1373 |
+
detail: stage
|
| 1374 |
+
});
|
| 1375 |
+
// load_config(source);
|
| 1376 |
+
// launch
|
| 1377 |
+
break;
|
| 1378 |
+
case "BUILDING":
|
| 1379 |
+
status_callback({
|
| 1380 |
+
status: "building",
|
| 1381 |
+
load_status: "pending",
|
| 1382 |
+
message: "Space is building...",
|
| 1383 |
+
detail: stage
|
| 1384 |
+
});
|
| 1385 |
+
|
| 1386 |
+
setTimeout(() => {
|
| 1387 |
+
check_space_status(id, type, status_callback);
|
| 1388 |
+
}, 1000);
|
| 1389 |
+
break;
|
| 1390 |
+
default:
|
| 1391 |
+
status_callback({
|
| 1392 |
+
status: "space_error",
|
| 1393 |
+
load_status: "error",
|
| 1394 |
+
message: "This space is experiencing an issue.",
|
| 1395 |
+
detail: stage,
|
| 1396 |
+
discussions_enabled: await discussions_enabled(space_name)
|
| 1397 |
+
});
|
| 1398 |
+
break;
|
| 1399 |
+
}
|
| 1400 |
+
}
|
| 1401 |
+
|
| 1402 |
+
function handle_message(
|
| 1403 |
+
data: any,
|
| 1404 |
+
last_status: Status["stage"]
|
| 1405 |
+
): {
|
| 1406 |
+
type: "hash" | "data" | "update" | "complete" | "generating" | "log" | "none";
|
| 1407 |
+
data?: any;
|
| 1408 |
+
status?: Status;
|
| 1409 |
+
} {
|
| 1410 |
+
const queue = true;
|
| 1411 |
+
switch (data.msg) {
|
| 1412 |
+
case "send_data":
|
| 1413 |
+
return { type: "data" };
|
| 1414 |
+
case "send_hash":
|
| 1415 |
+
return { type: "hash" };
|
| 1416 |
+
case "queue_full":
|
| 1417 |
+
return {
|
| 1418 |
+
type: "update",
|
| 1419 |
+
status: {
|
| 1420 |
+
queue,
|
| 1421 |
+
message: QUEUE_FULL_MSG,
|
| 1422 |
+
stage: "error",
|
| 1423 |
+
code: data.code,
|
| 1424 |
+
success: data.success
|
| 1425 |
+
}
|
| 1426 |
+
};
|
| 1427 |
+
case "estimation":
|
| 1428 |
+
return {
|
| 1429 |
+
type: "update",
|
| 1430 |
+
status: {
|
| 1431 |
+
queue,
|
| 1432 |
+
stage: last_status || "pending",
|
| 1433 |
+
code: data.code,
|
| 1434 |
+
size: data.queue_size,
|
| 1435 |
+
position: data.rank,
|
| 1436 |
+
eta: data.rank_eta,
|
| 1437 |
+
success: data.success
|
| 1438 |
+
}
|
| 1439 |
+
};
|
| 1440 |
+
case "progress":
|
| 1441 |
+
return {
|
| 1442 |
+
type: "update",
|
| 1443 |
+
status: {
|
| 1444 |
+
queue,
|
| 1445 |
+
stage: "pending",
|
| 1446 |
+
code: data.code,
|
| 1447 |
+
progress_data: data.progress_data,
|
| 1448 |
+
success: data.success
|
| 1449 |
+
}
|
| 1450 |
+
};
|
| 1451 |
+
case "log":
|
| 1452 |
+
return { type: "log", data: data };
|
| 1453 |
+
case "process_generating":
|
| 1454 |
+
return {
|
| 1455 |
+
type: "generating",
|
| 1456 |
+
status: {
|
| 1457 |
+
queue,
|
| 1458 |
+
message: !data.success ? data.output.error : null,
|
| 1459 |
+
stage: data.success ? "generating" : "error",
|
| 1460 |
+
code: data.code,
|
| 1461 |
+
progress_data: data.progress_data,
|
| 1462 |
+
eta: data.average_duration
|
| 1463 |
+
},
|
| 1464 |
+
data: data.success ? data.output : null
|
| 1465 |
+
};
|
| 1466 |
+
case "process_completed":
|
| 1467 |
+
if ("error" in data.output) {
|
| 1468 |
+
return {
|
| 1469 |
+
type: "update",
|
| 1470 |
+
status: {
|
| 1471 |
+
queue,
|
| 1472 |
+
message: data.output.error as string,
|
| 1473 |
+
stage: "error",
|
| 1474 |
+
code: data.code,
|
| 1475 |
+
success: data.success
|
| 1476 |
+
}
|
| 1477 |
+
};
|
| 1478 |
+
}
|
| 1479 |
+
return {
|
| 1480 |
+
type: "complete",
|
| 1481 |
+
status: {
|
| 1482 |
+
queue,
|
| 1483 |
+
message: !data.success ? data.output.error : undefined,
|
| 1484 |
+
stage: data.success ? "complete" : "error",
|
| 1485 |
+
code: data.code,
|
| 1486 |
+
progress_data: data.progress_data,
|
| 1487 |
+
eta: data.output.average_duration
|
| 1488 |
+
},
|
| 1489 |
+
data: data.success ? data.output : null
|
| 1490 |
+
};
|
| 1491 |
+
|
| 1492 |
+
case "process_starts":
|
| 1493 |
+
return {
|
| 1494 |
+
type: "update",
|
| 1495 |
+
status: {
|
| 1496 |
+
queue,
|
| 1497 |
+
stage: "pending",
|
| 1498 |
+
code: data.code,
|
| 1499 |
+
size: data.rank,
|
| 1500 |
+
position: 0,
|
| 1501 |
+
success: data.success
|
| 1502 |
+
}
|
| 1503 |
+
};
|
| 1504 |
+
}
|
| 1505 |
+
|
| 1506 |
+
return { type: "none", status: { stage: "error", queue } };
|
| 1507 |
+
}
|
node_modules/@gradio/client/src/globals.d.ts
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
declare global {
|
| 2 |
+
interface Window {
|
| 3 |
+
__gradio_mode__: "app" | "website";
|
| 4 |
+
gradio_config: Config;
|
| 5 |
+
__is_colab__: boolean;
|
| 6 |
+
__gradio_space__: string | null;
|
| 7 |
+
}
|
| 8 |
+
}
|
| 9 |
+
|
| 10 |
+
export interface Config {
|
| 11 |
+
auth_required: boolean | undefined;
|
| 12 |
+
auth_message: string;
|
| 13 |
+
components: any[];
|
| 14 |
+
css: string | null;
|
| 15 |
+
dependencies: any[];
|
| 16 |
+
dev_mode: boolean;
|
| 17 |
+
enable_queue: boolean;
|
| 18 |
+
layout: any;
|
| 19 |
+
mode: "blocks" | "interface";
|
| 20 |
+
root: string;
|
| 21 |
+
theme: string;
|
| 22 |
+
title: string;
|
| 23 |
+
version: string;
|
| 24 |
+
space_id: string | null;
|
| 25 |
+
is_colab: boolean;
|
| 26 |
+
show_api: boolean;
|
| 27 |
+
stylesheets: string[];
|
| 28 |
+
path: string;
|
| 29 |
+
}
|
node_modules/@gradio/client/src/index.ts
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
export {
|
| 2 |
+
client,
|
| 3 |
+
post_data,
|
| 4 |
+
upload_files,
|
| 5 |
+
duplicate,
|
| 6 |
+
api_factory
|
| 7 |
+
} from "./client.js";
|
| 8 |
+
export type { SpaceStatus } from "./types.js";
|
| 9 |
+
export {
|
| 10 |
+
normalise_file,
|
| 11 |
+
FileData,
|
| 12 |
+
upload,
|
| 13 |
+
get_fetchable_url_or_file,
|
| 14 |
+
prepare_files
|
| 15 |
+
} from "./upload.js";
|