anyconv-subtitle-basic 1.0.1__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,5 @@
1
+ """Basic subtitle conversion module for AnyConv."""
2
+
3
+ from .module import SubtitleModule
4
+
5
+ __all__ = ["SubtitleModule"]
@@ -0,0 +1,47 @@
1
+ spec: "^1.0"
2
+ api: ">=1.0,<2.0"
3
+ id: com.gitlab.raceozr.subtitle-basic
4
+ version: 1.0.1
5
+ title:
6
+ en: "Basic subtitles"
7
+ ru: "Базовые субтитры"
8
+ description:
9
+ en: "Convert SRT and WebVTT subtitles, with plain-text extraction."
10
+ ru: "Конвертация субтитров SRT и WebVTT, извлечение обычного текста."
11
+ license: MIT
12
+ homepage: "https://gitlab.com/anyconv/anyconv-modules"
13
+ keywords: [subtitle, srt, vtt, captions, text]
14
+ stability: stable
15
+ entrypoint:
16
+ kind: python
17
+ target: "anyconv_subtitle_basic.module:SubtitleModule"
18
+ requires:
19
+ python: ">=3.10"
20
+ packages: ["anyconv-core>=1.0,<2.0"]
21
+
22
+ capabilities:
23
+ - id: subtitle-convert
24
+ op: convert
25
+ since: 1.0.0
26
+ routing: auto
27
+ fidelity: semantic-loss
28
+ determinism: deterministic
29
+ cache: {reuse: true}
30
+ cost: {weight: 2}
31
+ limits: {timeout_s: 10, max_input_bytes: 10485760, max_outputs: 1}
32
+ inputs:
33
+ - name: source
34
+ cardinality: one
35
+ accept:
36
+ formats: [text:srt, text:vtt]
37
+ outputs:
38
+ - name: result
39
+ cardinality: one
40
+ kind: data
41
+ produce:
42
+ formats: [text:srt, text:vtt, text:plain]
43
+ settings:
44
+ type: object
45
+ additionalProperties: false
46
+ properties:
47
+ strip_tags: {type: boolean, default: false}
@@ -0,0 +1,178 @@
1
+ """SRT and WebVTT subtitle conversion for AnyConv."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from dataclasses import dataclass
7
+ from importlib.resources import files
8
+ from typing import Any
9
+
10
+ import yaml
11
+ from anyconv.sdk import Availability, CheckContext, Context, OpResult, Request
12
+ from anyconv.sdk.errors import CorruptInput, OpNotImplemented, UnsupportedType
13
+
14
+ TIME_RE = re.compile(
15
+ r"(?P<h>\d{1,3}):(?P<m>\d{2}):(?P<s>\d{2})[,.](?P<ms>\d{3})"
16
+ )
17
+ TAG_RE = re.compile(r"<[^>]+>")
18
+
19
+
20
+ @dataclass
21
+ class Cue:
22
+ start_ms: int
23
+ end_ms: int
24
+ text: str
25
+
26
+
27
+ class SubtitleModule:
28
+ @staticmethod
29
+ def manifest() -> dict[str, Any]:
30
+ return yaml.safe_load(
31
+ files("anyconv_subtitle_basic")
32
+ .joinpath("anyconv.module.yaml")
33
+ .read_text("utf-8")
34
+ )
35
+
36
+ def check(self, ctx: CheckContext) -> Availability:
37
+ return Availability(status="ready")
38
+
39
+ def convert(self, req: Request, ctx: Context) -> OpResult:
40
+ if req.capability_id != "subtitle-convert":
41
+ raise OpNotImplemented(
42
+ f"Неизвестная возможность {req.capability_id!r}",
43
+ details={"capability": req.capability_id},
44
+ )
45
+ source = req.inputs["source"][0]
46
+ source_format = source.typeref.format if source.typeref is not None else None
47
+ target = req.target.format if req.target is not None else None
48
+ if source_format not in ("text:srt", "text:vtt"):
49
+ raise UnsupportedType(
50
+ f"Формат {source_format!r} не является субтитрами",
51
+ details={"format": source_format},
52
+ )
53
+ if target not in ("text:srt", "text:vtt", "text:plain"):
54
+ raise UnsupportedType(
55
+ f"Формат {target!r} не поддерживается конвертацией субтитров",
56
+ details={"format": target},
57
+ )
58
+ text = _read_text(ctx, source)
59
+ cues = _parse_srt(text) if source_format == "text:srt" else _parse_vtt(text)
60
+ if bool(ctx.settings.get("strip_tags", False)):
61
+ cues = [
62
+ Cue(cue.start_ms, cue.end_ms, TAG_RE.sub("", cue.text)) for cue in cues
63
+ ]
64
+ output = _render(cues, target)
65
+ with ctx.out_blob("result", format=target) as writer:
66
+ writer.write(output.encode("utf-8"))
67
+ provenance = {
68
+ "source_format": source_format,
69
+ "target_format": target,
70
+ "cues": len(cues),
71
+ }
72
+ ctx.emit_provenance(provenance)
73
+ assert writer.output is not None
74
+ return OpResult(outputs={"result": writer.output}, provenance=provenance)
75
+
76
+
77
+ def _read_text(ctx: Context, source: Any) -> str:
78
+ if source.kind == "text" and isinstance(source.value, str):
79
+ return source.value
80
+ if isinstance(source.value, str):
81
+ return source.value
82
+ try:
83
+ return ctx.read_input("source").decode("utf-8-sig")
84
+ except UnicodeDecodeError as exc:
85
+ raise CorruptInput("Субтитры должны быть в UTF-8") from exc
86
+
87
+
88
+ def _parse_time(value: str) -> int:
89
+ match = TIME_RE.search(value.strip())
90
+ if not match:
91
+ raise CorruptInput(f"Некорректная временная метка: {value!r}")
92
+ return (
93
+ int(match.group("h")) * 3600000
94
+ + int(match.group("m")) * 60000
95
+ + int(match.group("s")) * 1000
96
+ + int(match.group("ms"))
97
+ )
98
+
99
+
100
+ def _parse_srt(text: str) -> list[Cue]:
101
+ cues: list[Cue] = []
102
+ blocks = re.split(r"\n\s*\n", text.replace("\r\n", "\n").strip())
103
+ for block in blocks:
104
+ lines = [line for line in block.splitlines() if line.strip()]
105
+ if not lines:
106
+ continue
107
+ timing_index = next(
108
+ (index for index, line in enumerate(lines) if "-->" in line),
109
+ None,
110
+ )
111
+ if timing_index is None:
112
+ continue
113
+ left, right = lines[timing_index].split("-->", 1)
114
+ content = "\n".join(lines[timing_index + 1 :]).strip()
115
+ if not content:
116
+ continue
117
+ cues.append(Cue(_parse_time(left), _parse_time(right), content))
118
+ if not cues:
119
+ raise CorruptInput("В SRT не найдено ни одного субтитра")
120
+ return cues
121
+
122
+
123
+ def _parse_vtt(text: str) -> list[Cue]:
124
+ lines = text.replace("\r\n", "\n").splitlines()
125
+ cues: list[Cue] = []
126
+ index = 0
127
+ while index < len(lines):
128
+ line = lines[index].strip()
129
+ if "-->" not in line:
130
+ index += 1
131
+ continue
132
+ left, right = line.split("-->", 1)
133
+ right = right.strip().split(" ", 1)[0]
134
+ index += 1
135
+ content: list[str] = []
136
+ while index < len(lines) and lines[index].strip():
137
+ content.append(lines[index].strip())
138
+ index += 1
139
+ if content:
140
+ cues.append(Cue(_parse_time(left), _parse_time(right), "\n".join(content)))
141
+ index += 1
142
+ if not cues:
143
+ raise CorruptInput("В WebVTT не найдено ни одного субтитра")
144
+ return cues
145
+
146
+
147
+ def _format_time(value: int, separator: str) -> str:
148
+ value = max(0, value)
149
+ hours, remainder = divmod(value, 3600000)
150
+ minutes, remainder = divmod(remainder, 60000)
151
+ seconds, millis = divmod(remainder, 1000)
152
+ return f"{hours:02d}:{minutes:02d}:{seconds:02d}{separator}{millis:03d}"
153
+
154
+
155
+ def _render(cues: list[Cue], target: str) -> str:
156
+ if target == "text:plain":
157
+ return "\n".join(cue.text for cue in cues) + "\n"
158
+ if target == "text:srt":
159
+ blocks = []
160
+ for index, cue in enumerate(cues, 1):
161
+ blocks.append(
162
+ f"{index}\n"
163
+ f"{_format_time(cue.start_ms, ',')} --> {_format_time(cue.end_ms, ',')}\n"
164
+ f"{cue.text}\n"
165
+ )
166
+ return "\n".join(blocks)
167
+ if target == "text:vtt":
168
+ blocks = ["WEBVTT\n"]
169
+ for cue in cues:
170
+ blocks.append(
171
+ f"{_format_time(cue.start_ms, '.')} --> {_format_time(cue.end_ms, '.')}\n"
172
+ f"{cue.text}\n"
173
+ )
174
+ return "\n".join(blocks)
175
+ raise UnsupportedType(f"Неизвестный формат субтитров {target!r}")
176
+
177
+
178
+ __all__ = ["SubtitleModule"]
@@ -0,0 +1,37 @@
1
+ Metadata-Version: 2.4
2
+ Name: anyconv-subtitle-basic
3
+ Version: 1.0.1
4
+ Summary: AnyConv basic SRT and WebVTT subtitle conversion module
5
+ Author: AnyConv
6
+ License-Expression: MIT
7
+ Keywords: anyconv,srt,vtt,subtitles,captions
8
+ Requires-Python: >=3.10
9
+ Description-Content-Type: text/markdown
10
+ License-File: LICENSE
11
+ Requires-Dist: anyconv-core<2.0,>=1.0
12
+ Provides-Extra: dev
13
+ Requires-Dist: pytest>=7; extra == "dev"
14
+ Requires-Dist: ruff>=0.5; extra == "dev"
15
+ Dynamic: license-file
16
+
17
+ # anyconv-subtitle-basic
18
+
19
+ Конвертация субтитров SRT и WebVTT.
20
+
21
+ ## Возможности
22
+
23
+ - **`subtitle-convert`** — SRT/VTT → SRT/VTT/plain text.
24
+ - `strip_tags` удаляет теги разметки из текста субтитров.
25
+
26
+ ## Установка
27
+
28
+ ```bash
29
+ pip install "anyconv-core[all] @ git+https://gitlab.com/anyconv/anyconv-core.git@v1.0.1"
30
+ pip install "git+https://gitlab.com/anyconv/anyconv-modules.git@v1.0.1#subdirectory=modules/subtitle-basic"
31
+ # ?????????? ?? checkout anyconv-modules
32
+ cd modules/subtitle-basic
33
+ pip install -e ".[dev]"
34
+ pytest
35
+ anyconv module validate .
36
+ anyconv module test .
37
+ ```
@@ -0,0 +1,9 @@
1
+ anyconv_subtitle_basic/__init__.py,sha256=eeCma5pV26DUZVg1DaYLpgDnDF3c6TsM86MBcGwlVfY,118
2
+ anyconv_subtitle_basic/anyconv.module.yaml,sha256=1ZkHP9sA4eagGC1HPTj_cr5LlmiDr72NoBHOgD-ayYo,1306
3
+ anyconv_subtitle_basic/module.py,sha256=O-nvW5w1B8SaqU_CoL3z11baJIcPX182_zBGXB5okN0,6272
4
+ anyconv_subtitle_basic-1.0.1.dist-info/licenses/LICENSE,sha256=Wahb1xasoYXZBxdcuh2ETI6eaWi4JazPi9yhb0eFBxU,1077
5
+ anyconv_subtitle_basic-1.0.1.dist-info/METADATA,sha256=2fR1VgpAaB6MdCbeqLVm7Cwi58T6cPHNA8DfQUo1vV8,1110
6
+ anyconv_subtitle_basic-1.0.1.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
7
+ anyconv_subtitle_basic-1.0.1.dist-info/entry_points.txt,sha256=a4CRTrLgB46OV7HmdO3Odhlu8bEAnE4dNW416EfqL5o,80
8
+ anyconv_subtitle_basic-1.0.1.dist-info/top_level.txt,sha256=-bNa4qjjZ__d-QyNNCgJ104jgCmgvasBeKtiBr5Y5yA,23
9
+ anyconv_subtitle_basic-1.0.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [anyconv.modules]
2
+ subtitle_basic = anyconv_subtitle_basic.module:SubtitleModule
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 AnyConv contributors
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
+ anyconv_subtitle_basic