Spaces:
Sleeping
Sleeping
Refactor backend: Replace standard Whisper with faster-whisper, add Demucs vocal separation and WebRTCVAD for improved alignment
Browse files- requirements.txt +6 -2
- server.py +659 -312
requirements.txt
CHANGED
|
@@ -2,5 +2,9 @@ fastapi
|
|
| 2 |
uvicorn[standard]
|
| 3 |
python-multipart
|
| 4 |
torch
|
| 5 |
-
|
| 6 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
uvicorn[standard]
|
| 3 |
python-multipart
|
| 4 |
torch
|
| 5 |
+
faster-whisper
|
| 6 |
+
demucs
|
| 7 |
+
webrtcvad
|
| 8 |
+
numpy
|
| 9 |
+
soundfile
|
| 10 |
+
scipy
|
server.py
CHANGED
|
@@ -1,41 +1,42 @@
|
|
| 1 |
import os
|
| 2 |
import re
|
| 3 |
import shutil
|
|
|
|
| 4 |
import tempfile
|
| 5 |
from contextlib import asynccontextmanager
|
| 6 |
-
from
|
|
|
|
|
|
|
| 7 |
|
| 8 |
-
import
|
|
|
|
|
|
|
| 9 |
from fastapi import FastAPI, File, Form, HTTPException, UploadFile
|
| 10 |
from fastapi.middleware.cors import CORSMiddleware
|
| 11 |
from fastapi.responses import PlainTextResponse
|
| 12 |
-
from
|
| 13 |
|
| 14 |
DEVICE = "cpu"
|
| 15 |
-
|
| 16 |
-
|
| 17 |
|
| 18 |
-
SrtMode = Literal["
|
| 19 |
|
|
|
|
|
|
|
|
|
|
| 20 |
|
| 21 |
-
|
| 22 |
-
srt_content: str
|
| 23 |
-
target_language: str
|
| 24 |
|
| 25 |
|
| 26 |
@asynccontextmanager
|
| 27 |
async def lifespan(app: FastAPI):
|
| 28 |
global whisper_model
|
| 29 |
-
print(f"
|
| 30 |
-
whisper_model =
|
| 31 |
-
|
| 32 |
-
whisper_model.to(DEVICE)
|
| 33 |
-
except Exception:
|
| 34 |
-
# Best effort: some whisper builds may not expose .to()
|
| 35 |
-
pass
|
| 36 |
-
print("Whisper model ready")
|
| 37 |
yield
|
| 38 |
-
print("
|
| 39 |
|
| 40 |
|
| 41 |
app = FastAPI(title="LyricSync Backend", lifespan=lifespan)
|
|
@@ -54,9 +55,10 @@ app.add_middleware(
|
|
| 54 |
async def root():
|
| 55 |
return {
|
| 56 |
"service": "LyricSync Backend",
|
| 57 |
-
"engine": "
|
| 58 |
-
"model":
|
| 59 |
"device": DEVICE,
|
|
|
|
| 60 |
"status": "operational",
|
| 61 |
}
|
| 62 |
|
|
@@ -72,9 +74,7 @@ def _cleanup_temp_dir(path: str) -> None:
|
|
| 72 |
|
| 73 |
|
| 74 |
def _format_srt_time(seconds: float) -> str:
|
| 75 |
-
|
| 76 |
-
seconds = 0.0
|
| 77 |
-
milliseconds_total = int(max(0.0, seconds) * 1000)
|
| 78 |
hours = milliseconds_total // 3_600_000
|
| 79 |
minutes = (milliseconds_total % 3_600_000) // 60_000
|
| 80 |
secs = (milliseconds_total % 60_000) // 1_000
|
|
@@ -83,33 +83,168 @@ def _format_srt_time(seconds: float) -> str:
|
|
| 83 |
|
| 84 |
|
| 85 |
def _build_srt(segments: list[dict]) -> str:
|
|
|
|
|
|
|
| 86 |
lines: list[str] = []
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
end = segment.get("end")
|
| 92 |
if not text or start is None or end is None:
|
| 93 |
continue
|
| 94 |
-
|
| 95 |
-
lines.append(
|
| 96 |
-
lines.append(f"{_format_srt_time(float(start))} --> {_format_srt_time(float(end))}")
|
| 97 |
lines.append(text)
|
| 98 |
lines.append("")
|
| 99 |
-
index += 1
|
| 100 |
-
|
| 101 |
-
if not lines:
|
| 102 |
-
return ""
|
| 103 |
-
|
| 104 |
return "\n".join(lines).rstrip() + "\n"
|
| 105 |
|
| 106 |
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 127 |
|
| 128 |
|
| 129 |
-
def
|
| 130 |
-
|
| 131 |
-
for seg in
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
return
|
| 141 |
|
| 142 |
|
| 143 |
-
def
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 147 |
|
| 148 |
-
|
| 149 |
-
return [t for t in text.split() if t]
|
| 150 |
|
| 151 |
-
# Languages without spaces (CJK, etc.): approximate words by chunking.
|
| 152 |
-
chunk_size = 4
|
| 153 |
-
return [text[i : i + chunk_size] for i in range(0, len(text), chunk_size) if text[i : i + chunk_size].strip()]
|
| 154 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 155 |
|
| 156 |
-
def
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 161 |
continue
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 171 |
return words
|
| 172 |
|
| 173 |
|
| 174 |
-
def
|
| 175 |
-
|
| 176 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 177 |
|
| 178 |
def flush() -> None:
|
| 179 |
-
nonlocal
|
| 180 |
-
if not
|
| 181 |
return
|
| 182 |
-
|
|
|
|
|
|
|
| 183 |
if text:
|
| 184 |
-
|
| 185 |
-
|
| 186 |
|
| 187 |
-
for
|
| 188 |
-
if
|
| 189 |
-
|
| 190 |
-
|
|
|
|
|
|
|
| 191 |
flush()
|
| 192 |
|
| 193 |
-
|
| 194 |
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
is_soft = bool(_SOFT_PUNCT_RE.search(token))
|
| 198 |
-
|
| 199 |
-
if is_strong:
|
| 200 |
flush()
|
| 201 |
continue
|
| 202 |
-
|
| 203 |
-
if len(current) >= max_words:
|
| 204 |
flush()
|
| 205 |
continue
|
| 206 |
-
|
| 207 |
-
|
|
|
|
|
|
|
|
|
|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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 234 |
|
| 235 |
|
| 236 |
@app.post("/srt", response_class=PlainTextResponse)
|
| 237 |
async def generate_srt(
|
| 238 |
audio_file: UploadFile = File(...),
|
| 239 |
-
|
|
|
|
|
|
|
| 240 |
):
|
| 241 |
"""
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
-
|
| 246 |
-
-
|
|
|
|
| 247 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 248 |
temp_dir = tempfile.mkdtemp(prefix="lyric-sync-")
|
| 249 |
try:
|
| 250 |
-
mode = srt_mode.strip().lower()
|
| 251 |
-
# Backward-compat with old UI values.
|
| 252 |
-
if mode == "sentence":
|
| 253 |
-
mode = "lyric"
|
| 254 |
-
if mode not in ("lyric", "paragraph"):
|
| 255 |
-
raise HTTPException(status_code=400, detail="Invalid srt_mode (expected 'lyric' or 'paragraph')")
|
| 256 |
-
|
| 257 |
source_name = audio_file.filename or "audio"
|
| 258 |
-
|
| 259 |
-
with open(
|
| 260 |
shutil.copyfileobj(audio_file.file, f)
|
| 261 |
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 267 |
except HTTPException:
|
| 268 |
raise
|
| 269 |
except Exception as e:
|
|
@@ -276,183 +786,20 @@ async def generate_srt(
|
|
| 276 |
|
| 277 |
|
| 278 |
@app.post("/align", response_class=PlainTextResponse)
|
| 279 |
-
async def
|
| 280 |
audio_file: UploadFile = File(...),
|
| 281 |
-
|
|
|
|
|
|
|
| 282 |
):
|
| 283 |
-
#
|
| 284 |
-
return await generate_srt(
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
)
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
def _parse_srt(srt_content: str) -> list[dict]:
|
| 293 |
-
blocks: list[dict] = []
|
| 294 |
-
lines = (srt_content or "").splitlines()
|
| 295 |
-
i = 0
|
| 296 |
-
|
| 297 |
-
while i < len(lines):
|
| 298 |
-
if not lines[i].strip():
|
| 299 |
-
i += 1
|
| 300 |
-
continue
|
| 301 |
-
|
| 302 |
-
raw_index = lines[i].strip()
|
| 303 |
-
try:
|
| 304 |
-
index = int(raw_index)
|
| 305 |
-
except ValueError:
|
| 306 |
-
index = len(blocks) + 1
|
| 307 |
-
i += 1
|
| 308 |
-
if i >= len(lines):
|
| 309 |
-
break
|
| 310 |
-
|
| 311 |
-
m = _SRT_TS_RE.match(lines[i].strip())
|
| 312 |
-
if not m:
|
| 313 |
-
# Skip malformed block
|
| 314 |
-
i += 1
|
| 315 |
-
continue
|
| 316 |
-
start = m.group("start")
|
| 317 |
-
end = m.group("end")
|
| 318 |
-
i += 1
|
| 319 |
-
|
| 320 |
-
text_lines: list[str] = []
|
| 321 |
-
while i < len(lines) and lines[i].strip():
|
| 322 |
-
text_lines.append(lines[i].rstrip("\n"))
|
| 323 |
-
i += 1
|
| 324 |
-
|
| 325 |
-
blocks.append({"index": index, "start": start, "end": end, "text": "\n".join(text_lines).strip()})
|
| 326 |
-
|
| 327 |
-
return blocks
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
def _render_srt(blocks: list[dict]) -> str:
|
| 331 |
-
out: list[str] = []
|
| 332 |
-
for idx, block in enumerate(blocks, start=1):
|
| 333 |
-
out.append(str(idx))
|
| 334 |
-
out.append(f"{block['start']} --> {block['end']}")
|
| 335 |
-
out.append((block.get("text") or "").strip())
|
| 336 |
-
out.append("")
|
| 337 |
-
return "\n".join(out).rstrip() + "\n"
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
_LANGUAGES: dict[str, dict] = {
|
| 341 |
-
"en": {"label": "English", "transliterate": False},
|
| 342 |
-
"fr": {"label": "French", "transliterate": False},
|
| 343 |
-
"es": {"label": "Spanish", "transliterate": False},
|
| 344 |
-
"de": {"label": "German", "transliterate": False},
|
| 345 |
-
"it": {"label": "Italian", "transliterate": False},
|
| 346 |
-
"ja": {"label": "Japanese (Romaji)", "transliterate": True, "scheme": "Romaji"},
|
| 347 |
-
"zh-Hans": {"label": "Chinese (Simplified, Pinyin)", "transliterate": True, "scheme": "Hanyu Pinyin"},
|
| 348 |
-
"zh-Hant": {"label": "Chinese (Traditional, Pinyin)", "transliterate": True, "scheme": "Hanyu Pinyin"},
|
| 349 |
-
"ko": {"label": "Korean (Romanized)", "transliterate": True, "scheme": "Revised Romanization"},
|
| 350 |
-
"th": {"label": "Thai (Romanized)", "transliterate": True, "scheme": "RTGS"},
|
| 351 |
-
"pt": {"label": "Portuguese", "transliterate": False},
|
| 352 |
-
"ru": {"label": "Russian (Transliterated)", "transliterate": True, "scheme": "Latin transliteration"},
|
| 353 |
-
"ar": {"label": "Arabic (Latin phonetic)", "transliterate": True, "scheme": "Latin phonetic"},
|
| 354 |
-
"hi": {"label": "Hindi (Latin transliteration)", "transliterate": True, "scheme": "Latin transliteration"},
|
| 355 |
-
"nl": {"label": "Dutch", "transliterate": False},
|
| 356 |
-
"id": {"label": "Indonesian", "transliterate": False},
|
| 357 |
-
"vi": {"label": "Vietnamese", "transliterate": False},
|
| 358 |
-
"tr": {"label": "Turkish", "transliterate": False},
|
| 359 |
-
"pl": {"label": "Polish", "transliterate": False},
|
| 360 |
-
}
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
def _translate_blocks_via_openai(texts: list[str], target_code: str) -> list[str]:
|
| 364 |
-
api_key = os.environ.get("OPENAI_API_KEY")
|
| 365 |
-
if not api_key:
|
| 366 |
-
raise HTTPException(status_code=503, detail="OPENAI_API_KEY is not configured on the server")
|
| 367 |
-
|
| 368 |
-
language = _LANGUAGES[target_code]
|
| 369 |
-
label = language["label"]
|
| 370 |
-
transliterate = bool(language.get("transliterate"))
|
| 371 |
-
scheme = language.get("scheme")
|
| 372 |
-
|
| 373 |
-
system = (
|
| 374 |
-
"You translate short subtitle lines. Preserve meaning, punctuation, and line breaks. "
|
| 375 |
-
"Return ONLY valid JSON with shape {\"translations\": [..]}. No markdown."
|
| 376 |
)
|
| 377 |
|
| 378 |
-
translit_rule = ""
|
| 379 |
-
if transliterate:
|
| 380 |
-
extra = f" using {scheme}" if scheme else ""
|
| 381 |
-
translit_rule = (
|
| 382 |
-
f"IMPORTANT: Output MUST be Latin-script transliteration{extra}. "
|
| 383 |
-
"Do NOT output any native-script characters (no Kana/Kanji/Hanzi/Hangul/Cyrillic/Arabic/Devanagari/Thai)."
|
| 384 |
-
)
|
| 385 |
-
|
| 386 |
-
from openai import OpenAI
|
| 387 |
-
|
| 388 |
-
client = OpenAI(api_key=api_key)
|
| 389 |
-
model_name = os.environ.get("OPENAI_TRANSLATE_MODEL", "gpt-4o-mini")
|
| 390 |
-
|
| 391 |
-
user = {
|
| 392 |
-
"target_language": label,
|
| 393 |
-
"rule": translit_rule,
|
| 394 |
-
"lines": texts,
|
| 395 |
-
}
|
| 396 |
-
|
| 397 |
-
import json
|
| 398 |
-
|
| 399 |
-
user_json = json.dumps(user, ensure_ascii=False)
|
| 400 |
-
|
| 401 |
-
resp = client.chat.completions.create(
|
| 402 |
-
model=model_name,
|
| 403 |
-
temperature=0,
|
| 404 |
-
messages=[
|
| 405 |
-
{"role": "system", "content": system},
|
| 406 |
-
{
|
| 407 |
-
"role": "user",
|
| 408 |
-
"content": (
|
| 409 |
-
f"Translate each line to {label}. {translit_rule}\n"
|
| 410 |
-
"Return JSON: {\"translations\": [\"...\", ...]} with the same length and order as input.\n\n"
|
| 411 |
-
"Input JSON:\n"
|
| 412 |
-
f"{user_json}"
|
| 413 |
-
),
|
| 414 |
-
},
|
| 415 |
-
],
|
| 416 |
-
)
|
| 417 |
-
|
| 418 |
-
content = (resp.choices[0].message.content or "").strip()
|
| 419 |
-
try:
|
| 420 |
-
import json
|
| 421 |
-
|
| 422 |
-
# Best-effort: extract the first JSON object from the response.
|
| 423 |
-
start = content.find("{")
|
| 424 |
-
end = content.rfind("}")
|
| 425 |
-
payload = json.loads(content[start : end + 1] if start != -1 and end != -1 else content)
|
| 426 |
-
translations = payload.get("translations")
|
| 427 |
-
if not isinstance(translations, list) or len(translations) != len(texts):
|
| 428 |
-
raise ValueError("Invalid translations payload")
|
| 429 |
-
return [str(t) for t in translations]
|
| 430 |
-
except Exception as e:
|
| 431 |
-
raise HTTPException(status_code=502, detail=f"Translation parsing failed: {e}") from e
|
| 432 |
-
|
| 433 |
-
|
| 434 |
-
@app.post("/translate", response_class=PlainTextResponse)
|
| 435 |
-
async def translate_srt(req: TranslateRequest):
|
| 436 |
-
target = (req.target_language or "").strip()
|
| 437 |
-
if target not in _LANGUAGES:
|
| 438 |
-
raise HTTPException(status_code=400, detail=f"Unsupported target_language (supported: {', '.join(_LANGUAGES)})")
|
| 439 |
-
|
| 440 |
-
blocks = _parse_srt(req.srt_content)
|
| 441 |
-
if not blocks:
|
| 442 |
-
raise HTTPException(status_code=400, detail="Empty or invalid SRT content")
|
| 443 |
-
|
| 444 |
-
texts = [b["text"] for b in blocks]
|
| 445 |
-
# Chunk to keep prompts manageable.
|
| 446 |
-
translated: list[str] = []
|
| 447 |
-
chunk_size = 60
|
| 448 |
-
for i in range(0, len(texts), chunk_size):
|
| 449 |
-
translated.extend(_translate_blocks_via_openai(texts[i : i + chunk_size], target))
|
| 450 |
-
|
| 451 |
-
for block, new_text in zip(blocks, translated, strict=True):
|
| 452 |
-
block["text"] = (new_text or "").strip()
|
| 453 |
-
|
| 454 |
-
return PlainTextResponse(content=_render_srt(blocks), media_type="application/x-subrip")
|
| 455 |
-
|
| 456 |
|
| 457 |
if __name__ == "__main__":
|
| 458 |
import uvicorn
|
|
|
|
| 1 |
import os
|
| 2 |
import re
|
| 3 |
import shutil
|
| 4 |
+
import subprocess
|
| 5 |
import tempfile
|
| 6 |
from contextlib import asynccontextmanager
|
| 7 |
+
from dataclasses import dataclass
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
from typing import Literal, Optional
|
| 10 |
|
| 11 |
+
import numpy as np
|
| 12 |
+
import soundfile as sf
|
| 13 |
+
import webrtcvad
|
| 14 |
from fastapi import FastAPI, File, Form, HTTPException, UploadFile
|
| 15 |
from fastapi.middleware.cors import CORSMiddleware
|
| 16 |
from fastapi.responses import PlainTextResponse
|
| 17 |
+
from faster_whisper import WhisperModel
|
| 18 |
|
| 19 |
DEVICE = "cpu"
|
| 20 |
+
MODEL_NAME = "large-v2"
|
| 21 |
+
COMPUTE_TYPE = "int8"
|
| 22 |
|
| 23 |
+
SrtMode = Literal["sentence", "paragraph"]
|
| 24 |
|
| 25 |
+
MIN_GAP_S = 0.08
|
| 26 |
+
MIN_DUR_S = 0.30
|
| 27 |
+
SILENCE_GAP_S = 0.50
|
| 28 |
|
| 29 |
+
whisper_model: Optional[WhisperModel] = None
|
|
|
|
|
|
|
| 30 |
|
| 31 |
|
| 32 |
@asynccontextmanager
|
| 33 |
async def lifespan(app: FastAPI):
|
| 34 |
global whisper_model
|
| 35 |
+
print(f"Startup: loading faster-whisper '{MODEL_NAME}' on {DEVICE} ({COMPUTE_TYPE})...")
|
| 36 |
+
whisper_model = WhisperModel(MODEL_NAME, device=DEVICE, compute_type=COMPUTE_TYPE)
|
| 37 |
+
print("Startup: ASR model ready")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
yield
|
| 39 |
+
print("Shutdown: done")
|
| 40 |
|
| 41 |
|
| 42 |
app = FastAPI(title="LyricSync Backend", lifespan=lifespan)
|
|
|
|
| 55 |
async def root():
|
| 56 |
return {
|
| 57 |
"service": "LyricSync Backend",
|
| 58 |
+
"engine": "faster-whisper + demucs + VAD",
|
| 59 |
+
"model": MODEL_NAME,
|
| 60 |
"device": DEVICE,
|
| 61 |
+
"compute_type": COMPUTE_TYPE,
|
| 62 |
"status": "operational",
|
| 63 |
}
|
| 64 |
|
|
|
|
| 74 |
|
| 75 |
|
| 76 |
def _format_srt_time(seconds: float) -> str:
|
| 77 |
+
milliseconds_total = int(max(0.0, float(seconds)) * 1000)
|
|
|
|
|
|
|
| 78 |
hours = milliseconds_total // 3_600_000
|
| 79 |
minutes = (milliseconds_total % 3_600_000) // 60_000
|
| 80 |
secs = (milliseconds_total % 60_000) // 1_000
|
|
|
|
| 83 |
|
| 84 |
|
| 85 |
def _build_srt(segments: list[dict]) -> str:
|
| 86 |
+
if not segments:
|
| 87 |
+
return ""
|
| 88 |
lines: list[str] = []
|
| 89 |
+
for idx, seg in enumerate(segments, start=1):
|
| 90 |
+
text = (seg.get("text") or "").strip()
|
| 91 |
+
start = seg.get("start")
|
| 92 |
+
end = seg.get("end")
|
|
|
|
| 93 |
if not text or start is None or end is None:
|
| 94 |
continue
|
| 95 |
+
lines.append(str(idx))
|
| 96 |
+
lines.append(f"{_format_srt_time(start)} --> {_format_srt_time(end)}")
|
|
|
|
| 97 |
lines.append(text)
|
| 98 |
lines.append("")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 99 |
return "\n".join(lines).rstrip() + "\n"
|
| 100 |
|
| 101 |
|
| 102 |
+
def _run_cmd(cmd: list[str]) -> None:
|
| 103 |
+
try:
|
| 104 |
+
subprocess.run(cmd, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
| 105 |
+
except subprocess.CalledProcessError as e:
|
| 106 |
+
stderr = (e.stderr or b"").decode("utf-8", errors="replace")
|
| 107 |
+
raise HTTPException(status_code=500, detail=f"Command failed: {' '.join(cmd)}\n{stderr}") from e
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def _ffmpeg_to_wav(
|
| 111 |
+
input_path: str,
|
| 112 |
+
output_path: str,
|
| 113 |
+
*,
|
| 114 |
+
sample_rate: int,
|
| 115 |
+
mono: bool,
|
| 116 |
+
) -> None:
|
| 117 |
+
channels = "1" if mono else "2"
|
| 118 |
+
cmd = [
|
| 119 |
+
"ffmpeg",
|
| 120 |
+
"-y",
|
| 121 |
+
"-i",
|
| 122 |
+
input_path,
|
| 123 |
+
"-vn",
|
| 124 |
+
"-ac",
|
| 125 |
+
channels,
|
| 126 |
+
"-ar",
|
| 127 |
+
str(sample_rate),
|
| 128 |
+
"-f",
|
| 129 |
+
"wav",
|
| 130 |
+
output_path,
|
| 131 |
+
]
|
| 132 |
+
_run_cmd(cmd)
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def _demucs_extract_vocals(input_wav_path: str, out_dir: str) -> str:
|
| 136 |
+
"""
|
| 137 |
+
Run Demucs vocals separation (two-stems=vocals) and return the vocals wav path.
|
| 138 |
+
Uses the CLI for maximum compatibility across environments.
|
| 139 |
+
"""
|
| 140 |
+
separated_dir = os.path.join(out_dir, "demucs_separated")
|
| 141 |
+
os.makedirs(separated_dir, exist_ok=True)
|
| 142 |
+
|
| 143 |
+
cmd = [
|
| 144 |
+
"python",
|
| 145 |
+
"-m",
|
| 146 |
+
"demucs.separate",
|
| 147 |
+
"-n",
|
| 148 |
+
"htdemucs",
|
| 149 |
+
"--two-stems",
|
| 150 |
+
"vocals",
|
| 151 |
+
"-o",
|
| 152 |
+
separated_dir,
|
| 153 |
+
input_wav_path,
|
| 154 |
+
]
|
| 155 |
+
_run_cmd(cmd)
|
| 156 |
+
|
| 157 |
+
# Demucs outputs: <out>/htdemucs/<trackname>/vocals.wav (may vary by version)
|
| 158 |
+
vocals_candidates = list(Path(separated_dir).rglob("vocals.wav"))
|
| 159 |
+
if not vocals_candidates:
|
| 160 |
+
raise HTTPException(status_code=500, detail="Demucs did not produce vocals.wav")
|
| 161 |
+
# Pick the newest/closest match deterministically
|
| 162 |
+
vocals_candidates.sort(key=lambda p: (len(p.parts), str(p)))
|
| 163 |
+
return str(vocals_candidates[0])
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def _read_wav_pcm16_mono(path: str, *, sample_rate: int) -> bytes:
|
| 167 |
+
audio, sr = sf.read(path, dtype="int16", always_2d=True)
|
| 168 |
+
if sr != sample_rate:
|
| 169 |
+
raise HTTPException(status_code=500, detail=f"VAD expected {sample_rate}Hz mono wav; got {sr}Hz")
|
| 170 |
+
if audio.shape[1] != 1:
|
| 171 |
+
raise HTTPException(status_code=500, detail="VAD expected mono wav (1 channel)")
|
| 172 |
+
return audio[:, 0].tobytes()
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
def _vad_voice_segments(
|
| 176 |
+
wav_16k_mono_path: str,
|
| 177 |
+
*,
|
| 178 |
+
gap_s: float = SILENCE_GAP_S,
|
| 179 |
+
vad_mode: int = 2,
|
| 180 |
+
) -> tuple[list[tuple[float, float]], list[tuple[float, float]]]:
|
| 181 |
+
"""
|
| 182 |
+
Return (voice_segments, instrumental_gaps).
|
| 183 |
+
- voice_segments: merged voiced ranges
|
| 184 |
+
- instrumental_gaps: gaps between voiced ranges longer than gap_s
|
| 185 |
+
"""
|
| 186 |
+
sample_rate = 16000
|
| 187 |
+
pcm = _read_wav_pcm16_mono(wav_16k_mono_path, sample_rate=sample_rate)
|
| 188 |
+
|
| 189 |
+
vad = webrtcvad.Vad(int(vad_mode))
|
| 190 |
+
frame_ms = 30
|
| 191 |
+
frame_bytes = int(sample_rate * (frame_ms / 1000.0) * 2) # 16-bit mono
|
| 192 |
+
|
| 193 |
+
voiced_frames: list[tuple[float, float]] = []
|
| 194 |
+
offset_bytes = 0
|
| 195 |
+
total_bytes = len(pcm)
|
| 196 |
+
while offset_bytes + frame_bytes <= total_bytes:
|
| 197 |
+
frame = pcm[offset_bytes : offset_bytes + frame_bytes]
|
| 198 |
+
t0 = (offset_bytes / 2) / sample_rate
|
| 199 |
+
t1 = ((offset_bytes + frame_bytes) / 2) / sample_rate
|
| 200 |
+
if vad.is_speech(frame, sample_rate):
|
| 201 |
+
voiced_frames.append((t0, t1))
|
| 202 |
+
offset_bytes += frame_bytes
|
| 203 |
+
|
| 204 |
+
if not voiced_frames:
|
| 205 |
+
return ([], [])
|
| 206 |
+
|
| 207 |
+
# Merge contiguous voiced frames with a small tolerance.
|
| 208 |
+
merged: list[tuple[float, float]] = []
|
| 209 |
+
cur_s, cur_e = voiced_frames[0]
|
| 210 |
+
tol = 0.06
|
| 211 |
+
for s, e in voiced_frames[1:]:
|
| 212 |
+
if s <= cur_e + tol:
|
| 213 |
+
cur_e = max(cur_e, e)
|
| 214 |
+
else:
|
| 215 |
+
merged.append((cur_s, cur_e))
|
| 216 |
+
cur_s, cur_e = s, e
|
| 217 |
+
merged.append((cur_s, cur_e))
|
| 218 |
+
|
| 219 |
+
gaps: list[tuple[float, float]] = []
|
| 220 |
+
for (_s1, e1), (s2, _e2) in zip(merged, merged[1:]):
|
| 221 |
+
if (s2 - e1) >= gap_s:
|
| 222 |
+
gaps.append((e1, s2))
|
| 223 |
+
|
| 224 |
+
return (merged, gaps)
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
@dataclass(frozen=True)
|
| 228 |
+
class WordTS:
|
| 229 |
+
display: str
|
| 230 |
+
norm: str
|
| 231 |
+
start: Optional[float] = None
|
| 232 |
+
end: Optional[float] = None
|
| 233 |
+
boundary_after: bool = False # punctuation boundary
|
| 234 |
+
line_break_after: bool = False
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
_STRONG_BOUNDARY_RE = re.compile(r"[.!?]+$")
|
| 238 |
+
_PUNCT_STRIP_RE = re.compile(r"^[^\w']+|[^\w']+$", re.UNICODE)
|
| 239 |
+
_NONWORD_RE = re.compile(r"[^\w']+", re.UNICODE)
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
def _normalize_token(token: str) -> str:
|
| 243 |
+
token = (token or "").strip().lower()
|
| 244 |
+
token = token.replace("’", "'").replace("‘", "'").replace("´", "'")
|
| 245 |
+
token = _PUNCT_STRIP_RE.sub("", token)
|
| 246 |
+
token = _NONWORD_RE.sub("", token)
|
| 247 |
+
return token
|
| 248 |
|
| 249 |
|
| 250 |
def _cleanup_spacing(text: str) -> str:
|
|
|
|
| 254 |
return text.strip()
|
| 255 |
|
| 256 |
|
| 257 |
+
def _parse_lyrics_words(lyrics_text: str) -> list[WordTS]:
|
| 258 |
+
words: list[WordTS] = []
|
| 259 |
+
for line in (lyrics_text or "").splitlines():
|
| 260 |
+
line = line.strip()
|
| 261 |
+
if not line:
|
| 262 |
+
# Preserve a strong boundary (line break) if we already have words.
|
| 263 |
+
if words:
|
| 264 |
+
last = words[-1]
|
| 265 |
+
words[-1] = WordTS(
|
| 266 |
+
display=last.display,
|
| 267 |
+
norm=last.norm,
|
| 268 |
+
start=last.start,
|
| 269 |
+
end=last.end,
|
| 270 |
+
boundary_after=True,
|
| 271 |
+
line_break_after=True,
|
| 272 |
+
)
|
| 273 |
+
continue
|
| 274 |
+
tokens = [t for t in re.split(r"\s+", line) if t]
|
| 275 |
+
for idx, tok in enumerate(tokens):
|
| 276 |
+
norm = _normalize_token(tok)
|
| 277 |
+
if not norm:
|
| 278 |
+
continue
|
| 279 |
+
boundary_after = bool(_STRONG_BOUNDARY_RE.search(tok))
|
| 280 |
+
line_break_after = idx == len(tokens) - 1
|
| 281 |
+
words.append(WordTS(display=tok, norm=norm, boundary_after=boundary_after, line_break_after=line_break_after))
|
| 282 |
+
return words
|
| 283 |
|
| 284 |
|
| 285 |
+
def _flatten_asr_words(transcribe_segments) -> list[WordTS]:
|
| 286 |
+
out: list[WordTS] = []
|
| 287 |
+
for seg in transcribe_segments:
|
| 288 |
+
for w in (seg.words or []):
|
| 289 |
+
tok = (w.word or "").strip()
|
| 290 |
+
norm = _normalize_token(tok)
|
| 291 |
+
if not norm:
|
| 292 |
+
continue
|
| 293 |
+
boundary_after = bool(_STRONG_BOUNDARY_RE.search(tok))
|
| 294 |
+
out.append(WordTS(display=tok, norm=norm, start=float(w.start), end=float(w.end), boundary_after=boundary_after))
|
| 295 |
+
out.sort(key=lambda x: (x.start or 0.0, x.end or 0.0))
|
| 296 |
+
return out
|
| 297 |
|
| 298 |
|
| 299 |
+
def _similarity(a: str, b: str) -> float:
|
| 300 |
+
if not a or not b:
|
| 301 |
+
return 0.0
|
| 302 |
+
if a == b:
|
| 303 |
+
return 1.0
|
| 304 |
+
# Cheap heuristics first
|
| 305 |
+
if len(a) >= 3 and (a in b or b in a):
|
| 306 |
+
return 0.86
|
| 307 |
+
# Standard library fuzzy match
|
| 308 |
+
import difflib
|
| 309 |
|
| 310 |
+
return difflib.SequenceMatcher(None, a, b).ratio()
|
|
|
|
| 311 |
|
|
|
|
|
|
|
|
|
|
| 312 |
|
| 313 |
+
def _align_words_dp(lyrics: list[WordTS], asr: list[WordTS]) -> list[Optional[int]]:
|
| 314 |
+
"""
|
| 315 |
+
Needleman–Wunsch alignment on normalized token sequences.
|
| 316 |
+
Returns: mapping lyric_index -> asr_index or None.
|
| 317 |
+
"""
|
| 318 |
+
n = len(lyrics)
|
| 319 |
+
m = len(asr)
|
| 320 |
+
if n == 0 or m == 0:
|
| 321 |
+
return [None] * n
|
| 322 |
+
|
| 323 |
+
# Backpointers for each row: 0=diag, 1=up (delete lyric), 2=left (insert asr)
|
| 324 |
+
back: list[bytearray] = [bytearray(m + 1) for _ in range(n + 1)]
|
| 325 |
+
|
| 326 |
+
prev = [float(j) for j in range(m + 1)]
|
| 327 |
+
for i in range(1, n + 1):
|
| 328 |
+
cur = [float(i)] + [0.0] * m
|
| 329 |
+
for j in range(1, m + 1):
|
| 330 |
+
sim = _similarity(lyrics[i - 1].norm, asr[j - 1].norm)
|
| 331 |
+
sub_cost = 0.0 if sim >= 0.90 else (0.25 if sim >= 0.82 else (0.6 if sim >= 0.74 else 1.0))
|
| 332 |
+
|
| 333 |
+
diag = prev[j - 1] + sub_cost
|
| 334 |
+
up = prev[j] + 1.0
|
| 335 |
+
left = cur[j - 1] + 1.0
|
| 336 |
+
|
| 337 |
+
best = diag
|
| 338 |
+
move = 0
|
| 339 |
+
if up < best:
|
| 340 |
+
best = up
|
| 341 |
+
move = 1
|
| 342 |
+
if left < best:
|
| 343 |
+
best = left
|
| 344 |
+
move = 2
|
| 345 |
+
cur[j] = best
|
| 346 |
+
back[i][j] = move
|
| 347 |
+
prev = cur
|
| 348 |
+
|
| 349 |
+
mapping: list[Optional[int]] = [None] * n
|
| 350 |
+
i, j = n, m
|
| 351 |
+
while i > 0 or j > 0:
|
| 352 |
+
move = back[i][j] if i >= 0 and j >= 0 else 0
|
| 353 |
+
if i > 0 and j > 0 and move == 0:
|
| 354 |
+
sim = _similarity(lyrics[i - 1].norm, asr[j - 1].norm)
|
| 355 |
+
if sim >= 0.74:
|
| 356 |
+
mapping[i - 1] = j - 1
|
| 357 |
+
i -= 1
|
| 358 |
+
j -= 1
|
| 359 |
+
elif i > 0 and (j == 0 or move == 1):
|
| 360 |
+
i -= 1
|
| 361 |
+
else:
|
| 362 |
+
j -= 1
|
| 363 |
+
|
| 364 |
+
return mapping
|
| 365 |
+
|
| 366 |
+
|
| 367 |
+
def _interpolate_missing_timestamps(
|
| 368 |
+
words: list[WordTS],
|
| 369 |
+
*,
|
| 370 |
+
voice_segments: Optional[list[tuple[float, float]]] = None,
|
| 371 |
+
default_dur: float = 0.25,
|
| 372 |
+
) -> list[WordTS]:
|
| 373 |
+
starts = [w.start for w in words]
|
| 374 |
+
ends = [w.end for w in words]
|
| 375 |
+
|
| 376 |
+
matched_durs = [float(e) - float(s) for s, e in zip(starts, ends, strict=False) if s is not None and e is not None and e > s]
|
| 377 |
+
avg_dur = float(np.median(matched_durs)) if matched_durs else default_dur
|
| 378 |
+
avg_dur = float(max(0.08, min(0.60, avg_dur)))
|
| 379 |
+
|
| 380 |
+
def set_word(idx: int, s: float, e: float) -> None:
|
| 381 |
+
nonlocal words
|
| 382 |
+
w = words[idx]
|
| 383 |
+
words[idx] = WordTS(
|
| 384 |
+
display=w.display,
|
| 385 |
+
norm=w.norm,
|
| 386 |
+
start=float(s),
|
| 387 |
+
end=float(e),
|
| 388 |
+
boundary_after=w.boundary_after,
|
| 389 |
+
line_break_after=w.line_break_after,
|
| 390 |
+
)
|
| 391 |
|
| 392 |
+
def available_voice_ranges(left: float, right: float) -> list[tuple[float, float]]:
|
| 393 |
+
if not voice_segments:
|
| 394 |
+
return []
|
| 395 |
+
out: list[tuple[float, float]] = []
|
| 396 |
+
for vs, ve in voice_segments:
|
| 397 |
+
s = max(left, float(vs))
|
| 398 |
+
e = min(right, float(ve))
|
| 399 |
+
if e > s:
|
| 400 |
+
out.append((s, e))
|
| 401 |
+
return out
|
| 402 |
+
|
| 403 |
+
# Fill internal runs
|
| 404 |
+
i = 0
|
| 405 |
+
while i < len(words):
|
| 406 |
+
if words[i].start is not None and words[i].end is not None:
|
| 407 |
+
i += 1
|
| 408 |
continue
|
| 409 |
+
run_start = i
|
| 410 |
+
while i < len(words) and (words[i].start is None or words[i].end is None):
|
| 411 |
+
i += 1
|
| 412 |
+
run_end = i - 1
|
| 413 |
+
|
| 414 |
+
prev_idx = run_start - 1
|
| 415 |
+
next_idx = i if i < len(words) else None
|
| 416 |
+
|
| 417 |
+
if prev_idx >= 0 and next_idx is not None and words[prev_idx].end is not None and words[next_idx].start is not None:
|
| 418 |
+
left_t = float(words[prev_idx].end)
|
| 419 |
+
right_t = float(words[next_idx].start)
|
| 420 |
+
k = (run_end - run_start) + 1
|
| 421 |
+
voice_ranges = available_voice_ranges(left_t, right_t)
|
| 422 |
+
total_voice = sum(e - s for s, e in voice_ranges)
|
| 423 |
+
|
| 424 |
+
if total_voice >= 0.20:
|
| 425 |
+
# Distribute words across voiced regions only.
|
| 426 |
+
cum = 0.0
|
| 427 |
+
for r in range(k):
|
| 428 |
+
target = (r + 1) / (k + 1) * total_voice
|
| 429 |
+
t = left_t
|
| 430 |
+
cum_local = 0.0
|
| 431 |
+
for s, e in voice_ranges:
|
| 432 |
+
dur = e - s
|
| 433 |
+
if cum_local + dur >= target:
|
| 434 |
+
t = s + (target - cum_local)
|
| 435 |
+
t = min(max(t, s), e)
|
| 436 |
+
break
|
| 437 |
+
cum_local += dur
|
| 438 |
+
s0 = float(t)
|
| 439 |
+
# Keep the word fully inside the voice range when possible.
|
| 440 |
+
end_limit = right_t
|
| 441 |
+
for s, e in voice_ranges:
|
| 442 |
+
if s0 >= s and s0 <= e:
|
| 443 |
+
end_limit = e
|
| 444 |
+
break
|
| 445 |
+
e0 = min(float(end_limit), s0 + avg_dur)
|
| 446 |
+
set_word(run_start + r, s0, max(e0, s0 + 0.06))
|
| 447 |
+
else:
|
| 448 |
+
# Fallback: linear interpolation over the full span.
|
| 449 |
+
span = max(0.001, right_t - left_t)
|
| 450 |
+
step = span / (k + 1)
|
| 451 |
+
for r in range(k):
|
| 452 |
+
s0 = left_t + step * (r + 1)
|
| 453 |
+
e0 = min(right_t, s0 + min(avg_dur, step * 0.9))
|
| 454 |
+
set_word(run_start + r, s0, max(e0, s0 + 0.06))
|
| 455 |
+
elif next_idx is not None and words[next_idx].start is not None:
|
| 456 |
+
right_t = float(words[next_idx].start)
|
| 457 |
+
k = (run_end - run_start) + 1
|
| 458 |
+
start_base = max(0.0, right_t - (avg_dur + 0.02) * k)
|
| 459 |
+
for r in range(k):
|
| 460 |
+
s = start_base + (avg_dur + 0.02) * r
|
| 461 |
+
e = s + avg_dur
|
| 462 |
+
set_word(run_start + r, s, e)
|
| 463 |
+
elif prev_idx >= 0 and words[prev_idx].end is not None:
|
| 464 |
+
left_t = float(words[prev_idx].end)
|
| 465 |
+
k = (run_end - run_start) + 1
|
| 466 |
+
for r in range(k):
|
| 467 |
+
s = left_t + (avg_dur + 0.02) * (r + 1)
|
| 468 |
+
e = s + avg_dur
|
| 469 |
+
set_word(run_start + r, s, e)
|
| 470 |
+
else:
|
| 471 |
+
# All missing; assign a simple ramp.
|
| 472 |
+
for r in range(run_end - run_start + 1):
|
| 473 |
+
s = (avg_dur + 0.02) * r
|
| 474 |
+
e = s + avg_dur
|
| 475 |
+
set_word(run_start + r, s, e)
|
| 476 |
+
|
| 477 |
return words
|
| 478 |
|
| 479 |
|
| 480 |
+
def _segment_from_words(
|
| 481 |
+
words: list[WordTS],
|
| 482 |
+
*,
|
| 483 |
+
mode: SrtMode,
|
| 484 |
+
silence_gap_s: float = SILENCE_GAP_S,
|
| 485 |
+
) -> list[dict]:
|
| 486 |
+
if not words:
|
| 487 |
+
return []
|
| 488 |
+
|
| 489 |
+
max_words = 8 if mode == "sentence" else 24
|
| 490 |
+
max_block_dur = 7.0 if mode == "sentence" else 14.0
|
| 491 |
+
|
| 492 |
+
segs: list[dict] = []
|
| 493 |
+
cur: list[WordTS] = []
|
| 494 |
|
| 495 |
def flush() -> None:
|
| 496 |
+
nonlocal cur
|
| 497 |
+
if not cur:
|
| 498 |
return
|
| 499 |
+
start = float(cur[0].start or 0.0)
|
| 500 |
+
end = float(cur[-1].end or start)
|
| 501 |
+
text = _cleanup_spacing(" ".join(w.display for w in cur))
|
| 502 |
if text:
|
| 503 |
+
segs.append({"start": start, "end": end, "text": text})
|
| 504 |
+
cur = []
|
| 505 |
|
| 506 |
+
for idx, w in enumerate(words):
|
| 507 |
+
if w.start is None or w.end is None:
|
| 508 |
+
continue
|
| 509 |
+
if cur:
|
| 510 |
+
gap = float(w.start) - float(cur[-1].end or w.start)
|
| 511 |
+
if gap >= silence_gap_s:
|
| 512 |
flush()
|
| 513 |
|
| 514 |
+
cur.append(w)
|
| 515 |
|
| 516 |
+
# Splitting rules
|
| 517 |
+
if len(cur) >= max_words:
|
|
|
|
|
|
|
|
|
|
| 518 |
flush()
|
| 519 |
continue
|
| 520 |
+
if cur and (float(cur[-1].end or 0.0) - float(cur[0].start or 0.0)) >= max_block_dur:
|
|
|
|
| 521 |
flush()
|
| 522 |
continue
|
| 523 |
+
if w.boundary_after:
|
| 524 |
+
flush()
|
| 525 |
+
continue
|
| 526 |
+
if mode == "sentence" and w.line_break_after:
|
| 527 |
+
flush()
|
| 528 |
+
continue
|
| 529 |
+
if mode == "paragraph" and w.line_break_after and len(cur) >= 16:
|
| 530 |
flush()
|
| 531 |
|
| 532 |
flush()
|
| 533 |
+
return segs
|
| 534 |
|
| 535 |
|
| 536 |
+
def _enforce_timing_rules(segments: list[dict]) -> list[dict]:
|
| 537 |
+
if not segments:
|
| 538 |
+
return []
|
| 539 |
+
segments = sorted(segments, key=lambda s: (float(s["start"]), float(s["end"])))
|
| 540 |
+
|
| 541 |
+
fixed: list[dict] = []
|
| 542 |
+
prev_end = 0.0
|
| 543 |
+
for seg in segments:
|
| 544 |
+
start = float(seg["start"])
|
| 545 |
+
end = float(seg["end"])
|
| 546 |
+
text = (seg.get("text") or "").strip()
|
| 547 |
+
if not text:
|
| 548 |
+
continue
|
| 549 |
+
|
| 550 |
+
start = max(start, prev_end + MIN_GAP_S) if fixed else max(0.0, start)
|
| 551 |
+
end = max(end, start + MIN_DUR_S)
|
| 552 |
+
|
| 553 |
+
fixed.append({"start": start, "end": end, "text": text})
|
| 554 |
+
prev_end = end
|
| 555 |
+
|
| 556 |
+
return fixed
|
| 557 |
+
|
| 558 |
+
|
| 559 |
+
def _overlaps_voice(start: float, end: float, voice_segments: list[tuple[float, float]]) -> bool:
|
| 560 |
+
for vs, ve in voice_segments:
|
| 561 |
+
if max(start, vs) < min(end, ve):
|
| 562 |
+
return True
|
| 563 |
+
return False
|
| 564 |
+
|
| 565 |
+
|
| 566 |
+
def _instrumental_tag_segments(gaps: list[tuple[float, float]]) -> list[dict]:
|
| 567 |
+
out: list[dict] = []
|
| 568 |
+
for s, e in gaps:
|
| 569 |
+
if (e - s) >= SILENCE_GAP_S:
|
| 570 |
+
out.append({"start": float(s), "end": float(e), "text": "[INSTRUMENTAL]"})
|
| 571 |
+
return out
|
| 572 |
+
|
| 573 |
+
|
| 574 |
+
def _extract_window_wav(input_wav_16k: str, out_wav: str, start_s: float, end_s: float) -> None:
|
| 575 |
+
cmd = [
|
| 576 |
+
"ffmpeg",
|
| 577 |
+
"-y",
|
| 578 |
+
"-i",
|
| 579 |
+
input_wav_16k,
|
| 580 |
+
"-ss",
|
| 581 |
+
f"{max(0.0, start_s):.3f}",
|
| 582 |
+
"-to",
|
| 583 |
+
f"{max(0.0, end_s):.3f}",
|
| 584 |
+
"-ac",
|
| 585 |
+
"1",
|
| 586 |
+
"-ar",
|
| 587 |
+
"16000",
|
| 588 |
+
"-f",
|
| 589 |
+
"wav",
|
| 590 |
+
out_wav,
|
| 591 |
+
]
|
| 592 |
+
_run_cmd(cmd)
|
| 593 |
|
| 594 |
+
|
| 595 |
+
def _transcribe_words(wav_16k_mono_path: str, *, beam_size: int) -> list[WordTS]:
|
| 596 |
+
if whisper_model is None:
|
| 597 |
+
raise HTTPException(status_code=503, detail="ASR model is not ready")
|
| 598 |
+
|
| 599 |
+
segments, _info = whisper_model.transcribe(
|
| 600 |
+
wav_16k_mono_path,
|
| 601 |
+
word_timestamps=True,
|
| 602 |
+
beam_size=int(beam_size),
|
| 603 |
+
best_of=max(beam_size, 5),
|
| 604 |
+
temperature=0.0,
|
| 605 |
+
vad_filter=False,
|
| 606 |
condition_on_previous_text=False,
|
|
|
|
| 607 |
)
|
| 608 |
+
return _flatten_asr_words(segments)
|
| 609 |
+
|
| 610 |
+
|
| 611 |
+
def _fill_lyrics_timestamps_with_fallback(
|
| 612 |
+
lyrics_words: list[WordTS],
|
| 613 |
+
asr_words: list[WordTS],
|
| 614 |
+
vocals_16k_path: str,
|
| 615 |
+
voice_segments: list[tuple[float, float]],
|
| 616 |
+
temp_dir: str,
|
| 617 |
+
) -> list[WordTS]:
|
| 618 |
+
mapping = _align_words_dp(lyrics_words, asr_words)
|
| 619 |
+
|
| 620 |
+
# Apply direct timestamps where matched.
|
| 621 |
+
filled: list[WordTS] = []
|
| 622 |
+
for i, lw in enumerate(lyrics_words):
|
| 623 |
+
j = mapping[i]
|
| 624 |
+
if j is not None and asr_words[j].start is not None and asr_words[j].end is not None:
|
| 625 |
+
aw = asr_words[j]
|
| 626 |
+
filled.append(
|
| 627 |
+
WordTS(
|
| 628 |
+
display=lw.display,
|
| 629 |
+
norm=lw.norm,
|
| 630 |
+
start=float(aw.start),
|
| 631 |
+
end=float(aw.end),
|
| 632 |
+
boundary_after=lw.boundary_after,
|
| 633 |
+
line_break_after=lw.line_break_after,
|
| 634 |
+
)
|
| 635 |
+
)
|
| 636 |
+
else:
|
| 637 |
+
filled.append(
|
| 638 |
+
WordTS(
|
| 639 |
+
display=lw.display,
|
| 640 |
+
norm=lw.norm,
|
| 641 |
+
start=None,
|
| 642 |
+
end=None,
|
| 643 |
+
boundary_after=lw.boundary_after,
|
| 644 |
+
line_break_after=lw.line_break_after,
|
| 645 |
+
)
|
| 646 |
+
)
|
| 647 |
+
|
| 648 |
+
# Identify long mismatch runs and try a windowed ASR pass (limited).
|
| 649 |
+
max_windows = 3
|
| 650 |
+
i = 0
|
| 651 |
+
windows_done = 0
|
| 652 |
+
while i < len(filled) and windows_done < max_windows:
|
| 653 |
+
if filled[i].start is not None:
|
| 654 |
+
i += 1
|
| 655 |
+
continue
|
| 656 |
+
run_start = i
|
| 657 |
+
while i < len(filled) and filled[i].start is None:
|
| 658 |
+
i += 1
|
| 659 |
+
run_end = i - 1
|
| 660 |
+
run_len = run_end - run_start + 1
|
| 661 |
|
| 662 |
+
if run_len < 10:
|
| 663 |
+
continue
|
| 664 |
|
| 665 |
+
# Window bounds from neighboring known timestamps.
|
| 666 |
+
left_end = None
|
| 667 |
+
right_start = None
|
| 668 |
+
if run_start - 1 >= 0:
|
| 669 |
+
left_end = filled[run_start - 1].end
|
| 670 |
+
if run_end + 1 < len(filled):
|
| 671 |
+
right_start = filled[run_end + 1].start
|
| 672 |
|
| 673 |
+
if left_end is None or right_start is None:
|
| 674 |
+
continue
|
| 675 |
+
|
| 676 |
+
w_start = max(0.0, float(left_end) - 0.8)
|
| 677 |
+
w_end = float(right_start) + 0.8
|
| 678 |
+
if (w_end - w_start) < 2.0:
|
| 679 |
+
continue
|
| 680 |
+
|
| 681 |
+
clip_path = os.path.join(temp_dir, f"asr_clip_{windows_done}.wav")
|
| 682 |
+
_extract_window_wav(vocals_16k_path, clip_path, w_start, w_end)
|
| 683 |
+
clip_words = _transcribe_words(clip_path, beam_size=10)
|
| 684 |
+
# Offset clip words into global timeline
|
| 685 |
+
clip_words_off = [
|
| 686 |
+
WordTS(display=w.display, norm=w.norm, start=float(w.start or 0.0) + w_start, end=float(w.end or 0.0) + w_start, boundary_after=w.boundary_after)
|
| 687 |
+
for w in clip_words
|
| 688 |
+
]
|
| 689 |
+
|
| 690 |
+
sub_lyrics = filled[run_start : run_end + 1]
|
| 691 |
+
sub_mapping = _align_words_dp(sub_lyrics, clip_words_off)
|
| 692 |
+
for k, j in enumerate(sub_mapping):
|
| 693 |
+
if j is None:
|
| 694 |
+
continue
|
| 695 |
+
aw = clip_words_off[j]
|
| 696 |
+
filled[run_start + k] = WordTS(
|
| 697 |
+
display=filled[run_start + k].display,
|
| 698 |
+
norm=filled[run_start + k].norm,
|
| 699 |
+
start=float(aw.start or 0.0),
|
| 700 |
+
end=float(aw.end or 0.0),
|
| 701 |
+
boundary_after=filled[run_start + k].boundary_after,
|
| 702 |
+
line_break_after=filled[run_start + k].line_break_after,
|
| 703 |
+
)
|
| 704 |
+
|
| 705 |
+
windows_done += 1
|
| 706 |
+
|
| 707 |
+
return _interpolate_missing_timestamps(filled, voice_segments=voice_segments)
|
| 708 |
|
| 709 |
|
| 710 |
@app.post("/srt", response_class=PlainTextResponse)
|
| 711 |
async def generate_srt(
|
| 712 |
audio_file: UploadFile = File(...),
|
| 713 |
+
lyrics_text: str = Form(""),
|
| 714 |
+
srt_mode: str = Form("sentence"),
|
| 715 |
+
add_instrumental_tags: bool = Form(False),
|
| 716 |
):
|
| 717 |
"""
|
| 718 |
+
Production lyric-to-SRT pipeline (open-source only):
|
| 719 |
+
1) Demucs vocal isolation (vocals stem)
|
| 720 |
+
2) VAD on vocals stem (instrumental gaps)
|
| 721 |
+
3) faster-whisper ASR on vocals stem (word timestamps)
|
| 722 |
+
4) Optional lyrics-guided alignment (lyrics text becomes source of truth)
|
| 723 |
+
5) Segment into SRT (sentence/paragraph) with silence-aware splits
|
| 724 |
"""
|
| 725 |
+
if whisper_model is None:
|
| 726 |
+
raise HTTPException(status_code=503, detail="ASR model is not ready")
|
| 727 |
+
|
| 728 |
+
mode = (srt_mode or "").strip().lower()
|
| 729 |
+
if mode not in ("sentence", "paragraph"):
|
| 730 |
+
raise HTTPException(status_code=400, detail="Invalid srt_mode (expected 'sentence' or 'paragraph')")
|
| 731 |
+
|
| 732 |
temp_dir = tempfile.mkdtemp(prefix="lyric-sync-")
|
| 733 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 734 |
source_name = audio_file.filename or "audio"
|
| 735 |
+
input_path = os.path.join(temp_dir, source_name)
|
| 736 |
+
with open(input_path, "wb") as f:
|
| 737 |
shutil.copyfileobj(audio_file.file, f)
|
| 738 |
|
| 739 |
+
# Convert to a stable wav for Demucs
|
| 740 |
+
input_wav = os.path.join(temp_dir, "input_44k_stereo.wav")
|
| 741 |
+
_ffmpeg_to_wav(input_path, input_wav, sample_rate=44100, mono=False)
|
| 742 |
+
|
| 743 |
+
vocals_wav = _demucs_extract_vocals(input_wav, temp_dir)
|
| 744 |
+
|
| 745 |
+
# Canonical vocals wav for VAD + ASR (16k mono)
|
| 746 |
+
vocals_16k = os.path.join(temp_dir, "vocals_16k_mono.wav")
|
| 747 |
+
_ffmpeg_to_wav(vocals_wav, vocals_16k, sample_rate=16000, mono=True)
|
| 748 |
+
|
| 749 |
+
voice_segments, instrumental_gaps = _vad_voice_segments(vocals_16k, gap_s=SILENCE_GAP_S)
|
| 750 |
+
|
| 751 |
+
# ASR pass on vocals (word timestamps)
|
| 752 |
+
asr_words = _transcribe_words(vocals_16k, beam_size=6)
|
| 753 |
+
if not asr_words:
|
| 754 |
+
return PlainTextResponse(content="", media_type="application/x-subrip")
|
| 755 |
+
|
| 756 |
+
# Choose source-of-truth tokens
|
| 757 |
+
lyrics_provided = bool((lyrics_text or "").strip())
|
| 758 |
+
if lyrics_provided:
|
| 759 |
+
lyric_words = _parse_lyrics_words(lyrics_text)
|
| 760 |
+
if not lyric_words:
|
| 761 |
+
raise HTTPException(status_code=400, detail="Lyrics provided but no usable words were found")
|
| 762 |
+
aligned_words = _fill_lyrics_timestamps_with_fallback(lyric_words, asr_words, vocals_16k, voice_segments, temp_dir)
|
| 763 |
+
else:
|
| 764 |
+
aligned_words = asr_words
|
| 765 |
+
|
| 766 |
+
# Segment AFTER alignment/transcription
|
| 767 |
+
segments = _segment_from_words(aligned_words, mode=mode) # type: ignore[arg-type]
|
| 768 |
+
|
| 769 |
+
# Enforce "no subtitles during instrumentals" via VAD (drop segments outside voice)
|
| 770 |
+
segments = [s for s in segments if _overlaps_voice(float(s["start"]), float(s["end"]), voice_segments)]
|
| 771 |
+
|
| 772 |
+
if add_instrumental_tags:
|
| 773 |
+
segments.extend(_instrumental_tag_segments(instrumental_gaps))
|
| 774 |
+
|
| 775 |
+
segments = _enforce_timing_rules(segments)
|
| 776 |
+
return PlainTextResponse(content=_build_srt(segments), media_type="application/x-subrip")
|
| 777 |
except HTTPException:
|
| 778 |
raise
|
| 779 |
except Exception as e:
|
|
|
|
| 786 |
|
| 787 |
|
| 788 |
@app.post("/align", response_class=PlainTextResponse)
|
| 789 |
+
async def align_compat(
|
| 790 |
audio_file: UploadFile = File(...),
|
| 791 |
+
lyrics_text: str = Form(""),
|
| 792 |
+
srt_mode: str = Form("sentence"),
|
| 793 |
+
add_instrumental_tags: bool = Form(False),
|
| 794 |
):
|
| 795 |
+
# Backward-compat route for older frontend builds.
|
| 796 |
+
return await generate_srt(
|
| 797 |
+
audio_file=audio_file,
|
| 798 |
+
lyrics_text=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