Update app.py
Browse files
app.py
CHANGED
|
@@ -19,6 +19,7 @@ if not hasattr(huggingface_hub, "HfFolder"):
|
|
| 19 |
import spaces
|
| 20 |
import gradio as gr
|
| 21 |
import asyncio
|
|
|
|
| 22 |
import os
|
| 23 |
import re
|
| 24 |
import secrets
|
|
@@ -83,12 +84,13 @@ MIN_FREE_DISK_BYTES: int = 1024 * 1024 * 1024
|
|
| 83 |
MALE_HINDI_VOICE = "hi-IN-MadhurNeural"
|
| 84 |
FEMALE_HINDI_VOICE = "hi-IN-SwaraNeural"
|
| 85 |
|
|
|
|
| 86 |
EMOTION_PROSODY: dict[str, tuple[str, str]] = {
|
| 87 |
"neutral": ("+0%", "+0Hz"),
|
| 88 |
-
"happy": ("+
|
| 89 |
-
"excited": ("+
|
| 90 |
-
"sad": ("-
|
| 91 |
-
"angry": ("+
|
| 92 |
}
|
| 93 |
|
| 94 |
_MT_TOKENIZER = None
|
|
@@ -143,9 +145,9 @@ def _wav_duration_seconds(wav_path: str) -> float:
|
|
| 143 |
with wave.open(wav_path, "rb") as wf:
|
| 144 |
frames = wf.getnframes()
|
| 145 |
rate = wf.getframerate() or 16000
|
| 146 |
-
return max(
|
| 147 |
except Exception:
|
| 148 |
-
return
|
| 149 |
|
| 150 |
|
| 151 |
def _detect_emotion_label(text: str) -> str:
|
|
@@ -159,8 +161,16 @@ def _detect_emotion_label(text: str) -> str:
|
|
| 159 |
return "neutral"
|
| 160 |
|
| 161 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 162 |
# ==============================================================================
|
| 163 |
-
# 3. SPEECH-TO-TEXT + OPUS-MT TRANSLATION +
|
| 164 |
# ==============================================================================
|
| 165 |
|
| 166 |
@spaces.GPU(duration=60)
|
|
@@ -177,17 +187,18 @@ def _gpu_transcribe_english(wav_path: str) -> list[dict[str, Any]]:
|
|
| 177 |
if not txt:
|
| 178 |
continue
|
| 179 |
start_s = max(0.0, float(seg.start))
|
| 180 |
-
end_s = max(start_s +
|
| 181 |
segments_out.append(
|
| 182 |
{
|
| 183 |
-
"
|
|
|
|
| 184 |
"duration_s": round(end_s - start_s, 2),
|
| 185 |
"gender": "MALE" if (idx % 2 == 0) else "FEMALE",
|
| 186 |
"emotion": _detect_emotion_label(txt),
|
| 187 |
"en_text": txt,
|
| 188 |
}
|
| 189 |
)
|
| 190 |
-
if len(segments_out) >=
|
| 191 |
break
|
| 192 |
|
| 193 |
if not segments_out:
|
|
@@ -242,9 +253,25 @@ def _translate_to_hindi_sync(segments: list[dict[str, Any]]) -> list[dict[str, A
|
|
| 242 |
return translated
|
| 243 |
|
| 244 |
|
| 245 |
-
async def
|
| 246 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 247 |
print(f"[DUB TTS] {seg['gender']} ({seg['emotion']}): {seg['hi_text'][:50]}", flush=True)
|
|
|
|
| 248 |
comm = edge_tts.Communicate(
|
| 249 |
text=seg["hi_text"],
|
| 250 |
voice=seg["voice"],
|
|
@@ -254,19 +281,34 @@ async def _synth_speech_file(seg: dict[str, Any], raw_audio_path: str) -> str:
|
|
| 254 |
await asyncio.wait_for(comm.save(mp3_path), timeout=15.0)
|
| 255 |
if not os.path.exists(mp3_path) or os.path.getsize(mp3_path) < 200:
|
| 256 |
raise RuntimeError(f"TTS returned empty audio for segment: {seg['hi_text'][:40]}")
|
| 257 |
-
return mp3_path
|
| 258 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 259 |
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 264 |
|
| 265 |
ok, err = await _run_ffmpeg(
|
| 266 |
[
|
| 267 |
-
"-i",
|
| 268 |
-
"-af",
|
| 269 |
-
"-t", f"{max_out_sec:.2f}",
|
| 270 |
"-ar", "44100",
|
| 271 |
"-ac", "2",
|
| 272 |
"-c:a", "pcm_s16le",
|
|
@@ -274,48 +316,65 @@ async def _render_delayed_segment(seg: dict[str, Any], out_wav_path: str) -> Non
|
|
| 274 |
],
|
| 275 |
timeout_sec=20.0,
|
| 276 |
)
|
| 277 |
-
if os.path.exists(
|
| 278 |
-
os.remove(
|
| 279 |
if not ok or not os.path.exists(out_wav_path) or os.path.getsize(out_wav_path) == 0:
|
| 280 |
-
raise RuntimeError(f"
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
async def
|
| 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 |
if not ok or not os.path.exists(out_m4a_path) or os.path.getsize(out_m4a_path) == 0:
|
| 318 |
-
raise RuntimeError(f"Failed
|
| 319 |
|
| 320 |
|
| 321 |
async def dub_video_to_hindi(src_video_path: str, out_video_path: str, status_cb) -> dict[str, Any]:
|
|
@@ -343,7 +402,6 @@ async def dub_video_to_hindi(src_video_path: str, out_video_path: str, status_cb
|
|
| 343 |
await status_cb(0.45, f"Translating {len(en_segments)} segment(s) with {HF_MT_MODEL}...")
|
| 344 |
hi_segments = await asyncio.to_thread(_translate_to_hindi_sync, en_segments)
|
| 345 |
|
| 346 |
-
aligned_wavs: list[str] = []
|
| 347 |
total_segs = max(1, len(hi_segments))
|
| 348 |
for idx, seg in enumerate(hi_segments, start=1):
|
| 349 |
pct = 0.45 + (idx / total_segs) * 0.35
|
|
@@ -351,12 +409,9 @@ async def dub_video_to_hindi(src_video_path: str, out_video_path: str, status_cb
|
|
| 351 |
pct,
|
| 352 |
f"Voicing Hindi [{seg['gender']} · {seg['emotion']}] ({idx}/{total_segs})...",
|
| 353 |
)
|
| 354 |
-
seg_out = os.path.join(work_dir, f"aligned_{idx:03d}.wav")
|
| 355 |
-
await _render_delayed_segment(seg, seg_out)
|
| 356 |
-
aligned_wavs.append(seg_out)
|
| 357 |
|
| 358 |
-
await status_cb(0.
|
| 359 |
-
await
|
| 360 |
|
| 361 |
await status_cb(0.92, "Muxing Hindi audio onto video...")
|
| 362 |
ok, err = await _run_ffmpeg(
|
|
@@ -632,7 +687,7 @@ async def cmd_start(_, message: Message) -> None:
|
|
| 632 |
await message.reply_text(
|
| 633 |
"**English → Hindi Dubbing Bot**\n\n"
|
| 634 |
f"Send or forward an English video (up to `{_format_size(DUB_MAX_BYTES)}`) to dub it into Hindi "
|
| 635 |
-
"with Male/Female voice separation and emotion
|
| 636 |
f"• **ASR Model:** `{HF_ASR_MODEL}`\n"
|
| 637 |
f"• **Translation Model:** `{HF_MT_MODEL}`"
|
| 638 |
)
|
|
|
|
| 19 |
import spaces
|
| 20 |
import gradio as gr
|
| 21 |
import asyncio
|
| 22 |
+
import math
|
| 23 |
import os
|
| 24 |
import re
|
| 25 |
import secrets
|
|
|
|
| 84 |
MALE_HINDI_VOICE = "hi-IN-MadhurNeural"
|
| 85 |
FEMALE_HINDI_VOICE = "hi-IN-SwaraNeural"
|
| 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": ("+3%", "+2Hz"),
|
| 91 |
+
"excited": ("+5%", "+3Hz"),
|
| 92 |
+
"sad": ("-3%", "-2Hz"),
|
| 93 |
+
"angry": ("+2%", "-2Hz"),
|
| 94 |
}
|
| 95 |
|
| 96 |
_MT_TOKENIZER = None
|
|
|
|
| 145 |
with wave.open(wav_path, "rb") as wf:
|
| 146 |
frames = wf.getnframes()
|
| 147 |
rate = wf.getframerate() or 16000
|
| 148 |
+
return max(0.2, frames / float(rate))
|
| 149 |
except Exception:
|
| 150 |
+
return 5.0
|
| 151 |
|
| 152 |
|
| 153 |
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 ""
|
| 169 |
+
return f"atempo={clamped:.3f}"
|
| 170 |
+
|
| 171 |
+
|
| 172 |
# ==============================================================================
|
| 173 |
+
# 3. SPEECH-TO-TEXT + OPUS-MT TRANSLATION + SYNCED HINDI TTS + CONCAT
|
| 174 |
# ==============================================================================
|
| 175 |
|
| 176 |
@spaces.GPU(duration=60)
|
|
|
|
| 187 |
if not txt:
|
| 188 |
continue
|
| 189 |
start_s = max(0.0, float(seg.start))
|
| 190 |
+
end_s = max(start_s + 0.8, float(seg.end))
|
| 191 |
segments_out.append(
|
| 192 |
{
|
| 193 |
+
"start_s": start_s,
|
| 194 |
+
"end_s": end_s,
|
| 195 |
"duration_s": round(end_s - start_s, 2),
|
| 196 |
"gender": "MALE" if (idx % 2 == 0) else "FEMALE",
|
| 197 |
"emotion": _detect_emotion_label(txt),
|
| 198 |
"en_text": txt,
|
| 199 |
}
|
| 200 |
)
|
| 201 |
+
if len(segments_out) >= 16:
|
| 202 |
break
|
| 203 |
|
| 204 |
if not segments_out:
|
|
|
|
| 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(
|
| 259 |
+
[
|
| 260 |
+
"-f", "lavfi",
|
| 261 |
+
"-i", f"anullsrc=r=44100:cl=stereo:d={dur:.3f}",
|
| 262 |
+
"-c:a", "pcm_s16le",
|
| 263 |
+
out_wav,
|
| 264 |
+
],
|
| 265 |
+
timeout_sec=15.0,
|
| 266 |
+
)
|
| 267 |
+
if not ok or not os.path.exists(out_wav):
|
| 268 |
+
raise RuntimeError(f"Failed to create silence clip: {err}")
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
async def _render_synced_speech_clip(seg: dict[str, Any], slot_dur_s: float, out_wav_path: str) -> None:
|
| 272 |
+
mp3_path = f"{out_wav_path}.mp3"
|
| 273 |
print(f"[DUB TTS] {seg['gender']} ({seg['emotion']}): {seg['hi_text'][:50]}", flush=True)
|
| 274 |
+
|
| 275 |
comm = edge_tts.Communicate(
|
| 276 |
text=seg["hi_text"],
|
| 277 |
voice=seg["voice"],
|
|
|
|
| 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", mp3_path, "-ar", "44100", "-ac", "2", "-c:a", "pcm_s16le", raw_wav],
|
| 288 |
+
timeout_sec=15.0,
|
| 289 |
+
)
|
| 290 |
+
if os.path.exists(mp3_path):
|
| 291 |
+
os.remove(mp3_path)
|
| 292 |
+
if not ok or not os.path.exists(raw_wav):
|
| 293 |
+
raise RuntimeError(f"Failed decoding TTS mp3: {err}")
|
| 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 |
+
needed_tempo = min(1.25, spoken_dur / slot_dur_s)
|
| 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", af_expr,
|
|
|
|
| 312 |
"-ar", "44100",
|
| 313 |
"-ac", "2",
|
| 314 |
"-c:a", "pcm_s16le",
|
|
|
|
| 316 |
],
|
| 317 |
timeout_sec=20.0,
|
| 318 |
)
|
| 319 |
+
if os.path.exists(raw_wav):
|
| 320 |
+
os.remove(raw_wav)
|
| 321 |
if not ok or not os.path.exists(out_wav_path) or os.path.getsize(out_wav_path) == 0:
|
| 322 |
+
raise RuntimeError(f"Failed fitting speech segment: {err}")
|
| 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 |
+
|
| 333 |
+
for idx, seg in enumerate(segments, start=1):
|
| 334 |
+
target_start_s = max(cursor_s, float(seg.get("start_s", cursor_s)))
|
| 335 |
+
gap_s = target_start_s - cursor_s
|
| 336 |
+
if gap_s > 0.04:
|
| 337 |
+
gap_wav = os.path.join(work_dir, f"gap_{idx:03d}.wav")
|
| 338 |
+
await _make_silence_wav(gap_s, gap_wav)
|
| 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 |
+
|
| 346 |
+
speech_wav = os.path.join(work_dir, f"speech_{idx:03d}.wav")
|
| 347 |
+
await _render_synced_speech_clip(seg, slot_dur_s, speech_wav)
|
| 348 |
+
timeline_files.append(speech_wav)
|
| 349 |
+
cursor_s += _wav_duration_seconds(speech_wav)
|
| 350 |
+
|
| 351 |
+
if cursor_s < total_sec - 0.05:
|
| 352 |
+
tail_wav = os.path.join(work_dir, "tail_silence.wav")
|
| 353 |
+
await _make_silence_wav(total_sec - cursor_s, tail_wav)
|
| 354 |
+
timeline_files.append(tail_wav)
|
| 355 |
+
|
| 356 |
+
concat_list = os.path.join(work_dir, "timeline.txt")
|
| 357 |
+
with open(concat_list, "w", encoding="utf-8") as fp:
|
| 358 |
+
for p in timeline_files:
|
| 359 |
+
safe_p = p.replace("'", "'\\''")
|
| 360 |
+
fp.write(f"file '{safe_p}'\n")
|
| 361 |
|
| 362 |
+
ok, err = await _run_ffmpeg(
|
| 363 |
+
[
|
| 364 |
+
"-f", "concat",
|
| 365 |
+
"-safe", "0",
|
| 366 |
+
"-i", concat_list,
|
| 367 |
+
"-t", f"{max(1.0, total_sec):.2f}",
|
| 368 |
+
"-c:a", "aac",
|
| 369 |
+
"-b:a", "192k",
|
| 370 |
+
"-ar", "44100",
|
| 371 |
+
"-ac", "2",
|
| 372 |
+
out_m4a_path,
|
| 373 |
+
],
|
| 374 |
+
timeout_sec=45.0,
|
| 375 |
+
)
|
| 376 |
if not ok or not os.path.exists(out_m4a_path) or os.path.getsize(out_m4a_path) == 0:
|
| 377 |
+
raise RuntimeError(f"Failed building Hindi timeline track: {err}")
|
| 378 |
|
| 379 |
|
| 380 |
async def dub_video_to_hindi(src_video_path: str, out_video_path: str, status_cb) -> dict[str, Any]:
|
|
|
|
| 402 |
await status_cb(0.45, f"Translating {len(en_segments)} segment(s) with {HF_MT_MODEL}...")
|
| 403 |
hi_segments = await asyncio.to_thread(_translate_to_hindi_sync, en_segments)
|
| 404 |
|
|
|
|
| 405 |
total_segs = max(1, len(hi_segments))
|
| 406 |
for idx, seg in enumerate(hi_segments, start=1):
|
| 407 |
pct = 0.45 + (idx / total_segs) * 0.35
|
|
|
|
| 409 |
pct,
|
| 410 |
f"Voicing Hindi [{seg['gender']} · {seg['emotion']}] ({idx}/{total_segs})...",
|
| 411 |
)
|
|
|
|
|
|
|
|
|
|
| 412 |
|
| 413 |
+
await status_cb(0.82, "Aligning & stitching synchronized Hindi audio...")
|
| 414 |
+
await _build_timeline_track(hi_segments, total_sec, work_dir, hindi_m4a)
|
| 415 |
|
| 416 |
await status_cb(0.92, "Muxing Hindi audio onto video...")
|
| 417 |
ok, err = await _run_ffmpeg(
|
|
|
|
| 687 |
await message.reply_text(
|
| 688 |
"**English → Hindi Dubbing Bot**\n\n"
|
| 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 |
)
|