@clipen/clipen-cli 0.0.0-stage → 1.0.0
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.
- package/LICENSE +21 -0
- package/README.md +79 -2
- package/apps/web/dist/assets/index-D5D2HiB1.js +14 -0
- package/apps/web/dist/assets/index-DIMuOXSu.css +1 -0
- package/apps/web/dist/favicon.svg +1 -0
- package/apps/web/dist/index.html +16 -0
- package/bin/clipen.js +157 -0
- package/clipen +18 -0
- package/install +25 -0
- package/package.json +52 -4
- package/pyproject.toml +28 -0
- package/requirements/asr-runtime.txt +13 -0
- package/requirements/runtime.txt +20 -0
- package/src/clipen/__init__.py +3 -0
- package/src/clipen/analysis/__init__.py +89 -0
- package/src/clipen/analysis/artifacts.py +416 -0
- package/src/clipen/analysis/audio.py +392 -0
- package/src/clipen/analysis/evidence.py +102 -0
- package/src/clipen/analysis/evidence_service.py +751 -0
- package/src/clipen/analysis/image_similarity.py +143 -0
- package/src/clipen/analysis/keyframes.py +171 -0
- package/src/clipen/analysis/models.py +230 -0
- package/src/clipen/analysis/qwen_worker.py +629 -0
- package/src/clipen/analysis/resources.py +21 -0
- package/src/clipen/analysis/runtime.py +64 -0
- package/src/clipen/analysis/service.py +626 -0
- package/src/clipen/analysis/setup.py +935 -0
- package/src/clipen/analysis/setup_cli.py +117 -0
- package/src/clipen/analysis/storage.py +2046 -0
- package/src/clipen/analysis/transcription.py +948 -0
- package/src/clipen/analysis/visual.py +176 -0
- package/src/clipen/annotations/__init__.py +10 -0
- package/src/clipen/annotations/models.py +22 -0
- package/src/clipen/annotations/storage.py +380 -0
- package/src/clipen/annotations/suggestions.py +120 -0
- package/src/clipen/asr_release.py +139 -0
- package/src/clipen/bootstrap.py +967 -0
- package/src/clipen/cli.py +84 -0
- package/src/clipen/controller/__init__.py +17 -0
- package/src/clipen/controller/app.py +1470 -0
- package/src/clipen/controller/server.py +543 -0
- package/src/clipen/domain/__init__.py +30 -0
- package/src/clipen/domain/errors.py +5 -0
- package/src/clipen/domain/media_time.py +117 -0
- package/src/clipen/domain/timeline.py +584 -0
- package/src/clipen/domain/validation.py +15 -0
- package/src/clipen/editing/EDITORIAL_REGRESSIONS.md +38 -0
- package/src/clipen/editing/PROGRAM_FORMAT.md +102 -0
- package/src/clipen/editing/README.md +115 -0
- package/src/clipen/editing/REFACTOR_DESIGN.md +241 -0
- package/src/clipen/editing/REFACTOR_HANDOFF.md +73 -0
- package/src/clipen/editing/__init__.py +15 -0
- package/src/clipen/editing/agent.py +13 -0
- package/src/clipen/editing/agent_models.py +134 -0
- package/src/clipen/editing/agent_repository.py +757 -0
- package/src/clipen/editing/agent_tools.py +532 -0
- package/src/clipen/editing/alignment.py +110 -0
- package/src/clipen/editing/alignment_setup.py +108 -0
- package/src/clipen/editing/alignment_worker.py +22 -0
- package/src/clipen/editing/change_report.py +71 -0
- package/src/clipen/editing/compiler.py +41 -0
- package/src/clipen/editing/component_looks.py +107 -0
- package/src/clipen/editing/component_review.py +78 -0
- package/src/clipen/editing/coordinator.py +374 -0
- package/src/clipen/editing/editorial_review.py +187 -0
- package/src/clipen/editing/evidence_jobs.py +295 -0
- package/src/clipen/editing/history_changes.py +131 -0
- package/src/clipen/editing/music_choices.py +15 -0
- package/src/clipen/editing/production_catalog.py +192 -0
- package/src/clipen/editing/production_limits.py +59 -0
- package/src/clipen/editing/production_media.py +226 -0
- package/src/clipen/editing/production_preview.py +180 -0
- package/src/clipen/editing/production_progress.py +141 -0
- package/src/clipen/editing/production_requirements.py +50 -0
- package/src/clipen/editing/production_tools.py +596 -0
- package/src/clipen/editing/program_audio.py +118 -0
- package/src/clipen/editing/program_direction.py +49 -0
- package/src/clipen/editing/program_story.py +53 -0
- package/src/clipen/editing/program_subtitles.py +134 -0
- package/src/clipen/editing/programme_review.py +73 -0
- package/src/clipen/editing/prompt_history.py +47 -0
- package/src/clipen/editing/recut.py +127 -0
- package/src/clipen/editing/refinement_references.py +188 -0
- package/src/clipen/editing/resolve_export.py +616 -0
- package/src/clipen/editing/resolve_titles.py +234 -0
- package/src/clipen/editing/skill_tools.py +575 -0
- package/src/clipen/editing/source_dialogue.py +82 -0
- package/src/clipen/editing/speech_coverage.py +30 -0
- package/src/clipen/editing/speech_quality.py +6 -0
- package/src/clipen/editing/tool_receipts.py +52 -0
- package/src/clipen/editing/versions.py +161 -0
- package/src/clipen/editing/visual_preview.py +93 -0
- package/src/clipen/editing/workbench.py +74 -0
- package/src/clipen/filesystem.py +25 -0
- package/src/clipen/finishing/README.md +103 -0
- package/src/clipen/finishing/__init__.py +1 -0
- package/src/clipen/finishing/audio.py +149 -0
- package/src/clipen/finishing/catalog.py +181 -0
- package/src/clipen/finishing/models.py +14 -0
- package/src/clipen/finishing/renderer.py +26 -0
- package/src/clipen/mcp_editing/__init__.py +5 -0
- package/src/clipen/mcp_editing/__main__.py +40 -0
- package/src/clipen/mcp_editing/server.py +353 -0
- package/src/clipen/media/__init__.py +50 -0
- package/src/clipen/media/discovery.py +266 -0
- package/src/clipen/media/models.py +360 -0
- package/src/clipen/media/preview.py +147 -0
- package/src/clipen/media/probe.py +446 -0
- package/src/clipen/media/service.py +317 -0
- package/src/clipen/media/storage.py +742 -0
- package/src/clipen/music_vocabulary.py +5 -0
- package/src/clipen/planning/__init__.py +9 -0
- package/src/clipen/planning/models.py +240 -0
- package/src/clipen/power.py +23 -0
- package/src/clipen/projects/__init__.py +26 -0
- package/src/clipen/projects/agent_schema.py +94 -0
- package/src/clipen/projects/annotation_schema.py +40 -0
- package/src/clipen/projects/deletion.py +269 -0
- package/src/clipen/projects/evidence_schema.py +52 -0
- package/src/clipen/projects/finishing_schema.py +34 -0
- package/src/clipen/projects/models.py +192 -0
- package/src/clipen/projects/picker.py +256 -0
- package/src/clipen/projects/preview_schema.py +29 -0
- package/src/clipen/projects/service.py +175 -0
- package/src/clipen/projects/storage.py +1478 -0
- package/src/clipen/projects/timeline_schema.py +32 -0
- package/src/clipen/projects/validation_schema.py +28 -0
- package/src/clipen/provider_registry.py +75 -0
- package/src/clipen/providers/__init__.py +43 -0
- package/src/clipen/providers/account.py +194 -0
- package/src/clipen/providers/claude.py +375 -0
- package/src/clipen/providers/claude_editing.py +111 -0
- package/src/clipen/providers/codex.py +1036 -0
- package/src/clipen/providers/codex_editing.py +91 -0
- package/src/clipen/providers/editing_agent.py +565 -0
- package/src/clipen/providers/errors.py +51 -0
- package/src/clipen/providers/recovery.py +270 -0
- package/src/clipen/py.typed +1 -0
- package/src/clipen/rendering/__init__.py +12 -0
- package/src/clipen/rendering/cover.py +126 -0
- package/src/clipen/rendering/custom_components.py +240 -0
- package/src/clipen/rendering/custom_render.py +197 -0
- package/src/clipen/rendering/fonts/anton-OFL.txt +93 -0
- package/src/clipen/rendering/fonts/bebasneue-OFL.txt +93 -0
- package/src/clipen/rendering/fonts/caveat-OFL.txt +93 -0
- package/src/clipen/rendering/fonts/chenyu-OFL.txt +93 -0
- package/src/clipen/rendering/fonts/delagothicone-OFL.txt +93 -0
- package/src/clipen/rendering/fonts/hachimarupop-OFL.txt +93 -0
- package/src/clipen/rendering/fonts/iansui-OFL.txt +93 -0
- package/src/clipen/rendering/fonts/manifest.json +145 -0
- package/src/clipen/rendering/fonts/playfairdisplay-OFL.txt +93 -0
- package/src/clipen/rendering/fonts/rocknrollone-OFL.txt +93 -0
- package/src/clipen/rendering/fonts/yomogi-OFL.txt +94 -0
- package/src/clipen/rendering/fonts/yuseimagic-OFL.txt +93 -0
- package/src/clipen/rendering/fonts/zenkurenaido-OFL.txt +93 -0
- package/src/clipen/rendering/fonts/zenmarugothic-OFL.txt +93 -0
- package/src/clipen/rendering/production_effects.py +64 -0
- package/src/clipen/rendering/program_components.py +193 -0
- package/src/clipen/rendering/program_creator.py +649 -0
- package/src/clipen/rendering/program_identities.py +255 -0
- package/src/clipen/rendering/program_motion.py +141 -0
- package/src/clipen/rendering/program_studio.py +168 -0
- package/src/clipen/rendering/program_styles.py +235 -0
- package/src/clipen/rendering/program_subtitles.py +52 -0
- package/src/clipen/rendering/renderer.py +708 -0
- package/src/clipen/rendering/storage.py +243 -0
- package/src/clipen/rendering/titles.py +360 -0
- package/src/clipen/skills/__init__.py +4 -0
- package/src/clipen/skills/builtin/SKILL.md +72 -0
- package/src/clipen/skills/builtin/assets/sample-daily-vlog.mp4 +0 -0
- package/src/clipen/skills/builtin/assets/sample-event-recap.mp4 +0 -0
- package/src/clipen/skills/builtin/assets/sample-food-review.mp4 +0 -0
- package/src/clipen/skills/builtin/assets/sample-product-demo.mp4 +0 -0
- package/src/clipen/skills/builtin/assets/sample-product-review.mp4 +0 -0
- package/src/clipen/skills/builtin/assets/sample-product-unboxing.mp4 +0 -0
- package/src/clipen/skills/builtin/assets/sample-shorts-highlight.mp4 +0 -0
- package/src/clipen/skills/builtin/assets/sample-travel-highlight.mp4 +0 -0
- package/src/clipen/skills/builtin/assets/sample-travel-vlog.mp4 +0 -0
- package/src/clipen/skills/builtin/assets/style-cinema.png +0 -0
- package/src/clipen/skills/builtin/assets/style-editorial.png +0 -0
- package/src/clipen/skills/builtin/assets/style-tpl-daily-vlog.png +0 -0
- package/src/clipen/skills/builtin/assets/style-tpl-event-recap.png +0 -0
- package/src/clipen/skills/builtin/assets/style-tpl-food-review.png +0 -0
- package/src/clipen/skills/builtin/assets/style-tpl-product-demo.png +0 -0
- package/src/clipen/skills/builtin/assets/style-tpl-product-review.png +0 -0
- package/src/clipen/skills/builtin/assets/style-tpl-product-unboxing.png +0 -0
- package/src/clipen/skills/builtin/assets/style-tpl-shorts-highlight.png +0 -0
- package/src/clipen/skills/builtin/assets/style-tpl-travel-highlight.png +0 -0
- package/src/clipen/skills/builtin/assets/style-tpl-travel-vlog.png +0 -0
- package/src/clipen/skills/builtin/assets/style-variety.png +0 -0
- package/src/clipen/skills/builtin/components.json +133 -0
- package/src/clipen/skills/builtin/font_sources.json +20 -0
- package/src/clipen/skills/builtin/font_styles.json +329 -0
- package/src/clipen/skills/builtin/manifest.json +32 -0
- package/src/clipen/skills/builtin/presets.json +8 -0
- package/src/clipen/skills/builtin/references/captions.md +14 -0
- package/src/clipen/skills/builtin/references/channel-design.md +37 -0
- package/src/clipen/skills/builtin/references/editing.md +30 -0
- package/src/clipen/skills/builtin/references/font-chenyu-OFL.txt +93 -0
- package/src/clipen/skills/builtin/references/font-iansui-OFL.txt +93 -0
- package/src/clipen/skills/builtin/references/graphics.md +59 -0
- package/src/clipen/skills/builtin/references/review.md +16 -0
- package/src/clipen/skills/builtin/references/sound.md +8 -0
- package/src/clipen/skills/builtin/references/story.md +7 -0
- package/src/clipen/skills/builtin/skills/travel-program/SKILL.md +27 -0
- package/src/clipen/skills/builtin/skills/travel-program/manifest.json +6 -0
- package/src/clipen/skills/builtin/template-skills/clipen-daily-vlog/SKILL.md +33 -0
- package/src/clipen/skills/builtin/template-skills/clipen-daily-vlog/manifest.json +8 -0
- package/src/clipen/skills/builtin/template-skills/clipen-event-recap/SKILL.md +34 -0
- package/src/clipen/skills/builtin/template-skills/clipen-event-recap/manifest.json +8 -0
- package/src/clipen/skills/builtin/template-skills/clipen-food-review/SKILL.md +33 -0
- package/src/clipen/skills/builtin/template-skills/clipen-food-review/manifest.json +8 -0
- package/src/clipen/skills/builtin/template-skills/clipen-product-demo/SKILL.md +35 -0
- package/src/clipen/skills/builtin/template-skills/clipen-product-demo/manifest.json +8 -0
- package/src/clipen/skills/builtin/template-skills/clipen-product-review/SKILL.md +36 -0
- package/src/clipen/skills/builtin/template-skills/clipen-product-review/manifest.json +8 -0
- package/src/clipen/skills/builtin/template-skills/clipen-product-unboxing/SKILL.md +39 -0
- package/src/clipen/skills/builtin/template-skills/clipen-product-unboxing/manifest.json +8 -0
- package/src/clipen/skills/builtin/template-skills/clipen-shorts-highlight/SKILL.md +38 -0
- package/src/clipen/skills/builtin/template-skills/clipen-shorts-highlight/manifest.json +8 -0
- package/src/clipen/skills/builtin/template-skills/clipen-travel-highlight/SKILL.md +34 -0
- package/src/clipen/skills/builtin/template-skills/clipen-travel-highlight/manifest.json +8 -0
- package/src/clipen/skills/builtin/template-skills/clipen-travel-vlog/SKILL.md +37 -0
- package/src/clipen/skills/builtin/template-skills/clipen-travel-vlog/manifest.json +8 -0
- package/src/clipen/skills/builtin/templates.json +284 -0
- package/src/clipen/skills/builtin/visual_styles.json +1074 -0
- package/src/clipen/skills/catalog.py +218 -0
- package/src/clipen/skills/library.py +131 -0
- package/src/clipen/skills/package.py +231 -0
- package/src/clipen/skills/visual_styles.py +44 -0
- package/src/clipen/workspace.py +210 -0
- package/uninstall +25 -0
|
@@ -0,0 +1,948 @@
|
|
|
1
|
+
"""Bounded local transcription adapter with strict timestamp validation."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from decimal import Decimal, InvalidOperation, ROUND_CEILING, ROUND_FLOOR
|
|
7
|
+
import hashlib
|
|
8
|
+
import json
|
|
9
|
+
import os
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
import queue
|
|
12
|
+
import re
|
|
13
|
+
import signal
|
|
14
|
+
import stat
|
|
15
|
+
import subprocess
|
|
16
|
+
import tempfile
|
|
17
|
+
import threading
|
|
18
|
+
import time
|
|
19
|
+
import unicodedata
|
|
20
|
+
|
|
21
|
+
from .audio import PreparedAudio
|
|
22
|
+
from .resources import local_analysis_slot
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
_MODEL_ID = re.compile(r"[a-z][a-z0-9_.-]{0,127}\Z")
|
|
26
|
+
_SHA256 = re.compile(r"[0-9a-f]{64}\Z")
|
|
27
|
+
_LANGUAGE = re.compile(r"[a-z]{2,3}(?:-[A-Z]{2})?\Z")
|
|
28
|
+
_MAX_CAPTURE_BYTES = 1024 * 1024
|
|
29
|
+
_MAX_RESULT_BYTES = 32 * 1024 * 1024
|
|
30
|
+
_MAX_SEGMENTS = 100_000
|
|
31
|
+
_MAX_WORDS = 1_000_000
|
|
32
|
+
_POLL_SECONDS = 0.05
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class TranscriptionError(RuntimeError):
|
|
36
|
+
def __init__(self, code: str) -> None:
|
|
37
|
+
super().__init__(code)
|
|
38
|
+
self.code = code
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@dataclass(frozen=True)
|
|
42
|
+
class LocalModelSnapshot:
|
|
43
|
+
model_id: str
|
|
44
|
+
revision: str
|
|
45
|
+
path: Path
|
|
46
|
+
manifest_sha256: str
|
|
47
|
+
expected_files: tuple[tuple[str, int], ...] = ()
|
|
48
|
+
|
|
49
|
+
def __post_init__(self) -> None:
|
|
50
|
+
if _MODEL_ID.fullmatch(self.model_id) is None:
|
|
51
|
+
raise ValueError("ASR model ID is invalid")
|
|
52
|
+
if not self.revision or len(self.revision) > 128 or any(
|
|
53
|
+
ord(character) < 32 for character in self.revision
|
|
54
|
+
):
|
|
55
|
+
raise ValueError("ASR model revision is invalid")
|
|
56
|
+
if _SHA256.fullmatch(self.manifest_sha256) is None:
|
|
57
|
+
raise ValueError("ASR model manifest digest is invalid")
|
|
58
|
+
if any(
|
|
59
|
+
not filename
|
|
60
|
+
or Path(filename).name != filename
|
|
61
|
+
or size < 1
|
|
62
|
+
for filename, size in self.expected_files
|
|
63
|
+
):
|
|
64
|
+
raise ValueError("ASR model file contract is invalid")
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
@dataclass(frozen=True)
|
|
68
|
+
class TranscriptWord:
|
|
69
|
+
start_sample: int
|
|
70
|
+
end_sample: int
|
|
71
|
+
text: str
|
|
72
|
+
probability: str | None
|
|
73
|
+
|
|
74
|
+
def __post_init__(self) -> None:
|
|
75
|
+
if self.start_sample < 0 or self.end_sample <= self.start_sample:
|
|
76
|
+
raise ValueError("transcript word range is invalid")
|
|
77
|
+
_validate_text(self.text, 1024, "transcript word")
|
|
78
|
+
if self.probability is not None:
|
|
79
|
+
probability = _decimal(self.probability, minimum=Decimal(0), maximum=Decimal(1))
|
|
80
|
+
if str(probability) != self.probability:
|
|
81
|
+
raise ValueError("word probability must be canonical")
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
@dataclass(frozen=True)
|
|
85
|
+
class TranscriptSegment:
|
|
86
|
+
start_sample: int
|
|
87
|
+
end_sample: int
|
|
88
|
+
text: str
|
|
89
|
+
no_speech_probability: str | None
|
|
90
|
+
words: tuple[TranscriptWord, ...]
|
|
91
|
+
|
|
92
|
+
def __post_init__(self) -> None:
|
|
93
|
+
if self.start_sample < 0 or self.end_sample <= self.start_sample:
|
|
94
|
+
raise ValueError("transcript segment range is invalid")
|
|
95
|
+
_validate_text(self.text, 64 * 1024, "transcript segment")
|
|
96
|
+
if self.no_speech_probability is not None:
|
|
97
|
+
probability = _decimal(
|
|
98
|
+
self.no_speech_probability,
|
|
99
|
+
minimum=Decimal(0),
|
|
100
|
+
maximum=Decimal(1),
|
|
101
|
+
)
|
|
102
|
+
if str(probability) != self.no_speech_probability:
|
|
103
|
+
raise ValueError("no-speech probability must be canonical")
|
|
104
|
+
previous_end = self.start_sample
|
|
105
|
+
for word in self.words:
|
|
106
|
+
if (
|
|
107
|
+
word.start_sample < self.start_sample
|
|
108
|
+
or word.end_sample > self.end_sample
|
|
109
|
+
or word.start_sample < previous_end
|
|
110
|
+
):
|
|
111
|
+
raise ValueError("transcript words must be ordered inside their segment")
|
|
112
|
+
previous_end = word.end_sample
|
|
113
|
+
|
|
114
|
+
@property
|
|
115
|
+
def word_confidence(self) -> str | None:
|
|
116
|
+
probabilities = [
|
|
117
|
+
Decimal(word.probability)
|
|
118
|
+
for word in self.words
|
|
119
|
+
if word.probability is not None
|
|
120
|
+
]
|
|
121
|
+
if not probabilities:
|
|
122
|
+
return None
|
|
123
|
+
return _canonical_probability(sum(probabilities) / len(probabilities))
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
@dataclass(frozen=True)
|
|
127
|
+
class TranscriptionResult:
|
|
128
|
+
language: str
|
|
129
|
+
text: str
|
|
130
|
+
segments: tuple[TranscriptSegment, ...]
|
|
131
|
+
|
|
132
|
+
def __post_init__(self) -> None:
|
|
133
|
+
if _LANGUAGE.fullmatch(self.language) is None:
|
|
134
|
+
raise ValueError("transcript language is invalid")
|
|
135
|
+
_validate_text(self.text, 8 * 1024 * 1024, "transcript")
|
|
136
|
+
previous_start = -1
|
|
137
|
+
for segment in self.segments:
|
|
138
|
+
if segment.start_sample < previous_start:
|
|
139
|
+
raise ValueError("transcript segments must be ordered")
|
|
140
|
+
previous_start = segment.start_sample
|
|
141
|
+
if not self.segments and self.text.strip():
|
|
142
|
+
raise ValueError("transcript text requires timestamped segments")
|
|
143
|
+
|
|
144
|
+
@property
|
|
145
|
+
def no_speech_detected(self) -> bool:
|
|
146
|
+
return not self.segments and not self.text.strip()
|
|
147
|
+
|
|
148
|
+
@property
|
|
149
|
+
def needs_review(self) -> bool:
|
|
150
|
+
if self.no_speech_detected:
|
|
151
|
+
return False
|
|
152
|
+
probabilities = [
|
|
153
|
+
Decimal(word.probability)
|
|
154
|
+
for segment in self.segments
|
|
155
|
+
for word in segment.words
|
|
156
|
+
if word.probability is not None
|
|
157
|
+
]
|
|
158
|
+
if not probabilities:
|
|
159
|
+
# Keep compatibility with older stored transcripts. Current Qwen3
|
|
160
|
+
# results always carry a phrase-level confidence value.
|
|
161
|
+
return any(segment.text.strip() == "[音訊不清楚]" for segment in self.segments)
|
|
162
|
+
mean = sum(probabilities) / len(probabilities)
|
|
163
|
+
low_ratio = sum(
|
|
164
|
+
probability < Decimal("0.5") for probability in probabilities
|
|
165
|
+
) / len(probabilities)
|
|
166
|
+
return mean < Decimal("0.65") or low_ratio > 0.3
|
|
167
|
+
|
|
168
|
+
def to_storage(self) -> dict[str, object]:
|
|
169
|
+
return {
|
|
170
|
+
"language": self.language,
|
|
171
|
+
"text": self.text,
|
|
172
|
+
"segments": [
|
|
173
|
+
{
|
|
174
|
+
"start_sample": segment.start_sample,
|
|
175
|
+
"end_sample": segment.end_sample,
|
|
176
|
+
"text": segment.text,
|
|
177
|
+
"no_speech_probability": segment.no_speech_probability,
|
|
178
|
+
"words": [
|
|
179
|
+
{
|
|
180
|
+
"start_sample": word.start_sample,
|
|
181
|
+
"end_sample": word.end_sample,
|
|
182
|
+
"text": word.text,
|
|
183
|
+
"probability": word.probability,
|
|
184
|
+
}
|
|
185
|
+
for word in segment.words
|
|
186
|
+
],
|
|
187
|
+
}
|
|
188
|
+
for segment in self.segments
|
|
189
|
+
],
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
@classmethod
|
|
193
|
+
def from_storage(cls, value: object) -> "TranscriptionResult":
|
|
194
|
+
if not isinstance(value, dict) or set(value) != {"language", "text", "segments"}:
|
|
195
|
+
raise ValueError("stored transcript shape is invalid")
|
|
196
|
+
raw_segments = value["segments"]
|
|
197
|
+
if not isinstance(raw_segments, list) or len(raw_segments) > _MAX_SEGMENTS:
|
|
198
|
+
raise ValueError("stored transcript segments are invalid")
|
|
199
|
+
segments: list[TranscriptSegment] = []
|
|
200
|
+
word_count = 0
|
|
201
|
+
for raw_segment in raw_segments:
|
|
202
|
+
if not isinstance(raw_segment, dict) or set(raw_segment) != {
|
|
203
|
+
"start_sample",
|
|
204
|
+
"end_sample",
|
|
205
|
+
"text",
|
|
206
|
+
"no_speech_probability",
|
|
207
|
+
"words",
|
|
208
|
+
}:
|
|
209
|
+
raise ValueError("stored transcript segment is invalid")
|
|
210
|
+
raw_words = raw_segment["words"]
|
|
211
|
+
if not isinstance(raw_words, list):
|
|
212
|
+
raise ValueError("stored transcript words are invalid")
|
|
213
|
+
word_count += len(raw_words)
|
|
214
|
+
if word_count > _MAX_WORDS:
|
|
215
|
+
raise ValueError("stored transcript has too many words")
|
|
216
|
+
words = []
|
|
217
|
+
for raw_word in raw_words:
|
|
218
|
+
if not isinstance(raw_word, dict) or set(raw_word) != {
|
|
219
|
+
"start_sample",
|
|
220
|
+
"end_sample",
|
|
221
|
+
"text",
|
|
222
|
+
"probability",
|
|
223
|
+
}:
|
|
224
|
+
raise ValueError("stored transcript word is invalid")
|
|
225
|
+
words.append(
|
|
226
|
+
TranscriptWord(
|
|
227
|
+
raw_word["start_sample"],
|
|
228
|
+
raw_word["end_sample"],
|
|
229
|
+
raw_word["text"],
|
|
230
|
+
raw_word["probability"],
|
|
231
|
+
)
|
|
232
|
+
)
|
|
233
|
+
segments.append(
|
|
234
|
+
TranscriptSegment(
|
|
235
|
+
raw_segment["start_sample"],
|
|
236
|
+
raw_segment["end_sample"],
|
|
237
|
+
raw_segment["text"],
|
|
238
|
+
raw_segment["no_speech_probability"],
|
|
239
|
+
tuple(words),
|
|
240
|
+
)
|
|
241
|
+
)
|
|
242
|
+
return cls(value["language"], value["text"], tuple(segments))
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
class _PersistentASRWorkerAdapter:
|
|
246
|
+
def __init__(
|
|
247
|
+
self,
|
|
248
|
+
python_executable: Path,
|
|
249
|
+
model: LocalModelSnapshot,
|
|
250
|
+
*,
|
|
251
|
+
timeout_seconds: float = 6 * 60 * 60,
|
|
252
|
+
worker: Path,
|
|
253
|
+
readiness_key: str,
|
|
254
|
+
worker_arguments: tuple[str, ...] = (),
|
|
255
|
+
) -> None:
|
|
256
|
+
executable = Path(python_executable)
|
|
257
|
+
executable_path = Path(os.path.abspath(executable))
|
|
258
|
+
try:
|
|
259
|
+
executable_target = executable_path.resolve(strict=True)
|
|
260
|
+
except OSError as error:
|
|
261
|
+
raise TranscriptionError("asr_runtime_unavailable") from error
|
|
262
|
+
if (
|
|
263
|
+
not executable_path.is_absolute()
|
|
264
|
+
or not executable_target.is_file()
|
|
265
|
+
or not os.access(executable_target, os.X_OK)
|
|
266
|
+
):
|
|
267
|
+
raise TranscriptionError("asr_runtime_unavailable")
|
|
268
|
+
if timeout_seconds <= 0:
|
|
269
|
+
raise ValueError("ASR timeout must be positive")
|
|
270
|
+
# A venv's Python is commonly a symlink. Executing the resolved base
|
|
271
|
+
# interpreter would silently discard the venv's site-packages.
|
|
272
|
+
self.python_executable = executable_path
|
|
273
|
+
self.model = model
|
|
274
|
+
self.timeout_seconds = timeout_seconds
|
|
275
|
+
self.worker = Path(worker).resolve(strict=True)
|
|
276
|
+
if not readiness_key or not readiness_key.isidentifier():
|
|
277
|
+
raise ValueError("ASR readiness key is invalid")
|
|
278
|
+
if any(not isinstance(argument, str) or "\x00" in argument for argument in worker_arguments):
|
|
279
|
+
raise ValueError("ASR worker arguments are invalid")
|
|
280
|
+
self._readiness_key = readiness_key
|
|
281
|
+
self._worker_arguments = worker_arguments
|
|
282
|
+
self._model_lock = threading.Lock()
|
|
283
|
+
self._verified_model_path: Path | None = None
|
|
284
|
+
self._verified_model_signature: str | None = None
|
|
285
|
+
self._worker_lock = threading.Lock()
|
|
286
|
+
self._process: subprocess.Popen[bytes] | None = None
|
|
287
|
+
self._responses: queue.Queue[bytes | None] = queue.Queue()
|
|
288
|
+
self._stderr_file = None
|
|
289
|
+
|
|
290
|
+
def probe(self) -> str:
|
|
291
|
+
model_path = self._verify_model()
|
|
292
|
+
stdout, _, returncode = self._run(self._worker_command("--probe", model_path), None)
|
|
293
|
+
if returncode != 0:
|
|
294
|
+
raise TranscriptionError("asr_runtime_unsupported")
|
|
295
|
+
try:
|
|
296
|
+
payload = json.loads(stdout.decode("utf-8"))
|
|
297
|
+
except (UnicodeError, json.JSONDecodeError) as error:
|
|
298
|
+
raise TranscriptionError("asr_runtime_unsupported") from error
|
|
299
|
+
version = payload.get(self._readiness_key) if isinstance(payload, dict) else None
|
|
300
|
+
if not isinstance(version, str) or not 1 <= len(version) <= 80:
|
|
301
|
+
raise TranscriptionError("asr_runtime_unsupported")
|
|
302
|
+
return version
|
|
303
|
+
|
|
304
|
+
def transcribe(
|
|
305
|
+
self,
|
|
306
|
+
audio: PreparedAudio,
|
|
307
|
+
output: Path,
|
|
308
|
+
*,
|
|
309
|
+
language: str = "zh",
|
|
310
|
+
initial_prompt: str | None = None,
|
|
311
|
+
cancel: threading.Event | None = None,
|
|
312
|
+
) -> TranscriptionResult:
|
|
313
|
+
if _LANGUAGE.fullmatch(language) is None:
|
|
314
|
+
raise ValueError("requested ASR language is invalid")
|
|
315
|
+
if initial_prompt is not None and (
|
|
316
|
+
not isinstance(initial_prompt, str)
|
|
317
|
+
or not initial_prompt.strip()
|
|
318
|
+
or len(initial_prompt.encode("utf-8")) > 2_200
|
|
319
|
+
):
|
|
320
|
+
raise ValueError("requested ASR prompt is invalid")
|
|
321
|
+
audio_path = _verify_regular_file(audio.path, "normalized_audio_missing")
|
|
322
|
+
output_path = _verify_empty_output(output)
|
|
323
|
+
model_path = self._verify_model()
|
|
324
|
+
try:
|
|
325
|
+
request = json.dumps(
|
|
326
|
+
{
|
|
327
|
+
"audio": str(audio_path),
|
|
328
|
+
"initial_prompt": initial_prompt,
|
|
329
|
+
"language": language,
|
|
330
|
+
"output": str(output_path),
|
|
331
|
+
},
|
|
332
|
+
ensure_ascii=False,
|
|
333
|
+
sort_keys=True,
|
|
334
|
+
separators=(",", ":"),
|
|
335
|
+
).encode("utf-8") + b"\n"
|
|
336
|
+
with self._worker_lock, local_analysis_slot(
|
|
337
|
+
cancel, lambda: TranscriptionError("cancelled")
|
|
338
|
+
):
|
|
339
|
+
process = self._ensure_server(model_path, cancel)
|
|
340
|
+
try:
|
|
341
|
+
assert process.stdin is not None
|
|
342
|
+
process.stdin.write(request)
|
|
343
|
+
process.stdin.flush()
|
|
344
|
+
except (BrokenPipeError, OSError) as error:
|
|
345
|
+
self._stop_server()
|
|
346
|
+
raise TranscriptionError("asr_runtime_unavailable") from error
|
|
347
|
+
response = self._wait_for_response(process, cancel, output_path)
|
|
348
|
+
if response.get("type") != "result" or response.get("ok") is not True:
|
|
349
|
+
code = response.get("code")
|
|
350
|
+
self._stop_server()
|
|
351
|
+
raise TranscriptionError(
|
|
352
|
+
code if code in {"asr_failed", "asr_request_invalid"} else "asr_failed"
|
|
353
|
+
)
|
|
354
|
+
return _parse_result(output_path, audio.frame_count, audio.sample_rate)
|
|
355
|
+
except Exception:
|
|
356
|
+
output_path.unlink(missing_ok=True)
|
|
357
|
+
raise
|
|
358
|
+
|
|
359
|
+
def close(self) -> None:
|
|
360
|
+
with self._worker_lock:
|
|
361
|
+
self._stop_server()
|
|
362
|
+
|
|
363
|
+
def _ensure_server(
|
|
364
|
+
self, model_path: Path, cancel: threading.Event | None
|
|
365
|
+
) -> subprocess.Popen[bytes]:
|
|
366
|
+
if self._process is not None and self._process.poll() is None:
|
|
367
|
+
return self._process
|
|
368
|
+
self._stop_server()
|
|
369
|
+
environment = self._environment()
|
|
370
|
+
responses: queue.Queue[bytes | None] = queue.Queue()
|
|
371
|
+
self._responses = responses
|
|
372
|
+
self._stderr_file = tempfile.TemporaryFile()
|
|
373
|
+
try:
|
|
374
|
+
process = subprocess.Popen(
|
|
375
|
+
self._worker_command("--serve", model_path),
|
|
376
|
+
cwd="/",
|
|
377
|
+
env=environment,
|
|
378
|
+
stdin=subprocess.PIPE,
|
|
379
|
+
stdout=subprocess.PIPE,
|
|
380
|
+
stderr=self._stderr_file,
|
|
381
|
+
start_new_session=os.name == "posix",
|
|
382
|
+
)
|
|
383
|
+
except OSError as error:
|
|
384
|
+
self._close_stderr()
|
|
385
|
+
raise TranscriptionError("asr_runtime_unavailable") from error
|
|
386
|
+
self._process = process
|
|
387
|
+
threading.Thread(
|
|
388
|
+
target=self._read_responses,
|
|
389
|
+
args=(process, responses),
|
|
390
|
+
name="clipen-asr-responses",
|
|
391
|
+
daemon=True,
|
|
392
|
+
).start()
|
|
393
|
+
ready = self._wait_for_response(process, cancel)
|
|
394
|
+
version = ready.get(self._readiness_key)
|
|
395
|
+
if (
|
|
396
|
+
ready.get("type") != "ready"
|
|
397
|
+
or not isinstance(version, str)
|
|
398
|
+
or not 1 <= len(version) <= 80
|
|
399
|
+
):
|
|
400
|
+
self._stop_server()
|
|
401
|
+
raise TranscriptionError("asr_runtime_unsupported")
|
|
402
|
+
return process
|
|
403
|
+
|
|
404
|
+
def _worker_command(self, mode: str, model_path: Path) -> tuple[str, ...]:
|
|
405
|
+
return (
|
|
406
|
+
str(self.python_executable),
|
|
407
|
+
str(self.worker),
|
|
408
|
+
mode,
|
|
409
|
+
"--model",
|
|
410
|
+
str(model_path),
|
|
411
|
+
*self._worker_arguments,
|
|
412
|
+
)
|
|
413
|
+
|
|
414
|
+
def _read_responses(
|
|
415
|
+
self,
|
|
416
|
+
process: subprocess.Popen[bytes],
|
|
417
|
+
responses: queue.Queue[bytes | None],
|
|
418
|
+
) -> None:
|
|
419
|
+
assert process.stdout is not None
|
|
420
|
+
try:
|
|
421
|
+
while line := process.stdout.readline(_MAX_CAPTURE_BYTES + 1):
|
|
422
|
+
if len(line) > _MAX_CAPTURE_BYTES or not line.endswith(b"\n"):
|
|
423
|
+
responses.put(None)
|
|
424
|
+
return
|
|
425
|
+
responses.put(line)
|
|
426
|
+
finally:
|
|
427
|
+
responses.put(None)
|
|
428
|
+
|
|
429
|
+
def _wait_for_response(
|
|
430
|
+
self,
|
|
431
|
+
process: subprocess.Popen[bytes],
|
|
432
|
+
cancel: threading.Event | None,
|
|
433
|
+
observed_output: Path | None = None,
|
|
434
|
+
) -> dict[str, object]:
|
|
435
|
+
deadline = time.monotonic() + self.timeout_seconds
|
|
436
|
+
while True:
|
|
437
|
+
if cancel is not None and cancel.is_set():
|
|
438
|
+
self._stop_server()
|
|
439
|
+
raise TranscriptionError("cancelled")
|
|
440
|
+
if time.monotonic() >= deadline:
|
|
441
|
+
self._stop_server()
|
|
442
|
+
raise TranscriptionError("asr_timeout")
|
|
443
|
+
if observed_output is not None:
|
|
444
|
+
try:
|
|
445
|
+
if observed_output.stat().st_size > _MAX_RESULT_BYTES:
|
|
446
|
+
self._stop_server()
|
|
447
|
+
raise TranscriptionError("asr_result_too_large")
|
|
448
|
+
except FileNotFoundError:
|
|
449
|
+
pass
|
|
450
|
+
if self._stderr_file is not None:
|
|
451
|
+
try:
|
|
452
|
+
if os.fstat(self._stderr_file.fileno()).st_size > _MAX_CAPTURE_BYTES:
|
|
453
|
+
self._stop_server()
|
|
454
|
+
raise TranscriptionError("asr_output_too_large")
|
|
455
|
+
except ValueError:
|
|
456
|
+
pass
|
|
457
|
+
try:
|
|
458
|
+
line = self._responses.get(timeout=_POLL_SECONDS)
|
|
459
|
+
except queue.Empty:
|
|
460
|
+
if process.poll() is not None:
|
|
461
|
+
self._stop_server()
|
|
462
|
+
raise TranscriptionError("asr_runtime_unavailable")
|
|
463
|
+
continue
|
|
464
|
+
if line is None:
|
|
465
|
+
self._stop_server()
|
|
466
|
+
raise TranscriptionError("asr_runtime_unavailable")
|
|
467
|
+
try:
|
|
468
|
+
value = json.loads(line)
|
|
469
|
+
except (UnicodeError, json.JSONDecodeError) as error:
|
|
470
|
+
self._stop_server()
|
|
471
|
+
raise TranscriptionError("asr_runtime_unsupported") from error
|
|
472
|
+
if not isinstance(value, dict):
|
|
473
|
+
self._stop_server()
|
|
474
|
+
raise TranscriptionError("asr_runtime_unsupported")
|
|
475
|
+
return value
|
|
476
|
+
|
|
477
|
+
def _stop_server(self) -> None:
|
|
478
|
+
process = self._process
|
|
479
|
+
self._process = None
|
|
480
|
+
if process is not None:
|
|
481
|
+
if process.stdin is not None:
|
|
482
|
+
try:
|
|
483
|
+
process.stdin.close()
|
|
484
|
+
except OSError:
|
|
485
|
+
pass
|
|
486
|
+
if process.poll() is None:
|
|
487
|
+
_terminate(process)
|
|
488
|
+
if process.stdout is not None:
|
|
489
|
+
process.stdout.close()
|
|
490
|
+
self._close_stderr()
|
|
491
|
+
|
|
492
|
+
def _close_stderr(self) -> None:
|
|
493
|
+
if self._stderr_file is not None:
|
|
494
|
+
self._stderr_file.close()
|
|
495
|
+
self._stderr_file = None
|
|
496
|
+
|
|
497
|
+
@staticmethod
|
|
498
|
+
def _environment() -> dict[str, str]:
|
|
499
|
+
return {
|
|
500
|
+
"LANG": "C.UTF-8",
|
|
501
|
+
"LC_ALL": "C.UTF-8",
|
|
502
|
+
"PYTHONNOUSERSITE": "1",
|
|
503
|
+
"HF_HUB_OFFLINE": "1",
|
|
504
|
+
"HF_HUB_DISABLE_TELEMETRY": "1",
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
def _run(
|
|
508
|
+
self,
|
|
509
|
+
command: tuple[str, ...],
|
|
510
|
+
cancel: threading.Event | None,
|
|
511
|
+
*,
|
|
512
|
+
observed_output: Path | None = None,
|
|
513
|
+
) -> tuple[bytes, bytes, int]:
|
|
514
|
+
environment = self._environment()
|
|
515
|
+
with local_analysis_slot(cancel, lambda: TranscriptionError("cancelled")), tempfile.TemporaryFile() as stdout_file, tempfile.TemporaryFile() as stderr_file:
|
|
516
|
+
deadline = time.monotonic() + self.timeout_seconds
|
|
517
|
+
try:
|
|
518
|
+
process = subprocess.Popen(
|
|
519
|
+
command,
|
|
520
|
+
cwd="/",
|
|
521
|
+
env=environment,
|
|
522
|
+
stdin=subprocess.DEVNULL,
|
|
523
|
+
stdout=stdout_file,
|
|
524
|
+
stderr=stderr_file,
|
|
525
|
+
start_new_session=os.name == "posix",
|
|
526
|
+
)
|
|
527
|
+
except OSError as error:
|
|
528
|
+
raise TranscriptionError("asr_runtime_unavailable") from error
|
|
529
|
+
while process.poll() is None:
|
|
530
|
+
if cancel is not None and cancel.is_set():
|
|
531
|
+
_terminate(process)
|
|
532
|
+
raise TranscriptionError("cancelled")
|
|
533
|
+
if time.monotonic() >= deadline:
|
|
534
|
+
_terminate(process)
|
|
535
|
+
raise TranscriptionError("asr_timeout")
|
|
536
|
+
if (
|
|
537
|
+
os.fstat(stdout_file.fileno()).st_size > _MAX_CAPTURE_BYTES
|
|
538
|
+
or os.fstat(stderr_file.fileno()).st_size > _MAX_CAPTURE_BYTES
|
|
539
|
+
):
|
|
540
|
+
_terminate(process)
|
|
541
|
+
raise TranscriptionError("asr_output_too_large")
|
|
542
|
+
if observed_output is not None:
|
|
543
|
+
try:
|
|
544
|
+
if observed_output.stat().st_size > _MAX_RESULT_BYTES:
|
|
545
|
+
_terminate(process)
|
|
546
|
+
raise TranscriptionError("asr_result_too_large")
|
|
547
|
+
except FileNotFoundError:
|
|
548
|
+
pass
|
|
549
|
+
time.sleep(_POLL_SECONDS)
|
|
550
|
+
if (
|
|
551
|
+
os.fstat(stdout_file.fileno()).st_size > _MAX_CAPTURE_BYTES
|
|
552
|
+
or os.fstat(stderr_file.fileno()).st_size > _MAX_CAPTURE_BYTES
|
|
553
|
+
):
|
|
554
|
+
raise TranscriptionError("asr_output_too_large")
|
|
555
|
+
if observed_output is not None and observed_output.stat().st_size > _MAX_RESULT_BYTES:
|
|
556
|
+
raise TranscriptionError("asr_result_too_large")
|
|
557
|
+
stdout_file.seek(0)
|
|
558
|
+
stderr_file.seek(0)
|
|
559
|
+
return stdout_file.read(), stderr_file.read(), process.returncode
|
|
560
|
+
|
|
561
|
+
def _verify_model(self) -> Path:
|
|
562
|
+
with self._model_lock:
|
|
563
|
+
if self._verified_model_path is None:
|
|
564
|
+
path = _verify_model(self.model)
|
|
565
|
+
self._verified_model_path = path
|
|
566
|
+
self._verified_model_signature = _model_directory_signature(path)
|
|
567
|
+
return path
|
|
568
|
+
observed = _model_directory_signature(self._verified_model_path)
|
|
569
|
+
if observed != self._verified_model_signature:
|
|
570
|
+
raise TranscriptionError("asr_model_changed")
|
|
571
|
+
return self._verified_model_path
|
|
572
|
+
|
|
573
|
+
|
|
574
|
+
class Qwen3ASRAdapter(_PersistentASRWorkerAdapter):
|
|
575
|
+
"""Managed Qwen3-ASR worker with token-confidence gating."""
|
|
576
|
+
|
|
577
|
+
def __init__(
|
|
578
|
+
self,
|
|
579
|
+
python_executable: Path,
|
|
580
|
+
model: LocalModelSnapshot,
|
|
581
|
+
*,
|
|
582
|
+
timeout_seconds: float = 6 * 60 * 60,
|
|
583
|
+
) -> None:
|
|
584
|
+
super().__init__(
|
|
585
|
+
python_executable,
|
|
586
|
+
model,
|
|
587
|
+
timeout_seconds=timeout_seconds,
|
|
588
|
+
worker=Path(__file__).with_name("qwen_worker.py"),
|
|
589
|
+
readiness_key="qwen3_asr_runtime",
|
|
590
|
+
)
|
|
591
|
+
|
|
592
|
+
|
|
593
|
+
def hash_model_directory(path: Path, *, maximum_bytes: int = 8 * 1024**3) -> str:
|
|
594
|
+
root = Path(path)
|
|
595
|
+
if root.is_symlink() or not root.is_dir():
|
|
596
|
+
raise TranscriptionError("asr_model_unavailable")
|
|
597
|
+
resolved = root.resolve(strict=True)
|
|
598
|
+
digest = hashlib.sha256()
|
|
599
|
+
total = 0
|
|
600
|
+
files = 0
|
|
601
|
+
for candidate in sorted(resolved.rglob("*")):
|
|
602
|
+
if candidate.is_symlink():
|
|
603
|
+
raise TranscriptionError("asr_model_unsafe")
|
|
604
|
+
if candidate.is_dir():
|
|
605
|
+
continue
|
|
606
|
+
info = os.lstat(candidate)
|
|
607
|
+
if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1:
|
|
608
|
+
raise TranscriptionError("asr_model_unsafe")
|
|
609
|
+
relative = candidate.relative_to(resolved).as_posix()
|
|
610
|
+
if len(relative) > 1024 or files >= 10_000:
|
|
611
|
+
raise TranscriptionError("asr_model_unsafe")
|
|
612
|
+
files += 1
|
|
613
|
+
total += info.st_size
|
|
614
|
+
if total > maximum_bytes:
|
|
615
|
+
raise TranscriptionError("asr_model_too_large")
|
|
616
|
+
file_digest = hashlib.sha256()
|
|
617
|
+
with candidate.open("rb") as source:
|
|
618
|
+
while block := source.read(1024 * 1024):
|
|
619
|
+
file_digest.update(block)
|
|
620
|
+
digest.update(relative.encode("utf-8"))
|
|
621
|
+
digest.update(b"\0")
|
|
622
|
+
digest.update(str(info.st_size).encode("ascii"))
|
|
623
|
+
digest.update(b"\0")
|
|
624
|
+
digest.update(file_digest.digest())
|
|
625
|
+
if files < 1:
|
|
626
|
+
raise TranscriptionError("asr_model_unavailable")
|
|
627
|
+
return digest.hexdigest()
|
|
628
|
+
|
|
629
|
+
|
|
630
|
+
def _model_directory_signature(path: Path) -> str:
|
|
631
|
+
root = Path(path)
|
|
632
|
+
if root.is_symlink() or not root.is_dir():
|
|
633
|
+
raise TranscriptionError("asr_model_unavailable")
|
|
634
|
+
resolved = root.resolve(strict=True)
|
|
635
|
+
digest = hashlib.sha256()
|
|
636
|
+
files = 0
|
|
637
|
+
for candidate in sorted(resolved.rglob("*")):
|
|
638
|
+
if candidate.is_symlink():
|
|
639
|
+
raise TranscriptionError("asr_model_unsafe")
|
|
640
|
+
if candidate.is_dir():
|
|
641
|
+
continue
|
|
642
|
+
info = os.lstat(candidate)
|
|
643
|
+
if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1 or files >= 10_000:
|
|
644
|
+
raise TranscriptionError("asr_model_unsafe")
|
|
645
|
+
files += 1
|
|
646
|
+
relative = candidate.relative_to(resolved).as_posix()
|
|
647
|
+
digest.update(relative.encode("utf-8"))
|
|
648
|
+
digest.update(b"\0")
|
|
649
|
+
digest.update(
|
|
650
|
+
f"{info.st_dev}:{info.st_ino}:{info.st_size}:{info.st_mtime_ns}".encode(
|
|
651
|
+
"ascii"
|
|
652
|
+
)
|
|
653
|
+
)
|
|
654
|
+
digest.update(b"\0")
|
|
655
|
+
if files < 1:
|
|
656
|
+
raise TranscriptionError("asr_model_unavailable")
|
|
657
|
+
return digest.hexdigest()
|
|
658
|
+
|
|
659
|
+
|
|
660
|
+
def _verify_model(model: LocalModelSnapshot) -> Path:
|
|
661
|
+
path = Path(model.path)
|
|
662
|
+
if not path.is_absolute():
|
|
663
|
+
raise TranscriptionError("asr_model_unavailable")
|
|
664
|
+
if model.expected_files:
|
|
665
|
+
return _verify_expected_model_files(path, model.expected_files)
|
|
666
|
+
observed = hash_model_directory(path)
|
|
667
|
+
if observed != model.manifest_sha256:
|
|
668
|
+
raise TranscriptionError("asr_model_changed")
|
|
669
|
+
return path.resolve(strict=True)
|
|
670
|
+
|
|
671
|
+
|
|
672
|
+
def _verify_expected_model_files(
|
|
673
|
+
path: Path, expected_files: tuple[tuple[str, int], ...]
|
|
674
|
+
) -> Path:
|
|
675
|
+
if path.is_symlink() or not path.is_dir():
|
|
676
|
+
raise TranscriptionError("asr_model_unavailable")
|
|
677
|
+
resolved = path.resolve(strict=True)
|
|
678
|
+
expected = dict(expected_files)
|
|
679
|
+
observed: set[str] = set()
|
|
680
|
+
for candidate in resolved.rglob("*"):
|
|
681
|
+
if candidate.is_symlink():
|
|
682
|
+
raise TranscriptionError("asr_model_unsafe")
|
|
683
|
+
if candidate.is_dir():
|
|
684
|
+
continue
|
|
685
|
+
info = os.lstat(candidate)
|
|
686
|
+
relative = candidate.relative_to(resolved).as_posix()
|
|
687
|
+
if (
|
|
688
|
+
not stat.S_ISREG(info.st_mode)
|
|
689
|
+
or info.st_nlink != 1
|
|
690
|
+
or relative not in expected
|
|
691
|
+
or info.st_size != expected[relative]
|
|
692
|
+
):
|
|
693
|
+
raise TranscriptionError("asr_model_changed")
|
|
694
|
+
observed.add(relative)
|
|
695
|
+
if observed != set(expected):
|
|
696
|
+
raise TranscriptionError("asr_model_changed")
|
|
697
|
+
return resolved
|
|
698
|
+
|
|
699
|
+
|
|
700
|
+
def _parse_result(path: Path, frame_count: int, sample_rate: int) -> TranscriptionResult:
|
|
701
|
+
try:
|
|
702
|
+
info = os.lstat(path)
|
|
703
|
+
if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1 or info.st_size > _MAX_RESULT_BYTES:
|
|
704
|
+
raise TranscriptionError("asr_result_invalid")
|
|
705
|
+
value = json.loads(path.read_text(encoding="utf-8"))
|
|
706
|
+
except TranscriptionError:
|
|
707
|
+
raise
|
|
708
|
+
except (OSError, UnicodeError, json.JSONDecodeError) as error:
|
|
709
|
+
raise TranscriptionError("asr_result_invalid") from error
|
|
710
|
+
if not isinstance(value, dict) or set(value) != {"language", "text", "segments"}:
|
|
711
|
+
raise TranscriptionError("asr_result_invalid")
|
|
712
|
+
language = value["language"]
|
|
713
|
+
text = value["text"]
|
|
714
|
+
raw_segments = value["segments"]
|
|
715
|
+
if (
|
|
716
|
+
not isinstance(language, str)
|
|
717
|
+
or _LANGUAGE.fullmatch(language) is None
|
|
718
|
+
or not isinstance(text, str)
|
|
719
|
+
or not isinstance(raw_segments, list)
|
|
720
|
+
or len(raw_segments) > _MAX_SEGMENTS
|
|
721
|
+
):
|
|
722
|
+
raise TranscriptionError("asr_result_invalid")
|
|
723
|
+
segments: list[TranscriptSegment] = []
|
|
724
|
+
word_count = 0
|
|
725
|
+
try:
|
|
726
|
+
for raw in raw_segments:
|
|
727
|
+
if not isinstance(raw, dict) or set(raw) != {
|
|
728
|
+
"start",
|
|
729
|
+
"end",
|
|
730
|
+
"text",
|
|
731
|
+
"no_speech_probability",
|
|
732
|
+
"words",
|
|
733
|
+
}:
|
|
734
|
+
raise ValueError("segment shape")
|
|
735
|
+
start = _seconds_to_sample(raw["start"], sample_rate, frame_count, start=True)
|
|
736
|
+
end = _seconds_to_sample(raw["end"], sample_rate, frame_count, start=False)
|
|
737
|
+
raw_words = raw["words"]
|
|
738
|
+
if not isinstance(raw_words, list):
|
|
739
|
+
raise ValueError("word shape")
|
|
740
|
+
word_count += len(raw_words)
|
|
741
|
+
if word_count > _MAX_WORDS:
|
|
742
|
+
raise ValueError("too many words")
|
|
743
|
+
words = []
|
|
744
|
+
probabilities = []
|
|
745
|
+
previous_word_end = start
|
|
746
|
+
for word in raw_words:
|
|
747
|
+
if not isinstance(word, dict) or set(word) != {
|
|
748
|
+
"start",
|
|
749
|
+
"end",
|
|
750
|
+
"text",
|
|
751
|
+
"probability",
|
|
752
|
+
}:
|
|
753
|
+
raise ValueError("word shape")
|
|
754
|
+
probability = _optional_probability(word["probability"])
|
|
755
|
+
if probability is not None:
|
|
756
|
+
probabilities.append(Decimal(probability))
|
|
757
|
+
word_start = max(
|
|
758
|
+
start,
|
|
759
|
+
previous_word_end,
|
|
760
|
+
_word_sample(word["start"], sample_rate, frame_count, start=True),
|
|
761
|
+
)
|
|
762
|
+
word_end = min(
|
|
763
|
+
end,
|
|
764
|
+
_word_sample(word["end"], sample_rate, frame_count, start=False),
|
|
765
|
+
)
|
|
766
|
+
if word_end <= word_start:
|
|
767
|
+
continue
|
|
768
|
+
words.append(
|
|
769
|
+
TranscriptWord(
|
|
770
|
+
word_start,
|
|
771
|
+
word_end,
|
|
772
|
+
word["text"],
|
|
773
|
+
probability,
|
|
774
|
+
)
|
|
775
|
+
)
|
|
776
|
+
previous_word_end = word_end
|
|
777
|
+
no_speech_probability = _optional_probability(
|
|
778
|
+
raw["no_speech_probability"]
|
|
779
|
+
)
|
|
780
|
+
if _low_quality_segment(
|
|
781
|
+
raw["text"], no_speech_probability, probabilities
|
|
782
|
+
):
|
|
783
|
+
continue
|
|
784
|
+
segments.append(
|
|
785
|
+
TranscriptSegment(
|
|
786
|
+
start,
|
|
787
|
+
end,
|
|
788
|
+
raw["text"],
|
|
789
|
+
no_speech_probability,
|
|
790
|
+
tuple(words),
|
|
791
|
+
)
|
|
792
|
+
)
|
|
793
|
+
segments = _drop_repetition_loops(segments)
|
|
794
|
+
accepted_text = "\n".join(
|
|
795
|
+
segment.text.strip() for segment in segments if segment.text.strip()
|
|
796
|
+
)
|
|
797
|
+
return TranscriptionResult(language, accepted_text, tuple(segments))
|
|
798
|
+
except (KeyError, TypeError, ValueError, InvalidOperation) as error:
|
|
799
|
+
raise TranscriptionError("asr_result_invalid") from error
|
|
800
|
+
|
|
801
|
+
|
|
802
|
+
def _seconds_to_sample(value: object, rate: int, frame_count: int, *, start: bool) -> int:
|
|
803
|
+
seconds = _decimal(value, minimum=Decimal(0), maximum=Decimal("1000000000"))
|
|
804
|
+
rounding = ROUND_FLOOR if start else ROUND_CEILING
|
|
805
|
+
sample = int((seconds * rate).to_integral_value(rounding=rounding))
|
|
806
|
+
if start:
|
|
807
|
+
if sample >= frame_count:
|
|
808
|
+
raise ValueError("timestamp starts outside audio")
|
|
809
|
+
elif sample < 1 or sample > frame_count + rate:
|
|
810
|
+
raise ValueError("timestamp ends outside audio")
|
|
811
|
+
return min(sample, frame_count)
|
|
812
|
+
|
|
813
|
+
|
|
814
|
+
def _word_sample(value: object, rate: int, frame_count: int, *, start: bool) -> int:
|
|
815
|
+
seconds = _decimal(value, minimum=Decimal(0), maximum=Decimal("1000000000"))
|
|
816
|
+
rounding = ROUND_FLOOR if start else ROUND_CEILING
|
|
817
|
+
sample = int((seconds * rate).to_integral_value(rounding=rounding))
|
|
818
|
+
return min(sample, frame_count)
|
|
819
|
+
|
|
820
|
+
|
|
821
|
+
def _low_quality_segment(
|
|
822
|
+
text: object,
|
|
823
|
+
no_speech_probability: str | None,
|
|
824
|
+
word_probabilities: list[Decimal],
|
|
825
|
+
) -> bool:
|
|
826
|
+
if not isinstance(text, str):
|
|
827
|
+
raise ValueError("segment text")
|
|
828
|
+
compact = "".join(character for character in text if not character.isspace())
|
|
829
|
+
if not compact:
|
|
830
|
+
return True
|
|
831
|
+
if not any(unicodedata.category(character)[0] in {"L", "N"} for character in compact):
|
|
832
|
+
return True
|
|
833
|
+
if (
|
|
834
|
+
no_speech_probability is not None
|
|
835
|
+
and Decimal(no_speech_probability) >= Decimal("0.6")
|
|
836
|
+
):
|
|
837
|
+
return True
|
|
838
|
+
if word_probabilities:
|
|
839
|
+
mean = sum(word_probabilities) / len(word_probabilities)
|
|
840
|
+
low_ratio = sum(
|
|
841
|
+
probability < Decimal("0.5") for probability in word_probabilities
|
|
842
|
+
) / len(word_probabilities)
|
|
843
|
+
if mean < Decimal("0.2") or (
|
|
844
|
+
mean < Decimal("0.35") and low_ratio >= 0.75
|
|
845
|
+
):
|
|
846
|
+
return True
|
|
847
|
+
if len(compact) >= 12 and len(set(compact)) / len(compact) < 0.15:
|
|
848
|
+
return True
|
|
849
|
+
return False
|
|
850
|
+
|
|
851
|
+
|
|
852
|
+
def _drop_repetition_loops(
|
|
853
|
+
segments: list[TranscriptSegment],
|
|
854
|
+
) -> list[TranscriptSegment]:
|
|
855
|
+
"""Keep natural emphasis while capping decoder loops across windows."""
|
|
856
|
+
|
|
857
|
+
accepted: list[TranscriptSegment] = []
|
|
858
|
+
totals: dict[str, int] = {}
|
|
859
|
+
previous = ""
|
|
860
|
+
consecutive = 0
|
|
861
|
+
for segment in segments:
|
|
862
|
+
normalized = "".join(
|
|
863
|
+
character.casefold()
|
|
864
|
+
for character in segment.text
|
|
865
|
+
if unicodedata.category(character)[0] in {"L", "N"}
|
|
866
|
+
)
|
|
867
|
+
if not normalized:
|
|
868
|
+
continue
|
|
869
|
+
consecutive = consecutive + 1 if normalized == previous else 1
|
|
870
|
+
previous = normalized
|
|
871
|
+
totals[normalized] = totals.get(normalized, 0) + 1
|
|
872
|
+
if consecutive > 2 or totals[normalized] > 3:
|
|
873
|
+
continue
|
|
874
|
+
accepted.append(segment)
|
|
875
|
+
return accepted
|
|
876
|
+
|
|
877
|
+
|
|
878
|
+
def _optional_probability(value: object) -> str | None:
|
|
879
|
+
if value is None:
|
|
880
|
+
return None
|
|
881
|
+
return str(_decimal(value, minimum=Decimal(0), maximum=Decimal(1)))
|
|
882
|
+
|
|
883
|
+
|
|
884
|
+
def _canonical_probability(value: Decimal) -> str:
|
|
885
|
+
rendered = format(value, "f").rstrip("0").rstrip(".")
|
|
886
|
+
return rendered or "0"
|
|
887
|
+
|
|
888
|
+
|
|
889
|
+
def _decimal(value: object, *, minimum: Decimal, maximum: Decimal) -> Decimal:
|
|
890
|
+
if isinstance(value, bool):
|
|
891
|
+
raise ValueError("boolean is not a decimal")
|
|
892
|
+
try:
|
|
893
|
+
result = Decimal(str(value)).normalize()
|
|
894
|
+
except (InvalidOperation, ValueError) as error:
|
|
895
|
+
raise ValueError("invalid decimal") from error
|
|
896
|
+
if not result.is_finite() or not minimum <= result <= maximum:
|
|
897
|
+
raise ValueError("decimal outside bounds")
|
|
898
|
+
return result
|
|
899
|
+
|
|
900
|
+
|
|
901
|
+
def _validate_text(value: object, maximum_bytes: int, label: str) -> None:
|
|
902
|
+
if (
|
|
903
|
+
not isinstance(value, str)
|
|
904
|
+
or "\x00" in value
|
|
905
|
+
or len(value.encode("utf-8")) > maximum_bytes
|
|
906
|
+
):
|
|
907
|
+
raise ValueError(f"{label} text is invalid")
|
|
908
|
+
|
|
909
|
+
|
|
910
|
+
def _verify_regular_file(path: Path, code: str) -> Path:
|
|
911
|
+
candidate = Path(path)
|
|
912
|
+
if candidate.is_symlink() or not candidate.is_file():
|
|
913
|
+
raise TranscriptionError(code)
|
|
914
|
+
info = os.lstat(candidate)
|
|
915
|
+
if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1:
|
|
916
|
+
raise TranscriptionError(code)
|
|
917
|
+
return candidate.resolve(strict=True)
|
|
918
|
+
|
|
919
|
+
|
|
920
|
+
def _verify_empty_output(path: Path) -> Path:
|
|
921
|
+
candidate = _verify_regular_file(path, "asr_output_unsafe")
|
|
922
|
+
if candidate.stat().st_size != 0:
|
|
923
|
+
raise TranscriptionError("asr_output_unsafe")
|
|
924
|
+
return candidate
|
|
925
|
+
|
|
926
|
+
|
|
927
|
+
def _terminate(process: subprocess.Popen[bytes]) -> None:
|
|
928
|
+
if process.poll() is not None:
|
|
929
|
+
return
|
|
930
|
+
if os.name == "posix":
|
|
931
|
+
try:
|
|
932
|
+
os.killpg(process.pid, signal.SIGTERM)
|
|
933
|
+
except ProcessLookupError:
|
|
934
|
+
process.wait(timeout=2)
|
|
935
|
+
return
|
|
936
|
+
else:
|
|
937
|
+
process.terminate()
|
|
938
|
+
try:
|
|
939
|
+
process.wait(timeout=3)
|
|
940
|
+
except subprocess.TimeoutExpired:
|
|
941
|
+
if os.name == "posix":
|
|
942
|
+
try:
|
|
943
|
+
os.killpg(process.pid, signal.SIGKILL)
|
|
944
|
+
except ProcessLookupError:
|
|
945
|
+
pass
|
|
946
|
+
else:
|
|
947
|
+
process.kill()
|
|
948
|
+
process.wait(timeout=2)
|