@clipen/clipen-cli 1.0.0 → 1.0.2

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 (132) hide show
  1. package/README.md +56 -48
  2. package/apps/web/dist/assets/{index-D5D2HiB1.js → index-DPHwA954.js} +1 -1
  3. package/apps/web/dist/index.html +1 -1
  4. package/bin/clipen.js +1 -1
  5. package/package.json +7 -6
  6. package/pyproject.toml +18 -2
  7. package/requirements/dev.txt +2 -0
  8. package/src/clipen/__init__.py +1 -1
  9. package/src/clipen/analysis/__init__.py +7 -7
  10. package/src/clipen/analysis/artifacts.py +4 -10
  11. package/src/clipen/analysis/audio.py +10 -8
  12. package/src/clipen/analysis/evidence_service.py +345 -167
  13. package/src/clipen/analysis/image_similarity.py +5 -14
  14. package/src/clipen/analysis/keyframes.py +5 -17
  15. package/src/clipen/analysis/models.py +5 -7
  16. package/src/clipen/analysis/qwen_worker.py +19 -54
  17. package/src/clipen/analysis/resources.py +2 -1
  18. package/src/clipen/analysis/runtime.py +1 -3
  19. package/src/clipen/analysis/service.py +16 -48
  20. package/src/clipen/analysis/setup.py +11 -25
  21. package/src/clipen/analysis/setup_cli.py +5 -15
  22. package/src/clipen/analysis/storage.py +96 -278
  23. package/src/clipen/analysis/transcription.py +40 -82
  24. package/src/clipen/analysis/visual.py +109 -48
  25. package/src/clipen/annotations/__init__.py +5 -2
  26. package/src/clipen/annotations/models.py +1 -1
  27. package/src/clipen/annotations/storage.py +132 -84
  28. package/src/clipen/annotations/suggestions.py +3 -8
  29. package/src/clipen/asr_release.py +4 -11
  30. package/src/clipen/bootstrap.py +71 -61
  31. package/src/clipen/{planning/models.py → candidates.py} +29 -47
  32. package/src/clipen/cli.py +4 -9
  33. package/src/clipen/controller/app.py +401 -214
  34. package/src/clipen/controller/server.py +28 -38
  35. package/src/clipen/domain/__init__.py +1 -1
  36. package/src/clipen/domain/media_time.py +3 -10
  37. package/src/clipen/domain/timeline.py +45 -47
  38. package/src/clipen/domain/validation.py +0 -1
  39. package/src/clipen/editing/__init__.py +1 -1
  40. package/src/clipen/editing/agent_models.py +4 -11
  41. package/src/clipen/editing/agent_repository.py +393 -172
  42. package/src/clipen/editing/agent_tools.py +180 -99
  43. package/src/clipen/editing/alignment.py +92 -52
  44. package/src/clipen/editing/alignment_setup.py +118 -70
  45. package/src/clipen/editing/alignment_worker.py +11 -9
  46. package/src/clipen/editing/change_report.py +95 -38
  47. package/src/clipen/editing/compiler.py +0 -1
  48. package/src/clipen/editing/component_looks.py +58 -34
  49. package/src/clipen/editing/component_review.py +34 -38
  50. package/src/clipen/editing/coordinator.py +213 -92
  51. package/src/clipen/editing/editorial_review.py +217 -95
  52. package/src/clipen/editing/evidence_jobs.py +457 -200
  53. package/src/clipen/editing/history_changes.py +129 -68
  54. package/src/clipen/editing/music_choices.py +8 -5
  55. package/src/clipen/editing/production_catalog.py +573 -136
  56. package/src/clipen/editing/production_limits.py +43 -17
  57. package/src/clipen/editing/production_media.py +376 -167
  58. package/src/clipen/editing/production_preview.py +322 -129
  59. package/src/clipen/editing/production_progress.py +164 -69
  60. package/src/clipen/editing/production_requirements.py +106 -39
  61. package/src/clipen/editing/production_tools.py +1064 -462
  62. package/src/clipen/editing/program_audio.py +211 -81
  63. package/src/clipen/editing/program_direction.py +59 -25
  64. package/src/clipen/editing/program_story.py +83 -45
  65. package/src/clipen/editing/program_subtitles.py +194 -96
  66. package/src/clipen/editing/programme_review.py +98 -50
  67. package/src/clipen/editing/prompt_history.py +64 -27
  68. package/src/clipen/editing/recut.py +65 -25
  69. package/src/clipen/editing/refinement_references.py +176 -86
  70. package/src/clipen/editing/resolve_export.py +449 -218
  71. package/src/clipen/editing/resolve_titles.py +162 -105
  72. package/src/clipen/editing/skill_tools.py +530 -154
  73. package/src/clipen/editing/source_dialogue.py +177 -67
  74. package/src/clipen/editing/speech_coverage.py +42 -22
  75. package/src/clipen/editing/speech_quality.py +6 -1
  76. package/src/clipen/editing/tool_receipts.py +78 -32
  77. package/src/clipen/editing/versions.py +122 -64
  78. package/src/clipen/editing/visual_preview.py +157 -61
  79. package/src/clipen/editing/workbench.py +104 -42
  80. package/src/clipen/finishing/audio.py +69 -30
  81. package/src/clipen/finishing/catalog.py +176 -93
  82. package/src/clipen/finishing/models.py +1 -1
  83. package/src/clipen/finishing/renderer.py +33 -14
  84. package/src/clipen/mcp_editing/__main__.py +3 -1
  85. package/src/clipen/mcp_editing/server.py +77 -34
  86. package/src/clipen/media/__init__.py +3 -3
  87. package/src/clipen/media/discovery.py +7 -20
  88. package/src/clipen/media/models.py +7 -18
  89. package/src/clipen/media/preview.py +14 -24
  90. package/src/clipen/media/probe.py +16 -44
  91. package/src/clipen/media/service.py +6 -19
  92. package/src/clipen/media/storage.py +33 -81
  93. package/src/clipen/music_vocabulary.py +33 -4
  94. package/src/clipen/power.py +8 -3
  95. package/src/clipen/projects/__init__.py +1 -1
  96. package/src/clipen/projects/deletion.py +19 -32
  97. package/src/clipen/projects/finishing_schema.py +3 -1
  98. package/src/clipen/projects/models.py +2 -5
  99. package/src/clipen/projects/picker.py +13 -37
  100. package/src/clipen/projects/service.py +8 -24
  101. package/src/clipen/projects/storage.py +226 -246
  102. package/src/clipen/provider_registry.py +9 -20
  103. package/src/clipen/providers/account.py +86 -35
  104. package/src/clipen/providers/claude.py +59 -25
  105. package/src/clipen/providers/claude_editing.py +14 -7
  106. package/src/clipen/providers/codex.py +73 -118
  107. package/src/clipen/providers/codex_editing.py +2 -2
  108. package/src/clipen/providers/editing_agent.py +19 -17
  109. package/src/clipen/providers/recovery.py +7 -8
  110. package/src/clipen/rendering/cover.py +18 -5
  111. package/src/clipen/rendering/custom_components.py +167 -79
  112. package/src/clipen/rendering/custom_render.py +62 -41
  113. package/src/clipen/rendering/production_effects.py +77 -45
  114. package/src/clipen/rendering/program_components.py +134 -73
  115. package/src/clipen/rendering/program_creator.py +432 -277
  116. package/src/clipen/rendering/program_identities.py +277 -182
  117. package/src/clipen/rendering/program_motion.py +140 -95
  118. package/src/clipen/rendering/program_studio.py +175 -116
  119. package/src/clipen/rendering/program_styles.py +231 -145
  120. package/src/clipen/rendering/program_subtitles.py +71 -34
  121. package/src/clipen/rendering/renderer.py +150 -121
  122. package/src/clipen/rendering/storage.py +9 -22
  123. package/src/clipen/rendering/titles.py +193 -86
  124. package/src/clipen/skills/__init__.py +1 -0
  125. package/src/clipen/skills/catalog.py +151 -55
  126. package/src/clipen/skills/library.py +13 -7
  127. package/src/clipen/skills/package.py +46 -23
  128. package/src/clipen/skills/visual_styles.py +29 -18
  129. package/src/clipen/workspace.py +15 -44
  130. package/install +0 -25
  131. package/src/clipen/planning/__init__.py +0 -9
  132. package/uninstall +0 -25
