Upload 2 files
Browse files- app.py +51 -0
- requirements.txt +5 -0
app.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import ffmpeg
|
| 3 |
+
import io
|
| 4 |
+
import tempfile
|
| 5 |
+
import srt
|
| 6 |
+
import datetime
|
| 7 |
+
from transformers import WhisperForConditionalGeneration, WhisperProcessor, pipeline, MT5ForConditionalGeneration, MT5Tokenizer
|
| 8 |
+
|
| 9 |
+
# مدلها
|
| 10 |
+
asr_model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-base.en")
|
| 11 |
+
asr_processor = WhisperProcessor.from_pretrained("openai/whisper-base.en")
|
| 12 |
+
translator = pipeline("text2text-generation", model="persiannlp/mt5-small-parsinlu-translation_en_fa", tokenizer="persiannlp/mt5-small-parsinlu-translation_en_fa")
|
| 13 |
+
|
| 14 |
+
def process(video):
|
| 15 |
+
# استخراج فایل صوتی
|
| 16 |
+
ytmp = tempfile.NamedTemporaryFile(suffix=".wav", delete=False)
|
| 17 |
+
(
|
| 18 |
+
ffmpeg
|
| 19 |
+
.input(video)
|
| 20 |
+
.output(ytmp.name, format="wav", ac=1, ar="16000")
|
| 21 |
+
.run(quiet=True, overwrite_output=True)
|
| 22 |
+
)
|
| 23 |
+
# ASR
|
| 24 |
+
input_feat = asr_processor(ytmp.name, return_tensors="pt", sampling_rate=16000)
|
| 25 |
+
out = asr_model.generate(**input_feat)
|
| 26 |
+
segments = asr_processor.batch_decode(out, skip_special_tokens=True) # متن کامل
|
| 27 |
+
|
| 28 |
+
# برای زمانبندی دستی، تقسیم به جملات
|
| 29 |
+
subs = []
|
| 30 |
+
text = segments[0]
|
| 31 |
+
lines = [l for l in text.split('.') if l.strip()]
|
| 32 |
+
for i, line in enumerate(lines):
|
| 33 |
+
start = datetime.timedelta(seconds=i*5)
|
| 34 |
+
end = datetime.timedelta(seconds=(i+1)*5)
|
| 35 |
+
# ترجمه
|
| 36 |
+
tr = translator(line.strip(), max_length=128)[0]['generated_text']
|
| 37 |
+
subs.append(srt.Subtitle(index=i+1, start=start, end=end, content=tr))
|
| 38 |
+
|
| 39 |
+
srt_data = srt.compose(subs)
|
| 40 |
+
return video, srt_data
|
| 41 |
+
|
| 42 |
+
demo = gr.Interface(
|
| 43 |
+
fn=process,
|
| 44 |
+
inputs=gr.Video(source="upload", format="mp4"),
|
| 45 |
+
outputs=[gr.Video(), gr.Textbox(label="Subtitles (SRT)")],
|
| 46 |
+
title="Offline English→Persian Subtitle Maker",
|
| 47 |
+
description="ویدیو را آپلود کنید؛ زیرنویس فارسی تولید میشود."
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
if __name__ == "__main__":
|
| 51 |
+
demo.launch()
|
requirements.txt
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
transformers
|
| 2 |
+
gradio
|
| 3 |
+
ffmpeg-python
|
| 4 |
+
srt
|
| 5 |
+
torch
|