subtitry 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: subtitry
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Субтитры SRT и WebVTT: конвертация, текст без таймкодов и проверка тайминга
|
|
5
|
+
Author: Андрей Петров
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Documentation, https://subtitry-srt-vtt.readthedocs.io/ru/latest/
|
|
8
|
+
Project-URL: Source, https://codeberg.org/apetrov/subtitry-srt-vtt
|
|
9
|
+
Project-URL: Issues, https://codeberg.org/apetrov/subtitry-srt-vtt/issues
|
|
10
|
+
Keywords: subtitles,srt,vtt,webvtt,субтитры,converter,timing
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Environment :: Console
|
|
13
|
+
Classifier: Intended Audience :: End Users/Desktop
|
|
14
|
+
Classifier: Natural Language :: Russian
|
|
15
|
+
Classifier: Operating System :: OS Independent
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
18
|
+
Classifier: Topic :: Multimedia :: Video
|
|
19
|
+
Classifier: Topic :: Text Processing
|
|
20
|
+
Requires-Python: >=3.8
|
|
21
|
+
Description-Content-Type: text/markdown
|
|
22
|
+
License-File: LICENSE
|
|
23
|
+
Dynamic: license-file
|
|
24
|
+
|
|
25
|
+
# subtitry
|
|
26
|
+
|
|
27
|
+
subtitry — утилита командной строки для субтитров SRT и WebVTT. Она переводит файл из одного формата в другой, достаёт из субтитров чистый текст и проверяет тайминг. Пороги проверки по умолчанию взяты из руководства Netflix по русским субтитрам. Утилита написана на Python и обходится без сторонних зависимостей.
|
|
28
|
+
|
|
29
|
+
Справочник по форматам и правилам тайминга: [subtitry-srt-vtt.readthedocs.io](https://subtitry-srt-vtt.readthedocs.io/ru/latest/).
|
|
30
|
+
|
|
31
|
+
## Установка
|
|
32
|
+
|
|
33
|
+
```bash
|
|
34
|
+
pip install subtitry
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
Пакет ставит команду `subtitry`. Нужен Python 3.8 или новее. Весь код лежит в одном модуле `subtitry.py`. Его можно скопировать в свой проект и запускать как `python subtitry.py`.
|
|
38
|
+
|
|
39
|
+
## Конвертация
|
|
40
|
+
|
|
41
|
+
```bash
|
|
42
|
+
subtitry convert lekciya.srt lekciya.vtt
|
|
43
|
+
subtitry convert lekciya.vtt lekciya.srt
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
Формат результата subtitry определяет по расширению выходного файла. При записи в SRT нумерация титров начинается заново. При записи в VTT сохраняются идентификаторы и настройки титров. Входной файл может быть в UTF-8 или в Windows-1251, результат всегда пишется в UTF-8.
|
|
47
|
+
|
|
48
|
+
## Текст без таймкодов
|
|
49
|
+
|
|
50
|
+
```bash
|
|
51
|
+
subtitry text intervyu.srt intervyu.txt
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
Команда выбрасывает номера, таймкоды и теги, а реплики склеивает в один абзац. Из такого текста удобно брать цитаты для статьи или конспекта. Запись без субтитров этой командой не обработать. Для неё нужна [транскрибация видео в текст](https://audiovtext.com/video-v-tekst/): программа распознаёт речь и сразу отдаёт готовый текст.
|
|
55
|
+
|
|
56
|
+
## Проверка тайминга
|
|
57
|
+
|
|
58
|
+
```bash
|
|
59
|
+
subtitry check film.srt --fps 24
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
```text
|
|
63
|
+
#14 00:01:12,300: 19,4 знака в секунду, предел 17
|
|
64
|
+
#15 00:01:15,000: зазор 0,040 с меньше двух кадров
|
|
65
|
+
#31 00:02:40,100: строка 51 знак, предел 42
|
|
66
|
+
титров: 212, замечаний: 3
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
Что проверяет `subtitry check`:
|
|
70
|
+
|
|
71
|
+
- титр держится на экране от 5/6 секунды до 7 секунд;
|
|
72
|
+
- в титре не больше двух строк;
|
|
73
|
+
- строка не длиннее 42 знаков (ключ `--chars`);
|
|
74
|
+
- скорость чтения не выше 17 знаков в секунду без учёта пробелов (ключ `--cps`);
|
|
75
|
+
- титры не наезжают друг на друга, а зазор между ними не короче двух кадров (ключ `--fps`, по умолчанию 25).
|
|
76
|
+
|
|
77
|
+
Если замечаний нет, команда завершается с кодом 0. Если есть, код будет 1. Проверку можно поставить в скрипт сборки или в CI.
|
|
78
|
+
|
|
79
|
+
## Вызов из Python
|
|
80
|
+
|
|
81
|
+
```python
|
|
82
|
+
from pathlib import Path
|
|
83
|
+
from subtitry import check, parse, read_text, to_vtt
|
|
84
|
+
|
|
85
|
+
cues = parse(read_text(Path("lekciya.srt")))
|
|
86
|
+
Path("lekciya.vtt").write_text(to_vtt(cues), encoding="utf-8")
|
|
87
|
+
for problem in check(cues, fps=25, max_cps=17, max_chars=42):
|
|
88
|
+
print(problem)
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
## Где взять субтитры
|
|
92
|
+
|
|
93
|
+
Субтитры к своей записи проще всего получить распознаванием речи. Например, [AudioVText](https://audiovtext.com/) расшифровывает аудио и видео на 99 языках. Русский язык для AudioVText основной. Готовые субтитры скачиваются оттуда файлом SRT или VTT. Перед публикацией такой файл стоит прогнать через `subtitry check`: команда найдёт титры, которые зритель не успеет прочитать.
|
|
94
|
+
|
|
95
|
+
## Лицензия
|
|
96
|
+
|
|
97
|
+
MIT. Текст лицензии лежит в файле `LICENSE`.
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
subtitry.py,sha256=UppC25EYvCJsQVXWSOZ7lWypatH3y_6hLDzcLOIiHa8,7171
|
|
2
|
+
subtitry-0.1.0.dist-info/licenses/LICENSE,sha256=WY5TZvCpnGPNwY9e7txa8FMwZ0zdsMYNUcyW3FXGNbo,1082
|
|
3
|
+
subtitry-0.1.0.dist-info/METADATA,sha256=q981hBWoHzTLimHBEnbR9Rg47Fy0hl24CxuHSESiikY,5674
|
|
4
|
+
subtitry-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
5
|
+
subtitry-0.1.0.dist-info/entry_points.txt,sha256=Zs3tdGOIucsX94gS2fR03-duKCPaYSIj1_B9Zb0-NKo,43
|
|
6
|
+
subtitry-0.1.0.dist-info/top_level.txt,sha256=zkEAsmtrnbaWSTSv4s0zURLRPXD6yUw_bwKnTB01l-g,9
|
|
7
|
+
subtitry-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Андрей Петров
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
subtitry
|
subtitry.py
ADDED
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
"""subtitry — конвертация и проверка субтитров SRT и WebVTT.
|
|
2
|
+
|
|
3
|
+
python subtitry.py convert in.srt out.vtt
|
|
4
|
+
python subtitry.py convert in.vtt out.srt
|
|
5
|
+
python subtitry.py text in.srt out.txt
|
|
6
|
+
python subtitry.py check in.srt [--fps 25] [--cps 17] [--chars 42]
|
|
7
|
+
|
|
8
|
+
Без внешних зависимостей, Python 3.8+.
|
|
9
|
+
"""
|
|
10
|
+
import argparse
|
|
11
|
+
import re
|
|
12
|
+
import sys
|
|
13
|
+
from dataclasses import dataclass
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from typing import List, Optional
|
|
16
|
+
|
|
17
|
+
ARROW = re.compile(
|
|
18
|
+
r"^\s*((?:\d+:)?\d{1,2}:\d{2}[,.]\d{3})\s*-->\s*((?:\d+:)?\d{1,2}:\d{2}[,.]\d{3})(.*)$"
|
|
19
|
+
)
|
|
20
|
+
TAG = re.compile(r"<[^>]+>|\{\\[^}]*\}")
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass
|
|
24
|
+
class Cue:
|
|
25
|
+
start: float
|
|
26
|
+
end: float
|
|
27
|
+
lines: List[str]
|
|
28
|
+
ident: Optional[str] = None
|
|
29
|
+
settings: str = ""
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def parse_time(value: str) -> float:
|
|
33
|
+
value = value.replace(",", ".")
|
|
34
|
+
parts = value.split(":")
|
|
35
|
+
seconds = float(parts[-1])
|
|
36
|
+
minutes = int(parts[-2])
|
|
37
|
+
hours = int(parts[-3]) if len(parts) == 3 else 0
|
|
38
|
+
return hours * 3600 + minutes * 60 + seconds
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def format_time(seconds: float, sep: str) -> str:
|
|
42
|
+
ms = int(round(seconds * 1000))
|
|
43
|
+
h, ms = divmod(ms, 3_600_000)
|
|
44
|
+
m, ms = divmod(ms, 60_000)
|
|
45
|
+
s, ms = divmod(ms, 1000)
|
|
46
|
+
return f"{h:02d}:{m:02d}:{s:02d}{sep}{ms:03d}"
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def plural(n: int, one: str, few: str, many: str) -> str:
|
|
50
|
+
if n % 10 == 1 and n % 100 != 11:
|
|
51
|
+
return one
|
|
52
|
+
if 2 <= n % 10 <= 4 and not 12 <= n % 100 <= 14:
|
|
53
|
+
return few
|
|
54
|
+
return many
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def num(value: float, digits: int = 2) -> str:
|
|
58
|
+
return f"{value:.{digits}f}".replace(".", ",")
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def read_text(path: Path) -> str:
|
|
62
|
+
raw = path.read_bytes()
|
|
63
|
+
try:
|
|
64
|
+
text = raw.decode("utf-8-sig")
|
|
65
|
+
except UnicodeDecodeError:
|
|
66
|
+
text = raw.decode("cp1251")
|
|
67
|
+
print(f"{path}: файл не в UTF-8, прочитан как cp1251", file=sys.stderr)
|
|
68
|
+
return text.replace("\r\n", "\n").replace("\r", "\n")
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def parse(text: str) -> List[Cue]:
|
|
72
|
+
cues: List[Cue] = []
|
|
73
|
+
blocks = re.split(r"\n\s*\n", text.strip())
|
|
74
|
+
for block in blocks:
|
|
75
|
+
rows = block.split("\n")
|
|
76
|
+
if rows[0].startswith(("WEBVTT", "NOTE", "STYLE", "REGION")):
|
|
77
|
+
continue
|
|
78
|
+
for i, row in enumerate(rows):
|
|
79
|
+
match = ARROW.match(row)
|
|
80
|
+
if not match:
|
|
81
|
+
continue
|
|
82
|
+
ident = rows[i - 1].strip() if i > 0 else None
|
|
83
|
+
cues.append(
|
|
84
|
+
Cue(
|
|
85
|
+
start=parse_time(match.group(1)),
|
|
86
|
+
end=parse_time(match.group(2)),
|
|
87
|
+
lines=[r for r in rows[i + 1:] if r.strip()],
|
|
88
|
+
ident=ident,
|
|
89
|
+
settings=match.group(3).strip(),
|
|
90
|
+
)
|
|
91
|
+
)
|
|
92
|
+
break
|
|
93
|
+
return cues
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def to_srt(cues: List[Cue]) -> str:
|
|
97
|
+
out = []
|
|
98
|
+
for n, cue in enumerate(cues, 1):
|
|
99
|
+
times = f"{format_time(cue.start, ',')} --> {format_time(cue.end, ',')}"
|
|
100
|
+
out.append("\n".join([str(n), times, *cue.lines]))
|
|
101
|
+
return "\n\n".join(out) + "\n"
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def to_vtt(cues: List[Cue]) -> str:
|
|
105
|
+
out = ["WEBVTT"]
|
|
106
|
+
for cue in cues:
|
|
107
|
+
times = f"{format_time(cue.start, '.')} --> {format_time(cue.end, '.')}"
|
|
108
|
+
if cue.settings:
|
|
109
|
+
times += " " + cue.settings
|
|
110
|
+
head = [cue.ident] if cue.ident and "-->" not in cue.ident else []
|
|
111
|
+
out.append("\n".join([*head, times, *cue.lines]))
|
|
112
|
+
return "\n\n".join(out) + "\n"
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def to_text(cues: List[Cue]) -> str:
|
|
116
|
+
words = []
|
|
117
|
+
for cue in cues:
|
|
118
|
+
for line in cue.lines:
|
|
119
|
+
clean = TAG.sub("", line).strip()
|
|
120
|
+
if clean:
|
|
121
|
+
words.append(clean)
|
|
122
|
+
return " ".join(words) + "\n"
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def check(cues: List[Cue], fps: float, max_cps: float, max_chars: int) -> List[str]:
|
|
126
|
+
problems = []
|
|
127
|
+
min_dur = 20 / 24
|
|
128
|
+
min_gap = 2 / fps
|
|
129
|
+
for n, cue in enumerate(cues, 1):
|
|
130
|
+
dur = cue.end - cue.start
|
|
131
|
+
text = TAG.sub("", " ".join(cue.lines))
|
|
132
|
+
where = f"#{n} {format_time(cue.start, ',')}"
|
|
133
|
+
if dur <= 0:
|
|
134
|
+
problems.append(f"{where}: конец раньше начала")
|
|
135
|
+
continue
|
|
136
|
+
if dur < min_dur:
|
|
137
|
+
problems.append(f"{where}: титр короче 5/6 секунды ({num(dur)} с)")
|
|
138
|
+
if dur > 7:
|
|
139
|
+
problems.append(f"{where}: титр дольше 7 секунд ({num(dur)} с)")
|
|
140
|
+
if len(cue.lines) > 2:
|
|
141
|
+
problems.append(f"{where}: больше двух строк ({len(cue.lines)})")
|
|
142
|
+
for line in cue.lines:
|
|
143
|
+
length = len(TAG.sub("", line))
|
|
144
|
+
if length > max_chars:
|
|
145
|
+
problems.append(f"{where}: строка {length} {plural(length, 'знак', 'знака', 'знаков')}, предел {max_chars}")
|
|
146
|
+
cps = len(text.replace(" ", "")) / dur
|
|
147
|
+
if cps > max_cps:
|
|
148
|
+
problems.append(f"{where}: {num(cps, 1)} знака в секунду, предел {max_cps:g}")
|
|
149
|
+
if n < len(cues):
|
|
150
|
+
gap = cues[n].start - cue.end
|
|
151
|
+
if gap < 0:
|
|
152
|
+
problems.append(f"{where}: наезжает на следующий титр на {num(-gap, 3)} с")
|
|
153
|
+
elif 0 < gap < min_gap:
|
|
154
|
+
problems.append(f"{where}: зазор {num(gap, 3)} с меньше двух кадров")
|
|
155
|
+
return problems
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def main(argv: Optional[List[str]] = None) -> int:
|
|
159
|
+
parser = argparse.ArgumentParser(prog="subtitry", description="SRT и WebVTT: конвертация и проверка")
|
|
160
|
+
sub = parser.add_subparsers(dest="cmd", required=True)
|
|
161
|
+
conv = sub.add_parser("convert", help="SRT ↔ VTT, формат по расширению выходного файла")
|
|
162
|
+
conv.add_argument("src", type=Path)
|
|
163
|
+
conv.add_argument("dst", type=Path)
|
|
164
|
+
txt = sub.add_parser("text", help="только текст, без номеров и таймкодов")
|
|
165
|
+
txt.add_argument("src", type=Path)
|
|
166
|
+
txt.add_argument("dst", type=Path)
|
|
167
|
+
chk = sub.add_parser("check", help="длительность, скорость чтения, длина строк, наезды")
|
|
168
|
+
chk.add_argument("src", type=Path)
|
|
169
|
+
chk.add_argument("--fps", type=float, default=25)
|
|
170
|
+
chk.add_argument("--cps", type=float, default=17)
|
|
171
|
+
chk.add_argument("--chars", type=int, default=42)
|
|
172
|
+
args = parser.parse_args(argv)
|
|
173
|
+
|
|
174
|
+
cues = parse(read_text(args.src))
|
|
175
|
+
if not cues:
|
|
176
|
+
print(f"{args.src}: титров не найдено", file=sys.stderr)
|
|
177
|
+
return 1
|
|
178
|
+
if args.cmd == "convert":
|
|
179
|
+
body = to_vtt(cues) if args.dst.suffix.lower() == ".vtt" else to_srt(cues)
|
|
180
|
+
args.dst.write_text(body, encoding="utf-8")
|
|
181
|
+
elif args.cmd == "text":
|
|
182
|
+
args.dst.write_text(to_text(cues), encoding="utf-8")
|
|
183
|
+
else:
|
|
184
|
+
problems = check(cues, args.fps, args.cps, args.chars)
|
|
185
|
+
for p in problems:
|
|
186
|
+
print(p)
|
|
187
|
+
print(f"титров: {len(cues)}, замечаний: {len(problems)}")
|
|
188
|
+
return 1 if problems else 0
|
|
189
|
+
return 0
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
if __name__ == "__main__":
|
|
193
|
+
sys.exit(main())
|