@@ -2,11 +2,10 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
- from dataclasses import dataclass
6
- from pathlib import Path
7
5
  import struct
8
6
  import zlib
9
-
7
+ from dataclasses import dataclass
8
+ from pathlib import Path
10
9
 
11
10
  _PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"
12
11
  _GRID_SIZE = 8
@@ -21,9 +20,7 @@ class VisualFingerprint:
21
20
  if len(self.cells) != len(other.cells):
22
21
  return False
23
22
  mean_delta = abs(self.mean_luma - other.mean_luma) / 255
24
- cell_delta = sum(abs(a - b) for a, b in zip(self.cells, other.cells)) / (
25
- len(self.cells) * 255
26
- )
23
+ cell_delta = sum(abs(a - b) for a, b in zip(self.cells, other.cells)) / (len(self.cells) * 255)
27
24
  return mean_delta <= 0.10 and cell_delta <= 0.085
28
25
 
29
26
 
@@ -66,9 +63,7 @@ def _decode_rgb8_png(data: bytes) -> tuple[int, int, bytes]:
66
63
  if kind == b"IHDR":
67
64
  if len(payload) != 13:
68
65
  raise ValueError("preview PNG header is invalid")
69
- width, height, depth, color, compression, filtering, interlace = struct.unpack(
70
- ">IIBBBBB", payload
71
- )
66
+ width, height, depth, color, compression, filtering, interlace = struct.unpack(">IIBBBBB", payload)
72
67
  if (
73
68
  not width
74
69
  or not height
@@ -96,11 +91,7 @@ def _decode_rgb8_png(data: bytes) -> tuple[int, int, bytes]:
96
91
  decoded = decompressor.decompress(bytes(compressed), expected_size + 1)
97
92
  except zlib.error as error:
98
93
  raise ValueError("preview PNG compression is invalid") from error
99
- if (
100
- len(decoded) != expected_size
101
- or not decompressor.eof
102
- or decompressor.unconsumed_tail
103
- ):
94
+ if len(decoded) != expected_size or not decompressor.eof or decompressor.unconsumed_tail:
104
95
  raise ValueError("preview PNG data length is invalid")
105
96
  rows: list[bytearray] = []
106
97
  for row_index in range(height):
@@ -8,8 +8,8 @@ or copy code from the unlicensed reference repository.
8
8
 
9
9
  from __future__ import annotations
10
10
 
11
- from dataclasses import dataclass
12
11
  import math
12
+ from dataclasses import dataclass
13
13
  from typing import Iterable
14
14
 
15
15
 
@@ -65,11 +65,7 @@ class AdaptiveKeyframeSelector:
65
65
  or end_pts <= start_pts
66
66
  ):
