#!/usr/bin/env python3 """Конвертирует SRT в WebVTT.""" from __future__ import annotations import argparse import re import sys from pathlib import Path TIME = re.compile( r"(\d{2}):(\d{2}):(\d{2})[,.](\d{3})\s*-->\s*" r"(\d{2}):(\d{2}):(\d{2})[,.](\d{3})" ) def read_text(path: Path) -> str: data = path.read_bytes() try: return data.decode("utf-8-sig") except UnicodeDecodeError: return data.decode("cp1251", errors="replace") def convert_block(block: str) -> str | None: lines = [line.rstrip() for line in block.splitlines()] if not lines: return None index = 0 if lines[0].strip().isdigit(): index = 1 if index >= len(lines): return None match = TIME.search(lines[index]) if not match: return None parts = [int(item) for item in match.groups()] start = f"{parts[0]:02d}:{parts[1]:02d}:{parts[2]:02d}.{parts[3]:03d}" end = f"{parts[4]:02d}:{parts[5]:02d}:{parts[6]:02d}.{parts[7]:03d}" text = "\n".join(lines[index + 1:]).strip() if not text: return None return f"{start} --> {end}\n{text}" def convert(text: str) -> str: normalized = text.replace("\r\n", "\n").replace("\r", "\n").strip() blocks = re.split(r"\n\s*\n", normalized) cues = [cue for block in blocks if (cue := convert_block(block))] if not cues: raise ValueError("Не найдено ни одного корректного блока SRT") return "WEBVTT\n\n" + "\n\n".join(cues) + "\n" def main() -> int: parser = argparse.ArgumentParser(description="Конвертировать SRT в WebVTT") parser.add_argument("--input", type=Path, required=True, help="Файл или папка с SRT") parser.add_argument("--output", type=Path, help="Файл .vtt или папка для результата") parser.add_argument("--force", action="store_true", help="Перезаписать существующие файлы") args = parser.parse_args() source = args.input.expanduser().resolve() if not source.exists(): parser.error(f"Путь не найден: {source}") if source.is_file(): files = [source] else: files = sorted(source.rglob("*.srt")) if not files: print("Файлы SRT не найдены.") return 1 output = args.output.expanduser() if args.output else None if output and len(files) > 1 and output.suffix.lower() == ".vtt": parser.error("Для нескольких файлов укажите папку вывода") for path in files: try: text = convert(read_text(path)) except ValueError as error: print(f"Пропуск {path}: {error}", file=sys.stderr) continue if output is None: print(f"# {path.name}") print(text, end="") continue target = output / (path.stem + ".vtt") if output.suffix.lower() != ".vtt" else output if target.exists() and not args.force: print(f"Пропуск, файл существует: {target}", file=sys.stderr) continue target.parent.mkdir(parents=True, exist_ok=True) target.write_text(text, encoding="utf-8") print(f"Сохранено: {target}") return 0 if __name__ == "__main__": raise SystemExit(main())