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