#!/usr/bin/env python3 """Кадрирование видео под заданное соотношение сторон.""" from __future__ import annotations import argparse import json import shutil import subprocess from pathlib import Path def parse_aspect(value: str) -> tuple[int, int]: parts = value.split(":") if len(parts) != 2 or not all(part.isdigit() for part in parts): raise argparse.ArgumentTypeError("Формат должен быть таким: 16:9") width, height = int(parts[0]), int(parts[1]) if width <= 0 or height <= 0: raise argparse.ArgumentTypeError("Стороны должны быть положительными") return width, height def probe_size(path: Path) -> tuple[int, int]: result = subprocess.run( [ "ffprobe", "-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height", "-of", "json", str(path), ], capture_output=True, text=True, check=False, ) if result.returncode != 0: raise SystemExit(f"ffprobe не смог прочитать {path}:\n{result.stderr.strip()}") streams = json.loads(result.stdout).get("streams", []) if not streams: raise SystemExit("В файле нет видеопотока") return int(streams[0]["width"]), int(streams[0]["height"]) def main() -> int: parser = argparse.ArgumentParser(description="Кадрировать видео под формат") parser.add_argument("input", type=Path) parser.add_argument("--aspect", type=parse_aspect, default=(16, 9)) parser.add_argument("--output-dir", type=Path, default=Path("cropped")) parser.add_argument("--crf", type=int, default=20) 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}") width, height = probe_size(source) aw, ah = args.aspect target_ratio = aw / ah source_ratio = width / height if source_ratio > target_ratio: crop_h = height crop_w = int(height * target_ratio) else: crop_w = width crop_h = int(width / target_ratio) crop_w -= crop_w % 2 crop_h -= crop_h % 2 if crop_w <= 0 or crop_h <= 0: parser.error("Не удалось вычислить область кадрирования") x = (width - crop_w) // 2 y = (height - crop_h) // 2 args.output_dir.mkdir(parents=True, exist_ok=True) target = args.output_dir / f"{source.stem}_crop_{aw}x{ah}.mp4" if target.exists() and not args.overwrite: raise SystemExit(f"Файл уже существует: {target}. Добавьте --overwrite.") command = [ "ffmpeg", "-hide_banner", "-nostdin", "-i", str(source), "-vf", f"crop={crop_w}:{crop_h}:{x}:{y}", "-c:v", "libx264", "-preset", "medium", "-crf", str(args.crf), "-pix_fmt", "yuv420p", "-c:a", "aac", "-b:a", "192k", "-movflags", "+faststart", "-n", str(target), ] print(f"Кадр {width}x{height} -> {crop_w}x{crop_h}, смещение {x}:{y}") 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())