Spaces:
Running
Running
File size: 17,109 Bytes
0c3ae0b 3b561b2 0c43594 c99413a 0c43594 3b561b2 59005cf e84b34f 0dcd7ee d28b080 a3a78ff 0dcd7ee 2db93aa 7ab98f2 2db93aa 0dcd7ee e84b34f ed3cf42 953a75a e84b34f 7ab98f2 e84b34f 888d297 0dcd7ee e84b34f 05c5e6f 6eef917 e84b34f 10dd9d7 687d525 10dd9d7 8adced8 fb47690 8adced8 5446ba7 f3a2a3b 06f3d1a 80162ec e47f71a 953a75a 06f3d1a f3a2a3b e84b34f 2db93aa ed3cf42 bf6e615 0c43594 47557e6 9f23b12 66c74b5 2f5c596 9f23b12 5446ba7 bf6e615 ed3cf42 bf6e615 58187c4 cf92956 58187c4 e149b71 6185ee4 58187c4 2f5c596 58187c4 19a1607 58187c4 2f830d3 7d94294 a8cd8f3 6eef917 58187c4 aa46a87 60c4763 2f830d3 57ec990 2f830d3 8b4b8b8 4f0eb11 c99413a 4f0eb11 b28bd1a 4a238c0 fe50d5a 23dca17 fe50d5a 23dca17 97b3e55 a8cd8f3 97b3e55 a8cd8f3 fe50d5a 9e3ae38 268fc4f bc06890 23dca17 101a87f 0f4e6bf fe50d5a 80162ec fe50d5a 5c18fbf 58187c4 d023960 58187c4 18a354d 0490910 18a354d 6185ee4 268fc4f 5e2a8be 58187c4 50ec890 62af528 0f4e6bf 268fc4f 5e2a8be 268fc4f 09b7ce7 906a82c 268fc4f 58187c4 ed3cf42 58187c4 ed3cf42 58187c4 f6168ab 4a238c0 58187c4 09b7ce7 5e2a8be f91c972 58187c4 f3a2a3b e84b34f 5e2a8be b72f6c5 50ec890 b72f6c5 6db6a42 0c43594 9f23b12 f3a2a3b 03deed5 f3a2a3b 0c43594 03deed5 |
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 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 |
enhanced_accessibility = False #@param {type:"boolean"}
#@markdown ---
#@markdown #### Please select your language:
#lang_select = "English" #@param ["English", "Spanish"]
#if lang_select == "English":
# lang = "en"
#elif lang_select == "Spanish":
# lang = "es"
#else:
# raise Exception("Language not supported.")
#@markdown ---
use_gpu = False #@param {type:"boolean"}
from fastapi import FastAPI, Request, Form
from fastapi.responses import HTMLResponse
from fastapi.responses import FileResponse
from fastapi.templating import Jinja2Templates
from fastapi.staticfiles import StaticFiles
# ...
# Mount a directory to serve static files (e.g., CSS and JavaScript)
import logging
app = FastAPI()
app.mount("/static", StaticFiles(directory="static"), name="static")
templates = Jinja2Templates(directory="templates")
files = {}
# Configure logging
logging.basicConfig(level=logging.DEBUG)
# Mock data for your interface
data = {
"speaker_options": ["en","en-us","en-029","n-gb-x-gbclan","en-gb-x-rp","en-gb-scotland","en-gb-gbcwmd", "es", "de", "pl","ar","be","bn","bpy","bs","bg","ca","yue","hak","haw","cmn","hr","cs","da","nl","eo","et","fa","fa-latn","fi","fr-be","fr","ga","gd","ka","grc","el","kl","gn","gu","ht","he","hi","hu","id","io","it","ja","kn","kok","ko","ku","kk","ky","la","lb","ltg","lv","lfn","lt","jbo","mi","mk","ms","ml","mt","mr","nci","ne","nb","nog","or","om","pap","pt-br","pt","ro","ru","ru-lv","uk","sjn","sr","tn","sd","shn","si","sk","sl","es","es-419","sw","sv","ta","th","tk","tt","te","tr","ug","ur","uz","vi-vn-x-central","vi","vi0vn-x-south"],
"default_speaker": "en",
}
@app.get("/", response_class=HTMLResponse)
async def read_root(request: Request):
return templates.TemplateResponse("interface.html", {"request": request, "data": data})
import json
import logging
import math
import sys
from pathlib import Path
from enum import Enum
from typing import Iterable, List, Optional, Union
import numpy as np
import onnxruntime
import glob
#import ipywidgets as widgets
from pydub import AudioSegment
import tempfile
import uuid
import soundfile as sf
#from IPython.display import display, Audio, Markdown, clear_output
from piper_phonemize import phonemize_codepoints, phonemize_espeak, tashkeel_run
_LOGGER = logging.getLogger("piper_train.infer_onnx")
import os
#if not os.path.exists("./content/piper/src/python/lng"):
# import subprocess
# command = "cp -r ./content/piper/notebooks/lng ./content/piper/src/python/lng"
# subprocess.run(command, shell=True)
import sys
#sys.path.append('/content/piper/notebooks')
sys.path.append('./content/piper/src/python')
import configparser
class Translator:
def __init__(self):
self.configs = {}
def load_language(self, language_name):
if language_name not in self.configs:
config = configparser.ConfigParser()
config.read(os.path.join(os.getcwd(), "lng", f"{language_name}.lang"))
self.configs[language_name] = config
def translate(self, language_name, string):
if language_name == "en":
return string
elif language_name not in self.configs:
self.load_language(language_name)
config = self.configs[language_name]
try:
return config.get("Strings", string)
except (configparser.NoOptionError, configparser.NoSectionError):
if string:
return string
else:
raise Exception("language engine error: This translation is corrupt!")
return 0
#from translator import *
lan = Translator()
def detect_onnx_models(path):
onnx_models = glob.glob(path + '/*.onnx')
if len(onnx_models) > 1:
return onnx_models
elif len(onnx_models) == 1:
return onnx_models[0]
else:
return None
renamed_audio_file = None
#@app.post("/synthesize")
#@app.post("/", response_class=FileResponse)
@app.post("/", response_class=HTMLResponse)
async def main(
request: Request,
text_input: str = Form(...),
speaker: str = Form(...),
speed_slider: float = Form(1.0),
noise_scale_slider: float = Form(0.667),
noise_scale_w_slider: float = Form(1.0),
play: bool = Form(True)
):
"""Main entry point"""
sys.path.append('./content/piper/src/python')
models_path = "./content/piper/src/python"
logging.basicConfig(level=logging.DEBUG)
providers = [
"CPUExecutionProvider"
if use_gpu is False
else ("CUDAExecutionProvider", {"cudnn_conv_algo_search": "DEFAULT"})
]
sess_options = onnxruntime.SessionOptions()
model = None
lang = speaker
onnx_models = detect_onnx_models(models_path)
if len(text_input) == 0:
text_input = "1, 2, 3. This is a test. Enter some text to generate."
# speaker_selection = widgets.Dropdown(
# options=[],
# description=f'{lan.translate(lang, "Select speaker")}:',
# layout={'visibility': 'hidden'}
# )
if onnx_models is None:
if enhanced_accessibility:
playaudio("novoices")
raise Exception(lan.translate(lang, "No downloaded voice packages!"))
elif isinstance(onnx_models, str):
onnx_model = onnx_models
model, config = load_onnx(onnx_model, sess_options, providers)
config["espeak"]["voice"] = speaker
config["inference"]["noise_scale"] = noise_scale_slider
config["inference"]["length_scale"] = speed_slider
config["inference"]["noise_w"] = noise_scale_w_slider
# lan.load_language(speaker)
print("nuber of speakers = ", config["num_speakers"])
print("speaker", speaker)
print("language", config["espeak"]["voice"])
# rate = speed_slider.value
# noise_scale = noise_scale_slider.value
# noise_scale_w = noise_scale_w_slider.value
auto_play = play
audio = inferencing(model, config, 1, text_input, speed_slider, noise_scale_slider, noise_scale_w_slider, auto_play)
temp_dir = tempfile.mkdtemp()
# Create a temporary directory to store the audio files
#temp_dir = tempfile.mkdtemp()
# Export the audio to an MP3 file in the temporary directory
# temp_audio_file = os.path.join(temp_dir, "generated_audio.mp3")
# Check if text_input is more than 200 characters
if len(text_input) > 200:
# Truncate text_input to 200 characters
text_input = text_input[:200]
# Rename the audio file based on the text input
renamed_audio_file = os.path.join(temp_dir, f"{text_input}.mp3")
audio.export(renamed_audio_file, format="mp3")
# Save the generated audio as a temporary file
filepath = renamed_audio_file
# Generate a unique file ID
file_id = str(uuid.uuid4())
# Store the file path with the generated file ID
files[file_id] = filepath
# Create a URL to download the file
file_url = f'/download?fileId={file_id}'
# os.rename(temp_audio_file, renamed_audio_file)
# Specify the path to your MP3 audio file
# audio_file_path = "path/to/your/audio.mp3"
# Check if the file exists
# if not os.path.exists(audio_file_path):
# return {"detail": "Audio file not found"}
# temp_audio_file = tempfile.NamedTemporaryFile(delete=False, suffix=".mp3")
# audio.export(temp_audio_file.name, format="mp3")
# Rename the temporary audio file based on the text input
# global renamed_audio_file
# renamed_audio_file = os.path.join(tempfile.gettempdir(), f"{text_input}.mp3")
# os.rename(temp_audio_file.name, renamed_audio_file)
else:
voice_model_names = []
for current in onnx_models:
voice_struct = current.split("/")[5]
voice_model_names.append(voice_struct)
# if enhanced_accessibility:
# playaudio("selectmodel")
# selection = widgets.Dropdown(
# options=voice_model_names,
# description=f'{lan.translate(lang, "Select voice package")}:',
# )
# load_btn = widgets.Button(
# description=lan.translate(lang, "Load it!")
# )
# config = None
# def load_model(button):
# nonlocal config
# global onnx_model
# nonlocal model
# nonlocal models_path
# selected_voice = selection.value
# onnx_model = f"{models_path}/{selected_voice}"
# model, config = load_onnx(onnx_model, sess_options, providers)
# if enhanced_accessibility:
# playaudio("loaded")
# if config["num_speakers"] > 1:
# speaker_selection.options = config["speaker_id_map"].values()
# speaker_selection.layout.visibility = 'visible'
# if enhanced_accessibility:
# playaudio("multispeaker")
# else:
# speaker_selection.layout.visibility = 'hidden'
# load_btn.on_click(load_model)
# display(selection, load_btn)
# display(speaker_selection)
# Save the audio as a temporary WAV file
return templates.TemplateResponse("interface.html", {"request": request, "file_url": file_url, "data": data})
# Serve the audio file with the correct media type
# return FileResponse(renamed_audio_file)
# return {"message": f"Text to synthesize: {text_input}, Speed: {speed_slider}, Play: {play}"}
@app.get("/download")
async def download_file(fileId: str):
# Retrieve the file path from the dictionary using the file ID
filepath = files.get(fileId)
if filepath:
# Create a FileResponse to serve the file for download
return FileResponse(filepath, headers={"Content-Disposition": "attachment"})
else:
return {"error": "File not found"}
def load_onnx(model, sess_options, providers = ["CPUExecutionProvider"]):
_LOGGER.debug("Loading model from %s", model)
config = load_config(model)
model = onnxruntime.InferenceSession(
str(model),
sess_options=sess_options,
providers= providers
)
_LOGGER.info("Loaded model from %s", model)
return model, config
def load_config(model):
with open(f"{model}.json", "r") as file:
config = json.load(file)
return config
PAD = "_" # padding (0)
BOS = "^" # beginning of sentence
EOS = "$" # end of sentence
class PhonemeType(str, Enum):
ESPEAK = "espeak"
TEXT = "text"
def phonemize(config, text: str) -> List[List[str]]:
"""Text to phonemes grouped by sentence."""
if config["phoneme_type"] == PhonemeType.ESPEAK:
if config["espeak"]["voice"] == "ar":
# Arabic diacritization
# https://github.com/mush42/libtashkeel/
text = tashkeel_run(text)
return phonemize_espeak(text, config["espeak"]["voice"])
if config["phoneme_type"] == PhonemeType.TEXT:
return phonemize_codepoints(text)
raise ValueError(f'Unexpected phoneme type: {config["phoneme_type"]}')
def phonemes_to_ids(config, phonemes: List[str]) -> List[int]:
"""Phonemes to ids."""
id_map = config["phoneme_id_map"]
ids: List[int] = list(id_map[BOS])
for phoneme in phonemes:
if phoneme not in id_map:
print("Missing phoneme from id map: %s", phoneme)
continue
ids.extend(id_map[phoneme])
ids.extend(id_map[PAD])
ids.extend(id_map[EOS])
return ids
def audio_float_to_int16(
audio: np.ndarray, max_wav_value: float = 32767.0
) -> np.ndarray:
"""Normalize audio and convert to int16 range"""
audio_norm = audio * (max_wav_value / max(0.01, np.max(np.abs(audio))))
audio_norm = np.clip(audio_norm, -max_wav_value, max_wav_value)
audio_norm = audio_norm.astype("int16")
return audio_norm
def inferencing(model, config, sid, line, length_scale, noise_scale, noise_scale_w, auto_play=True):
audios = []
if config["phoneme_type"] == "PhonemeType.ESPEAK":
config["phoneme_type"] = "espeak"
text = phonemize(config, line)
for phonemes in text:
phoneme_ids = phonemes_to_ids(config, phonemes)
num_speakers = config["num_speakers"]
if num_speakers == 1:
speaker_id = None # for now
else:
speaker_id = sid
text = np.expand_dims(np.array(phoneme_ids, dtype=np.int64), 0)
text_lengths = np.array([text.shape[1]], dtype=np.int64)
scales = np.array(
[noise_scale, length_scale, noise_scale_w],
dtype=np.float32,
)
sid = None
if speaker_id is not None:
sid = np.array([speaker_id], dtype=np.int64)
audio = model.run(
None,
{
"input": text,
"input_lengths": text_lengths,
"scales": scales,
"sid": sid,
},
)[0].squeeze((0, 1))
audio = audio_float_to_int16(audio.squeeze())
audios.append(audio)
merged_audio = np.concatenate(audios)
sample_rate = config["audio"]["sample_rate"]
temp_audio_path = os.path.join(tempfile.gettempdir(), "generated_audio.wav")
sf.write(temp_audio_path, merged_audio, config["audio"]["sample_rate"])
audio = AudioSegment.from_mp3(temp_audio_path)
return audio
# return FileResponse(temp_audio_path)
# Return the audio file as a FastAPI response
# display(Markdown(f"{line}"))
# display(Audio(merged_audio, rate=sample_rate, autoplay=auto_play))
def denoise(
audio: np.ndarray, bias_spec: np.ndarray, denoiser_strength: float
) -> np.ndarray:
audio_spec, audio_angles = transform(audio)
a = bias_spec.shape[-1]
b = audio_spec.shape[-1]
repeats = max(1, math.ceil(b / a))
bias_spec_repeat = np.repeat(bias_spec, repeats, axis=-1)[..., :b]
audio_spec_denoised = audio_spec - (bias_spec_repeat * denoiser_strength)
audio_spec_denoised = np.clip(audio_spec_denoised, a_min=0.0, a_max=None)
audio_denoised = inverse(audio_spec_denoised, audio_angles)
return audio_denoised
def stft(x, fft_size, hopsamp):
"""Compute and return the STFT of the supplied time domain signal x.
Args:
x (1-dim Numpy array): A time domain signal.
fft_size (int): FFT size. Should be a power of 2, otherwise DFT will be used.
hopsamp (int):
Returns:
The STFT. The rows are the time slices and columns are the frequency bins.
"""
window = np.hanning(fft_size)
fft_size = int(fft_size)
hopsamp = int(hopsamp)
return np.array(
[
np.fft.rfft(window * x[i : i + fft_size])
for i in range(0, len(x) - fft_size, hopsamp)
]
)
def istft(X, fft_size, hopsamp):
"""Invert a STFT into a time domain signal.
Args:
X (2-dim Numpy array): Input spectrogram. The rows are the time slices and columns are the frequency bins.
fft_size (int):
hopsamp (int): The hop size, in samples.
Returns:
The inverse STFT.
"""
fft_size = int(fft_size)
hopsamp = int(hopsamp)
window = np.hanning(fft_size)
time_slices = X.shape[0]
len_samples = int(time_slices * hopsamp + fft_size)
x = np.zeros(len_samples)
for n, i in enumerate(range(0, len(x) - fft_size, hopsamp)):
x[i : i + fft_size] += window * np.real(np.fft.irfft(X[n]))
return x
def inverse(magnitude, phase):
recombine_magnitude_phase = np.concatenate(
[magnitude * np.cos(phase), magnitude * np.sin(phase)], axis=1
)
x_org = recombine_magnitude_phase
n_b, n_f, n_t = x_org.shape # pylint: disable=unpacking-non-sequence
x = np.empty([n_b, n_f // 2, n_t], dtype=np.complex64)
x.real = x_org[:, : n_f // 2]
x.imag = x_org[:, n_f // 2 :]
inverse_transform = []
for y in x:
y_ = istft(y.T, fft_size=1024, hopsamp=256)
inverse_transform.append(y_[None, :])
inverse_transform = np.concatenate(inverse_transform, 0)
return inverse_transform
def transform(input_data):
x = input_data
real_part = []
imag_part = []
for y in x:
y_ = stft(y, fft_size=1024, hopsamp=256).T
real_part.append(y_.real[None, :, :]) # pylint: disable=unsubscriptable-object
imag_part.append(y_.imag[None, :, :]) # pylint: disable=unsubscriptable-object
real_part = np.concatenate(real_part, 0)
imag_part = np.concatenate(imag_part, 0)
magnitude = np.sqrt(real_part**2 + imag_part**2)
phase = np.arctan2(imag_part.data, real_part.data)
return magnitude, phase
#@app.get("/")
#async def read_root(request: Request):
# return templates.TemplateResponse("interface.html", {"request": request})
if __name__ == "__main__":
# main()
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=7860)
# main()
# pass
# app()
# Create an instance of the FastAPI class
#app = main()
# Define a route for the root endpoint
#def read_root():
# return {"message": "Hello, World!"} |