Spaces:
Running on Zero
Running on Zero
File size: 26,243 Bytes
ca6ab3f 3d17e8b ca6ab3f baf044b ca6ab3f baf044b ca6ab3f 3d17e8b ca6ab3f 3d17e8b ca6ab3f ccb5453 ca6ab3f baf044b 91765a4 baf044b 91765a4 baf044b 91765a4 baf044b ca6ab3f f5f2774 ca6ab3f f5f2774 ca6ab3f ccb5453 ca6ab3f ccb5453 ca6ab3f b2e2daa ccb5453 ca6ab3f ccb5453 ca6ab3f ccb5453 ca6ab3f 3d17e8b ca6ab3f f5f2774 ca6ab3f f5f2774 ca6ab3f 28dadb1 3d17e8b ca6ab3f 3d17e8b ca6ab3f 3d17e8b ca6ab3f ccb5453 91765a4 4e77f57 91765a4 4e77f57 91765a4 4e77f57 ccb5453 ca6ab3f ccb5453 ca6ab3f 4e77f57 ccb5453 4e77f57 ccb5453 4e77f57 ccb5453 4e77f57 ca6ab3f 28dadb1 ca6ab3f ccb5453 ca6ab3f ccb5453 ca6ab3f ccb5453 ca6ab3f ccb5453 ca6ab3f ccb5453 ca6ab3f ccb5453 ca6ab3f ccb5453 ca6ab3f ccb5453 ca6ab3f ccb5453 ca6ab3f ccb5453 ca6ab3f ccb5453 ca6ab3f ccb5453 ca6ab3f ccb5453 ca6ab3f ccb5453 ca6ab3f ccb5453 ca6ab3f ccb5453 ca6ab3f ccb5453 ca6ab3f ccb5453 ca6ab3f ccb5453 ca6ab3f 3d17e8b ca6ab3f 3d17e8b ccb5453 ca6ab3f ccb5453 3d17e8b ca6ab3f ccb5453 ca6ab3f ccb5453 28dadb1 3d17e8b ccb5453 3d17e8b ca6ab3f ccb5453 ca6ab3f ccb5453 ca6ab3f 3d17e8b ca6ab3f 3d17e8b ccb5453 ca6ab3f ccb5453 ca6ab3f ccb5453 ca6ab3f ccb5453 ca6ab3f ccb5453 ca6ab3f 3d17e8b ca6ab3f 3d17e8b ccb5453 ca6ab3f ccb5453 ca6ab3f 3d17e8b ca6ab3f f5f2774 ccb5453 ca6ab3f ccb5453 ca6ab3f ccb5453 ca6ab3f ccb5453 ca6ab3f 3d17e8b ca6ab3f 3d17e8b ca6ab3f ccb5453 3d17e8b ccb5453 ca6ab3f ccb5453 ca6ab3f 3d17e8b ca6ab3f 3d17e8b ccb5453 ca6ab3f ccb5453 ca6ab3f ccb5453 ca6ab3f ccb5453 28dadb1 3d17e8b 28dadb1 3d17e8b ccb5453 ca6ab3f ccb5453 ca6ab3f ccb5453 ca6ab3f ccb5453 3d17e8b | 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 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 | """
pipeline_runner.py β Mazinger Dubber pipeline orchestrator for HF ZeroGPU Spaces.
Orchestrates all 10 dubbing stages. GPU-heavy stages are split into two separate
@spaces.GPU-decorated functions to stay within the 120s-per-request hard cap.
"""
from __future__ import annotations
import os
import shutil
import tempfile
import time
from typing import Any, Generator
import spaces # provided by HF ZeroGPU runtime
import re
# ---------------------------------------------------------------------------
# Constants
# ---------------------------------------------------------------------------
YT_PROXY_SPACE = "HeshamHaroon/yt-proxy"
_YT_RE = re.compile(r'(?:youtube\.com/watch\?v=|youtu\.be/|youtube\.com/shorts/)([a-zA-Z0-9_-]{11})')
HF_TOKEN: str = os.environ.get("HF_TOKEN", "")
LLM_BASE_URL: str = "https://router.huggingface.co/v1"
LLM_MODEL_TEXT: str = "Qwen/Qwen2.5-72B-Instruct"
LLM_MODEL_VISION: str = "Qwen/Qwen2.5-VL-7B-Instruct"
BASE_DIR: str = "/tmp/mazinger_output"
STAGE_NAMES: list[str] = [
"Download", # 1
"Transcribe", # 2
"Thumbnails", # 3
"Describe", # 4
"Review", # 5 (optional β skipped when asr_review=False)
"Translate", # 6
"Resegment", # 7
"Synthesize", # 8
"Assemble", # 9
"Subtitle", # 10
]
# ---------------------------------------------------------------------------
# Mazinger imports (only available on HF Spaces where the package is installed)
# ---------------------------------------------------------------------------
from mazinger import ProjectPaths, LLMUsageTracker # noqa: E402
from mazinger.llm import build_client # noqa: E402
from mazinger import ( # noqa: E402
download,
transcribe,
thumbnails,
describe,
review,
translate,
resegment,
tts,
assemble,
subtitle,
)
from mazinger.subtitle import SubtitleStyle, download_google_font # noqa: E402
from mazinger.srt import parse_file as parse_srt # noqa: E402
from mazinger import profiles # noqa: E402
# ---------------------------------------------------------------------------
# Helper: build LLM client
# ---------------------------------------------------------------------------
def _make_client(model: str = LLM_MODEL_TEXT):
"""Return an OpenAI-compatible client pointed at HF Inference Router."""
return build_client(api_key=HF_TOKEN, base_url=LLM_BASE_URL)
def _is_youtube_url(url: str) -> bool:
return bool(_YT_RE.search(url))
def _download_via_proxy(url: str, output_path: str) -> str:
"""Download a YouTube video via the yt-proxy helper Space.
Uses a background job so we can enforce a timeout (proxy Spaces can be
asleep and take 1-2 min to wake).
"""
from gradio_client import Client
import threading
print(f"[proxy] Connecting to {YT_PROXY_SPACE}...")
client = Client(YT_PROXY_SPACE, hf_token=HF_TOKEN)
print(f"[proxy] Connected. Requesting download of {url} ...")
# Run predict in a thread so we can enforce a hard timeout
result_box: list = []
error_box: list = []
def _run():
try:
r = client.predict(url=url, api_name="/download_video")
result_box.append(r)
except Exception as exc:
error_box.append(exc)
t = threading.Thread(target=_run, daemon=True)
t.start()
t.join(timeout=300) # 5 min max β proxy may need to wake + download
if error_box:
raise RuntimeError(f"YouTube proxy download failed: {error_box[0]}")
if not result_box:
raise TimeoutError(
"YouTube proxy download timed out after 5 minutes. "
"The proxy Space may be sleeping β try again in a minute."
)
result = result_box[0]
print(f"[proxy] Download complete: {result}")
os.makedirs(os.path.dirname(output_path) or ".", exist_ok=True)
shutil.copy2(result, output_path)
return output_path
# ---------------------------------------------------------------------------
# Helper: call with exponential backoff on 429
# ---------------------------------------------------------------------------
def _call_with_retry(fn, *args, max_retries: int = 3, **kwargs):
"""
Call *fn* with *args*/*kwargs*, retrying up to *max_retries* times on
HTTP 429 (rate-limit) errors with exponential backoff (5 s / 15 s / 45 s).
"""
delays = [5, 15, 45]
last_exc: Exception | None = None
for attempt in range(max_retries + 1):
try:
return fn(*args, **kwargs)
except Exception as exc:
# Detect rate-limit errors by status code attribute or message text
is_rate_limit = (
getattr(exc, "status_code", None) == 429
or "429" in str(exc)
or "rate limit" in str(exc).lower()
or "too many requests" in str(exc).lower()
)
if is_rate_limit and attempt < max_retries:
wait = delays[attempt]
print(
f"[retry] 429 rate-limit hit β waiting {wait}s "
f"(attempt {attempt + 1}/{max_retries})"
)
time.sleep(wait)
last_exc = exc
continue
raise
# Should never reach here, but satisfy the type checker
raise last_exc # type: ignore[misc]
# ---------------------------------------------------------------------------
# Helper: audio duration guard
# ---------------------------------------------------------------------------
def _check_audio_duration(audio_path: str, max_seconds: float = 300.0) -> float:
"""
Return audio duration in seconds.
Raises ValueError if the file exceeds *max_seconds*.
Requires the `soundfile` package (included in mazinger[all-qwen]).
"""
import soundfile as sf # lazy import β only needed here
info = sf.info(audio_path)
duration: float = info.duration
if duration > max_seconds:
raise ValueError(
f"Audio is {duration:.1f}s β exceeds the {max_seconds:.0f}s limit. "
"Please trim your video before uploading."
)
return duration
# ---------------------------------------------------------------------------
# GPU Stage 1 β Transcription (120 s allocation)
# ---------------------------------------------------------------------------
@spaces.GPU(duration=120)
def _gpu_transcribe(
audio_path: str,
output_path: str,
method: str = "whisperx",
model: str | None = None,
language: str | None = None,
) -> str:
"""
Run WhisperX (or the requested STT method) on *audio_path* with CUDA.
Returns the path to the written SRT file (*output_path*).
First invocation may be slow due to model weight downloads.
"""
transcribe.transcribe(
audio_path=audio_path,
output_path=output_path,
method=method,
model=model,
language=language,
device="cuda",
)
return output_path
# ---------------------------------------------------------------------------
# GPU Stage 2 β TTS Synthesis (120 s allocation)
# ---------------------------------------------------------------------------
@spaces.GPU(duration=120)
def _gpu_synthesize(
tts_model_name: str,
voice_sample: str | None,
voice_script: str | None,
voice_theme: str | None,
clone_profile: str | None,
srt_entries: list[dict],
output_dir: str,
target_language: str,
) -> list[dict]:
"""
Load the TTS model, resolve a voice prompt via one of the supported modes,
then synthesize all SRT segments into *output_dir*.
Voice-prompt priority:
1. clone_profile β load a pre-built voice profile
2. voice_sample + voice_script β create a voice prompt from recorded audio
3. voice_theme β load a named built-in theme
4. fallback β built-in "narrator-m" voice
Returns the segment_info list from synthesize_segments (dicts with
``idx``, ``start``, ``end``, ``target_dur``, ``wav_path``, ``actual_dur``).
This is required by :func:`assemble.assemble_timeline`.
"""
# Load TTS model onto GPU
tts_model = tts.load_model(tts_model_name, device="cuda")
# Resolve voice prompt β fetch reference audio + transcript, then create wrapper
if clone_profile:
ref_audio, script_path = profiles.fetch_profile(clone_profile)
# fetch_profile returns file PATHS β read the script content
with open(script_path) as f:
ref_text = f.read().strip()
voice_prompt = tts.create_voice_prompt(tts_model, ref_audio, ref_text)
elif voice_sample and voice_script:
voice_prompt = tts.create_voice_prompt(tts_model, voice_sample, voice_script)
elif voice_theme:
ref_audio, ref_text = profiles.resolve_theme(voice_theme, target_language, device="cuda")
voice_prompt = tts.create_voice_prompt(tts_model, ref_audio, ref_text)
else:
# Auto-clone: voice_sample is set but voice_script is None
# For auto-clone, ref_text=None is valid β TTS uses the audio sample only
if voice_sample:
voice_prompt = tts.create_voice_prompt(tts_model, voice_sample, None)
else:
ref_audio, ref_text = profiles.resolve_theme("narrator-m", target_language, device="cuda")
voice_prompt = tts.create_voice_prompt(tts_model, ref_audio, ref_text)
# Synthesize all segments β returns segment_info with wav_path, actual_dur, etc.
segment_info = tts.synthesize_segments(
model=tts_model,
voice_prompt=voice_prompt,
srt_entries=srt_entries,
output_dir=output_dir,
language=target_language,
)
return segment_info
# ---------------------------------------------------------------------------
# Main pipeline generator
# ---------------------------------------------------------------------------
def run_pipeline(
source: str,
target_language: str,
voice_mode: str,
voice_theme: str | None = None,
voice_profile: str | None = None,
voice_sample: str | None = None,
voice_script: str | None = None,
output_type: str = "video",
embed_subtitles: bool = True,
subtitle_font: str = "Cairo",
subtitle_font_size: int = 28,
source_language: str = "auto",
slice_start: str = "",
slice_end: str = "",
subtitle_position: str = "bottom",
subtitle_color: str = "white",
subtitle_bg_alpha: float = 0.6,
subtitle_outline_width: int = 1,
subtitle_bold: bool = False,
subtitle_line_spacing: int = 8,
subtitle_source: str = "translated",
asr_review: bool = False,
tempo_mode: str = "auto",
max_tempo: float = 1.5,
words_per_second: float | None = None,
duration_budget: float | None = None,
translate_technical_terms: bool = False,
) -> Generator[tuple[int, str, dict[str, Any]], None, None]:
"""
Orchestrate all 10 dubbing stages for *source* (URL or local path).
Yields ``(stage_index, log_message, result_dict)`` tuples at each stage.
Stage indices are 1-based; a final yield with ``done=True`` is emitted
after all stages complete.
"""
from pathlib import Path
import soundfile as sf
import hashlib
# ββ Upfront source validation ββββββββββββββββββββββββββββββββββββββ
# ZeroGPU blocks all external DNS except HuggingFace services.
# Only YouTube URLs (via proxy) and uploaded files work.
source = source.strip()
is_local = os.path.exists(source)
is_url = download.is_url(source)
is_yt = _is_youtube_url(source)
if not is_local and not is_url:
# Might be a URL without scheme β try adding https://
if "youtube.com" in source or "youtu.be" in source:
source = "https://" + source
is_url = True
is_yt = True
else:
yield 1, (
f"[ERROR] Invalid source: '{source}'\n"
"Please provide a YouTube URL (e.g. https://youtube.com/watch?v=...) "
"or upload a video/audio file."
), {"error": "invalid source"}
return
if is_url and not is_yt:
yield 1, (
f"[ERROR] Non-YouTube URLs are not supported on this Space.\n"
f"URL: {source}\n"
"ZeroGPU blocks external network access. Only YouTube URLs work "
"(downloaded via proxy). Please use a YouTube link or upload your file directly."
), {"error": "unsupported URL"}
return
if is_yt:
match = _YT_RE.search(source)
if not match:
yield 1, (
f"[ERROR] Could not find a valid YouTube video ID in: {source}\n"
"Expected format: https://youtube.com/watch?v=VIDEO_ID or https://youtu.be/VIDEO_ID"
), {"error": "invalid YouTube URL"}
return
slug = match.group(1)
elif is_local:
try:
slug = download.slug_from_path(source)
except Exception:
slug = hashlib.md5(source.encode()).hexdigest()[:12]
else:
slug = hashlib.md5(source.encode()).hexdigest()[:12]
proj = ProjectPaths(slug, base_dir=BASE_DIR, target_language=target_language)
proj.ensure_dirs()
tracker = LLMUsageTracker()
result_tmp = tempfile.mkdtemp(prefix="mazinger_result_")
# -----------------------------------------------------------------------
# Stage 1 β Download
# -----------------------------------------------------------------------
stage = 1
yield stage, f"[{STAGE_NAMES[stage - 1]}] Downloading: {source}", {}
try:
if is_yt:
yield stage, f"[{STAGE_NAMES[stage - 1]}] Downloading via YouTube proxy...", {}
_download_via_proxy(source, proj.video)
download.extract_audio(proj.video, proj.audio)
elif is_local and download.is_audio_file(source):
download.ingest_local_audio(source, proj.audio)
elif is_local:
download.ingest_local_video(source, proj.video, proj.audio)
else:
yield stage, f"[{STAGE_NAMES[stage - 1]}] FAILED: unsupported source", {"error": "unsupported"}
return
except Exception as exc:
yield stage, f"[{STAGE_NAMES[stage - 1]}] FAILED: {exc}", {"error": str(exc)}
return
# Slice if requested
if slice_start or slice_end:
try:
download.slice_project(
proj,
start=slice_start if slice_start else None,
end=slice_end if slice_end else None,
)
yield stage, f"[{STAGE_NAMES[stage - 1]}] Trimmed to {slice_start or 'start'}β{slice_end or 'end'}.", {}
except Exception as exc:
yield stage, f"[{STAGE_NAMES[stage - 1]}] Slice warning: {exc}", {}
try:
duration = _check_audio_duration(proj.audio, max_seconds=300.0)
except ValueError as exc:
yield stage, f"[{STAGE_NAMES[stage - 1]}] REJECTED: {exc}", {"error": str(exc)}
return
yield stage, f"[{STAGE_NAMES[stage - 1]}] Done β {duration:.1f}s of audio.", {}
# -----------------------------------------------------------------------
# Stage 2 β Transcribe (GPU)
# -----------------------------------------------------------------------
stage = 2
yield stage, f"[{STAGE_NAMES[stage - 1]}] Transcribing (first run downloads ~3GB model)β¦", {}
try:
_gpu_transcribe(proj.audio, proj.source_srt, method="whisperx")
except TimeoutError:
yield stage, f"[{STAGE_NAMES[stage - 1]}] GPU timeout β try a shorter clip.", {"error": "timeout"}
return
except Exception as exc:
yield stage, f"[{STAGE_NAMES[stage - 1]}] FAILED: {exc}", {"error": str(exc)}
return
yield stage, f"[{STAGE_NAMES[stage - 1]}] Transcription complete.", {}
# -----------------------------------------------------------------------
# Stage 3 β Thumbnails
# -----------------------------------------------------------------------
stage = 3
source_srt_text = Path(proj.source_srt).read_text()
thumb_paths: list[dict] = []
if Path(proj.video).exists():
yield stage, f"[{STAGE_NAMES[stage - 1]}] Extracting keyframesβ¦", {}
try:
client = _make_client()
ts = _call_with_retry(
thumbnails.select_timestamps,
source_srt_text, client,
llm_model=LLM_MODEL_TEXT, usage_tracker=tracker,
)
thumb_paths = thumbnails.extract_frames(proj.video, ts, proj.thumbnails_dir)
except Exception as exc:
yield stage, f"[{STAGE_NAMES[stage - 1]}] WARNING: {exc}", {}
else:
yield stage, f"[{STAGE_NAMES[stage - 1]}] No video β skipping.", {}
yield stage, f"[{STAGE_NAMES[stage - 1]}] Done β {len(thumb_paths)} keyframe(s).", {}
# -----------------------------------------------------------------------
# Stage 4 β Describe (vision LLM)
# -----------------------------------------------------------------------
stage = 4
description: dict = {}
if thumb_paths:
yield stage, f"[{STAGE_NAMES[stage - 1]}] Analyzing video contentβ¦", {}
try:
vision_client = _make_client()
description = _call_with_retry(
describe.describe_content,
source_srt_text, thumb_paths, vision_client,
llm_model=LLM_MODEL_VISION, usage_tracker=tracker,
)
except Exception as exc:
yield stage, f"[{STAGE_NAMES[stage - 1]}] WARNING: {exc}", {}
else:
yield stage, f"[{STAGE_NAMES[stage - 1]}] Skipping (no thumbnails).", {}
yield stage, f"[{STAGE_NAMES[stage - 1]}] Done.", {}
# -----------------------------------------------------------------------
# Stage 5 β Review (optional)
# -----------------------------------------------------------------------
stage = 5
if asr_review:
yield stage, f"[{STAGE_NAMES[stage - 1]}] Reviewing transcriptionβ¦", {}
try:
review_client = _make_client()
source_srt_text = _call_with_retry(
review.review_srt,
source_srt_text, description, review_client,
llm_model=LLM_MODEL_TEXT,
source_language=source_language if source_language != "auto" else "auto",
usage_tracker=tracker,
)
Path(proj.reviewed_srt).write_text(source_srt_text)
yield stage, f"[{STAGE_NAMES[stage - 1]}] Review complete.", {}
except Exception as exc:
yield stage, f"[{STAGE_NAMES[stage - 1]}] WARNING: {exc} β using original.", {}
else:
yield stage, f"[{STAGE_NAMES[stage - 1]}] Skipped (not enabled).", {}
# -----------------------------------------------------------------------
# Stage 6 β Translate
# -----------------------------------------------------------------------
stage = 6
yield stage, f"[{STAGE_NAMES[stage - 1]}] Translating to {target_language}β¦", {}
text_client = _make_client()
translate_kwargs: dict[str, Any] = {}
if words_per_second is not None:
translate_kwargs["words_per_second"] = words_per_second
if duration_budget is not None:
translate_kwargs["duration_budget"] = duration_budget
try:
translated_srt = _call_with_retry(
translate.translate_srt,
source_srt_text, description, thumb_paths, text_client,
llm_model=LLM_MODEL_TEXT,
source_language=source_language if source_language != "auto" else "auto",
target_language=target_language,
translate_technical_terms=translate_technical_terms,
usage_tracker=tracker,
**translate_kwargs,
)
Path(proj.translated_raw_srt).write_text(translated_srt)
except Exception as exc:
yield stage, f"[{STAGE_NAMES[stage - 1]}] FAILED: {exc}", {"error": str(exc)}
return
yield stage, f"[{STAGE_NAMES[stage - 1]}] Translation complete.", {}
# -----------------------------------------------------------------------
# Stage 7 β Resegment
# -----------------------------------------------------------------------
stage = 7
yield stage, f"[{STAGE_NAMES[stage - 1]}] Resegmenting subtitlesβ¦", {}
try:
final_srt = _call_with_retry(
resegment.resegment_srt,
translated_srt,
client=text_client, llm_model=LLM_MODEL_TEXT,
usage_tracker=tracker,
)
Path(proj.final_srt).write_text(final_srt)
except Exception as exc:
yield stage, f"[{STAGE_NAMES[stage - 1]}] FAILED: {exc}", {"error": str(exc)}
return
yield stage, f"[{STAGE_NAMES[stage - 1]}] Done.", {}
# -----------------------------------------------------------------------
# Stage 8 β Synthesize (GPU)
# -----------------------------------------------------------------------
stage = 8
yield stage, f"[{STAGE_NAMES[stage - 1]}] Synthesizing voice (first run downloads TTS model)β¦", {}
srt_entries = parse_srt(proj.final_srt)
_voice_theme = voice_theme if voice_mode == "theme" else None
_clone_profile = voice_profile if voice_mode == "profile" else None
_voice_sample = voice_sample if voice_mode == "clone" else None
_voice_script = voice_script if voice_mode == "clone" else None
# Auto-clone: extract a voice segment from source audio (CPU, no GPU needed)
if voice_mode == "auto":
yield stage, f"[{STAGE_NAMES[stage - 1]}] Auto-cloning voice from source audioβ¦", {}
try:
auto_profile_dir = os.path.join(proj.root, "voice_profile")
_voice_sample = profiles.create_auto_clone_profile(
proj.audio, proj.source_srt, auto_profile_dir,
)
except Exception as exc:
yield stage, f"[{STAGE_NAMES[stage - 1]}] Auto-clone failed: {exc} β falling back to narrator-m.", {}
_voice_theme = "narrator-m"
_voice_sample = None
try:
segment_info = _gpu_synthesize(
tts_model_name="Qwen/Qwen3-TTS-12Hz-1.7B-Base",
voice_sample=_voice_sample,
voice_script=_voice_script,
voice_theme=_voice_theme,
clone_profile=_clone_profile,
srt_entries=srt_entries,
output_dir=proj.tts_segments_dir,
target_language=target_language,
)
except TimeoutError:
yield stage, f"[{STAGE_NAMES[stage - 1]}] GPU timeout β try a shorter clip.", {"error": "timeout"}
return
except Exception as exc:
yield stage, f"[{STAGE_NAMES[stage - 1]}] FAILED: {exc}", {"error": str(exc)}
return
yield stage, f"[{STAGE_NAMES[stage - 1]}] Synthesis complete.", {}
# -----------------------------------------------------------------------
# Stage 9 β Assemble
# -----------------------------------------------------------------------
stage = 9
yield stage, f"[{STAGE_NAMES[stage - 1]}] Assembling dubbed timelineβ¦", {}
try:
original_duration = sf.info(proj.audio).duration
assemble.assemble_timeline(
segment_info, original_duration, proj.final_audio,
tempo_mode=tempo_mode,
max_tempo=max_tempo,
)
assemble.post_process(proj.final_audio, proj.audio, proj.final_audio)
except Exception as exc:
yield stage, f"[{STAGE_NAMES[stage - 1]}] FAILED: {exc}", {"error": str(exc)}
return
yield stage, f"[{STAGE_NAMES[stage - 1]}] Audio assembled.", {}
# -----------------------------------------------------------------------
# Stage 10 β Subtitle / Mux
# -----------------------------------------------------------------------
stage = 10
yield stage, f"[{STAGE_NAMES[stage - 1]}] Creating final outputβ¦", {}
try:
if embed_subtitles and Path(proj.video).exists():
font_file = None
try:
font_file = download_google_font(subtitle_font)
except Exception:
pass
style = SubtitleStyle(
font=subtitle_font,
font_file=font_file,
font_size=subtitle_font_size,
font_color=subtitle_color,
position=subtitle_position,
bg_alpha=subtitle_bg_alpha,
outline_width=subtitle_outline_width,
bold=subtitle_bold,
line_spacing=subtitle_line_spacing,
)
# Resolve subtitle source SRT
if subtitle_source == "original":
srt_for_burn = proj.source_srt
else:
srt_for_burn = proj.translated_raw_srt if os.path.exists(proj.translated_raw_srt) else proj.final_srt
subtitle.burn_subtitles(proj.video, proj.final_video, srt_for_burn, style=style, audio_path=proj.final_audio)
final_path = proj.final_video
elif Path(proj.video).exists():
assemble.mux_video(proj.video, proj.final_audio, proj.final_video)
final_path = proj.final_video
else:
final_path = proj.final_audio
except Exception as exc:
yield stage, f"[{STAGE_NAMES[stage - 1]}] FAILED: {exc}", {"error": str(exc)}
return
# Copy to persistent temp dir
result_file = shutil.copy2(final_path, os.path.join(result_tmp, os.path.basename(final_path)))
result_srt = shutil.copy2(proj.final_srt, os.path.join(result_tmp, "subtitles.srt"))
yield stage, f"[{STAGE_NAMES[stage - 1]}] Done.", {"final_path": result_file, "srt_path": result_srt}
# Final sentinel
yield len(STAGE_NAMES), "Pipeline complete.", {"final_path": result_file, "srt_path": result_srt, "done": True}
|