Spaces:
Runtime error
Runtime error
Download app.py from dermakgeralt/_2_: direct link, hf CLI and curl.
- Browser
- Download file 14.3 kB
-
https://huggingface.co/spaces/dermakgeralt/_2_/resolve/main/app.py
- Command line
-
hf download hf://spaces/dermakgeralt/_2_/app.py
-
curl -L -o app.py https://huggingface.co/spaces/dermakgeralt/_2_/resolve/main/app.py
14.3 kB
| # app.py | |
| # Multilingual Video Translator & Dubber — single-file Gradio app | |
| # Features: | |
| # - Upload MP4/MOV/MKV | |
| # - ASR (faster-whisper) with optional fixed-language or auto | |
| # - Translation (M2M100 universal model) | |
| # - Per-segment TTS (Edge TTS if available; fallback to gTTS) | |
| # - Generates SRT & VTT; muxes dubbed MP4 with FFmpeg | |
| # - Simple per-speaker voice mapping UI (Speaker 1..2); diarization placeholder (single speaker) | |
| # | |
| # Notes: | |
| # - This is CPU-friendly but still heavy; large videos will take time. | |
| # - Hugging Face Spaces (Gradio SDK) should work out of the box. | |
| # - If Edge TTS rate/pitch is needed: they’re strings like "+0%" / "+0Hz". | |
| # | |
| # Env toggles (optional): | |
| # - USE_EDGE_TTS=true -> default to Edge TTS; else falls back to gTTS per-run toggle. | |
| import os | |
| import json | |
| import math | |
| import shutil | |
| import tempfile | |
| import subprocess | |
| import asyncio | |
| from dataclasses import dataclass | |
| from typing import List, Dict, Tuple, Optional | |
| import gradio as gr | |
| import numpy as np | |
| # ---------- Optional TTS backends ---------- | |
| EDGE_TTS_AVAILABLE = False | |
| try: | |
| import edge_tts # async TTS (Microsoft voices) | |
| EDGE_TTS_AVAILABLE = True | |
| except Exception: | |
| EDGE_TTS_AVAILABLE = False | |
| from gtts import gTTS | |
| # ---------- ASR ---------- | |
| from faster_whisper import WhisperModel | |
| # ---------- Translation ---------- | |
| from transformers import M2M100ForConditionalGeneration, M2M100Tokenizer | |
| import torch | |
| # ---------- Subtitle helpers ---------- | |
| import srt | |
| import datetime | |
| # ---------- Audio helpers ---------- | |
| from pydub import AudioSegment | |
| # ========================= | |
| # Config / Globals | |
| # ========================= | |
| LANG_CHOICES = [ | |
| ("en", "English"), | |
| ("ru", "Russian"), | |
| ("es", "Spanish"), | |
| ("fr", "French"), | |
| ("de", "German"), | |
| ("ar", "Arabic"), | |
| ("hi", "Hindi"), | |
| ("zh", "Chinese"), | |
| ("pt", "Portuguese"), | |
| ("tr", "Turkish"), | |
| ] | |
| EDGE_DEFAULT_VOICE_SPK1 = "en-US-JennyNeural" | |
| EDGE_DEFAULT_VOICE_SPK2 = "en-US-GuyNeural" | |
| DEFAULT_ASR_MODEL = os.environ.get("ASR_MODEL", "small") # faster-whisper size | |
| USE_EDGE_TTS_ENV = os.environ.get("USE_EDGE_TTS", "false").lower() == "true" | |
| # Cache models to avoid reloads | |
| _asr_model = None | |
| _m2m_tokenizer = None | |
| _m2m_model = None | |
| def get_asr_model() -> WhisperModel: | |
| global _asr_model | |
| if _asr_model is None: | |
| # CPU + int8 is light enough for Spaces CPU | |
| _asr_model = WhisperModel(DEFAULT_ASR_MODEL, device="cpu", compute_type="int8") | |
| return _asr_model | |
| def get_m2m() -> Tuple[M2M100Tokenizer, M2M100ForConditionalGeneration]: | |
| global _m2m_tokenizer, _m2m_model | |
| if _m2m_tokenizer is None or _m2m_model is None: | |
| name = "facebook/m2m100_418M" | |
| _m2m_tokenizer = M2M100Tokenizer.from_pretrained(name) | |
| _m2m_model = M2M100ForConditionalGeneration.from_pretrained(name) | |
| _m2m_model.to("cpu") | |
| return _m2m_tokenizer, _m2m_model | |
| # ========================= | |
| # Utils | |
| # ========================= | |
| def check_ffmpeg() -> None: | |
| try: | |
| subprocess.run(["ffmpeg", "-version"], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) | |
| except Exception as e: | |
| raise RuntimeError("FFmpeg is not installed or not on PATH. Please install ffmpeg.") from e | |
| def ffmpeg_extract_audio(input_video: str, output_wav: str, sr: int = 16000) -> None: | |
| cmd = [ | |
| "ffmpeg", "-y", "-i", input_video, "-vn", | |
| "-ac", "1", "-ar", str(sr), "-f", "wav", output_wav | |
| ] | |
| subprocess.run(cmd, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) | |
| def ffmpeg_concat_audio(files: List[str], out_path: str) -> None: | |
| # concat demuxer (no re-encode) – files must match codecs | |
| # We will just re-encode to MP3 at the end anyway; for safety concatenate with re-encode: | |
| with open(out_path, "wb") as _: | |
| pass # placeholder, we will use pydub to join instead | |
| def ffmpeg_mux(video_path: str, audio_path: str, output_path: str) -> None: | |
| # Copy video, encode audio to AAC, shortest duration | |
| cmd = [ | |
| "ffmpeg", "-y", | |
| "-i", video_path, "-i", audio_path, | |
| "-map", "0:v:0", "-map", "1:a:0", | |
| "-c:v", "copy", "-c:a", "aac", | |
| "-shortest", output_path | |
| ] | |
| subprocess.run(cmd, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) | |
| # ----------------- Subtitle dataclass & helpers ----------------- | |
| class Segment: | |
| start: float | |
| end: float | |
| speaker: str | |
| text: str | |
| def ensure_no_overlap(segments: List[Segment], min_gap: float = 0.08) -> List[Segment]: | |
| segs = sorted(segments, key=lambda s: s.start) | |
| for i in range(1, len(segs)): | |
| prev, cur = segs[i - 1], segs[i] | |
| if prev.end > cur.start - min_gap: | |
| diff = (prev.end - cur.start) + min_gap | |
| cur.start += diff | |
| if cur.start >= cur.end: | |
| cur.end = cur.start + 0.1 | |
| return segs | |
| def to_srt(segments: List[Segment]) -> str: | |
| subs = [] | |
| for i, seg in enumerate(segments, 1): | |
| subs.append( | |
| srt.Subtitle( | |
| index=i, | |
| start=datetime.timedelta(seconds=seg.start), | |
| end=datetime.timedelta(seconds=seg.end), | |
| content=f"{seg.speaker}: {seg.text}", | |
| ) | |
| ) | |
| return srt.compose(subs) | |
| def to_vtt(segments: List[Segment]) -> str: | |
| srt_txt = to_srt(segments) | |
| # A quick-and-dirty SRT->VTT; good enough for demo | |
| vtt_txt = "WEBVTT\n\n" + srt_txt.replace(",", ".") | |
| return vtt_txt | |
| # ========================= | |
| # Pipeline Steps | |
| # ========================= | |
| def run_asr(video_path: str, language: Optional[str]) -> Tuple[str, List[Segment]]: | |
| """ | |
| ASR via faster-whisper. If language is 'auto', leave None to auto-detect. | |
| Returns (detected_lang, segments). | |
| """ | |
| model = get_asr_model() | |
| seg_iter, info = model.transcribe(video_path, beam_size=5, language=None if language in (None, "", "auto") else language) | |
| segments = [] | |
| for seg in seg_iter: | |
| # Diarization placeholder: single speaker | |
| segments.append(Segment(start=float(seg.start), end=float(seg.end), speaker="Speaker 1", text=seg.text.strip())) | |
| fixed = ensure_no_overlap(segments) | |
| return info.language or (language if language and language != "auto" else "en"), fixed | |
| def translate_texts_m2m(texts: List[str], src_lang: str, tgt_lang: str) -> List[str]: | |
| tok, model = get_m2m() | |
| tok.src_lang = src_lang | |
| encoded = tok(texts, return_tensors="pt", padding=True, truncation=True) | |
| with torch.no_grad(): | |
| gen = model.generate(**encoded, forced_bos_token_id=tok.get_lang_id(tgt_lang), max_new_tokens=256) | |
| outs = tok.batch_decode(gen, skip_special_tokens=True) | |
| return outs | |
| def translate_segments(segments: List[Segment], src_lang: str, tgt_lang: str) -> List[Segment]: | |
| texts = [s.text for s in segments] | |
| outs = translate_texts_m2m(texts, src_lang=src_lang, tgt_lang=tgt_lang) | |
| new = [] | |
| for s, t in zip(segments, outs): | |
| new.append(Segment(start=s.start, end=s.end, speaker=s.speaker, text=t)) | |
| return new | |
| async def synth_edge_tts_one(text: str, voice: str, out_path: str, rate: str = "+0%", pitch: str = "+0Hz"): | |
| communicate = edge_tts.Communicate(text, voice=voice, rate=rate, pitch=pitch) | |
| with open(out_path, "wb") as f: | |
| async for chunk in communicate.stream(): | |
| if chunk["type"] == "audio": | |
| f.write(chunk["data"]) | |
| def tts_segment(text: str, lang: str, voice: str, use_edge: bool, rate: str = "+0%", pitch: str = "+0Hz") -> str: | |
| """ | |
| Returns path to MP3 file with spoken text. | |
| """ | |
| out_path = tempfile.mktemp(suffix=".mp3") | |
| if use_edge and EDGE_TTS_AVAILABLE: | |
| # Run async coroutine | |
| asyncio.run(synth_edge_tts_one(text, voice=voice, out_path=out_path, rate=rate, pitch=pitch)) | |
| else: | |
| # gTTS expects language codes like 'en', 'ru', 'zh-cn' | |
| lang_map = {"zh": "zh-cn"} | |
| glang = lang_map.get(lang, lang) | |
| gTTS(text=text, lang=glang).save(out_path) | |
| return out_path | |
| def tts_segments(segments: List[Segment], lang: str, voice_map: Dict[str, str], use_edge: bool, rate: str = "+0%", pitch: str = "+0Hz") -> List[str]: | |
| paths = [] | |
| for s in segments: | |
| v = voice_map.get(s.speaker, EDGE_DEFAULT_VOICE_SPK1) | |
| p = tts_segment(s.text, lang=lang, voice=v, use_edge=use_edge, rate=rate, pitch=pitch) | |
| paths.append(p) | |
| return paths | |
| def join_audio(segment_audio_paths: List[str]) -> str: | |
| """ | |
| Concatenate MP3s with pydub and export as MP3 192k. | |
| """ | |
| out = AudioSegment.silent(duration=0) | |
| for p in segment_audio_paths: | |
| a = AudioSegment.from_file(p) | |
| out += a | |
| out_path = tempfile.mktemp(suffix=".mp3") | |
| out.export(out_path, format="mp3", bitrate="192k") | |
| return out_path | |
| # ========================= | |
| # Content Safety (very basic) | |
| # ========================= | |
| FORBIDDEN = ["terror", "explosive"] | |
| def content_allowed(filename: str) -> bool: | |
| name = (filename or "").lower() | |
| return not any(w in name for w in FORBIDDEN) | |
| # ========================= | |
| # Gradio App | |
| # ========================= | |
| def pipeline(video, src_lang, target_langs, prefer_edge_tts, spk1_voice, spk2_voice, rate_str, pitch_str): | |
| if video is None: | |
| return None, "Upload a video to start.", "", None, None | |
| if not content_allowed(getattr(video, "name", "")): | |
| return None, "Content blocked by policy.", "", None, None | |
| check_ffmpeg() | |
| # Use temp copy so we can hand to ffmpeg reliably | |
| tmp_video = video | |
| if hasattr(video, "name") and os.path.exists(video.name): | |
| tmp_video = video.name | |
| # 1) ASR | |
| detected_lang, src_segments = run_asr(tmp_video, language=src_lang if src_lang != "auto" else None) | |
| # Subtitles for source | |
| srt_src = to_srt(src_segments) | |
| vtt_src = to_vtt(src_segments) | |
| # 2) VOICE MAP (Speaker 1..2) | |
| voice_map = { | |
| "Speaker 1": spk1_voice or EDGE_DEFAULT_VOICE_SPK1, | |
| "Speaker 2": spk2_voice or EDGE_DEFAULT_VOICE_SPK2, | |
| } | |
| # 3) For each target language: translate -> TTS -> join -> mux | |
| out_files_info = [] # list of dicts to show as downloadable files | |
| dubbed_preview = None | |
| use_edge = bool(prefer_edge_tts or USE_EDGE_TTS_ENV) and EDGE_TTS_AVAILABLE | |
| for idx, tgt in enumerate(target_langs or []): | |
| # Translate | |
| tgt_segments = translate_segments(src_segments, src_lang=detected_lang, tgt_lang=tgt) | |
| # Materials (SRT/VTT) | |
| srt_tgt = to_srt(tgt_segments) | |
| vtt_tgt = to_vtt(tgt_segments) | |
| srt_path = tempfile.mktemp(suffix=f"_{tgt}.srt") | |
| vtt_path = tempfile.mktemp(suffix=f"_{tgt}.vtt") | |
| with open(srt_path, "w", encoding="utf-8") as f: | |
| f.write(srt_tgt) | |
| with open(vtt_path, "w", encoding="utf-8") as f: | |
| f.write(vtt_tgt) | |
| # TTS per-segment | |
| seg_mp3s = tts_segments(tgt_segments, lang=tgt, voice_map=voice_map, use_edge=use_edge, rate=rate_str or "+0%", pitch=pitch_str or "+0Hz") | |
| joined_mp3 = join_audio(seg_mp3s) | |
| # Mux with original video | |
| out_mp4 = tempfile.mktemp(suffix=f"_{tgt}.mp4") | |
| ffmpeg_mux(tmp_video, joined_mp3, out_mp4) | |
| # first dubbed video as preview | |
| if dubbed_preview is None: | |
| dubbed_preview = out_mp4 | |
| # register downloads | |
| out_files_info.append({"label": f"Dubbed MP4 ({tgt})", "path": out_mp4}) | |
| out_files_info.append({"label": f"SRT ({tgt})", "path": srt_path}) | |
| out_files_info.append({"label": f"VTT ({tgt})", "path": vtt_path}) | |
| downloads_json = json.dumps(out_files_info, ensure_ascii=False) | |
| # Return: preview_video, source_srt, source_vtt, downloads_json (hidden), message | |
| return dubbed_preview, srt_src, vtt_src, downloads_json, f"Detected source language: {detected_lang}. Done." | |
| def render_downloads(downloads_json: Optional[str]): | |
| if not downloads_json: | |
| return [] | |
| items = json.loads(downloads_json) | |
| return [i["path"] for i in items] | |
| with gr.Blocks(title="VideoDubber – Gradio") as demo: | |
| gr.Markdown("## 🎬 Multilingual Video Translator & Dubber") | |
| gr.Markdown("Upload a video, choose target languages, pick voices, and get dubbed MP4 + subtitles.") | |
| with gr.Row(): | |
| with gr.Column(): | |
| video = gr.Video(label="Upload video (MP4/MOV/MKV)") | |
| src_lang = gr.Dropdown(choices=[("auto", "Auto")] + LANG_CHOICES, value="auto", label="Source language") | |
| target_langs = gr.CheckboxGroup(choices=LANG_CHOICES, value=["ru", "es"], label="Target languages (1–10)") | |
| prefer_edge_tts = gr.Checkbox(value=EDGE_TTS_AVAILABLE or USE_EDGE_TTS_ENV, label=f"Use Edge TTS (available={EDGE_TTS_AVAILABLE}) – else gTTS") | |
| gr.Markdown("**Per-speaker voices** (Edge TTS voice IDs, e.g., `en-US-JennyNeural`, `en-GB-RyanNeural`, `ru-RU-SvetlanaNeural`)") | |
| spk1 = gr.Textbox(value=EDGE_DEFAULT_VOICE_SPK1, label="Speaker 1 voice") | |
| spk2 = gr.Textbox(value=EDGE_DEFAULT_VOICE_SPK2, label="Speaker 2 voice") | |
| rate = gr.Textbox(value="+0%", label="Speaking rate (Edge TTS, e.g., +0%, -10%, +15%)") | |
| pitch = gr.Textbox(value="+0Hz", label="Pitch (Edge TTS, e.g., +0Hz, -2Hz, +4Hz)") | |
| run_btn = gr.Button("Process", variant="primary") | |
| with gr.Column(): | |
| out_video = gr.Video(label="Dubbed preview (first selected language)") | |
| src_srt = gr.Code(label="Source SRT", language="text") | |
| src_vtt = gr.Code(label="Source VTT", language="text") | |
| hidden = gr.Textbox(visible=False) | |
| files = gr.Files(label="Downloads (click to save) – dubbed MP4 + per-language SRT/VTT") | |
| msg = gr.Markdown("") | |
| run_btn.click( | |
| pipeline, | |
| inputs=[video, src_lang, target_langs, prefer_edge_tts, spk1, spk2, rate, pitch], | |
| outputs=[out_video, src_srt, src_vtt, hidden, msg] | |
| ).then( | |
| fn=render_downloads, | |
| inputs=[hidden], | |
| outputs=[files] | |
| ) | |
| if __name__ == "__main__": | |
| demo.launch() | |
| gradio>=4.44.0 | |
| faster-whisper>=1.0.3 | |
| transformers>=4.44.2 | |
| torch>=2.3.1 | |
| sentencepiece>=0.2.0 | |
| gTTS>=2.5.1 | |
| edge-tts>=6.1.14 | |
| ffmpeg-python>=0.2.0 | |
| pydub>=0.25.1 | |
| srt>=3.5.3 | |
| numpy>=1.26.4 | |
| soundfile>=0.12.1 | |
| protobuf<5 | |