67
67
  raise ValueError("keyframe source span is invalid")
68
- if (
69
- isinstance(budget, bool)
70
- or not isinstance(budget, int)
71
- or not 1 <= budget <= self.MAXIMUM_BUDGET
72
- ):
68
+ if isinstance(budget, bool) or not isinstance(budget, int) or not 1 <= budget <= self.MAXIMUM_BUDGET:
73
69
  raise ValueError("keyframe budget is invalid")
74
70
 
75
71
  deduplicated: dict[int, KeyframeCandidate] = {}
@@ -116,10 +112,7 @@ class AdaptiveKeyframeSelector:
116
112
  if end_pts <= start_pts or isinstance(count, bool) or not 1 <= count <= 256:
117
113
  raise ValueError("uniform keyframe request is invalid")
118
114
  duration = end_pts - start_pts
119
- points = {
120
- start_pts + duration * (index * 2 + 1) // (count * 2)
121
- for index in range(count)
122
- }
115
+ points = {start_pts + duration * (index * 2 + 1) // (count * 2) for index in range(count)}
123
116
  return tuple(KeyframeCandidate(point, 0.0, "uniform") for point in sorted(points))
124
117
 
125
118
  def _choose(
@@ -138,9 +131,7 @@ class AdaptiveKeyframeSelector:
138
131
  return (max(candidates, key=lambda item: (item.score, -abs(item.pts - center), -item.pts)),)
139
132
 
140
133
  top = sorted(candidates, key=lambda item: (-item.score, abs(item.pts - center), item.pts))[:quota]
141
- advantage = sum(item.score for item in top) / quota - sum(
142
- item.score for item in candidates
143
- ) / len(candidates)
134
+ advantage = sum(item.score for item in top) / quota - sum(item.score for item in candidates) / len(candidates)
144
135
  if (allow_relevance_focus and advantage >= self.split_threshold) or depth >= self.maximum_depth:
145
136
  return tuple(top)
146
137
 
@@ -158,9 +149,7 @@ class AdaptiveKeyframeSelector:
158
149
  if len(right) < right_quota:
159
150
  left_quota += right_quota - len(right)
160
151
  right_quota = len(right)
161
- return self._choose(
162
- left, left_quota, lower, midpoint, depth + 1, allow_relevance_focus
163
- ) + self._choose(
152
+ return self._choose(left, left_quota, lower, midpoint, depth + 1, allow_relevance_focus) + self._choose(
164
153
  right, right_quota, midpoint, upper, depth + 1, allow_relevance_focus
165
154
  )
166
155
 
@@ -168,4 +157,3 @@ class AdaptiveKeyframeSelector:
168
157
  def _priority(candidate: KeyframeCandidate) -> tuple[float, int]:
169
158
  source_priority = {"uniform": 0, "codec": 1, "semantic": 2}
170
159
  return float(candidate.score), source_priority[candidate.source]
171
-
@@ -2,16 +2,16 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
- from dataclasses import dataclass
6
- from enum import Enum
7
5
  import json
8
6
  import re
7
+ from dataclasses import dataclass
8
+ from enum import Enum
9
9
  from typing import Mapping
10
10
 
11
- from clipen.domain.media_time import Rational, SourceSpan
11
+ from clipen.domain.media_time import Rational as Rational # re-exported for the analysis modules
12
+ from clipen.domain.media_time import SourceSpan
12
13
  from clipen.projects.models import validate_project_id
13
14
 
14
-
15
15
  _ARTIFACT_ID = re.compile(r"art_[0-9a-f]{32}\Z")
16
16
  _PREPARATION_ID = re.compile(r"prep_[0-9a-f]{32}\Z")
17
17
  _OPERATION_ID = re.compile(r"op_[0-9a-f]{32}\Z")
@@ -124,9 +124,7 @@ class PreparationRun:
124
124
  raise ValueError("preparation input identity is invalid")
125
125
  if not re.fullmatch(r"[a-z][a-z0-9_]{0,63}", self.phase):
126
126
  raise ValueError("preparation phase is invalid")
127
- if self.error_code is not None and not re.fullmatch(
128
- r"[a-z][a-z0-9_]{0,63}", self.error_code
129
- ):
127
+ if self.error_code is not None and not re.fullmatch(r"[a-z][a-z0-9_]{0,63}", self.error_code):
130
128
  raise ValueError("preparation error code is invalid")
131
129
  terminal = self.state in {
132
130
  PreparationState.SUCCEEDED,
@@ -3,17 +3,16 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  import argparse
6
- from decimal import Decimal
7
6
  import importlib.metadata
8
7
  import json
9
8
  import math
10
9
  import os
11
- from pathlib import Path
12
10
  import stat
13
11
  import sys
14
12
  import unicodedata
15
13
  import wave
16
-
14
+ from decimal import Decimal
15
+ from pathlib import Path
17
16
 
18
17
  _MAX_REQUEST_BYTES = 64 * 1024
19
18
  _MAX_CAPTURE_BYTES = 32 * 1024 * 1024
@@ -72,9 +71,7 @@ def _write_result(path: Path, value: dict[str, object]) -> None:
72
71
  info = os.fstat(descriptor)
73
72
  if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1:
74
73
  raise ValueError("unsafe output")
75
- encoded = json.dumps(
76
- value, ensure_ascii=False, sort_keys=True, separators=(",", ":")
77
- ).encode("utf-8")
74
+ encoded = json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode("utf-8")
78
75
  if len(encoded) > _MAX_CAPTURE_BYTES:
79
76
  raise ValueError("result too large")
80
77
  with os.fdopen(descriptor, "wb", closefd=False) as output:
@@ -98,9 +95,7 @@ def _read_audio(path: Path):
98
95
  raise ValueError("unsupported audio")
99
96
  frame_count = audio.getnframes()
100
97
  duration = frame_count / audio.getframerate()
101
- samples = np.frombuffer(audio.readframes(frame_count), dtype="<i2").astype(
102
- np.float32
103
- ) / 32768.0
98
+ samples = np.frombuffer(audio.readframes(frame_count), dtype="<i2").astype(np.float32) / 32768.0
104
99
  if duration > _MAX_AUDIO_SECONDS:
105
100
  raise ValueError("audio chunk too long")
106
101
  return samples
@@ -115,9 +110,7 @@ def _window_ranges(samples, sample_rate: int = 16_000) -> list[tuple[int, int]]:
115
110
  usable = int(samples.shape[0]) // search_frame * search_frame
116
111
  frames = samples[:usable].reshape(-1, search_frame)
117
112
  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
- )
113
+ return _window_ranges_from_energy(int(samples.shape[0]), energies, search_frame, sample_rate)
121
114
 
122
115
 
123
116
  def _window_ranges_from_energy(
@@ -164,9 +157,7 @@ def _has_audible_activity(samples, sample_rate: int = 16_000) -> bool:
164
157
  return _audible_from_rms(rms.tolist(), int(samples.shape[0]), sample_rate)
165
158
 
166
159
 
167
- def _audible_from_rms(
168
- rms: list[float], sample_count: int, sample_rate: int = 16_000
169
- ) -> bool:
160
+ def _audible_from_rms(rms: list[float], sample_count: int, sample_rate: int = 16_000) -> bool:
170
161
  if sample_count < sample_rate // 2 or not rms:
171
162
  return False
172
163
  return max(rms) >= 0.006 and sum(value >= 0.003 for value in rms) / len(rms) >= 0.02
@@ -185,9 +176,7 @@ def _percentile(values: list[float], fraction: float) -> float:
185
176
  return ordered[lower] * (1 - weight) + ordered[upper] * weight
186
177
 
187
178
 
188
- def _quality_from_rms(
189
- rms: list[float], *, peak: float, clipping_ratio: float
190
- ) -> dict[str, float | bool]:
179
+ def _quality_from_rms(rms: list[float], *, peak: float, clipping_ratio: float) -> dict[str, float | bool]:
191
180
  """Summarize capture quality without claiming that energy equals speech."""
192
181
 
193
182
  if (
@@ -298,11 +287,7 @@ def _retry_budget(sample_count: int, sample_rate: int = 16_000) -> int:
298
287
 
299
288
 
300
289
  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
- )
290
+ return "".join(character.casefold() for character in value if unicodedata.category(character)[0] in {"L", "N"})
306
291
 
307
292
 
308
293
  def _looks_repetitive(value: str) -> bool:
@@ -327,9 +312,7 @@ def _confidence(probabilities: list[float]) -> tuple[float, float, float]:
327
312
  return mean, low_ratio, score
328
313
 
329
314
 
330
- def _accept_candidate(
331
- text: str, probabilities: list[float], *, ended: bool
332
- ) -> tuple[bool, float]:
315
+ def _accept_candidate(text: str, probabilities: list[float], *, ended: bool) -> tuple[bool, float]:
333
316
  compact = _semantic(text)
334
317
  _mean, low_ratio, score = _confidence(probabilities)
335
318
  if not ended or len(compact) < 2 or _looks_repetitive(text):
@@ -347,9 +330,7 @@ def _candidate(runtime, convert, audio) -> dict[str, object]:
347
330
  return {"text": text, "accepted": accepted, "score": score}
348
331
 
349
332
 
350
- def _should_retry(
351
- candidate: dict[str, object], quality: dict[str, float | bool]
352
- ) -> bool:
333
+ def _should_retry(candidate: dict[str, object], quality: dict[str, float | bool]) -> bool:
353
334
  # Model confidence was high for several labelled Pocket 3 near-homophone
354
335
  # errors. Capture quality, not model confidence alone, controls the bounded
355
336
  # comparison pass.
@@ -357,16 +338,10 @@ def _should_retry(
357
338
  return bool(quality["needs_enhancement"])
358
339
 
359
340
 
360
- def _choose_candidate(
361
- original: dict[str, object], enhanced: dict[str, object] | None
362
- ) -> tuple[str, float] | None:
341
+ def _choose_candidate(original: dict[str, object], enhanced: dict[str, object] | None) -> tuple[str, float] | None:
363
342
  original_ok = bool(original["accepted"])
364
343
  if enhanced is None:
365
- return (
366
- (str(original["text"]), float(original["score"]))
367
- if original_ok
368
- else None
369
- )
344
+ return (str(original["text"]), float(original["score"])) if original_ok else None
370
345
  enhanced_ok = bool(enhanced["accepted"])
371
346
  if original_ok and enhanced_ok:
372
347
  original_score = float(original["score"])
@@ -398,11 +373,7 @@ def _selection_needs_review(
398
373
  enhanced_ok = enhanced is not None and bool(enhanced["accepted"])
399
374
  if not original_ok and not enhanced_ok:
400
375
  return False
401
- return not (
402
- original_ok
403
- and enhanced_ok
404
- and _semantic(str(original["text"])) == _semantic(str(enhanced["text"]))
405
- )
376
+ return not (original_ok and enhanced_ok and _semantic(str(original["text"])) == _semantic(str(enhanced["text"])))
406
377
 
407
378
 
408
379
  def _canonical_probability(value: float) -> str:
@@ -421,9 +392,7 @@ def _transcribe(runtime, audio) -> tuple[str, list[float], bool]:
421
392
 
422
393
  features = runtime.processor.feature_extractor(audio, sample_rate=16_000)
423
394
  audio_length = int(features.audio_lengths.reshape(-1)[0])
424
- prompt = runtime.processor.build_prompt(
425
- context="", audio_length=audio_length, language="Chinese"
426
- )
395
+ prompt = runtime.processor.build_prompt(context="", audio_length=audio_length, language="Chinese")
427
396
  audio_features = runtime.model.get_audio_features(
428
397
  mx.array(features.input_features, dtype=mx.float32),
429
398
  feature_attention_mask=mx.array(features.feature_attention_mask, dtype=mx.int32),
@@ -503,14 +472,16 @@ def _result(runtime, convert, audio: Path) -> dict[str, object]:
503
472
  for index, _record in eligible[: _retry_budget(int(samples.shape[0]))]:
504
473
  record = windows[index]
505
474
  enhanced_audio = _enhance_for_speech(
506
- record["audio"], record["quality"] # type: ignore[arg-type]
475
+ record["audio"],
476
+ record["quality"], # type: ignore[arg-type]
507
477
  )
508
478
  record["enhanced"] = _candidate(runtime, convert, enhanced_audio)
509
479
 
510
480
  selections: list[tuple[dict[str, object], str, float, bool]] = []
511
481
  for record in windows:
512
482
  selected = _choose_candidate(
513
- record["original"], record["enhanced"] # type: ignore[arg-type]
483
+ record["original"],
484
+ record["enhanced"], # type: ignore[arg-type]
514
485
  )
515
486
  if selected is None:
516
487
  continue
@@ -612,13 +583,7 @@ def main() -> int:
612
583
  mlx_version = importlib.metadata.version("mlx")
613
584
  speech_version = importlib.metadata.version("mlx-speech")
614
585
  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
- )
586
+ _response({"qwen3_asr_runtime": (f"mlx-speech-{speech_version}+mlx-{mlx_version}+opencc-{opencc_version}")})
622
587
  return 0
623
588
  if arguments.serve:
624
589
  return _serve(model)
@@ -1,6 +1,7 @@
1
1
  """Keep local FFmpeg and ASR subprocesses from competing for memory/compute."""
2
- from contextlib import contextmanager
2
+
3
3
  import threading
4
+ from contextlib import contextmanager
4
5
  from typing import Callable, Iterator
5
6
 
6
7
  _SLOT = threading.Lock()
@@ -48,9 +48,7 @@ class ManagedAnalysisRuntime:
48
48
  with self._lock:
49
49
  coordinator = self._coordinator
50
50
  self._coordinator = None
51
- return self._setup.remove(
52
- None if coordinator is None else lambda: coordinator.close(timeout=15)
53
- )
51
+ return self._setup.remove(None if coordinator is None else lambda: coordinator.close(timeout=15))
54
52
 
55
53
  def close(self) -> None:
56
54
  self._setup.close()
@@ -2,11 +2,11 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
- from dataclasses import dataclass
6
5
  import json
7
- from pathlib import Path
8
6
  import queue
9
7
  import threading
8
+ from dataclasses import dataclass
9
+ from pathlib import Path
10
10
  from typing import Callable, Iterable, Mapping, Protocol
11
11
 
12
12
  from clipen.projects.models import ProjectError
@@ -35,9 +35,7 @@ from .transcription import TranscriptionError, TranscriptionResult
35
35
  class _AudioAdapter(Protocol):
36
36
  def version(self) -> str: ...
37
37
 
38
- def extract(
39
- self, source, output: Path, cancel: threading.Event | None = None
40
- ) -> PreparedAudio: ...
38
+ def extract(self, source, output: Path, cancel: threading.Event | None = None) -> PreparedAudio: ...
41
39
 
42
40
 
43
41
  class _Transcriber(Protocol):
@@ -72,10 +70,7 @@ class PreparationRecipe:
72
70
  not isinstance(self.vocabulary, tuple)
73
71
  or len(self.vocabulary) > 40
74
72
  or any(
75
- not isinstance(term, str)
76
- or not term.strip()
77
- or term != term.strip()
78
- or len(term) > 40
73
+ not isinstance(term, str) or not term.strip() or term != term.strip() or len(term) > 40
79
74
  for term in self.vocabulary
80
75
  )
81
76
  or len(set(self.vocabulary)) != len(self.vocabulary)
@@ -102,9 +97,7 @@ class PreparationRecipe:
102
97
  @classmethod
103
98
  def from_storage(cls, value: Mapping[str, object]) -> "PreparationRecipe":
104
99
  vocabulary = value.get("vocabulary", [])
105
- if not isinstance(vocabulary, list) or any(
106
- not isinstance(term, str) for term in vocabulary
107
- ):
100
+ if not isinstance(vocabulary, list) or any(not isinstance(term, str) for term in vocabulary):
108
101
  raise ValueError("stored preparation vocabulary is invalid")
109
102
  return cls(
110
103
  audio_recipe_id=str(value.get("audio_recipe_id", "")),
@@ -170,11 +163,7 @@ class PreparationCoordinator:
170
163
  raise ValueError("language must be a string")
171
164
  if not isinstance(vocabulary, (list, tuple)):
172
165
  raise ValueError("vocabulary must be a list")
173
- normalized_vocabulary = tuple(
174
- term.strip()
175
- for term in vocabulary
176
- if isinstance(term, str) and term.strip()
177
- )
166
+ normalized_vocabulary = tuple(term.strip() for term in vocabulary if isinstance(term, str) and term.strip())
178
167
  if len(normalized_vocabulary) != len(vocabulary):
179
168
  raise ValueError("vocabulary entries are invalid")
180
169
  recipe = PreparationRecipe(
@@ -295,9 +284,7 @@ class PreparationCoordinator:
295
284
  if self._shutdown.is_set():
296
285
  self._interrupt(job, "controller_stopped")
297
286
  return
298
- recipe = PreparationRecipe.from_storage(
299
- self.repository.recipe(job.project_id, job.run_id)
300
- )
287
+ recipe = PreparationRecipe.from_storage(self.repository.recipe(job.project_id, job.run_id))
301
288
  run = self.repository.transition(
302
289
  job.project_id,
303
290
  job.run_id,
@@ -319,9 +306,7 @@ class PreparationCoordinator:
319
306
  PreparationItemStatus.NO_SPEECH,
320
307
  }:
321
308
  continue
322
- self._process_item(
323
- job, run, item, audio_adapter, transcriber, cancel, recipe
324
- )
309
+ self._process_item(job, run, item, audio_adapter, transcriber, cancel, recipe)
325
310
  if cancel.is_set():
326
311
  self._finish_cancel_or_interrupt(job)
327
312
  return
@@ -389,14 +374,10 @@ class PreparationCoordinator:
389
374
  checkpoint={"audio_ready": True},
390
375
  )
391
376
  if artifact_id is None:
392
- raise ProjectError(
393
- "storage_corrupt", "Clipen 找不到已準備的音訊。", status_code=500
394
- )
377
+ raise ProjectError("storage_corrupt", "Clipen 找不到已準備的音訊。", status_code=500)
395
378
  audio_record = self.artifacts.get(job.project_id, artifact_id)
396
379
  prepared = inspect_normalized_audio(self.artifacts.path(audio_record))
397
- chunker = PCMChunker(
398
- chunk_seconds=recipe.chunk_seconds, overlap_seconds=0
399
- )
380
+ chunker = PCMChunker(chunk_seconds=recipe.chunk_seconds, overlap_seconds=0)
400
381
  chunk_paths: list[Path] = []
401
382
 
402
383
  def make_chunk() -> Path:
@@ -419,9 +400,7 @@ class PreparationCoordinator:
419
400
  raise TranscriptionError("cancelled")
420
401
  if checkpoint.status is PreparationChunkStatus.PENDING:
421
402
  chunk_audio = inspect_normalized_audio(chunk_file.path)
422
- output = self.artifacts.create_staging_file(
423
- job.project_id, suffix=".json"
424
- )
403
+ output = self.artifacts.create_staging_file(job.project_id, suffix=".json")
425
404
  try:
426
405
  result = transcriber.transcribe(
427
406
  chunk_audio,
@@ -455,9 +434,7 @@ class PreparationCoordinator:
455
434
  result,
456
435
  )
457
436
  completed.append(checkpoint)
458
- self._publish_transcript(
459
- job, run, item, artifact_id, tuple(completed), recipe
460
- )
437
+ self._publish_transcript(job, run, item, artifact_id, tuple(completed), recipe)
461
438
  finally:
462
439
  for path in chunk_paths:
463
440
  path.unlink(missing_ok=True)
@@ -470,9 +447,7 @@ class PreparationCoordinator:
470
447
  except Exception:
471
448
  self._fail_item(job, target, "preparation_item_internal_error")
472
449
 
473
- def _publish_transcript(
474
- self, job, run, item, audio_artifact_id, chunks, recipe: PreparationRecipe
475
- ) -> None:
450
+ def _publish_transcript(self, job, run, item, audio_artifact_id, chunks, recipe: PreparationRecipe) -> None:
476
451
  target = item.target
477
452
  timeline: list[TimelineSegment] = []
478
453
  payload_segments: list[dict[str, object]] = []
@@ -480,9 +455,7 @@ class PreparationCoordinator:
480
455
  chunk_artifacts: list[str] = []
481
456
  for chunk in chunks:
482
457
  if chunk.result is None or chunk.transcript_artifact_id is None:
483
- raise ProjectError(
484
- "storage_corrupt", "Clipen 找不到逐字稿切塊。", status_code=500
485
- )
458
+ raise ProjectError("storage_corrupt", "Clipen 找不到逐字稿切塊。", status_code=500)
486
459
  chunk_artifacts.append(chunk.transcript_artifact_id)
487
460
  if chunk.result.text.strip():
488
461
  texts.append(chunk.result.text.strip())
@@ -493,9 +466,7 @@ class PreparationCoordinator:
493
466
  chunk.start_sample + segment.end_sample,
494
467
  16_000,
495
468
  )
496
- timeline.append(
497
- TimelineSegment(span, segment.text, segment.word_confidence)
498
- )
469
+ timeline.append(TimelineSegment(span, segment.text, segment.word_confidence))
499
470
  words = []
500
471
  for word in segment.words:
501
472
  word_span = project_samples_to_source(
@@ -561,10 +532,7 @@ class PreparationCoordinator:
561
532
  recipe_id=recipe.transcript_recipe_id,
562
533
  source_span=target.audio.source_span,
563
534
  segments=tuple(timeline),
564
- needs_review=any(
565
- chunk.result is not None and chunk.result.needs_review
566
- for chunk in chunks
567
- ),
535
+ needs_review=any(chunk.result is not None and chunk.result.needs_review for chunk in chunks),
568
536
  )
569
537
 
570
538
  def _fail_item(self, job, target, code: str) -> None:
@@ -2,13 +2,9 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
- from collections import deque
6
- from dataclasses import dataclass
7
- from enum import Enum
8
5
  import hashlib
9
6
  import json
10
7
  import os
11
- from pathlib import Path
12
8
  import platform
13
9
  import re
14
10
  import secrets
@@ -18,10 +14,14 @@ import stat
18
14
  import subprocess
19
15
  import threading
20
16
  import time
17
+ import venv
18
+ from collections import deque
19
+ from dataclasses import dataclass
20
+ from enum import Enum
21
+ from pathlib import Path
21
22
  from typing import Callable
22
23
  from urllib.error import HTTPError, URLError
23
24
  from urllib.request import Request, urlopen
24
- import venv
25
25
 
26
26
  from clipen.asr_release import (
27
27
  ASR_SOFTWARE_LICENSE,
@@ -44,7 +44,6 @@ from clipen.asr_release import (
44
44
 
45
45
  from .transcription import LocalModelSnapshot, Qwen3ASRAdapter
46
46
 
47
-
48
47
  _MAX_DOWNLOAD_BYTES = 4 * 1024**3
49
48
  _INSTALL_FREE_SPACE_MARGIN = 512 * 1024**2
50
49
  _INSTALL_TIMEOUT_SECONDS = 60 * 60
@@ -160,11 +159,7 @@ class ASRSetupManager:
160
159
  self._model_revision = model_revision
161
160
  self._model_files = model_files
162
161
  if model_downloads is None:
163
- if (
164
- model_repository == MODEL_REPOSITORY
165
- and model_revision == MODEL_REVISION
166
- and model_files == MODEL_FILES
167
- ):
162
+ if model_repository == MODEL_REPOSITORY and model_revision == MODEL_REVISION and model_files == MODEL_FILES:
168
163
  model_downloads = MODEL_DOWNLOADS
169
164
  else:
170
165
  model_downloads = tuple(
@@ -179,8 +174,7 @@ class ASRSetupManager:
179
174
  if (
180
175
  len(model_downloads) != len(model_files)
181
176
  or len({item[0] for item in model_downloads}) != len(model_downloads)
182
- or {item[0] for item in model_downloads}
183
- != {item[0] for item in model_files}
177
+ or {item[0] for item in model_downloads} != {item[0] for item in model_files}
184
178
  or any(
185
179
  not url.startswith("https://") or size < 1 or len(digest) != 64
186
180
  for _filename, url, size, digest in model_downloads
@@ -296,7 +290,6 @@ class ASRSetupManager:
296
290
  binding = self.runtime_binding()
297
291
  return None if binding is None else binding[0]
298
292
 
299
-
300
293
  def runtime_binding(
301
294
  self,
302
295
  ) -> tuple[Callable[[], Qwen3ASRAdapter], dict[str, object]] | None:
@@ -447,9 +440,7 @@ class ASRSetupManager:
447
440
  detail_total_bytes=max(0, detail_total_bytes),
448
441
  )
449
442
 
450
- def _install_runtime(
451
- self, destination: Path, requirements: Path, cancel: threading.Event
452
- ) -> None:
443
+ def _install_runtime(self, destination: Path, requirements: Path, cancel: threading.Event) -> None:
453
444
  try:
454
445
  venv.EnvBuilder(with_pip=True, clear=False, symlinks=False).create(destination)
455
446
  except Exception as error:
@@ -621,16 +612,13 @@ class ASRSetupManager:
621
612
  raise ASRSetupError("asr_download_too_large")
622
613
  digest.update(block)
623
614
  output.write(block)
624
- base, model_total = getattr(
625
- self, "_active_model_download", (0, expected_size)
626
- )
615
+ base, model_total = getattr(self, "_active_model_download", (0, expected_size))
627
616
  if getattr(self, "_active_download_phase", "model") == "runtime":
628
617
  self._set_progress(
629
618
  "downloading_runtime",
630
619
  "正在下載固定版本的語音辨識程式…",
631
620
  1,
632
- progress_percent=40
633
- + int(min(base + total, model_total) / max(1, model_total) * 2),
621
+ progress_percent=40 + int(min(base + total, model_total) / max(1, model_total) * 2),
634
622
  detail_completed_bytes=base + total,
635
623
  detail_total_bytes=model_total,
636
624
  )
@@ -877,9 +865,7 @@ class ASRSetupManager:
877
865
  self._remove_tree(candidate, missing_ok=True)
878
866
  except ASRSetupError as error:
879
867
  with self._lock:
880
- self._diagnostic_lines = (
881
- f"superseded ASR cleanup failed: {release_id}: {error.code}",
882
- )
868
+ self._diagnostic_lines = (f"superseded ASR cleanup failed: {release_id}: {error.code}",)
883
869
 
884
870
  def _cleanup_staging(self) -> None:
885
871
  for candidate in self.root.iterdir():
@@ -3,9 +3,9 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  import argparse
6
- from pathlib import Path
7
6
  import sys
8
7
  import time
8
+ from pathlib import Path
9
9
 
10
10
  from clipen.asr_release import NOTICE_VERSION, PROGRESS_RECORD_PREFIX
11
11
 
@@ -29,14 +29,8 @@ def _progress_line(status: ASRSetupStatus, elapsed: int) -> str:
29
29
  bar = "█" * filled + "░" * (width - filled)
30
30
  detail = ""
31
31
  if status.detail_total_bytes > 0:
32
- detail = (
33
- f" · {_format_bytes(status.detail_completed_bytes)}"
34
- f" / {_format_bytes(status.detail_total_bytes)}"
35
- )
36
- return (
37
- f"[{bar}] {percent:3d}% {status.message}{detail}"
38
- f" · {elapsed // 60} 分 {elapsed % 60} 秒"
39
- )
32
+ detail = f" · {_format_bytes(status.detail_completed_bytes)} / {_format_bytes(status.detail_total_bytes)}"
33
+ return f"[{bar}] {percent:3d}% {status.message}{detail} · {elapsed // 60} 分 {elapsed % 60} 秒"
40
34
 
41
35
 
42
36
  def main(arguments: list[str] | None = None) -> int:
@@ -71,13 +65,9 @@ def main(arguments: list[str] | None = None) -> int:
71
65
  while True:
72
66
  status = manager.status()
73
67
  now = time.monotonic()
74
- should_report_progress = (
75
- status.progress_percent != last_percent and now - last_reported_at >= 0.5
76
- )
68
+ should_report_progress = status.progress_percent != last_percent and now - last_reported_at >= 0.5
77
69
  if status.state is ASRSetupState.INSTALLING and (
78
- status.phase != last_phase
79
- or should_report_progress
80
- or now - last_reported_at >= 5
70
+ status.phase != last_phase or should_report_progress or now - last_reported_at >= 5
81
71
  ):
82
72
  elapsed = max(0, int(now - started_at))
83
73
  print(