Spaces:
Sleeping
Sleeping
File size: 7,810 Bytes
da8d589 374f426 9d9fe0d d2b7e94 374f426 d2b7e94 bed01bd 374f426 d2b7e94 374f426 d2b7e94 f83b1b7 374f426 ae79826 374f426 da8d589 374f426 da8d589 374f426 da8d589 503e823 da8d589 627d3d7 da8d589 374f426 503e823 ae79826 1df74c6 bed01bd 9d9fe0d ae79826 374f426 bed01bd 374f426 da8d589 374f426 bed01bd 374f426 bed01bd 1df74c6 bed01bd ae79826 bed01bd ae79826 374f426 f83b1b7 374f426 f83b1b7 503e823 374f426 da8d589 374f426 da8d589 1df74c6 bed01bd 9d9fe0d 374f426 bed01bd 374f426 bed01bd 374f426 da8d589 374f426 bed01bd 374f426 da8d589 bed01bd da8d589 bed01bd 374f426 bed01bd 374f426 bed01bd 374f426 1df74c6 bed01bd 374f426 bed01bd da8d589 bed01bd ae79826 374f426 503e823 9d9fe0d 374f426 503e823 f367757 374f426 f367757 374f426 f367757 374f426 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 |
from typing import Union
import gradio as gr
import numpy as np
import torch
import torch.profiler
from modules import refiner
from modules.api.impl.handler.SSMLHandler import SSMLHandler
from modules.api.impl.handler.TTSHandler import TTSHandler
from modules.api.impl.model.audio_model import AdjustConfig
from modules.api.impl.model.chattts_model import ChatTTSConfig, InferConfig
from modules.api.impl.model.enhancer_model import EnhancerConfig
from modules.api.utils import calc_spk_style
from modules.data import styles_mgr
from modules.Enhancer.ResembleEnhance import apply_audio_enhance as _apply_audio_enhance
from modules.normalization import text_normalize
from modules.SentenceSplitter import SentenceSplitter
from modules.speaker import Speaker, speaker_mgr
from modules.ssml_parser.SSMLParser import SSMLBreak, SSMLSegment, create_ssml_parser
from modules.utils import audio
from modules.utils.hf import spaces
from modules.webui import webui_config
def get_speakers():
return speaker_mgr.list_speakers()
def get_speaker_names() -> tuple[list[Speaker], list[str]]:
speakers = get_speakers()
def get_speaker_show_name(spk):
if spk.gender == "*" or spk.gender == "":
return spk.name
return f"{spk.gender} : {spk.name}"
speaker_names = [get_speaker_show_name(speaker) for speaker in speakers]
speaker_names.sort(key=lambda x: x.startswith("*") and "-1" or x)
return speakers, speaker_names
def get_styles():
return styles_mgr.list_items()
def load_spk_info(file):
if file is None:
return "empty"
try:
spk: Speaker = Speaker.from_file(file)
infos = spk.to_json()
return f"""
- name: {infos.name}
- gender: {infos.gender}
- describe: {infos.describe}
""".strip()
except:
return "load failed"
def segments_length_limit(
segments: list[Union[SSMLBreak, SSMLSegment]], total_max: int
) -> list[Union[SSMLBreak, SSMLSegment]]:
ret_segments = []
total_len = 0
for seg in segments:
if isinstance(seg, SSMLBreak):
ret_segments.append(seg)
continue
total_len += len(seg["text"])
if total_len > total_max:
break
ret_segments.append(seg)
return ret_segments
@torch.inference_mode()
@spaces.GPU(duration=120)
def apply_audio_enhance(audio_data, sr, enable_denoise, enable_enhance):
return _apply_audio_enhance(audio_data, sr, enable_denoise, enable_enhance)
@torch.inference_mode()
@spaces.GPU(duration=120)
def synthesize_ssml(
ssml: str,
batch_size=4,
enable_enhance=False,
enable_denoise=False,
eos: str = "[uv_break]",
spliter_thr: int = 100,
pitch: float = 0,
speed_rate: float = 1,
volume_gain_db: float = 0,
normalize: bool = True,
headroom: float = 1,
progress=gr.Progress(track_tqdm=True),
):
try:
batch_size = int(batch_size)
except Exception:
batch_size = 8
ssml = ssml.strip()
if ssml == "":
raise gr.Error("SSML is empty, please input some SSML")
parser = create_ssml_parser()
segments = parser.parse(ssml)
max_len = webui_config.ssml_max
segments = segments_length_limit(segments, max_len)
if len(segments) == 0:
raise gr.Error("No valid segments in SSML")
infer_config = InferConfig(
batch_size=batch_size,
spliter_threshold=spliter_thr,
eos=eos,
# NOTE: SSML not support `infer_seed` contorl
# seed=42,
)
adjust_config = AdjustConfig(
pitch=pitch,
speed_rate=speed_rate,
volume_gain_db=volume_gain_db,
normalize=normalize,
headroom=headroom,
)
enhancer_config = EnhancerConfig(
enabled=enable_denoise or enable_enhance or False,
lambd=0.9 if enable_denoise else 0.1,
)
handler = SSMLHandler(
ssml_content=ssml,
infer_config=infer_config,
adjust_config=adjust_config,
enhancer_config=enhancer_config,
)
audio_data, sr = handler.enqueue()
# NOTE: 这里必须要加,不然 gradio 没法解析成 mp3 格式
audio_data = audio.audio_to_int16(audio_data)
return sr, audio_data
# @torch.inference_mode()
@spaces.GPU(duration=120)
def tts_generate(
text,
temperature=0.3,
top_p=0.7,
top_k=20,
spk=-1,
infer_seed=-1,
use_decoder=True,
prompt1="",
prompt2="",
prefix="",
style="",
disable_normalize=False,
batch_size=4,
enable_enhance=False,
enable_denoise=False,
spk_file=None,
spliter_thr: int = 100,
eos: str = "[uv_break]",
pitch: float = 0,
speed_rate: float = 1,
volume_gain_db: float = 0,
normalize: bool = True,
headroom: float = 1,
progress=gr.Progress(track_tqdm=True),
):
try:
batch_size = int(batch_size)
except Exception:
batch_size = 4
max_len = webui_config.tts_max
text = text.strip()[0:max_len]
if text == "":
raise gr.Error("Text is empty, please input some text")
if style == "*auto":
style = ""
if isinstance(top_k, float):
top_k = int(top_k)
params = calc_spk_style(spk=spk, style=style)
spk = params.get("spk", spk)
infer_seed = infer_seed or params.get("seed", infer_seed)
temperature = temperature or params.get("temperature", temperature)
prefix = prefix or params.get("prefix", prefix)
prompt1 = prompt1 or params.get("prompt1", "")
prompt2 = prompt2 or params.get("prompt2", "")
infer_seed = np.clip(infer_seed, -1, 2**32 - 1, out=None, dtype=np.float64)
infer_seed = int(infer_seed)
if isinstance(spk, int):
spk = Speaker.from_seed(spk)
if spk_file:
try:
spk: Speaker = Speaker.from_file(spk_file)
except Exception:
raise gr.Error("Failed to load speaker file")
if not isinstance(spk.emb, torch.Tensor):
raise gr.Error("Speaker file is not supported")
tts_config = ChatTTSConfig(
style=style,
temperature=temperature,
top_k=top_k,
top_p=top_p,
prefix=prefix,
prompt1=prompt1,
prompt2=prompt2,
)
infer_config = InferConfig(
batch_size=batch_size,
spliter_threshold=spliter_thr,
eos=eos,
seed=infer_seed,
)
adjust_config = AdjustConfig(
pitch=pitch,
speed_rate=speed_rate,
volume_gain_db=volume_gain_db,
normalize=normalize,
headroom=headroom,
)
enhancer_config = EnhancerConfig(
enabled=enable_denoise or enable_enhance or False,
lambd=0.9 if enable_denoise else 0.1,
)
handler = TTSHandler(
text_content=text,
spk=spk,
tts_config=tts_config,
infer_config=infer_config,
adjust_config=adjust_config,
enhancer_config=enhancer_config,
)
audio_data, sample_rate = handler.enqueue()
# NOTE: 这里必须要加,不然 gradio 没法解析成 mp3 格式
audio_data = audio.audio_to_int16(audio_data)
return sample_rate, audio_data
@torch.inference_mode()
@spaces.GPU(duration=120)
def refine_text(
text: str,
prompt: str,
progress=gr.Progress(track_tqdm=True),
):
text = text_normalize(text)
return refiner.refine_text(text, prompt=prompt)
@torch.inference_mode()
@spaces.GPU(duration=120)
def split_long_text(long_text_input, spliter_threshold=100, eos=""):
spliter = SentenceSplitter(threshold=spliter_threshold)
sentences = spliter.parse(long_text_input)
sentences = [text_normalize(s) + eos for s in sentences]
data = []
for i, text in enumerate(sentences):
token_length = spliter.count_tokens(text)
data.append([i, text, token_length])
return data
|