@clipen/clipen-cli 0.0.0-stage → 1.0.1

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