یک اسکریپت پایتون آماده که از لینک یوتیوب صدا را میگیرد، با Whisper زیرنویس فارسی میسازد، تایمبندیها را بر اساس سرعت مطالعه اصلاح میکند و فایل SRT/VTT و ویدیوی سابتیتلدار تحویل میدهد.
You are a senior Python engineer specialized in media automation, speech recognition and ffmpeg pipelines. Write production-ready code, not pseudocode.
GOAL
Build a single-file CLI tool named persian_subtitle.py that turns a YouTube URL (or a local media file) into broadcast-quality Persian subtitles, an optional English translation track, and a subtitled video.
TECH STACK
- Python 3.10+, type hints and dataclasses, argparse, pathlib, logging
- yt-dlp for audio extraction, ffmpeg for audio conversion and burning subtitles
- faster-whisper (large-v3, compute_type int8 on CPU / float16 on CUDA, vad_filter=True) with a JSON transcript cache
- optional translation step behind an injected callable so the tool works with any MT provider (key read from environment variable, never hardcoded)
FUNCTIONAL REQUIREMENTS
1. Input handling: accept a URL or local path, a --lang-source (default fa) and --lang-target (default en) pair, --model-size, --device, --output-dir and --burn-in flags.
2. Pipeline: download bestaudio with yt-dlp, convert to 16 kHz mono WAV via ffmpeg, run whisper with word_timestamps=True, cache raw segments to transcript.json and reuse on re-run.
3. Subtitle segmentation engine (the most important part): build cues from word timings using these rules — max 2 lines per cue, max 42 characters per line, reading speed <= 17 characters/second, minimum duration 1.2 s, maximum duration 7 s, minimum 80 ms gap between cues, no overlapping timestamps, split on Persian and English sentence/clause punctuation, merge very short fragments with neighbours, never break inside a number, Latin brand name or URL.
4. Persian text normalization: convert Arabic ي/ك/ة to Persian ی/ک/ه, normalize Arabic-Indic digits to Persian digits, collapse repeated spaces, trim filler words from a configurable list, and fix punctuation spacing so no space appears before ، ؛ ؟.
5. Output: write SRT and WebVTT in UTF-8 with BOM for legacy players, a bilingual mode that places English under Persian in the same cue, and a plain TXT transcript. Provide a summary report (cue count, average CPS, longest cue, total duration).
6. Burn-in: ffmpeg subprocess with the subtitles/ass filter, using an .ass override style with a Persian font (Vazirmatn), font size, primary/outline colour, outline and shadow width, bottom margin and alignment; make the style configurable and skip gracefully if the font is missing.
7. Engineering quality: ffmpeg/whisper availability checks with clear error messages, retry with exponential backoff on download failures, --dry-run mode, progress logging with percentages, clean temp-file cleanup, memory-safe batching for long videos, and a downloadable-content rights warning in the docstring.
CONSTRAINTS
- No global state, no hardcoded API keys or absolute paths, no shell=True.
- Each segmentation function must be pure and unit-testable.
- Explain every non-obvious constant in comments in one short line.
- Keep the total file readable: modular functions, not one giant main().
OUTPUT FORMAT (in this order)
1. A short architecture note (max 150 words) explaining the data flow.
2. The complete code in one python block.
3. A requirements.txt block.
4. A usage section with 4 copy-paste commands: quick start, CUDA model, bilingual output, burn-in subtitles.
5. A flag reference table (flag, default, description).
6. A troubleshooting list for: ffmpeg not found, CUDA out of memory, whisper hallucinating repeated text in silent parts, and Persian glyphs rendering as boxes in the burned video.