Конвертировать SRT в WebVTT
Переводит обычные субтитры SRT в WebVTT с точками в таймкодах и заголовком WEBVTT.
Что делает скрипт
Скрипт разбирает блоки SRT, проверяет таймкоды и собирает корректный VTT. Кодировка определяется как UTF-8 или Windows-1251, результат пишется в UTF-8. Без --output текст выводится на экран, существующий файл требует --force.
Быстрый старт
python srt_to_vtt.py --input movie.srt --output movie.vtt
Скачайте файл, откройте терминал в папке со скриптом и выполните команду.
В Linux и macOS интерпретатор может называться python3, в Windows - python или py.
Другие варианты
python srt_to_vtt.py --input movie.srtpython srt_to_vtt.py --input movie.srt --output movie.vttpython srt_to_vtt.py --input subs/ --output out/ --force
Что понадобится
winget install Python.Python.3.12
brew install python
sudo apt install python3
srt_to_vtt.py
#!/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())
Скрипты работают с файлами и настройками системы. Перед запуском прочитайте код и проверьте пути. Особенно если скрипт удаляет, перезаписывает или перемещает данные.