@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,150 @@
1
+ """Validated word boundaries from an installed, pinned local model; no estimated words."""
2
+
3
+ import json
4
+ import math
5
+ import unicodedata
6
+ from pathlib import Path
7
+
8
+ from clipen.projects import ProjectError
9
+
10
+ MODEL = "mlx-community/Qwen3-ForcedAligner-0.6B-8bit"
11
+ REVISION = "0e1a68e91d815300c7c9754b2a7639378b23db15"
12
+ FILES = {
13
+ "chat_template.json": 1161,
14
+ "config.json": 6940,
15
+ "generation_config.json": 115,
16
+ "merges.txt": 1671853,
17
+ "model.safetensors": 1271924386,
18
+ "model.safetensors.index.json": 79108,
19
+ "preprocessor_config.json": 330,
20
+ "tokenizer_config.json": 12666,
21
+ "vocab.json": 2776833,
22
+ }
23
+
24
+
25
+ def significant(text):
26
+ return "".join(c.casefold() for c in unicodedata.normalize("NFKC", text) if unicodedata.category(c)[0] not in "PZC")
27
+
28
+
29
+ # The pinned aligner reports times on an 80 ms grid. A zero-width token one
30
+ # step away from its neighbour still marks a boundary the model observed.
31
+ FRAME = 0.1
32
+ # A result where most characters collapse onto instants, or a run of them
33
+ # share one instant, means the model lost the speech; keep it for repair.
34
+ MAX_INSTANT_SHARE = 0.4
35
+ MAX_INSTANT_RUN = 4
36
+
37
+
38
+ def validate_alignment(words, text, duration):
39
+ if not isinstance(words, list) or not 1 <= len(words) <= 1000:
40
+ raise ProjectError("alignment_invalid", "對齊結果沒有有效字詞。", status_code=422)
41
+ # Quantized aligners can emit a zero-width token at, or one grid step from,
42
+ # an adjacent word boundary. Keep the observed interval as a grouped word;
43
+ # never assign an invented duration to the individual character or bridge
44
+ # a gap longer than one grid step. A token away from any neighbour stays an
45
+ # instant: its observed time, with no duration added.
46
+ grouped = []
47
+ pending = []
48
+ for raw in words:
49
+ word = dict(raw)
50
+ start, end = word.get("start"), word.get("end")
51
+ if not significant(word.get("text", "")):
52
+ continue
53
+ finite = all(not isinstance(v, bool) and isinstance(v, (int, float)) and math.isfinite(v) for v in (start, end))
54
+ zero = finite and 0 <= start == end <= duration
55
+ last = grouped[-1] if grouped else None
56
+ if (
57
+ zero
58
+ and last
59
+ and not pending
60
+ and isinstance(last.get("end"), (int, float))
61
+ and not isinstance(last.get("end"), bool)
62
+ and 0 <= start - last["end"] <= FRAME
63
+ and last.get("start", start) < start
64
+ ):
65
+ last["text"] += word["text"]
66
+ last["end"] = start
67
+ elif zero:
68
+ pending.append(word)
69
+ else:
70
+ if pending and finite and start < end and all(0 <= start - w["end"] <= FRAME for w in pending):
71
+ word["text"] = "".join(w["text"] for w in pending) + word["text"]
72
+ word["start"] = min(start, pending[0]["start"])
73
+ else:
74
+ grouped.extend(pending)
75
+ pending = []
76
+ grouped.append(word)
77
+ words = grouped + pending
78
+ positions = [(index, significant(character)) for index, character in enumerate(text) if significant(character)]
79
+ normalized = "".join(char for _, char in positions)
80
+ # Require a stable one-to-one character normalization. Do not silently assign
81
+ # fractional timing inside a word or fabricate missing/mismatched characters.
82
+ if any(len(char) != 1 for _, char in positions):
83
+ raise ProjectError("alignment_text_unsupported", "這段文字需要額外正規化核對。", status_code=422)
84
+ cursor, previous, result = 0, 0.0, []
85
+ for word in words:
86
+ token = significant(word.get("text", ""))
87
+ if not token:
88
+ continue
89
+ start, end = word.get("start"), word.get("end")
90
+ if (
91
+ any(isinstance(v, bool) or not isinstance(v, (int, float)) or not math.isfinite(v) for v in (start, end))
92
+ or not 0 <= start <= end <= duration + 0.05
93
+ or start < previous - 0.02
94
+ or end < previous
95
+ or normalized[cursor : cursor + len(token)] != token
96
+ ):
97
+ raise ProjectError("alignment_invalid", "字詞對齊與文字或音訊範圍不符,已保留待修。", status_code=422)
98
+ result.append(
99
+ {
100
+ "text": word["text"],
101
+ "char_start": positions[cursor][0],
102
+ "char_end": positions[cursor + len(token) - 1][0] + 1,
103
+ "start_seconds": max(previous, start),
104
+ "end_seconds": min(duration, end),
105
+ }
106
+ )
107
+ cursor += len(token)
108
+ previous = min(duration, end)
109
+ if cursor != len(normalized) or not result:
110
+ raise ProjectError("alignment_incomplete", "對齊未涵蓋完整文字。", status_code=422)
111
+ instants = [w["start_seconds"] >= w["end_seconds"] for w in result]
112
+ run = longest = 0
113
+ for instant in instants:
114
+ run = run + 1 if instant else 0
115
+ longest = max(longest, run)
116
+ if (
117
+ sum(instants) > len(result) * MAX_INSTANT_SHARE
118
+ or longest >= MAX_INSTANT_RUN
119
+ or not any(not i for i in instants)
120
+ ):
121
+ raise ProjectError("alignment_invalid", "對齊結果多數字詞沒有時間長度,已保留待修。", status_code=422)
122
+ return result
123
+
124
+
125
+ def run_alignment(data_root, audio, text, language, output, cancel):
126
+ if data_root is None:
127
+ raise ProjectError("alignment_unavailable", "本機字詞對齊環境尚未設定。", status_code=409)
128
+ from .alignment_setup import root_for, verified_runtime
129
+
130
+ binding = verified_runtime(root_for(data_root))
131
+ if binding is None:
132
+ raise ProjectError("alignment_unavailable", "缺少固定版本的本機字詞對齊環境。", status_code=409)
133
+ python, model = binding
134
+ from clipen.finishing.audio import run_process
135
+
136
+ from .production_media import atomic_json
137
+
138
+ request = output.with_suffix(".request.json")
139
+ atomic_json(
140
+ request, {"model": str(model), "audio": str(audio), "text": text, "language": language, "output": str(output)}
141
+ )
142
+ try:
143
+ run_process(
144
+ [str(python), str(Path(__file__).with_name("alignment_worker.py")), str(request)], cancel, timeout=180
145
+ )
146
+ if output.is_symlink() or not output.is_file() or output.stat().st_size > 1024 * 1024:
147
+ raise ProjectError("alignment_invalid", "無法讀取對齊結果。", status_code=409)
148
+ return json.loads(output.read_text())
149
+ finally:
150
+ request.unlink(missing_ok=True)
@@ -0,0 +1,156 @@
1
+ """Cancellable installation of the fixed local alignment runtime, without source uploads."""
2
+
3
+ import hashlib
4
+ import json
5
+ import os
6
+ import platform
7
+ import shutil
8
+ import sys
9
+ import time
10
+ import urllib.request
11
+ import uuid
12
+ import venv
13
+ from pathlib import Path
14
+
15
+ from clipen.projects import ProjectError
16
+
17
+ from .alignment import FILES, MODEL, REVISION
18
+
19
+ HASHES = {
20
+ "chat_template.json": "75a8cfca24f00de72d796fbfed6858fc9614ef3dabd8696684cc3bc03a9c58ff",
21
+ "config.json": "8dc126e1a4ac001acb02f3a9ca6277c8a20a25485fde293bc99eeab3aedc604d",
22
+ "generation_config.json": "948d089b23bca1d214e768d59c4438365665f52ec6d33678f4062206b3fbbb8c",
23
+ "merges.txt": "8831e4f1a044471340f7c0a83d7bd71306a5b867e95fd870f74d0c5308a904d5",
24
+ "model.safetensors": "be19ef8ac4326d032e7673342930b14c2df30bd68c1632493b0f563e30829f91",
25
+ "model.safetensors.index.json": "766eb50873855eeb4d95ab92def358cfd173bfc8c7aabd8635ababa1edf6db79",
26
+ "preprocessor_config.json": "45e120a4eda2c20c5d7f2ea9354e63536bf35e27aa573fb7cdf78017b378770d",
27
+ "tokenizer_config.json": "3ab80063f8511deb9566e6ad438d17b7a6277fcffd52d92854112f19d36bd81c",
28
+ "vocab.json": "ca10d7e9fb3ed18575dd1e277a2579c16d108e32f27439684afa0e10b1440910",
29
+ }
30
+ RECEIPT = {"model": MODEL, "revision": REVISION, "runtime": "mlx-audio-0.6.0"}
31
+
32
+
33
+ def root_for(data_root):
34
+ return Path(data_root) / "alignment" / "qwen3-0.6b-8bit-v1"
35
+
36
+
37
+ def verified_runtime(root):
38
+ root = Path(root)
39
+ receipt = root / "ready.json"
40
+ model = root / "model"
41
+ python = root / "runtime/bin/python"
42
+ if (
43
+ any(p.is_symlink() for p in (root.parent, root, model, root / "runtime", root / "runtime/bin", receipt))
44
+ or not receipt.is_file()
45
+ or receipt.stat().st_size > 4096
46
+ or not python.is_file()
47
+ ):
48
+ return None
49
+ try:
50
+ if json.loads(receipt.read_text()) != RECEIPT:
51
+ return None
52
+ for name, size in FILES.items():
53
+ path = model / name
54
+ if path.is_symlink() or not path.is_file() or path.stat().st_size != size:
55
+ return None
56
+ value = hashlib.sha256()
57
+ with path.open("rb") as source:
58
+ while block := source.read(1024 * 1024):
59
+ value.update(block)
60
+ if value.hexdigest() != HASHES[name]:
61
+ return None
62
+ return python, model
63
+ except (OSError, ValueError):
64
+ return None
65
+
66
+
67
+ def install_runtime(data_root, cancel, progress=lambda _: None):
68
+ if sys.platform != "darwin" or platform.machine() != "arm64":
69
+ raise ProjectError("alignment_platform_unsupported", "本機對齊目前支援 Apple Silicon Mac。", status_code=409)
70
+ if data_root is None:
71
+ raise ProjectError("alignment_unavailable", "本機對齊目錄尚未設定。", status_code=409)
72
+ import fcntl
73
+
74
+ from clipen.finishing.audio import run_process
75
+
76
+ from .production_media import atomic_json
77
+
78
+ root = root_for(data_root)
79
+ if root.parent.is_symlink() or root.is_symlink():
80
+ raise ProjectError("storage_unsafe", "模型安裝路徑不安全。", status_code=409)
81
+ root.parent.mkdir(mode=0o700, exist_ok=True, parents=True)
82
+ lock_path = root.parent / "setup.lock"
83
+ fd = os.open(lock_path, os.O_CREAT | os.O_RDWR | getattr(os, "O_NOFOLLOW", 0), 0o600)
84
+ staging = None
85
+ try:
86
+ deadline = time.monotonic() + 1800
87
+ while True:
88
+ if cancel.is_set():
89
+ raise ProjectError("user_cancelled", "已取消模型準備。", status_code=409)
90
+ if time.monotonic() > deadline:
91
+ raise ProjectError("alignment_setup_timeout", "模型準備逾時。", status_code=409)
92
+ try:
93
+ fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
94
+ break
95
+ except BlockingIOError:
96
+ cancel.wait(0.2)
97
+ if verified_runtime(root):
98
+ return {"ready": True, "model": MODEL, "revision": REVISION, "reused": True}
99
+ if root.exists():
100
+ # An invalid prior environment is preserved for diagnosis. Never
101
+ # silently delete an existing user installation during a retry.
102
+ raise ProjectError(
103
+ "alignment_install_invalid", "現有對齊環境未通過驗證,請修復該本機環境。", status_code=409
104
+ )
105
+ if shutil.disk_usage(root.parent).free < sum(FILES.values()) + 1024**3:
106
+ raise ProjectError("alignment_disk_space", "準備對齊模型需要額外約 2.3 GB 可用空間。", status_code=409)
107
+ staging = root.parent / (".setup-" + uuid.uuid4().hex)
108
+ staging.mkdir(mode=0o700)
109
+ (staging / "model").mkdir(mode=0o700)
110
+ progress({"phase": "runtime"})
111
+ venv.EnvBuilder(with_pip=True).create(staging / "runtime")
112
+ run_process(
113
+ [
114
+ str(staging / "runtime/bin/python"),
115
+ "-m",
116
+ "pip",
117
+ "install",
118
+ "--disable-pip-version-check",
119
+ "mlx-audio==0.6.0",
120
+ ],
121
+ cancel,
122
+ timeout=900,
123
+ )
124
+ total = sum(FILES.values())
125
+ completed = 0
126
+ for name, size in FILES.items():
127
+ path = staging / "model" / name
128
+ request = urllib.request.Request(
129
+ f"https://huggingface.co/{MODEL}/resolve/{REVISION}/{name}",
130
+ headers={"User-Agent": "Clipen-local-alignment/1"},
131
+ )
132
+ value = hashlib.sha256()
133
+ count = 0
134
+ with urllib.request.urlopen(request, timeout=30) as response, path.open("xb") as output:
135
+ while block := response.read(1024 * 1024):
136
+ if cancel.is_set():
137
+ raise ProjectError("user_cancelled", "已取消模型下載。", status_code=409)
138
+ if time.monotonic() > deadline:
139
+ raise ProjectError("alignment_setup_timeout", "模型下載逾時。", status_code=409)
140
+ count += len(block)
141
+ if count > size:
142
+ raise ValueError("alignment download exceeds pinned size")
143
+ output.write(block)
144
+ value.update(block)
145
+ progress({"phase": "model", "completed_bytes": completed + count, "total_bytes": total})
146
+ if count != size or value.hexdigest() != HASHES[name]:
147
+ raise ProjectError("alignment_download_invalid", "模型下載未通過固定版本校驗。", status_code=409)
148
+ completed += size
149
+ atomic_json(staging / "ready.json", RECEIPT)
150
+ os.rename(staging, root)
151
+ staging = None
152
+ return {"ready": True, "model": MODEL, "revision": REVISION, "reused": False}
153
+ finally:
154
+ if staging is not None:
155
+ shutil.rmtree(staging, ignore_errors=True)
156
+ os.close(fd)
@@ -0,0 +1,24 @@
1
+ """Offline subprocess for the separately installed MLX forced-aligner."""
2
+
3
+ import json
4
+ import os
5
+ import sys
6
+ from pathlib import Path
7
+
8
+ os.environ["HF_HUB_OFFLINE"] = "1"
9
+ os.environ["TRANSFORMERS_OFFLINE"] = "1"
10
+
11
+
12
+ def main():
13
+ from mlx_audio.stt import load
14
+
15
+ request = json.loads(Path(sys.argv[1]).read_text())
16
+ model = load(request["model"])
17
+ language = {"zh": "Chinese", "en": "English", "ja": "Japanese"}[request["language"]]
18
+ result = model.generate(audio=request["audio"], text=request["text"], language=language)
19
+ words = [{"text": i.text, "start": float(i.start_time), "end": float(i.end_time)} for i in result]
20
+ Path(request["output"]).write_text(json.dumps(words, ensure_ascii=False))
21
+
22
+
23
+ if __name__ == "__main__":
24
+ main()
@@ -0,0 +1,128 @@
1
+ """The account the AI gives of each change: what it changed and why, how it handled each review note,
2
+ and what it left undone. finish_edit refuses to close a change without one."""
3
+
4
+ from clipen.projects import ProjectError
5
+
6
+ OUTCOMES = {"done": "已處理", "partly": "部分處理", "not_done": "沒有處理", "kept": "照你說的保留"}
7
+ # Work may be left only for one of these: the person has to decide or supply something,
8
+ # or no Clipen tool can do it. Running out of effort is not a reason.
9
+ REASONS = {"needs_you": "需要你決定或提供", "cannot": "Clipen 目前做不到"}
10
+ UNFINISHED = "change_report_unfinished"
11
+
12
+
13
+ def _text(value, limit):
14
+ return isinstance(value, str) and 0 < len(value.strip()) <= limit
15
+
16
+
17
+ def _invalid(message):
18
+ return ProjectError("change_report_invalid", message, status_code=422)
19
+
20
+
21
+ def check_report(arguments, intent):
22
+ """The report finish_edit was given, checked against the notes the person sent with this request."""
23
+ changes = arguments.get("changes")
24
+ if (
25
+ not isinstance(changes, list)
26
+ or not 1 <= len(changes) <= 20
27
+ or not all(
28
+ isinstance(c, dict) and set(c) <= {"what", "why"} and _text(c.get("what"), 200) and _text(c.get("why"), 300)
29
+ for c in changes
30
+ )
31
+ ):
32
+ raise _invalid(
33
+ "finish_edit 要附上修改說明:changes 列出 1–20 項,每項寫 what(改了什麼,200 字內)與 why(為什麼,300 字內),用觀眾看得懂的話。"
34
+ )
35
+ not_done = arguments.get("not_done", [])
36
+ if (
37
+ not isinstance(not_done, list)
38
+ or len(not_done) > 10
39
+ or not all(
40
+ isinstance(item, dict)
41
+ and set(item) <= {"what", "reason", "detail"}
42
+ and item.get("reason") in REASONS
43
+ and _text(item.get("what"), 200)
44
+ and _text(item.get("detail"), 300)
45
+ for item in not_done
46
+ )
47
+ ):
48
+ raise _invalid(
49
+ "not_done 每項要有 what(沒做到什麼)、reason 與 detail,最多 10 項。reason 只能是 needs_you"
50
+ "(detail 寫使用者要決定或提供什麼)或 cannot(detail 寫是哪個工具限制做不到)。"
51
+ "你的工具做得到的事不能列在這裡,要先做完。"
52
+ )
53
+ request = intent.get("latest_revision_request") or {}
54
+ sent = {
55
+ item["reference_id"]
56
+ for item in (request.get("references") or {}).get("items", [])
57
+ if isinstance(item, dict) and "reference_id" in item
58
+ }
59
+ notes = arguments.get("notes", [])
60
+ if not isinstance(notes, list) or not all(
61
+ isinstance(n, dict)
62
+ and set(n) <= {"reference_id", "outcome", "explanation", "reason"}
63
+ and n.get("outcome") in OUTCOMES
64
+ and _text(n.get("explanation"), 300)
65
+ and isinstance(n.get("reference_id"), str)
66
+ for n in notes
67
+ ):
68
+ raise _invalid(
69
+ "notes 每項要有 reference_id、outcome(done/partly/not_done/kept)與 explanation(300 字內)。"
70
+ )
71
+ if any(n["outcome"] in ("partly", "not_done") and n.get("reason") not in REASONS for n in notes):
72
+ raise _invalid(
73
+ "outcome 是 partly 或 not_done 的注記要附 reason:needs_you(需要使用者決定或提供)或 cannot(工具做不到)。"
74
+ "你的工具做得到的就先做完,再回報 done。"
75
+ )
76
+ answered = [n["reference_id"] for n in notes]
77
+ if len(answered) != len(set(answered)) or set(answered) != sent:
78
+ missing = len(sent - set(answered))
79
+ raise _invalid(
80
+ f"使用者這次送了 {len(sent)} 筆注記,notes 要逐筆回應每一筆(reference_id 不重複、不多不少)"
81
+ + (f";還有 {missing} 筆沒回應。" if missing else "。")
82
+ )
83
+ return {
84
+ "changes": [{"what": c["what"].strip(), "why": c["why"].strip()} for c in changes],
85
+ "notes": [
86
+ {
87
+ "reference_id": n["reference_id"],
88
+ "outcome": n["outcome"],
89
+ "explanation": n["explanation"].strip(),
90
+ **({"reason": n["reason"]} if n["outcome"] in ("partly", "not_done") else {}),
91
+ }
92
+ for n in notes
93
+ ],
94
+ "not_done": [
95
+ {"what": i["what"].strip(), "reason": i["reason"], "detail": i["detail"].strip()} for i in not_done
96
+ ],
97
+ }
98
+
99
+
100
+ def unfinished(report):
101
+ """What the report leaves undone, as short lines the AI is asked to reconsider."""
102
+ return [
103
+ f"注記 {n['reference_id']}:{n['explanation']}"
104
+ for n in report["notes"]
105
+ if n["outcome"] in ("partly", "not_done")
106
+ ] + [f"{i['what']}({i['detail']})" for i in report["not_done"]]
107
+
108
+
109
+ def challenge(report):
110
+ """Asked once per request before work is left undone: do what the tools can do first."""
111
+ left = unfinished(report)
112
+ return ProjectError(
113
+ UNFINISHED,
114
+ "修改說明裡還有沒做完的地方:"
115
+ + ";".join(left)[:900]
116
+ + "。用你的工具做得到的,現在就做完並改回報 done;只有真的需要使用者決定或提供、或工具確實做不到的才保留,"
117
+ "確認後再呼叫一次 finish_edit。",
118
+ status_code=409,
119
+ )
120
+
121
+
122
+ def carried(report):
123
+ """What the last change left for the person, handed to the next request."""
124
+ return [
125
+ {"what": i["what"], "reason": i["reason"], "detail": i["detail"]}
126
+ for i in report.get("not_done", [])
127
+ if isinstance(i, dict) and i.get("reason") in REASONS
128
+ ]
@@ -0,0 +1,40 @@
1
+ """Output settings stored with an edit timeline."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+
7
+ _PRESETS = {
8
+ "landscape_1080p": (1920, 1080),
9
+ "portrait_1080p": (1080, 1920),
10
+ }
11
+ _FRAME_RATES = frozenset((24, 25, 30, 60))
12
+
13
+
14
+ @dataclass(frozen=True, slots=True)
15
+ class OutputSettings:
16
+ preset: str
17
+ frame_rate: int
18
+
19
+ def __post_init__(self) -> None:
20
+ if not isinstance(self.preset, str) or self.preset not in _PRESETS:
21
+ raise ValueError("output preset is invalid")
22
+ if (
23
+ isinstance(self.frame_rate, bool)
24
+ or not isinstance(self.frame_rate, int)
25
+ or self.frame_rate not in _FRAME_RATES
26
+ ):
27
+ raise ValueError("output frame rate is invalid")
28
+
29
+ @property
30
+ def canvas(self) -> tuple[int, int]:
31
+ return _PRESETS[self.preset]
32
+
33
+ def to_payload(self) -> dict[str, object]:
34
+ width, height = self.canvas
35
+ return {
36
+ "preset": self.preset,
37
+ "frame_rate": self.frame_rate,
38
+ "width": width,
39
+ "height": height,
40
+ }
@@ -0,0 +1,131 @@
1
+ """Looks: named sets of typefaces and colours that graphics of one kind share.
2
+
3
+ The Agent designs each look (a chapter look, a place look, a reaction look...) and
4
+ every free design names the look it uses. Clipen gives the page that look's
5
+ fonts and colours as --look-font-<key> and --look-<key> variables, and a page may
6
+ draw text only in its look's typefaces, so graphics of one kind stay consistent
7
+ while their layout and motion remain free.
8
+
9
+ Each graphic keeps a copy of its look, so every version draws as it was saved.
10
+ The run's list of looks lives beside the film; the copies on the current film
11
+ win, so going back to an earlier version also brings back its looks.
12
+ """
13
+
14
+ import json
15
+ import re
16
+
17
+ from clipen.projects import ProjectError
18
+ from clipen.rendering.custom_components import FONT_CHOICES
19
+
20
+ KEY = re.compile(r"^[A-Za-z0-9_\-一-鿿]{1,24}$")
21
+ HEX = re.compile(r"^#[0-9a-fA-F]{6}$")
22
+ MAX_LOOKS, MAX_FONTS, MAX_COLORS = 8, 3, 6
23
+
24
+
25
+ def _invalid(message):
26
+ return ProjectError("component_look_invalid", message, status_code=422)
27
+
28
+
29
+ def normalize(value):
30
+ """A look as given by the Agent, checked: {look_id, name, fonts: [{key, label, family}], colors: [{key, label, value}]}."""
31
+ if not isinstance(value, dict) or not isinstance(value.get("look_id"), str) or not KEY.match(value["look_id"]):
32
+ raise _invalid("look_id 要是 1–24 個字的英數字、中文、- 或 _。")
33
+ name = value.get("name") if isinstance(value.get("name"), str) and value["name"].strip() else value["look_id"]
34
+ fonts, colors = value.get("fonts"), value.get("colors", [])
35
+ if not isinstance(fonts, list) or not 1 <= len(fonts) <= MAX_FONTS:
36
+ raise _invalid(f"每個外觀要有 1–{MAX_FONTS} 套字型。")
37
+ if not isinstance(colors, list) or len(colors) > MAX_COLORS:
38
+ raise _invalid(f"每個外觀最多 {MAX_COLORS} 個顏色。")
39
+
40
+ def entries(items, kind):
41
+ seen, result = set(), []
42
+ for entry in items:
43
+ if (
44
+ not isinstance(entry, dict)
45
+ or not isinstance(entry.get("key"), str)
46
+ or not KEY.match(entry["key"])
47
+ or entry["key"] in seen
48
+ ):
49
+ raise _invalid("字型與顏色的 key 要是不重複的英數字、中文、- 或 _。")
50
+ seen.add(entry["key"])
51
+ label = (
52
+ entry.get("label") if isinstance(entry.get("label"), str) and entry["label"].strip() else entry["key"]
53
+ )
54
+ if kind == "font":
55
+ if entry.get("family") not in FONT_CHOICES:
56
+ raise _invalid("可用的字型:" + "、".join(FONT_CHOICES) + "。")
57
+ result.append({"key": entry["key"], "label": label.strip()[:24], "family": entry["family"]})
58
+ else:
59
+ if not isinstance(entry.get("value"), str) or not HEX.match(entry["value"]):
60
+ raise _invalid("顏色要寫成 #rrggbb。")
61
+ result.append({"key": entry["key"], "label": label.strip()[:24], "value": entry["value"].lower()})
62
+ return result
63
+
64
+ return {
65
+ "look_id": value["look_id"],
66
+ "name": name.strip()[:24],
67
+ "fonts": entries(fonts, "font"),
68
+ "colors": entries(colors, "color"),
69
+ }
70
+
71
+
72
+ def _path(tools):
73
+ return tools.repository.projects.root / tools.project_id / f"component-looks-{tools.run_id}.json"
74
+
75
+
76
+ def stored(tools):
77
+ path = _path(tools)
78
+ if path.is_symlink():
79
+ raise ProjectError("storage_unsafe", "外觀檔案不安全。", status_code=409)
80
+ if not path.exists():
81
+ return {}
82
+ return {look["look_id"]: look for look in json.loads(path.read_text(encoding="utf-8"))}
83
+
84
+
85
+ def store(tools, looks):
86
+ from .production_media import atomic_json
87
+
88
+ atomic_json(_path(tools), list(looks.values()))
89
+
90
+
91
+ def on_film(tools, timeline=None):
92
+ """(graphic, profile) for each free design on the film."""
93
+ from .production_media import load_text_styles
94
+
95
+ styles = load_text_styles(tools.repository.projects, tools.project_id)
96
+ timeline = timeline or tools._timeline()
97
+ return [
98
+ (item, styles[item.style_id])
99
+ for track in timeline.tracks
100
+ if track.track_id == "program-components" or track.track_id.startswith("program-components-")
101
+ for item in track.items
102
+ if styles.get(item.style_id, {}).get("component_id") == "custom"
103
+ ]
104
+
105
+
106
+ def current(tools):
107
+ """The run's looks, as the current film has them."""
108
+ looks = stored(tools)
109
+ for _, profile in on_film(tools):
110
+ look = profile.get("look")
111
+ if look:
112
+ looks[look["look_id"]] = look
113
+ return looks
114
+
115
+
116
+ def public(look, used=0):
117
+ """A look as the Agent and the review page see it, with the variables a page writes."""
118
+ return {
119
+ **look,
120
+ "used_by": used,
121
+ "fonts": [{**f, "css": f"var(--look-font-{f['key']})"} for f in look["fonts"]],
122
+ "colors": [{**c, "css": f"var(--look-{c['key']})"} for c in look["colors"]],
123
+ }
124
+
125
+
126
+ def listing(tools):
127
+ counts = {}
128
+ for _, profile in on_film(tools):
129
+ if profile.get("look"):
130
+ counts[profile["look"]["look_id"]] = counts.get(profile["look"]["look_id"], 0) + 1
131
+ return [public(look, counts.get(key, 0)) for key, look in current(tools).items()]