mirror of
https://github.com/RVC-Boss/GPT-SoVITS.git
synced 2026-11-23 22:55:46 +08:00
refactor: reorganize inference service architecture
This commit is contained in:
parent
8fbc8c2ed8
commit
5ed064cdc9
@ -8,6 +8,7 @@ GPT_SoVITS/pretrained_models/*
|
||||
GPT_SoVITS/text/G2PWModel/*
|
||||
__pycache__
|
||||
*.pyc
|
||||
GPT_SoVITS/vendor/ap_bwe/24kto48k/*.zip
|
||||
tools/AP_BWE_main/24kto48k/*.zip
|
||||
references
|
||||
.env
|
||||
|
||||
2
.gitignore
vendored
2
.gitignore
vendored
@ -16,6 +16,8 @@
|
||||
/SoVITS_weights*/
|
||||
/GPT_SoVITS/text/G2PWModel/
|
||||
/GPT_SoVITS/configs/tts_local*.yaml
|
||||
/GPT_SoVITS/vendor/ap_bwe/24kto48k/*
|
||||
!/GPT_SoVITS/vendor/ap_bwe/24kto48k/config.json
|
||||
/tools/AP_BWE_main/24kto48k/*
|
||||
!/tools/AP_BWE_main/24kto48k/config.json
|
||||
/weight.json
|
||||
|
||||
@ -9,7 +9,7 @@ from typing import Optional, TypeVar
|
||||
|
||||
import torch
|
||||
|
||||
from tools.acceleration import cuda_graph_available
|
||||
from GPT_SoVITS.Accel.capabilities import cuda_graph_available
|
||||
|
||||
from .sample_funcs import sample_naive
|
||||
from .structs import KVCache, T2SRequest, T2SSession
|
||||
|
||||
@ -2,7 +2,7 @@
|
||||
|
||||
import os
|
||||
|
||||
from tools.portable_runtime import _prepare_dlls
|
||||
from GPT_SoVITS.runtime.portable import _prepare_dlls
|
||||
|
||||
|
||||
os.environ.setdefault("G2PW", "0")
|
||||
|
||||
@ -6,7 +6,7 @@ from queue import Empty
|
||||
|
||||
import torch
|
||||
|
||||
from tools.acceleration import resolve_acceleration
|
||||
from .capabilities import resolve_acceleration
|
||||
from .PyTorch.AR.structs import T2SRequest
|
||||
from .PyTorch.AR.t2s_engine import T2SEngine
|
||||
|
||||
|
||||
58
GPT_SoVITS/Accel/capabilities.py
Normal file
58
GPT_SoVITS/Accel/capabilities.py
Normal file
@ -0,0 +1,58 @@
|
||||
"""Detect optional AR acceleration capabilities for a device and precision."""
|
||||
|
||||
from functools import lru_cache
|
||||
from importlib import import_module
|
||||
import logging
|
||||
import os
|
||||
|
||||
import torch
|
||||
|
||||
from GPT_SoVITS.runtime.portable import _prepare_dlls
|
||||
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _cuda_available(device):
|
||||
return device.type == "cuda" and torch.cuda.is_available() and torch.version.cuda is not None
|
||||
|
||||
|
||||
def cuda_graph_available(device):
|
||||
device = torch.device(device)
|
||||
return bool(
|
||||
_cuda_available(device)
|
||||
and os.environ.get("CUDAGraph", "1") != "0"
|
||||
and callable(getattr(torch.cuda, "CUDAGraph", None))
|
||||
and callable(getattr(torch.cuda, "graph", None))
|
||||
and callable(getattr(torch.cuda, "Stream", None))
|
||||
and callable(getattr(torch.nn.functional, "scaled_dot_product_attention", None))
|
||||
)
|
||||
|
||||
|
||||
@lru_cache(maxsize=1)
|
||||
def _flash_attention_module():
|
||||
_prepare_dlls()
|
||||
try:
|
||||
return import_module("flash_attn")
|
||||
except (ImportError, OSError, RuntimeError) as exc:
|
||||
_logger.info("FlashAttention is unavailable: %s", exc)
|
||||
return None
|
||||
|
||||
|
||||
def flash_attention_available(device, dtype):
|
||||
device = torch.device(device)
|
||||
if not _cuda_available(device) or dtype not in (torch.float16, torch.bfloat16):
|
||||
return False
|
||||
if torch.cuda.get_device_capability(device)[0] < 8:
|
||||
return False
|
||||
module = _flash_attention_module()
|
||||
return callable(getattr(module, "flash_attn_with_kvcache", None))
|
||||
|
||||
|
||||
def resolve_acceleration(device, dtype, use_cuda_graph=True, use_flash_attention=True):
|
||||
graph = bool(use_cuda_graph and cuda_graph_available(device))
|
||||
if use_flash_attention and flash_attention_available(device, dtype):
|
||||
return "flash_attn_varlen_cuda_graph", graph
|
||||
if graph:
|
||||
return "torch_static_cuda_graph", True
|
||||
return None, False
|
||||
40
GPT_SoVITS/Accel/factory.py
Normal file
40
GPT_SoVITS/Accel/factory.py
Normal file
@ -0,0 +1,40 @@
|
||||
"""Construct optional AR acceleration adapters with ordinary-inference fallback."""
|
||||
|
||||
from importlib import import_module
|
||||
import logging
|
||||
|
||||
from .capabilities import resolve_acceleration
|
||||
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def create_acceleration(
|
||||
weights_path,
|
||||
device,
|
||||
dtype,
|
||||
max_batch_size=32,
|
||||
use_cuda_graph=True,
|
||||
use_flash_attention=True,
|
||||
max_seq_length=None,
|
||||
):
|
||||
backend, _ = resolve_acceleration(device, dtype, use_cuda_graph, use_flash_attention)
|
||||
if backend is None:
|
||||
return None
|
||||
try:
|
||||
from .adapter import AccelInference
|
||||
|
||||
# Preserve the dynamic backend module names consumed by T2SEngine.
|
||||
import_module("GPT_SoVITS.Accel.PyTorch.AR.backends." + backend)
|
||||
except (ImportError, OSError, RuntimeError) as exc:
|
||||
_logger.warning("AR acceleration is unavailable; using ordinary inference: %s", exc)
|
||||
return None
|
||||
return AccelInference(
|
||||
weights_path,
|
||||
device=device,
|
||||
dtype=dtype,
|
||||
max_batch_size=max_batch_size,
|
||||
use_cuda_graph=use_cuda_graph,
|
||||
use_flash_attention=use_flash_attention,
|
||||
max_seq_length=max_seq_length,
|
||||
)
|
||||
@ -1 +0,0 @@
|
||||
from . import TTS, text_segmentation_method
|
||||
1
GPT_SoVITS/__init__.py
Normal file
1
GPT_SoVITS/__init__.py
Normal file
@ -0,0 +1 @@
|
||||
"""GPT-SoVITS inference application package."""
|
||||
@ -1,6 +1,6 @@
|
||||
import torch
|
||||
import os
|
||||
from tools.portable_runtime import prepare_transformers_flash_attention
|
||||
from GPT_SoVITS.runtime.portable import prepare_transformers_flash_attention
|
||||
|
||||
prepare_transformers_flash_attention()
|
||||
|
||||
|
||||
10
GPT_SoVITS/inference/__init__.py
Normal file
10
GPT_SoVITS/inference/__init__.py
Normal file
@ -0,0 +1,10 @@
|
||||
"""Canonical public inference API."""
|
||||
|
||||
from GPT_SoVITS.runtime.portable import activate as _activate
|
||||
|
||||
_activate(change_cwd=False)
|
||||
|
||||
from .config import TTSConfig, TTS_Config
|
||||
from .pipeline import TTS
|
||||
|
||||
__all__ = ["TTS", "TTSConfig", "TTS_Config"]
|
||||
125
GPT_SoVITS/inference/audio.py
Normal file
125
GPT_SoVITS/inference/audio.py
Normal file
@ -0,0 +1,125 @@
|
||||
"""Audio loading, resampling, and spectrogram helpers for inference."""
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
import torchaudio
|
||||
|
||||
from GPT_SoVITS.module.mel_processing import mel_spectrogram_torch
|
||||
|
||||
|
||||
resample_transform_dict = {}
|
||||
resampy_filter_cache = {}
|
||||
spec_min = -12
|
||||
spec_max = 2
|
||||
|
||||
def _resampy_gpu_filter(sr0, sr1, device):
|
||||
key = "%s-%s-%s" % (sr0, sr1, str(device))
|
||||
if key not in resampy_filter_cache:
|
||||
import resampy
|
||||
interp_win, precision, rolloff = resampy.filters.get_filter("kaiser_best")
|
||||
interp_win = torch.from_numpy(interp_win.astype(np.float32)).to(device)
|
||||
interp_delta = torch.diff(interp_win, append=interp_win[-1:])
|
||||
resampy_filter_cache[key] = (interp_win, interp_delta, int(precision))
|
||||
return resampy_filter_cache[key]
|
||||
|
||||
def resample(audio_tensor, sr0, sr1, device, match_librosa=False):
|
||||
if match_librosa:
|
||||
if int(sr0) == int(sr1):
|
||||
return audio_tensor.clone()
|
||||
ratio = float(sr1) / float(sr0)
|
||||
scale = min(1.0, ratio)
|
||||
n_orig = audio_tensor.shape[-1]
|
||||
n_out = int(n_orig * ratio)
|
||||
interp_win, interp_delta, num_table = _resampy_gpu_filter(sr0, sr1, audio_tensor.device)
|
||||
if ratio < 1.0:
|
||||
interp_win = interp_win * ratio
|
||||
interp_delta = interp_delta * ratio
|
||||
index_step = int(scale * num_table)
|
||||
nwin = interp_win.numel()
|
||||
t_all = torch.arange(n_out, device=audio_tensor.device, dtype=torch.float32) / ratio
|
||||
out = torch.zeros((audio_tensor.shape[0], n_out), device=audio_tensor.device, dtype=audio_tensor.dtype)
|
||||
chunk = 4096
|
||||
max_taps = (nwin + index_step - 1) // index_step
|
||||
for begin in range(0, n_out, chunk):
|
||||
t = t_all[begin:begin + chunk]
|
||||
n = torch.floor(t).long()
|
||||
frac = scale * (t - n.to(t.dtype))
|
||||
index_frac = frac * num_table
|
||||
offset = torch.floor(index_frac).long()
|
||||
eta = index_frac - offset.to(index_frac.dtype)
|
||||
ii = torch.arange(max_taps, device=audio_tensor.device).view(1, -1)
|
||||
li = offset.view(-1, 1) + ii * index_step
|
||||
lmax = torch.minimum(n + 1, (nwin - offset) // index_step).view(-1, 1)
|
||||
lm = ii < lmax
|
||||
li_safe = li.clamp(0, nwin - 1)
|
||||
lw = interp_win[li_safe] + eta.view(-1, 1) * interp_delta[li_safe]
|
||||
left_idx = (n.view(-1, 1) - ii).clamp(0, n_orig - 1)
|
||||
left = (lw * lm).to(audio_tensor.dtype)
|
||||
lv = audio_tensor[:, left_idx]
|
||||
frac_r = scale - frac
|
||||
index_frac = frac_r * num_table
|
||||
offset = torch.floor(index_frac).long()
|
||||
eta = index_frac - offset.to(index_frac.dtype)
|
||||
ri = offset.view(-1, 1) + ii * index_step
|
||||
rmax = torch.minimum(n_orig - n - 1, (nwin - offset) // index_step).view(-1, 1)
|
||||
rm = ii < rmax
|
||||
ri_safe = ri.clamp(0, nwin - 1)
|
||||
rw = interp_win[ri_safe] + eta.view(-1, 1) * interp_delta[ri_safe]
|
||||
right_idx = (n.view(-1, 1) + ii + 1).clamp(0, n_orig - 1)
|
||||
right = (rw * rm).to(audio_tensor.dtype)
|
||||
out[:, begin:begin + t.numel()] = (
|
||||
(lv * left.unsqueeze(0)).sum(-1)
|
||||
+ (audio_tensor[:, right_idx] * right.unsqueeze(0)).sum(-1)
|
||||
)
|
||||
return out
|
||||
global resample_transform_dict
|
||||
key = "%s-%s-%s" % (sr0, sr1, str(device))
|
||||
if key not in resample_transform_dict:
|
||||
resample_transform_dict[key] = torchaudio.transforms.Resample(sr0, sr1).to(device)
|
||||
return resample_transform_dict[key](audio_tensor)
|
||||
|
||||
def load_audio_gpu(path, target_sr, device, mono=True, dtype=torch.float32, match_librosa=False):
|
||||
"""Load audio once, then resample and keep the signal on the target device."""
|
||||
audio, source_sr = torchaudio.load(path)
|
||||
audio = audio.to(device=device, dtype=dtype)
|
||||
if mono and audio.dim() == 2 and audio.shape[0] > 1:
|
||||
audio = audio.mean(dim=0, keepdim=True)
|
||||
if source_sr != target_sr:
|
||||
audio = resample(audio, source_sr, target_sr, device, match_librosa=match_librosa)
|
||||
return audio, target_sr
|
||||
|
||||
def norm_spec(x):
|
||||
return (x - spec_min) / (spec_max - spec_min) * 2 - 1
|
||||
|
||||
def denorm_spec(x):
|
||||
return (x + 1) / 2 * (spec_max - spec_min) + spec_min
|
||||
|
||||
|
||||
mel_fn = lambda x: mel_spectrogram_torch(
|
||||
x,
|
||||
**{
|
||||
"n_fft": 1024,
|
||||
"win_size": 1024,
|
||||
"hop_size": 256,
|
||||
"num_mels": 100,
|
||||
"sampling_rate": 24000,
|
||||
"fmin": 0,
|
||||
"fmax": None,
|
||||
"center": False,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
mel_fn_v4 = lambda x: mel_spectrogram_torch(
|
||||
x,
|
||||
**{
|
||||
"n_fft": 1280,
|
||||
"win_size": 1280,
|
||||
"hop_size": 320,
|
||||
"num_mels": 100,
|
||||
"sampling_rate": 32000,
|
||||
"fmin": 0,
|
||||
"fmax": None,
|
||||
"center": False,
|
||||
},
|
||||
)
|
||||
162
GPT_SoVITS/inference/batching.py
Normal file
162
GPT_SoVITS/inference/batching.py
Normal file
@ -0,0 +1,162 @@
|
||||
"""Text bucket construction, padding, and output-order restoration."""
|
||||
|
||||
from typing import List
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
|
||||
|
||||
class BatchingMixin:
|
||||
def batch_sequences(self, sequences: List[torch.Tensor], axis: int = 0, pad_value: int = 0, max_length: int = None):
|
||||
seq = sequences[0]
|
||||
ndim = seq.dim()
|
||||
if axis < 0:
|
||||
axis += ndim
|
||||
dtype: torch.dtype = seq.dtype
|
||||
pad_value = torch.tensor(pad_value, dtype=dtype)
|
||||
seq_lengths = [seq.shape[axis] for seq in sequences]
|
||||
if max_length is None:
|
||||
max_length = max(seq_lengths)
|
||||
else:
|
||||
max_length = max(seq_lengths) if max_length < max(seq_lengths) else max_length
|
||||
|
||||
padded_sequences = []
|
||||
for seq, length in zip(sequences, seq_lengths):
|
||||
padding = [0] * axis + [0, max_length - length] + [0] * (ndim - axis - 1)
|
||||
padded_seq = torch.nn.functional.pad(seq, padding, value=pad_value)
|
||||
padded_sequences.append(padded_seq)
|
||||
batch = torch.stack(padded_sequences)
|
||||
return batch
|
||||
|
||||
def to_batch(
|
||||
self,
|
||||
data: list,
|
||||
prompt_data: dict = None,
|
||||
batch_size: int = 5,
|
||||
threshold: float = 0.75,
|
||||
split_bucket: bool = True,
|
||||
device: torch.device = torch.device("cpu"),
|
||||
precision: torch.dtype = torch.float32,
|
||||
):
|
||||
_data: list = []
|
||||
index_and_len_list = []
|
||||
for idx, item in enumerate(data):
|
||||
norm_text_len = len(item["norm_text"])
|
||||
index_and_len_list.append([idx, norm_text_len])
|
||||
|
||||
batch_index_list = []
|
||||
if split_bucket:
|
||||
index_and_len_list.sort(key=lambda x: x[1])
|
||||
index_and_len_list = np.array(index_and_len_list, dtype=np.int64)
|
||||
|
||||
batch_index_list_len = 0
|
||||
pos = 0
|
||||
while pos < index_and_len_list.shape[0]:
|
||||
# batch_index_list.append(index_and_len_list[pos:min(pos+batch_size,len(index_and_len_list))])
|
||||
pos_end = min(pos + batch_size, index_and_len_list.shape[0])
|
||||
while pos < pos_end:
|
||||
batch = index_and_len_list[pos:pos_end, 1].astype(np.float32)
|
||||
score = batch[(pos_end - pos) // 2] / (batch.mean() + 1e-8)
|
||||
if (score >= threshold) or (pos_end - pos == 1):
|
||||
batch_index = index_and_len_list[pos:pos_end, 0].tolist()
|
||||
batch_index_list_len += len(batch_index)
|
||||
batch_index_list.append(batch_index)
|
||||
pos = pos_end
|
||||
break
|
||||
pos_end = pos_end - 1
|
||||
|
||||
assert batch_index_list_len == len(data)
|
||||
|
||||
else:
|
||||
for i in range(len(data)):
|
||||
if i % batch_size == 0:
|
||||
batch_index_list.append([])
|
||||
batch_index_list[-1].append(i)
|
||||
|
||||
for batch_idx, index_list in enumerate(batch_index_list):
|
||||
item_list = [data[idx] for idx in index_list]
|
||||
phones_list = []
|
||||
phones_len_list = []
|
||||
# bert_features_list = []
|
||||
all_phones_list = []
|
||||
all_phones_len_list = []
|
||||
all_bert_features_list = []
|
||||
norm_text_batch = []
|
||||
all_bert_max_len = 0
|
||||
all_phones_max_len = 0
|
||||
for item in item_list:
|
||||
if prompt_data is not None:
|
||||
all_bert_features = torch.cat([prompt_data["bert_features"], item["bert_features"]], 1).to(
|
||||
dtype=precision, device=device
|
||||
)
|
||||
all_phones = torch.LongTensor(prompt_data["phones"] + item["phones"]).to(device)
|
||||
phones = torch.LongTensor(item["phones"]).to(device)
|
||||
# norm_text = prompt_data["norm_text"]+item["norm_text"]
|
||||
else:
|
||||
all_bert_features = item["bert_features"].to(dtype=precision, device=device)
|
||||
phones = torch.LongTensor(item["phones"]).to(device)
|
||||
all_phones = phones
|
||||
# norm_text = item["norm_text"]
|
||||
|
||||
all_bert_max_len = max(all_bert_max_len, all_bert_features.shape[-1])
|
||||
all_phones_max_len = max(all_phones_max_len, all_phones.shape[-1])
|
||||
|
||||
phones_list.append(phones)
|
||||
phones_len_list.append(phones.shape[-1])
|
||||
all_phones_list.append(all_phones)
|
||||
all_phones_len_list.append(all_phones.shape[-1])
|
||||
all_bert_features_list.append(all_bert_features)
|
||||
norm_text_batch.append(item["norm_text"])
|
||||
|
||||
phones_batch = phones_list
|
||||
all_phones_batch = all_phones_list
|
||||
all_bert_features_batch = all_bert_features_list
|
||||
|
||||
max_len = max(all_bert_max_len, all_phones_max_len)
|
||||
# phones_batch = self.batch_sequences(phones_list, axis=0, pad_value=0, max_length=max_len)
|
||||
#### 直接对phones和bert_features进行pad。(padding策略会影响T2S模型生成的结果,但不直接影响复读概率。影响复读概率的主要因素是mask的策略)
|
||||
# all_phones_batch = self.batch_sequences(all_phones_list, axis=0, pad_value=0, max_length=max_len)
|
||||
# all_bert_features_batch = all_bert_features_list
|
||||
# all_bert_features_batch = torch.zeros((len(all_bert_features_list), 1024, max_len), dtype=precision, device=device)
|
||||
# for idx, item in enumerate(all_bert_features_list):
|
||||
# all_bert_features_batch[idx, :, : item.shape[-1]] = item
|
||||
|
||||
# #### 先对phones进行embedding、对bert_features进行project,再pad到相同长度,(padding策略会影响T2S模型生成的结果,但不直接影响复读概率。影响复读概率的主要因素是mask的策略)
|
||||
# all_phones_list = [self.t2s_model.model.ar_text_embedding(item.to(self.t2s_model.device)) for item in all_phones_list]
|
||||
# all_phones_list = [F.pad(item,(0,0,0,max_len-item.shape[0]),value=0) for item in all_phones_list]
|
||||
# all_phones_batch = torch.stack(all_phones_list, dim=0)
|
||||
|
||||
# all_bert_features_list = [self.t2s_model.model.bert_proj(item.to(self.t2s_model.device).transpose(0, 1)) for item in all_bert_features_list]
|
||||
# all_bert_features_list = [F.pad(item,(0,0,0,max_len-item.shape[0]), value=0) for item in all_bert_features_list]
|
||||
# all_bert_features_batch = torch.stack(all_bert_features_list, dim=0)
|
||||
|
||||
batch = {
|
||||
"phones": phones_batch,
|
||||
"phones_len": torch.LongTensor(phones_len_list).to(device),
|
||||
"all_phones": all_phones_batch,
|
||||
"all_phones_len": torch.LongTensor(all_phones_len_list).to(device),
|
||||
"all_bert_features": all_bert_features_batch,
|
||||
"norm_text": norm_text_batch,
|
||||
"max_len": max_len,
|
||||
}
|
||||
_data.append(batch)
|
||||
|
||||
return _data, batch_index_list
|
||||
|
||||
def recovery_order(self, data: list, batch_index_list: list) -> list:
|
||||
"""
|
||||
Recovery the order of the audio according to the batch_index_list.
|
||||
|
||||
Args:
|
||||
data (List[list(torch.Tensor)]): the out of order audio .
|
||||
batch_index_list (List[list[int]]): the batch index list.
|
||||
|
||||
Returns:
|
||||
list (List[torch.Tensor]): the data in the original order.
|
||||
"""
|
||||
length = len(sum(batch_index_list, []))
|
||||
_data = [None] * length
|
||||
for i, index_list in enumerate(batch_index_list):
|
||||
for j, index in enumerate(index_list):
|
||||
_data[index] = data[i][j]
|
||||
return _data
|
||||
210
GPT_SoVITS/inference/config.py
Normal file
210
GPT_SoVITS/inference/config.py
Normal file
@ -0,0 +1,210 @@
|
||||
"""Configuration contract for the stateful TTS pipeline."""
|
||||
|
||||
import os
|
||||
from copy import deepcopy
|
||||
from typing import Union
|
||||
|
||||
import torch
|
||||
import yaml
|
||||
|
||||
from GPT_SoVITS.runtime.i18n import I18nAuto
|
||||
|
||||
language = os.environ.get("language", "Auto")
|
||||
i18n = I18nAuto(language=language)
|
||||
V5_VERSIONS = {"v5dev", "v5turbo"}
|
||||
|
||||
|
||||
class TTSConfig:
|
||||
default_configs = {
|
||||
"v1": {
|
||||
"device": "cpu",
|
||||
"is_half": False,
|
||||
"version": "v1",
|
||||
"t2s_weights_path": "GPT_SoVITS/pretrained_models/s1bert25hz-2kh-longer-epoch=68e-step=50232.ckpt",
|
||||
"vits_weights_path": "GPT_SoVITS/pretrained_models/s2G488k.pth",
|
||||
"cnhuhbert_base_path": "GPT_SoVITS/pretrained_models/chinese-hubert-base",
|
||||
"bert_base_path": "GPT_SoVITS/pretrained_models/chinese-roberta-wwm-ext-large",
|
||||
},
|
||||
"v2": {
|
||||
"device": "cpu",
|
||||
"is_half": False,
|
||||
"version": "v2",
|
||||
"t2s_weights_path": "GPT_SoVITS/pretrained_models/gsv-v2final-pretrained/s1bert25hz-5kh-longer-epoch=12-step=369668.ckpt",
|
||||
"vits_weights_path": "GPT_SoVITS/pretrained_models/gsv-v2final-pretrained/s2G2333k.pth",
|
||||
"cnhuhbert_base_path": "GPT_SoVITS/pretrained_models/chinese-hubert-base",
|
||||
"bert_base_path": "GPT_SoVITS/pretrained_models/chinese-roberta-wwm-ext-large",
|
||||
},
|
||||
"v3": {
|
||||
"device": "cpu",
|
||||
"is_half": False,
|
||||
"version": "v3",
|
||||
"t2s_weights_path": "GPT_SoVITS/pretrained_models/s1v3.ckpt",
|
||||
"vits_weights_path": "GPT_SoVITS/pretrained_models/s2Gv3.pth",
|
||||
"cnhuhbert_base_path": "GPT_SoVITS/pretrained_models/chinese-hubert-base",
|
||||
"bert_base_path": "GPT_SoVITS/pretrained_models/chinese-roberta-wwm-ext-large",
|
||||
},
|
||||
"v4": {
|
||||
"device": "cpu",
|
||||
"is_half": False,
|
||||
"version": "v4",
|
||||
"t2s_weights_path": "GPT_SoVITS/pretrained_models/s1v3.ckpt",
|
||||
"vits_weights_path": "GPT_SoVITS/pretrained_models/gsv-v4-pretrained/s2Gv4.pth",
|
||||
"cnhuhbert_base_path": "GPT_SoVITS/pretrained_models/chinese-hubert-base",
|
||||
"bert_base_path": "GPT_SoVITS/pretrained_models/chinese-roberta-wwm-ext-large",
|
||||
},
|
||||
"v2Pro": {
|
||||
"device": "cpu",
|
||||
"is_half": False,
|
||||
"version": "v2Pro",
|
||||
"t2s_weights_path": "GPT_SoVITS/pretrained_models/s1v3.ckpt",
|
||||
"vits_weights_path": "GPT_SoVITS/pretrained_models/v2Pro/s2Gv2Pro.pth",
|
||||
"cnhuhbert_base_path": "GPT_SoVITS/pretrained_models/chinese-hubert-base",
|
||||
"bert_base_path": "GPT_SoVITS/pretrained_models/chinese-roberta-wwm-ext-large",
|
||||
},
|
||||
"v2ProPlus": {
|
||||
"device": "cpu",
|
||||
"is_half": False,
|
||||
"version": "v2ProPlus",
|
||||
"t2s_weights_path": "GPT_SoVITS/pretrained_models/s1v3.ckpt",
|
||||
"vits_weights_path": "GPT_SoVITS/pretrained_models/v2Pro/s2Gv2ProPlus.pth",
|
||||
"cnhuhbert_base_path": "GPT_SoVITS/pretrained_models/chinese-hubert-base",
|
||||
"bert_base_path": "GPT_SoVITS/pretrained_models/chinese-roberta-wwm-ext-large",
|
||||
},
|
||||
}
|
||||
for v5_variant in V5_VERSIONS:
|
||||
default_configs[v5_variant] = dict(
|
||||
default_configs["v4"], version=v5_variant,
|
||||
vits_weights_path=f"GPT_SoVITS/pretrained_models/gsv-v5-pretrained/s2G{v5_variant}.pth",
|
||||
)
|
||||
configs: dict = None
|
||||
v1_languages: list = ["auto", "en", "zh", "ja", "all_zh", "all_ja"]
|
||||
v2_languages: list = ["auto", "auto_yue", "en", "zh", "ja", "yue", "ko", "all_zh", "all_ja", "all_yue", "all_ko"]
|
||||
languages: list = v2_languages
|
||||
mute_tokens: dict = {
|
||||
"v1" : 486,
|
||||
"v2" : 486,
|
||||
"v2Pro": 486,
|
||||
"v2ProPlus": 486,
|
||||
"v3" : 486,
|
||||
"v4" : 486,
|
||||
"v5dev": 486,
|
||||
"v5turbo": 486,
|
||||
}
|
||||
mute_emb_sim_matrix: torch.Tensor = None
|
||||
# "all_zh",#全部按中文识别
|
||||
# "en",#全部按英文识别#######不变
|
||||
# "all_ja",#全部按日文识别
|
||||
# "all_yue",#全部按中文识别
|
||||
# "all_ko",#全部按韩文识别
|
||||
# "zh",#按中英混合识别####不变
|
||||
# "ja",#按日英混合识别####不变
|
||||
# "yue",#按粤英混合识别####不变
|
||||
# "ko",#按韩英混合识别####不变
|
||||
# "auto",#多语种启动切分识别语种
|
||||
# "auto_yue",#多语种启动切分识别语种
|
||||
|
||||
def __init__(self, configs: Union[dict, str] = None):
|
||||
# 设置默认配置文件路径
|
||||
configs_base_path: str = "GPT_SoVITS/configs/"
|
||||
self.configs_path: str = os.path.join(configs_base_path, "tts_infer.yaml")
|
||||
|
||||
if configs in ["", None]:
|
||||
configs: dict = deepcopy(self.default_configs)
|
||||
|
||||
if isinstance(configs, str):
|
||||
self.configs_path = configs
|
||||
configs: dict = self._load_configs(self.configs_path)
|
||||
|
||||
assert isinstance(configs, dict)
|
||||
configs_ = deepcopy(self.default_configs)
|
||||
configs_.update(configs)
|
||||
self.configs: dict = configs_.get("custom", configs_["v2"])
|
||||
self.default_configs = deepcopy(configs_)
|
||||
|
||||
self.device = self.configs.get("device", torch.device("cpu"))
|
||||
if "cuda" in str(self.device) and not torch.cuda.is_available():
|
||||
print("Warning: CUDA is not available, set device to CPU.")
|
||||
self.device = torch.device("cpu")
|
||||
|
||||
self.is_half = self.configs.get("is_half", False)
|
||||
if str(self.device) == "cpu" and self.is_half:
|
||||
print(f"Warning: Half precision is not supported on CPU, set is_half to False.")
|
||||
self.is_half = False
|
||||
|
||||
version = self.configs.get("version", None)
|
||||
self.version = version
|
||||
assert self.version in ["v1", "v2", "v3", "v4", "v5dev", "v5turbo", "v2Pro", "v2ProPlus"], "Invalid version!"
|
||||
self.t2s_weights_path = self.configs.get("t2s_weights_path", None)
|
||||
self.vits_weights_path = self.configs.get("vits_weights_path", None)
|
||||
self.bert_base_path = self.configs.get("bert_base_path", None)
|
||||
self.cnhuhbert_base_path = self.configs.get("cnhuhbert_base_path", None)
|
||||
self.languages = self.v1_languages if self.version == "v1" else self.v2_languages
|
||||
|
||||
self.use_vocoder: bool = False
|
||||
|
||||
if (self.t2s_weights_path in [None, ""]) or (not os.path.exists(self.t2s_weights_path)):
|
||||
self.t2s_weights_path = self.default_configs[version]["t2s_weights_path"]
|
||||
print(f"fall back to default t2s_weights_path: {self.t2s_weights_path}")
|
||||
if (self.vits_weights_path in [None, ""]) or (not os.path.exists(self.vits_weights_path)):
|
||||
self.vits_weights_path = self.default_configs[version]["vits_weights_path"]
|
||||
print(f"fall back to default vits_weights_path: {self.vits_weights_path}")
|
||||
if (self.bert_base_path in [None, ""]) or (not os.path.exists(self.bert_base_path)):
|
||||
self.bert_base_path = self.default_configs[version]["bert_base_path"]
|
||||
print(f"fall back to default bert_base_path: {self.bert_base_path}")
|
||||
if (self.cnhuhbert_base_path in [None, ""]) or (not os.path.exists(self.cnhuhbert_base_path)):
|
||||
self.cnhuhbert_base_path = self.default_configs[version]["cnhuhbert_base_path"]
|
||||
print(f"fall back to default cnhuhbert_base_path: {self.cnhuhbert_base_path}")
|
||||
self.update_configs()
|
||||
|
||||
self.max_sec = None
|
||||
self.hz: int = 50
|
||||
self.semantic_frame_rate: str = "25hz"
|
||||
self.filter_length: int = 2048
|
||||
self.sampling_rate: int = 32000
|
||||
self.hop_length: int = 640
|
||||
self.win_length: int = 2048
|
||||
|
||||
def _load_configs(self, configs_path: str) -> dict:
|
||||
if not os.path.exists(configs_path):
|
||||
print(i18n("路径不存在,使用默认配置"))
|
||||
return deepcopy(self.default_configs)
|
||||
with open(configs_path, "r", encoding="utf-8") as f:
|
||||
configs = yaml.load(f, Loader=yaml.FullLoader)
|
||||
|
||||
return configs
|
||||
|
||||
def update_configs(self):
|
||||
self.config = {
|
||||
"device": str(self.device),
|
||||
"is_half": self.is_half,
|
||||
"version": self.version,
|
||||
"t2s_weights_path": self.t2s_weights_path,
|
||||
"vits_weights_path": self.vits_weights_path,
|
||||
"bert_base_path": self.bert_base_path,
|
||||
"cnhuhbert_base_path": self.cnhuhbert_base_path,
|
||||
}
|
||||
return self.config
|
||||
|
||||
def update_version(self, version: str) -> None:
|
||||
self.version = version
|
||||
self.languages = self.v1_languages if self.version == "v1" else self.v2_languages
|
||||
|
||||
def __str__(self):
|
||||
self.configs = self.update_configs()
|
||||
string = "TTS Config".center(100, "-") + "\n"
|
||||
for k, v in self.configs.items():
|
||||
string += f"{str(k).ljust(20)}: {str(v)}\n"
|
||||
string += "-" * 100 + "\n"
|
||||
return string
|
||||
|
||||
def __repr__(self):
|
||||
return self.__str__()
|
||||
|
||||
def __hash__(self):
|
||||
return hash(self.configs_path)
|
||||
|
||||
def __eq__(self, other):
|
||||
return isinstance(other, TTSConfig) and self.configs_path == other.configs_path
|
||||
|
||||
|
||||
TTS_Config = TTSConfig
|
||||
271
GPT_SoVITS/inference/model_runtime.py
Normal file
271
GPT_SoVITS/inference/model_runtime.py
Normal file
@ -0,0 +1,271 @@
|
||||
"""Model construction, checkpoint loading, and hot-switch lifecycle."""
|
||||
|
||||
import os
|
||||
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
from peft import LoraConfig, get_peft_model
|
||||
from transformers import AutoModel, AutoTokenizer
|
||||
|
||||
from GPT_SoVITS.AR.models.t2s_inference import Text2SemanticInference
|
||||
from GPT_SoVITS.BigVGAN.bigvgan import BigVGAN
|
||||
from GPT_SoVITS.feature_extractor.cnhubert import CNHubert
|
||||
from GPT_SoVITS.inference.checkpoints import get_sovits_version_from_path_fast, load_sovits_new
|
||||
from GPT_SoVITS.inference.speaker import SV
|
||||
from GPT_SoVITS.inference.super_resolution import AP_BWE
|
||||
from GPT_SoVITS.module.models import Generator, SynthesizerTrn, SynthesizerTrnV3
|
||||
from GPT_SoVITS.module.models_v5 import V5_VERSIONS
|
||||
from GPT_SoVITS.runtime.i18n import I18nAuto
|
||||
|
||||
now_dir = os.getcwd()
|
||||
language = os.environ.get("language", "Auto")
|
||||
i18n = I18nAuto(language=language)
|
||||
|
||||
|
||||
class DictToAttrRecursive(dict):
|
||||
def __init__(self, input_dict):
|
||||
super().__init__(input_dict)
|
||||
for key, value in input_dict.items():
|
||||
if isinstance(value, dict):
|
||||
value = DictToAttrRecursive(value)
|
||||
self[key] = value
|
||||
setattr(self, key, value)
|
||||
|
||||
def __getattr__(self, item):
|
||||
try:
|
||||
return self[item]
|
||||
except KeyError:
|
||||
raise AttributeError(f"Attribute {item} not found")
|
||||
|
||||
def __setattr__(self, key, value):
|
||||
if isinstance(value, dict):
|
||||
value = DictToAttrRecursive(value)
|
||||
super(DictToAttrRecursive, self).__setitem__(key, value)
|
||||
super().__setattr__(key, value)
|
||||
|
||||
def __delattr__(self, item):
|
||||
try:
|
||||
del self[item]
|
||||
except KeyError:
|
||||
raise AttributeError(f"Attribute {item} not found")
|
||||
|
||||
|
||||
class ModelRuntimeMixin:
|
||||
def _init_models(
|
||||
self,
|
||||
):
|
||||
self.init_t2s_weights(self.configs.t2s_weights_path)
|
||||
self.init_vits_weights(self.configs.vits_weights_path)
|
||||
self.init_bert_weights(self.configs.bert_base_path)
|
||||
self.init_cnhuhbert_weights(self.configs.cnhuhbert_base_path)
|
||||
|
||||
def init_cnhuhbert_weights(self, base_path: str):
|
||||
print(f"Loading CNHuBERT weights from {base_path}")
|
||||
self.cnhuhbert_model = CNHubert(base_path)
|
||||
self.cnhuhbert_model = self.cnhuhbert_model.eval()
|
||||
self.cnhuhbert_model = self.cnhuhbert_model.to(self.configs.device)
|
||||
if self.configs.is_half and str(self.configs.device) != "cpu":
|
||||
self.cnhuhbert_model = self.cnhuhbert_model.half()
|
||||
|
||||
def init_bert_weights(self, base_path: str):
|
||||
print(f"Loading BERT weights from {base_path}")
|
||||
self.bert_tokenizer = AutoTokenizer.from_pretrained(base_path)
|
||||
self.bert_model = AutoModel.from_pretrained(base_path, add_pooling_layer=False)
|
||||
self.bert_model = self.bert_model.eval()
|
||||
self.bert_model = self.bert_model.to(self.configs.device)
|
||||
if self.configs.is_half and str(self.configs.device) != "cpu":
|
||||
self.bert_model = self.bert_model.half()
|
||||
|
||||
def init_vits_weights(self, weights_path: str):
|
||||
self.configs.vits_weights_path = weights_path
|
||||
version, model_version, if_lora_v3 = get_sovits_version_from_path_fast(weights_path)
|
||||
if "Pro" in model_version:
|
||||
self.init_sv_model()
|
||||
path_sovits = self.configs.default_configs[model_version]["vits_weights_path"]
|
||||
|
||||
if if_lora_v3 == True and os.path.exists(path_sovits) == False:
|
||||
info = path_sovits + i18n("SoVITS %s 底模缺失,无法加载相应 LoRA 权重" % model_version)
|
||||
raise FileNotFoundError(info)
|
||||
|
||||
# dict_s2 = torch.load(weights_path, map_location=self.configs.device,weights_only=False)
|
||||
dict_s2 = load_sovits_new(weights_path)
|
||||
hps = dict_s2["config"]
|
||||
hps["model"]["semantic_frame_rate"] = "25hz"
|
||||
if "enc_p.text_embedding.weight" not in dict_s2["weight"]:
|
||||
hps["model"]["version"] = "v2" # v3model,v2sybomls
|
||||
elif dict_s2["weight"]["enc_p.text_embedding.weight"].shape[0] == 322:
|
||||
hps["model"]["version"] = "v1"
|
||||
else:
|
||||
hps["model"]["version"] = "v2"
|
||||
version = hps["model"]["version"]
|
||||
v3v4set = {"v3", "v4"} | V5_VERSIONS
|
||||
if model_version not in v3v4set:
|
||||
if "Pro" not in model_version:
|
||||
model_version = version
|
||||
else:
|
||||
hps["model"]["version"] = model_version
|
||||
else:
|
||||
hps["model"]["version"] = model_version
|
||||
|
||||
self.configs.filter_length = hps["data"]["filter_length"]
|
||||
self.configs.sampling_rate = hps["data"]["sampling_rate"]
|
||||
self.configs.hop_length = hps["data"]["hop_length"]
|
||||
self.configs.win_length = hps["data"]["win_length"]
|
||||
self.configs.semantic_frame_rate = hps["model"]["semantic_frame_rate"]
|
||||
kwargs = hps["model"]
|
||||
# print(f"self.configs.sampling_rate:{self.configs.sampling_rate}")
|
||||
|
||||
self.configs.update_version(model_version)
|
||||
|
||||
# print(f"model_version:{model_version}")
|
||||
# print(f'hps["model"]["version"]:{hps["model"]["version"]}')
|
||||
if model_version not in v3v4set:
|
||||
vits_model = SynthesizerTrn(
|
||||
self.configs.filter_length // 2 + 1,
|
||||
**kwargs,
|
||||
)
|
||||
self.configs.use_vocoder = False
|
||||
else:
|
||||
kwargs["version"] = model_version
|
||||
vits_model = SynthesizerTrnV3(
|
||||
self.configs.filter_length // 2 + 1,
|
||||
**kwargs,
|
||||
)
|
||||
self.configs.use_vocoder = True
|
||||
self.init_vocoder(model_version)
|
||||
|
||||
self.is_v2pro = model_version in {"v2Pro", "v2ProPlus"}
|
||||
|
||||
if if_lora_v3 == False:
|
||||
print(
|
||||
f"Loading VITS weights from {weights_path}. {vits_model.load_state_dict(dict_s2['weight'], strict=False)}"
|
||||
)
|
||||
else:
|
||||
print(
|
||||
f"Loading VITS pretrained weights from {weights_path}. {vits_model.load_state_dict(load_sovits_new(path_sovits)['weight'], strict=False)}"
|
||||
)
|
||||
lora_rank = dict_s2["lora_rank"]
|
||||
lora_config = LoraConfig(
|
||||
target_modules=["to_k", "to_q", "to_v", "to_out.0"],
|
||||
r=lora_rank,
|
||||
lora_alpha=lora_rank,
|
||||
init_lora_weights=True,
|
||||
)
|
||||
vits_model.cfm = get_peft_model(vits_model.cfm, lora_config)
|
||||
print(
|
||||
f"Loading LoRA weights from {weights_path}. {vits_model.load_state_dict(dict_s2['weight'], strict=False)}"
|
||||
)
|
||||
|
||||
vits_model.cfm = vits_model.cfm.merge_and_unload()
|
||||
|
||||
vits_model = vits_model.to(self.configs.device)
|
||||
vits_model = vits_model.eval()
|
||||
|
||||
self.vits_model = vits_model
|
||||
if self.configs.is_half and str(self.configs.device) != "cpu":
|
||||
self.vits_model = self.vits_model.half()
|
||||
|
||||
def init_t2s_weights(self, weights_path: str):
|
||||
if self.streaming_accel is not None:
|
||||
self.streaming_accel.close()
|
||||
self.streaming_accel = None
|
||||
if self.t2s_accel is not None:
|
||||
self.t2s_accel.close()
|
||||
self.t2s_accel = None
|
||||
print(f"Loading Text2Semantic weights from {weights_path}")
|
||||
self.configs.t2s_weights_path = weights_path
|
||||
self.configs.hz = 50
|
||||
dict_s1 = torch.load(weights_path, map_location=self.configs.device, weights_only=False)
|
||||
config = dict_s1["config"]
|
||||
self.configs.max_sec = config["data"]["max_sec"]
|
||||
t2s_model = Text2SemanticInference(config)
|
||||
t2s_model.load_state_dict(dict_s1["weight"])
|
||||
t2s_model = t2s_model.to(self.configs.device)
|
||||
t2s_model = t2s_model.eval()
|
||||
self.t2s_model = t2s_model
|
||||
if self.configs.is_half and str(self.configs.device) != "cpu":
|
||||
self.t2s_model = self.t2s_model.half()
|
||||
|
||||
codebook = t2s_model.model.ar_audio_embedding.weight.clone()
|
||||
mute_emb = codebook[self.configs.mute_tokens[self.configs.version]].unsqueeze(0)
|
||||
sim_matrix = F.cosine_similarity(mute_emb.float(), codebook.float(), dim=-1)
|
||||
self.configs.mute_emb_sim_matrix = sim_matrix
|
||||
|
||||
def init_vocoder(self, version: str):
|
||||
if version == "v3":
|
||||
if self.vocoder is not None and self.vocoder.__class__.__name__ == "BigVGAN":
|
||||
return
|
||||
if self.vocoder is not None:
|
||||
self.vocoder.cpu()
|
||||
del self.vocoder
|
||||
self.empty_cache()
|
||||
|
||||
self.vocoder = BigVGAN.from_pretrained(
|
||||
"%s/GPT_SoVITS/pretrained_models/models--nvidia--bigvgan_v2_24khz_100band_256x" % (now_dir,),
|
||||
use_cuda_kernel=False,
|
||||
)
|
||||
# remove weight norm in the model and set to eval mode
|
||||
self.vocoder.remove_weight_norm()
|
||||
|
||||
self.vocoder_configs["sr"] = 24000
|
||||
self.vocoder_configs["T_ref"] = 468
|
||||
self.vocoder_configs["T_chunk"] = 934
|
||||
self.vocoder_configs["upsample_rate"] = 256
|
||||
self.vocoder_configs["overlapped_len"] = 12
|
||||
|
||||
elif version in ({"v4"} | V5_VERSIONS):
|
||||
if (self.vocoder is not None and self.vocoder.__class__.__name__ == "Generator"
|
||||
and getattr(self, "_vocoder_version", None) == version):
|
||||
return
|
||||
if self.vocoder is not None:
|
||||
self.vocoder.cpu()
|
||||
del self.vocoder
|
||||
self.empty_cache()
|
||||
|
||||
self.vocoder = Generator(
|
||||
initial_channel=100,
|
||||
resblock="1",
|
||||
resblock_kernel_sizes=[3, 7, 11],
|
||||
resblock_dilation_sizes=[[1, 3, 5], [1, 3, 5], [1, 3, 5]],
|
||||
upsample_rates=[10, 6, 2, 2, 2],
|
||||
upsample_initial_channel=512,
|
||||
upsample_kernel_sizes=[20, 12, 4, 4, 4],
|
||||
gin_channels=0,
|
||||
is_bias=True,
|
||||
)
|
||||
self.vocoder.remove_weight_norm()
|
||||
state_dict_g = torch.load(
|
||||
"%s/GPT_SoVITS/pretrained_models/gsv-%s-pretrained/vocoder.pth" %
|
||||
(now_dir, "v5" if version in V5_VERSIONS else version),
|
||||
map_location="cpu",
|
||||
weights_only=False,
|
||||
)
|
||||
print("loading vocoder", self.vocoder.load_state_dict(state_dict_g))
|
||||
|
||||
self.vocoder_configs["sr"] = 48000
|
||||
self.vocoder_configs["T_ref"] = 500
|
||||
self.vocoder_configs["T_chunk"] = 1000
|
||||
self.vocoder_configs["upsample_rate"] = 480
|
||||
self.vocoder_configs["overlapped_len"] = 12
|
||||
|
||||
self.vocoder = self.vocoder.eval()
|
||||
self._vocoder_version = version
|
||||
if self.configs.is_half == True:
|
||||
self.vocoder = self.vocoder.half().to(self.configs.device)
|
||||
else:
|
||||
self.vocoder = self.vocoder.to(self.configs.device)
|
||||
|
||||
def init_sr_model(self):
|
||||
if self.sr_model is not None:
|
||||
return
|
||||
try:
|
||||
self.sr_model: AP_BWE = AP_BWE(self.configs.device, DictToAttrRecursive)
|
||||
self.sr_model_not_exist = False
|
||||
except FileNotFoundError:
|
||||
print(i18n("你没有下载超分模型的参数,因此不进行超分。如想超分请先参照教程把文件下载好"))
|
||||
self.sr_model_not_exist = True
|
||||
|
||||
def init_sv_model(self):
|
||||
if self.sv_model is not None:
|
||||
return
|
||||
self.sv_model = SV(self.configs.device, self.configs.is_half)
|
||||
80
GPT_SoVITS/inference/pipeline.py
Normal file
80
GPT_SoVITS/inference/pipeline.py
Normal file
@ -0,0 +1,80 @@
|
||||
"""Canonical stateful TTS pipeline assembled from inference mixins."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Union
|
||||
|
||||
import torch
|
||||
|
||||
from GPT_SoVITS.runtime.portable import prepare_transformers_flash_attention
|
||||
|
||||
prepare_transformers_flash_attention()
|
||||
|
||||
from transformers import AutoModel, AutoTokenizer
|
||||
|
||||
from GPT_SoVITS.AR.models.t2s_inference import Text2SemanticInference
|
||||
from GPT_SoVITS.feature_extractor.cnhubert import CNHubert
|
||||
from GPT_SoVITS.inference.super_resolution import AP_BWE
|
||||
from GPT_SoVITS.module.models import SynthesizerTrn, SynthesizerTrnV3
|
||||
|
||||
from .batching import BatchingMixin
|
||||
from .config import TTSConfig
|
||||
from .model_runtime import ModelRuntimeMixin
|
||||
from .reference import ReferenceMixin
|
||||
from .synthesis import SynthesisMixin
|
||||
from .text_frontend import TextPreprocessor
|
||||
|
||||
|
||||
class TTS(ModelRuntimeMixin, ReferenceMixin, BatchingMixin, SynthesisMixin):
|
||||
def __init__(self, configs: Union[dict, str, TTSConfig]):
|
||||
if isinstance(configs, TTSConfig):
|
||||
self.configs = configs
|
||||
else:
|
||||
self.configs: TTSConfig = TTSConfig(configs)
|
||||
|
||||
self.t2s_model: Text2SemanticInference = None
|
||||
self.t2s_accel = None
|
||||
self.streaming_accel = None
|
||||
self.vits_model: Union[SynthesizerTrn, SynthesizerTrnV3] = None
|
||||
self.bert_tokenizer: AutoTokenizer = None
|
||||
self.bert_model: AutoModel = None
|
||||
self.cnhuhbert_model: CNHubert = None
|
||||
self.vocoder = None
|
||||
self.sr_model: AP_BWE = None
|
||||
self.sv_model = None
|
||||
self.sr_model_not_exist: bool = False
|
||||
|
||||
self.vocoder_configs: dict = {
|
||||
"sr": None,
|
||||
"T_ref": None,
|
||||
"T_chunk": None,
|
||||
"upsample_rate": None,
|
||||
"overlapped_len": None,
|
||||
}
|
||||
|
||||
self._init_models()
|
||||
|
||||
self.text_preprocessor: TextPreprocessor = TextPreprocessor(
|
||||
self.bert_model, self.bert_tokenizer, self.configs.device
|
||||
)
|
||||
|
||||
self.prompt_cache: dict = {
|
||||
"ref_audio_path": None,
|
||||
"prompt_semantic": None,
|
||||
"refer_spec": [],
|
||||
"prompt_text": None,
|
||||
"prompt_lang": None,
|
||||
"phones": None,
|
||||
"bert_features": None,
|
||||
"norm_text": None,
|
||||
"aux_ref_audio_paths": [],
|
||||
}
|
||||
|
||||
self.stop_flag: bool = False
|
||||
self.precision: torch.dtype = torch.float16 if self.configs.is_half else torch.float32
|
||||
|
||||
def stop(self):
|
||||
"""Stop the inference process."""
|
||||
self.stop_flag = True
|
||||
|
||||
TTS_Config = TTSConfig
|
||||
102
GPT_SoVITS/inference/reference.py
Normal file
102
GPT_SoVITS/inference/reference.py
Normal file
@ -0,0 +1,102 @@
|
||||
"""Reference audio, semantic, spectrogram, and speaker cache ownership."""
|
||||
|
||||
import os
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
import torchaudio
|
||||
|
||||
from GPT_SoVITS.inference.audio import load_audio_gpu, resample
|
||||
from GPT_SoVITS.module.mel_processing import spectrogram_torch
|
||||
from GPT_SoVITS.runtime.i18n import I18nAuto
|
||||
|
||||
language = os.environ.get("language", "Auto")
|
||||
i18n = I18nAuto(language=language)
|
||||
|
||||
|
||||
class ReferenceMixin:
|
||||
def set_ref_audio(self, ref_audio_path: str):
|
||||
"""
|
||||
To set the reference audio for the TTS model,
|
||||
including the prompt_semantic and refer_spepc.
|
||||
Args:
|
||||
ref_audio_path: str, the path of the reference audio.
|
||||
"""
|
||||
self._set_prompt_semantic(ref_audio_path)
|
||||
self._set_ref_spec(ref_audio_path)
|
||||
self._set_ref_audio_path(ref_audio_path)
|
||||
|
||||
def _set_ref_audio_path(self, ref_audio_path):
|
||||
self.prompt_cache["ref_audio_path"] = ref_audio_path
|
||||
|
||||
def _set_ref_spec(self, ref_audio_path):
|
||||
spec_audio = self._get_ref_spec(ref_audio_path)
|
||||
if self.prompt_cache["refer_spec"] in [[], None]:
|
||||
self.prompt_cache["refer_spec"] = [spec_audio]
|
||||
else:
|
||||
self.prompt_cache["refer_spec"][0] = spec_audio
|
||||
|
||||
def _get_ref_spec(self, ref_audio_path):
|
||||
raw_audio, raw_sr = torchaudio.load(ref_audio_path)
|
||||
raw_audio = raw_audio.to(self.configs.device).float()
|
||||
self.prompt_cache["raw_audio"] = raw_audio
|
||||
self.prompt_cache["raw_sr"] = raw_sr
|
||||
|
||||
if raw_sr != self.configs.sampling_rate:
|
||||
audio = raw_audio.to(self.configs.device)
|
||||
if audio.shape[0] == 2:
|
||||
audio = audio.mean(0).unsqueeze(0)
|
||||
audio = resample(audio, raw_sr, self.configs.sampling_rate, self.configs.device)
|
||||
else:
|
||||
audio = raw_audio.to(self.configs.device)
|
||||
if audio.shape[0] == 2:
|
||||
audio = audio.mean(0).unsqueeze(0)
|
||||
|
||||
maxx = audio.abs().max()
|
||||
if maxx > 1:
|
||||
audio /= min(2, maxx)
|
||||
spec = spectrogram_torch(
|
||||
audio,
|
||||
self.configs.filter_length,
|
||||
self.configs.sampling_rate,
|
||||
self.configs.hop_length,
|
||||
self.configs.win_length,
|
||||
center=False,
|
||||
)
|
||||
if self.configs.is_half:
|
||||
spec = spec.half()
|
||||
if self.is_v2pro == True:
|
||||
audio = resample(audio, self.configs.sampling_rate, 16000, self.configs.device)
|
||||
if self.configs.is_half:
|
||||
audio = audio.half()
|
||||
else:
|
||||
audio = None
|
||||
return spec, audio
|
||||
|
||||
def _set_prompt_semantic(self, ref_wav_path: str):
|
||||
zero_wav = np.zeros(
|
||||
int(self.configs.sampling_rate * 0.3),
|
||||
dtype=np.float16 if self.configs.is_half else np.float32,
|
||||
)
|
||||
with torch.no_grad():
|
||||
wav16k, sr = load_audio_gpu(
|
||||
ref_wav_path, 16000, self.configs.device, mono=True,
|
||||
dtype=torch.float32, match_librosa=True,
|
||||
)
|
||||
if wav16k.shape[-1] > 160000 or wav16k.shape[-1] < 48000:
|
||||
raise OSError(i18n("参考音频在3~10秒范围外,请更换!"))
|
||||
zero_wav_torch = torch.from_numpy(zero_wav)
|
||||
wav16k = wav16k.squeeze(0)
|
||||
zero_wav_torch = zero_wav_torch.to(self.configs.device)
|
||||
if self.configs.is_half:
|
||||
wav16k = wav16k.half()
|
||||
zero_wav_torch = zero_wav_torch.half()
|
||||
|
||||
wav16k = torch.cat([wav16k, zero_wav_torch])
|
||||
hubert_feature = self.cnhuhbert_model.model(wav16k.unsqueeze(0))["last_hidden_state"].transpose(
|
||||
1, 2
|
||||
) # .float()
|
||||
codes = self.vits_model.extract_latent(hubert_feature)
|
||||
|
||||
prompt_semantic = codes[0, 0].to(self.configs.device)
|
||||
self.prompt_cache["prompt_semantic"] = prompt_semantic
|
||||
86
GPT_SoVITS/inference/request.py
Normal file
86
GPT_SoVITS/inference/request.py
Normal file
@ -0,0 +1,86 @@
|
||||
"""Normalized options for direct pipeline synthesis calls."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import random
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, Mapping
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SynthesisRequest:
|
||||
text: str = ""
|
||||
text_lang: str = ""
|
||||
ref_audio_path: str = ""
|
||||
aux_ref_audio_paths: tuple[str, ...] = ()
|
||||
prompt_text: str = ""
|
||||
prompt_lang: str = ""
|
||||
top_k: int = 15
|
||||
top_p: float = 1.0
|
||||
temperature: float = 1.0
|
||||
text_split_method: str = "cut1"
|
||||
batch_size: int = 1
|
||||
batch_threshold: float = 0.75
|
||||
split_bucket: bool = True
|
||||
speed_factor: float = 1.0
|
||||
fragment_interval: float = 0.3
|
||||
seed: int = -1
|
||||
parallel_infer: bool = True
|
||||
use_cuda_graph: bool = True
|
||||
use_flash_attention: bool = True
|
||||
repetition_penalty: float = 1.35
|
||||
sample_steps: int = 32
|
||||
cfg_rate: float = 0.0
|
||||
super_sampling: bool = False
|
||||
return_fragment: bool = False
|
||||
streaming_mode: bool | int = False
|
||||
overlap_length: int = 2
|
||||
min_chunk_length: int = 16
|
||||
fixed_length_chunk: bool = False
|
||||
gpt_streaming: bool = False
|
||||
streaming_chunk_seconds: float = 2.0
|
||||
streaming_window_mode: str = "fixed"
|
||||
streaming_lookahead_seconds: float = 0.12
|
||||
streaming_overlap_seconds: float = 0.04
|
||||
gpt_streaming_lookahead_seconds: float = 0.5
|
||||
media_type: str = "wav"
|
||||
|
||||
@classmethod
|
||||
def from_mapping(cls, inputs: Mapping[str, Any], version: str) -> "SynthesisRequest":
|
||||
values = dict(inputs)
|
||||
values["aux_ref_audio_paths"] = tuple(values.get("aux_ref_audio_paths") or ())
|
||||
values["seed"] = -1 if values.get("seed", -1) in ("", None) else int(values.get("seed", -1))
|
||||
sample_steps = values.get("sample_steps")
|
||||
values["sample_steps"] = (4 if version == "v5turbo" else 32) if sample_steps is None else int(sample_steps)
|
||||
cfg_rate = values.get("cfg_rate")
|
||||
values["cfg_rate"] = (1.30 if version == "v5dev" else 0.0) if cfg_rate is None else float(cfg_rate)
|
||||
known = cls.__dataclass_fields__
|
||||
return cls(**{name: values[name] for name in known if name in values})
|
||||
|
||||
def as_dict(self) -> dict[str, Any]:
|
||||
values = dict(self.__dict__)
|
||||
values["aux_ref_audio_paths"] = list(self.aux_ref_audio_paths)
|
||||
return values
|
||||
|
||||
|
||||
def set_seed(seed: int) -> int:
|
||||
seed = int(seed)
|
||||
seed = seed if seed != -1 else random.randint(0, 2**32 - 1)
|
||||
print(f"Set seed to {seed}")
|
||||
os.environ["PYTHONHASHSEED"] = str(seed)
|
||||
random.seed(seed)
|
||||
np.random.seed(seed)
|
||||
torch.manual_seed(seed)
|
||||
try:
|
||||
if torch.cuda.is_available():
|
||||
torch.cuda.manual_seed(seed)
|
||||
torch.cuda.manual_seed_all(seed)
|
||||
torch.backends.cuda.matmul.allow_tf32 = False
|
||||
torch.backends.cudnn.allow_tf32 = False
|
||||
except Exception:
|
||||
pass
|
||||
return seed
|
||||
@ -2,8 +2,9 @@ import torch
|
||||
|
||||
from GPT_SoVITS.eres2net.ERes2NetV2 import ERes2NetV2
|
||||
from GPT_SoVITS.eres2net import kaldi as Kaldi
|
||||
from GPT_SoVITS.runtime.paths import SPEAKER_MODEL_PATH
|
||||
|
||||
sv_path = "GPT_SoVITS/pretrained_models/sv/pretrained_eres2netv2w24s4ep4.ckpt"
|
||||
sv_path = str(SPEAKER_MODEL_PATH)
|
||||
|
||||
|
||||
class SV:
|
||||
@ -3,13 +3,20 @@ import math
|
||||
import threading
|
||||
import time
|
||||
import torch
|
||||
from tools.acceleration import create_acceleration
|
||||
from GPT_SoVITS.Accel.factory import create_acceleration
|
||||
from GPT_SoVITS.module.models_v5 import (
|
||||
V5_MAX_TARGET_CHUNK_FRAMES,
|
||||
V5_REFERENCE_FRAMES,
|
||||
V5_ROLLING_TAIL_FRAMES,
|
||||
V5_TOTAL_CHUNK_FRAMES,
|
||||
V5_VERSIONS,
|
||||
)
|
||||
|
||||
|
||||
def validate_streaming_options(req, version, api_mode=False):
|
||||
if not req.get("gpt_streaming", False):
|
||||
return
|
||||
if version not in {"v2ProPlus", "v5turbo", "v5dev"}:
|
||||
if version not in ({"v2ProPlus"} | V5_VERSIONS):
|
||||
raise ValueError("gpt_streaming supports v2ProPlus, v5turbo and v5dev")
|
||||
mode = req.get("streaming_mode", False)
|
||||
if (api_mode and (type(mode) is not int or mode not in (2, 3))) or (not api_mode and mode not in (True, 2, 3)):
|
||||
@ -190,7 +197,7 @@ def v2_token_chunks(updates, chunk_length, mute_emb_sim_matrix=None, threshold=0
|
||||
|
||||
|
||||
def v5_reference(pipeline):
|
||||
from .TTS import resample, mel_fn_v4, norm_spec
|
||||
from .audio import resample, mel_fn_v4, norm_spec
|
||||
cache = pipeline.prompt_cache
|
||||
spec = cache["refer_spec"][0][0].to(pipeline.configs.device, dtype=pipeline.precision)
|
||||
prompt = cache["prompt_semantic"].reshape(1, 1, -1).to(pipeline.configs.device)
|
||||
@ -201,7 +208,7 @@ def v5_reference(pipeline):
|
||||
audio = resample(audio, cache["raw_sr"], 32000, pipeline.configs.device)
|
||||
mel = norm_spec(mel_fn_v4(audio)).to(pipeline.precision)
|
||||
limit = min(mel.shape[-1], features.shape[-1])
|
||||
count = min(500, limit)
|
||||
count = min(V5_REFERENCE_FRAMES, limit)
|
||||
return (cache["phones"], cache["bert_features"], prompt,
|
||||
spec, features[..., :limit][..., -count:], ge, mel[..., :limit][..., -count:])
|
||||
|
||||
@ -221,9 +228,9 @@ def stream_v5_windows(vq_model, vocoder, denorm_spec, device, token_updates, pho
|
||||
fade = fade_frames * 480
|
||||
left_frames = max(24, fade_frames)
|
||||
ref_features, ref_mel = reference[4], reference[6]
|
||||
count = min(500, ref_features.shape[-1], ref_mel.shape[-1])
|
||||
count = min(V5_REFERENCE_FRAMES, ref_features.shape[-1], ref_mel.shape[-1])
|
||||
ref_features, ref_mel = ref_features[..., -count:], ref_mel[..., -count:]
|
||||
if count + core + future > 1000:
|
||||
if count + core + future > V5_TOTAL_CHUNK_FRAMES:
|
||||
raise ValueError("Reference plus streaming window exceeds the V5 1000-frame context")
|
||||
# The AR sampler uses the global CUDA RNG. CFM must not advance that RNG
|
||||
# while AR is still decoding on its owner thread.
|
||||
@ -234,7 +241,7 @@ def stream_v5_windows(vq_model, vocoder, denorm_spec, device, token_updates, pho
|
||||
feature_history = ref_features[..., :0]
|
||||
pending = None
|
||||
cursor = previous_tokens = 0
|
||||
schedule = StreamingWindowSchedule(core, min(1000-count, 640)) if hybrid else None
|
||||
schedule = StreamingWindowSchedule(core, min(V5_TOTAL_CHUNK_FRAMES-count, V5_MAX_TARGET_CHUNK_FRAMES)) if hybrid else None
|
||||
for tokens, finished in token_updates:
|
||||
if stop.is_set():
|
||||
return
|
||||
@ -265,7 +272,7 @@ def stream_v5_windows(vq_model, vocoder, denorm_spec, device, token_updates, pho
|
||||
if cursor == 0:
|
||||
prompt, features = ref_mel, ref_features
|
||||
else:
|
||||
tail = min(32, count, history.shape[-1])
|
||||
tail = min(V5_ROLLING_TAIL_FRAMES, count, history.shape[-1])
|
||||
prefix = count - tail
|
||||
prompt = torch.cat((ref_mel[..., :prefix], history[..., -tail:]), -1)
|
||||
tail_features = feature_history[..., -tail:] if hybrid else target[..., cursor-tail:cursor]
|
||||
@ -292,8 +299,8 @@ def stream_v5_windows(vq_model, vocoder, denorm_spec, device, token_updates, pho
|
||||
else:
|
||||
emitted = torch.cat((prefix_audio, current))
|
||||
pending = None
|
||||
history = torch.cat((history, accepted), -1)[..., -max(left_frames, 32):]
|
||||
feature_history = torch.cat((feature_history, target[..., cursor:end]), -1)[..., -max(left_frames, 32):]
|
||||
history = torch.cat((history, accepted), -1)[..., -max(left_frames, V5_ROLLING_TAIL_FRAMES):]
|
||||
feature_history = torch.cat((feature_history, target[..., cursor:end]), -1)[..., -max(left_frames, V5_ROLLING_TAIL_FRAMES):]
|
||||
units = end-cursor
|
||||
cursor = end
|
||||
if stop.is_set():
|
||||
53
GPT_SoVITS/inference/super_resolution.py
Normal file
53
GPT_SoVITS/inference/super_resolution.py
Normal file
@ -0,0 +1,53 @@
|
||||
"""AP-BWE adapter used for inference-time bandwidth extension."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import torch
|
||||
import torchaudio.functional as aF
|
||||
|
||||
from GPT_SoVITS.runtime.paths import AP_BWE_DIR, resolve_ap_bwe_checkpoint
|
||||
from GPT_SoVITS.vendor.ap_bwe.audio_ops import amp_pha_istft, amp_pha_stft
|
||||
from GPT_SoVITS.vendor.ap_bwe.models.model import APNet_BWE_Model
|
||||
|
||||
|
||||
AP_BWE_main_dir_path = str(AP_BWE_DIR)
|
||||
|
||||
|
||||
class AP_BWE:
|
||||
def __init__(self, device, DictToAttrRecursive, checkpoint_file=None):
|
||||
checkpoint_path = resolve_ap_bwe_checkpoint(checkpoint_file)
|
||||
if not checkpoint_path.is_file():
|
||||
raise FileNotFoundError(checkpoint_path)
|
||||
config_path = Path(checkpoint_path).parent / "config.json"
|
||||
with config_path.open(encoding="utf-8") as file:
|
||||
json_config = json.load(file)
|
||||
h = DictToAttrRecursive(json_config)
|
||||
model = APNet_BWE_Model(h).to(device)
|
||||
state_dict = torch.load(checkpoint_path, map_location="cpu", weights_only=False)
|
||||
model.load_state_dict(state_dict["generator"])
|
||||
model.eval()
|
||||
self.device = device
|
||||
self.model = model
|
||||
self.h = h
|
||||
|
||||
def to(self, *args, **kwargs):
|
||||
self.model.to(*args, **kwargs)
|
||||
self.device = self.model.conv_pre_mag.weight.device
|
||||
return self
|
||||
|
||||
def __call__(self, audio, orig_sampling_rate):
|
||||
with torch.no_grad():
|
||||
audio = aF.resample(audio, orig_freq=orig_sampling_rate, new_freq=self.h.hr_sampling_rate)
|
||||
amp_nb, pha_nb, _ = amp_pha_stft(audio, self.h.n_fft, self.h.hop_size, self.h.win_size)
|
||||
amp_wb_g, pha_wb_g, _ = self.model(amp_nb, pha_nb)
|
||||
audio_hr_g = amp_pha_istft(
|
||||
amp_wb_g,
|
||||
pha_wb_g,
|
||||
self.h.n_fft,
|
||||
self.h.hop_size,
|
||||
self.h.win_size,
|
||||
)
|
||||
return audio_hr_g.squeeze().cpu().numpy(), self.h.hr_sampling_rate
|
||||
File diff suppressed because it is too large
Load Diff
@ -15,9 +15,9 @@ from typing import Dict, List, Tuple
|
||||
from text.cleaner import clean_text
|
||||
from text import cleaned_text_to_sequence
|
||||
from transformers import AutoModel, AutoTokenizer
|
||||
from TTS_infer_pack.text_segmentation_method import split_big_text, splits, get_method as get_seg_method
|
||||
from .segmentation import split_big_text, splits, get_method as get_seg_method
|
||||
|
||||
from tools.i18n.i18n import I18nAuto
|
||||
from GPT_SoVITS.runtime.i18n import I18nAuto
|
||||
|
||||
language = os.environ.get("language", "Auto")
|
||||
i18n = I18nAuto(language=language)
|
||||
@ -97,7 +97,7 @@ class TextPreprocessor:
|
||||
# 解决输入目标文本的空行导致报错的问题
|
||||
if len(text.strip()) == 0:
|
||||
continue
|
||||
if not re.sub("\W+", "", text):
|
||||
if not re.sub(r"\W+", "", text):
|
||||
# 检测一下,如果是纯符号,就跳过。
|
||||
continue
|
||||
if text[-1] not in splits:
|
||||
1
GPT_SoVITS/runtime/__init__.py
Normal file
1
GPT_SoVITS/runtime/__init__.py
Normal file
@ -0,0 +1 @@
|
||||
"""Runtime paths, portable environment setup, and localization support."""
|
||||
5
GPT_SoVITS/runtime/i18n/__init__.py
Normal file
5
GPT_SoVITS/runtime/i18n/__init__.py
Normal file
@ -0,0 +1,5 @@
|
||||
"""Localization helpers for inference logs."""
|
||||
|
||||
from .i18n import I18N_JSON_DIR, I18nAuto, load_language_list
|
||||
|
||||
__all__ = ["I18N_JSON_DIR", "I18nAuto", "load_language_list"]
|
||||
30
GPT_SoVITS/runtime/i18n/i18n.py
Normal file
30
GPT_SoVITS/runtime/i18n/i18n.py
Normal file
@ -0,0 +1,30 @@
|
||||
"""Inference log localization."""
|
||||
|
||||
import json
|
||||
import locale
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
I18N_JSON_DIR = Path(__file__).resolve().parent / "locale"
|
||||
|
||||
|
||||
def load_language_list(language):
|
||||
with open(I18N_JSON_DIR / f"{language}.json", "r", encoding="utf-8") as file:
|
||||
return json.load(file)
|
||||
|
||||
|
||||
class I18nAuto:
|
||||
def __init__(self, language=None):
|
||||
if language in ["Auto", None]:
|
||||
language = locale.getdefaultlocale()[0]
|
||||
# getlocale cannot identify the system language when it returns (None, None).
|
||||
if not (I18N_JSON_DIR / f"{language}.json").exists():
|
||||
language = "en_US"
|
||||
self.language = language
|
||||
self.language_map = load_language_list(language)
|
||||
|
||||
def __call__(self, key):
|
||||
return self.language_map.get(key, key)
|
||||
|
||||
def __repr__(self):
|
||||
return "Use Language: " + self.language
|
||||
22
GPT_SoVITS/runtime/i18n/locale/en_US.json
Normal file
22
GPT_SoVITS/runtime/i18n/locale/en_US.json
Normal file
@ -0,0 +1,22 @@
|
||||
{
|
||||
"你没有下载超分模型的参数,因此不进行超分。如想超分请先参照教程把文件下载好": "Super-Resolution Model Not Found. Please follow the tutorial to download the model file if you want to use it.",
|
||||
"分桶处理模式已关闭": "Bucket Processing Mode Disabled",
|
||||
"分桶处理模式已开启": "Bucket Processing Mode Enabled",
|
||||
"切分文本": "Segment Text",
|
||||
"前端处理后的文本(每句):": "Processed text from the frontend (per sentence):",
|
||||
"参考音频在3~10秒范围外,请更换!": "Reference audio is outside the 3-10 second range, please choose another one!",
|
||||
"合成音频": "Synthesize Audio",
|
||||
"实际输入的参考文本:": "Actual Input Reference Text:",
|
||||
"实际输入的目标文本(切句后):": "Actual Input Target Text (after sentence segmentation):",
|
||||
"实际输入的目标文本:": "Actual Input Target Text:",
|
||||
"并行合成中": "Parallel Synthesis in Progress",
|
||||
"并行推理模式已开启": "Parallel Inference Mode Enabled",
|
||||
"当开启并行推理模式时,SoVits V3/4模型不支持分桶处理,已自动关闭分桶处理": "When parallel inference mode is enabled, SoVITS V3/4 models do not support bucket processing; bucket processing has been automatically disabled.",
|
||||
"提取文本Bert特征": "Extract Text BERT Features",
|
||||
"语速调节不支持分桶处理,已自动关闭分桶处理": "Speech Rate Adjustment does not support Bucket Processing, Bucket Processing Disabled automatically",
|
||||
"请输入有效文本": "Please enter valid text.",
|
||||
"路径不存在,使用默认配置": "Paths Not Found, Using Default Config",
|
||||
"音频文件不存在,跳过:": "Audio File Not Found, Skipping: ",
|
||||
"音频超采样": "Audio Upsampling",
|
||||
"预测语义Token": "Predict Semantic Token"
|
||||
}
|
||||
22
GPT_SoVITS/runtime/i18n/locale/es_ES.json
Normal file
22
GPT_SoVITS/runtime/i18n/locale/es_ES.json
Normal file
@ -0,0 +1,22 @@
|
||||
{
|
||||
"你没有下载超分模型的参数,因此不进行超分。如想超分请先参照教程把文件下载好": "No has descargado los parámetros del modelo de superresolución, por lo que no se realizará la superresolución. Si deseas habilitarla, sigue el tutorial y descarga los archivos necesarios",
|
||||
"分桶处理模式已关闭": "Modo de procesamiento por lotes deshabilitado",
|
||||
"分桶处理模式已开启": "Modo de procesamiento por lotes habilitado",
|
||||
"切分文本": "Segmentar texto",
|
||||
"前端处理后的文本(每句):": "Texto después del procesamiento previo (por frase):",
|
||||
"参考音频在3~10秒范围外,请更换!": "El audio de referencia está fuera del rango de 3 a 10 segundos, ¡por favor cámbielo!",
|
||||
"合成音频": "Sintetizar Audio",
|
||||
"实际输入的参考文本:": "Texto de referencia realmente ingresado:",
|
||||
"实际输入的目标文本(切句后):": "Texto objetivo realmente ingresado (después de dividir en frases):",
|
||||
"实际输入的目标文本:": "Texto objetivo realmente ingresado:",
|
||||
"并行合成中": "Síntesis en paralelo en curso",
|
||||
"并行推理模式已开启": "Modo de inferencia paralela habilitado",
|
||||
"当开启并行推理模式时,SoVits V3/4模型不支持分桶处理,已自动关闭分桶处理": "Al activar el modo de inferencia paralela, los modelos SoVITS V3/4 no admiten el procesamiento por lotes, por lo que este ha sido desactivado automáticamente.",
|
||||
"提取文本Bert特征": "Extraer características de texto con BERT",
|
||||
"语速调节不支持分桶处理,已自动关闭分桶处理": "El ajuste de velocidad de voz no es compatible con el procesamiento por lotes, se ha deshabilitado automáticamente",
|
||||
"请输入有效文本": "Por favor, introduzca un texto válido",
|
||||
"路径不存在,使用默认配置": "Ruta no encontrada, usando configuración predeterminada",
|
||||
"音频文件不存在,跳过:": "Archivo de audio no encontrado, omitiendo: ",
|
||||
"音频超采样": "Muestreo superior del audio",
|
||||
"预测语义Token": "Predecir token semántico"
|
||||
}
|
||||
22
GPT_SoVITS/runtime/i18n/locale/fr_FR.json
Normal file
22
GPT_SoVITS/runtime/i18n/locale/fr_FR.json
Normal file
@ -0,0 +1,22 @@
|
||||
{
|
||||
"你没有下载超分模型的参数,因此不进行超分。如想超分请先参照教程把文件下载好": "Vous n'avez pas téléchargé les paramètres du modèle d'upscaling, donc l'upscaling ne sera pas effectué. Veuillez suivre le tutoriel pour télécharger les fichiers nécessaires",
|
||||
"分桶处理模式已关闭": "Mode de traitement par regroupement désactivé",
|
||||
"分桶处理模式已开启": "Mode de traitement par regroupement activé",
|
||||
"切分文本": "Segmenter le texte",
|
||||
"前端处理后的文本(每句):": "Texte après traitement frontal (par phrase):",
|
||||
"参考音频在3~10秒范围外,请更换!": "Veuillez remplacer l'audio de référence si sa durée est en dehors de la plage de 3 à 10 secondes!",
|
||||
"合成音频": "Synthétiser l'audio",
|
||||
"实际输入的参考文本:": "Texte de référence réellement saisi:",
|
||||
"实际输入的目标文本(切句后):": "Texte cible réellement saisi (après découpage):",
|
||||
"实际输入的目标文本:": "Texte cible réellement saisi:",
|
||||
"并行合成中": "Synthèse parallèle en cours",
|
||||
"并行推理模式已开启": "Mode d’inférence parallèle activé",
|
||||
"当开启并行推理模式时,SoVits V3/4模型不支持分桶处理,已自动关闭分桶处理": "Lorsque le mode d'inférence parallèle est activé, les modèles SoVITS V3/4 ne prennent pas en charge le traitement par lots, qui a donc été désactivé automatiquement.",
|
||||
"提取文本Bert特征": "Extraire les caractéristiques du texte avec BERT",
|
||||
"语速调节不支持分桶处理,已自动关闭分桶处理": "Le réglage de la vitesse vocale ne prend pas en charge le regroupement des données, désactivation automatique",
|
||||
"请输入有效文本": "Veuillez entrer un texte valide",
|
||||
"路径不存在,使用默认配置": "Chemin introuvable, utilisation de la configuration par défaut",
|
||||
"音频文件不存在,跳过:": "Fichier audio introuvable, passage : ",
|
||||
"音频超采样": "Suréchantillonnage audio",
|
||||
"预测语义Token": "Prédire le jeton sémantique"
|
||||
}
|
||||
22
GPT_SoVITS/runtime/i18n/locale/it_IT.json
Normal file
22
GPT_SoVITS/runtime/i18n/locale/it_IT.json
Normal file
@ -0,0 +1,22 @@
|
||||
{
|
||||
"你没有下载超分模型的参数,因此不进行超分。如想超分请先参照教程把文件下载好": "Non hai scaricato i parametri del modello di super-risoluzione, quindi l'upscaling non verrà eseguito. Segui il tutorial per scaricare i file necessari.",
|
||||
"分桶处理模式已关闭": "Modalità di elaborazione per bucket disabilitata",
|
||||
"分桶处理模式已开启": "Modalità di elaborazione per bucket abilitata",
|
||||
"切分文本": "Segmenta il testo",
|
||||
"前端处理后的文本(每句):": "Testo elaborato dal front-end (per frase):",
|
||||
"参考音频在3~10秒范围外,请更换!": "L'audio di riferimento è al di fuori dell'intervallo di 3-10 secondi. Si prega di cambiarlo!",
|
||||
"合成音频": "Sintesi audio",
|
||||
"实际输入的参考文本:": "Testo di riferimento effettivamente inserito:",
|
||||
"实际输入的目标文本(切句后):": "Testo di destinazione effettivamente inserito (dopo il taglio delle frasi):",
|
||||
"实际输入的目标文本:": "Testo di destinazione effettivamente inserito:",
|
||||
"并行合成中": "Sintesi parallela in corso",
|
||||
"并行推理模式已开启": "Modalità di inferenza parallela abilitata",
|
||||
"当开启并行推理模式时,SoVits V3/4模型不支持分桶处理,已自动关闭分桶处理": "Quando la modalità di inferenza parallela è attiva, i modelli SoVITS V3/4 non supportano l'elaborazione suddivisa in gruppi e questa è stata automaticamente disattivata.",
|
||||
"提取文本Bert特征": "Estrai caratteristiche Bert dal testo",
|
||||
"语速调节不支持分桶处理,已自动关闭分桶处理": "Il controllo della velocità del discorso non supporta l'elaborazione per bucket, l'elaborazione per bucket è stata disabilitata automaticamente",
|
||||
"请输入有效文本": "Inserisci un testo valido",
|
||||
"路径不存在,使用默认配置": "Percorso non trovato, utilizzo della configurazione predefinita",
|
||||
"音频文件不存在,跳过:": "File audio non trovato, salto: ",
|
||||
"音频超采样": "Upsampling audio",
|
||||
"预测语义Token": "Predici token semantico"
|
||||
}
|
||||
22
GPT_SoVITS/runtime/i18n/locale/ja_JP.json
Normal file
22
GPT_SoVITS/runtime/i18n/locale/ja_JP.json
Normal file
@ -0,0 +1,22 @@
|
||||
{
|
||||
"你没有下载超分模型的参数,因此不进行超分。如想超分请先参照教程把文件下载好": "超解像モデルのパラメータをダウンロードしていないため、超解像は行われません。超解像を行いたい場合は、まずチュートリアルを参照してファイルをダウンロードしてください",
|
||||
"分桶处理模式已关闭": "バケット処理モードを無効化",
|
||||
"分桶处理模式已开启": "バケット処理モードを有効化",
|
||||
"切分文本": "テキストをセグメント",
|
||||
"前端处理后的文本(每句):": "フロントエンド処理後のテキスト(文ごと):",
|
||||
"参考音频在3~10秒范围外,请更换!": "参照音声が3~10秒の範囲外です。別の音声に変更してください!",
|
||||
"合成音频": "音声を合成する",
|
||||
"实际输入的参考文本:": "実際に入力された参照テキスト:",
|
||||
"实际输入的目标文本(切句后):": "実際に入力された目標テキスト(文分割後):",
|
||||
"实际输入的目标文本:": "実際に入力された目標テキスト:",
|
||||
"并行合成中": "並列合成処理中",
|
||||
"并行推理模式已开启": "並列推論モードを有効化",
|
||||
"当开启并行推理模式时,SoVits V3/4模型不支持分桶处理,已自动关闭分桶处理": "並列推論モードが有効な場合、SoVITS V3/4モデルはバケット処理をサポートしないため、自動的に無効になっています。",
|
||||
"提取文本Bert特征": "テキストBERT特徴を抽出",
|
||||
"语速调节不支持分桶处理,已自动关闭分桶处理": "音声調整はバケット処理をサポートしていないため、自動的にバケット処理を無効化",
|
||||
"请输入有效文本": "有効なテキストを入力してください",
|
||||
"路径不存在,使用默认配置": "パスが見つからないため、デフォルト設定を使用",
|
||||
"音频文件不存在,跳过:": "音声ファイルが見つかりません。スキップします:",
|
||||
"音频超采样": "音声アップサンプリング",
|
||||
"预测语义Token": "意味的トークンを予測する"
|
||||
}
|
||||
22
GPT_SoVITS/runtime/i18n/locale/ko_KR.json
Normal file
22
GPT_SoVITS/runtime/i18n/locale/ko_KR.json
Normal file
@ -0,0 +1,22 @@
|
||||
{
|
||||
"你没有下载超分模型的参数,因此不进行超分。如想超分请先参照教程把文件下载好": "슈퍼 레졸루션 모델의 파라미터를 다운로드하지 않았으므로 슈퍼 레졸루션을 수행하지 않습니다. 사용하려면 먼저 튜토리얼을 참고하여 파일을 다운로드하세요",
|
||||
"分桶处理模式已关闭": "버킷 처리 모드 비활성화됨",
|
||||
"分桶处理模式已开启": "버킷 처리 모드 활성화됨",
|
||||
"切分文本": "텍스트 분할",
|
||||
"前端处理后的文本(每句):": "프론트엔드 처리 후 텍스트(문장별):",
|
||||
"参考音频在3~10秒范围外,请更换!": "참고 오디오가 3~10초 범위를 벗어났습니다. 다른 것으로 바꾸십시오!",
|
||||
"合成音频": "오디오 생성",
|
||||
"实际输入的参考文本:": "실제 입력된 참고 텍스트:",
|
||||
"实际输入的目标文本(切句后):": "실제 입력된 목표 텍스트(문장 분리 후):",
|
||||
"实际输入的目标文本:": "실제 입력된 목표 텍스트:",
|
||||
"并行合成中": "병렬 오디오 생성 중",
|
||||
"并行推理模式已开启": "병렬 추론 모드 활성화됨",
|
||||
"当开启并行推理模式时,SoVits V3/4模型不支持分桶处理,已自动关闭分桶处理": "병렬 추론 모드가 활성화된 경우, SoVITS V3/4 모델은 버킷 처리를 지원하지 않으며, 자동으로 비활성화됩니다.",
|
||||
"提取文本Bert特征": "텍스트 BERT 특징 추출",
|
||||
"语速调节不支持分桶处理,已自动关闭分桶处理": "음속 조절은 버킷 처리를 지원하지 않아 버킷 처리 자동 비활성화됨",
|
||||
"请输入有效文本": "유효한 텍스트를 입력하세요",
|
||||
"路径不存在,使用默认配置": "경로가 존재하지 않음, 기본 설정 사용",
|
||||
"音频文件不存在,跳过:": "오디오 파일이 존재하지 않음, 건너뜀: ",
|
||||
"音频超采样": "오디오 업샘플링",
|
||||
"预测语义Token": "의미 기반 토큰 예측"
|
||||
}
|
||||
22
GPT_SoVITS/runtime/i18n/locale/pt_BR.json
Normal file
22
GPT_SoVITS/runtime/i18n/locale/pt_BR.json
Normal file
@ -0,0 +1,22 @@
|
||||
{
|
||||
"你没有下载超分模型的参数,因此不进行超分。如想超分请先参照教程把文件下载好": "Os parâmetros do modelo de super-resolução não foram baixados, então a super-resolução não será realizada. Para utilizá-la, siga o tutorial e baixe os arquivos necessários.",
|
||||
"分桶处理模式已关闭": "Modo de Processamento em Balde Desativado",
|
||||
"分桶处理模式已开启": "Modo de Processamento em Balde Ativado",
|
||||
"切分文本": "Segmentar Texto",
|
||||
"前端处理后的文本(每句):": "Texto após processamento front-end (por frase):",
|
||||
"参考音频在3~10秒范围外,请更换!": "O áudio de referência está fora do intervalo de 3 a 10 segundos. Por favor, substitua!",
|
||||
"合成音频": "Sintetizar áudio",
|
||||
"实际输入的参考文本:": "Texto de referência realmente inserido:",
|
||||
"实际输入的目标文本(切句后):": "Texto alvo realmente inserido (após divisão de frases):",
|
||||
"实际输入的目标文本:": "Texto alvo realmente inserido:",
|
||||
"并行合成中": "Síntese em paralelo em andamento",
|
||||
"并行推理模式已开启": "Modo de Inferência Paralela Ativado",
|
||||
"当开启并行推理模式时,SoVits V3/4模型不支持分桶处理,已自动关闭分桶处理": "Quando o modo de inferência paralela está ativado, os modelos SoVITS V3/4 não suportam processamento por lotes e esta funcionalidade foi automaticamente desativada.",
|
||||
"提取文本Bert特征": "Extrair Características BERT do Texto",
|
||||
"语速调节不支持分桶处理,已自动关闭分桶处理": "Ajuste de Velocidade de Fala não suporta Processamento em Balde, Processamento em Balde Desativado Automaticamente",
|
||||
"请输入有效文本": "Por favor, insira um texto válido",
|
||||
"路径不存在,使用默认配置": "Caminhos Não Encontrados, Usando Configuração Padrão",
|
||||
"音频文件不存在,跳过:": "Arquivo de áudio não encontrado, pulando: ",
|
||||
"音频超采样": "Superamostragem de áudio",
|
||||
"预测语义Token": "Prever token semântico"
|
||||
}
|
||||
22
GPT_SoVITS/runtime/i18n/locale/ru_RU.json
Normal file
22
GPT_SoVITS/runtime/i18n/locale/ru_RU.json
Normal file
@ -0,0 +1,22 @@
|
||||
{
|
||||
"你没有下载超分模型的参数,因此不进行超分。如想超分请先参照教程把文件下载好": "Параметры модели супер-разрешения не загружены, поэтому супер-разрешение не будет выполняться. Чтобы использовать его, сначала загрузите необходимые файлы, следуя руководству.",
|
||||
"分桶处理模式已关闭": "Режим обработки пакетов отключен",
|
||||
"分桶处理模式已开启": "Режим обработки пакетов включен",
|
||||
"切分文本": "Сегментировать текст",
|
||||
"前端处理后的文本(每句):": "Текст после предварительной обработки (каждое предложение):",
|
||||
"参考音频在3~10秒范围外,请更换!": "Референтное аудио вне диапазона 3~10 секунд, пожалуйста, замените!",
|
||||
"合成音频": "Синтезировать аудио",
|
||||
"实际输入的参考文本:": "Фактически введенный референсный текст:",
|
||||
"实际输入的目标文本(切句后):": "Фактически введенный целевой текст (после разбиения на предложения):",
|
||||
"实际输入的目标文本:": "Фактически введенный целевой текст:",
|
||||
"并行合成中": "Синтез в параллельном режиме",
|
||||
"并行推理模式已开启": "Режим параллельного вывода включен",
|
||||
"当开启并行推理模式时,SoVits V3/4模型不支持分桶处理,已自动关闭分桶处理": "При включенном режиме параллельного вывода модель SoVits V3/4 не поддерживает обработку по бакетам, эта функция была автоматически отключена.",
|
||||
"提取文本Bert特征": "Извлечь текстовые признаки BERT",
|
||||
"语速调节不支持分桶处理,已自动关闭分桶处理": "Регулировка скорости речи не поддерживает обработку пакетов, обработка пакетов отключена автоматически",
|
||||
"请输入有效文本": "Введите действительный текст",
|
||||
"路径不存在,使用默认配置": "Путь не найден, используется конфигурация по умолчанию",
|
||||
"音频文件不存在,跳过:": "Файл аудио не найден, пропускается: ",
|
||||
"音频超采样": "Апсэмплирование аудио",
|
||||
"预测语义Token": "Предсказать семантический токен"
|
||||
}
|
||||
22
GPT_SoVITS/runtime/i18n/locale/tr_TR.json
Normal file
22
GPT_SoVITS/runtime/i18n/locale/tr_TR.json
Normal file
@ -0,0 +1,22 @@
|
||||
{
|
||||
"你没有下载超分模型的参数,因此不进行超分。如想超分请先参照教程把文件下载好": "Süper çözünürlük model parametrelerini indirmediniz, bu yüzden süper çözünürlük yapılmaz. Süper çözünürlük yapmak için önce kılavuzu takip ederek dosyaları indirin.",
|
||||
"分桶处理模式已关闭": "Kovaya İşleme Modu Kapalı",
|
||||
"分桶处理模式已开启": "Kovaya İşleme Modu Etkin",
|
||||
"切分文本": "Metni Bölümle",
|
||||
"前端处理后的文本(每句):": "Ön işleme tabi tutulan metin (her cümle):",
|
||||
"参考音频在3~10秒范围外,请更换!": "Referans ses dosyası 3~10 saniye aralığının dışında, lütfen değiştirin!",
|
||||
"合成音频": "Ses Sentezleme",
|
||||
"实际输入的参考文本:": "Gerçekten girilen referans metin:",
|
||||
"实际输入的目标文本(切句后):": "Gerçekten girilen hedef metin (cümleler kesildikten sonra):",
|
||||
"实际输入的目标文本:": "Gerçekten girilen hedef metin:",
|
||||
"并行合成中": "Paralel Sentezleme Yapılıyor",
|
||||
"并行推理模式已开启": "Paralel Çıkarım Modu Etkin",
|
||||
"当开启并行推理模式时,SoVits V3/4模型不支持分桶处理,已自动关闭分桶处理": "Paralel çıkarım modu etkinleştirildiğinde, SoVITS V3/4 modelleri bölme işlemeyi desteklemez ve bu işlem otomatik olarak devre dışı bırakılır.",
|
||||
"提取文本Bert特征": "Metin BERT Özelliklerini Çıkar",
|
||||
"语速调节不支持分桶处理,已自动关闭分桶处理": "Konuşma Hızı Ayarlaması Kovaya İşlemeyi Desteklemediği İçin Kovaya İşleme Otomatik Olarak Kapatılmıştır",
|
||||
"请输入有效文本": "Geçerli metin girin",
|
||||
"路径不存在,使用默认配置": "Yol Bulunamadı, Varsayılan Yapılandırma Kullanılıyor",
|
||||
"音频文件不存在,跳过:": "Ses dosyası bulunamadı, atlanıyor: ",
|
||||
"音频超采样": "Ses Üst-örnekleme",
|
||||
"预测语义Token": "Anlamsal Token Tahmini"
|
||||
}
|
||||
22
GPT_SoVITS/runtime/i18n/locale/zh_CN.json
Normal file
22
GPT_SoVITS/runtime/i18n/locale/zh_CN.json
Normal file
@ -0,0 +1,22 @@
|
||||
{
|
||||
"你没有下载超分模型的参数,因此不进行超分。如想超分请先参照教程把文件下载好": "你没有下载超分模型的参数,因此不进行超分。如想超分请先参照教程把文件下载好",
|
||||
"分桶处理模式已关闭": "分桶处理模式已关闭",
|
||||
"分桶处理模式已开启": "分桶处理模式已开启",
|
||||
"切分文本": "切分文本",
|
||||
"前端处理后的文本(每句):": "前端处理后的文本(每句):",
|
||||
"参考音频在3~10秒范围外,请更换!": "参考音频在3~10秒范围外,请更换!",
|
||||
"合成音频": "合成音频",
|
||||
"实际输入的参考文本:": "实际输入的参考文本:",
|
||||
"实际输入的目标文本(切句后):": "实际输入的目标文本(切句后):",
|
||||
"实际输入的目标文本:": "实际输入的目标文本:",
|
||||
"并行合成中": "并行合成中",
|
||||
"并行推理模式已开启": "并行推理模式已开启",
|
||||
"当开启并行推理模式时,SoVits V3/4模型不支持分桶处理,已自动关闭分桶处理": "当开启并行推理模式时,SoVits V3/4模型不支持分桶处理,已自动关闭分桶处理",
|
||||
"提取文本Bert特征": "提取文本Bert特征",
|
||||
"语速调节不支持分桶处理,已自动关闭分桶处理": "语速调节不支持分桶处理,已自动关闭分桶处理",
|
||||
"请输入有效文本": "请输入有效文本",
|
||||
"路径不存在,使用默认配置": "路径不存在,使用默认配置",
|
||||
"音频文件不存在,跳过:": "音频文件不存在,跳过:",
|
||||
"音频超采样": "音频超采样",
|
||||
"预测语义Token": "预测语义Token"
|
||||
}
|
||||
22
GPT_SoVITS/runtime/i18n/locale/zh_HK.json
Normal file
22
GPT_SoVITS/runtime/i18n/locale/zh_HK.json
Normal file
@ -0,0 +1,22 @@
|
||||
{
|
||||
"你没有下载超分模型的参数,因此不进行超分。如想超分请先参照教程把文件下载好": "你沒有下載超分模型的參數,因此不進行超分。如想超分請先參照教程把文件下載好",
|
||||
"分桶处理模式已关闭": "分桶處理模式已關閉",
|
||||
"分桶处理模式已开启": "分桶處理模式已開啟",
|
||||
"切分文本": "切分文本",
|
||||
"前端处理后的文本(每句):": "前端處理後的文本(每句):",
|
||||
"参考音频在3~10秒范围外,请更换!": "參考音頻在3~10秒範圍外,請更換!",
|
||||
"合成音频": "合成音訊",
|
||||
"实际输入的参考文本:": "實際輸入的參考文本:",
|
||||
"实际输入的目标文本(切句后):": "實際輸入的目標文本(切句後):",
|
||||
"实际输入的目标文本:": "實際輸入的目標文本:",
|
||||
"并行合成中": "平行合成中",
|
||||
"并行推理模式已开启": "並行推理模式已開啟",
|
||||
"当开启并行推理模式时,SoVits V3/4模型不支持分桶处理,已自动关闭分桶处理": "當啟用平行推論模式時,SoVITS V3/4 模型不支援分倉處理,已自動關閉分倉處理。",
|
||||
"提取文本Bert特征": "提取文本BERT特徵",
|
||||
"语速调节不支持分桶处理,已自动关闭分桶处理": "語速調節不支持分桶處理,已自動關閉分桶處理",
|
||||
"请输入有效文本": "請輸入有效文本",
|
||||
"路径不存在,使用默认配置": "路徑不存在,使用默認配置",
|
||||
"音频文件不存在,跳过:": "音頻檔案不存在,跳過:",
|
||||
"音频超采样": "音頻超取樣",
|
||||
"预测语义Token": "預測語意 Token"
|
||||
}
|
||||
22
GPT_SoVITS/runtime/i18n/locale/zh_SG.json
Normal file
22
GPT_SoVITS/runtime/i18n/locale/zh_SG.json
Normal file
@ -0,0 +1,22 @@
|
||||
{
|
||||
"你没有下载超分模型的参数,因此不进行超分。如想超分请先参照教程把文件下载好": "你沒有下載超分模型的參數,因此不進行超分。如想超分請先參照教程把文件下載好",
|
||||
"分桶处理模式已关闭": "分桶處理模式已關閉",
|
||||
"分桶处理模式已开启": "分桶處理模式已開啟",
|
||||
"切分文本": "切分文本",
|
||||
"前端处理后的文本(每句):": "前端處理後的文本(每句):",
|
||||
"参考音频在3~10秒范围外,请更换!": "參考音頻在3~10秒範圍外,請更換!",
|
||||
"合成音频": "合成音频",
|
||||
"实际输入的参考文本:": "實際輸入的參考文本:",
|
||||
"实际输入的目标文本(切句后):": "實際輸入的目標文本(切句後):",
|
||||
"实际输入的目标文本:": "實際輸入的目標文本:",
|
||||
"并行合成中": "并行合成中",
|
||||
"并行推理模式已开启": "並行推理模式已開啟",
|
||||
"当开启并行推理模式时,SoVits V3/4模型不支持分桶处理,已自动关闭分桶处理": "当启用并行推理模式时,SoVits V3/4 模型不支持分桶处理,已自动关闭分桶处理。",
|
||||
"提取文本Bert特征": "提取文本BERT特徵",
|
||||
"语速调节不支持分桶处理,已自动关闭分桶处理": "語速調節不支援分桶處理,已自動關閉分桶處理",
|
||||
"请输入有效文本": "請輸入有效文本",
|
||||
"路径不存在,使用默认配置": "路徑不存在,使用預設配置",
|
||||
"音频文件不存在,跳过:": "音频文件不存在,跳过:",
|
||||
"音频超采样": "音频超采样",
|
||||
"预测语义Token": "预测语义 Token"
|
||||
}
|
||||
22
GPT_SoVITS/runtime/i18n/locale/zh_TW.json
Normal file
22
GPT_SoVITS/runtime/i18n/locale/zh_TW.json
Normal file
@ -0,0 +1,22 @@
|
||||
{
|
||||
"你没有下载超分模型的参数,因此不进行超分。如想超分请先参照教程把文件下载好": "你沒有下載超分模型的參數,因此不進行超分。如想超分請先參照教程把文件下載好",
|
||||
"分桶处理模式已关闭": "分桶處理模式已關閉",
|
||||
"分桶处理模式已开启": "分桶處理模式已開啟",
|
||||
"切分文本": "切分文字",
|
||||
"前端处理后的文本(每句):": "前端處理後的文本(每句):",
|
||||
"参考音频在3~10秒范围外,请更换!": "參考音頻在3~10秒範圍外,請更換!",
|
||||
"合成音频": "合成音訊",
|
||||
"实际输入的参考文本:": "實際輸入的參考文本:",
|
||||
"实际输入的目标文本(切句后):": "實際輸入的目標文本(切句後):",
|
||||
"实际输入的目标文本:": "實際輸入的目標文本:",
|
||||
"并行合成中": "平行合成中",
|
||||
"并行推理模式已开启": "並行推理模式已開啟",
|
||||
"当开启并行推理模式时,SoVits V3/4模型不支持分桶处理,已自动关闭分桶处理": "啟用平行推論模式時,SoVITS V3/4 模型不支援分倉處理,已自動關閉該功能。",
|
||||
"提取文本Bert特征": "提取文字BERT特徵",
|
||||
"语速调节不支持分桶处理,已自动关闭分桶处理": "語速調節不支援分桶處理,已自動關閉分桶處理",
|
||||
"请输入有效文本": "請輸入有效文本",
|
||||
"路径不存在,使用默认配置": "路徑不存在,使用預設配置",
|
||||
"音频文件不存在,跳过:": "音訊檔案不存在,跳過:",
|
||||
"音频超采样": "音訊超取樣",
|
||||
"预测语义Token": "預測語意 Token"
|
||||
}
|
||||
65
GPT_SoVITS/runtime/paths.py
Normal file
65
GPT_SoVITS/runtime/paths.py
Normal file
@ -0,0 +1,65 @@
|
||||
"""Canonical filesystem locations used by the inference runtime."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
PACKAGE_ROOT = Path(__file__).resolve().parents[1]
|
||||
PROJECT_ROOT = PACKAGE_ROOT.parent
|
||||
RUNTIME_DIR = PROJECT_ROOT / "runtime"
|
||||
SITE_PACKAGES_DIR = RUNTIME_DIR / "Lib" / "site-packages"
|
||||
CACHE_DIR = PROJECT_ROOT / ".codex" / "runtime-cache"
|
||||
PRETRAINED_MODELS_DIR = PACKAGE_ROOT / "pretrained_models"
|
||||
|
||||
G2PW_MODEL_DIR = PACKAGE_ROOT / "text" / "G2PWModel"
|
||||
BERT_MODEL_DIR = PRETRAINED_MODELS_DIR / "chinese-roberta-wwm-ext-large"
|
||||
CNHUBERT_MODEL_DIR = PRETRAINED_MODELS_DIR / "chinese-hubert-base"
|
||||
BIGVGAN_VOCODER_DIR = PRETRAINED_MODELS_DIR / "models--nvidia--bigvgan_v2_24khz_100band_256x"
|
||||
SPEAKER_MODEL_PATH = PRETRAINED_MODELS_DIR / "sv" / "pretrained_eres2netv2w24s4ep4.ckpt"
|
||||
|
||||
AP_BWE_DIR = PACKAGE_ROOT / "vendor" / "ap_bwe"
|
||||
AP_BWE_CHECKPOINT_DIR = AP_BWE_DIR / "24kto48k"
|
||||
AP_BWE_CHECKPOINT_PATH = AP_BWE_CHECKPOINT_DIR / "g_24kto48k.zip"
|
||||
LEGACY_AP_BWE_CHECKPOINT_DIR = PROJECT_ROOT / "tools" / "AP_BWE_main" / "24kto48k"
|
||||
LEGACY_AP_BWE_CHECKPOINT_PATH = LEGACY_AP_BWE_CHECKPOINT_DIR / "g_24kto48k.zip"
|
||||
|
||||
|
||||
def package_path(*parts: str, project_root: str | Path = PROJECT_ROOT) -> Path:
|
||||
"""Build a path below the GPT_SoVITS package for an alternate project root."""
|
||||
|
||||
return Path(project_root) / "GPT_SoVITS" / Path(*parts)
|
||||
|
||||
|
||||
def pretrained_path(*parts: str, project_root: str | Path = PROJECT_ROOT) -> Path:
|
||||
"""Build a path below the pretrained-model directory."""
|
||||
|
||||
return package_path("pretrained_models", *parts, project_root=project_root)
|
||||
|
||||
|
||||
def cache_path(name: str, *, project_root: str | Path = PROJECT_ROOT, env_var: str | None = None) -> Path:
|
||||
"""Return a writable runtime-cache location, honoring an existing override."""
|
||||
|
||||
configured = os.environ.get(env_var, "").strip() if env_var else ""
|
||||
if configured:
|
||||
return Path(configured).expanduser()
|
||||
return Path(project_root) / ".codex" / "runtime-cache" / name
|
||||
|
||||
|
||||
def vocoder_checkpoint(version: str) -> Path:
|
||||
"""Return the local V3/V4/V5 vocoder checkpoint for a model version."""
|
||||
|
||||
return PRETRAINED_MODELS_DIR / f"gsv-{version}-pretrained" / "vocoder.pth"
|
||||
|
||||
|
||||
def resolve_ap_bwe_checkpoint(checkpoint: str | Path | None = None) -> Path:
|
||||
"""Resolve AP-BWE weights, preferring the vendored path over the legacy mount."""
|
||||
|
||||
if checkpoint is not None:
|
||||
return Path(checkpoint).expanduser()
|
||||
if AP_BWE_CHECKPOINT_PATH.is_file():
|
||||
return AP_BWE_CHECKPOINT_PATH
|
||||
if LEGACY_AP_BWE_CHECKPOINT_PATH.is_file():
|
||||
return LEGACY_AP_BWE_CHECKPOINT_PATH
|
||||
return AP_BWE_CHECKPOINT_PATH
|
||||
116
GPT_SoVITS/runtime/portable.py
Normal file
116
GPT_SoVITS/runtime/portable.py
Normal file
@ -0,0 +1,116 @@
|
||||
"""Runtime initialization for the bundled GPT-SoVITS environment."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
from importlib import import_module
|
||||
from importlib.machinery import ModuleSpec
|
||||
from importlib.metadata import version
|
||||
from pathlib import Path
|
||||
from threading import RLock
|
||||
from types import ModuleType
|
||||
|
||||
from .paths import CACHE_DIR, PACKAGE_ROOT, PROJECT_ROOT, RUNTIME_DIR, SITE_PACKAGES_DIR
|
||||
|
||||
|
||||
# Backward-compatible name used by the former tools.portable_runtime module.
|
||||
SITE_PACKAGES = SITE_PACKAGES_DIR
|
||||
|
||||
|
||||
def _resolve_binary(bundled_name: str, system_name: str) -> str:
|
||||
bundled = RUNTIME_DIR / bundled_name
|
||||
if bundled.exists():
|
||||
return str(bundled)
|
||||
return shutil.which(system_name) or system_name
|
||||
|
||||
|
||||
FFMPEG_EXE = _resolve_binary("ffmpeg.exe", "ffmpeg")
|
||||
FFPROBE_EXE = _resolve_binary("ffprobe.exe", "ffprobe")
|
||||
_DLL_HANDLES = []
|
||||
_DLL_READY = False
|
||||
_ACTIVE = False
|
||||
_FLASH_IMPORT_READY = False
|
||||
_FLASH_IMPORT_LOCK = RLock()
|
||||
|
||||
|
||||
def _prepare_dlls() -> None:
|
||||
global _DLL_READY
|
||||
if _DLL_READY or os.name != "nt":
|
||||
return
|
||||
package_directories = [SITE_PACKAGES_DIR, Path(sys.prefix) / "Lib" / "site-packages"]
|
||||
directories = [
|
||||
RUNTIME_DIR,
|
||||
*(packages / "torch" / "lib" for packages in package_directories),
|
||||
PACKAGE_ROOT / "Accel" / "vendor" / "cuda" / "bin",
|
||||
*(directory for packages in package_directories for directory in sorted((packages / "nvidia").glob("*/bin"))),
|
||||
]
|
||||
for directory in dict.fromkeys(directories):
|
||||
if directory.is_dir():
|
||||
_DLL_HANDLES.append(os.add_dll_directory(str(directory)))
|
||||
# cuDNN dynamically loads its component DLLs through the process PATH.
|
||||
os.environ["PATH"] = str(directory) + os.pathsep + os.environ.get("PATH", "")
|
||||
_DLL_READY = True
|
||||
|
||||
|
||||
def _lazy_apply_rotary_emb(*args, **kwargs):
|
||||
return import_module("flash_attn.layers.rotary").apply_rotary_emb(*args, **kwargs)
|
||||
|
||||
|
||||
def prepare_transformers_flash_attention() -> None:
|
||||
global _FLASH_IMPORT_READY
|
||||
with _FLASH_IMPORT_LOCK:
|
||||
if _FLASH_IMPORT_READY:
|
||||
return
|
||||
_prepare_dlls()
|
||||
import_utils = import_module("transformers.utils.import_utils")
|
||||
if import_utils.is_flash_attn_2_available():
|
||||
from GPT_SoVITS.Accel.capabilities import _flash_attention_module
|
||||
|
||||
if _flash_attention_module() is None:
|
||||
import_utils.is_flash_attn_2_available = lambda: False
|
||||
import_module("transformers.utils").is_flash_attn_2_available = import_utils.is_flash_attn_2_available
|
||||
if os.name != "nt" or version("transformers") != "4.51.3":
|
||||
_FLASH_IMPORT_READY = True
|
||||
return
|
||||
# Transformers 4.51.3 imports Triton rotary even for BERT/HuBERT, which never use it.
|
||||
rotary_name = "flash_attn.layers.rotary"
|
||||
previous_rotary = sys.modules.get(rotary_name)
|
||||
if previous_rotary is None:
|
||||
rotary = ModuleType(rotary_name)
|
||||
rotary.__spec__ = ModuleSpec(rotary_name, loader=None)
|
||||
rotary.apply_rotary_emb = _lazy_apply_rotary_emb
|
||||
sys.modules[rotary_name] = rotary
|
||||
try:
|
||||
import_module("transformers.modeling_flash_attention_utils")
|
||||
finally:
|
||||
if previous_rotary is None:
|
||||
sys.modules.pop(rotary_name, None)
|
||||
_FLASH_IMPORT_READY = True
|
||||
|
||||
|
||||
def activate(*, change_cwd: bool = False) -> None:
|
||||
global _ACTIVE
|
||||
if change_cwd:
|
||||
os.chdir(PROJECT_ROOT)
|
||||
if not _ACTIVE:
|
||||
sys.path.insert(0, str(PROJECT_ROOT))
|
||||
sys.path.insert(0, str(PACKAGE_ROOT))
|
||||
if RUNTIME_DIR.is_dir():
|
||||
os.environ["PATH"] = str(RUNTIME_DIR) + os.pathsep + os.environ.get("PATH", "")
|
||||
os.environ.setdefault("G2PW", "0")
|
||||
nltk_data = RUNTIME_DIR / "nltk_data"
|
||||
if not nltk_data.is_dir():
|
||||
nltk_data = CACHE_DIR / "nltk_data"
|
||||
if nltk_data.is_dir():
|
||||
os.environ.setdefault("NLTK_DATA", str(nltk_data))
|
||||
try:
|
||||
import _distutils_hack
|
||||
|
||||
_distutils_hack.add_shim()
|
||||
except ImportError:
|
||||
pass
|
||||
_prepare_dlls()
|
||||
_ACTIVE = True
|
||||
prepare_transformers_flash_attention()
|
||||
19
GPT_SoVITS/service/__init__.py
Normal file
19
GPT_SoVITS/service/__init__.py
Normal file
@ -0,0 +1,19 @@
|
||||
"""HTTP service components for the GPT-SoVITS inference application.
|
||||
|
||||
The package keeps imports lazy so importing a focused helper, such as an audio
|
||||
packer, does not construct the application or inference configuration.
|
||||
"""
|
||||
|
||||
__all__ = ["APP", "TTS_Request", "create_app"]
|
||||
|
||||
|
||||
def __getattr__(name):
|
||||
if name == "TTS_Request":
|
||||
from .schemas import TTS_Request
|
||||
|
||||
return TTS_Request
|
||||
if name in {"APP", "create_app"}:
|
||||
from .app import APP, create_app
|
||||
|
||||
return {"APP": APP, "create_app": create_app}[name]
|
||||
raise AttributeError(name)
|
||||
73
GPT_SoVITS/service/app.py
Normal file
73
GPT_SoVITS/service/app.py
Normal file
@ -0,0 +1,73 @@
|
||||
"""FastAPI application assembly and inference process lifecycle."""
|
||||
|
||||
import asyncio
|
||||
import sys
|
||||
from contextlib import asynccontextmanager
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any
|
||||
|
||||
from fastapi import FastAPI
|
||||
|
||||
if "tools.portable_runtime" in sys.modules:
|
||||
from tools.portable_runtime import activate as activate_portable_runtime
|
||||
else:
|
||||
try:
|
||||
from GPT_SoVITS.runtime.portable import activate as activate_portable_runtime
|
||||
except ImportError:
|
||||
from tools.portable_runtime import activate as activate_portable_runtime
|
||||
|
||||
activate_portable_runtime(change_cwd=True)
|
||||
|
||||
from GPT_SoVITS.inference import TTS, TTS_Config
|
||||
|
||||
from .concurrency import run_in_threadpool_shielded
|
||||
|
||||
|
||||
DEFAULT_CONFIG_PATH = "GPT_SoVITS/configs/tts_infer.yaml"
|
||||
|
||||
|
||||
@dataclass
|
||||
class ServiceState:
|
||||
"""Mutable state shared by routes in this single-worker application."""
|
||||
|
||||
tts_config: Any
|
||||
tts_pipeline: Any = None
|
||||
pipeline_lock: asyncio.Lock = field(default_factory=asyncio.Lock)
|
||||
|
||||
|
||||
# Configuration construction remains import-time compatible; model construction
|
||||
# remains deferred until the ASGI lifespan starts.
|
||||
state = ServiceState(tts_config=TTS_Config(DEFAULT_CONFIG_PATH))
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(_app):
|
||||
if state.tts_pipeline is None:
|
||||
print(state.tts_config)
|
||||
state.tts_pipeline = await run_in_threadpool_shielded(TTS, state.tts_config)
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
pipeline = state.tts_pipeline
|
||||
for name in ("streaming_accel", "t2s_accel"):
|
||||
accelerator = getattr(pipeline, name, None)
|
||||
if accelerator is not None:
|
||||
await run_in_threadpool_shielded(accelerator.close)
|
||||
state.tts_pipeline = None
|
||||
|
||||
|
||||
def create_app() -> FastAPI:
|
||||
"""Assemble the stable inference-only HTTP surface."""
|
||||
|
||||
application = FastAPI(
|
||||
title="GPT-SoVITS 推理 API",
|
||||
description="使用已加载的 GPT/SoVITS 模型合成语音。模型和参考音频路径均由服务端读取;热切换仅作用于当前进程。",
|
||||
lifespan=lifespan,
|
||||
)
|
||||
from .routes import register_routes
|
||||
|
||||
register_routes(application)
|
||||
return application
|
||||
|
||||
|
||||
APP = create_app()
|
||||
107
GPT_SoVITS/service/audio_response.py
Normal file
107
GPT_SoVITS/service/audio_response.py
Normal file
@ -0,0 +1,107 @@
|
||||
"""Audio container encoding for HTTP responses."""
|
||||
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import wave
|
||||
from io import BytesIO
|
||||
|
||||
import numpy as np
|
||||
import soundfile as sf
|
||||
|
||||
if "tools.portable_runtime" in sys.modules:
|
||||
from tools.portable_runtime import FFMPEG_EXE
|
||||
else:
|
||||
try:
|
||||
from GPT_SoVITS.runtime.portable import FFMPEG_EXE
|
||||
except ImportError:
|
||||
from tools.portable_runtime import FFMPEG_EXE
|
||||
|
||||
|
||||
def pack_ogg(io_buffer: BytesIO, data: np.ndarray, rate: int):
|
||||
"""Write OGG in a large-stack thread to avoid libsndfile stack overflow."""
|
||||
|
||||
def handle_pack_ogg():
|
||||
with sf.SoundFile(io_buffer, mode="w", samplerate=rate, channels=1, format="ogg") as audio_file:
|
||||
audio_file.write(data)
|
||||
|
||||
stack_size = 4096 * 4096
|
||||
try:
|
||||
threading.stack_size(stack_size)
|
||||
pack_ogg_thread = threading.Thread(target=handle_pack_ogg)
|
||||
pack_ogg_thread.start()
|
||||
pack_ogg_thread.join()
|
||||
except RuntimeError as error:
|
||||
print("RuntimeError: {}".format(error))
|
||||
print("Changing the thread stack size is unsupported.")
|
||||
except ValueError as error:
|
||||
print("ValueError: {}".format(error))
|
||||
print("The specified stack size is invalid.")
|
||||
return io_buffer
|
||||
|
||||
|
||||
def pack_raw(io_buffer: BytesIO, data: np.ndarray, rate: int):
|
||||
io_buffer.write(data.tobytes())
|
||||
return io_buffer
|
||||
|
||||
|
||||
def pack_wav(io_buffer: BytesIO, data: np.ndarray, rate: int):
|
||||
io_buffer = BytesIO()
|
||||
sf.write(io_buffer, data, rate, format="wav")
|
||||
return io_buffer
|
||||
|
||||
|
||||
def pack_aac(io_buffer: BytesIO, data: np.ndarray, rate: int):
|
||||
process = subprocess.Popen(
|
||||
[
|
||||
str(FFMPEG_EXE),
|
||||
"-f",
|
||||
"s16le",
|
||||
"-ar",
|
||||
str(rate),
|
||||
"-ac",
|
||||
"1",
|
||||
"-i",
|
||||
"pipe:0",
|
||||
"-c:a",
|
||||
"aac",
|
||||
"-b:a",
|
||||
"192k",
|
||||
"-vn",
|
||||
"-f",
|
||||
"adts",
|
||||
"pipe:1",
|
||||
],
|
||||
stdin=subprocess.PIPE,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
)
|
||||
out, _ = process.communicate(input=data.tobytes())
|
||||
io_buffer.write(out)
|
||||
return io_buffer
|
||||
|
||||
|
||||
def pack_audio(io_buffer: BytesIO, data: np.ndarray, rate: int, media_type: str):
|
||||
if media_type == "ogg":
|
||||
io_buffer = pack_ogg(io_buffer, data, rate)
|
||||
elif media_type == "aac":
|
||||
io_buffer = pack_aac(io_buffer, data, rate)
|
||||
elif media_type == "wav":
|
||||
io_buffer = pack_wav(io_buffer, data, rate)
|
||||
else:
|
||||
io_buffer = pack_raw(io_buffer, data, rate)
|
||||
io_buffer.seek(0)
|
||||
return io_buffer
|
||||
|
||||
|
||||
def wave_header_chunk(frame_input=b"", channels=1, sample_width=2, sample_rate=32000):
|
||||
"""Create the single RIFF header prepended to a streaming WAV response."""
|
||||
|
||||
wav_buffer = BytesIO()
|
||||
with wave.open(wav_buffer, "wb") as output:
|
||||
output.setnchannels(channels)
|
||||
output.setsampwidth(sample_width)
|
||||
output.setframerate(sample_rate)
|
||||
output.writeframes(frame_input)
|
||||
wav_buffer.seek(0)
|
||||
return wav_buffer.read()
|
||||
35
GPT_SoVITS/service/cli.py
Normal file
35
GPT_SoVITS/service/cli.py
Normal file
@ -0,0 +1,35 @@
|
||||
"""Command-line entry point for the single-worker inference server."""
|
||||
|
||||
import argparse
|
||||
|
||||
import uvicorn
|
||||
|
||||
from . import app as service_app
|
||||
|
||||
|
||||
def build_parser() -> argparse.ArgumentParser:
|
||||
parser = argparse.ArgumentParser(description="GPT-SoVITS inference API")
|
||||
parser.add_argument(
|
||||
"-c",
|
||||
"--tts_config",
|
||||
default=service_app.DEFAULT_CONFIG_PATH,
|
||||
help="TTS inference configuration",
|
||||
)
|
||||
parser.add_argument("-a", "--bind_addr", default="127.0.0.1", help="default: 127.0.0.1")
|
||||
parser.add_argument("-p", "--port", type=int, default=9880, help="default: 9880")
|
||||
return parser
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
args = build_parser().parse_args(argv)
|
||||
service_app.state.tts_config = service_app.TTS_Config(
|
||||
args.tts_config or service_app.DEFAULT_CONFIG_PATH
|
||||
)
|
||||
host = args.bind_addr
|
||||
if host == "None":
|
||||
host = None
|
||||
uvicorn.run(app=service_app.APP, host=host, port=args.port, workers=1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
56
GPT_SoVITS/service/concurrency.py
Normal file
56
GPT_SoVITS/service/concurrency.py
Normal file
@ -0,0 +1,56 @@
|
||||
"""Cancellation-safe threadpool and generator iteration primitives."""
|
||||
|
||||
import asyncio
|
||||
|
||||
import anyio
|
||||
from starlette.concurrency import run_in_threadpool
|
||||
|
||||
|
||||
STREAM_END = object()
|
||||
|
||||
|
||||
async def await_shielded(awaitable):
|
||||
"""Finish an in-flight worker operation before propagating cancellation."""
|
||||
|
||||
task = asyncio.ensure_future(awaitable)
|
||||
try:
|
||||
return await asyncio.shield(task)
|
||||
except asyncio.CancelledError:
|
||||
# AnyIO cancellation is level-triggered. Shield the worker until it
|
||||
# finishes, then let the original cancellation unwind the stream.
|
||||
with anyio.CancelScope(shield=True):
|
||||
try:
|
||||
await task
|
||||
except BaseException:
|
||||
pass
|
||||
raise
|
||||
|
||||
|
||||
async def run_in_threadpool_shielded(function, *args):
|
||||
return await await_shielded(run_in_threadpool(function, *args))
|
||||
|
||||
|
||||
def next_or_end(iterator):
|
||||
try:
|
||||
return next(iterator)
|
||||
except StopIteration:
|
||||
return STREAM_END
|
||||
|
||||
|
||||
async def next_tts_chunk(iterator, skip_empty=False):
|
||||
"""Advance a synchronous TTS iterator without blocking the event loop."""
|
||||
|
||||
while True:
|
||||
item = await run_in_threadpool_shielded(next_or_end, iterator)
|
||||
if item is STREAM_END or not skip_empty or item[1].size > 0:
|
||||
return item
|
||||
|
||||
|
||||
async def close_generator(generator):
|
||||
"""Close a synchronous generator with cancellation-safe worker affinity."""
|
||||
|
||||
if generator is None:
|
||||
return
|
||||
close = getattr(generator, "close", None)
|
||||
if callable(close):
|
||||
await run_in_threadpool_shielded(close)
|
||||
345
GPT_SoVITS/service/routes.py
Normal file
345
GPT_SoVITS/service/routes.py
Normal file
@ -0,0 +1,345 @@
|
||||
"""Inference and model-control HTTP routes."""
|
||||
|
||||
import asyncio
|
||||
from io import BytesIO
|
||||
from typing import Annotated, Optional, Union
|
||||
|
||||
from fastapi import FastAPI, Query, Request, Response
|
||||
from fastapi.responses import JSONResponse, StreamingResponse
|
||||
from starlette.background import BackgroundTask
|
||||
|
||||
from GPT_SoVITS.inference.segmentation import get_method_names as get_cut_method_names
|
||||
from GPT_SoVITS.inference.streaming import validate_streaming_options
|
||||
|
||||
from . import app as service_app
|
||||
from .audio_response import pack_audio, wave_header_chunk
|
||||
from .concurrency import (
|
||||
STREAM_END,
|
||||
await_shielded,
|
||||
close_generator,
|
||||
next_tts_chunk,
|
||||
run_in_threadpool_shielded,
|
||||
)
|
||||
from .schemas import TTS_Request, get_request_dict, raw_get_streaming_mode, request_model_to_dict
|
||||
|
||||
|
||||
cut_method_names = get_cut_method_names()
|
||||
|
||||
|
||||
def check_params(req: dict):
|
||||
text: str = req.get("text", "")
|
||||
text_lang: str = req.get("text_lang", "")
|
||||
ref_audio_path: str = req.get("ref_audio_path", "")
|
||||
media_type: str = req.get("media_type", "wav")
|
||||
prompt_lang: str = req.get("prompt_lang", "")
|
||||
text_split_method: str = req.get("text_split_method", "cut5")
|
||||
config = service_app.state.tts_config
|
||||
|
||||
if ref_audio_path in [None, ""]:
|
||||
return JSONResponse(status_code=400, content={"message": "ref_audio_path is required"})
|
||||
if text in [None, ""]:
|
||||
return JSONResponse(status_code=400, content={"message": "text is required"})
|
||||
if text_lang in [None, ""]:
|
||||
return JSONResponse(status_code=400, content={"message": "text_lang is required"})
|
||||
if text_lang.lower() not in config.languages:
|
||||
return JSONResponse(
|
||||
status_code=400,
|
||||
content={"message": f"text_lang: {text_lang} is not supported in version {config.version}"},
|
||||
)
|
||||
if prompt_lang in [None, ""]:
|
||||
return JSONResponse(status_code=400, content={"message": "prompt_lang is required"})
|
||||
if prompt_lang.lower() not in config.languages:
|
||||
return JSONResponse(
|
||||
status_code=400,
|
||||
content={"message": f"prompt_lang: {prompt_lang} is not supported in version {config.version}"},
|
||||
)
|
||||
if media_type not in ["wav", "raw", "ogg", "aac"]:
|
||||
return JSONResponse(status_code=400, content={"message": f"media_type: {media_type} is not supported"})
|
||||
if text_split_method not in cut_method_names:
|
||||
return JSONResponse(
|
||||
status_code=400,
|
||||
content={"message": f"text_split_method:{text_split_method} is not supported"},
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
async def tts_handle(req: dict, raw_streaming_mode=None):
|
||||
"""Validate, serialize inference, and retain the lock through streaming."""
|
||||
|
||||
state = service_app.state
|
||||
await state.pipeline_lock.acquire()
|
||||
tts_generator = None
|
||||
response_owns_lock = False
|
||||
stream_cleanup_task = None
|
||||
|
||||
async def cleanup_stream():
|
||||
nonlocal stream_cleanup_task
|
||||
if stream_cleanup_task is None:
|
||||
|
||||
async def close_and_release():
|
||||
try:
|
||||
await close_generator(tts_generator)
|
||||
finally:
|
||||
state.pipeline_lock.release()
|
||||
|
||||
stream_cleanup_task = asyncio.create_task(close_and_release())
|
||||
await await_shielded(stream_cleanup_task)
|
||||
|
||||
try:
|
||||
check_result = check_params(req)
|
||||
if check_result is not None:
|
||||
return check_result
|
||||
|
||||
gpt_streaming = req.get("gpt_streaming", False)
|
||||
pipeline = state.tts_pipeline
|
||||
if gpt_streaming:
|
||||
try:
|
||||
validation_req = dict(req)
|
||||
if raw_streaming_mode is not None:
|
||||
validation_req["streaming_mode"] = raw_streaming_mode
|
||||
validate_streaming_options(
|
||||
validation_req,
|
||||
getattr(pipeline.configs, "version", state.tts_config.version),
|
||||
api_mode=True,
|
||||
)
|
||||
except (TypeError, ValueError) as error:
|
||||
return JSONResponse(status_code=400, content={"message": str(error)})
|
||||
|
||||
streaming_mode = req.get("streaming_mode", False)
|
||||
return_fragment = req.get("return_fragment", False)
|
||||
media_type = req.get("media_type", "wav")
|
||||
|
||||
if streaming_mode == 0:
|
||||
streaming_mode = False
|
||||
return_fragment = False
|
||||
fixed_length_chunk = False
|
||||
elif streaming_mode == 1:
|
||||
streaming_mode = False
|
||||
return_fragment = True
|
||||
fixed_length_chunk = False
|
||||
elif streaming_mode == 2:
|
||||
streaming_mode = True
|
||||
return_fragment = False
|
||||
fixed_length_chunk = False
|
||||
elif streaming_mode == 3:
|
||||
streaming_mode = True
|
||||
return_fragment = False
|
||||
fixed_length_chunk = True
|
||||
else:
|
||||
return JSONResponse(
|
||||
status_code=400,
|
||||
content={
|
||||
"message": "the value of streaming_mode must be 0, 1, 2, 3(int) or true/false(bool)"
|
||||
},
|
||||
)
|
||||
|
||||
req["streaming_mode"] = streaming_mode
|
||||
req["return_fragment"] = return_fragment
|
||||
req["fixed_length_chunk"] = fixed_length_chunk
|
||||
|
||||
streaming_mode = streaming_mode or return_fragment
|
||||
tts_generator = await run_in_threadpool_shielded(pipeline.run, req)
|
||||
|
||||
if streaming_mode:
|
||||
first_chunk = STREAM_END
|
||||
if gpt_streaming:
|
||||
first_chunk = await next_tts_chunk(tts_generator, skip_empty=True)
|
||||
if first_chunk is STREAM_END:
|
||||
return JSONResponse(
|
||||
status_code=400,
|
||||
content={"message": "tts failed", "Exception": "stream produced no PCM audio"},
|
||||
)
|
||||
|
||||
async def streaming_generator():
|
||||
nonlocal media_type
|
||||
first_audio = True
|
||||
item = first_chunk
|
||||
try:
|
||||
while True:
|
||||
if item is STREAM_END:
|
||||
item = await next_tts_chunk(tts_generator, skip_empty=gpt_streaming)
|
||||
if item is STREAM_END:
|
||||
break
|
||||
|
||||
sample_rate, chunk = item
|
||||
if first_audio and media_type == "wav":
|
||||
yield wave_header_chunk(sample_rate=sample_rate)
|
||||
media_type = "raw"
|
||||
first_audio = False
|
||||
packed = await run_in_threadpool_shielded(
|
||||
pack_audio, BytesIO(), chunk, sample_rate, media_type
|
||||
)
|
||||
yield packed.getvalue()
|
||||
item = STREAM_END
|
||||
finally:
|
||||
await cleanup_stream()
|
||||
|
||||
response = StreamingResponse(
|
||||
streaming_generator(),
|
||||
media_type=f"audio/{media_type}",
|
||||
background=BackgroundTask(cleanup_stream),
|
||||
)
|
||||
response_owns_lock = True
|
||||
return response
|
||||
|
||||
item = await next_tts_chunk(tts_generator)
|
||||
if item is STREAM_END:
|
||||
raise RuntimeError("TTS produced no audio")
|
||||
sample_rate, audio_data = item
|
||||
packed = await run_in_threadpool_shielded(pack_audio, BytesIO(), audio_data, sample_rate, media_type)
|
||||
return Response(packed.getvalue(), media_type=f"audio/{media_type}")
|
||||
except Exception as error:
|
||||
return JSONResponse(status_code=400, content={"message": "tts failed", "Exception": str(error)})
|
||||
finally:
|
||||
if not response_owns_lock:
|
||||
try:
|
||||
await close_generator(tts_generator)
|
||||
finally:
|
||||
state.pipeline_lock.release()
|
||||
|
||||
|
||||
async def tts_get_endpoint(
|
||||
request: Request,
|
||||
text: str = None,
|
||||
text_lang: str = None,
|
||||
ref_audio_path: str = None,
|
||||
aux_ref_audio_paths: Annotated[Optional[list[str]], Query()] = None,
|
||||
prompt_lang: str = None,
|
||||
prompt_text: str = "",
|
||||
top_k: int = 15,
|
||||
top_p: float = 1,
|
||||
temperature: float = 1,
|
||||
text_split_method: str = "cut5",
|
||||
batch_size: int = 1,
|
||||
batch_threshold: float = 0.75,
|
||||
split_bucket: bool = True,
|
||||
speed_factor: float = 1.0,
|
||||
fragment_interval: float = 0.3,
|
||||
seed: int = -1,
|
||||
media_type: str = "wav",
|
||||
parallel_infer: bool = True,
|
||||
use_cuda_graph: bool = True,
|
||||
repetition_penalty: float = 1.35,
|
||||
sample_steps: Optional[int] = None,
|
||||
cfg_rate: Optional[float] = None,
|
||||
super_sampling: bool = False,
|
||||
streaming_mode: Union[bool, int] = False,
|
||||
overlap_length: int = 2,
|
||||
min_chunk_length: int = 16,
|
||||
gpt_streaming: bool = False,
|
||||
streaming_chunk_seconds: float = 2.0,
|
||||
streaming_window_mode: str = "fixed",
|
||||
streaming_lookahead_seconds: float = 0.12,
|
||||
streaming_overlap_seconds: float = 0.04,
|
||||
gpt_streaming_lookahead_seconds: float = 0.5,
|
||||
use_flash_attention: bool = True,
|
||||
):
|
||||
"""使用查询参数合成语音,响应体为音频字节。参考音频路径由服务端读取。"""
|
||||
|
||||
req = get_request_dict(
|
||||
text=text,
|
||||
text_lang=text_lang,
|
||||
ref_audio_path=ref_audio_path,
|
||||
aux_ref_audio_paths=aux_ref_audio_paths,
|
||||
prompt_lang=prompt_lang,
|
||||
prompt_text=prompt_text,
|
||||
top_k=top_k,
|
||||
top_p=top_p,
|
||||
temperature=temperature,
|
||||
text_split_method=text_split_method,
|
||||
batch_size=batch_size,
|
||||
batch_threshold=batch_threshold,
|
||||
split_bucket=split_bucket,
|
||||
speed_factor=speed_factor,
|
||||
fragment_interval=fragment_interval,
|
||||
seed=seed,
|
||||
media_type=media_type,
|
||||
parallel_infer=parallel_infer,
|
||||
use_cuda_graph=use_cuda_graph,
|
||||
repetition_penalty=repetition_penalty,
|
||||
sample_steps=sample_steps,
|
||||
cfg_rate=cfg_rate,
|
||||
super_sampling=super_sampling,
|
||||
streaming_mode=streaming_mode,
|
||||
overlap_length=overlap_length,
|
||||
min_chunk_length=min_chunk_length,
|
||||
gpt_streaming=gpt_streaming,
|
||||
streaming_chunk_seconds=streaming_chunk_seconds,
|
||||
streaming_window_mode=streaming_window_mode,
|
||||
streaming_lookahead_seconds=streaming_lookahead_seconds,
|
||||
streaming_overlap_seconds=streaming_overlap_seconds,
|
||||
gpt_streaming_lookahead_seconds=gpt_streaming_lookahead_seconds,
|
||||
use_flash_attention=use_flash_attention,
|
||||
)
|
||||
return await tts_handle(req, raw_streaming_mode=raw_get_streaming_mode(request))
|
||||
|
||||
|
||||
async def tts_post_endpoint(request: TTS_Request, raw_request: Request):
|
||||
"""使用 JSON 参数合成语音,响应体为音频字节。字段与 GET /tts 对应。"""
|
||||
|
||||
req = request_model_to_dict(request)
|
||||
request_body = await raw_request.json()
|
||||
raw_streaming_mode = request_body.get("streaming_mode", request.streaming_mode)
|
||||
return await tts_handle(req, raw_streaming_mode=raw_streaming_mode)
|
||||
|
||||
|
||||
async def set_refer_aduio(refer_audio_path: str = None):
|
||||
"""预加载服务端参考音频。后续 /tts 仍须提供 ref_audio_path 和对应参考文本。"""
|
||||
|
||||
try:
|
||||
async with service_app.state.pipeline_lock:
|
||||
await run_in_threadpool_shielded(
|
||||
service_app.state.tts_pipeline.set_ref_audio, refer_audio_path
|
||||
)
|
||||
except Exception as error:
|
||||
return JSONResponse(
|
||||
status_code=400,
|
||||
content={"message": "set refer audio failed", "Exception": str(error)},
|
||||
)
|
||||
return JSONResponse(status_code=200, content={"message": "success"})
|
||||
|
||||
|
||||
async def set_gpt_weights(weights_path: str = None):
|
||||
"""加载匹配当前 SoVITS 版本的 GPT 权重;只影响当前进程。"""
|
||||
|
||||
try:
|
||||
if weights_path in ["", None]:
|
||||
return JSONResponse(status_code=400, content={"message": "gpt weight path is required"})
|
||||
async with service_app.state.pipeline_lock:
|
||||
await run_in_threadpool_shielded(
|
||||
service_app.state.tts_pipeline.init_t2s_weights, weights_path
|
||||
)
|
||||
except Exception as error:
|
||||
return JSONResponse(
|
||||
status_code=400,
|
||||
content={"message": "change gpt weight failed", "Exception": str(error)},
|
||||
)
|
||||
return JSONResponse(status_code=200, content={"message": "success"})
|
||||
|
||||
|
||||
async def set_sovits_weights(weights_path: str = None):
|
||||
"""加载 SoVITS 权重及对应版本。切换整套声音时,随后加载匹配 GPT 和参考音频。"""
|
||||
|
||||
try:
|
||||
if weights_path in ["", None]:
|
||||
return JSONResponse(status_code=400, content={"message": "sovits weight path is required"})
|
||||
async with service_app.state.pipeline_lock:
|
||||
await run_in_threadpool_shielded(
|
||||
service_app.state.tts_pipeline.init_vits_weights, weights_path
|
||||
)
|
||||
except Exception as error:
|
||||
return JSONResponse(
|
||||
status_code=400,
|
||||
content={"message": "change sovits weight failed", "Exception": str(error)},
|
||||
)
|
||||
return JSONResponse(status_code=200, content={"message": "success"})
|
||||
|
||||
|
||||
def register_routes(application: FastAPI) -> None:
|
||||
"""Attach the stable inference routes to an application instance."""
|
||||
|
||||
application.add_api_route("/tts", tts_get_endpoint, methods=["GET"])
|
||||
application.add_api_route("/tts", tts_post_endpoint, methods=["POST"])
|
||||
application.add_api_route("/set_refer_audio", set_refer_aduio, methods=["GET"])
|
||||
application.add_api_route("/set_gpt_weights", set_gpt_weights, methods=["GET"])
|
||||
application.add_api_route("/set_sovits_weights", set_sovits_weights, methods=["GET"])
|
||||
131
GPT_SoVITS/service/schemas.py
Normal file
131
GPT_SoVITS/service/schemas.py
Normal file
@ -0,0 +1,131 @@
|
||||
"""Public request schema and HTTP-to-pipeline normalization."""
|
||||
|
||||
from typing import Annotated, Optional, Union
|
||||
|
||||
from fastapi import Query, Request
|
||||
from pydantic import BaseModel
|
||||
|
||||
|
||||
class TTS_Request(BaseModel):
|
||||
text: str = None
|
||||
text_lang: str = None
|
||||
ref_audio_path: str = None
|
||||
aux_ref_audio_paths: list = None
|
||||
prompt_lang: str = None
|
||||
prompt_text: str = ""
|
||||
top_k: int = 15
|
||||
top_p: float = 1
|
||||
temperature: float = 1
|
||||
text_split_method: str = "cut5"
|
||||
batch_size: int = 1
|
||||
batch_threshold: float = 0.75
|
||||
split_bucket: bool = True
|
||||
speed_factor: float = 1.0
|
||||
fragment_interval: float = 0.3
|
||||
seed: int = -1
|
||||
media_type: str = "wav"
|
||||
streaming_mode: Union[bool, int] = False
|
||||
parallel_infer: bool = True
|
||||
use_cuda_graph: bool = True
|
||||
repetition_penalty: float = 1.35
|
||||
sample_steps: Optional[int] = None
|
||||
cfg_rate: Optional[float] = None
|
||||
super_sampling: bool = False
|
||||
overlap_length: int = 2
|
||||
min_chunk_length: int = 16
|
||||
gpt_streaming: bool = False
|
||||
streaming_chunk_seconds: float = 2.0
|
||||
streaming_window_mode: str = "fixed"
|
||||
streaming_lookahead_seconds: float = 0.12
|
||||
streaming_overlap_seconds: float = 0.04
|
||||
gpt_streaming_lookahead_seconds: float = 0.5
|
||||
use_flash_attention: bool = True
|
||||
|
||||
|
||||
def request_model_to_dict(request: TTS_Request) -> dict:
|
||||
"""Convert either supported Pydantic generation to a plain request dict."""
|
||||
|
||||
return request.model_dump() if hasattr(request, "model_dump") else request.dict()
|
||||
|
||||
|
||||
def get_request_dict(
|
||||
text: str = None,
|
||||
text_lang: str = None,
|
||||
ref_audio_path: str = None,
|
||||
aux_ref_audio_paths: Annotated[Optional[list[str]], Query()] = None,
|
||||
prompt_lang: str = None,
|
||||
prompt_text: str = "",
|
||||
top_k: int = 15,
|
||||
top_p: float = 1,
|
||||
temperature: float = 1,
|
||||
text_split_method: str = "cut5",
|
||||
batch_size: int = 1,
|
||||
batch_threshold: float = 0.75,
|
||||
split_bucket: bool = True,
|
||||
speed_factor: float = 1.0,
|
||||
fragment_interval: float = 0.3,
|
||||
seed: int = -1,
|
||||
media_type: str = "wav",
|
||||
parallel_infer: bool = True,
|
||||
use_cuda_graph: bool = True,
|
||||
repetition_penalty: float = 1.35,
|
||||
sample_steps: Optional[int] = None,
|
||||
cfg_rate: Optional[float] = None,
|
||||
super_sampling: bool = False,
|
||||
streaming_mode: Union[bool, int] = False,
|
||||
overlap_length: int = 2,
|
||||
min_chunk_length: int = 16,
|
||||
gpt_streaming: bool = False,
|
||||
streaming_chunk_seconds: float = 2.0,
|
||||
streaming_window_mode: str = "fixed",
|
||||
streaming_lookahead_seconds: float = 0.12,
|
||||
streaming_overlap_seconds: float = 0.04,
|
||||
gpt_streaming_lookahead_seconds: float = 0.5,
|
||||
use_flash_attention: bool = True,
|
||||
) -> dict:
|
||||
"""Build the internal request mapping while preserving GET coercions."""
|
||||
|
||||
return {
|
||||
"text": text,
|
||||
"text_lang": text_lang.lower() if text_lang else text_lang,
|
||||
"ref_audio_path": ref_audio_path,
|
||||
"aux_ref_audio_paths": aux_ref_audio_paths,
|
||||
"prompt_text": prompt_text,
|
||||
"prompt_lang": prompt_lang.lower() if prompt_lang else prompt_lang,
|
||||
"top_k": top_k,
|
||||
"top_p": top_p,
|
||||
"temperature": temperature,
|
||||
"text_split_method": text_split_method,
|
||||
"batch_size": int(batch_size),
|
||||
"batch_threshold": float(batch_threshold),
|
||||
"speed_factor": float(speed_factor),
|
||||
"split_bucket": split_bucket,
|
||||
"fragment_interval": fragment_interval,
|
||||
"seed": seed,
|
||||
"media_type": media_type,
|
||||
"streaming_mode": streaming_mode,
|
||||
"parallel_infer": parallel_infer,
|
||||
"use_cuda_graph": use_cuda_graph,
|
||||
"repetition_penalty": float(repetition_penalty),
|
||||
"sample_steps": None if sample_steps is None else int(sample_steps),
|
||||
"cfg_rate": None if cfg_rate is None else float(cfg_rate),
|
||||
"super_sampling": super_sampling,
|
||||
"overlap_length": int(overlap_length),
|
||||
"min_chunk_length": int(min_chunk_length),
|
||||
"gpt_streaming": gpt_streaming,
|
||||
"streaming_chunk_seconds": float(streaming_chunk_seconds),
|
||||
"streaming_window_mode": streaming_window_mode,
|
||||
"streaming_lookahead_seconds": float(streaming_lookahead_seconds),
|
||||
"streaming_overlap_seconds": float(streaming_overlap_seconds),
|
||||
"gpt_streaming_lookahead_seconds": float(gpt_streaming_lookahead_seconds),
|
||||
"use_flash_attention": use_flash_attention,
|
||||
}
|
||||
|
||||
|
||||
def raw_get_streaming_mode(request: Request):
|
||||
"""Retain the uncoerced mode needed by semantic-stream validation."""
|
||||
|
||||
raw_mode = request.query_params.get("streaming_mode")
|
||||
if raw_mode in {"2", "3"}:
|
||||
return int(raw_mode)
|
||||
return raw_mode
|
||||
@ -9,12 +9,17 @@ jieba.setLogLevel(logging.CRITICAL)
|
||||
|
||||
import fast_langdetect
|
||||
|
||||
from GPT_SoVITS.runtime.paths import cache_path, pretrained_path
|
||||
|
||||
|
||||
def _langdetect_config(project_root: Path):
|
||||
configured_cache = os.environ.get("GPT_SOVITS_LANGDETECT_CACHE", "").strip()
|
||||
cache_dir = Path(configured_cache).expanduser() if configured_cache else project_root / ".codex" / "runtime-cache" / "fast_langdetect"
|
||||
cache_dir = cache_path(
|
||||
"fast_langdetect",
|
||||
project_root=project_root,
|
||||
env_var="GPT_SOVITS_LANGDETECT_CACHE",
|
||||
)
|
||||
cache_dir.mkdir(parents=True, exist_ok=True)
|
||||
legacy_model = project_root / "GPT_SoVITS" / "pretrained_models" / "fast_langdetect" / "lid.176.bin"
|
||||
legacy_model = pretrained_path("fast_langdetect", "lid.176.bin", project_root=project_root)
|
||||
local_model = legacy_model if legacy_model.is_file() and not (cache_dir / "lid.176.bin").is_file() else None
|
||||
return fast_langdetect.infer.LangDetectConfig(
|
||||
cache_dir=str(cache_dir),
|
||||
|
||||
@ -5,6 +5,7 @@ import cn2an
|
||||
from pypinyin import lazy_pinyin, Style
|
||||
from pypinyin.contrib.tone_convert import to_finals_tone3, to_initials
|
||||
|
||||
from GPT_SoVITS.runtime.paths import BERT_MODEL_DIR, G2PW_MODEL_DIR
|
||||
from text.symbols import punctuation
|
||||
from text.tone_sandhi import ToneSandhi
|
||||
from text.zh_normalization.text_normlization import TextNormalizer
|
||||
@ -32,8 +33,8 @@ if is_g2pw:
|
||||
|
||||
parent_directory = os.path.dirname(current_file_path)
|
||||
g2pw = G2PWPinyin(
|
||||
model_dir="GPT_SoVITS/text/G2PWModel",
|
||||
model_source=os.environ.get("bert_path", "GPT_SoVITS/pretrained_models/chinese-roberta-wwm-ext-large"),
|
||||
model_dir=str(G2PW_MODEL_DIR),
|
||||
model_source=os.environ.get("bert_path", str(BERT_MODEL_DIR)),
|
||||
v_to_u=False,
|
||||
neutral_tone_with_five=True,
|
||||
)
|
||||
|
||||
@ -4,10 +4,9 @@ import os
|
||||
import hashlib
|
||||
import shutil
|
||||
|
||||
OPENJTALK_CACHE_DIR = os.path.join(
|
||||
os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))),
|
||||
".codex", "runtime-cache", "openjtalk",
|
||||
)
|
||||
from GPT_SoVITS.runtime.paths import cache_path
|
||||
|
||||
OPENJTALK_CACHE_DIR = str(cache_path("openjtalk"))
|
||||
if os.name == "nt" and not re.match(r"^[A-Za-z0-9_/\\:.\-]*$", OPENJTALK_CACHE_DIR):
|
||||
OPENJTALK_CACHE_DIR = os.path.relpath(OPENJTALK_CACHE_DIR)
|
||||
|
||||
|
||||
1
GPT_SoVITS/vendor/__init__.py
vendored
Normal file
1
GPT_SoVITS/vendor/__init__.py
vendored
Normal file
@ -0,0 +1 @@
|
||||
"""Vendored inference-only dependencies and their licenses."""
|
||||
29
GPT_SoVITS/vendor/ap_bwe/24kto48k/config.json
vendored
Normal file
29
GPT_SoVITS/vendor/ap_bwe/24kto48k/config.json
vendored
Normal file
@ -0,0 +1,29 @@
|
||||
{
|
||||
"num_gpus": 0,
|
||||
"batch_size": 16,
|
||||
"learning_rate": 0.0002,
|
||||
"adam_b1": 0.8,
|
||||
"adam_b2": 0.99,
|
||||
"lr_decay": 0.999,
|
||||
"seed": 1234,
|
||||
|
||||
"ConvNeXt_channels": 512,
|
||||
"ConvNeXt_layers": 8,
|
||||
|
||||
"segment_size": 8000,
|
||||
"n_fft": 1024,
|
||||
"hop_size": 80,
|
||||
"win_size": 320,
|
||||
|
||||
"hr_sampling_rate": 48000,
|
||||
"lr_sampling_rate": 24000,
|
||||
"subsampling_rate": 2,
|
||||
|
||||
"num_workers": 4,
|
||||
|
||||
"dist_config": {
|
||||
"dist_backend": "nccl",
|
||||
"dist_url": "tcp://localhost:54321",
|
||||
"world_size": 1
|
||||
}
|
||||
}
|
||||
21
GPT_SoVITS/vendor/ap_bwe/LICENSE
vendored
Normal file
21
GPT_SoVITS/vendor/ap_bwe/LICENSE
vendored
Normal file
@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2023 Ye-Xin Lu
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
1
GPT_SoVITS/vendor/ap_bwe/__init__.py
vendored
Normal file
1
GPT_SoVITS/vendor/ap_bwe/__init__.py
vendored
Normal file
@ -0,0 +1 @@
|
||||
"""Inference-only AP-BWE implementation."""
|
||||
29
GPT_SoVITS/vendor/ap_bwe/audio_ops.py
vendored
Normal file
29
GPT_SoVITS/vendor/ap_bwe/audio_ops.py
vendored
Normal file
@ -0,0 +1,29 @@
|
||||
"""STFT helpers required by the inference-time AP-BWE model."""
|
||||
|
||||
import torch
|
||||
|
||||
|
||||
def amp_pha_stft(audio, n_fft, hop_size, win_size, center=True):
|
||||
hann_window = torch.hann_window(win_size).to(audio.device)
|
||||
stft_spec = torch.stft(
|
||||
audio,
|
||||
n_fft,
|
||||
hop_length=hop_size,
|
||||
win_length=win_size,
|
||||
window=hann_window,
|
||||
center=center,
|
||||
pad_mode="reflect",
|
||||
normalized=False,
|
||||
return_complex=True,
|
||||
)
|
||||
log_amp = torch.log(torch.abs(stft_spec) + 1e-4)
|
||||
pha = torch.angle(stft_spec)
|
||||
com = torch.stack((torch.exp(log_amp) * torch.cos(pha), torch.exp(log_amp) * torch.sin(pha)), dim=-1)
|
||||
return log_amp, pha, com
|
||||
|
||||
|
||||
def amp_pha_istft(log_amp, pha, n_fft, hop_size, win_size, center=True):
|
||||
amp = torch.exp(log_amp)
|
||||
com = torch.complex(amp * torch.cos(pha), amp * torch.sin(pha))
|
||||
hann_window = torch.hann_window(win_size).to(com.device)
|
||||
return torch.istft(com, n_fft, hop_length=hop_size, win_length=win_size, window=hann_window, center=center)
|
||||
1
GPT_SoVITS/vendor/ap_bwe/models/__init__.py
vendored
Normal file
1
GPT_SoVITS/vendor/ap_bwe/models/__init__.py
vendored
Normal file
@ -0,0 +1 @@
|
||||
"""AP-BWE model definitions."""
|
||||
115
GPT_SoVITS/vendor/ap_bwe/models/model.py
vendored
Normal file
115
GPT_SoVITS/vendor/ap_bwe/models/model.py
vendored
Normal file
@ -0,0 +1,115 @@
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
|
||||
|
||||
def get_padding(kernel_size, dilation=1):
|
||||
return int((kernel_size * dilation - dilation) / 2)
|
||||
|
||||
|
||||
class ConvNeXtBlock(nn.Module):
|
||||
"""ConvNeXt Block adapted from https://github.com/facebookresearch/ConvNeXt to 1D audio signal.
|
||||
|
||||
Args:
|
||||
dim (int): Number of input channels.
|
||||
layer_scale_init_value (float, optional): Initial value for the layer scale. Zero disables scaling.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
dim: int,
|
||||
layer_scale_init_value=0,
|
||||
):
|
||||
super().__init__()
|
||||
self.dwconv = nn.Conv1d(dim, dim, kernel_size=7, padding=3, groups=dim) # depthwise conv
|
||||
self.norm = nn.LayerNorm(dim, eps=1e-6)
|
||||
self.pwconv1 = nn.Linear(dim, dim * 3) # pointwise/1x1 convs, implemented with linear layers
|
||||
self.act = nn.GELU()
|
||||
self.pwconv2 = nn.Linear(dim * 3, dim)
|
||||
self.gamma = (
|
||||
nn.Parameter(layer_scale_init_value * torch.ones(dim), requires_grad=True)
|
||||
if layer_scale_init_value > 0
|
||||
else None
|
||||
)
|
||||
|
||||
def forward(self, x):
|
||||
residual = x
|
||||
x = self.dwconv(x)
|
||||
x = x.transpose(1, 2) # (B, C, T) -> (B, T, C)
|
||||
x = self.norm(x)
|
||||
x = self.pwconv1(x)
|
||||
x = self.act(x)
|
||||
x = self.pwconv2(x)
|
||||
if self.gamma is not None:
|
||||
x = self.gamma * x
|
||||
x = x.transpose(1, 2) # (B, T, C) -> (B, C, T)
|
||||
|
||||
x = residual + x
|
||||
return x
|
||||
|
||||
|
||||
class APNet_BWE_Model(torch.nn.Module):
|
||||
def __init__(self, h):
|
||||
super(APNet_BWE_Model, self).__init__()
|
||||
self.h = h
|
||||
layer_scale_init_value = 1 / h.ConvNeXt_layers
|
||||
|
||||
self.conv_pre_mag = nn.Conv1d(h.n_fft // 2 + 1, h.ConvNeXt_channels, 7, 1, padding=get_padding(7, 1))
|
||||
self.norm_pre_mag = nn.LayerNorm(h.ConvNeXt_channels, eps=1e-6)
|
||||
self.conv_pre_pha = nn.Conv1d(h.n_fft // 2 + 1, h.ConvNeXt_channels, 7, 1, padding=get_padding(7, 1))
|
||||
self.norm_pre_pha = nn.LayerNorm(h.ConvNeXt_channels, eps=1e-6)
|
||||
|
||||
self.convnext_mag = nn.ModuleList(
|
||||
[
|
||||
ConvNeXtBlock(
|
||||
dim=h.ConvNeXt_channels,
|
||||
layer_scale_init_value=layer_scale_init_value,
|
||||
)
|
||||
for _ in range(h.ConvNeXt_layers)
|
||||
]
|
||||
)
|
||||
|
||||
self.convnext_pha = nn.ModuleList(
|
||||
[
|
||||
ConvNeXtBlock(
|
||||
dim=h.ConvNeXt_channels,
|
||||
layer_scale_init_value=layer_scale_init_value,
|
||||
)
|
||||
for _ in range(h.ConvNeXt_layers)
|
||||
]
|
||||
)
|
||||
|
||||
self.norm_post_mag = nn.LayerNorm(h.ConvNeXt_channels, eps=1e-6)
|
||||
self.norm_post_pha = nn.LayerNorm(h.ConvNeXt_channels, eps=1e-6)
|
||||
self.apply(self._init_weights)
|
||||
self.linear_post_mag = nn.Linear(h.ConvNeXt_channels, h.n_fft // 2 + 1)
|
||||
self.linear_post_pha_r = nn.Linear(h.ConvNeXt_channels, h.n_fft // 2 + 1)
|
||||
self.linear_post_pha_i = nn.Linear(h.ConvNeXt_channels, h.n_fft // 2 + 1)
|
||||
|
||||
def _init_weights(self, m):
|
||||
if isinstance(m, (nn.Conv1d, nn.Linear)):
|
||||
nn.init.trunc_normal_(m.weight, std=0.02)
|
||||
nn.init.constant_(m.bias, 0)
|
||||
|
||||
def forward(self, mag_nb, pha_nb):
|
||||
x_mag = self.conv_pre_mag(mag_nb)
|
||||
x_pha = self.conv_pre_pha(pha_nb)
|
||||
x_mag = self.norm_pre_mag(x_mag.transpose(1, 2)).transpose(1, 2)
|
||||
x_pha = self.norm_pre_pha(x_pha.transpose(1, 2)).transpose(1, 2)
|
||||
|
||||
for conv_block_mag, conv_block_pha in zip(self.convnext_mag, self.convnext_pha):
|
||||
x_mag = x_mag + x_pha
|
||||
x_pha = x_pha + x_mag
|
||||
x_mag = conv_block_mag(x_mag)
|
||||
x_pha = conv_block_pha(x_pha)
|
||||
|
||||
x_mag = self.norm_post_mag(x_mag.transpose(1, 2))
|
||||
mag_wb = mag_nb + self.linear_post_mag(x_mag).transpose(1, 2)
|
||||
|
||||
x_pha = self.norm_post_pha(x_pha.transpose(1, 2))
|
||||
x_pha_r = self.linear_post_pha_r(x_pha)
|
||||
x_pha_i = self.linear_post_pha_i(x_pha)
|
||||
pha_wb = torch.atan2(x_pha_i, x_pha_r).transpose(1, 2)
|
||||
|
||||
com_wb = torch.stack((torch.exp(mag_wb) * torch.cos(pha_wb), torch.exp(mag_wb) * torch.sin(pha_wb)), dim=-1)
|
||||
|
||||
return mag_wb, pha_wb, com_wb
|
||||
20
README.md
20
README.md
@ -2,7 +2,7 @@
|
||||
|
||||
这是从 [GPT-SoVITS](https://github.com/RVC-Boss/GPT-SoVITS) 裁剪得到的语音推理服务。给定一组模型权重、参考音频和待合成文字,服务生成对应音色的语音,供其他程序通过 HTTP 调用。
|
||||
|
||||
唯一服务入口是 `api_v2.py`,默认地址为 `http://127.0.0.1:9880`。仓库提供推理代码、配置样例、安装脚本和 Docker 部署文件;模型权重需要另行准备。训练、微调、数据集处理、ASR、音频分离和 WebUI 已移除。
|
||||
唯一服务入口是 `api_v2.py`,默认地址为 `http://127.0.0.1:9880`。该文件保留原 CLI 和导出兼容,实际 HTTP 服务位于 `GPT_SoVITS/service/`,推理编排位于 `GPT_SoVITS/inference/`。仓库提供推理代码、配置样例、安装脚本和 Docker 部署文件;模型权重需要另行准备。训练、微调、数据集处理、ASR、音频分离和 WebUI 已移除。
|
||||
|
||||
- 模型版本:v1、v2、v2Pro、v2ProPlus、v3、v4、v5dev、v5turbo。
|
||||
- 语言:中文、英文、日文、韩文、粤语及混合语言模式;具体取决于模型版本。
|
||||
@ -75,7 +75,7 @@ GPT_SoVITS/pretrained_models/
|
||||
GPT_SoVITS/text/G2PWModel/
|
||||
```
|
||||
|
||||
参考音频用于提供音色和说话方式;`prompt_text` 必须填写该音频实际说出的内容,`text` 才是希望模型生成的新内容。
|
||||
参考音频用于提供音色和说话方式;`prompt_text` 必须填写该音频实际说出的内容,`text` 才是希望模型生成的新内容。v3 需要 24→48 kHz 超采样时,将 AP-BWE 权重放在 `GPT_SoVITS/vendor/ap_bwe/24kto48k/`;旧的 `tools/AP_BWE_main/24kto48k/` 仍作为兼容回退。
|
||||
|
||||
### 3. 配置要加载的模型
|
||||
|
||||
@ -136,7 +136,18 @@ curl --fail-with-body -X POST http://127.0.0.1:9880/tts -H 'Content-Type: applic
|
||||
|
||||
需要流式输出时,先按上述步骤确认普通 WAV 推理正常,再根据 [API 文档的流式说明](docs/api.md) 选择模式。普通流式使用 `batch_size=1`;GPT 语义流式仅适用于 v2ProPlus、v5dev、v5turbo,需要可用的 CUDA 加速后端,并有额外参数限制。
|
||||
|
||||
## 文档与验证
|
||||
## 代码布局、文档与验证
|
||||
|
||||
```text
|
||||
api_v2.py # 稳定启动器与兼容导出
|
||||
GPT_SoVITS/service/ # FastAPI、请求模型、响应编码、锁和 CLI
|
||||
GPT_SoVITS/inference/ # 模型加载、参考/文本处理、合成和流式
|
||||
GPT_SoVITS/runtime/ # 资源路径、便携环境和日志本地化
|
||||
GPT_SoVITS/vendor/ap_bwe/ # AP-BWE 实现、许可证和规范权重目录
|
||||
GPT_SoVITS/{AR,module,text}/ # 检查点/动态导入敏感的底层实现
|
||||
```
|
||||
|
||||
顶层 `tools/` 当前只保留旧导入包装和旧 AP-BWE 资源路径兼容;新代码应使用上述 `GPT_SoVITS.*` 模块。完整职责与兼容边界见 [目录与架构](docs/architecture.md)。
|
||||
|
||||
| 文档 | 内容 |
|
||||
| --- | --- |
|
||||
@ -148,10 +159,11 @@ curl --fail-with-body -X POST http://127.0.0.1:9880/tts -H 'Content-Type: applic
|
||||
安装好语言资源后,可执行回归测试:
|
||||
|
||||
```bash
|
||||
python -c "import api_v2; from GPT_SoVITS.service.app import APP; from GPT_SoVITS.inference import TTS, TTS_Config; assert api_v2.APP is APP and api_v2.tts_pipeline is None"
|
||||
python -m unittest discover -s tests -t . -p "test_*.py"
|
||||
```
|
||||
|
||||
仅检查入口导入时使用 `python -c "import api_v2"`;这个命令不会加载 TTS 权重,不能代替真实服务启动与语音生成检查。
|
||||
第一条命令检查兼容入口和规范模块可导入,且不会加载 TTS 权重;它不能代替真实服务启动与语音生成检查。
|
||||
|
||||
## Limitations / Known Issues
|
||||
|
||||
|
||||
617
api_v2.py
617
api_v2.py
@ -1,562 +1,95 @@
|
||||
"""GPT-SoVITS HTTP inference service.
|
||||
"""Compatibility launcher for the GPT-SoVITS HTTP inference service.
|
||||
|
||||
Start: python api_v2.py -a 127.0.0.1 -p 9880 -c GPT_SoVITS/configs/tts_infer.yaml
|
||||
Usage and API reference: README.md and docs/api.md.
|
||||
"""
|
||||
|
||||
from tools.portable_runtime import FFMPEG_EXE, activate as activate_portable_runtime
|
||||
|
||||
activate_portable_runtime(change_cwd=True)
|
||||
|
||||
from typing import Annotated, Union, Optional
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
import anyio
|
||||
import subprocess
|
||||
import wave
|
||||
import numpy as np
|
||||
import soundfile as sf
|
||||
from fastapi import FastAPI, Query, Request, Response
|
||||
from fastapi.responses import StreamingResponse, JSONResponse
|
||||
from starlette.background import BackgroundTask
|
||||
from starlette.concurrency import run_in_threadpool
|
||||
import uvicorn
|
||||
from io import BytesIO
|
||||
from GPT_SoVITS.TTS_infer_pack.TTS import TTS, TTS_Config
|
||||
from GPT_SoVITS.TTS_infer_pack.streaming import validate_streaming_options
|
||||
from GPT_SoVITS.TTS_infer_pack.text_segmentation_method import get_method_names as get_cut_method_names
|
||||
from pydantic import BaseModel
|
||||
import threading
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
cut_method_names = get_cut_method_names()
|
||||
|
||||
DEFAULT_CONFIG_PATH = "GPT_SoVITS/configs/tts_infer.yaml"
|
||||
tts_config = TTS_Config(DEFAULT_CONFIG_PATH)
|
||||
tts_pipeline = None
|
||||
import sys
|
||||
import types
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(_app):
|
||||
global tts_pipeline
|
||||
if tts_pipeline is None:
|
||||
print(tts_config)
|
||||
tts_pipeline = await run_in_threadpool(TTS, tts_config)
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
for name in ("streaming_accel", "t2s_accel"):
|
||||
accelerator = getattr(tts_pipeline, name, None)
|
||||
if accelerator is not None:
|
||||
await run_in_threadpool(accelerator.close)
|
||||
tts_pipeline = None
|
||||
# GPU-free compatibility tests and downstream launchers may inject the historic
|
||||
# GPT_SoVITS inference modules while loading this file directly. Keep the real
|
||||
# package path available so the new service package can coexist with those
|
||||
# injected modules.
|
||||
_package = sys.modules.get("GPT_SoVITS")
|
||||
_package_path = str(Path(__file__).resolve().parent / "GPT_SoVITS")
|
||||
if _package is not None and hasattr(_package, "__path__") and _package_path not in _package.__path__:
|
||||
_package.__path__.append(_package_path)
|
||||
|
||||
|
||||
APP = FastAPI(
|
||||
title="GPT-SoVITS 推理 API",
|
||||
description="使用已加载的 GPT/SoVITS 模型合成语音。模型和参考音频路径均由服务端读取;热切换仅作用于当前进程。",
|
||||
lifespan=lifespan,
|
||||
from GPT_SoVITS.service.app import (
|
||||
APP,
|
||||
DEFAULT_CONFIG_PATH,
|
||||
TTS,
|
||||
TTS_Config,
|
||||
create_app,
|
||||
lifespan,
|
||||
state as _service_state,
|
||||
)
|
||||
from GPT_SoVITS.service.audio_response import (
|
||||
pack_aac,
|
||||
pack_audio,
|
||||
pack_ogg,
|
||||
pack_raw,
|
||||
pack_wav,
|
||||
wave_header_chunk,
|
||||
)
|
||||
from GPT_SoVITS.service.cli import main
|
||||
from GPT_SoVITS.service.concurrency import (
|
||||
STREAM_END as _STREAM_END,
|
||||
await_shielded as _await_shielded,
|
||||
next_or_end as _next_or_end,
|
||||
next_tts_chunk as _next_tts_chunk,
|
||||
run_in_threadpool_shielded as _run_in_threadpool_shielded,
|
||||
)
|
||||
from GPT_SoVITS.service.routes import (
|
||||
check_params,
|
||||
cut_method_names,
|
||||
set_gpt_weights,
|
||||
set_refer_aduio,
|
||||
set_sovits_weights,
|
||||
tts_get_endpoint,
|
||||
tts_handle,
|
||||
tts_post_endpoint,
|
||||
)
|
||||
from GPT_SoVITS.service.schemas import TTS_Request
|
||||
|
||||
|
||||
class TTS_Request(BaseModel):
|
||||
text: str = None
|
||||
text_lang: str = None
|
||||
ref_audio_path: str = None
|
||||
aux_ref_audio_paths: list = None
|
||||
prompt_lang: str = None
|
||||
prompt_text: str = ""
|
||||
top_k: int = 15
|
||||
top_p: float = 1
|
||||
temperature: float = 1
|
||||
text_split_method: str = "cut5"
|
||||
batch_size: int = 1
|
||||
batch_threshold: float = 0.75
|
||||
split_bucket: bool = True
|
||||
speed_factor: float = 1.0
|
||||
fragment_interval: float = 0.3
|
||||
seed: int = -1
|
||||
media_type: str = "wav"
|
||||
streaming_mode: Union[bool, int] = False
|
||||
parallel_infer: bool = True
|
||||
use_cuda_graph: bool = True
|
||||
repetition_penalty: float = 1.35
|
||||
sample_steps: Optional[int] = None
|
||||
cfg_rate: Optional[float] = None
|
||||
super_sampling: bool = False
|
||||
overlap_length: int = 2
|
||||
min_chunk_length: int = 16
|
||||
gpt_streaming: bool = False
|
||||
streaming_chunk_seconds: float = 2.0
|
||||
streaming_window_mode: str = "fixed"
|
||||
streaming_lookahead_seconds: float = 0.12
|
||||
streaming_overlap_seconds: float = 0.04
|
||||
gpt_streaming_lookahead_seconds: float = 0.5
|
||||
use_flash_attention: bool = True
|
||||
# Keep the legacy names visible in the module namespace as well as dynamically
|
||||
# synchronized below. This preserves introspection and ``from api_v2 import *``.
|
||||
tts_config = _service_state.tts_config
|
||||
tts_pipeline = _service_state.tts_pipeline
|
||||
_tts_pipeline_lock = _service_state.pipeline_lock
|
||||
|
||||
|
||||
_tts_pipeline_lock = asyncio.Lock()
|
||||
_STREAM_END = object()
|
||||
class _CompatibilityModule(types.ModuleType):
|
||||
"""Keep mutable legacy globals synchronized with explicit service state."""
|
||||
|
||||
|
||||
async def _await_shielded(awaitable):
|
||||
task = asyncio.ensure_future(awaitable)
|
||||
try:
|
||||
return await asyncio.shield(task)
|
||||
except asyncio.CancelledError:
|
||||
# AnyIO cancellation is level-triggered. Shield the in-flight worker call
|
||||
# until it finishes, then let the original cancellation unwind the stream.
|
||||
with anyio.CancelScope(shield=True):
|
||||
try:
|
||||
await task
|
||||
except BaseException:
|
||||
pass
|
||||
raise
|
||||
|
||||
|
||||
async def _run_in_threadpool_shielded(function, *args):
|
||||
return await _await_shielded(run_in_threadpool(function, *args))
|
||||
|
||||
|
||||
def _next_or_end(iterator):
|
||||
try:
|
||||
return next(iterator)
|
||||
except StopIteration:
|
||||
return _STREAM_END
|
||||
|
||||
|
||||
async def _next_tts_chunk(iterator, skip_empty=False):
|
||||
while True:
|
||||
item = await _run_in_threadpool_shielded(_next_or_end, iterator)
|
||||
if item is _STREAM_END or not skip_empty or item[1].size > 0:
|
||||
return item
|
||||
|
||||
|
||||
def pack_ogg(io_buffer: BytesIO, data: np.ndarray, rate: int):
|
||||
# Author: AkagawaTsurunaki
|
||||
# Issue:
|
||||
# Stack overflow probabilistically occurs
|
||||
# when the function `sf_writef_short` of `libsndfile_64bit.dll` is called
|
||||
# using the Python library `soundfile`
|
||||
# Note:
|
||||
# This is an issue related to `libsndfile`, not this project itself.
|
||||
# It happens when you generate a large audio tensor (about 499804 frames in my PC)
|
||||
# and try to convert it to an ogg file.
|
||||
# Related:
|
||||
# https://github.com/RVC-Boss/GPT-SoVITS/issues/1199
|
||||
# https://github.com/libsndfile/libsndfile/issues/1023
|
||||
# https://github.com/bastibe/python-soundfile/issues/396
|
||||
# Suggestion:
|
||||
# Or split the whole audio data into smaller audio segment to avoid stack overflow?
|
||||
|
||||
def handle_pack_ogg():
|
||||
with sf.SoundFile(io_buffer, mode="w", samplerate=rate, channels=1, format="ogg") as audio_file:
|
||||
audio_file.write(data)
|
||||
|
||||
|
||||
|
||||
# See: https://docs.python.org/3/library/threading.html
|
||||
# The stack size of this thread is at least 32768
|
||||
# If stack overflow error still occurs, just modify the `stack_size`.
|
||||
# stack_size = n * 4096, where n should be a positive integer.
|
||||
# Here we chose n = 4096.
|
||||
stack_size = 4096 * 4096
|
||||
try:
|
||||
threading.stack_size(stack_size)
|
||||
pack_ogg_thread = threading.Thread(target=handle_pack_ogg)
|
||||
pack_ogg_thread.start()
|
||||
pack_ogg_thread.join()
|
||||
except RuntimeError as e:
|
||||
# If changing the thread stack size is unsupported, a RuntimeError is raised.
|
||||
print("RuntimeError: {}".format(e))
|
||||
print("Changing the thread stack size is unsupported.")
|
||||
except ValueError as e:
|
||||
# If the specified stack size is invalid, a ValueError is raised and the stack size is unmodified.
|
||||
print("ValueError: {}".format(e))
|
||||
print("The specified stack size is invalid.")
|
||||
|
||||
return io_buffer
|
||||
|
||||
|
||||
def pack_raw(io_buffer: BytesIO, data: np.ndarray, rate: int):
|
||||
io_buffer.write(data.tobytes())
|
||||
return io_buffer
|
||||
|
||||
|
||||
def pack_wav(io_buffer: BytesIO, data: np.ndarray, rate: int):
|
||||
io_buffer = BytesIO()
|
||||
sf.write(io_buffer, data, rate, format="wav")
|
||||
return io_buffer
|
||||
|
||||
|
||||
def pack_aac(io_buffer: BytesIO, data: np.ndarray, rate: int):
|
||||
process = subprocess.Popen(
|
||||
[
|
||||
str(FFMPEG_EXE),
|
||||
"-f",
|
||||
"s16le", # 输入16位有符号小端整数PCM
|
||||
"-ar",
|
||||
str(rate), # 设置采样率
|
||||
"-ac",
|
||||
"1", # 单声道
|
||||
"-i",
|
||||
"pipe:0", # 从管道读取输入
|
||||
"-c:a",
|
||||
"aac", # 音频编码器为AAC
|
||||
"-b:a",
|
||||
"192k", # 比特率
|
||||
"-vn", # 不包含视频
|
||||
"-f",
|
||||
"adts", # 输出AAC数据流格式
|
||||
"pipe:1", # 将输出写入管道
|
||||
],
|
||||
stdin=subprocess.PIPE,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
)
|
||||
out, _ = process.communicate(input=data.tobytes())
|
||||
io_buffer.write(out)
|
||||
return io_buffer
|
||||
|
||||
|
||||
def pack_audio(io_buffer: BytesIO, data: np.ndarray, rate: int, media_type: str):
|
||||
if media_type == "ogg":
|
||||
io_buffer = pack_ogg(io_buffer, data, rate)
|
||||
elif media_type == "aac":
|
||||
io_buffer = pack_aac(io_buffer, data, rate)
|
||||
elif media_type == "wav":
|
||||
io_buffer = pack_wav(io_buffer, data, rate)
|
||||
else:
|
||||
io_buffer = pack_raw(io_buffer, data, rate)
|
||||
io_buffer.seek(0)
|
||||
return io_buffer
|
||||
|
||||
|
||||
# from https://huggingface.co/spaces/coqui/voice-chat-with-mistral/blob/main/app.py
|
||||
def wave_header_chunk(frame_input=b"", channels=1, sample_width=2, sample_rate=32000):
|
||||
# This will create a wave header then append the frame input
|
||||
# It should be first on a streaming wav file
|
||||
# Other frames better should not have it (else you will hear some artifacts each chunk start)
|
||||
wav_buf = BytesIO()
|
||||
with wave.open(wav_buf, "wb") as vfout:
|
||||
vfout.setnchannels(channels)
|
||||
vfout.setsampwidth(sample_width)
|
||||
vfout.setframerate(sample_rate)
|
||||
vfout.writeframes(frame_input)
|
||||
|
||||
wav_buf.seek(0)
|
||||
return wav_buf.read()
|
||||
|
||||
|
||||
def check_params(req: dict):
|
||||
text: str = req.get("text", "")
|
||||
text_lang: str = req.get("text_lang", "")
|
||||
ref_audio_path: str = req.get("ref_audio_path", "")
|
||||
streaming_mode: bool = req.get("streaming_mode", False)
|
||||
media_type: str = req.get("media_type", "wav")
|
||||
prompt_lang: str = req.get("prompt_lang", "")
|
||||
text_split_method: str = req.get("text_split_method", "cut5")
|
||||
|
||||
if ref_audio_path in [None, ""]:
|
||||
return JSONResponse(status_code=400, content={"message": "ref_audio_path is required"})
|
||||
if text in [None, ""]:
|
||||
return JSONResponse(status_code=400, content={"message": "text is required"})
|
||||
if text_lang in [None, ""]:
|
||||
return JSONResponse(status_code=400, content={"message": "text_lang is required"})
|
||||
elif text_lang.lower() not in tts_config.languages:
|
||||
return JSONResponse(
|
||||
status_code=400,
|
||||
content={"message": f"text_lang: {text_lang} is not supported in version {tts_config.version}"},
|
||||
)
|
||||
if prompt_lang in [None, ""]:
|
||||
return JSONResponse(status_code=400, content={"message": "prompt_lang is required"})
|
||||
elif prompt_lang.lower() not in tts_config.languages:
|
||||
return JSONResponse(
|
||||
status_code=400,
|
||||
content={"message": f"prompt_lang: {prompt_lang} is not supported in version {tts_config.version}"},
|
||||
)
|
||||
if media_type not in ["wav", "raw", "ogg", "aac"]:
|
||||
return JSONResponse(status_code=400, content={"message": f"media_type: {media_type} is not supported"})
|
||||
# elif media_type == "ogg" and not streaming_mode:
|
||||
# return JSONResponse(status_code=400, content={"message": "ogg format is not supported in non-streaming mode"})
|
||||
|
||||
if text_split_method not in cut_method_names:
|
||||
return JSONResponse(
|
||||
status_code=400, content={"message": f"text_split_method:{text_split_method} is not supported"}
|
||||
)
|
||||
|
||||
return None
|
||||
|
||||
|
||||
async def tts_handle(req: dict, raw_streaming_mode=None):
|
||||
"""Validate a request and serialize inference and stream cleanup for the shared pipeline."""
|
||||
|
||||
await _tts_pipeline_lock.acquire()
|
||||
tts_generator = None
|
||||
response_owns_lock = False
|
||||
stream_cleanup_task = None
|
||||
|
||||
async def cleanup_stream():
|
||||
nonlocal stream_cleanup_task
|
||||
if stream_cleanup_task is None:
|
||||
async def close_and_release():
|
||||
try:
|
||||
if tts_generator is not None:
|
||||
close = getattr(tts_generator, "close", None)
|
||||
if callable(close):
|
||||
await _run_in_threadpool_shielded(close)
|
||||
finally:
|
||||
_tts_pipeline_lock.release()
|
||||
|
||||
stream_cleanup_task = asyncio.create_task(close_and_release())
|
||||
await _await_shielded(stream_cleanup_task)
|
||||
|
||||
try:
|
||||
check_res = check_params(req)
|
||||
if check_res is not None:
|
||||
return check_res
|
||||
|
||||
gpt_streaming = req.get("gpt_streaming", False)
|
||||
if gpt_streaming:
|
||||
try:
|
||||
validation_req = dict(req)
|
||||
if raw_streaming_mode is not None:
|
||||
validation_req["streaming_mode"] = raw_streaming_mode
|
||||
validate_streaming_options(
|
||||
validation_req,
|
||||
getattr(tts_pipeline.configs, "version", tts_config.version),
|
||||
api_mode=True,
|
||||
)
|
||||
except (TypeError, ValueError) as e:
|
||||
return JSONResponse(status_code=400, content={"message": str(e)})
|
||||
|
||||
streaming_mode = req.get("streaming_mode", False)
|
||||
return_fragment = req.get("return_fragment", False)
|
||||
media_type = req.get("media_type", "wav")
|
||||
|
||||
if streaming_mode == 0:
|
||||
streaming_mode = False
|
||||
return_fragment = False
|
||||
fixed_length_chunk = False
|
||||
elif streaming_mode == 1:
|
||||
streaming_mode = False
|
||||
return_fragment = True
|
||||
fixed_length_chunk = False
|
||||
elif streaming_mode == 2:
|
||||
streaming_mode = True
|
||||
return_fragment = False
|
||||
fixed_length_chunk = False
|
||||
elif streaming_mode == 3:
|
||||
streaming_mode = True
|
||||
return_fragment = False
|
||||
fixed_length_chunk = True
|
||||
else:
|
||||
return JSONResponse(status_code=400, content={"message": f"the value of streaming_mode must be 0, 1, 2, 3(int) or true/false(bool)"})
|
||||
|
||||
req["streaming_mode"] = streaming_mode
|
||||
req["return_fragment"] = return_fragment
|
||||
req["fixed_length_chunk"] = fixed_length_chunk
|
||||
|
||||
|
||||
streaming_mode = streaming_mode or return_fragment
|
||||
tts_generator = await _run_in_threadpool_shielded(tts_pipeline.run, req)
|
||||
|
||||
if streaming_mode:
|
||||
first_chunk = _STREAM_END
|
||||
if gpt_streaming:
|
||||
first_chunk = await _next_tts_chunk(tts_generator, skip_empty=True)
|
||||
if first_chunk is _STREAM_END:
|
||||
return JSONResponse(
|
||||
status_code=400,
|
||||
content={"message": "tts failed", "Exception": "stream produced no PCM audio"},
|
||||
)
|
||||
|
||||
async def streaming_generator():
|
||||
nonlocal media_type
|
||||
first_audio = True
|
||||
item = first_chunk
|
||||
try:
|
||||
while True:
|
||||
if item is _STREAM_END:
|
||||
item = await _next_tts_chunk(tts_generator, skip_empty=gpt_streaming)
|
||||
if item is _STREAM_END:
|
||||
break
|
||||
|
||||
sr, chunk = item
|
||||
if first_audio and media_type == "wav":
|
||||
yield wave_header_chunk(sample_rate=sr)
|
||||
media_type = "raw"
|
||||
first_audio = False
|
||||
packed = await _run_in_threadpool_shielded(
|
||||
pack_audio, BytesIO(), chunk, sr, media_type
|
||||
)
|
||||
yield packed.getvalue()
|
||||
item = _STREAM_END
|
||||
finally:
|
||||
await cleanup_stream()
|
||||
|
||||
response = StreamingResponse(
|
||||
streaming_generator(),
|
||||
media_type=f"audio/{media_type}",
|
||||
background=BackgroundTask(cleanup_stream),
|
||||
)
|
||||
response_owns_lock = True
|
||||
return response
|
||||
|
||||
item = await _next_tts_chunk(tts_generator)
|
||||
if item is _STREAM_END:
|
||||
raise RuntimeError("TTS produced no audio")
|
||||
sr, audio_data = item
|
||||
packed = await _run_in_threadpool_shielded(pack_audio, BytesIO(), audio_data, sr, media_type)
|
||||
return Response(packed.getvalue(), media_type=f"audio/{media_type}")
|
||||
except Exception as e:
|
||||
return JSONResponse(status_code=400, content={"message": "tts failed", "Exception": str(e)})
|
||||
finally:
|
||||
if not response_owns_lock:
|
||||
try:
|
||||
if tts_generator is not None:
|
||||
close = getattr(tts_generator, "close", None)
|
||||
if callable(close):
|
||||
await _run_in_threadpool_shielded(close)
|
||||
finally:
|
||||
_tts_pipeline_lock.release()
|
||||
|
||||
|
||||
@APP.get("/tts")
|
||||
async def tts_get_endpoint(
|
||||
request: Request,
|
||||
text: str = None,
|
||||
text_lang: str = None,
|
||||
ref_audio_path: str = None,
|
||||
aux_ref_audio_paths: Annotated[Optional[list[str]], Query()] = None,
|
||||
prompt_lang: str = None,
|
||||
prompt_text: str = "",
|
||||
top_k: int = 15,
|
||||
top_p: float = 1,
|
||||
temperature: float = 1,
|
||||
text_split_method: str = "cut5",
|
||||
batch_size: int = 1,
|
||||
batch_threshold: float = 0.75,
|
||||
split_bucket: bool = True,
|
||||
speed_factor: float = 1.0,
|
||||
fragment_interval: float = 0.3,
|
||||
seed: int = -1,
|
||||
media_type: str = "wav",
|
||||
parallel_infer: bool = True,
|
||||
use_cuda_graph: bool = True,
|
||||
repetition_penalty: float = 1.35,
|
||||
sample_steps: Optional[int] = None,
|
||||
cfg_rate: Optional[float] = None,
|
||||
super_sampling: bool = False,
|
||||
streaming_mode: Union[bool, int] = False,
|
||||
overlap_length: int = 2,
|
||||
min_chunk_length: int = 16,
|
||||
gpt_streaming: bool = False,
|
||||
streaming_chunk_seconds: float = 2.0,
|
||||
streaming_window_mode: str = "fixed",
|
||||
streaming_lookahead_seconds: float = 0.12,
|
||||
streaming_overlap_seconds: float = 0.04,
|
||||
gpt_streaming_lookahead_seconds: float = 0.5,
|
||||
use_flash_attention: bool = True,
|
||||
):
|
||||
"""使用查询参数合成语音,响应体为音频字节。参考音频路径由服务端读取。"""
|
||||
req = {
|
||||
"text": text,
|
||||
"text_lang": text_lang.lower() if text_lang else text_lang,
|
||||
"ref_audio_path": ref_audio_path,
|
||||
"aux_ref_audio_paths": aux_ref_audio_paths,
|
||||
"prompt_text": prompt_text,
|
||||
"prompt_lang": prompt_lang.lower() if prompt_lang else prompt_lang,
|
||||
"top_k": top_k,
|
||||
"top_p": top_p,
|
||||
"temperature": temperature,
|
||||
"text_split_method": text_split_method,
|
||||
"batch_size": int(batch_size),
|
||||
"batch_threshold": float(batch_threshold),
|
||||
"speed_factor": float(speed_factor),
|
||||
"split_bucket": split_bucket,
|
||||
"fragment_interval": fragment_interval,
|
||||
"seed": seed,
|
||||
"media_type": media_type,
|
||||
"streaming_mode": streaming_mode,
|
||||
"parallel_infer": parallel_infer,
|
||||
"use_cuda_graph": use_cuda_graph,
|
||||
"repetition_penalty": float(repetition_penalty),
|
||||
"sample_steps": None if sample_steps is None else int(sample_steps),
|
||||
"cfg_rate": None if cfg_rate is None else float(cfg_rate),
|
||||
"super_sampling": super_sampling,
|
||||
"overlap_length": int(overlap_length),
|
||||
"min_chunk_length": int(min_chunk_length),
|
||||
"gpt_streaming": gpt_streaming,
|
||||
"streaming_chunk_seconds": float(streaming_chunk_seconds),
|
||||
"streaming_window_mode": streaming_window_mode,
|
||||
"streaming_lookahead_seconds": float(streaming_lookahead_seconds),
|
||||
"streaming_overlap_seconds": float(streaming_overlap_seconds),
|
||||
"gpt_streaming_lookahead_seconds": float(gpt_streaming_lookahead_seconds),
|
||||
"use_flash_attention": use_flash_attention,
|
||||
_state_attributes = {
|
||||
"tts_config": "tts_config",
|
||||
"tts_pipeline": "tts_pipeline",
|
||||
"_tts_pipeline_lock": "pipeline_lock",
|
||||
}
|
||||
raw_streaming_mode = request.query_params.get("streaming_mode")
|
||||
if raw_streaming_mode in {"2", "3"}:
|
||||
raw_streaming_mode = int(raw_streaming_mode)
|
||||
return await tts_handle(req, raw_streaming_mode=raw_streaming_mode)
|
||||
|
||||
def __getattribute__(self, name):
|
||||
state_attributes = types.ModuleType.__getattribute__(self, "_state_attributes")
|
||||
if name in state_attributes:
|
||||
state = types.ModuleType.__getattribute__(self, "_service_state")
|
||||
return getattr(state, state_attributes[name])
|
||||
return types.ModuleType.__getattribute__(self, name)
|
||||
|
||||
def __setattr__(self, name, value):
|
||||
state_attributes = types.ModuleType.__getattribute__(self, "_state_attributes")
|
||||
if name in state_attributes:
|
||||
state = types.ModuleType.__getattribute__(self, "_service_state")
|
||||
setattr(state, state_attributes[name], value)
|
||||
return
|
||||
types.ModuleType.__setattr__(self, name, value)
|
||||
|
||||
|
||||
@APP.post("/tts")
|
||||
async def tts_post_endpoint(request: TTS_Request, raw_request: Request):
|
||||
"""使用 JSON 参数合成语音,响应体为音频字节。字段与 GET /tts 对应。"""
|
||||
req = request.model_dump() if hasattr(request, "model_dump") else request.dict()
|
||||
request_body = await raw_request.json()
|
||||
raw_streaming_mode = request_body.get("streaming_mode", request.streaming_mode)
|
||||
return await tts_handle(req, raw_streaming_mode=raw_streaming_mode)
|
||||
|
||||
|
||||
@APP.get("/set_refer_audio")
|
||||
async def set_refer_aduio(refer_audio_path: str = None):
|
||||
"""预加载服务端参考音频。后续 /tts 仍须提供 ref_audio_path 和对应参考文本。"""
|
||||
try:
|
||||
async with _tts_pipeline_lock:
|
||||
await _run_in_threadpool_shielded(tts_pipeline.set_ref_audio, refer_audio_path)
|
||||
except Exception as e:
|
||||
return JSONResponse(status_code=400, content={"message": "set refer audio failed", "Exception": str(e)})
|
||||
return JSONResponse(status_code=200, content={"message": "success"})
|
||||
|
||||
|
||||
@APP.get("/set_gpt_weights")
|
||||
async def set_gpt_weights(weights_path: str = None):
|
||||
"""加载匹配当前 SoVITS 版本的 GPT 权重;只影响当前进程。"""
|
||||
try:
|
||||
if weights_path in ["", None]:
|
||||
return JSONResponse(status_code=400, content={"message": "gpt weight path is required"})
|
||||
async with _tts_pipeline_lock:
|
||||
await _run_in_threadpool_shielded(tts_pipeline.init_t2s_weights, weights_path)
|
||||
except Exception as e:
|
||||
return JSONResponse(status_code=400, content={"message": "change gpt weight failed", "Exception": str(e)})
|
||||
|
||||
return JSONResponse(status_code=200, content={"message": "success"})
|
||||
|
||||
|
||||
@APP.get("/set_sovits_weights")
|
||||
async def set_sovits_weights(weights_path: str = None):
|
||||
"""加载 SoVITS 权重及对应版本。切换整套声音时,随后加载匹配 GPT 和参考音频。"""
|
||||
try:
|
||||
if weights_path in ["", None]:
|
||||
return JSONResponse(status_code=400, content={"message": "sovits weight path is required"})
|
||||
async with _tts_pipeline_lock:
|
||||
await _run_in_threadpool_shielded(tts_pipeline.init_vits_weights, weights_path)
|
||||
except Exception as e:
|
||||
return JSONResponse(status_code=400, content={"message": "change sovits weight failed", "Exception": str(e)})
|
||||
return JSONResponse(status_code=200, content={"message": "success"})
|
||||
sys.modules[__name__].__class__ = _CompatibilityModule
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser(description="GPT-SoVITS inference API")
|
||||
parser.add_argument("-c", "--tts_config", default=DEFAULT_CONFIG_PATH, help="TTS inference configuration")
|
||||
parser.add_argument("-a", "--bind_addr", default="127.0.0.1", help="default: 127.0.0.1")
|
||||
parser.add_argument("-p", "--port", type=int, default=9880, help="default: 9880")
|
||||
args = parser.parse_args()
|
||||
tts_config = TTS_Config(args.tts_config or DEFAULT_CONFIG_PATH)
|
||||
host, port = args.bind_addr, args.port
|
||||
if host == "None":
|
||||
host = None
|
||||
uvicorn.run(app=APP, host=host, port=port, workers=1)
|
||||
main()
|
||||
|
||||
@ -10,6 +10,7 @@ services:
|
||||
- ./GPT_SoVITS/text/G2PWModel:/app/GPT_SoVITS/text/G2PWModel:ro
|
||||
- ./GPT_SoVITS/configs/tts_infer.yaml:/app/GPT_SoVITS/configs/tts_infer.yaml:ro
|
||||
- ./references:/app/references:ro
|
||||
- ./GPT_SoVITS/vendor/ap_bwe/24kto48k:/app/GPT_SoVITS/vendor/ap_bwe/24kto48k:ro
|
||||
- ./tools/AP_BWE_main/24kto48k:/app/tools/AP_BWE_main/24kto48k:ro
|
||||
- ./.codex/runtime-cache:/app/.codex/runtime-cache
|
||||
gpus: all
|
||||
|
||||
@ -330,4 +330,4 @@ curl --get --fail-with-body --show-error \
|
||||
- **普通推理不做完整数值范围校验。** 类型能被解析不代表任意数值组合都有效;GPT 语义流式表中的范围检查不应当视为所有模式的统一校验。固定 `seed` 也不保证不同硬件、精度、后端或窗口模式下得到逐字节相同的音频。
|
||||
- **v3 超采样权重缺失时会跳过超采样。** 请求中的 `super_sampling=true` 不保证输出为 48000 Hz,应以实际模型配置或 WAV 采样率为准。
|
||||
|
||||
本页依据当前 [API 路由](../api_v2.py)、[TTS pipeline](../GPT_SoVITS/TTS_infer_pack/TTS.py)、[语义流式实现](../GPT_SoVITS/TTS_infer_pack/streaming.py) 和 [文本切分实现](../GPT_SoVITS/TTS_infer_pack/text_segmentation_method.py) 描述。
|
||||
本页依据当前 [兼容入口](../api_v2.py)、[HTTP 路由](../GPT_SoVITS/service/routes.py)、[请求模型](../GPT_SoVITS/service/schemas.py)、[TTS pipeline](../GPT_SoVITS/inference/pipeline.py)、[语义流式实现](../GPT_SoVITS/inference/streaming.py) 和 [文本切分实现](../GPT_SoVITS/inference/segmentation.py) 描述。
|
||||
|
||||
@ -1,50 +1,61 @@
|
||||
# 目录与架构
|
||||
|
||||
本仓库将 GPT-SoVITS 作为一个有状态的 HTTP 推理服务运行。一个进程加载一套当前模型与参考音频,通过 `api_v2.py` 接收合成和模型切换请求。安装与首次合成见 [README](../README.md),接口契约见 [API 文档](api.md)。
|
||||
本仓库将 GPT-SoVITS 作为单进程、有状态的 HTTP 推理服务运行。`api_v2.py` 是稳定的启动命令和兼容导出层;实际 HTTP 服务位于 `GPT_SoVITS/service/`,推理编排位于 `GPT_SoVITS/inference/`。安装与首次合成见 [README](../README.md),接口契约见 [API 文档](api.md)。
|
||||
|
||||
## 目录职责
|
||||
|
||||
```text
|
||||
GPT-SoVITS/
|
||||
├── api_v2.py # 唯一服务入口、HTTP 参数与音频响应
|
||||
├── GPT_SoVITS/ # 模型推理实现与默认资源路径
|
||||
│ ├── TTS_infer_pack/ # 配置、文本预处理、推理编排、流式窗口
|
||||
├── api_v2.py # 兼容启动器;保持原 CLI 和常用导出
|
||||
├── GPT_SoVITS/
|
||||
│ ├── service/ # FastAPI 装配、路由、请求模型、编码与并发控制
|
||||
│ ├── inference/ # 配置、模型生命周期、文本/参考处理与合成编排
|
||||
│ ├── runtime/ # 项目路径、便携运行时初始化和日志本地化
|
||||
│ ├── vendor/ap_bwe/ # AP-BWE 实现、许可证及规范资源位置
|
||||
│ ├── Accel/ # 可选 CUDA Graph / FlashAttention AR 后端
|
||||
│ ├── AR/ # GPT 文本到语义 token 推理
|
||||
│ ├── Accel/ # 可选 CUDA Graph / Flash Attention AR 后端
|
||||
│ ├── text/ # 多语言规范化、音素、字典与 G2PW
|
||||
│ ├── feature_extractor/ # CNHuBERT 参考音频特征
|
||||
│ ├── module/ # SoVITS 解码、量化、CFM 与声码器组件
|
||||
│ ├── module/ # SoVITS、量化、CFM 与声码器组件
|
||||
│ ├── f5_tts/ # CFM 使用的 DiT 网络
|
||||
│ ├── BigVGAN/ # v3 声码器
|
||||
│ ├── eres2net/ # Pro 系列说话人特征网络
|
||||
│ ├── sv.py # 说话人特征提取入口
|
||||
│ ├── inference_loader.py # 权重加载和版本识别
|
||||
│ ├── utils.py # 旧检查点的 HParams 类型
|
||||
│ ├── configs/ # 默认 tts_infer.yaml
|
||||
│ └── pretrained_models/ # 本地基础权重,另行下载
|
||||
├── tools/ # 推理运行时、加速检测、超采样、日志翻译
|
||||
│ ├── pretrained_models/ # 本地基础权重,另行下载
|
||||
│ └── utils.py # 旧检查点的 HParams 反序列化类型
|
||||
├── tools/ # 旧导入/资源路径兼容层,不是新代码的规范入口
|
||||
├── tests/ # API、流式、模型和文本回归测试
|
||||
├── requirements.txt # Windows/Linux 共用基础依赖
|
||||
├── requirements/ # 指定平台的可选加速依赖
|
||||
├── examples/ # 可复制的 YAML 配置与 JSON 请求
|
||||
├── docs/ # 架构、模型、API 和部署说明
|
||||
├── install.ps1 / install.sh # 当前 Python 环境的依赖安装器
|
||||
├── Dockerfile # 推理镜像
|
||||
├── docker-compose.yaml # 单服务部署及资源挂载
|
||||
└── .github/workflows/ # Windows/Linux 回归与容器检查
|
||||
├── Dockerfile # 推理镜像,入口仍为 api_v2.py
|
||||
└── docker-compose.yaml # 单服务、单 worker 部署及资源挂载
|
||||
```
|
||||
|
||||
用户部署时还会创建 `.venv/`、`models/`、`references/` 和 `.codex/runtime-cache/`。它们分别保存隔离环境、角色权重、参考音频和运行缓存,不进入 Git。模型布局与各版本资源清单见 [模型指南](models.md)。
|
||||
`service/` 的主要边界如下:
|
||||
|
||||
- `app.py`:应用状态、FastAPI 装配和模型 lifespan。
|
||||
- `routes.py` / `schemas.py`:`/tts`、三个热切换接口、请求默认值与规范化。
|
||||
- `concurrency.py`:线程池调用、生成器迭代、取消清理和锁生命周期。
|
||||
- `audio_response.py`:WAV、RAW、OGG、AAC 编码。
|
||||
- `cli.py`:`-c/-a/-p` 参数和 `workers=1` 启动。
|
||||
|
||||
`inference/` 中,`pipeline.py` 组合有状态 `TTS`;`config.py` 处理版本与 YAML;`model_runtime.py` 负责 GPT、SoVITS、BERT、CNHuBERT、声码器和热切换;`reference.py` 管理参考缓存;`text_frontend.py`、`segmentation.py`、`batching.py` 处理文本;`synthesis.py`、`streaming.py` 执行普通和流式合成;`checkpoints.py`、`speaker.py`、`super_resolution.py` 分别承接旧加载器、声纹入口和 AP-BWE 适配职责。
|
||||
|
||||
用户部署时还会创建 `.venv/`、`models/`、`references/`、`.codex/runtime-cache/`,也可能提供顶层 `runtime/` 便携二进制包。它们分别保存隔离环境、角色权重、参考音频、可写缓存和可选 FFmpeg/DLL/语言资源,不进入 Git。模型布局见 [模型指南](models.md)。
|
||||
|
||||
## 一次推理的处理链路
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
Client[HTTP 客户端] --> API[api_v2.py:参数校验与请求锁]
|
||||
API --> TTS[TTS_infer_pack:推理编排]
|
||||
Config[配置与 inference_loader] --> TTS
|
||||
TTS --> Text[文本规范化、音素、BERT 特征]
|
||||
TTS --> Reference[参考音频:CNHuBERT、频谱、可选声纹]
|
||||
Client[HTTP 客户端] --> Launcher[api_v2.py 兼容入口]
|
||||
Launcher --> Service[service:参数、锁与音频响应]
|
||||
Service --> Pipeline[inference.pipeline:TTS 状态]
|
||||
Config[inference.config / checkpoints] --> Pipeline
|
||||
Pipeline --> Text[text_frontend / segmentation / batching]
|
||||
Pipeline --> Reference[reference:CNHuBERT、频谱、可选声纹]
|
||||
Text --> AR[AR 普通推理或 Accel 加速后端]
|
||||
Reference --> AR
|
||||
AR --> Semantic[语义 token]
|
||||
@ -52,58 +63,61 @@ flowchart TD
|
||||
Reference --> SoVITS
|
||||
SoVITS --> Direct[v1 / v2 / Pro:内置波形解码]
|
||||
SoVITS --> CFM[v3 / v4 / v5:DiT 与 CFM 生成 mel]
|
||||
CFM --> Vocoder[BigVGAN 或 Generator 声码器]
|
||||
Direct --> PCM[PCM 音频与可选超采样]
|
||||
CFM --> Vocoder[BigVGAN 或 Generator]
|
||||
Direct --> PCM[PCM 与可选 AP-BWE]
|
||||
Vocoder --> PCM
|
||||
PCM --> Encode[API 编码 WAV / RAW / OGG / AAC]
|
||||
PCM --> Encode[service.audio_response]
|
||||
Encode --> Client
|
||||
```
|
||||
|
||||
`TTS.py` 持有 GPT、SoVITS、BERT、CNHuBERT、声码器及参考音频缓存;`TextPreprocessor.py` 组织多语言文本处理。`AR/models/t2s_inference.py` 是纯 `nn.Module` 包装器,使用原检查点的 `model.*` 参数布局。版本识别和 SoVITS 权重读取由 `inference_loader.py` 负责。
|
||||
|
||||
v1、v2、v2Pro、v2ProPlus 使用 SoVITS 内置波形解码;v3 使用 24 kHz BigVGAN,v4、v5dev、v5turbo 使用 48 kHz `Generator` 声码器。`f5_tts/` 提供这些 CFM 路径实际使用的 DiT 网络。`tools/audio_sr.py` 调用 `AP_BWE_main/` 提供可选 24→48 kHz 超采样。
|
||||
v1、v2、v2Pro、v2ProPlus 使用 SoVITS 内置波形解码;v3 使用 24 kHz BigVGAN,v4、v5dev、v5turbo 使用 48 kHz `Generator` 声码器。`f5_tts/` 提供 CFM 路径使用的 DiT 网络。v3 可由 `inference/super_resolution.py` 调用 `vendor/ap_bwe/` 完成 24→48 kHz 超采样。
|
||||
|
||||
## 服务状态与流式生命周期
|
||||
|
||||
导入 `api_v2` 时,`tools/portable_runtime.py` 将工作目录切到仓库根目录,准备模块搜索路径、FFmpeg、Windows DLL 和语言资源路径。此时只读取配置,尚未加载 TTS 模型;FastAPI 的 `lifespan` 在服务启动时创建 TTS 实例,并在退出时关闭加速器。
|
||||
导入 `api_v2` 时,`service/app.py` 调用 `runtime/portable.py`,将工作目录切到仓库根目录并准备模块搜索路径、FFmpeg、Windows DLL 和语言资源路径。此时构造配置,但不加载 TTS 权重;FastAPI lifespan 在服务启动时创建一个 `TTS` 实例,并在退出时关闭加速器。
|
||||
|
||||
`/tts` 与三个 `/set_*` 接口共用一把进程内异步锁。推理生成器在线程池中执行;流式响应持锁直到生成结束或客户端取消。取消时等待正在执行的工作完成,关闭生成器并释放锁,以免下一个请求与旧推理同时操作模型。
|
||||
`/tts` 与三个 `/set_*` 接口共用一把进程内异步锁。同步推理生成器在线程池中执行;流式响应持锁直到生成结束或客户端取消,清理完成后才释放锁。模型和参考音频状态只属于当前进程,因此 CLI 和容器均固定单 worker。
|
||||
|
||||
`/set_sovits_weights`、`/set_gpt_weights`、`/set_refer_audio` 修改当前进程的状态。更换角色时先暂停合成请求,再按 SoVITS、GPT、参考音频顺序切换;整套切换由多个 HTTP 请求组成,并非原子事务。多 worker 会各自持有独立模型和锁,因此部署示例使用单 worker。
|
||||
普通流式及 GPT 语义流式实现位于 `inference/streaming.py`。GPT 语义流式目前用于 v2ProPlus、v5dev、v5turbo,需要可用 CUDA 后端;普通推理在加速不可用时回退。详细约束见 [API 流式说明](api.md)。
|
||||
|
||||
普通流式按文本片段或窗口返回音频,相关窗口算法在 `TTS_infer_pack/streaming.py`。GPT 语义流式由 `Accel/` 增量生成 token,目前用于 v2ProPlus、v5dev、v5turbo,需要可用 CUDA 后端。普通推理可在加速器不可用时回退;GPT 语义流式有单独的设备与参数要求,详见 [API 流式说明](api.md)。
|
||||
## 导入、检查点与资源兼容边界
|
||||
|
||||
## 模块与资源边界
|
||||
新应用代码应使用 `GPT_SoVITS.service.*`、`GPT_SoVITS.inference.*`、`GPT_SoVITS.runtime.*` 和 `GPT_SoVITS.vendor.ap_bwe.*`。以下兼容边界仍有意保留:
|
||||
|
||||
保留推理模块原名和默认模型布局,是为了让已有权重和配置继续工作:
|
||||
|
||||
- 旧检查点可能将配置保存为 `utils.HParams`;`GPT_SoVITS/utils.py` 提供该反序列化类型。
|
||||
- 运行时把 `GPT_SoVITS/` 加入模块搜索路径,代码同时使用 `AR`、`module`、`text` 等短路径与 `GPT_SoVITS.*` 导入。语言模块和加速后端还存在动态导入。
|
||||
- 网络参数名称和 AR 的 `model.*` 前缀属于检查点合约,修改它们需要相应的加载与数值回归证据。
|
||||
- `pretrained_models/`、`text/G2PWModel/`、`tools/AP_BWE_main/24kto48k/` 有直接读取资源的代码;权重与源码分开提供,部署时按约定位置放置或挂载。
|
||||
- `tools/i18n/` 服务于推理日志;`tools/portable_runtime.py` 和 `tools/acceleration.py` 服务于跨平台导入及后端选择,均属于运行依赖。
|
||||
- `api_v2.py` 继续导出 `APP`、`TTS`、`TTS_Config`、请求类型及旧可变状态名称,并保持原启动命令。
|
||||
- `tools/portable_runtime.py`、`tools/acceleration.py`、`tools/audio_sr.py` 和 `tools/i18n/` 是旧导入兼容包装;`tools/AP_BWE_main/` 还保留旧部署资源位置。
|
||||
- `runtime/paths.py` 优先读取 `GPT_SoVITS/vendor/ap_bwe/24kto48k/g_24kto48k.zip`,不存在时回退 `tools/AP_BWE_main/24kto48k/g_24kto48k.zip`,以兼容既有挂载。
|
||||
- 旧检查点可能保存 `utils.HParams`;`GPT_SoVITS/utils.py` 必须留在原位。
|
||||
- `AR/`、`module/`、`text/` 等短导入、网络参数名称和 AR 的 `model.*` 前缀属于检查点或动态导入合约,不应只为目录统一而改名。
|
||||
- `pretrained_models/`、`text/G2PWModel/`、`vendor/ap_bwe/24kto48k/` 和 `runtime/i18n/locale/` 是运行资源路径;部署时按约定位置提供。
|
||||
|
||||
## 修改入口与验证
|
||||
|
||||
| 需求 | 主要修改位置 | 对应测试 |
|
||||
| --- | --- | --- |
|
||||
| HTTP 参数、响应、热切换、取消清理 | `api_v2.py` | `tests/test_api_v2_streaming.py` |
|
||||
| 流式窗口和拼接 | `TTS_infer_pack/streaming.py` | `tests/test_official_streaming.py` |
|
||||
| AR 推理、权重读取 | `AR/`、`inference_loader.py` | `tests/test_inference_runtime.py`、`tests/test_ar_g2pw_runtime.py` |
|
||||
| SoVITS 与声码器 | `module/`、`f5_tts/`、`BigVGAN/` | `tests/test_sovits_inference.py`、`tests/test_inference_components.py` |
|
||||
| 多语言处理和缓存 | `text/` | `tests/test_text_inference.py`、`tests/test_langdetect_cache.py` |
|
||||
| 推理服务边界 | 入口与运行依赖 | `tests/test_inference_surface.py` |
|
||||
| HTTP 参数、响应、热切换、取消清理 | `GPT_SoVITS/service/`、`api_v2.py` | `tests/test_api_v2_streaming.py` |
|
||||
| 流式窗口和拼接 | `GPT_SoVITS/inference/streaming.py` | `tests/test_official_streaming.py` |
|
||||
| 配置、权重识别与模型生命周期 | `GPT_SoVITS/inference/config.py`、`checkpoints.py`、`model_runtime.py` | `tests/test_inference_runtime.py` |
|
||||
| SoVITS、声码器、声纹与 AP-BWE | `module/`、`f5_tts/`、`BigVGAN/`、`inference/speaker.py`、`vendor/ap_bwe/` | `tests/test_sovits_inference.py`、`tests/test_inference_components.py` |
|
||||
| 多语言处理和缓存 | `inference/text_frontend.py`、`text/`、`runtime/paths.py` | `tests/test_text_inference.py`、`tests/test_langdetect_cache.py` |
|
||||
| 推理服务边界 | `service/`、`inference/`、`runtime/` 与兼容入口 | `tests/test_inference_surface.py` |
|
||||
|
||||
在仓库根目录运行全部测试:
|
||||
不加载模型权重的导入检查:
|
||||
|
||||
```bash
|
||||
python -c "import api_v2; from GPT_SoVITS.service.app import APP; from GPT_SoVITS.inference import TTS, TTS_Config; assert api_v2.APP is APP and api_v2.tts_pipeline is None"
|
||||
```
|
||||
|
||||
运行全部回归:
|
||||
|
||||
```bash
|
||||
python -m unittest discover -s tests -t . -p "test_*.py"
|
||||
```
|
||||
|
||||
仅验证 API 与流式算法:
|
||||
仅验证 API、流式和结构边界:
|
||||
|
||||
```bash
|
||||
python -m unittest tests.test_official_streaming tests.test_api_v2_streaming
|
||||
python -m unittest tests.test_inference_surface tests.test_api_v2_streaming tests.test_official_streaming
|
||||
```
|
||||
|
||||
测试使用小型检查点、受控输入或 mock pipeline 验证代码行为;多语言测试还需要相应语言资源。使用真实角色模型启动服务并调用 `/tts` 才能验证模型组合及实际语音输出。已验证平台与当前运行限制统一列在 [部署指南](deployment.md#limitations--known-issues) 和 [API 文档](api.md) 中。
|
||||
测试使用小型检查点、受控输入或 mock pipeline;多语言测试还需要相应语言资源。真实权重启动和一次 `/tts` 请求仍是模型组合及实际语音输出的最终验证。已验证平台和限制见 [部署指南](deployment.md#limitations--known-issues) 与 [API 文档](api.md)。
|
||||
|
||||
@ -83,7 +83,7 @@ bash install.sh --device CPU
|
||||
| v3 声码器 | `GPT_SoVITS/pretrained_models/models--nvidia--bigvgan_v2_24khz_100band_256x/` 下的 `config.json`、`bigvgan_generator.pt` |
|
||||
| v4 声码器 | `GPT_SoVITS/pretrained_models/gsv-v4-pretrained/vocoder.pth` |
|
||||
| v5dev / v5turbo 声码器 | `GPT_SoVITS/pretrained_models/gsv-v5-pretrained/vocoder.pth` |
|
||||
| 可选超采样 | `tools/AP_BWE_main/24kto48k/g_24kto48k.zip` 及同目录的 `config.json` |
|
||||
| 可选超采样 | 规范位置 `GPT_SoVITS/vendor/ap_bwe/24kto48k/g_24kto48k.zip` 及同目录 `config.json`;旧 `tools/AP_BWE_main/24kto48k/` 仍作为回退 |
|
||||
| 参考音频 | 例如 `references/reference.wav`,请求指定其本地路径 |
|
||||
|
||||
LoRA 权重还需要相应版本的基础 SoVITS 权重。准备实际使用版本所需的资源即可。
|
||||
@ -119,7 +119,7 @@ python .\api_v2.py -c GPT_SoVITS/configs/tts_infer.yaml -a 127.0.0.1 -p 9880
|
||||
|
||||
`-c/--tts_config` 指定配置文件,`-a/--bind_addr` 指定监听地址,`-p/--port` 指定端口。默认地址为 `127.0.0.1:9880`;需要外部客户端访问时使用 `-a 0.0.0.0`。
|
||||
|
||||
模型在服务启动阶段加载,日志出现 `Application startup complete` 后再发送请求。权重缺失会导致启动失败;单独运行 `python -c "import api_v2"` 不加载 TTS 权重,不能替代完整启动检查。服务默认使用一个 worker;请求、参考音频设置和模型切换共享该进程的模型状态。
|
||||
模型在服务启动阶段加载,日志出现 `Application startup complete` 后再发送请求。权重缺失会导致启动失败;单独运行 `python -c "import api_v2"` 不加载 TTS 权重,不能替代完整启动检查。`api_v2.py` 是稳定兼容入口,实际应用和 CLI 位于 `GPT_SoVITS/service/`,推理实现位于 `GPT_SoVITS/inference/`。服务固定使用一个 worker;请求、参考音频设置和模型切换共享该进程的模型状态。
|
||||
|
||||
日志默认输出到控制台。Linux 保存日志:
|
||||
|
||||
@ -165,7 +165,7 @@ PowerShell 设置 `$env:API_PORT = '19880'` 后执行 `docker compose up -d`。
|
||||
|
||||
### 挂载自定义权重
|
||||
|
||||
Compose 已挂载默认预训练资源、G2PW、推理配置、参考音频和超采样目录,挂载为只读;`.codex/runtime-cache/` 为可写持久化缓存。自定义权重若放在 `models/`,在服务的 `volumes` 中追加:
|
||||
Compose 已将默认预训练资源、G2PW、推理配置、参考音频和 AP-BWE 目录挂载到原有 `/app/...` 路径,均为只读;`.codex/runtime-cache/` 为可写持久化缓存。AP-BWE 同时挂载规范目录 `/app/GPT_SoVITS/vendor/ap_bwe/24kto48k` 和旧目录 `/app/tools/AP_BWE_main/24kto48k`:运行时优先规范目录,保留旧挂载是为了已有部署在迁移权重前仍可运行。自定义权重若放在 `models/`,在服务的 `volumes` 中追加:
|
||||
|
||||
```yaml
|
||||
services:
|
||||
@ -195,7 +195,7 @@ docker compose down
|
||||
|
||||
## 缓存和离线准备
|
||||
|
||||
离线机器需要先具备运行依赖、FFmpeg 和所用版本的全部模型。可在相同平台、Python 版本及设备后端的环境完成安装和资源准备后迁移部署材料;安装脚本自身会访问 PyPI/PyTorch 和语言资源下载站点。
|
||||
离线机器需要先具备运行依赖、FFmpeg 和所用版本的全部模型。可在相同平台、Python 版本及设备后端的环境完成安装和资源准备后迁移部署材料;安装脚本自身会访问 PyPI/PyTorch 和语言资源下载站点。规范运行资源由 `GPT_SoVITS/runtime/paths.py` 定位,顶层 `runtime/` 仅用于可选便携 FFmpeg、DLL、site-packages 和 NLTK 数据。
|
||||
|
||||
| 资源 | 准备方法与运行位置 |
|
||||
| --- | --- |
|
||||
@ -209,14 +209,14 @@ docker compose down
|
||||
|
||||
设置 `NLTK_DATA` 可指向预先准备的 NLTK 目录;运行时也会依次查找项目便携包的 `runtime/nltk_data/` 和 `.codex/runtime-cache/nltk_data/`。便携包中存在 `runtime/ffmpeg.exe` / `runtime/ffprobe.exe` 时优先使用它们,否则从系统 `PATH` 查找。
|
||||
|
||||
本地 Hugging Face 模型及 tokenizer 准备完整后,可设置 `HF_HUB_OFFLINE=1` 验证离线启动和一次真实请求。该变量只控制 Hugging Face 的访问,G2PW、语言检测和 NLTK 等资源仍须分别准备。Docker 离线运行需要提前构建或导入完整镜像,并准备宿主机挂载目录;`.dockerignore` 排除了默认预训练权重、G2PW 和 `.codex` 缓存目录,镜像构建不会自动包含这些资源。容器内 NLTK 默认使用镜像预置的 `/opt/nltk_data`。
|
||||
本地 Hugging Face 模型及 tokenizer 准备完整后,可设置 `HF_HUB_OFFLINE=1` 验证离线启动和一次真实请求。该变量只控制 Hugging Face 的访问,G2PW、语言检测和 NLTK 等资源仍须分别准备。Docker 离线运行需要提前构建或导入完整镜像,并准备宿主机挂载目录;`.dockerignore` 排除了默认预训练权重、G2PW、AP-BWE ZIP 和 `.codex` 缓存目录,镜像构建不会自动包含这些资源。容器内 NLTK 默认使用镜像预置的 `/opt/nltk_data`。
|
||||
|
||||
## 检查和 CI
|
||||
|
||||
先检查入口可导入,再运行回归:
|
||||
|
||||
```bash
|
||||
python -c "import api_v2; assert api_v2.tts_pipeline is None"
|
||||
python -c "import api_v2; from GPT_SoVITS.service.app import APP; from GPT_SoVITS.inference import TTS, TTS_Config; assert api_v2.APP is APP and api_v2.tts_pipeline is None"
|
||||
python -m unittest discover -s tests -t . -p "test_*.py"
|
||||
```
|
||||
|
||||
|
||||
@ -14,7 +14,7 @@
|
||||
|
||||
优先使用模型提供者说明中配套的 `.ckpt` 和 `.pth`。参考音频建议为单人、清晰、无配乐的 WAV;服务按重采样到 16 kHz 后的长度检查 3–10 秒范围。`prompt_lang` 对应参考转写的语言,`text_lang` 对应生成文本的语言。v3、v4 和 v5 的请求必须提供非空 `prompt_text`。
|
||||
|
||||
保留下载文件的原始 checkpoint 格式。服务可直接加载受支持的已有模型及其兼容配置;修改文件名或 YAML 中的 `version` 不会转换模型版本。实际 SoVITS 类型由加载器根据权重标识和内容确定。
|
||||
保留下载文件的原始 checkpoint 格式。服务可直接加载受支持的已有模型及其兼容配置;修改文件名或 YAML 中的 `version` 不会转换模型版本。实际 SoVITS 类型由 [`inference/checkpoints.py`](../GPT_SoVITS/inference/checkpoints.py) 根据权重标识和内容确定。
|
||||
|
||||
## 共享资源与模型来源
|
||||
|
||||
@ -64,14 +64,14 @@ GPT_SoVITS/pretrained_models/
|
||||
└── sv/
|
||||
└── pretrained_eres2netv2w24s4ep4.ckpt # v2Pro/v2ProPlus
|
||||
|
||||
tools/AP_BWE_main/24kto48k/
|
||||
GPT_SoVITS/vendor/ap_bwe/24kto48k/
|
||||
├── config.json
|
||||
└── g_24kto48k.zip # 可选的 v3 超采样
|
||||
```
|
||||
|
||||
v3 的 BigVGAN 资源可取模型库中的同名目录,或取 [NVIDIA BigVGAN 模型](https://huggingface.co/nvidia/bigvgan_v2_24khz_100band_256x/tree/main) 中的 `config.json` 和 `bigvgan_generator.pt`,直接放入上述本地目录。运行时读取这两个本地文件,目录名不表示需要额外的 Hugging Face 缓存层级。v3 默认输出 24 kHz;v4 与两个 v5 版本的声码器输出 48 kHz。
|
||||
|
||||
v3 的可选超采样使用 [AP-BWE](https://github.com/yxlu-0102/AP-BWE) 提供的 [预训练资源](https://drive.google.com/drive/folders/1IIYTf2zbJWzelu4IftKD6ooHloJ8mnZF?usp=share_link)。将 `g_24kto48k.zip` 与对应 `config.json` 放在同一目录;这里的 ZIP 文件由加载器直接读取,不需解压为其他权重文件。请求设置 `super_sampling: true` 后才会加载,当前该选项用于 v3 的 24→48 kHz 输出。缺少超采样权重时,服务记录提示并保留原采样率输出。
|
||||
v3 的可选超采样使用 [AP-BWE](https://github.com/yxlu-0102/AP-BWE) 提供的 [预训练资源](https://drive.google.com/drive/folders/1IIYTf2zbJWzelu4IftKD6ooHloJ8mnZF?usp=share_link)。将 `g_24kto48k.zip` 与对应 `config.json` 放在规范目录 `GPT_SoVITS/vendor/ap_bwe/24kto48k/`;ZIP 由加载器直接读取,不需解压。运行时优先使用该目录,若权重不存在,再检查旧部署位置 `tools/AP_BWE_main/24kto48k/`。请求设置 `super_sampling: true` 后才会加载,当前该选项用于 v3 的 24→48 kHz 输出;缺少权重时记录提示并保留原采样率输出。
|
||||
|
||||
## 可复制的 v4 CPU 配置
|
||||
|
||||
@ -144,7 +144,7 @@ python api_v2.py -c models/voice/tts-default-v4.yaml
|
||||
| `v4.vits_weights_path` 等版本默认路径 | 可使用相对路径或绝对路径,LoRA 用它查找基座 |
|
||||
| `/tts` 的参考音频、辅助参考音频与 `/set_*` 路径 | 指向服务进程可访问的本地文件,可使用相对路径或绝对路径 |
|
||||
| G2PW 模型目录、BigVGAN、v4/v5 声码器、Pro 声纹模型 | 当前按上面的项目固定布局查找,YAML 没有单独的重定位字段 |
|
||||
| AP-BWE 超采样 | 固定在 `tools/AP_BWE_main/24kto48k/`,相对于该工具源码位置 |
|
||||
| AP-BWE 超采样 | 规范位置为 `GPT_SoVITS/vendor/ap_bwe/24kto48k/`;为兼容已有挂载,缺失时回退 `tools/AP_BWE_main/24kto48k/` |
|
||||
|
||||
相对路径以服务的工作目录为基准,不以 YAML 文件所在目录为基准。Windows 的绝对路径建议在 YAML 中使用正斜杠或单引号,避免反斜杠被双引号当作转义字符。
|
||||
|
||||
|
||||
@ -68,16 +68,14 @@ def _load_api_module(argv=None):
|
||||
activate=lambda **_kwargs: None,
|
||||
)
|
||||
i18n = _module("tools.i18n.i18n", I18nAuto=lambda: object())
|
||||
tts = _module("GPT_SoVITS.TTS_infer_pack.TTS", TTS=_FakePipeline, TTS_Config=_FakeConfig)
|
||||
inference = _module("GPT_SoVITS.inference", package=True, TTS=_FakePipeline, TTS_Config=_FakeConfig)
|
||||
segmentation = _module(
|
||||
"GPT_SoVITS.TTS_infer_pack.text_segmentation_method",
|
||||
"GPT_SoVITS.inference.segmentation",
|
||||
get_method_names=lambda: [f"cut{index}" for index in range(6)],
|
||||
)
|
||||
streaming_name = "GPT_SoVITS.TTS_infer_pack.streaming"
|
||||
streaming_spec = importlib.util.spec_from_file_location(
|
||||
streaming_name, root / "GPT_SoVITS" / "TTS_infer_pack" / "streaming.py"
|
||||
)
|
||||
streaming = importlib.util.module_from_spec(streaming_spec)
|
||||
streaming_name = "GPT_SoVITS.inference.streaming"
|
||||
from GPT_SoVITS.inference.streaming import validate_streaming_options
|
||||
streaming = _module(streaming_name, validate_streaming_options=validate_streaming_options)
|
||||
replacements = {
|
||||
"tools": _module("tools", package=True),
|
||||
"tools.portable_runtime": portable,
|
||||
@ -86,16 +84,18 @@ def _load_api_module(argv=None):
|
||||
"tools.acceleration": _module("tools.acceleration", create_acceleration=lambda *_args, **_kwargs: None),
|
||||
"torch": _module("torch", inference_mode=lambda: lambda function: function),
|
||||
"GPT_SoVITS": _module("GPT_SoVITS", package=True),
|
||||
"GPT_SoVITS.TTS_infer_pack": _module("GPT_SoVITS.TTS_infer_pack", package=True),
|
||||
"GPT_SoVITS.TTS_infer_pack.TTS": tts,
|
||||
"GPT_SoVITS.TTS_infer_pack.text_segmentation_method": segmentation,
|
||||
"GPT_SoVITS.Accel": _module("GPT_SoVITS.Accel", package=True),
|
||||
"GPT_SoVITS.Accel.factory": _module(
|
||||
"GPT_SoVITS.Accel.factory", create_acceleration=lambda *_args, **_kwargs: None
|
||||
),
|
||||
"GPT_SoVITS.inference": inference,
|
||||
"GPT_SoVITS.inference.segmentation": segmentation,
|
||||
streaming_name: streaming,
|
||||
}
|
||||
spec = importlib.util.spec_from_file_location("api_v2_streaming_test_module", root / "api_v2.py")
|
||||
api = importlib.util.module_from_spec(spec)
|
||||
replacements[spec.name] = api
|
||||
with patch.dict(sys.modules, replacements), patch.object(sys, "argv", argv or [sys.argv[0]]):
|
||||
streaming_spec.loader.exec_module(streaming)
|
||||
spec.loader.exec_module(api)
|
||||
return api
|
||||
|
||||
|
||||
@ -12,9 +12,10 @@ from torchaudio.compliance.kaldi import fbank as reference_fbank
|
||||
from GPT_SoVITS.BigVGAN.bigvgan import AttrDict, BigVGAN
|
||||
from GPT_SoVITS.eres2net.ERes2NetV2 import ERes2NetV2
|
||||
from GPT_SoVITS.eres2net.kaldi import fbank
|
||||
from GPT_SoVITS.sv import SV
|
||||
from tools.AP_BWE_main.models.model import APNet_BWE_Model
|
||||
from tools.audio_sr import AP_BWE
|
||||
from GPT_SoVITS.inference.super_resolution import AP_BWE
|
||||
from GPT_SoVITS.runtime.paths import resolve_ap_bwe_checkpoint
|
||||
from GPT_SoVITS.inference.speaker import SV
|
||||
from GPT_SoVITS.vendor.ap_bwe.models.model import APNet_BWE_Model
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
@ -52,7 +53,7 @@ class InferenceComponentTests(unittest.TestCase):
|
||||
model = self._speaker_model()
|
||||
state = dict(model.state_dict())
|
||||
state.update({"seg_1.weight": torch.zeros(2, 2), "seg_1.bias": torch.zeros(2)})
|
||||
with patch("GPT_SoVITS.sv.ERes2NetV2", return_value=model), patch("GPT_SoVITS.sv.torch.load", return_value=state):
|
||||
with patch("GPT_SoVITS.inference.speaker.ERes2NetV2", return_value=model), patch("GPT_SoVITS.inference.speaker.torch.load", return_value=state):
|
||||
speaker = SV("cpu", False)
|
||||
self.assertFalse(hasattr(model, "pool"))
|
||||
self.assertFalse(hasattr(model, "seg_1"))
|
||||
@ -70,7 +71,7 @@ class InferenceComponentTests(unittest.TestCase):
|
||||
state.pop("conv1.weight")
|
||||
else:
|
||||
state["seg_2.weight"] = torch.zeros(1)
|
||||
with patch("GPT_SoVITS.sv.ERes2NetV2", return_value=model), patch("GPT_SoVITS.sv.torch.load", return_value=state):
|
||||
with patch("GPT_SoVITS.inference.speaker.ERes2NetV2", return_value=model), patch("GPT_SoVITS.inference.speaker.torch.load", return_value=state):
|
||||
with self.assertRaises(RuntimeError):
|
||||
SV("cpu", False)
|
||||
|
||||
@ -119,6 +120,21 @@ class InferenceComponentTests(unittest.TestCase):
|
||||
self.assertEqual(output.shape, (4800,))
|
||||
self.assertTrue(torch.isfinite(torch.from_numpy(output)).all())
|
||||
|
||||
def test_bandwidth_extension_checkpoint_prefers_vendor_and_falls_back_to_legacy_mount(self):
|
||||
with tempfile.TemporaryDirectory(dir=TEMP_ROOT) as directory:
|
||||
directory = Path(directory)
|
||||
canonical = directory / "vendor" / "g_24kto48k.zip"
|
||||
legacy = directory / "tools" / "g_24kto48k.zip"
|
||||
legacy.parent.mkdir(parents=True)
|
||||
legacy.write_bytes(b"legacy")
|
||||
with patch("GPT_SoVITS.runtime.paths.AP_BWE_CHECKPOINT_PATH", canonical), patch(
|
||||
"GPT_SoVITS.runtime.paths.LEGACY_AP_BWE_CHECKPOINT_PATH", legacy
|
||||
):
|
||||
self.assertEqual(resolve_ap_bwe_checkpoint(), legacy)
|
||||
canonical.parent.mkdir(parents=True)
|
||||
canonical.write_bytes(b"vendor")
|
||||
self.assertEqual(resolve_ap_bwe_checkpoint(), canonical)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
@ -20,7 +20,7 @@ sys.path.insert(0, str(ROOT / "GPT_SoVITS"))
|
||||
|
||||
from AR.models.t2s_inference import Text2SemanticInference
|
||||
from AR.models.t2s_model import Text2SemanticDecoder
|
||||
from inference_loader import get_sovits_version_from_path_fast, load_sovits_new
|
||||
from GPT_SoVITS.inference.checkpoints import get_sovits_version_from_path_fast, load_sovits_new
|
||||
|
||||
|
||||
class InferenceModelTests(unittest.TestCase):
|
||||
|
||||
@ -66,10 +66,10 @@ class InferenceSurfaceTests(unittest.TestCase):
|
||||
|
||||
|
||||
def test_api_v2_exposes_inference_routes_only(self):
|
||||
source = (ROOT / "api_v2.py").read_text(encoding="utf-8")
|
||||
self.assertIn('@APP.get("/tts")', source)
|
||||
self.assertIn('@APP.post("/tts")', source)
|
||||
self.assertIn('@APP.get("/set_refer_audio")', source)
|
||||
self.assertIn('@APP.get("/set_gpt_weights")', source)
|
||||
self.assertIn('@APP.get("/set_sovits_weights")', source)
|
||||
self.assertNotIn('@APP.get("/control")', source)
|
||||
source = (ROOT / "GPT_SoVITS" / "service" / "routes.py").read_text(encoding="utf-8")
|
||||
self.assertIn('application.add_api_route("/tts", tts_get_endpoint, methods=["GET"])', source)
|
||||
self.assertIn('application.add_api_route("/tts", tts_post_endpoint, methods=["POST"])', source)
|
||||
self.assertIn('application.add_api_route("/set_refer_audio", set_refer_aduio, methods=["GET"])', source)
|
||||
self.assertIn('application.add_api_route("/set_gpt_weights", set_gpt_weights, methods=["GET"])', source)
|
||||
self.assertIn('application.add_api_route("/set_sovits_weights", set_sovits_weights, methods=["GET"])', source)
|
||||
self.assertNotIn('application.add_api_route("/control"', source)
|
||||
|
||||
@ -19,9 +19,10 @@ from module.models import CFM, SynthesizerTrn
|
||||
|
||||
# Load the official helper file directly so importing its package does not
|
||||
# eagerly import the full TTS stack (and its optional librosa/numba cache).
|
||||
_streaming_path = Path(__file__).resolve().parents[1] / "GPT_SoVITS" / "TTS_infer_pack" / "streaming.py"
|
||||
_streaming_spec = importlib.util.spec_from_file_location("GPT_SoVITS.TTS_infer_pack.streaming", _streaming_path)
|
||||
_streaming_path = Path(__file__).resolve().parents[1] / "GPT_SoVITS" / "inference" / "streaming.py"
|
||||
_streaming_spec = importlib.util.spec_from_file_location("GPT_SoVITS.inference.streaming", _streaming_path)
|
||||
_streaming_module = importlib.util.module_from_spec(_streaming_spec)
|
||||
sys.modules[_streaming_spec.name] = _streaming_module
|
||||
_streaming_spec.loader.exec_module(_streaming_module)
|
||||
v2_token_chunks = _streaming_module.v2_token_chunks
|
||||
validate_streaming_options = _streaming_module.validate_streaming_options
|
||||
@ -81,8 +82,8 @@ class ReferenceTests(unittest.TestCase):
|
||||
pipeline = SimpleNamespace(prompt_cache=cache, precision=torch.float32,
|
||||
configs=SimpleNamespace(device=torch.device("cpu")),
|
||||
vits_model=SimpleNamespace(decode_encp=lambda *args: (features, None)))
|
||||
stub = SimpleNamespace(resample=None, mel_fn_v4=lambda _: mel, norm_spec=lambda x: x)
|
||||
with patch.dict(sys.modules, {"GPT_SoVITS.TTS_infer_pack.TTS": stub}):
|
||||
with patch.dict(sys.modules, {"GPT_SoVITS.inference.audio": SimpleNamespace(
|
||||
resample=lambda *_args: torch.zeros(1, 10), mel_fn_v4=lambda _: mel, norm_spec=lambda x: x)}):
|
||||
reference = _streaming_module.v5_reference(pipeline)
|
||||
torch.testing.assert_close(reference[4], features[..., :5])
|
||||
torch.testing.assert_close(reference[6], mel)
|
||||
|
||||
@ -1,29 +1,5 @@
|
||||
"""STFT helpers required by the inference-time AP-BWE model."""
|
||||
"""Compatibility shim for the vendored AP-BWE audio helpers."""
|
||||
|
||||
import torch
|
||||
from GPT_SoVITS.vendor.ap_bwe.audio_ops import amp_pha_istft, amp_pha_stft
|
||||
|
||||
|
||||
def amp_pha_stft(audio, n_fft, hop_size, win_size, center=True):
|
||||
hann_window = torch.hann_window(win_size).to(audio.device)
|
||||
stft_spec = torch.stft(
|
||||
audio,
|
||||
n_fft,
|
||||
hop_length=hop_size,
|
||||
win_length=win_size,
|
||||
window=hann_window,
|
||||
center=center,
|
||||
pad_mode="reflect",
|
||||
normalized=False,
|
||||
return_complex=True,
|
||||
)
|
||||
log_amp = torch.log(torch.abs(stft_spec) + 1e-4)
|
||||
pha = torch.angle(stft_spec)
|
||||
com = torch.stack((torch.exp(log_amp) * torch.cos(pha), torch.exp(log_amp) * torch.sin(pha)), dim=-1)
|
||||
return log_amp, pha, com
|
||||
|
||||
|
||||
def amp_pha_istft(log_amp, pha, n_fft, hop_size, win_size, center=True):
|
||||
amp = torch.exp(log_amp)
|
||||
com = torch.complex(amp * torch.cos(pha), amp * torch.sin(pha))
|
||||
hann_window = torch.hann_window(win_size).to(com.device)
|
||||
return torch.istft(com, n_fft, hop_length=hop_size, win_length=win_size, window=hann_window, center=center)
|
||||
__all__ = ["amp_pha_istft", "amp_pha_stft"]
|
||||
|
||||
@ -1 +1,5 @@
|
||||
"""Compatibility package for the vendored AP-BWE model."""
|
||||
|
||||
from .model import APNet_BWE_Model
|
||||
|
||||
__all__ = ["APNet_BWE_Model"]
|
||||
|
||||
@ -1,115 +1,5 @@
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
"""Compatibility shim for the vendored AP-BWE model."""
|
||||
|
||||
from GPT_SoVITS.vendor.ap_bwe.models.model import APNet_BWE_Model, ConvNeXtBlock, get_padding
|
||||
|
||||
def get_padding(kernel_size, dilation=1):
|
||||
return int((kernel_size * dilation - dilation) / 2)
|
||||
|
||||
|
||||
class ConvNeXtBlock(nn.Module):
|
||||
"""ConvNeXt Block adapted from https://github.com/facebookresearch/ConvNeXt to 1D audio signal.
|
||||
|
||||
Args:
|
||||
dim (int): Number of input channels.
|
||||
layer_scale_init_value (float, optional): Initial value for the layer scale. Zero disables scaling.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
dim: int,
|
||||
layer_scale_init_value=0,
|
||||
):
|
||||
super().__init__()
|
||||
self.dwconv = nn.Conv1d(dim, dim, kernel_size=7, padding=3, groups=dim) # depthwise conv
|
||||
self.norm = nn.LayerNorm(dim, eps=1e-6)
|
||||
self.pwconv1 = nn.Linear(dim, dim * 3) # pointwise/1x1 convs, implemented with linear layers
|
||||
self.act = nn.GELU()
|
||||
self.pwconv2 = nn.Linear(dim * 3, dim)
|
||||
self.gamma = (
|
||||
nn.Parameter(layer_scale_init_value * torch.ones(dim), requires_grad=True)
|
||||
if layer_scale_init_value > 0
|
||||
else None
|
||||
)
|
||||
|
||||
def forward(self, x):
|
||||
residual = x
|
||||
x = self.dwconv(x)
|
||||
x = x.transpose(1, 2) # (B, C, T) -> (B, T, C)
|
||||
x = self.norm(x)
|
||||
x = self.pwconv1(x)
|
||||
x = self.act(x)
|
||||
x = self.pwconv2(x)
|
||||
if self.gamma is not None:
|
||||
x = self.gamma * x
|
||||
x = x.transpose(1, 2) # (B, T, C) -> (B, C, T)
|
||||
|
||||
x = residual + x
|
||||
return x
|
||||
|
||||
|
||||
class APNet_BWE_Model(torch.nn.Module):
|
||||
def __init__(self, h):
|
||||
super(APNet_BWE_Model, self).__init__()
|
||||
self.h = h
|
||||
layer_scale_init_value = 1 / h.ConvNeXt_layers
|
||||
|
||||
self.conv_pre_mag = nn.Conv1d(h.n_fft // 2 + 1, h.ConvNeXt_channels, 7, 1, padding=get_padding(7, 1))
|
||||
self.norm_pre_mag = nn.LayerNorm(h.ConvNeXt_channels, eps=1e-6)
|
||||
self.conv_pre_pha = nn.Conv1d(h.n_fft // 2 + 1, h.ConvNeXt_channels, 7, 1, padding=get_padding(7, 1))
|
||||
self.norm_pre_pha = nn.LayerNorm(h.ConvNeXt_channels, eps=1e-6)
|
||||
|
||||
self.convnext_mag = nn.ModuleList(
|
||||
[
|
||||
ConvNeXtBlock(
|
||||
dim=h.ConvNeXt_channels,
|
||||
layer_scale_init_value=layer_scale_init_value,
|
||||
)
|
||||
for _ in range(h.ConvNeXt_layers)
|
||||
]
|
||||
)
|
||||
|
||||
self.convnext_pha = nn.ModuleList(
|
||||
[
|
||||
ConvNeXtBlock(
|
||||
dim=h.ConvNeXt_channels,
|
||||
layer_scale_init_value=layer_scale_init_value,
|
||||
)
|
||||
for _ in range(h.ConvNeXt_layers)
|
||||
]
|
||||
)
|
||||
|
||||
self.norm_post_mag = nn.LayerNorm(h.ConvNeXt_channels, eps=1e-6)
|
||||
self.norm_post_pha = nn.LayerNorm(h.ConvNeXt_channels, eps=1e-6)
|
||||
self.apply(self._init_weights)
|
||||
self.linear_post_mag = nn.Linear(h.ConvNeXt_channels, h.n_fft // 2 + 1)
|
||||
self.linear_post_pha_r = nn.Linear(h.ConvNeXt_channels, h.n_fft // 2 + 1)
|
||||
self.linear_post_pha_i = nn.Linear(h.ConvNeXt_channels, h.n_fft // 2 + 1)
|
||||
|
||||
def _init_weights(self, m):
|
||||
if isinstance(m, (nn.Conv1d, nn.Linear)):
|
||||
nn.init.trunc_normal_(m.weight, std=0.02)
|
||||
nn.init.constant_(m.bias, 0)
|
||||
|
||||
def forward(self, mag_nb, pha_nb):
|
||||
x_mag = self.conv_pre_mag(mag_nb)
|
||||
x_pha = self.conv_pre_pha(pha_nb)
|
||||
x_mag = self.norm_pre_mag(x_mag.transpose(1, 2)).transpose(1, 2)
|
||||
x_pha = self.norm_pre_pha(x_pha.transpose(1, 2)).transpose(1, 2)
|
||||
|
||||
for conv_block_mag, conv_block_pha in zip(self.convnext_mag, self.convnext_pha):
|
||||
x_mag = x_mag + x_pha
|
||||
x_pha = x_pha + x_mag
|
||||
x_mag = conv_block_mag(x_mag)
|
||||
x_pha = conv_block_pha(x_pha)
|
||||
|
||||
x_mag = self.norm_post_mag(x_mag.transpose(1, 2))
|
||||
mag_wb = mag_nb + self.linear_post_mag(x_mag).transpose(1, 2)
|
||||
|
||||
x_pha = self.norm_post_pha(x_pha.transpose(1, 2))
|
||||
x_pha_r = self.linear_post_pha_r(x_pha)
|
||||
x_pha_i = self.linear_post_pha_i(x_pha)
|
||||
pha_wb = torch.atan2(x_pha_i, x_pha_r).transpose(1, 2)
|
||||
|
||||
com_wb = torch.stack((torch.exp(mag_wb) * torch.cos(pha_wb), torch.exp(mag_wb) * torch.sin(pha_wb)), dim=-1)
|
||||
|
||||
return mag_wb, pha_wb, com_wb
|
||||
__all__ = ["APNet_BWE_Model", "ConvNeXtBlock", "get_padding"]
|
||||
|
||||
@ -1,87 +1,16 @@
|
||||
"""Select optional AR acceleration for the requested device and precision."""
|
||||
"""Compatibility shim for acceleration capabilities and construction."""
|
||||
|
||||
from functools import lru_cache
|
||||
from importlib import import_module
|
||||
import logging
|
||||
import os
|
||||
from GPT_SoVITS.Accel.capabilities import ( # noqa: F401
|
||||
_flash_attention_module,
|
||||
cuda_graph_available,
|
||||
flash_attention_available,
|
||||
resolve_acceleration,
|
||||
)
|
||||
from GPT_SoVITS.Accel.factory import create_acceleration # noqa: F401
|
||||
|
||||
import torch
|
||||
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _cuda_available(device):
|
||||
return device.type == "cuda" and torch.cuda.is_available() and torch.version.cuda is not None
|
||||
|
||||
|
||||
def cuda_graph_available(device):
|
||||
device = torch.device(device)
|
||||
return bool(
|
||||
_cuda_available(device)
|
||||
and os.environ.get("CUDAGraph", "1") != "0"
|
||||
and callable(getattr(torch.cuda, "CUDAGraph", None))
|
||||
and callable(getattr(torch.cuda, "graph", None))
|
||||
and callable(getattr(torch.cuda, "Stream", None))
|
||||
and callable(getattr(torch.nn.functional, "scaled_dot_product_attention", None))
|
||||
)
|
||||
|
||||
|
||||
@lru_cache(maxsize=1)
|
||||
def _flash_attention_module():
|
||||
from tools.portable_runtime import _prepare_dlls
|
||||
|
||||
_prepare_dlls()
|
||||
try:
|
||||
return import_module("flash_attn")
|
||||
except (ImportError, OSError, RuntimeError) as exc:
|
||||
_logger.info("FlashAttention is unavailable: %s", exc)
|
||||
return None
|
||||
|
||||
|
||||
def flash_attention_available(device, dtype):
|
||||
device = torch.device(device)
|
||||
if not _cuda_available(device) or dtype not in (torch.float16, torch.bfloat16):
|
||||
return False
|
||||
if torch.cuda.get_device_capability(device)[0] < 8:
|
||||
return False
|
||||
module = _flash_attention_module()
|
||||
return callable(getattr(module, "flash_attn_with_kvcache", None))
|
||||
|
||||
|
||||
def resolve_acceleration(device, dtype, use_cuda_graph=True, use_flash_attention=True):
|
||||
graph = bool(use_cuda_graph and cuda_graph_available(device))
|
||||
if use_flash_attention and flash_attention_available(device, dtype):
|
||||
return "flash_attn_varlen_cuda_graph", graph
|
||||
if graph:
|
||||
return "torch_static_cuda_graph", True
|
||||
return None, False
|
||||
|
||||
|
||||
def create_acceleration(
|
||||
weights_path,
|
||||
device,
|
||||
dtype,
|
||||
max_batch_size=32,
|
||||
use_cuda_graph=True,
|
||||
use_flash_attention=True,
|
||||
max_seq_length=None,
|
||||
):
|
||||
backend, _ = resolve_acceleration(device, dtype, use_cuda_graph, use_flash_attention)
|
||||
if backend is None:
|
||||
return None
|
||||
try:
|
||||
from GPT_SoVITS.Accel.adapter import AccelInference
|
||||
import_module("GPT_SoVITS.Accel.PyTorch.AR.backends." + backend)
|
||||
except (ImportError, OSError, RuntimeError) as exc:
|
||||
_logger.warning("AR acceleration is unavailable; using ordinary inference: %s", exc)
|
||||
return None
|
||||
return AccelInference(
|
||||
weights_path,
|
||||
device=device,
|
||||
dtype=dtype,
|
||||
max_batch_size=max_batch_size,
|
||||
use_cuda_graph=use_cuda_graph,
|
||||
use_flash_attention=use_flash_attention,
|
||||
max_seq_length=max_seq_length,
|
||||
)
|
||||
__all__ = [
|
||||
"create_acceleration",
|
||||
"cuda_graph_available",
|
||||
"flash_attention_available",
|
||||
"resolve_acceleration",
|
||||
]
|
||||
|
||||
@ -1,42 +1,8 @@
|
||||
import os
|
||||
import json
|
||||
import torch
|
||||
import torchaudio.functional as aF
|
||||
"""Compatibility shim for the canonical AP-BWE inference adapter."""
|
||||
|
||||
from tools.AP_BWE_main.audio_ops import amp_pha_stft, amp_pha_istft
|
||||
from tools.AP_BWE_main.models.model import APNet_BWE_Model
|
||||
from GPT_SoVITS.inference.super_resolution import AP_BWE
|
||||
from GPT_SoVITS.runtime.paths import LEGACY_AP_BWE_CHECKPOINT_DIR
|
||||
|
||||
AP_BWE_main_dir_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "AP_BWE_main")
|
||||
AP_BWE_main_dir_path = str(LEGACY_AP_BWE_CHECKPOINT_DIR.parent)
|
||||
|
||||
|
||||
class AP_BWE:
|
||||
def __init__(self, device, DictToAttrRecursive, checkpoint_file=None):
|
||||
if checkpoint_file == None:
|
||||
checkpoint_file = "%s/24kto48k/g_24kto48k.zip" % (AP_BWE_main_dir_path)
|
||||
if os.path.exists(checkpoint_file) == False:
|
||||
raise FileNotFoundError
|
||||
config_file = os.path.join(os.path.split(checkpoint_file)[0], "config.json")
|
||||
with open(config_file) as f:
|
||||
data = f.read()
|
||||
json_config = json.loads(data)
|
||||
h = DictToAttrRecursive(json_config)
|
||||
model = APNet_BWE_Model(h).to(device)
|
||||
state_dict = torch.load(checkpoint_file, map_location="cpu", weights_only=False)
|
||||
model.load_state_dict(state_dict["generator"])
|
||||
model.eval()
|
||||
self.device = device
|
||||
self.model = model
|
||||
self.h = h
|
||||
|
||||
def to(self, *arg, **kwargs):
|
||||
self.model.to(*arg, **kwargs)
|
||||
self.device = self.model.conv_pre_mag.weight.device
|
||||
return self
|
||||
|
||||
def __call__(self, audio, orig_sampling_rate):
|
||||
with torch.no_grad():
|
||||
audio = aF.resample(audio, orig_freq=orig_sampling_rate, new_freq=self.h.hr_sampling_rate)
|
||||
amp_nb, pha_nb, com_nb = amp_pha_stft(audio, self.h.n_fft, self.h.hop_size, self.h.win_size)
|
||||
amp_wb_g, pha_wb_g, com_wb_g = self.model(amp_nb, pha_nb)
|
||||
audio_hr_g = amp_pha_istft(amp_wb_g, pha_wb_g, self.h.n_fft, self.h.hop_size, self.h.win_size)
|
||||
return audio_hr_g.squeeze().cpu().numpy(), self.h.hr_sampling_rate
|
||||
__all__ = ["AP_BWE", "AP_BWE_main_dir_path"]
|
||||
|
||||
@ -1,28 +1,5 @@
|
||||
import json
|
||||
import locale
|
||||
from pathlib import Path
|
||||
"""Compatibility shim for GPT_SoVITS.runtime.i18n."""
|
||||
|
||||
I18N_JSON_DIR = Path(__file__).resolve().parent / "locale"
|
||||
from GPT_SoVITS.runtime.i18n.i18n import I18N_JSON_DIR, I18nAuto, load_language_list
|
||||
|
||||
|
||||
def load_language_list(language):
|
||||
with open(I18N_JSON_DIR / f"{language}.json", "r", encoding="utf-8") as f:
|
||||
language_list = json.load(f)
|
||||
return language_list
|
||||
|
||||
|
||||
class I18nAuto:
|
||||
def __init__(self, language=None):
|
||||
if language in ["Auto", None]:
|
||||
language = locale.getdefaultlocale()[0]
|
||||
# getlocale can't identify the system's language ((None, None))
|
||||
if not (I18N_JSON_DIR / f"{language}.json").exists():
|
||||
language = "en_US"
|
||||
self.language = language
|
||||
self.language_map = load_language_list(language)
|
||||
|
||||
def __call__(self, key):
|
||||
return self.language_map.get(key, key)
|
||||
|
||||
def __repr__(self):
|
||||
return "Use Language: " + self.language
|
||||
__all__ = ["I18N_JSON_DIR", "I18nAuto", "load_language_list"]
|
||||
|
||||
@ -1,114 +1,4 @@
|
||||
"""Runtime initialization for the bundled GPT-SoVITS environment."""
|
||||
"""Compatibility shim for the canonical GPT_SoVITS.runtime.portable module."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
from importlib import import_module
|
||||
from importlib.machinery import ModuleSpec
|
||||
from importlib.metadata import version
|
||||
from pathlib import Path
|
||||
from threading import RLock
|
||||
from types import ModuleType
|
||||
|
||||
PROJECT_ROOT = Path(__file__).resolve().parents[1]
|
||||
RUNTIME_DIR = PROJECT_ROOT / "runtime"
|
||||
SITE_PACKAGES = RUNTIME_DIR / "Lib" / "site-packages"
|
||||
|
||||
|
||||
def _resolve_binary(bundled_name: str, system_name: str) -> str:
|
||||
bundled = RUNTIME_DIR / bundled_name
|
||||
if bundled.exists():
|
||||
return str(bundled)
|
||||
return shutil.which(system_name) or system_name
|
||||
|
||||
|
||||
FFMPEG_EXE = _resolve_binary("ffmpeg.exe", "ffmpeg")
|
||||
FFPROBE_EXE = _resolve_binary("ffprobe.exe", "ffprobe")
|
||||
_DLL_HANDLES = []
|
||||
_DLL_READY = False
|
||||
_ACTIVE = False
|
||||
_FLASH_IMPORT_READY = False
|
||||
_FLASH_IMPORT_LOCK = RLock()
|
||||
|
||||
|
||||
def _prepare_dlls() -> None:
|
||||
global _DLL_READY
|
||||
if _DLL_READY or os.name != "nt":
|
||||
return
|
||||
package_directories = [SITE_PACKAGES, Path(sys.prefix) / "Lib" / "site-packages"]
|
||||
directories = [
|
||||
RUNTIME_DIR,
|
||||
*(packages / "torch" / "lib" for packages in package_directories),
|
||||
PROJECT_ROOT / "GPT_SoVITS" / "Accel" / "vendor" / "cuda" / "bin",
|
||||
*(directory for packages in package_directories
|
||||
for directory in sorted((packages / "nvidia").glob("*/bin"))),
|
||||
]
|
||||
for directory in dict.fromkeys(directories):
|
||||
if directory.is_dir():
|
||||
_DLL_HANDLES.append(os.add_dll_directory(str(directory)))
|
||||
# cuDNN dynamically loads its component DLLs through the process PATH.
|
||||
os.environ["PATH"] = str(directory) + os.pathsep + os.environ.get("PATH", "")
|
||||
_DLL_READY = True
|
||||
|
||||
|
||||
def _lazy_apply_rotary_emb(*args, **kwargs):
|
||||
return import_module("flash_attn.layers.rotary").apply_rotary_emb(*args, **kwargs)
|
||||
|
||||
|
||||
def prepare_transformers_flash_attention() -> None:
|
||||
global _FLASH_IMPORT_READY
|
||||
with _FLASH_IMPORT_LOCK:
|
||||
if _FLASH_IMPORT_READY:
|
||||
return
|
||||
_prepare_dlls()
|
||||
import_utils = import_module("transformers.utils.import_utils")
|
||||
if import_utils.is_flash_attn_2_available():
|
||||
from tools.acceleration import _flash_attention_module
|
||||
|
||||
if _flash_attention_module() is None:
|
||||
import_utils.is_flash_attn_2_available = lambda: False
|
||||
import_module("transformers.utils").is_flash_attn_2_available = import_utils.is_flash_attn_2_available
|
||||
if os.name != "nt" or version("transformers") != "4.51.3":
|
||||
_FLASH_IMPORT_READY = True
|
||||
return
|
||||
# Transformers 4.51.3 imports Triton rotary even for BERT/HuBERT, which never use it.
|
||||
rotary_name = "flash_attn.layers.rotary"
|
||||
previous_rotary = sys.modules.get(rotary_name)
|
||||
if previous_rotary is None:
|
||||
rotary = ModuleType(rotary_name)
|
||||
rotary.__spec__ = ModuleSpec(rotary_name, loader=None)
|
||||
rotary.apply_rotary_emb = _lazy_apply_rotary_emb
|
||||
sys.modules[rotary_name] = rotary
|
||||
try:
|
||||
import_module("transformers.modeling_flash_attention_utils")
|
||||
finally:
|
||||
if previous_rotary is None:
|
||||
sys.modules.pop(rotary_name, None)
|
||||
_FLASH_IMPORT_READY = True
|
||||
|
||||
|
||||
def activate(*, change_cwd: bool = False) -> None:
|
||||
global _ACTIVE
|
||||
if change_cwd:
|
||||
os.chdir(PROJECT_ROOT)
|
||||
if not _ACTIVE:
|
||||
sys.path.insert(0, str(PROJECT_ROOT))
|
||||
sys.path.insert(0, str(PROJECT_ROOT / "GPT_SoVITS"))
|
||||
if RUNTIME_DIR.is_dir():
|
||||
os.environ["PATH"] = str(RUNTIME_DIR) + os.pathsep + os.environ.get("PATH", "")
|
||||
os.environ.setdefault("G2PW", "0")
|
||||
nltk_data = RUNTIME_DIR / "nltk_data"
|
||||
if not nltk_data.is_dir():
|
||||
nltk_data = PROJECT_ROOT / ".codex" / "runtime-cache" / "nltk_data"
|
||||
if nltk_data.is_dir():
|
||||
os.environ.setdefault("NLTK_DATA", str(nltk_data))
|
||||
try:
|
||||
import _distutils_hack
|
||||
_distutils_hack.add_shim()
|
||||
except ImportError:
|
||||
pass
|
||||
_prepare_dlls()
|
||||
_ACTIVE = True
|
||||
prepare_transformers_flash_attention()
|
||||
from GPT_SoVITS.runtime.portable import * # noqa: F401,F403
|
||||
from GPT_SoVITS.runtime.portable import _prepare_dlls
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user