File size: 9,526 Bytes
524409f | 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 | import io
import os
import re
import unicodedata
import logging
import numpy as np
import torch
import soundfile as sf
import torchaudio
from fastapi import FastAPI, HTTPException, UploadFile, File, Form
from fastapi.responses import StreamingResponse
from transformers import SpeechT5Processor, SpeechT5ForTextToSpeech, SpeechT5HifiGan
from speechbrain.pretrained import EncoderClassifier
from denoiser import pretrained
from typing import Optional
from phonemizer import phonemize
from phonemizer.backend import EspeakBackend
import re
# ββ Logging βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# ββ Paths β models loaded from filesystem via symlink ./models β /tmp/models ββ
MODEL_DIR = os.environ.get("MODEL_DIR", "./models/urdu-speecht5-finetuned")
PROCESSOR_DIR = os.environ.get("PROCESSOR_DIR", "./models/urdu-tts-processor")
VOCODER_DIR = os.environ.get("VOCODER_DIR", "./models/speecht5-hifigan")
SPKREC_DIR = os.environ.get("SPKREC_DIR", "./models/spkrec-xvect-voxceleb")
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
logger.info(f"Using device: {DEVICE}")
# ββ Standalone Urdu normalization (no urduhack / tensorflow dependency) ββββββββ
_PUNCT_MAP = str.maketrans({
"Ωͺ": "%", "Ω«": ".", "Ω¬": ",",
"\u060c": "Ψ",
"\u200f": "", "\u200e": "", "\u200b": "", "\ufeff": "",
})
_ARABIC_INDIC = str.maketrans("Ω Ω‘Ω’Ω£Ω€Ω₯Ω¦Ω§Ω¨Ω©", "0123456789")
_EXTENDED_AR = str.maketrans("Ϋ°Ϋ±Ϋ²Ϋ³Ϋ΄Ϋ΅ΫΆΫ·ΫΈΫΉ", "0123456789")
def normalize_urdu(text: str) -> str:
text = unicodedata.normalize("NFC", text)
text = text.translate(_PUNCT_MAP)
text = text.translate(_ARABIC_INDIC)
text = text.translate(_EXTENDED_AR)
text = re.sub(r"\s+", " ", text).strip()
return text
# ββ Load all models at startup ββββββββββββββββββββββββββββββββββββββββββββββββ
logger.info("Loading processor...")
processor = SpeechT5Processor.from_pretrained(PROCESSOR_DIR)
logger.info("Loading TTS model...")
tts_model = SpeechT5ForTextToSpeech.from_pretrained(MODEL_DIR).to(DEVICE)
tts_model.eval()
logger.info("Loading vocoder...")
vocoder = SpeechT5HifiGan.from_pretrained(VOCODER_DIR).to(DEVICE)
vocoder.eval()
logger.info("Loading speaker encoder...")
speaker_encoder = EncoderClassifier.from_hparams(
source=SPKREC_DIR,
run_opts={"device": DEVICE},
)
logger.info("Loading DNS64 denoiser...")
denoiser_model = pretrained.dns64().to(DEVICE)
denoiser_model.eval()
# ββ Default speaker embedding β loaded from embeddings/normal_embedding.pt ββββ
_EMBEDDING_PATH = os.environ.get("SPEAKER_EMBEDDING_PATH", "./embeddings/normal_embedding.pt")
logger.info(f"Loading speaker embedding from {_EMBEDDING_PATH}...")
_emb = torch.load(_EMBEDDING_PATH, map_location="cpu")
if not isinstance(_emb, torch.Tensor):
_emb = torch.tensor(_emb)
_emb = _emb.float().squeeze()
_emb = torch.nn.functional.normalize(_emb.unsqueeze(0), dim=1) # (1, 512)
DEFAULT_SPEAKER_EMBEDDING = _emb.to(DEVICE)
# Initialize phonemizer for Urdu
backend = EspeakBackend(
'ur',
preserve_punctuation=False, # punctuation has no sound, skip it
with_stress=True, # stress markers improve prosody
)
def urdu_to_phonemes(text):
"""Convert Urdu text to space-separated IPA phoneme string."""
result = backend.phonemize([text], njobs=1)[0]
# Clean up extra whitespace
result = re.sub(r'\s+', ' ', result).strip()
return result
logger.info("All models loaded β
")
# ββ FastAPI app βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
app = FastAPI(
title="Urdu TTS Phonemes API",
description="Convert Urdu text to speech using a fine-tuned SpeechT5 model.",
version="1.0.0",
)
TARGET_SR = 16000 # SpeechT5 and speaker encoder both expect 16 kHz
def embedding_from_audio(audio_bytes: bytes) -> torch.Tensor:
"""
Compute a (1, 512) speaker embedding from raw audio file bytes.
Accepts any format soundfile can read (wav, mp3, flac, ogg, etc.).
Resamples to 16 kHz mono automatically.
"""
buf = io.BytesIO(audio_bytes)
# Read with torchaudio β supports more formats than soundfile
waveform, sr = torchaudio.load(buf) # (channels, T)
# Mix down to mono
if waveform.shape[0] > 1:
waveform = waveform.mean(dim=0, keepdim=True) # (1, T)
# Resample to 16 kHz if needed
if sr != TARGET_SR:
resampler = torchaudio.transforms.Resample(orig_freq=sr, new_freq=TARGET_SR)
waveform = resampler(waveform)
waveform = waveform.to(DEVICE) # (1, T)
with torch.no_grad():
emb = speaker_encoder.encode_batch(waveform) # (1, 1, 512)
emb = torch.nn.functional.normalize(emb, dim=2)
emb = emb.squeeze(0) # (1, 512)
return emb # (1, 512) on DEVICE
def run_tts(text: str, speaker_embedding: torch.Tensor) -> np.ndarray:
"""Full pipeline: text β normalize β tokenize β TTS β vocoder β denoise."""
normalized = normalize_urdu(text)
phonemized = urdu_to_phonemes(normalized)
logger.info(f"Phonemes: {phonemized}")
inputs = processor(text=phonemized, return_tensors="pt")
input_ids = inputs["input_ids"].to(DEVICE)
with torch.no_grad():
speech = tts_model.generate_speech(
input_ids,
speaker_embedding,
vocoder=vocoder,
)
# DNS64 expects (batch, channels, time) at 16 kHz
speech_3d = speech.unsqueeze(0).unsqueeze(0)
with torch.no_grad():
denoised = denoiser_model(speech_3d)[0]
return denoised.squeeze().cpu().numpy()
@app.get("/health")
def health():
return {"status": "ok"}
@app.post("/synthesize")
async def synthesize(
text: str = Form(..., description="Urdu text to synthesize"),
reference_audio: Optional[UploadFile] = File(
default=None,
description="Optional reference audio file for voice cloning. "
"If omitted, the default speaker voice is used. "
"Accepts WAV, MP3, FLAC, OGG etc.",
),
):
"""
Convert Urdu text to speech.
- Send as **multipart/form-data** with:
- `text` (required): the Urdu string to synthesize
- `reference_audio` (optional): an audio file whose voice will be cloned
- If no `reference_audio` is provided, the pre-loaded default embedding is used.
- Response is a denoised **audio/wav** file.
**Example β default voice (curl):**
```
curl -X POST /synthesize -F "text=ΫΫ Ψ§Ψ±Ψ―Ω ΫΫ" --output out.wav
```
**Example β custom voice (curl):**
```
curl -X POST /synthesize -F "text=ΫΫ Ψ§Ψ±Ψ―Ω ΫΫ" -F "reference_audio=@my_voice.wav" --output out.wav
```
"""
if not text or not text.strip():
raise HTTPException(status_code=400, detail="text must not be empty.")
# ββ Resolve speaker embedding βββββββββββββββββββββββββββββββββββββββββββββ
if reference_audio is not None:
# Validate content type loosely β torchaudio will hard-fail on bad files
allowed = {"audio/wav", "audio/wave", "audio/mpeg", "audio/mp3",
"audio/flac", "audio/ogg", "audio/x-wav", "audio/x-flac"}
ct = (reference_audio.content_type or "").lower()
if ct and ct not in allowed:
raise HTTPException(
status_code=415,
detail=f"Unsupported audio type '{ct}'. Use WAV, MP3, FLAC, or OGG.",
)
audio_bytes = await reference_audio.read()
if len(audio_bytes) == 0:
raise HTTPException(status_code=400, detail="Uploaded audio file is empty.")
try:
logger.info(f"Computing embedding from uploaded file: {reference_audio.filename}")
speaker_embedding = embedding_from_audio(audio_bytes)
except Exception as e:
logger.exception("Failed to compute speaker embedding from reference audio")
raise HTTPException(
status_code=422,
detail=f"Could not process reference audio: {str(e)}",
)
else:
logger.info("No reference audio provided β using default speaker embedding")
speaker_embedding = DEFAULT_SPEAKER_EMBEDDING
# ββ Run TTS βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
try:
audio_np = run_tts(text.strip(), speaker_embedding)
except Exception as e:
logger.exception("TTS generation failed")
raise HTTPException(status_code=500, detail=f"TTS generation failed: {str(e)}")
buffer = io.BytesIO()
sf.write(buffer, audio_np, samplerate=16000, format="WAV")
buffer.seek(0)
return StreamingResponse(
buffer,
media_type="audio/wav",
headers={"Content-Disposition": 'attachment; filename="output.wav"'},
)
|