Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,210 +1,140 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import
|
| 3 |
-
import
|
| 4 |
-
import
|
| 5 |
-
import
|
| 6 |
-
from
|
| 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 |
-
outputs = para_model.generate(**inputs, max_length=512, num_beams=4)
|
| 142 |
-
return _clean_text(para_tok.decode(outputs[0], skip_special_tokens=True))
|
| 143 |
-
|
| 144 |
-
# ------------ SRT Helpers ------------
|
| 145 |
-
def smart_sentence_chunks(text: str, max_len: int = 800) -> List[str]:
|
| 146 |
-
"""
|
| 147 |
-
Split text by sentences with a soft max token length (approx by chars).
|
| 148 |
-
"""
|
| 149 |
-
# crude sentence split
|
| 150 |
-
sents = re.split(r'(?<=[.!?])\s+', _clean_text(text))
|
| 151 |
-
chunks, cur = [], ""
|
| 152 |
-
for s in sents:
|
| 153 |
-
if len(cur) + len(s) + 1 <= max_len:
|
| 154 |
-
cur = (cur + " " + s).strip()
|
| 155 |
-
else:
|
| 156 |
-
if cur:
|
| 157 |
-
chunks.append(cur)
|
| 158 |
-
cur = s
|
| 159 |
-
if cur:
|
| 160 |
-
chunks.append(cur)
|
| 161 |
-
return chunks
|
| 162 |
-
|
| 163 |
-
def make_naive_srt(transcript: str, total_seconds: float) -> str:
|
| 164 |
-
"""
|
| 165 |
-
Make a "good enough" SRT by assigning equal time slices per sentence.
|
| 166 |
-
Not perfect, but usable when we don't have per-token timestamps.
|
| 167 |
-
"""
|
| 168 |
-
sents = [s for s in re.split(r'(?<=[.!?])\s+', _clean_text(transcript)) if s]
|
| 169 |
-
n = max(1, len(sents))
|
| 170 |
-
# Avoid too-short windows: min 1.5s per sentence
|
| 171 |
-
avg = max(1.5, total_seconds / n) if total_seconds > 0 else 3.0
|
| 172 |
-
lines = []
|
| 173 |
-
t = 0.0
|
| 174 |
-
for i, s in enumerate(sents, start=1):
|
| 175 |
-
start = t
|
| 176 |
-
end = t + avg
|
| 177 |
-
t = end
|
| 178 |
-
lines.append(str(i))
|
| 179 |
-
lines.append(f"{_fmt_srt_time(start)} --> {_fmt_srt_time(end)}")
|
| 180 |
-
lines.append(s)
|
| 181 |
-
lines.append("") # blank
|
| 182 |
-
return "\n".join(lines).strip()
|
| 183 |
-
|
| 184 |
-
def _fmt_srt_time(sec: float) -> str:
|
| 185 |
-
sec = max(0.0, sec)
|
| 186 |
-
h = int(sec // 3600)
|
| 187 |
-
m = int((sec % 3600) // 60)
|
| 188 |
-
s = int(sec % 60)
|
| 189 |
-
ms = int((sec - math.floor(sec)) * 1000)
|
| 190 |
-
return f"{h:02d}:{m:02d}:{s:02d},{ms:03d}"
|
| 191 |
-
|
| 192 |
-
# ------------ Gradio Handlers ------------
|
| 193 |
-
def ui_video_translate(video, src_lang, tgt_lang):
|
| 194 |
-
if video is None:
|
| 195 |
-
return gr.update(value=""), gr.update(value=""), gr.update(value=b"", visible=False), gr.update(value="")
|
| 196 |
-
src = M2M_LANGS[src_lang]
|
| 197 |
-
tgt = M2M_LANGS[tgt_lang]
|
| 198 |
-
transcript, duration = transcribe_video(video)
|
| 199 |
-
translated = translate_text_m2m(transcript, src, tgt)
|
| 200 |
-
srt_text = make_naive_srt(translated, duration)
|
| 201 |
-
# Prepare SRT file for download
|
| 202 |
-
srt_bytes = srt_text.encode("utf-8")
|
| 203 |
-
srt_file = io.BytesIO(srt_bytes)
|
| 204 |
-
srt_file.name = "subtitles_translated.srt"
|
| 205 |
-
return transcript, translated, srt_file, srt_text
|
| 206 |
-
|
| 207 |
-
def ui_video_summarize(video, lang_hint):
|
| 208 |
-
if video is None:
|
| 209 |
-
return "", ""
|
| 210 |
-
# Transcribe then summarize (lang-hint doesn’t constrain
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import tempfile
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
import gradio as gr
|
| 5 |
+
import yt_dlp
|
| 6 |
+
from faster_whisper import WhisperModel
|
| 7 |
+
|
| 8 |
+
# -------- Settings you can tweak --------
|
| 9 |
+
DEFAULT_MODEL = os.getenv("WHISPER_MODEL", "small") # small | medium | large-v3 (requires more RAM)
|
| 10 |
+
COMPUTE_TYPE = os.getenv("COMPUTE_TYPE", "int8") # int8 | int8_float16 | float16 | float32
|
| 11 |
+
MAX_DURATION_SEC = int(os.getenv("MAX_DURATION_SEC", "1800")) # 30 min cap to keep things predictable
|
| 12 |
+
# ---------------------------------------
|
| 13 |
+
|
| 14 |
+
# Lazy-load model once per container
|
| 15 |
+
_model = None
|
| 16 |
+
def get_model():
|
| 17 |
+
global _model
|
| 18 |
+
if _model is None:
|
| 19 |
+
_model = WhisperModel(DEFAULT_MODEL, compute_type=COMPUTE_TYPE)
|
| 20 |
+
return _model
|
| 21 |
+
|
| 22 |
+
def _download_youtube_audio(url: str, workdir: str) -> str:
|
| 23 |
+
"""
|
| 24 |
+
Download YouTube audio and convert to WAV mono 16 kHz using FFmpegExtractAudio.
|
| 25 |
+
Returns path to the WAV file.
|
| 26 |
+
"""
|
| 27 |
+
outtmpl = str(Path(workdir) / "%(id)s.%(ext)s")
|
| 28 |
+
ydl_opts = {
|
| 29 |
+
"format": "bestaudio/best",
|
| 30 |
+
"outtmpl": outtmpl,
|
| 31 |
+
"noplaylist": True,
|
| 32 |
+
"quiet": True,
|
| 33 |
+
"no_warnings": True,
|
| 34 |
+
"postprocessors": [
|
| 35 |
+
{
|
| 36 |
+
"key": "FFmpegExtractAudio",
|
| 37 |
+
"preferredcodec": "wav",
|
| 38 |
+
"preferredquality": "5",
|
| 39 |
+
}
|
| 40 |
+
],
|
| 41 |
+
# ensure mono @ 16 kHz
|
| 42 |
+
"postprocessor_args": ["-ac", "1", "-ar", "16000"],
|
| 43 |
+
}
|
| 44 |
+
|
| 45 |
+
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
|
| 46 |
+
info = ydl.extract_info(url, download=True)
|
| 47 |
+
duration = info.get("duration") or 0
|
| 48 |
+
if duration and duration > MAX_DURATION_SEC:
|
| 49 |
+
raise gr.Error(f"Video too long ({duration//60} min). Max allowed is {MAX_DURATION_SEC//60} min.")
|
| 50 |
+
|
| 51 |
+
# Find the produced .wav in the temp dir (name can vary)
|
| 52 |
+
wavs = list(Path(workdir).glob("*.wav"))
|
| 53 |
+
if not wavs:
|
| 54 |
+
raise gr.Error("Audio extraction failed. Try a different video.")
|
| 55 |
+
return str(wavs[0])
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def _write_srt(segments, path: str):
|
| 59 |
+
def srt_timestamp(t):
|
| 60 |
+
# t in seconds -> "HH:MM:SS,mmm"
|
| 61 |
+
h = int(t // 3600)
|
| 62 |
+
m = int((t % 3600) // 60)
|
| 63 |
+
s = int(t % 60)
|
| 64 |
+
ms = int((t - int(t)) * 1000)
|
| 65 |
+
return f"{h:02d}:{m:02d}:{s:02d},{ms:03d}"
|
| 66 |
+
|
| 67 |
+
with open(path, "w", encoding="utf-8") as f:
|
| 68 |
+
for i, seg in enumerate(segments, start=1):
|
| 69 |
+
f.write(f"{i}\n")
|
| 70 |
+
f.write(f"{srt_timestamp(seg.start)} --> {srt_timestamp(seg.end)}\n")
|
| 71 |
+
f.write(seg.text.strip() + "\n\n")
|
| 72 |
+
|
| 73 |
+
def transcribe(youtube_url, upload_file, model_size, language, translate_to_english):
|
| 74 |
+
if not youtube_url and not upload_file:
|
| 75 |
+
raise gr.Error("Provide a YouTube URL or upload a file.")
|
| 76 |
+
|
| 77 |
+
# Update model on-the-fly if user changes it
|
| 78 |
+
global _model
|
| 79 |
+
if _model is None or getattr(_model, "_model_size", None) != model_size:
|
| 80 |
+
_model = WhisperModel(model_size, compute_type=COMPUTE_TYPE)
|
| 81 |
+
_model._model_size = model_size # tag for reuse
|
| 82 |
+
|
| 83 |
+
with tempfile.TemporaryDirectory() as td:
|
| 84 |
+
if youtube_url:
|
| 85 |
+
audio_path = _download_youtube_audio(youtube_url.strip(), td)
|
| 86 |
+
else:
|
| 87 |
+
# Save uploaded file and (optionally) convert via ffmpeg if needed
|
| 88 |
+
src = Path(td) / Path(upload_file.name).name
|
| 89 |
+
with open(src, "wb") as w:
|
| 90 |
+
w.write(upload_file.read())
|
| 91 |
+
# Let faster-whisper/ffmpeg handle decoding directly
|
| 92 |
+
audio_path = str(src)
|
| 93 |
+
|
| 94 |
+
# Transcribe
|
| 95 |
+
segments, info = _model.transcribe(
|
| 96 |
+
audio_path,
|
| 97 |
+
language=None if language == "auto" else language,
|
| 98 |
+
task="translate" if translate_to_english else "transcribe",
|
| 99 |
+
vad_filter=True
|
| 100 |
+
)
|
| 101 |
+
|
| 102 |
+
# Collect text and also write SRT
|
| 103 |
+
segs = list(segments)
|
| 104 |
+
full_text = "".join(s.text for s in segs).strip()
|
| 105 |
+
srt_path = Path(td) / "subtitles.srt"
|
| 106 |
+
_write_srt(segs, srt_path)
|
| 107 |
+
return full_text, str(srt_path)
|
| 108 |
+
|
| 109 |
+
# ---- Gradio UI ----
|
| 110 |
+
with gr.Blocks(title="YouTube → Text (Whisper)") as demo:
|
| 111 |
+
gr.Markdown("## 🎬 YouTube → 📝 Text\nPaste a YouTube link **or** upload a media file to get a transcript.")
|
| 112 |
+
with gr.Row():
|
| 113 |
+
youtube_url = gr.Textbox(label="YouTube URL", placeholder="https://www.youtube.com/watch?v=...")
|
| 114 |
+
with gr.Row():
|
| 115 |
+
upload_file = gr.File(label="Or upload a video/audio file", file_count="single")
|
| 116 |
+
with gr.Row():
|
| 117 |
+
model_size = gr.Dropdown(
|
| 118 |
+
["small", "medium", "large-v3"],
|
| 119 |
+
value=DEFAULT_MODEL,
|
| 120 |
+
label="Model size (larger = more accurate, slower)"
|
| 121 |
+
)
|
| 122 |
+
language = gr.Dropdown(
|
| 123 |
+
["auto","en","ar","fr","de","es","hi","ur","fa","ru","zh"],
|
| 124 |
+
value="auto",
|
| 125 |
+
label="Language (auto-detect or force)"
|
| 126 |
+
)
|
| 127 |
+
translate_to_english = gr.Checkbox(value=False, label="Translate to English")
|
| 128 |
+
|
| 129 |
+
run_btn = gr.Button("Transcribe", variant="primary")
|
| 130 |
+
transcript = gr.Textbox(label="Transcript", lines=12)
|
| 131 |
+
srt_file = gr.File(label="Download SRT (subtitles)")
|
| 132 |
+
|
| 133 |
+
run_btn.click(
|
| 134 |
+
transcribe,
|
| 135 |
+
inputs=[youtube_url, upload_file, model_size, language, translate_to_english],
|
| 136 |
+
outputs=[transcript, srt_file]
|
| 137 |
+
)
|
| 138 |
+
|
| 139 |
+
if __name__ == "__main__":
|
| 140 |
+
demo.launch(server_name="0.0.0.0", server_port=7860)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|