anyconv-speech-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 whisper.cpp speech module for AnyConv."""
2
+
3
+ from .module import SpeechModule
4
+
5
+ __all__ = ["SpeechModule"]
@@ -0,0 +1,70 @@
1
+ spec: "^1.0"
2
+ api: ">=1.0,<2.0"
3
+ id: com.gitlab.raceozr.speech-basic
4
+ version: 1.0.1
5
+ title:
6
+ en: "Basic speech"
7
+ ru: "Базовая расшифровка речи"
8
+ description:
9
+ en: "Transcribe audio and video to text or subtitles with whisper.cpp."
10
+ ru: "Расшифровка аудио и видео в текст или субтитры через whisper.cpp."
11
+ license: MIT
12
+ homepage: "https://gitlab.com/raceozr/anyconv-modules"
13
+ keywords: [speech, whisper, transcript, subtitles, srt, vtt]
14
+ stability: stable
15
+ entrypoint:
16
+ kind: python
17
+ target: "anyconv_speech_basic.module:SpeechModule"
18
+ config:
19
+ schema:
20
+ type: object
21
+ additionalProperties: false
22
+ properties:
23
+ whisper_path: {type: string}
24
+ model_path: {type: string}
25
+ ffmpeg_path: {type: string}
26
+ threads: {type: integer, minimum: 1, maximum: 32}
27
+ requires:
28
+ python: ">=3.10"
29
+ packages: ["anyconv-core>=1.0,<2.0"]
30
+
31
+ capabilities:
32
+ - id: speech-transcribe
33
+ op: convert
34
+ since: 1.0.0
35
+ routing: auto
36
+ fidelity: lossy
37
+ determinism: stochastic
38
+ cache: {reuse: false}
39
+ cost: {weight: 60}
40
+ limits: {timeout_s: 1800, max_input_bytes: 2147483648, max_outputs: 1}
41
+ inputs:
42
+ - name: source
43
+ cardinality: one
44
+ accept:
45
+ formats:
46
+ - audio:wav
47
+ - audio:mp3
48
+ - audio:flac
49
+ - audio:ogg
50
+ - audio:opus
51
+ - audio:m4a
52
+ - audio:aac
53
+ - audio:aiff
54
+ - video:mp4
55
+ - video:webm
56
+ - video:mkv
57
+ - video:mov
58
+ - video:avi
59
+ outputs:
60
+ - name: result
61
+ cardinality: one
62
+ kind: data
63
+ produce:
64
+ formats: [text:plain, text:srt, text:vtt]
65
+ settings:
66
+ type: object
67
+ additionalProperties: false
68
+ properties:
69
+ language: {enum: [auto, ru, en], default: auto}
70
+ translate: {type: boolean, default: false}
@@ -0,0 +1,264 @@
1
+ """Speech-to-text through the whisper.cpp CLI."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import shutil
8
+ import subprocess
9
+ from importlib.resources import files
10
+ from pathlib import Path
11
+ from typing import Any
12
+
13
+ import yaml
14
+ from anyconv.sdk import Availability, CheckContext, Context, OpResult, Request
15
+ from anyconv.sdk.errors import CorruptInput, ModuleUnavailable, OpNotImplemented, UnsupportedType
16
+
17
+
18
+ class SpeechModule:
19
+ @staticmethod
20
+ def manifest() -> dict[str, Any]:
21
+ return yaml.safe_load(
22
+ files("anyconv_speech_basic")
23
+ .joinpath("anyconv.module.yaml")
24
+ .read_text("utf-8")
25
+ )
26
+
27
+ def check(self, ctx: CheckContext) -> Availability:
28
+ missing: list[str] = []
29
+ if _find_whisper(ctx.config) is None:
30
+ missing.append("binary:whisper-cli")
31
+ if _find_model(ctx.config) is None:
32
+ missing.append("model:ggml-tiny.bin")
33
+ if _find_ffmpeg(ctx.config) is None:
34
+ missing.append("binary:ffmpeg")
35
+ return Availability(
36
+ status="unavailable" if missing else "ready",
37
+ missing=missing,
38
+ )
39
+
40
+ def convert(self, req: Request, ctx: Context) -> OpResult:
41
+ if req.capability_id != "speech-transcribe":
42
+ raise OpNotImplemented(
43
+ f"Неизвестная возможность {req.capability_id!r}",
44
+ details={"capability": req.capability_id},
45
+ )
46
+ target = req.target.format if req.target is not None else None
47
+ if target not in ("text:plain", "text:srt", "text:vtt"):
48
+ raise UnsupportedType(
49
+ f"Формат {target!r} не поддерживается расшифровкой",
50
+ details={"format": target},
51
+ )
52
+ whisper = _find_whisper(ctx.config)
53
+ model = _find_model(ctx.config)
54
+ ffmpeg = _find_ffmpeg(ctx.config)
55
+ if whisper is None or model is None:
56
+ raise ModuleUnavailable(
57
+ "whisper.cpp или модель не найдены",
58
+ details={"whisper": whisper, "model": model},
59
+ )
60
+ if ffmpeg is None:
61
+ raise ModuleUnavailable("FFmpeg не найден")
62
+ source = req.inputs["source"][0]
63
+ source_path = _source_path(source, ctx)
64
+ workdir = ctx.tmp().parent
65
+ wav = workdir / "speech-16k.wav"
66
+ _extract_audio(ffmpeg, source_path, wav, ctx)
67
+ prefix = workdir / "transcript"
68
+ language = str(ctx.settings.get("language", "auto"))
69
+ translate = bool(ctx.settings.get("translate", False))
70
+ threads = int(ctx.config.get("threads", 4))
71
+ args = [
72
+ whisper,
73
+ "-m",
74
+ str(model),
75
+ "-f",
76
+ str(wav),
77
+ "-l",
78
+ language,
79
+ "-t",
80
+ str(threads),
81
+ "-oj",
82
+ "-of",
83
+ str(prefix),
84
+ "-np",
85
+ ]
86
+ if translate:
87
+ args.append("-tr")
88
+ try:
89
+ completed = subprocess.run(
90
+ args,
91
+ check=False,
92
+ capture_output=True,
93
+ text=True,
94
+ encoding="utf-8",
95
+ errors="replace",
96
+ timeout=ctx.limits.timeout_s,
97
+ )
98
+ except (OSError, subprocess.TimeoutExpired) as exc:
99
+ raise ModuleUnavailable("Не удалось запустить whisper.cpp") from exc
100
+ json_path = prefix.with_suffix(".json")
101
+ if completed.returncode != 0 or not json_path.is_file():
102
+ raise CorruptInput(
103
+ "whisper.cpp не смог расшифровать аудио",
104
+ details={"stderr": completed.stderr.strip()[:500]},
105
+ )
106
+ try:
107
+ payload = json.loads(json_path.read_text(encoding="utf-8"))
108
+ except (OSError, json.JSONDecodeError) as exc:
109
+ raise CorruptInput("Некорректный JSON whisper.cpp") from exc
110
+ segments = payload.get("transcription") or []
111
+ if target == "text:plain":
112
+ text = "\n".join(
113
+ str(segment.get("text", "")).strip()
114
+ for segment in segments
115
+ if str(segment.get("text", "")).strip()
116
+ )
117
+ output = ctx.out_text("result", text + ("\n" if text else ""))
118
+ else:
119
+ rendered = _render_subtitles(segments, target)
120
+ with ctx.out_blob("result", format=target) as writer:
121
+ writer.write(rendered.encode("utf-8"))
122
+ assert writer.output is not None
123
+ output = writer.output
124
+ provenance = {
125
+ "engine": "whisper.cpp",
126
+ "model": str(model),
127
+ "language": language,
128
+ "segments": len(segments),
129
+ "target_format": target,
130
+ }
131
+ ctx.emit_provenance(provenance)
132
+ return OpResult(outputs={"result": output}, provenance=provenance)
133
+
134
+
135
+ def _find_whisper(config: Any) -> str | None:
136
+ configured = config.get("whisper_path") if hasattr(config, "get") else None
137
+ candidates = [
138
+ configured,
139
+ os.environ.get("WHISPER_CLI"),
140
+ shutil.which("whisper-cli"),
141
+ shutil.which("main"),
142
+ Path.cwd() / "var" / "tools" / "whisper" / "bin" / "Release" / "whisper-cli.exe",
143
+ Path.cwd().parent / "var" / "tools" / "whisper" / "bin" / "Release" / "whisper-cli.exe",
144
+ Path("/opt/whisper/whisper-cli"),
145
+ ]
146
+ for candidate in candidates:
147
+ if candidate and Path(str(candidate)).is_file():
148
+ return str(candidate)
149
+ if candidate:
150
+ found = shutil.which(str(candidate))
151
+ if found:
152
+ return found
153
+ return None
154
+
155
+
156
+ def _find_model(config: Any) -> str | None:
157
+ configured = config.get("model_path") if hasattr(config, "get") else None
158
+ candidates = [
159
+ configured,
160
+ os.environ.get("WHISPER_MODEL"),
161
+ Path.cwd() / "var" / "tools" / "whisper" / "ggml-tiny.bin",
162
+ Path.cwd().parent / "var" / "tools" / "whisper" / "ggml-tiny.bin",
163
+ Path.home() / ".cache" / "whisper.cpp" / "ggml-tiny.bin",
164
+ Path("/opt/whisper/ggml-tiny.bin"),
165
+ ]
166
+ for candidate in candidates:
167
+ if candidate and Path(str(candidate)).is_file():
168
+ return str(candidate)
169
+ return None
170
+
171
+
172
+ def _find_ffmpeg(config: Any) -> str | None:
173
+ configured = config.get("ffmpeg_path") if hasattr(config, "get") else None
174
+ candidates = [
175
+ configured,
176
+ os.environ.get("FFMPEG_PATH"),
177
+ shutil.which("ffmpeg"),
178
+ r"C:\Program Files\Krita (x64)\bin\ffmpeg.exe",
179
+ Path("/usr/bin/ffmpeg"),
180
+ ]
181
+ for candidate in candidates:
182
+ if candidate and Path(str(candidate)).is_file():
183
+ return str(candidate)
184
+ if candidate:
185
+ found = shutil.which(str(candidate))
186
+ if found:
187
+ return found
188
+ return None
189
+
190
+
191
+ def _source_path(source: Any, ctx: Context) -> Path:
192
+ if source.path is not None:
193
+ return Path(source.path)
194
+ path = ctx.tmp().with_suffix(".bin")
195
+ path.write_bytes(ctx.read_input("source"))
196
+ return path
197
+
198
+
199
+ def _extract_audio(ffmpeg: str, source: Path, destination: Path, ctx: Context) -> None:
200
+ try:
201
+ completed = subprocess.run(
202
+ [
203
+ ffmpeg,
204
+ "-hide_banner",
205
+ "-loglevel",
206
+ "error",
207
+ "-y",
208
+ "-i",
209
+ str(source),
210
+ "-vn",
211
+ "-ac",
212
+ "1",
213
+ "-ar",
214
+ "16000",
215
+ "-c:a",
216
+ "pcm_s16le",
217
+ str(destination),
218
+ ],
219
+ check=False,
220
+ capture_output=True,
221
+ text=True,
222
+ encoding="utf-8",
223
+ errors="replace",
224
+ timeout=ctx.limits.timeout_s,
225
+ )
226
+ except (OSError, subprocess.TimeoutExpired) as exc:
227
+ raise ModuleUnavailable("Не удалось извлечь аудио через FFmpeg") from exc
228
+ if completed.returncode != 0 or not destination.is_file():
229
+ raise CorruptInput(
230
+ "FFmpeg не смог извлечь аудио",
231
+ details={"stderr": completed.stderr.strip()[:500]},
232
+ )
233
+
234
+
235
+ def _render_subtitles(segments: list[dict[str, Any]], target: str) -> str:
236
+ def stamp(value: int, separator: str) -> str:
237
+ value = max(0, int(value))
238
+ hours, remainder = divmod(value, 3600000)
239
+ minutes, remainder = divmod(remainder, 60000)
240
+ seconds, millis = divmod(remainder, 1000)
241
+ return f"{hours:02d}:{minutes:02d}:{seconds:02d}{separator}{millis:03d}"
242
+
243
+ if target == "text:srt":
244
+ blocks = []
245
+ for index, segment in enumerate(segments, 1):
246
+ start = int((segment.get("offsets") or {}).get("from", 0))
247
+ end = int((segment.get("offsets") or {}).get("to", 0))
248
+ blocks.append(
249
+ f"{index}\n{stamp(start, ',')} --> {stamp(end, ',')}\n"
250
+ f"{str(segment.get('text', '')).strip()}\n"
251
+ )
252
+ return "\n".join(blocks)
253
+ blocks = ["WEBVTT\n"]
254
+ for segment in segments:
255
+ start = int((segment.get("offsets") or {}).get("from", 0))
256
+ end = int((segment.get("offsets") or {}).get("to", 0))
257
+ blocks.append(
258
+ f"{stamp(start, '.')} --> {stamp(end, '.')}\n"
259
+ f"{str(segment.get('text', '')).strip()}\n"
260
+ )
261
+ return "\n".join(blocks)
262
+
263
+
264
+ __all__ = ["SpeechModule"]
@@ -0,0 +1,58 @@
1
+ Metadata-Version: 2.4
2
+ Name: anyconv-speech-basic
3
+ Version: 1.0.1
4
+ Summary: AnyConv speech-to-text module using whisper.cpp
5
+ Author: AnyConv
6
+ License-Expression: MIT
7
+ Keywords: anyconv,speech,whisper,transcription,subtitles
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-speech-basic
18
+
19
+ Расшифровка аудио и видео через **whisper.cpp** с моделью `ggml-tiny`.
20
+
21
+ ## Возможности
22
+
23
+ - **`speech-transcribe`** — аудио/видео → `text:plain`, SRT или WebVTT.
24
+ - Модель по умолчанию: `ggml-tiny.bin`.
25
+ - Аудио из видео извлекается FFmpeg в WAV 16 kHz mono.
26
+ - Настройки: `language` (`auto`, `ru`, `en`), `translate`.
27
+
28
+ ## Требования
29
+
30
+ - [`whisper.cpp`](https://github.com/ggml-org/whisper.cpp) CLI (`whisper-cli`/`main`).
31
+ - Модель `ggml-tiny.bin`.
32
+ - FFmpeg в `PATH` или `ffmpeg_path`.
33
+
34
+ Пути задаются в конфигурации модуля:
35
+
36
+ ```yaml
37
+ modules:
38
+ config:
39
+ com.gitlab.raceozr.speech-basic:
40
+ whisper_path: /opt/whisper/whisper-cli
41
+ model_path: /opt/whisper/ggml-tiny.bin
42
+ ffmpeg_path: /usr/bin/ffmpeg
43
+ ```
44
+
45
+ Можно использовать `WHISPER_CLI`, `WHISPER_MODEL` и `FFMPEG_PATH`.
46
+
47
+ ## Установка
48
+
49
+ ```bash
50
+ pip install "anyconv-core[all] @ git+https://gitlab.com/raceozr/anyconv-core.git@v1.0.0"
51
+ pip install "git+https://gitlab.com/raceozr/anyconv-modules.git@v1.0.1#subdirectory=modules/speech-basic"
52
+ # ?????????? ?? checkout anyconv-modules
53
+ cd modules/speech-basic
54
+ pip install -e ".[dev]"
55
+ pytest
56
+ anyconv module validate .
57
+ anyconv module test .
58
+ ```
@@ -0,0 +1,9 @@
1
+ anyconv_speech_basic/__init__.py,sha256=ffmHcs3av8leIMhWx4TrLegizx5mO3ueo6ctpsFSAZM,113
2
+ anyconv_speech_basic/anyconv.module.yaml,sha256=fFxvCVnmr3kGVjPJNfcQ8Glm0JzJezi7TZ38F0XH3_M,1918
3
+ anyconv_speech_basic/module.py,sha256=0WqC6JSDOsnJjXEMFq-WeVL33D9SnmikIz_O4-GSfTQ,9530
4
+ anyconv_speech_basic-1.0.1.dist-info/licenses/LICENSE,sha256=Wahb1xasoYXZBxdcuh2ETI6eaWi4JazPi9yhb0eFBxU,1077
5
+ anyconv_speech_basic-1.0.1.dist-info/METADATA,sha256=Cb-S4BeYESCcunr9zRCTQjgPqZ5C0-HR1VqTqubgqv0,1828
6
+ anyconv_speech_basic-1.0.1.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
7
+ anyconv_speech_basic-1.0.1.dist-info/entry_points.txt,sha256=VAvrk37bvm8bWL5_OnzAiyCpv-xjMx7KqK-woRDWQRA,74
8
+ anyconv_speech_basic-1.0.1.dist-info/top_level.txt,sha256=gg1-AXNXM2aw524D-guwO15jVbJV-LnaI5Y4-fu1G3g,21
9
+ anyconv_speech_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
+ speech_basic = anyconv_speech_basic.module:SpeechModule
@@ -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_speech_basic