#!/usr/bin/env python3 """Извлечение встроенных субтитров.""" from __future__ import annotations import argparse import json import shutil import subprocess from pathlib import Path CODECS = {"srt": "srt", "vtt": "webvtt", "ass": "ass"} def subtitle_streams(path: Path) -> list[dict]: result = subprocess.run( [ "ffprobe", "-v", "error", "-select_streams", "s", "-show_entries", "stream=index,codec_name:stream_tags=language,title", "-of", "json", str(path), ], capture_output=True, text=True, check=False, ) if result.returncode != 0: raise SystemExit(f"ffprobe не смог прочитать {path}:\n{result.stderr.strip()}") return json.loads(result.stdout).get("streams", []) def main() -> int: parser = argparse.ArgumentParser(description="Извлечь субтитры из видео") parser.add_argument("input", type=Path) parser.add_argument("--stream", type=int, default=0, help="Номер дорожки субтитров") parser.add_argument("--format", choices=tuple(CODECS), default="srt") parser.add_argument("--output-dir", type=Path, default=Path("subtitles")) parser.add_argument("--overwrite", action="store_true") args = parser.parse_args() if shutil.which("ffmpeg") is None: raise SystemExit("Не найден ffmpeg. Установите FFmpeg.") source = args.input.expanduser() if not source.is_file(): parser.error(f"Файл не найден: {source}") streams = subtitle_streams(source) if not streams: raise SystemExit("В файле нет дорожек субтитров") print("Доступные дорожки:") for position, stream in enumerate(streams): tags = stream.get("tags", {}) print( f" {position}: index={stream.get('index')} " f"codec={stream.get('codec_name')} " f"language={tags.get('language', '?')} title={tags.get('title', '?')}" ) if not 0 <= args.stream < len(streams): parser.error(f"Номер дорожки должен быть от 0 до {len(streams) - 1}") args.output_dir.mkdir(parents=True, exist_ok=True) target = args.output_dir / f"{source.stem}.{args.format}" if target.exists() and not args.overwrite: raise SystemExit(f"Файл уже существует: {target}. Добавьте --overwrite.") command = [ "ffmpeg", "-hide_banner", "-nostdin", "-i", str(source), "-map", f"0:s:{args.stream}", "-c:s", CODECS[args.format], "-y" if args.overwrite else "-n", str(target), ] result = subprocess.run(command, check=False) if result.returncode != 0: raise SystemExit(f"ffmpeg завершился с кодом {result.returncode}") print(f"Готово: {target}") return 0 if __name__ == "__main__": raise SystemExit(main())