@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,594 @@
1
+ """Persistent Qwen3-ASR worker with confidence-based hallucination rejection."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import importlib.metadata
7
+ import json
8
+ import math
9
+ import os
10
+ import stat
11
+ import sys
12
+ import unicodedata
13
+ import wave
14
+ from decimal import Decimal
15
+ from pathlib import Path
16
+
17
+ _MAX_REQUEST_BYTES = 64 * 1024
18
+ _MAX_CAPTURE_BYTES = 32 * 1024 * 1024
19
+ _MAX_AUDIO_SECONDS = 5 * 60 + 1
20
+ _WINDOW_SECONDS = 12
21
+ _MAX_NEW_TOKENS = 128
22
+ _REVIEW_SCORE = 0.64
23
+ _MAX_ENHANCED_RETRIES = 4
24
+ _MODEL_FILES = {
25
+ "chat_template.json",
26
+ "config.json",
27
+ "generation_config.json",
28
+ "merges.txt",
29
+ "model.safetensors",
30
+ "preprocessor_config.json",
31
+ "tokenizer_config.json",
32
+ "vocab.json",
33
+ }
34
+
35
+
36
+ def _arguments() -> argparse.Namespace:
37
+ parser = argparse.ArgumentParser(add_help=False)
38
+ parser.add_argument("--probe", action="store_true")
39
+ parser.add_argument("--serve", action="store_true")
40
+ parser.add_argument("--model", required=True)
41
+ return parser.parse_args()
42
+
43
+
44
+ def _regular(path: str, *, directory: bool = False) -> Path:
45
+ candidate = Path(path)
46
+ if not candidate.is_absolute() or candidate.is_symlink():
47
+ raise ValueError("unsafe path")
48
+ info = os.lstat(candidate)
49
+ expected = stat.S_ISDIR(info.st_mode) if directory else stat.S_ISREG(info.st_mode)
50
+ if not expected or (not directory and info.st_nlink != 1):
51
+ raise ValueError("unsafe path")
52
+ return candidate.resolve(strict=True)
53
+
54
+
55
+ def _model_files(model: Path) -> dict[str, Path]:
56
+ children = tuple(model.iterdir())
57
+ observed = {candidate.name for candidate in children if candidate.is_file()}
58
+ if observed != _MODEL_FILES or any(candidate.is_symlink() for candidate in children):
59
+ raise ValueError("unsafe model")
60
+ return {name: _regular(str(model / name)) for name in _MODEL_FILES}
61
+
62
+
63
+ def _response(value: dict[str, object]) -> None:
64
+ print(json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")), flush=True)
65
+
66
+
67
+ def _write_result(path: Path, value: dict[str, object]) -> None:
68
+ flags = os.O_WRONLY | os.O_TRUNC | getattr(os, "O_NOFOLLOW", 0)
69
+ descriptor = os.open(path, flags)
70
+ try:
71
+ info = os.fstat(descriptor)
72
+ if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1:
73
+ raise ValueError("unsafe output")
74
+ encoded = json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode("utf-8")
75
+ if len(encoded) > _MAX_CAPTURE_BYTES:
76
+ raise ValueError("result too large")
77
+ with os.fdopen(descriptor, "wb", closefd=False) as output:
78
+ output.write(encoded)
79
+ output.flush()
80
+ os.fsync(output.fileno())
81
+ finally:
82
+ os.close(descriptor)
83
+
84
+
85
+ def _read_audio(path: Path):
86
+ import numpy as np
87
+
88
+ with wave.open(str(path), "rb") as audio:
89
+ if (
90
+ audio.getframerate() != 16_000
91
+ or audio.getnchannels() != 1
92
+ or audio.getsampwidth() != 2
93
+ or audio.getnframes() < 1
94
+ ):
95
+ raise ValueError("unsupported audio")
96
+ frame_count = audio.getnframes()
97
+ duration = frame_count / audio.getframerate()
98
+ samples = np.frombuffer(audio.readframes(frame_count), dtype="<i2").astype(np.float32) / 32768.0
99
+ if duration > _MAX_AUDIO_SECONDS:
100
+ raise ValueError("audio chunk too long")
101
+ return samples
102
+
103
+
104
+ def _window_ranges(samples, sample_rate: int = 16_000) -> list[tuple[int, int]]:
105
+ """Create bounded windows and move cuts toward nearby low-energy frames."""
106
+
107
+ import numpy as np
108
+
109
+ search_frame = max(1, sample_rate // 50)
110
+ usable = int(samples.shape[0]) // search_frame * search_frame
111
+ frames = samples[:usable].reshape(-1, search_frame)
112
+ energies = np.mean(frames * frames, axis=1).tolist()
113
+ return _window_ranges_from_energy(int(samples.shape[0]), energies, search_frame, sample_rate)
114
+
115
+
116
+ def _window_ranges_from_energy(
117
+ total: int, energies: list[float], frame_size: int, sample_rate: int = 16_000
118
+ ) -> list[tuple[int, int]]:
119
+ maximum = _WINDOW_SECONDS * sample_rate
120
+ minimum = 8 * sample_rate
121
+ ranges: list[tuple[int, int]] = []
122
+ start = 0
123
+ while start < total:
124
+ hard_end = min(total, start + maximum)
125
+ end = hard_end
126
+ if hard_end < total:
127
+ search_start = start + minimum
128
+ candidates = [
129
+ (energies[index], index * frame_size)
130
+ for index in range(
131
+ (search_start + frame_size - 1) // frame_size,
132
+ min(len(energies), hard_end // frame_size),
133
+ )
134
+ ]
135
+ if candidates:
136
+ end = min(candidates)[1]
137
+ if end <= start:
138
+ end = hard_end
139
+ ranges.append((start, end))
140
+ start = end
141
+ return ranges
142
+
143
+
144
+ def _has_audible_activity(samples, sample_rate: int = 16_000) -> bool:
145
+ """Skip digital silence and very low camera noise before loading the model."""
146
+
147
+ import numpy as np
148
+
149
+ if int(samples.shape[0]) < sample_rate // 2:
150
+ return False
151
+ frame_size = max(1, sample_rate // 50)
152
+ usable = int(samples.shape[0]) // frame_size * frame_size
153
+ if usable < frame_size:
154
+ return False
155
+ frames = samples[:usable].reshape(-1, frame_size)
156
+ rms = np.sqrt(np.mean(frames * frames, axis=1))
157
+ return _audible_from_rms(rms.tolist(), int(samples.shape[0]), sample_rate)
158
+
159
+
160
+ def _audible_from_rms(rms: list[float], sample_count: int, sample_rate: int = 16_000) -> bool:
161
+ if sample_count < sample_rate // 2 or not rms:
162
+ return False
163
+ return max(rms) >= 0.006 and sum(value >= 0.003 for value in rms) / len(rms) >= 0.02
164
+
165
+
166
+ def _percentile(values: list[float], fraction: float) -> float:
167
+ if not values or not 0 <= fraction <= 1:
168
+ raise ValueError("invalid percentile")
169
+ ordered = sorted(float(value) for value in values)
170
+ position = (len(ordered) - 1) * fraction
171
+ lower = math.floor(position)
172
+ upper = math.ceil(position)
173
+ if lower == upper:
174
+ return ordered[lower]
175
+ weight = position - lower
176
+ return ordered[lower] * (1 - weight) + ordered[upper] * weight
177
+
178
+
179
+ def _quality_from_rms(rms: list[float], *, peak: float, clipping_ratio: float) -> dict[str, float | bool]:
180
+ """Summarize capture quality without claiming that energy equals speech."""
181
+
182
+ if (
183
+ not rms
184
+ or not math.isfinite(peak)
185
+ or not math.isfinite(clipping_ratio)
186
+ or peak < 0
187
+ or not 0 <= clipping_ratio <= 1
188
+ or any(not math.isfinite(value) or value < 0 for value in rms)
189
+ ):
190
+ raise ValueError("invalid audio quality input")
191
+ noise_floor = _percentile(rms, 0.2)
192
+ foreground = _percentile(rms, 0.9)
193
+ denominator = max(noise_floor, 0.0005)
194
+ snr_db = 20 * math.log10(max(foreground, denominator) / denominator)
195
+ active_threshold = max(0.003, noise_floor * 2.5)
196
+ active_ratio = sum(value >= active_threshold for value in rms) / len(rms)
197
+ quiet = foreground < 0.025
198
+ noisy = noise_floor >= 0.0025 and snr_db < 12
199
+ clipped = clipping_ratio >= 0.001
200
+ return {
201
+ "noise_floor": noise_floor,
202
+ "foreground_rms": foreground,
203
+ "snr_db": snr_db,
204
+ "active_ratio": active_ratio,
205
+ "peak": peak,
206
+ "clipping_ratio": clipping_ratio,
207
+ "quiet": quiet,
208
+ "noisy": noisy,
209
+ "clipped": clipped,
210
+ "needs_enhancement": quiet or noisy,
211
+ }
212
+
213
+
214
+ def _audio_quality(samples, sample_rate: int = 16_000) -> dict[str, float | bool]:
215
+ import numpy as np
216
+
217
+ frame_size = max(1, sample_rate // 50)
218
+ usable = int(samples.shape[0]) // frame_size * frame_size
219
+ if usable < frame_size:
220
+ raise ValueError("audio window is too short")
221
+ frames = samples[:usable].reshape(-1, frame_size)
222
+ rms = np.sqrt(np.mean(frames * frames, axis=1)).tolist()
223
+ absolute = np.abs(samples)
224
+ return _quality_from_rms(
225
+ rms,
226
+ peak=float(np.max(absolute)),
227
+ clipping_ratio=float(np.mean(absolute >= 0.985)),
228
+ )
229
+
230
+
231
+ def _enhance_for_speech(samples, quality: dict[str, float | bool]):
232
+ """Apply one bounded spectral-gating candidate to a short local window."""
233
+
234
+ import numpy as np
235
+
236
+ source = np.asarray(samples, dtype=np.float32)
237
+ if source.ndim != 1 or source.size < 1 or not np.all(np.isfinite(source)):
238
+ raise ValueError("invalid audio samples")
239
+ frame_size = 512
240
+ hop = 256
241
+ if source.size < frame_size:
242
+ output = source.astype(np.float32, copy=True)
243
+ else:
244
+ frame_count = 1 + math.ceil((source.size - frame_size) / hop)
245
+ padded_size = (frame_count - 1) * hop + frame_size
246
+ padded = np.pad(source, (0, padded_size - source.size))
247
+ frames = np.lib.stride_tricks.sliding_window_view(padded, frame_size)[::hop]
248
+ window = np.hanning(frame_size).astype(np.float32)
249
+ spectrum = np.fft.rfft(frames * window, axis=1)
250
+ magnitude = np.abs(spectrum)
251
+ noise = np.quantile(magnitude, 0.2, axis=0)
252
+ strength = 1.2 if bool(quality["noisy"]) else 0.8
253
+ floor = 0.12 if bool(quality["noisy"]) else 0.22
254
+ gain = np.clip(
255
+ 1.0 - strength * noise[None, :] / np.maximum(magnitude, 1e-7),
256
+ floor,
257
+ 1.0,
258
+ )
259
+ frequencies = np.fft.rfftfreq(frame_size, d=1 / 16_000)
260
+ gain[:, frequencies < 80] *= 0.15
261
+ reconstructed = np.fft.irfft(spectrum * gain, n=frame_size, axis=1)
262
+ output = np.zeros(padded_size, dtype=np.float64)
263
+ weights = np.zeros(padded_size, dtype=np.float64)
264
+ synthesis = window.astype(np.float64)
265
+ for index, frame in enumerate(reconstructed):
266
+ start = index * hop
267
+ output[start : start + frame_size] += frame * synthesis
268
+ weights[start : start + frame_size] += synthesis * synthesis
269
+ valid = weights > 1e-8
270
+ output[valid] /= weights[valid]
271
+ output = output[: source.size].astype(np.float32)
272
+ level = float(np.quantile(np.abs(output), 0.95))
273
+ if level > 1e-5:
274
+ amplification = min(6.0, max(0.5, 0.18 / level))
275
+ output = output * amplification
276
+ peak = float(np.max(np.abs(output)))
277
+ if peak > 0.95:
278
+ output = output * (0.95 / peak)
279
+ return np.clip(output, -1.0, 1.0).astype(np.float32)
280
+
281
+
282
+ def _retry_budget(sample_count: int, sample_rate: int = 16_000) -> int:
283
+ if sample_count < 1 or sample_rate < 1:
284
+ raise ValueError("invalid retry duration")
285
+ minutes = sample_count / sample_rate / 60
286
+ return min(_MAX_ENHANCED_RETRIES, max(1, math.ceil(minutes)))
287
+
288
+
289
+ def _semantic(value: str) -> str:
290
+ return "".join(character.casefold() for character in value if unicodedata.category(character)[0] in {"L", "N"})
291
+
292
+
293
+ def _looks_repetitive(value: str) -> bool:
294
+ compact = _semantic(value)
295
+ if len(compact) >= 12 and len(set(compact)) / len(compact) < 0.2:
296
+ return True
297
+ for width in range(1, min(16, len(compact) // 3 + 1)):
298
+ phrase = compact[:width]
299
+ if phrase and compact.count(phrase) >= 4 and len(phrase) * 4 >= len(compact) * 0.7:
300
+ return True
301
+ return False
302
+
303
+
304
+ def _confidence(probabilities: list[float]) -> tuple[float, float, float]:
305
+ if not probabilities:
306
+ return 0.0, 1.0, 0.0
307
+ mean = sum(probabilities) / len(probabilities)
308
+ low_ratio = sum(value < 0.5 for value in probabilities) / len(probabilities)
309
+ # The aggregate remains conservative even when a few high-confidence tokens
310
+ # hide an uncertain phrase. It is stored as phrase confidence downstream.
311
+ score = min(mean, 1.0 - low_ratio)
312
+ return mean, low_ratio, score
313
+
314
+
315
+ def _accept_candidate(text: str, probabilities: list[float], *, ended: bool) -> tuple[bool, float]:
316
+ compact = _semantic(text)
317
+ _mean, low_ratio, score = _confidence(probabilities)
318
+ if not ended or len(compact) < 2 or _looks_repetitive(text):
319
+ return False, score
320
+ # Token confidence can reject weak decoding and fluent hallucinations, but
321
+ # it cannot prove that audible speech belongs to the foreground subject.
322
+ # Capture stability is evaluated separately before downstream use.
323
+ return score >= 0.68 and low_ratio < 0.32, score
324
+
325
+
326
+ def _candidate(runtime, convert, audio) -> dict[str, object]:
327
+ text, probabilities, ended = _transcribe(runtime, audio)
328
+ text = convert(text).strip()
329
+ accepted, score = _accept_candidate(text, probabilities, ended=ended)
330
+ return {"text": text, "accepted": accepted, "score": score}
331
+
332
+
333
+ def _should_retry(candidate: dict[str, object], quality: dict[str, float | bool]) -> bool:
334
+ # Model confidence was high for several labelled Pocket 3 near-homophone
335
+ # errors. Capture quality, not model confidence alone, controls the bounded
336
+ # comparison pass.
337
+ del candidate
338
+ return bool(quality["needs_enhancement"])
339
+
340
+
341
+ def _choose_candidate(original: dict[str, object], enhanced: dict[str, object] | None) -> tuple[str, float] | None:
342
+ original_ok = bool(original["accepted"])
343
+ if enhanced is None:
344
+ return (str(original["text"]), float(original["score"])) if original_ok else None
345
+ enhanced_ok = bool(enhanced["accepted"])
346
+ if original_ok and enhanced_ok:
347
+ original_score = float(original["score"])
348
+ enhanced_score = float(enhanced["score"])
349
+ selected = enhanced if enhanced_score > original_score else original
350
+ if _semantic(str(original["text"])) == _semantic(str(enhanced["text"])):
351
+ return str(selected["text"]), max(original_score, enhanced_score)
352
+ # Enhancement is a disagreement detector, not an authority. Preserve
353
+ # the original capture's reading and make the uncertainty visible.
354
+ return str(original["text"]), min(original_score, _REVIEW_SCORE)
355
+ if original_ok:
356
+ return str(original["text"]), float(original["score"])
357
+ if enhanced_ok:
358
+ # Speech recovered only after processing must remain visibly reviewable.
359
+ return str(enhanced["text"]), min(float(enhanced["score"]), _REVIEW_SCORE)
360
+ return None
361
+
362
+
363
+ def _selection_needs_review(
364
+ original: dict[str, object],
365
+ enhanced: dict[str, object] | None,
366
+ quality: dict[str, float | bool],
367
+ ) -> bool:
368
+ """Require human review when weak capture has no stable second reading."""
369
+
370
+ if not bool(quality["needs_enhancement"]):
371
+ return False
372
+ original_ok = bool(original["accepted"])
373
+ enhanced_ok = enhanced is not None and bool(enhanced["accepted"])
374
+ if not original_ok and not enhanced_ok:
375
+ return False
376
+ return not (original_ok and enhanced_ok and _semantic(str(original["text"])) == _semantic(str(enhanced["text"])))
377
+
378
+
379
+ def _canonical_probability(value: float) -> str:
380
+ decimal = Decimal(str(round(max(0.0, min(1.0, value)), 6))).normalize()
381
+ return "0" if decimal == 0 else str(decimal)
382
+
383
+
384
+ def _transcribe(runtime, audio) -> tuple[str, list[float], bool]:
385
+ import mlx.core as mx
386
+ import numpy as np
387
+ from mlx_speech.generation.qwen3_asr import (
388
+ _first_token_id,
389
+ parse_asr_output,
390
+ replace_audio_embeddings,
391
+ )
392
+
393
+ features = runtime.processor.feature_extractor(audio, sample_rate=16_000)
394
+ audio_length = int(features.audio_lengths.reshape(-1)[0])
395
+ prompt = runtime.processor.build_prompt(context="", audio_length=audio_length, language="Chinese")
396
+ audio_features = runtime.model.get_audio_features(
397
+ mx.array(features.input_features, dtype=mx.float32),
398
+ feature_attention_mask=mx.array(features.feature_attention_mask, dtype=mx.int32),
399
+ )
400
+ mx.eval(audio_features)
401
+ input_ids = mx.array([prompt.input_ids], dtype=mx.int32)
402
+ embeddings = replace_audio_embeddings(
403
+ input_ids,
404
+ runtime.model.embed_input_ids(input_ids),
405
+ audio_features,
406
+ audio_token_id=runtime.config.audio_token_id,
407
+ )
408
+ prefill = runtime.model.prefill(
409
+ inputs_embeds=embeddings,
410
+ max_cache_len=len(prompt.input_ids) + _MAX_NEW_TOKENS,
411
+ )
412
+ mx.eval(prefill.logits)
413
+ if prefill.past_key_values is None:
414
+ raise RuntimeError("missing cache")
415
+ logits = prefill.logits
416
+ tokens: list[int] = []
417
+ probabilities: list[float] = []
418
+ eos = set(runtime.eos_token_ids)
419
+ ended = False
420
+ for _ in range(_MAX_NEW_TOKENS):
421
+ token = _first_token_id(mx.argmax(logits[:, -1, :], axis=-1))
422
+ if token in eos:
423
+ ended = True
424
+ break
425
+ probability = mx.softmax(logits[:, -1, :].astype(mx.float32), axis=-1)[0, token]
426
+ mx.eval(probability)
427
+ probabilities.append(float(np.asarray(probability)))
428
+ tokens.append(token)
429
+ step = runtime.model.decode_step(
430
+ input_ids=mx.array([[token]], dtype=mx.int32),
431
+ kv_cache=prefill.past_key_values,
432
+ )
433
+ mx.eval(step.logits)
434
+ logits = step.logits
435
+ raw = runtime.processor.tokenizer.decode(tokens, skip_special_tokens=True).strip()
436
+ _, text = parse_asr_output(raw, user_language=prompt.language)
437
+ return text.strip(), probabilities, ended
438
+
439
+
440
+ def _result(runtime, convert, audio: Path) -> dict[str, object]:
441
+ samples = _read_audio(audio)
442
+ windows: list[dict[str, object]] = []
443
+ for start_sample, end_sample in _window_ranges(samples):
444
+ window = samples[start_sample:end_sample]
445
+ if not _has_audible_activity(window):
446
+ continue
447
+ quality = _audio_quality(window)
448
+ original = _candidate(runtime, convert, window)
449
+ windows.append(
450
+ {
451
+ "start": start_sample,
452
+ "end": end_sample,
453
+ "audio": window,
454
+ "quality": quality,
455
+ "original": original,
456
+ "enhanced": None,
457
+ }
458
+ )
459
+ eligible = [
460
+ (index, record)
461
+ for index, record in enumerate(windows)
462
+ if _should_retry(record["original"], record["quality"]) # type: ignore[arg-type]
463
+ ]
464
+ eligible.sort(
465
+ key=lambda item: (
466
+ bool(item[1]["original"]["accepted"]), # type: ignore[index]
467
+ float(item[1]["quality"]["active_ratio"]), # type: ignore[index]
468
+ float(item[1]["original"]["score"]), # type: ignore[index]
469
+ ),
470
+ reverse=True,
471
+ )
472
+ for index, _record in eligible[: _retry_budget(int(samples.shape[0]))]:
473
+ record = windows[index]
474
+ enhanced_audio = _enhance_for_speech(
475
+ record["audio"],
476
+ record["quality"], # type: ignore[arg-type]
477
+ )
478
+ record["enhanced"] = _candidate(runtime, convert, enhanced_audio)
479
+
480
+ selections: list[tuple[dict[str, object], str, float, bool]] = []
481
+ for record in windows:
482
+ selected = _choose_candidate(
483
+ record["original"],
484
+ record["enhanced"], # type: ignore[arg-type]
485
+ )
486
+ if selected is None:
487
+ continue
488
+ text, score = selected
489
+ selections.append(
490
+ (
491
+ record,
492
+ text,
493
+ score,
494
+ _selection_needs_review(
495
+ record["original"], # type: ignore[arg-type]
496
+ record["enhanced"], # type: ignore[arg-type]
497
+ record["quality"], # type: ignore[arg-type]
498
+ ),
499
+ )
500
+ )
501
+
502
+ # One uncertain phrase makes the whole transcript unsafe for automatic
503
+ # downstream use. Cap every phrase so averaging cannot hide that fact.
504
+ transcript_needs_review = any(selection[3] for selection in selections)
505
+ segments: list[dict[str, object]] = []
506
+ for record, text, score, _needs_review in selections:
507
+ if transcript_needs_review:
508
+ score = min(score, _REVIEW_SCORE)
509
+ start_sample = int(record["start"])
510
+ end_sample = int(record["end"])
511
+ start = start_sample / 16_000
512
+ end = end_sample / 16_000
513
+ probability = _canonical_probability(score)
514
+ segments.append(
515
+ {
516
+ "start": start,
517
+ "end": end,
518
+ "text": text,
519
+ "no_speech_probability": None,
520
+ # Qwen3-ASR does not expose word timestamps. A single phrase
521
+ # span retains confidence without inventing per-word timing.
522
+ "words": [
523
+ {
524
+ "start": start,
525
+ "end": end,
526
+ "text": text,
527
+ "probability": probability,
528
+ }
529
+ ],
530
+ }
531
+ )
532
+ return {
533
+ "language": "zh",
534
+ "text": "\n".join(str(segment["text"]) for segment in segments),
535
+ "segments": segments,
536
+ }
537
+
538
+
539
+ def _load_runtime(model: Path):
540
+ import mlx_speech
541
+
542
+ return mlx_speech.asr.load(str(model))._runtime
543
+
544
+
545
+ def _serve(model: Path) -> int:
546
+ from opencc import OpenCC
547
+
548
+ runtime = _load_runtime(model)
549
+ convert = OpenCC("s2twp").convert
550
+ _response({"type": "ready", "qwen3_asr_runtime": "mlx-speech-0.5.2"})
551
+ while line := sys.stdin.buffer.readline(_MAX_REQUEST_BYTES + 1):
552
+ if len(line) > _MAX_REQUEST_BYTES or not line.endswith(b"\n"):
553
+ return 2
554
+ try:
555
+ request = json.loads(line)
556
+ if not isinstance(request, dict) or set(request) != {
557
+ "audio",
558
+ "initial_prompt",
559
+ "language",
560
+ "output",
561
+ }:
562
+ raise ValueError("invalid request")
563
+ if request["language"] != "zh" or request["initial_prompt"] is not None:
564
+ raise ValueError("unsupported request")
565
+ audio = _regular(request["audio"])
566
+ output = _regular(request["output"])
567
+ if output.stat().st_size != 0:
568
+ raise ValueError("unsafe output")
569
+ _write_result(output, _result(runtime, convert, audio))
570
+ _response({"type": "result", "ok": True})
571
+ except (KeyError, OSError, TypeError, ValueError, wave.Error):
572
+ _response({"type": "result", "ok": False, "code": "asr_request_invalid"})
573
+ except Exception:
574
+ _response({"type": "result", "ok": False, "code": "asr_failed"})
575
+ return 0
576
+
577
+
578
+ def main() -> int:
579
+ arguments = _arguments()
580
+ model = _regular(arguments.model, directory=True)
581
+ _model_files(model)
582
+ if arguments.probe:
583
+ mlx_version = importlib.metadata.version("mlx")
584
+ speech_version = importlib.metadata.version("mlx-speech")
585
+ opencc_version = importlib.metadata.version("opencc-python-reimplemented")
586
+ _response({"qwen3_asr_runtime": (f"mlx-speech-{speech_version}+mlx-{mlx_version}+opencc-{opencc_version}")})
587
+ return 0
588
+ if arguments.serve:
589
+ return _serve(model)
590
+ return 2
591
+
592
+
593
+ if __name__ == "__main__":
594
+ raise SystemExit(main())
@@ -0,0 +1,22 @@
1
+ """Keep local FFmpeg and ASR subprocesses from competing for memory/compute."""
2
+
3
+ import threading
4
+ from contextlib import contextmanager
5
+ from typing import Callable, Iterator
6
+
7
+ _SLOT = threading.Lock()
8
+
9
+
10
+ @contextmanager
11
+ def local_analysis_slot(cancel: threading.Event | None, error: Callable[[], Exception]) -> Iterator[None]:
12
+ while True:
13
+ if cancel is not None and cancel.is_set():
14
+ raise error()
15
+ if _SLOT.acquire(timeout=0.05):
16
+ break
17
+ try:
18
+ if cancel is not None and cancel.is_set():
19
+ raise error()
20
+ yield
21
+ finally:
22
+ _SLOT.release()
@@ -0,0 +1,62 @@
1
+ """Lazy lifecycle binding between managed ASR setup and media preparation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import threading
6
+
7
+ from .artifacts import ArtifactStore
8
+ from .service import PreparationCoordinator
9
+ from .setup import ASRSetupManager, ASRSetupStatus
10
+ from .storage import PreparationRepository
11
+
12
+
13
+ class ManagedAnalysisRuntime:
14
+ """Creates the heavy coordinator only after the verified runtime is ready."""
15
+
16
+ def __init__(
17
+ self,
18
+ repository: PreparationRepository,
19
+ artifacts: ArtifactStore,
20
+ setup: ASRSetupManager,
21
+ ) -> None:
22
+ self.repository = repository
23
+ self._artifacts = artifacts
24
+ self._setup = setup
25
+ self._lock = threading.Lock()
26
+ self._coordinator: PreparationCoordinator | None = None
27
+
28
+ def public_status(self) -> dict[str, object]:
29
+ return self._setup.public_status()
30
+
31
+ def coordinator(self) -> PreparationCoordinator | None:
32
+ with self._lock:
33
+ if self._coordinator is not None:
34
+ return self._coordinator
35
+ binding = self._setup.runtime_binding()
36
+ if binding is None:
37
+ return None
38
+ factory, model = binding
39
+ self._coordinator = PreparationCoordinator(
40
+ self.repository,
41
+ self._artifacts,
42
+ transcriber_factory=factory,
43
+ model=model,
44
+ )
45
+ return self._coordinator
46
+
47
+ def remove(self) -> ASRSetupStatus:
48
+ with self._lock:
49
+ coordinator = self._coordinator
50
+ self._coordinator = None
51
+ return self._setup.remove(None if coordinator is None else lambda: coordinator.close(timeout=15))
52
+
53
+ def close(self) -> None:
54
+ self._setup.close()
55
+ with self._lock:
56
+ coordinator = self._coordinator
57
+ self._coordinator = None
58
+ if coordinator is not None:
59
+ coordinator.close(timeout=15)
60
+
61
+
62
+ __all__ = ["ManagedAnalysisRuntime"]