Spaces:
Running
Running
Upload 2 files
Browse files- requirements.txt +15 -0
- streamlit_app.py +525 -0
requirements.txt
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Movie Dubber — requirements.txt
|
| 2 |
+
# Hugging Face Spaces (CPU-only, free tier)
|
| 3 |
+
|
| 4 |
+
streamlit>=1.32.0
|
| 5 |
+
faster-whisper>=1.0.0
|
| 6 |
+
transformers>=4.40.0
|
| 7 |
+
sentencepiece>=0.1.99
|
| 8 |
+
sacremoses>=0.1.1
|
| 9 |
+
gTTS>=2.5.1
|
| 10 |
+
pydub>=0.25.1
|
| 11 |
+
librosa>=0.10.1
|
| 12 |
+
soundfile>=0.12.1
|
| 13 |
+
ffmpeg-python>=0.2.0
|
| 14 |
+
torch>=2.2.0
|
| 15 |
+
numpy>=1.24.0
|
streamlit_app.py
ADDED
|
@@ -0,0 +1,525 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
🎬 Movie Dubber — Any Language → Hindi
|
| 3 |
+
Single-file Streamlit app for Hugging Face Spaces (CPU, free tier)
|
| 4 |
+
|
| 5 |
+
ALL code is in this one file — no utils/ folder needed.
|
| 6 |
+
This is the most reliable way to avoid import errors on HF Spaces.
|
| 7 |
+
|
| 8 |
+
Pipeline:
|
| 9 |
+
Upload MP4 → Extract Audio → Transcribe → Translate → TTS → Merge → Download
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
import os
|
| 13 |
+
import gc
|
| 14 |
+
import math
|
| 15 |
+
import tempfile
|
| 16 |
+
import subprocess
|
| 17 |
+
|
| 18 |
+
import streamlit as st
|
| 19 |
+
|
| 20 |
+
# ─── Page config (MUST be first Streamlit call) ───────────────────────────────
|
| 21 |
+
st.set_page_config(
|
| 22 |
+
page_title="🎬 Movie Dubber — Any Language → Hindi",
|
| 23 |
+
page_icon="🎬",
|
| 24 |
+
layout="wide",
|
| 25 |
+
initial_sidebar_state="expanded",
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
st.markdown("""
|
| 29 |
+
<style>
|
| 30 |
+
.stProgress > div > div { background-color: #FF4B4B; }
|
| 31 |
+
.seg-card {
|
| 32 |
+
background: #1a1a2e;
|
| 33 |
+
border-left: 4px solid #FF4B4B;
|
| 34 |
+
border-radius: 8px;
|
| 35 |
+
padding: 10px 14px;
|
| 36 |
+
margin: 6px 0;
|
| 37 |
+
}
|
| 38 |
+
.spk { background:#FF4B4B; color:#fff; border-radius:10px;
|
| 39 |
+
padding:2px 9px; font-size:0.78em; font-weight:700; }
|
| 40 |
+
.ts { color:#999; font-size:0.82em; }
|
| 41 |
+
</style>
|
| 42 |
+
""", unsafe_allow_html=True)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
# ═══════════════════════════════════════════════════════════════════════════════
|
| 46 |
+
# SECTION 1 — AUDIO UTILITIES
|
| 47 |
+
# ═══════════════════════════════════════════════════════════════════════════════
|
| 48 |
+
|
| 49 |
+
def extract_audio(video_path: str) -> str:
|
| 50 |
+
"""
|
| 51 |
+
Pull audio from video using ffmpeg.
|
| 52 |
+
Returns path to a 16 kHz mono WAV — ideal for Whisper.
|
| 53 |
+
"""
|
| 54 |
+
out = os.path.join(tempfile.gettempdir(), "extracted_audio.wav")
|
| 55 |
+
subprocess.run([
|
| 56 |
+
"ffmpeg", "-y", "-i", video_path,
|
| 57 |
+
"-vn", # no video
|
| 58 |
+
"-acodec", "pcm_s16le", # uncompressed WAV
|
| 59 |
+
"-ar", "16000", # 16 kHz
|
| 60 |
+
"-ac", "1", # mono
|
| 61 |
+
out,
|
| 62 |
+
], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
| 63 |
+
return out
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def detect_silence_segments(audio_path: str):
|
| 67 |
+
"""Return list of (start_sec, end_sec) for silent / music regions."""
|
| 68 |
+
from pydub import AudioSegment
|
| 69 |
+
from pydub.silence import detect_nonsilent
|
| 70 |
+
|
| 71 |
+
audio = AudioSegment.from_wav(audio_path)
|
| 72 |
+
speech = detect_nonsilent(audio, min_silence_len=700, silence_thresh=-40)
|
| 73 |
+
|
| 74 |
+
total_ms = len(audio)
|
| 75 |
+
silence, prev = [], 0
|
| 76 |
+
for s, e in speech:
|
| 77 |
+
if s > prev + 200:
|
| 78 |
+
silence.append((prev / 1000, s / 1000))
|
| 79 |
+
prev = e
|
| 80 |
+
if prev < total_ms - 200:
|
| 81 |
+
silence.append((prev / 1000, total_ms / 1000))
|
| 82 |
+
return silence
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
# ═══════════════════════════════════════════════════════════════════════════════
|
| 86 |
+
# SECTION 2 — TRANSCRIPTION
|
| 87 |
+
# ═══════════════════════════════════════════════════════════════════════════════
|
| 88 |
+
|
| 89 |
+
def transcribe_audio(audio_path: str, model_size: str = "base", progress_cb=None):
|
| 90 |
+
"""
|
| 91 |
+
Transcribe audio with faster-whisper (INT8 quantised, CPU-optimised).
|
| 92 |
+
Returns list of { start, end, text, speaker, lang }.
|
| 93 |
+
"""
|
| 94 |
+
from faster_whisper import WhisperModel
|
| 95 |
+
|
| 96 |
+
if progress_cb:
|
| 97 |
+
progress_cb(5, f"Loading Whisper '{model_size}'…")
|
| 98 |
+
|
| 99 |
+
model = WhisperModel(model_size, device="cpu", compute_type="int8")
|
| 100 |
+
|
| 101 |
+
if progress_cb:
|
| 102 |
+
progress_cb(20, "Transcribing…")
|
| 103 |
+
|
| 104 |
+
raw_segs, info = model.transcribe(
|
| 105 |
+
audio_path,
|
| 106 |
+
beam_size=3,
|
| 107 |
+
vad_filter=True,
|
| 108 |
+
vad_parameters={"min_silence_duration_ms": 500},
|
| 109 |
+
word_timestamps=True,
|
| 110 |
+
)
|
| 111 |
+
|
| 112 |
+
if progress_cb:
|
| 113 |
+
progress_cb(50, f"Language detected: {info.language}")
|
| 114 |
+
|
| 115 |
+
segments = []
|
| 116 |
+
for i, seg in enumerate(raw_segs):
|
| 117 |
+
text = seg.text.strip()
|
| 118 |
+
if not text:
|
| 119 |
+
continue
|
| 120 |
+
speaker = _heuristic_speaker(segments, seg.start)
|
| 121 |
+
segments.append({
|
| 122 |
+
"start": round(seg.start, 2),
|
| 123 |
+
"end": round(seg.end, 2),
|
| 124 |
+
"text": text,
|
| 125 |
+
"speaker": speaker,
|
| 126 |
+
"lang": info.language,
|
| 127 |
+
})
|
| 128 |
+
if progress_cb and i % 5 == 0:
|
| 129 |
+
progress_cb(min(90, 50 + i * 2), f"Segment {i+1} done…")
|
| 130 |
+
|
| 131 |
+
del model
|
| 132 |
+
gc.collect()
|
| 133 |
+
return segments
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def _heuristic_speaker(existing, current_start):
|
| 137 |
+
"""Flip speaker ID when gap > 1.5 s (lightweight alternative to pyannote)."""
|
| 138 |
+
if not existing:
|
| 139 |
+
return "1"
|
| 140 |
+
if current_start - existing[-1]["end"] > 1.5:
|
| 141 |
+
return "2" if existing[-1]["speaker"] == "1" else "1"
|
| 142 |
+
return existing[-1]["speaker"]
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
# ═══════════════════════════════════════════════════════════════════════════════
|
| 146 |
+
# SECTION 3 — TRANSLATION (Helsinki-NLP MarianMT)
|
| 147 |
+
# ═══════════════════════════════════════════════════════════════════════════════
|
| 148 |
+
|
| 149 |
+
_DIRECT_HI = {"en-hi": "Helsinki-NLP/opus-mt-en-hi"}
|
| 150 |
+
_TO_EN = {
|
| 151 |
+
"de": "Helsinki-NLP/opus-mt-de-en",
|
| 152 |
+
"fr": "Helsinki-NLP/opus-mt-fr-en",
|
| 153 |
+
"es": "Helsinki-NLP/opus-mt-es-en",
|
| 154 |
+
"it": "Helsinki-NLP/opus-mt-it-en",
|
| 155 |
+
"pt": "Helsinki-NLP/opus-mt-pt-en",
|
| 156 |
+
"ja": "Helsinki-NLP/opus-mt-ja-en",
|
| 157 |
+
"zh": "Helsinki-NLP/opus-mt-zh-en",
|
| 158 |
+
"ko": "Helsinki-NLP/opus-mt-ko-en",
|
| 159 |
+
"ar": "Helsinki-NLP/opus-mt-ar-en",
|
| 160 |
+
"ru": "Helsinki-NLP/opus-mt-ru-en",
|
| 161 |
+
"tr": "Helsinki-NLP/opus-mt-tr-en",
|
| 162 |
+
"nl": "Helsinki-NLP/opus-mt-nl-en",
|
| 163 |
+
"pl": "Helsinki-NLP/opus-mt-pl-en",
|
| 164 |
+
}
|
| 165 |
+
_mt_cache = {}
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def _load_mt(name):
|
| 169 |
+
from transformers import MarianMTModel, MarianTokenizer
|
| 170 |
+
if name not in _mt_cache:
|
| 171 |
+
tok = MarianTokenizer.from_pretrained(name)
|
| 172 |
+
mdl = MarianMTModel.from_pretrained(name)
|
| 173 |
+
mdl.eval()
|
| 174 |
+
_mt_cache[name] = (tok, mdl)
|
| 175 |
+
return _mt_cache[name]
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
def _mt(text, model_name):
|
| 179 |
+
tok, mdl = _load_mt(model_name)
|
| 180 |
+
inp = tok([text], return_tensors="pt", padding=True,
|
| 181 |
+
truncation=True, max_length=512)
|
| 182 |
+
out = mdl.generate(**inp, num_beams=2, max_length=512)
|
| 183 |
+
return tok.decode(out[0], skip_special_tokens=True).strip()
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
def translate_to_hindi(text: str, source_lang: str = "en") -> str:
|
| 187 |
+
"""Translate text → Hindi. Pivots through English if no direct model."""
|
| 188 |
+
if not text.strip() or source_lang == "hi":
|
| 189 |
+
return text
|
| 190 |
+
src = source_lang.lower()
|
| 191 |
+
# Direct path
|
| 192 |
+
if f"{src}-hi" in _DIRECT_HI:
|
| 193 |
+
try:
|
| 194 |
+
return _mt(text, _DIRECT_HI[f"{src}-hi"])
|
| 195 |
+
except Exception:
|
| 196 |
+
pass
|
| 197 |
+
# Pivot: src → English
|
| 198 |
+
if src != "en" and src in _TO_EN:
|
| 199 |
+
try:
|
| 200 |
+
text = _mt(text, _TO_EN[src])
|
| 201 |
+
except Exception:
|
| 202 |
+
pass
|
| 203 |
+
# English → Hindi
|
| 204 |
+
try:
|
| 205 |
+
return _mt(text, _DIRECT_HI["en-hi"])
|
| 206 |
+
except Exception:
|
| 207 |
+
return f"[Translation failed: {text}]"
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
# ═══════════════════════════════════════════════════════════════════════════════
|
| 211 |
+
# SECTION 4 — HINDI TTS (gTTS — free, instant, no GPU)
|
| 212 |
+
# ═══════════════════════════════════════════════════════════════════════════════
|
| 213 |
+
|
| 214 |
+
SPEAKER_OPTIONS = {
|
| 215 |
+
"Hindi (India — Standard)": "com",
|
| 216 |
+
"Hindi (India — Alternate)": "co.in",
|
| 217 |
+
}
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
def _text_to_wav(text, tld, out_path):
|
| 221 |
+
"""Hindi text → WAV using gTTS."""
|
| 222 |
+
from gtts import gTTS
|
| 223 |
+
from pydub import AudioSegment
|
| 224 |
+
|
| 225 |
+
if not text.strip():
|
| 226 |
+
AudioSegment.silent(500).export(out_path, format="wav")
|
| 227 |
+
return
|
| 228 |
+
|
| 229 |
+
mp3 = out_path.replace(".wav", ".mp3")
|
| 230 |
+
gTTS(text=text, lang="hi", tld=tld, slow=False).save(mp3)
|
| 231 |
+
AudioSegment.from_mp3(mp3).export(out_path, format="wav")
|
| 232 |
+
try:
|
| 233 |
+
os.remove(mp3)
|
| 234 |
+
except Exception:
|
| 235 |
+
pass
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
def _fit_to_duration(speech, target_ms):
|
| 239 |
+
"""Speed-fit TTS audio to match original segment duration."""
|
| 240 |
+
from pydub import AudioSegment
|
| 241 |
+
dur = len(speech)
|
| 242 |
+
if not dur or not target_ms:
|
| 243 |
+
return speech
|
| 244 |
+
ratio = dur / target_ms
|
| 245 |
+
if ratio > 1.3:
|
| 246 |
+
mult = min(ratio, 1.8)
|
| 247 |
+
speech = speech._spawn(
|
| 248 |
+
speech.raw_data,
|
| 249 |
+
overrides={"frame_rate": int(speech.frame_rate * mult)},
|
| 250 |
+
).set_frame_rate(speech.frame_rate)
|
| 251 |
+
elif dur < target_ms:
|
| 252 |
+
speech = speech + AudioSegment.silent(target_ms - dur)
|
| 253 |
+
return speech
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
def generate_hindi_speech(segments, speaker="com", speech_volume=1.2, progress_cb=None):
|
| 257 |
+
"""
|
| 258 |
+
Generate full dubbed audio track.
|
| 259 |
+
Each segment → TTS → speed-fit → overlaid at correct timestamp.
|
| 260 |
+
"""
|
| 261 |
+
from pydub import AudioSegment
|
| 262 |
+
|
| 263 |
+
total_ms = int(max(s["end"] for s in segments) * 1000) + 2000
|
| 264 |
+
track = AudioSegment.silent(duration=total_ms)
|
| 265 |
+
tmp, n = tempfile.gettempdir(), len(segments)
|
| 266 |
+
|
| 267 |
+
for i, seg in enumerate(segments):
|
| 268 |
+
if progress_cb:
|
| 269 |
+
progress_cb(int((i + 1) / n * 90), f"Synthesising {i+1}/{n}…")
|
| 270 |
+
|
| 271 |
+
hindi = seg.get("hindi_text", "").strip()
|
| 272 |
+
if not hindi:
|
| 273 |
+
continue
|
| 274 |
+
|
| 275 |
+
start_ms = int(seg["start"] * 1000)
|
| 276 |
+
target_ms = int(seg["end"] * 1000) - start_ms
|
| 277 |
+
wav = os.path.join(tmp, f"seg_{i:04d}.wav")
|
| 278 |
+
|
| 279 |
+
try:
|
| 280 |
+
_text_to_wav(hindi, speaker, wav)
|
| 281 |
+
except Exception:
|
| 282 |
+
continue
|
| 283 |
+
|
| 284 |
+
speech = AudioSegment.from_wav(wav)
|
| 285 |
+
if speech_volume != 1.0:
|
| 286 |
+
speech = speech + (20 * math.log10(max(speech_volume, 0.01)))
|
| 287 |
+
speech = _fit_to_duration(speech, target_ms)
|
| 288 |
+
track = track.overlay(speech, position=start_ms)
|
| 289 |
+
|
| 290 |
+
try:
|
| 291 |
+
os.remove(wav)
|
| 292 |
+
except Exception:
|
| 293 |
+
pass
|
| 294 |
+
gc.collect()
|
| 295 |
+
|
| 296 |
+
out = os.path.join(tmp, "hindi_dubbed_audio.wav")
|
| 297 |
+
track.export(out, format="wav")
|
| 298 |
+
return out
|
| 299 |
+
|
| 300 |
+
|
| 301 |
+
# ═══════════════════════════════════════════════════════════════════════════════
|
| 302 |
+
# SECTION 5 — VIDEO MERGE (ffmpeg, no video re-encoding)
|
| 303 |
+
# ═══════════════════════════════════════════════════════════════════════════════
|
| 304 |
+
|
| 305 |
+
def merge_audio_video(video_path, dubbed_audio_path, bgm_volume=0.15):
|
| 306 |
+
"""
|
| 307 |
+
Mix Hindi speech with faint original BGM, then mux into video.
|
| 308 |
+
Video stream is COPIED (no re-encode) → fast even on CPU.
|
| 309 |
+
"""
|
| 310 |
+
out = os.path.join(tempfile.gettempdir(), "hindi_dubbed_output.mp4")
|
| 311 |
+
bgm = str(round(bgm_volume, 3))
|
| 312 |
+
|
| 313 |
+
result = subprocess.run([
|
| 314 |
+
"ffmpeg", "-y",
|
| 315 |
+
"-i", video_path,
|
| 316 |
+
"-i", dubbed_audio_path,
|
| 317 |
+
"-filter_complex",
|
| 318 |
+
f"[0:a]volume={bgm}[b];[b][1:a]amix=inputs=2:duration=first[mix]",
|
| 319 |
+
"-map", "0:v", "-map", "[mix]",
|
| 320 |
+
"-c:v", "copy", "-c:a", "aac", "-b:a", "192k", "-shortest",
|
| 321 |
+
out,
|
| 322 |
+
], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
| 323 |
+
|
| 324 |
+
if result.returncode != 0:
|
| 325 |
+
# Fallback: replace audio entirely (skip BGM blend)
|
| 326 |
+
fallback = os.path.join(tempfile.gettempdir(), "dubbed_fallback.mp4")
|
| 327 |
+
subprocess.run([
|
| 328 |
+
"ffmpeg", "-y",
|
| 329 |
+
"-i", video_path, "-i", dubbed_audio_path,
|
| 330 |
+
"-map", "0:v", "-map", "1:a",
|
| 331 |
+
"-c:v", "copy", "-c:a", "aac", "-b:a", "192k", "-shortest",
|
| 332 |
+
fallback,
|
| 333 |
+
], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
| 334 |
+
return fallback
|
| 335 |
+
|
| 336 |
+
return out
|
| 337 |
+
|
| 338 |
+
|
| 339 |
+
# ═══════════════════════════════════════════════════════════════════════════════
|
| 340 |
+
# STREAMLIT UI
|
| 341 |
+
# ═══════════════════════════════════════════════════════════════════════════════
|
| 342 |
+
|
| 343 |
+
# Session state
|
| 344 |
+
for k in ["audio_path", "segments", "translated_segments",
|
| 345 |
+
"dubbed_audio_path", "output_video_path"]:
|
| 346 |
+
if k not in st.session_state:
|
| 347 |
+
st.session_state[k] = None
|
| 348 |
+
|
| 349 |
+
# ── Sidebar ───────────────────────────────────────────────────────────────────
|
| 350 |
+
with st.sidebar:
|
| 351 |
+
st.title("⚙️ Settings")
|
| 352 |
+
|
| 353 |
+
st.subheader("🎙️ Transcription")
|
| 354 |
+
whisper_model = st.selectbox(
|
| 355 |
+
"Whisper model",
|
| 356 |
+
["tiny", "base", "small"],
|
| 357 |
+
index=1,
|
| 358 |
+
help="tiny=fastest | base=balanced ✅ | small=most accurate",
|
| 359 |
+
)
|
| 360 |
+
|
| 361 |
+
st.subheader("🗣️ Hindi Voice")
|
| 362 |
+
selected_speaker = st.selectbox("Voice", list(SPEAKER_OPTIONS.keys()))
|
| 363 |
+
|
| 364 |
+
st.subheader("🎚️ Audio Mix")
|
| 365 |
+
bgm_volume = st.slider("Background music volume", 0.0, 1.0, 0.15, 0.05)
|
| 366 |
+
speech_volume = st.slider("Hindi speech volume", 0.5, 2.0, 1.2, 0.1)
|
| 367 |
+
|
| 368 |
+
st.subheader("ℹ️ Stack")
|
| 369 |
+
st.caption("faster-whisper · Helsinki-NLP · gTTS · ffmpeg\n100% free · CPU · Open-source")
|
| 370 |
+
|
| 371 |
+
# ── Main ─────────────────────────────────────────────────────────────────────
|
| 372 |
+
st.title("🎬 Movie Dubber")
|
| 373 |
+
st.markdown("**Upload any video → Get Hindi dubbed output — 100% free**")
|
| 374 |
+
|
| 375 |
+
# STEP 1 — Upload
|
| 376 |
+
st.header("Step 1 — Upload Video")
|
| 377 |
+
uploaded = st.file_uploader(
|
| 378 |
+
"MP4 / AVI / MKV / MOV (keep under ~200 MB for CPU tier)",
|
| 379 |
+
type=["mp4", "avi", "mkv", "mov"],
|
| 380 |
+
)
|
| 381 |
+
|
| 382 |
+
if uploaded:
|
| 383 |
+
video_path = os.path.join(tempfile.gettempdir(), uploaded.name)
|
| 384 |
+
with open(video_path, "wb") as f:
|
| 385 |
+
f.write(uploaded.read())
|
| 386 |
+
|
| 387 |
+
st.video(video_path)
|
| 388 |
+
st.success(f"✅ {uploaded.name} ({os.path.getsize(video_path)/1e6:.1f} MB)")
|
| 389 |
+
|
| 390 |
+
# STEP 2 — Extract Audio
|
| 391 |
+
st.header("Step 2 — Extract Audio")
|
| 392 |
+
if st.button("🔊 Extract Audio", use_container_width=True):
|
| 393 |
+
with st.spinner("Running ffmpeg…"):
|
| 394 |
+
bar = st.progress(0, "Extracting…")
|
| 395 |
+
apth = extract_audio(video_path)
|
| 396 |
+
bar.progress(70, "Detecting silence…")
|
| 397 |
+
sil = detect_silence_segments(apth)
|
| 398 |
+
bar.progress(100, "Done!")
|
| 399 |
+
st.session_state.audio_path = apth
|
| 400 |
+
|
| 401 |
+
st.audio(apth)
|
| 402 |
+
st.success("✅ Audio extracted!")
|
| 403 |
+
if sil:
|
| 404 |
+
with st.expander(f"🔇 {len(sil)} silence segment(s)"):
|
| 405 |
+
for s, e in sil[:10]:
|
| 406 |
+
st.caption(f" {s:.1f}s → {e:.1f}s")
|
| 407 |
+
|
| 408 |
+
# STEP 3 — Transcribe
|
| 409 |
+
if st.session_state.audio_path:
|
| 410 |
+
st.header("Step 3 — Transcribe Speech")
|
| 411 |
+
st.info(f"Whisper **{whisper_model}** on CPU — ~1–3 min/min of audio. ☕")
|
| 412 |
+
|
| 413 |
+
if st.button("📝 Transcribe", use_container_width=True):
|
| 414 |
+
bar = st.progress(0, "Loading…")
|
| 415 |
+
segs = transcribe_audio(
|
| 416 |
+
st.session_state.audio_path,
|
| 417 |
+
model_size=whisper_model,
|
| 418 |
+
progress_cb=lambda p, t: bar.progress(p, t),
|
| 419 |
+
)
|
| 420 |
+
bar.progress(100, "Done!")
|
| 421 |
+
st.session_state.segments = segs
|
| 422 |
+
st.session_state.translated_segments = [{**s, "hindi_text": ""} for s in segs]
|
| 423 |
+
st.success(f"✅ {len(segs)} segments found!")
|
| 424 |
+
|
| 425 |
+
# STEP 4 — Translate
|
| 426 |
+
if st.session_state.segments:
|
| 427 |
+
st.header("Step 4 — Translate to Hindi")
|
| 428 |
+
|
| 429 |
+
if st.button("🌏 Translate All", use_container_width=True):
|
| 430 |
+
segs = st.session_state.segments
|
| 431 |
+
bar = st.progress(0, "Loading translation model…")
|
| 432 |
+
out = []
|
| 433 |
+
for i, seg in enumerate(segs):
|
| 434 |
+
bar.progress(int((i+1)/len(segs)*100), f"Translating {i+1}/{len(segs)}…")
|
| 435 |
+
out.append({**seg, "hindi_text": translate_to_hindi(
|
| 436 |
+
seg["text"], source_lang=seg.get("lang", "en")
|
| 437 |
+
)})
|
| 438 |
+
gc.collect()
|
| 439 |
+
st.session_state.translated_segments = out
|
| 440 |
+
st.success("✅ Translation done!")
|
| 441 |
+
|
| 442 |
+
# STEP 5 — Edit
|
| 443 |
+
if st.session_state.translated_segments and any(
|
| 444 |
+
s.get("hindi_text") for s in st.session_state.translated_segments
|
| 445 |
+
):
|
| 446 |
+
st.header("Step 5 — Review & Edit Translations")
|
| 447 |
+
st.caption("Fix Hindi text before generating speech.")
|
| 448 |
+
|
| 449 |
+
edited = []
|
| 450 |
+
for i, seg in enumerate(st.session_state.translated_segments):
|
| 451 |
+
c1, c2 = st.columns(2)
|
| 452 |
+
with c1:
|
| 453 |
+
st.markdown(
|
| 454 |
+
f'<div class="seg-card">'
|
| 455 |
+
f'<span class="spk">Speaker {seg.get("speaker","?")}</span> '
|
| 456 |
+
f'<span class="ts">{seg["start"]:.1f}s→{seg["end"]:.1f}s</span><br>'
|
| 457 |
+
f'<b>Original:</b> {seg["text"]}</div>',
|
| 458 |
+
unsafe_allow_html=True,
|
| 459 |
+
)
|
| 460 |
+
with c2:
|
| 461 |
+
new = st.text_area(
|
| 462 |
+
f"Hindi #{i+1}", value=seg.get("hindi_text",""),
|
| 463 |
+
key=f"hi_{i}", height=100, label_visibility="collapsed",
|
| 464 |
+
)
|
| 465 |
+
edited.append({**seg, "hindi_text": new})
|
| 466 |
+
|
| 467 |
+
if st.button("💾 Save Edits", use_container_width=True):
|
| 468 |
+
st.session_state.translated_segments = edited
|
| 469 |
+
st.success("✅ Saved!")
|
| 470 |
+
|
| 471 |
+
# STEP 6 — TTS
|
| 472 |
+
st.header("Step 6 — Generate Hindi Speech")
|
| 473 |
+
if st.button("🎤 Generate Hindi Audio", use_container_width=True):
|
| 474 |
+
bar = st.progress(0, "Starting…")
|
| 475 |
+
dpth = generate_hindi_speech(
|
| 476 |
+
st.session_state.translated_segments,
|
| 477 |
+
speaker=SPEAKER_OPTIONS[selected_speaker],
|
| 478 |
+
speech_volume=speech_volume,
|
| 479 |
+
progress_cb=lambda p, t: bar.progress(p, t),
|
| 480 |
+
)
|
| 481 |
+
bar.progress(100, "Done!")
|
| 482 |
+
st.session_state.dubbed_audio_path = dpth
|
| 483 |
+
st.audio(dpth)
|
| 484 |
+
st.success("✅ Hindi audio ready!")
|
| 485 |
+
|
| 486 |
+
# STEP 7 — Merge
|
| 487 |
+
if st.session_state.dubbed_audio_path:
|
| 488 |
+
st.header("Step 7 — Merge & Download")
|
| 489 |
+
if st.button("🎬 Create Dubbed Video", use_container_width=True):
|
| 490 |
+
with st.spinner("Merging…"):
|
| 491 |
+
out_path = merge_audio_video(
|
| 492 |
+
video_path=video_path,
|
| 493 |
+
dubbed_audio_path=st.session_state.dubbed_audio_path,
|
| 494 |
+
bgm_volume=bgm_volume,
|
| 495 |
+
)
|
| 496 |
+
st.session_state.output_video_path = out_path
|
| 497 |
+
|
| 498 |
+
st.video(out_path)
|
| 499 |
+
st.success("🎉 Done!")
|
| 500 |
+
with open(out_path, "rb") as f:
|
| 501 |
+
st.download_button(
|
| 502 |
+
"⬇️ Download Hindi Dubbed Video",
|
| 503 |
+
data=f,
|
| 504 |
+
file_name="hindi_dubbed.mp4",
|
| 505 |
+
mime="video/mp4",
|
| 506 |
+
use_container_width=True,
|
| 507 |
+
)
|
| 508 |
+
|
| 509 |
+
else:
|
| 510 |
+
st.markdown("""
|
| 511 |
+
---
|
| 512 |
+
### How it works
|
| 513 |
+
|
| 514 |
+
| Step | What happens |
|
| 515 |
+
|------|-------------|
|
| 516 |
+
| 1️⃣ Upload | Any MP4 / AVI / MKV video |
|
| 517 |
+
| 2️⃣ Extract | ffmpeg pulls the audio track |
|
| 518 |
+
| 3️⃣ Transcribe | Whisper converts speech → text with timestamps |
|
| 519 |
+
| 4️⃣ Translate | MarianMT translates → natural Hindi |
|
| 520 |
+
| 5️⃣ Edit | Fix any translation manually |
|
| 521 |
+
| 6️⃣ Speak | gTTS generates Hindi audio per segment |
|
| 522 |
+
| 7️⃣ Merge | ffmpeg mixes Hindi audio back into video |
|
| 523 |
+
|
| 524 |
+
> ⚠️ On CPU: transcription takes ~1–3 min per minute of video. Grab a chai ☕
|
| 525 |
+
""")
|