Update app.py
Browse files
app.py
CHANGED
|
@@ -19,7 +19,6 @@ if not hasattr(huggingface_hub, "HfFolder"):
|
|
| 19 |
import spaces
|
| 20 |
import gradio as gr
|
| 21 |
import asyncio
|
| 22 |
-
import math
|
| 23 |
import os
|
| 24 |
import re
|
| 25 |
import secrets
|
|
@@ -48,6 +47,7 @@ from pyrogram.types import Message
|
|
| 48 |
BASE_DIR = Path(__file__).resolve().parent
|
| 49 |
HF_ASR_MODEL = os.getenv("HF_ASR_MODEL", "Systran/faster-whisper-small").strip()
|
| 50 |
HF_MT_MODEL = os.getenv("HF_MT_MODEL", "Helsinki-NLP/opus-mt-en-hi").strip()
|
|
|
|
| 51 |
|
| 52 |
|
| 53 |
def _normalize_turso_url(raw_url: str) -> str:
|
|
@@ -81,14 +81,13 @@ BASE_URL: str = _detect_base_url()
|
|
| 81 |
DUB_MAX_BYTES: int = int(os.getenv("DUB_TEST_MAX_BYTES", str(100 * 1024 * 1024)))
|
| 82 |
MIN_FREE_DISK_BYTES: int = 1024 * 1024 * 1024
|
| 83 |
|
| 84 |
-
|
| 85 |
-
|
| 86 |
|
| 87 |
-
# Subtle prosody keeps edge-tts natural and avoids robotic/metallic artifacts
|
| 88 |
EMOTION_PROSODY: dict[str, tuple[str, str]] = {
|
| 89 |
"neutral": ("+0%", "+0Hz"),
|
| 90 |
-
"happy": ("+
|
| 91 |
-
"excited": ("+
|
| 92 |
"sad": ("-3%", "-2Hz"),
|
| 93 |
"angry": ("+2%", "-2Hz"),
|
| 94 |
}
|
|
@@ -97,6 +96,12 @@ _MT_TOKENIZER = None
|
|
| 97 |
_MT_MODEL = None
|
| 98 |
_MT_LOCK = threading.Lock()
|
| 99 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 100 |
|
| 101 |
# ==============================================================================
|
| 102 |
# 2. HELPERS & FFMPEG
|
|
@@ -161,8 +166,27 @@ def _detect_emotion_label(text: str) -> str:
|
|
| 161 |
return "neutral"
|
| 162 |
|
| 163 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 164 |
def _build_atempo_chain(tempo: float) -> str:
|
| 165 |
-
"""FFmpeg atempo accepts values in [0.5, 2.0] per filter; chain if needed."""
|
| 166 |
clamped = max(0.5, min(2.0, tempo))
|
| 167 |
if abs(clamped - 1.0) < 0.02:
|
| 168 |
return ""
|
|
@@ -170,7 +194,7 @@ def _build_atempo_chain(tempo: float) -> str:
|
|
| 170 |
|
| 171 |
|
| 172 |
# ==============================================================================
|
| 173 |
-
# 3. SPEECH-TO-TEXT + OPUS-MT TRANSLATION +
|
| 174 |
# ==============================================================================
|
| 175 |
|
| 176 |
@spaces.GPU(duration=60)
|
|
@@ -216,7 +240,7 @@ def _get_mt_model():
|
|
| 216 |
if _MT_TOKENIZER is None or _MT_MODEL is None:
|
| 217 |
from transformers import AutoModelForSeq2SeqLM, AutoTokenizer # type: ignore
|
| 218 |
|
| 219 |
-
print(f"[DUB] Loading
|
| 220 |
tok = AutoTokenizer.from_pretrained(HF_MT_MODEL)
|
| 221 |
mdl = AutoModelForSeq2SeqLM.from_pretrained(HF_MT_MODEL)
|
| 222 |
_MT_TOKENIZER = tok
|
|
@@ -238,21 +262,86 @@ def _translate_to_hindi_sync(segments: list[dict[str, Any]]) -> list[dict[str, A
|
|
| 238 |
clean_hi = hi_txt if hi_txt else seg["en_text"]
|
| 239 |
gender = seg["gender"]
|
| 240 |
emotion = seg.get("emotion", "neutral")
|
| 241 |
-
voice = MALE_HINDI_VOICE if gender == "MALE" else FEMALE_HINDI_VOICE
|
| 242 |
-
rate, pitch = EMOTION_PROSODY.get(emotion, ("+0%", "+0Hz"))
|
| 243 |
-
|
| 244 |
translated.append(
|
| 245 |
{
|
| 246 |
**seg,
|
| 247 |
-
"voice": voice,
|
| 248 |
-
"rate": rate,
|
| 249 |
-
"pitch": pitch,
|
| 250 |
"hi_text": clean_hi,
|
|
|
|
| 251 |
}
|
| 252 |
)
|
| 253 |
return translated
|
| 254 |
|
| 255 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 256 |
async def _make_silence_wav(duration_s: float, out_wav: str) -> None:
|
| 257 |
dur = max(0.02, duration_s)
|
| 258 |
ok, err = await _run_ffmpeg(
|
|
@@ -269,46 +358,32 @@ async def _make_silence_wav(duration_s: float, out_wav: str) -> None:
|
|
| 269 |
|
| 270 |
|
| 271 |
async def _render_synced_speech_clip(seg: dict[str, Any], slot_dur_s: float, out_wav_path: str) -> None:
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
comm = edge_tts.Communicate(
|
| 276 |
-
text=seg["hi_text"],
|
| 277 |
-
voice=seg["voice"],
|
| 278 |
-
rate=seg["rate"],
|
| 279 |
-
pitch=seg["pitch"],
|
| 280 |
-
)
|
| 281 |
-
await asyncio.wait_for(comm.save(mp3_path), timeout=15.0)
|
| 282 |
-
if not os.path.exists(mp3_path) or os.path.getsize(mp3_path) < 200:
|
| 283 |
-
raise RuntimeError(f"TTS returned empty audio for segment: {seg['hi_text'][:40]}")
|
| 284 |
|
| 285 |
raw_wav = f"{out_wav_path}_raw.wav"
|
| 286 |
ok, err = await _run_ffmpeg(
|
| 287 |
-
["-i",
|
| 288 |
-
timeout_sec=
|
| 289 |
)
|
| 290 |
-
if os.path.exists(
|
| 291 |
-
os.remove(
|
| 292 |
if not ok or not os.path.exists(raw_wav):
|
| 293 |
-
raise RuntimeError(f"Failed decoding
|
| 294 |
|
| 295 |
spoken_dur = _wav_duration_seconds(raw_wav)
|
| 296 |
filters_chain: list[str] = []
|
| 297 |
|
| 298 |
-
# Gently speed up if Hindi speech is longer than its available time slot (up to 1.25x)
|
| 299 |
if spoken_dur > slot_dur_s and slot_dur_s > 0.3:
|
| 300 |
-
|
| 301 |
-
tempo_filter = _build_atempo_chain(needed_tempo)
|
| 302 |
if tempo_filter:
|
| 303 |
filters_chain.append(tempo_filter)
|
| 304 |
|
| 305 |
filters_chain.append("asetpts=PTS-STARTPTS")
|
| 306 |
-
af_expr = ",".join(filters_chain)
|
| 307 |
-
|
| 308 |
ok, err = await _run_ffmpeg(
|
| 309 |
[
|
| 310 |
"-i", raw_wav,
|
| 311 |
-
"-af",
|
| 312 |
"-ar", "44100",
|
| 313 |
"-ac", "2",
|
| 314 |
"-c:a", "pcm_s16le",
|
|
@@ -323,10 +398,6 @@ async def _render_synced_speech_clip(seg: dict[str, Any], slot_dur_s: float, out
|
|
| 323 |
|
| 324 |
|
| 325 |
async def _build_timeline_track(segments: list[dict[str, Any]], total_sec: float, work_dir: str, out_m4a_path: str) -> None:
|
| 326 |
-
"""
|
| 327 |
-
Places each speech clip at its target timestamp sequentially (non-overlapping)
|
| 328 |
-
with exact silence gaps so there is zero amix echo or overlap drift.
|
| 329 |
-
"""
|
| 330 |
timeline_files: list[str] = []
|
| 331 |
cursor_s = 0.0
|
| 332 |
|
|
@@ -339,7 +410,6 @@ async def _build_timeline_track(segments: list[dict[str, Any]], total_sec: float
|
|
| 339 |
timeline_files.append(gap_wav)
|
| 340 |
cursor_s += gap_s
|
| 341 |
|
| 342 |
-
# Available window before next segment starts
|
| 343 |
next_start_s = float(segments[idx]["start_s"]) if idx < len(segments) else total_sec
|
| 344 |
slot_dur_s = max(0.8, next_start_s - cursor_s)
|
| 345 |
|
|
@@ -446,7 +516,7 @@ async def dub_video_to_hindi(src_video_path: str, out_video_path: str, status_cb
|
|
| 446 |
|
| 447 |
|
| 448 |
# ==============================================================================
|
| 449 |
-
# 4. TURSO DATABASE
|
| 450 |
# ==============================================================================
|
| 451 |
|
| 452 |
class TursoDB:
|
|
@@ -456,16 +526,10 @@ class TursoDB:
|
|
| 456 |
"Authorization": f"Bearer {TURSO_AUTH_TOKEN}",
|
| 457 |
"Content-Type": "application/json",
|
| 458 |
}
|
| 459 |
-
self._client: httpx.AsyncClient | None = None
|
| 460 |
|
| 461 |
async def start(self) -> None:
|
| 462 |
-
self._client = httpx.AsyncClient(headers=self.headers, timeout=20.0)
|
| 463 |
await self._init_schema()
|
| 464 |
|
| 465 |
-
async def close(self) -> None:
|
| 466 |
-
if self._client:
|
| 467 |
-
await self._client.aclose()
|
| 468 |
-
|
| 469 |
@staticmethod
|
| 470 |
def _encode_arg(val: Any) -> dict[str, Any]:
|
| 471 |
if val is None:
|
|
@@ -490,17 +554,18 @@ class TursoDB:
|
|
| 490 |
return cell.get("value")
|
| 491 |
|
| 492 |
async def execute(self, sql: str, params: list[Any] | None = None) -> list[dict[str, Any]]:
|
| 493 |
-
assert self._client is not None, "TursoDB not initialized"
|
| 494 |
stmt: dict[str, Any] = {"sql": sql}
|
| 495 |
if params:
|
| 496 |
stmt["args"] = [self._encode_arg(p) for p in params]
|
| 497 |
|
| 498 |
-
|
| 499 |
-
|
| 500 |
-
|
| 501 |
-
|
| 502 |
-
|
| 503 |
-
|
|
|
|
|
|
|
| 504 |
if first["type"] == "error":
|
| 505 |
raise RuntimeError(f"Turso SQL Error: {first['error']}")
|
| 506 |
|
|
@@ -689,7 +754,8 @@ async def cmd_start(_, message: Message) -> None:
|
|
| 689 |
f"Send or forward an English video (up to `{_format_size(DUB_MAX_BYTES)}`) to dub it into Hindi "
|
| 690 |
"with synced timing, Male/Female voice separation, and natural emotion prosody.\n"
|
| 691 |
f"• **ASR Model:** `{HF_ASR_MODEL}`\n"
|
| 692 |
-
f"• **Translation Model:** `{HF_MT_MODEL}`"
|
|
|
|
| 693 |
)
|
| 694 |
|
| 695 |
|
|
@@ -922,7 +988,7 @@ _bg_loop: asyncio.AbstractEventLoop | None = None
|
|
| 922 |
|
| 923 |
@spaces.GPU(duration=20)
|
| 924 |
def check_hf_model_gpu() -> str:
|
| 925 |
-
return f"ZeroGPU ready · ASR: {HF_ASR_MODEL} · MT: {HF_MT_MODEL}"
|
| 926 |
|
| 927 |
|
| 928 |
async def _bg_runner() -> None:
|
|
@@ -950,7 +1016,7 @@ def build_ui() -> gr.Blocks:
|
|
| 950 |
with gr.Blocks(title="Hindi Video Dubbing Bot") as blocks:
|
| 951 |
gr.Markdown(
|
| 952 |
f"# English → Hindi Video Dubbing Bot\n"
|
| 953 |
-
f"• **ASR
|
| 954 |
f"• **Telegram Bot:** Send an English video (up to `{_format_size(DUB_MAX_BYTES)}`) for live progress & Hindi dubbing."
|
| 955 |
)
|
| 956 |
gpu_btn = gr.Button("Verify ZeroGPU & Linked HF Models")
|
|
|
|
| 19 |
import spaces
|
| 20 |
import gradio as gr
|
| 21 |
import asyncio
|
|
|
|
| 22 |
import os
|
| 23 |
import re
|
| 24 |
import secrets
|
|
|
|
| 47 |
BASE_DIR = Path(__file__).resolve().parent
|
| 48 |
HF_ASR_MODEL = os.getenv("HF_ASR_MODEL", "Systran/faster-whisper-small").strip()
|
| 49 |
HF_MT_MODEL = os.getenv("HF_MT_MODEL", "Helsinki-NLP/opus-mt-en-hi").strip()
|
| 50 |
+
HF_TTS_MODEL = os.getenv("HF_TTS_MODEL", "ai4bharat/indic-parler-tts").strip()
|
| 51 |
|
| 52 |
|
| 53 |
def _normalize_turso_url(raw_url: str) -> str:
|
|
|
|
| 81 |
DUB_MAX_BYTES: int = int(os.getenv("DUB_TEST_MAX_BYTES", str(100 * 1024 * 1024)))
|
| 82 |
MIN_FREE_DISK_BYTES: int = 1024 * 1024 * 1024
|
| 83 |
|
| 84 |
+
EDGE_MALE_VOICE = "hi-IN-MadhurNeural"
|
| 85 |
+
EDGE_FEMALE_VOICE = "hi-IN-SwaraNeural"
|
| 86 |
|
|
|
|
| 87 |
EMOTION_PROSODY: dict[str, tuple[str, str]] = {
|
| 88 |
"neutral": ("+0%", "+0Hz"),
|
| 89 |
+
"happy": ("+2%", "+2Hz"),
|
| 90 |
+
"excited": ("+4%", "+3Hz"),
|
| 91 |
"sad": ("-3%", "-2Hz"),
|
| 92 |
"angry": ("+2%", "-2Hz"),
|
| 93 |
}
|
|
|
|
| 96 |
_MT_MODEL = None
|
| 97 |
_MT_LOCK = threading.Lock()
|
| 98 |
|
| 99 |
+
_TTS_MODEL = None
|
| 100 |
+
_TTS_PROMPT_TOK = None
|
| 101 |
+
_TTS_DESC_TOK = None
|
| 102 |
+
_TTS_DEVICE = "cpu"
|
| 103 |
+
_TTS_LOCK = threading.Lock()
|
| 104 |
+
|
| 105 |
|
| 106 |
# ==============================================================================
|
| 107 |
# 2. HELPERS & FFMPEG
|
|
|
|
| 166 |
return "neutral"
|
| 167 |
|
| 168 |
|
| 169 |
+
def _build_parler_description(gender: str, emotion: str) -> str:
|
| 170 |
+
# Descriptive speaker & emotion caption for ai4bharat/indic-parler-tts
|
| 171 |
+
if gender == "MALE":
|
| 172 |
+
speaker = "Rohit"
|
| 173 |
+
base_voice = "A male speaker with a natural, expressive tone"
|
| 174 |
+
else:
|
| 175 |
+
speaker = "Divya"
|
| 176 |
+
base_voice = "A female speaker with a natural, expressive tone"
|
| 177 |
+
|
| 178 |
+
emotion_map = {
|
| 179 |
+
"happy": "cheerful and upbeat",
|
| 180 |
+
"excited": "lively and energetic",
|
| 181 |
+
"sad": "soft and empathetic",
|
| 182 |
+
"angry": "firm and intense",
|
| 183 |
+
"neutral": "calm and conversational",
|
| 184 |
+
}
|
| 185 |
+
mood = emotion_map.get(emotion, "calm and conversational")
|
| 186 |
+
return f"{speaker} speaks with a {mood} delivery. {base_voice}, recorded clearly in a quiet room with very clear audio."
|
| 187 |
+
|
| 188 |
+
|
| 189 |
def _build_atempo_chain(tempo: float) -> str:
|
|
|
|
| 190 |
clamped = max(0.5, min(2.0, tempo))
|
| 191 |
if abs(clamped - 1.0) < 0.02:
|
| 192 |
return ""
|
|
|
|
| 194 |
|
| 195 |
|
| 196 |
# ==============================================================================
|
| 197 |
+
# 3. SPEECH-TO-TEXT + OPUS-MT TRANSLATION + INDIC PARLER-TTS + SYNCED MIXER
|
| 198 |
# ==============================================================================
|
| 199 |
|
| 200 |
@spaces.GPU(duration=60)
|
|
|
|
| 240 |
if _MT_TOKENIZER is None or _MT_MODEL is None:
|
| 241 |
from transformers import AutoModelForSeq2SeqLM, AutoTokenizer # type: ignore
|
| 242 |
|
| 243 |
+
print(f"[DUB] Loading translation model ({HF_MT_MODEL})...", flush=True)
|
| 244 |
tok = AutoTokenizer.from_pretrained(HF_MT_MODEL)
|
| 245 |
mdl = AutoModelForSeq2SeqLM.from_pretrained(HF_MT_MODEL)
|
| 246 |
_MT_TOKENIZER = tok
|
|
|
|
| 262 |
clean_hi = hi_txt if hi_txt else seg["en_text"]
|
| 263 |
gender = seg["gender"]
|
| 264 |
emotion = seg.get("emotion", "neutral")
|
|
|
|
|
|
|
|
|
|
| 265 |
translated.append(
|
| 266 |
{
|
| 267 |
**seg,
|
|
|
|
|
|
|
|
|
|
| 268 |
"hi_text": clean_hi,
|
| 269 |
+
"description": _build_parler_description(gender, emotion),
|
| 270 |
}
|
| 271 |
)
|
| 272 |
return translated
|
| 273 |
|
| 274 |
|
| 275 |
+
def _get_parler_tts():
|
| 276 |
+
global _TTS_MODEL, _TTS_PROMPT_TOK, _TTS_DESC_TOK, _TTS_DEVICE
|
| 277 |
+
if _TTS_MODEL is not None:
|
| 278 |
+
return _TTS_MODEL, _TTS_PROMPT_TOK, _TTS_DESC_TOK, _TTS_DEVICE
|
| 279 |
+
|
| 280 |
+
with _TTS_LOCK:
|
| 281 |
+
if _TTS_MODEL is None:
|
| 282 |
+
import torch # type: ignore
|
| 283 |
+
from parler_tts import ParlerTTSForConditionalGeneration # type: ignore
|
| 284 |
+
from transformers import AutoTokenizer # type: ignore
|
| 285 |
+
|
| 286 |
+
device = "cuda:0" if torch.cuda.is_available() else "cpu"
|
| 287 |
+
dtype = torch.float16 if device.startswith("cuda") else torch.float32
|
| 288 |
+
print(f"[DUB] Loading {HF_TTS_MODEL} on {device}...", flush=True)
|
| 289 |
+
|
| 290 |
+
model = ParlerTTSForConditionalGeneration.from_pretrained(HF_TTS_MODEL, torch_dtype=dtype).to(device)
|
| 291 |
+
prompt_tok = AutoTokenizer.from_pretrained(HF_TTS_MODEL)
|
| 292 |
+
desc_tok_name = getattr(model.config, "text_encoder", None) or HF_TTS_MODEL
|
| 293 |
+
desc_tok = AutoTokenizer.from_pretrained(desc_tok_name)
|
| 294 |
+
|
| 295 |
+
_TTS_MODEL = model
|
| 296 |
+
_TTS_PROMPT_TOK = prompt_tok
|
| 297 |
+
_TTS_DESC_TOK = desc_tok
|
| 298 |
+
_TTS_DEVICE = device
|
| 299 |
+
|
| 300 |
+
return _TTS_MODEL, _TTS_PROMPT_TOK, _TTS_DESC_TOK, _TTS_DEVICE
|
| 301 |
+
|
| 302 |
+
|
| 303 |
+
@spaces.GPU(duration=90)
|
| 304 |
+
def _gpu_synth_parler_clip(hi_text: str, description: str, out_wav: str) -> bool:
|
| 305 |
+
try:
|
| 306 |
+
import soundfile as sf # type: ignore
|
| 307 |
+
import torch # type: ignore
|
| 308 |
+
|
| 309 |
+
model, prompt_tok, desc_tok, device = _get_parler_tts()
|
| 310 |
+
desc_ids = desc_tok(description, return_tensors="pt").input_ids.to(device)
|
| 311 |
+
prompt_ids = prompt_tok(hi_text, return_tensors="pt").input_ids.to(device)
|
| 312 |
+
|
| 313 |
+
with torch.inference_mode():
|
| 314 |
+
gen = model.generate(input_ids=desc_ids, prompt_input_ids=prompt_ids)
|
| 315 |
+
|
| 316 |
+
audio_arr = gen.cpu().numpy().squeeze()
|
| 317 |
+
sr = int(getattr(model.config, "sampling_rate", 44100) or 44100)
|
| 318 |
+
sf.write(out_wav, audio_arr, sr)
|
| 319 |
+
return os.path.exists(out_wav) and os.path.getsize(out_wav) > 400
|
| 320 |
+
except Exception as exc:
|
| 321 |
+
print(f"[DUB PARLER FALLBACK] {type(exc).__name__}: {exc}", flush=True)
|
| 322 |
+
return False
|
| 323 |
+
|
| 324 |
+
|
| 325 |
+
async def _synth_natural_hindi_clip(seg: dict[str, Any], base_path: str) -> str:
|
| 326 |
+
parler_wav = f"{base_path}_parler.wav"
|
| 327 |
+
ok = await asyncio.to_thread(_gpu_synth_parler_clip, seg["hi_text"], seg["description"], parler_wav)
|
| 328 |
+
if ok:
|
| 329 |
+
return parler_wav
|
| 330 |
+
|
| 331 |
+
if os.path.exists(parler_wav):
|
| 332 |
+
os.remove(parler_wav)
|
| 333 |
+
|
| 334 |
+
# Fallback to edge-tts with subtle prosody if parler-tts package isn't installed
|
| 335 |
+
mp3_path = f"{base_path}_edge.mp3"
|
| 336 |
+
voice = EDGE_MALE_VOICE if seg["gender"] == "MALE" else EDGE_FEMALE_VOICE
|
| 337 |
+
rate, pitch = EMOTION_PROSODY.get(seg.get("emotion", "neutral"), ("+0%", "+0Hz"))
|
| 338 |
+
comm = edge_tts.Communicate(text=seg["hi_text"], voice=voice, rate=rate, pitch=pitch)
|
| 339 |
+
await asyncio.wait_for(comm.save(mp3_path), timeout=15.0)
|
| 340 |
+
if not os.path.exists(mp3_path) or os.path.getsize(mp3_path) < 200:
|
| 341 |
+
raise RuntimeError(f"TTS returned empty audio for: {seg['hi_text'][:40]}")
|
| 342 |
+
return mp3_path
|
| 343 |
+
|
| 344 |
+
|
| 345 |
async def _make_silence_wav(duration_s: float, out_wav: str) -> None:
|
| 346 |
dur = max(0.02, duration_s)
|
| 347 |
ok, err = await _run_ffmpeg(
|
|
|
|
| 358 |
|
| 359 |
|
| 360 |
async def _render_synced_speech_clip(seg: dict[str, Any], slot_dur_s: float, out_wav_path: str) -> None:
|
| 361 |
+
print(f"[DUB VOICE] {seg['gender']} ({seg['emotion']}): {seg['hi_text'][:50]}", flush=True)
|
| 362 |
+
src_clip = await _synth_natural_hindi_clip(seg, f"{out_wav_path}_src")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 363 |
|
| 364 |
raw_wav = f"{out_wav_path}_raw.wav"
|
| 365 |
ok, err = await _run_ffmpeg(
|
| 366 |
+
["-i", src_clip, "-ar", "44100", "-ac", "2", "-c:a", "pcm_s16le", raw_wav],
|
| 367 |
+
timeout_sec=20.0,
|
| 368 |
)
|
| 369 |
+
if os.path.exists(src_clip):
|
| 370 |
+
os.remove(src_clip)
|
| 371 |
if not ok or not os.path.exists(raw_wav):
|
| 372 |
+
raise RuntimeError(f"Failed decoding synthesized audio: {err}")
|
| 373 |
|
| 374 |
spoken_dur = _wav_duration_seconds(raw_wav)
|
| 375 |
filters_chain: list[str] = []
|
| 376 |
|
|
|
|
| 377 |
if spoken_dur > slot_dur_s and slot_dur_s > 0.3:
|
| 378 |
+
tempo_filter = _build_atempo_chain(min(1.25, spoken_dur / slot_dur_s))
|
|
|
|
| 379 |
if tempo_filter:
|
| 380 |
filters_chain.append(tempo_filter)
|
| 381 |
|
| 382 |
filters_chain.append("asetpts=PTS-STARTPTS")
|
|
|
|
|
|
|
| 383 |
ok, err = await _run_ffmpeg(
|
| 384 |
[
|
| 385 |
"-i", raw_wav,
|
| 386 |
+
"-af", ",".join(filters_chain),
|
| 387 |
"-ar", "44100",
|
| 388 |
"-ac", "2",
|
| 389 |
"-c:a", "pcm_s16le",
|
|
|
|
| 398 |
|
| 399 |
|
| 400 |
async def _build_timeline_track(segments: list[dict[str, Any]], total_sec: float, work_dir: str, out_m4a_path: str) -> None:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 401 |
timeline_files: list[str] = []
|
| 402 |
cursor_s = 0.0
|
| 403 |
|
|
|
|
| 410 |
timeline_files.append(gap_wav)
|
| 411 |
cursor_s += gap_s
|
| 412 |
|
|
|
|
| 413 |
next_start_s = float(segments[idx]["start_s"]) if idx < len(segments) else total_sec
|
| 414 |
slot_dur_s = max(0.8, next_start_s - cursor_s)
|
| 415 |
|
|
|
|
| 516 |
|
| 517 |
|
| 518 |
# ==============================================================================
|
| 519 |
+
# 4. TURSO DATABASE (EVENT-LOOP-SAFE PER-CALL CLIENT)
|
| 520 |
# ==============================================================================
|
| 521 |
|
| 522 |
class TursoDB:
|
|
|
|
| 526 |
"Authorization": f"Bearer {TURSO_AUTH_TOKEN}",
|
| 527 |
"Content-Type": "application/json",
|
| 528 |
}
|
|
|
|
| 529 |
|
| 530 |
async def start(self) -> None:
|
|
|
|
| 531 |
await self._init_schema()
|
| 532 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 533 |
@staticmethod
|
| 534 |
def _encode_arg(val: Any) -> dict[str, Any]:
|
| 535 |
if val is None:
|
|
|
|
| 554 |
return cell.get("value")
|
| 555 |
|
| 556 |
async def execute(self, sql: str, params: list[Any] | None = None) -> list[dict[str, Any]]:
|
|
|
|
| 557 |
stmt: dict[str, Any] = {"sql": sql}
|
| 558 |
if params:
|
| 559 |
stmt["args"] = [self._encode_arg(p) for p in params]
|
| 560 |
|
| 561 |
+
async with httpx.AsyncClient(headers=self.headers, timeout=20.0) as client:
|
| 562 |
+
resp = await client.post(
|
| 563 |
+
self.pipeline_url,
|
| 564 |
+
json={"requests": [{"type": "execute", "stmt": stmt}, {"type": "close"}]},
|
| 565 |
+
)
|
| 566 |
+
resp.raise_for_status()
|
| 567 |
+
first = resp.json()["results"][0]
|
| 568 |
+
|
| 569 |
if first["type"] == "error":
|
| 570 |
raise RuntimeError(f"Turso SQL Error: {first['error']}")
|
| 571 |
|
|
|
|
| 754 |
f"Send or forward an English video (up to `{_format_size(DUB_MAX_BYTES)}`) to dub it into Hindi "
|
| 755 |
"with synced timing, Male/Female voice separation, and natural emotion prosody.\n"
|
| 756 |
f"• **ASR Model:** `{HF_ASR_MODEL}`\n"
|
| 757 |
+
f"• **Translation Model:** `{HF_MT_MODEL}`\n"
|
| 758 |
+
f"• **Natural Hindi TTS:** `{HF_TTS_MODEL}`"
|
| 759 |
)
|
| 760 |
|
| 761 |
|
|
|
|
| 988 |
|
| 989 |
@spaces.GPU(duration=20)
|
| 990 |
def check_hf_model_gpu() -> str:
|
| 991 |
+
return f"ZeroGPU ready · ASR: {HF_ASR_MODEL} · MT: {HF_MT_MODEL} · TTS: {HF_TTS_MODEL}"
|
| 992 |
|
| 993 |
|
| 994 |
async def _bg_runner() -> None:
|
|
|
|
| 1016 |
with gr.Blocks(title="Hindi Video Dubbing Bot") as blocks:
|
| 1017 |
gr.Markdown(
|
| 1018 |
f"# English → Hindi Video Dubbing Bot\n"
|
| 1019 |
+
f"• **ASR:** `{HF_ASR_MODEL}` · **MT:** `{HF_MT_MODEL}` · **TTS:** `{HF_TTS_MODEL}`\n"
|
| 1020 |
f"• **Telegram Bot:** Send an English video (up to `{_format_size(DUB_MAX_BYTES)}`) for live progress & Hindi dubbing."
|
| 1021 |
)
|
| 1022 |
gpu_btn = gr.Button("Verify ZeroGPU & Linked HF Models")
|