@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,428 @@
1
+ """Transactional persistence for user-authored material annotations."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import re
7
+ import sqlite3
8
+ from collections.abc import Mapping
9
+
10
+ from clipen.projects.models import ProjectError, validate_project_id, validate_request_id
11
+ from clipen.projects.storage import ProjectRepository, command_digest, utc_now
12
+
13
+ from .models import DayPart, MaterialUsage
14
+ from .suggestions import annotation_suggestion
15
+
16
+ _VERSION_ID = re.compile(r"av_[0-9a-f]{32}\Z")
17
+
18
+
19
+ class AnnotationRepository:
20
+ def __init__(self, projects: ProjectRepository) -> None:
21
+ self.projects = projects
22
+
23
+ def get(self, project_id: str, version_id: str, stream_index: int) -> dict[str, object]:
24
+ validate_project_id(project_id)
25
+ self._validate_identity(version_id, stream_index)
26
+ try:
27
+ with self.projects.connect(project_id) as database:
28
+ self._require_version(database, version_id)
29
+ material = database.execute(
30
+ "SELECT * FROM material_annotations WHERE version_id=?",
31
+ (version_id,),
32
+ ).fetchone()
33
+ transcript = (
34
+ database.execute(
35
+ "SELECT * FROM transcript_annotations WHERE version_id=? AND stream_index=?",
36
+ (version_id, stream_index),
37
+ ).fetchone()
38
+ if stream_index >= 0
39
+ else None
40
+ )
41
+ current_revision = self._current_transcript_revision(database, version_id, stream_index)
42
+ suggestion = annotation_suggestion(database, version_id)
43
+ return self._public(material, transcript, version_id, stream_index, current_revision, suggestion)
44
+ except ProjectError:
45
+ raise
46
+ except (json.JSONDecodeError, TypeError, ValueError) as error:
47
+ raise ProjectError("storage_corrupt", "Clipen 無法讀取素材標註。", status_code=500) from error
48
+ except sqlite3.Error as error:
49
+ raise ProjectError("storage_failed", "Clipen 無法讀取素材標註。", status_code=500) from error
50
+
51
+ def save(
52
+ self,
53
+ project_id: str,
54
+ request_id: object,
55
+ version_id: str,
56
+ stream_index: int,
57
+ expected_material_revision: object,
58
+ expected_transcript_revision: object,
59
+ material: object,
60
+ transcript: object,
61
+ ) -> dict[str, object]:
62
+ validate_project_id(project_id)
63
+ normalized_request = validate_request_id(request_id)
64
+ self._validate_identity(version_id, stream_index)
65
+ material_revision = self._expected_revision(expected_material_revision)
66
+ transcript_revision = self._expected_revision(expected_transcript_revision)
67
+ normalized_material = self._material(material)
68
+ normalized_transcript = self._transcript(transcript, stream_index)
69
+ request_hash = command_digest(
70
+ {
71
+ "version_id": version_id,
72
+ "stream_index": stream_index,
73
+ "expected_material_revision": material_revision,
74
+ "expected_transcript_revision": transcript_revision,
75
+ "material": normalized_material,
76
+ "transcript": normalized_transcript,
77
+ }
78
+ )
79
+ now = utc_now()
80
+ try:
81
+ with self.projects.connect(project_id) as database:
82
+ database.execute("BEGIN IMMEDIATE")
83
+ receipt = database.execute(
84
+ "SELECT command_type,request_hash,response_json "
85
+ "FROM annotation_command_receipts WHERE request_id=?",
86
+ (normalized_request,),
87
+ ).fetchone()
88
+ if receipt is not None:
89
+ if receipt["command_type"] != "save_annotation" or receipt["request_hash"] != request_hash:
90
+ raise ProjectError(
91
+ "request_conflict",
92
+ "這次保存標註的操作與既有內容衝突。",
93
+ status_code=409,
94
+ )
95
+ response = json.loads(receipt["response_json"])
96
+ database.rollback()
97
+ return response
98
+ self._require_version(database, version_id)
99
+ current_material = database.execute(
100
+ "SELECT revision FROM material_annotations WHERE version_id=?",
101
+ (version_id,),
102
+ ).fetchone()
103
+ observed_material = 0 if current_material is None else current_material["revision"]
104
+ current_transcript = (
105
+ database.execute(
106
+ "SELECT revision FROM transcript_annotations WHERE version_id=? AND stream_index=?",
107
+ (version_id, stream_index),
108
+ ).fetchone()
109
+ if stream_index >= 0
110
+ else None
111
+ )
112
+ observed_transcript = 0 if current_transcript is None else current_transcript["revision"]
113
+ if observed_material != material_revision or observed_transcript != transcript_revision:
114
+ raise ProjectError(
115
+ "annotation_revision_conflict",
116
+ "素材標註已更新,請重新整理後再保存。",
117
+ status_code=409,
118
+ )
119
+ next_material = observed_material + 1
120
+ database.execute(
121
+ "INSERT INTO material_annotations "
122
+ "(version_id,revision,people_json,location,trip_day,day_part,note,usage,updated_at) "
123
+ "VALUES(?,?,?,?,?,?,?,?,?) ON CONFLICT(version_id) DO UPDATE SET "
124
+ "revision=excluded.revision,people_json=excluded.people_json,"
125
+ "location=excluded.location,trip_day=excluded.trip_day,"
126
+ "day_part=excluded.day_part,note=excluded.note,usage=excluded.usage,"
127
+ "updated_at=excluded.updated_at",
128
+ (
129
+ version_id,
130
+ next_material,
131
+ json.dumps(normalized_material["people"], ensure_ascii=False, separators=(",", ":")),
132
+ normalized_material["location"],
133
+ normalized_material["trip_day"],
134
+ normalized_material["day_part"],
135
+ normalized_material["note"],
136
+ normalized_material["usage"],
137
+ now,
138
+ ),
139
+ )
140
+ next_transcript = observed_transcript
141
+ if normalized_transcript is not None:
142
+ source_revision = self._current_transcript_revision(database, version_id, stream_index)
143
+ if source_revision is None or source_revision != normalized_transcript["source_revision_id"]:
144
+ raise ProjectError(
145
+ "annotation_transcript_changed",
146
+ "逐字稿已重新分析,請重新載入後再保存修正。",
147
+ status_code=409,
148
+ )
149
+ self._validate_corrections(database, source_revision, normalized_transcript["corrections"])
150
+ next_transcript += 1
151
+ database.execute(
152
+ "INSERT INTO transcript_annotations "
153
+ "(version_id,stream_index,source_revision_id,revision,confirmed,discarded,"
154
+ "corrections_json,updated_at) VALUES(?,?,?,?,?,?,?,?) "
155
+ "ON CONFLICT(version_id,stream_index) DO UPDATE SET "
156
+ "source_revision_id=excluded.source_revision_id,revision=excluded.revision,"
157
+ "confirmed=excluded.confirmed,discarded=excluded.discarded,"
158
+ "corrections_json=excluded.corrections_json,"
159
+ "updated_at=excluded.updated_at",
160
+ (
161
+ version_id,
162
+ stream_index,
163
+ source_revision,
164
+ next_transcript,
165
+ int(normalized_transcript["confirmed"]),
166
+ int(normalized_transcript["discarded"]),
167
+ json.dumps(normalized_transcript["corrections"], ensure_ascii=False, separators=(",", ":")),
168
+ now,
169
+ ),
170
+ )
171
+ material_row = database.execute(
172
+ "SELECT * FROM material_annotations WHERE version_id=?", (version_id,)
173
+ ).fetchone()
174
+ transcript_row = (
175
+ database.execute(
176
+ "SELECT * FROM transcript_annotations WHERE version_id=? AND stream_index=?",
177
+ (version_id, stream_index),
178
+ ).fetchone()
179
+ if stream_index >= 0
180
+ else None
181
+ )
182
+ response = self._public(
183
+ material_row,
184
+ transcript_row,
185
+ version_id,
186
+ stream_index,
187
+ self._current_transcript_revision(database, version_id, stream_index),
188
+ annotation_suggestion(database, version_id),
189
+ )
190
+ database.execute(
191
+ "INSERT INTO annotation_command_receipts "
192
+ "(request_id,command_type,request_hash,response_json,created_at) "
193
+ "VALUES(?,'save_annotation',?,?,?)",
194
+ (
195
+ normalized_request,
196
+ request_hash,
197
+ json.dumps(response, ensure_ascii=False, sort_keys=True, separators=(",", ":")),
198
+ now,
199
+ ),
200
+ )
201
+ database.commit()
202
+ return response
203
+ except ProjectError:
204
+ raise
205
+ except (json.JSONDecodeError, TypeError, ValueError) as error:
206
+ raise ProjectError("annotation_invalid", "素材標註內容無效。", status_code=422) from error
207
+ except sqlite3.Error as error:
208
+ raise ProjectError("storage_failed", "Clipen 無法保存素材標註。", status_code=500) from error
209
+
210
+ @staticmethod
211
+ def _validate_identity(version_id: str, stream_index: int) -> None:
212
+ if not isinstance(version_id, str) or _VERSION_ID.fullmatch(version_id) is None:
213
+ raise ProjectError("annotation_not_found", "找不到這個素材。", status_code=404)
214
+ if isinstance(stream_index, bool) or not isinstance(stream_index, int) or stream_index < -1:
215
+ raise ProjectError("annotation_not_found", "找不到這個素材。", status_code=404)
216
+
217
+ @staticmethod
218
+ def _expected_revision(value: object) -> int:
219
+ if isinstance(value, bool) or not isinstance(value, int) or value < 0:
220
+ raise ProjectError("annotation_invalid", "素材標註版本無效。", status_code=422)
221
+ return value
222
+
223
+ @staticmethod
224
+ def _material(value: object) -> dict[str, object]:
225
+ if not isinstance(value, Mapping) or set(value) != {
226
+ "people",
227
+ "location",
228
+ "trip_day",
229
+ "day_part",
230
+ "note",
231
+ "usage",
232
+ }:
233
+ raise ProjectError("annotation_invalid", "素材標註內容無效。", status_code=422)
234
+ people = value["people"]
235
+ if not isinstance(people, list) or len(people) > 20:
236
+ raise ProjectError("annotation_invalid", "人物標註內容無效。", status_code=422)
237
+ normalized_people = []
238
+ for person in people:
239
+ if not isinstance(person, str) or not person.strip() or "\x00" in person or len(person.strip()) > 80:
240
+ raise ProjectError("annotation_invalid", "人物標註內容無效。", status_code=422)
241
+ normalized_people.append(person.strip())
242
+ if len(normalized_people) != len(set(normalized_people)):
243
+ raise ProjectError("annotation_invalid", "人物標註不能重複。", status_code=422)
244
+ location = value["location"]
245
+ note = value["note"]
246
+ if location is not None and (
247
+ not isinstance(location, str) or "\x00" in location or len(location.strip()) > 160
248
+ ):
249
+ raise ProjectError("annotation_invalid", "地點標註內容無效。", status_code=422)
250
+ if not isinstance(note, str) or "\x00" in note or len(note) > 2_000:
251
+ raise ProjectError("annotation_invalid", "剪輯備註內容無效。", status_code=422)
252
+ trip_day = value["trip_day"]
253
+ if trip_day is not None and (
254
+ isinstance(trip_day, bool) or not isinstance(trip_day, int) or not 1 <= trip_day <= 365
255
+ ):
256
+ raise ProjectError("annotation_invalid", "旅程日次無效。", status_code=422)
257
+ day_part = value["day_part"]
258
+ usage = value["usage"]
259
+ try:
260
+ if day_part is not None:
261
+ day_part = DayPart(day_part).value
262
+ usage = MaterialUsage(usage).value
263
+ except (TypeError, ValueError) as error:
264
+ raise ProjectError("annotation_invalid", "素材使用方式或旅程時段無效。", status_code=422) from error
265
+ return {
266
+ "people": normalized_people,
267
+ "location": None if location is None or not location.strip() else location.strip(),
268
+ "trip_day": trip_day,
269
+ "day_part": day_part,
270
+ "note": note.strip(),
271
+ "usage": usage,
272
+ }
273
+
274
+ @staticmethod
275
+ def _transcript(value: object, stream_index: int) -> dict[str, object] | None:
276
+ if value is None:
277
+ return None
278
+ if (
279
+ stream_index < 0
280
+ or not isinstance(value, Mapping)
281
+ or set(value) != {"source_revision_id", "confirmed", "discarded", "corrections"}
282
+ ):
283
+ raise ProjectError("annotation_invalid", "逐字稿修正內容無效。", status_code=422)
284
+ source_revision = value["source_revision_id"]
285
+ confirmed = value["confirmed"]
286
+ discarded = value["discarded"]
287
+ corrections = value["corrections"]
288
+ if (
289
+ not isinstance(source_revision, str)
290
+ or not source_revision
291
+ or not isinstance(confirmed, bool)
292
+ or not isinstance(discarded, bool)
293
+ or not isinstance(corrections, list)
294
+ or len(corrections) > 1_000
295
+ ):
296
+ raise ProjectError("annotation_invalid", "逐字稿修正內容無效。", status_code=422)
297
+ normalized = []
298
+ ordinals = set()
299
+ for correction in corrections:
300
+ if not isinstance(correction, Mapping) or set(correction) != {"ordinal", "text"}:
301
+ raise ProjectError("annotation_invalid", "逐字稿修正內容無效。", status_code=422)
302
+ ordinal = correction["ordinal"]
303
+ text = correction["text"]
304
+ if (
305
+ isinstance(ordinal, bool)
306
+ or not isinstance(ordinal, int)
307
+ or ordinal < 0
308
+ or ordinal in ordinals
309
+ or not isinstance(text, str)
310
+ or "\x00" in text
311
+ or len(text) > 1_000
312
+ ):
313
+ raise ProjectError("annotation_invalid", "逐字稿修正內容無效。", status_code=422)
314
+ ordinals.add(ordinal)
315
+ normalized.append({"ordinal": ordinal, "text": text.strip()})
316
+ return {
317
+ "source_revision_id": source_revision,
318
+ "confirmed": False if discarded else confirmed,
319
+ "discarded": discarded,
320
+ "corrections": normalized,
321
+ }
322
+
323
+ @staticmethod
324
+ def _require_version(database: sqlite3.Connection, version_id: str) -> None:
325
+ if database.execute("SELECT 1 FROM asset_versions WHERE version_id=?", (version_id,)).fetchone() is None:
326
+ raise ProjectError("annotation_not_found", "找不到這個素材。", status_code=404)
327
+
328
+ @staticmethod
329
+ def _current_transcript_revision(database: sqlite3.Connection, version_id: str, stream_index: int) -> str | None:
330
+ if stream_index < 0:
331
+ return None
332
+ row = database.execute(
333
+ "SELECT items.transcript_revision_id FROM current_preparation AS current "
334
+ "JOIN preparation_items AS items ON items.run_id=current.run_id "
335
+ "WHERE current.slot=1 AND items.version_id=? AND items.stream_index=? "
336
+ "AND items.status='transcribed'",
337
+ (version_id, stream_index),
338
+ ).fetchone()
339
+ return None if row is None else row["transcript_revision_id"]
340
+
341
+ @staticmethod
342
+ def _validate_corrections(database: sqlite3.Connection, revision_id: str, corrections: object) -> None:
343
+ available = {
344
+ row["ordinal"]
345
+ for row in database.execute("SELECT ordinal FROM transcript_segments WHERE revision_id=?", (revision_id,))
346
+ }
347
+ if any(item["ordinal"] not in available for item in corrections):
348
+ raise ProjectError("annotation_transcript_changed", "逐字稿片段已更新,請重新載入。", status_code=409)
349
+
350
+ @staticmethod
351
+ def _public(
352
+ material,
353
+ transcript,
354
+ version_id: str,
355
+ stream_index: int,
356
+ current_revision: str | None,
357
+ suggestion: dict[str, object],
358
+ ) -> dict[str, object]:
359
+ if material is None:
360
+ material_public = {
361
+ "version_id": version_id,
362
+ "revision": 0,
363
+ "people": [],
364
+ "location": None,
365
+ "trip_day": None,
366
+ "day_part": None,
367
+ "note": "",
368
+ "usage": "normal",
369
+ }
370
+ else:
371
+ people = json.loads(material["people_json"])
372
+ try:
373
+ normalized = AnnotationRepository._material(
374
+ {
375
+ "people": people,
376
+ "location": material["location"],
377
+ "trip_day": material["trip_day"],
378
+ "day_part": material["day_part"],
379
+ "note": material["note"],
380
+ "usage": material["usage"],
381
+ }
382
+ )
383
+ except ProjectError as error:
384
+ raise ValueError("stored material annotation is invalid") from error
385
+ if (
386
+ isinstance(material["revision"], bool)
387
+ or not isinstance(material["revision"], int)
388
+ or material["revision"] < 1
389
+ ):
390
+ raise ValueError("stored material annotation revision is invalid")
391
+ material_public = {
392
+ "version_id": version_id,
393
+ "revision": material["revision"],
394
+ **normalized,
395
+ }
396
+ transcript_public = None
397
+ if current_revision is not None:
398
+ stale = transcript is not None and transcript["source_revision_id"] != current_revision
399
+ corrections = [] if transcript is None or stale else json.loads(transcript["corrections_json"])
400
+ if transcript is not None and not stale:
401
+ try:
402
+ normalized_transcript = AnnotationRepository._transcript(
403
+ {
404
+ "source_revision_id": current_revision,
405
+ "confirmed": bool(transcript["confirmed"]),
406
+ "discarded": bool(transcript["discarded"]),
407
+ "corrections": corrections,
408
+ },
409
+ stream_index,
410
+ )
411
+ except ProjectError as error:
412
+ raise ValueError("stored transcript annotation is invalid") from error
413
+ assert normalized_transcript is not None
414
+ corrections = normalized_transcript["corrections"]
415
+ transcript_public = {
416
+ "stream_index": stream_index,
417
+ "revision": 0 if transcript is None else transcript["revision"],
418
+ "source_revision_id": current_revision,
419
+ "confirmed": False if transcript is None or stale else bool(transcript["confirmed"]),
420
+ "discarded": False if transcript is None else bool(transcript["discarded"]),
421
+ "corrections": corrections,
422
+ "stale": stale,
423
+ }
424
+ return {
425
+ "material": material_public,
426
+ "transcript": transcript_public,
427
+ "suggestion": suggestion,
428
+ }
@@ -0,0 +1,115 @@
1
+ """Conservative local suggestions derived from capture metadata."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import re
7
+ import sqlite3
8
+ from datetime import datetime
9
+
10
+ _FILENAME_TIME = re.compile(r"(?<!\d)(20\d{12})(?!\d)")
11
+
12
+
13
+ def annotation_suggestion(database: sqlite3.Connection, version_id: str) -> dict[str, object]:
14
+ return annotation_suggestions(database).get(version_id, _empty())
15
+
16
+
17
+ def annotation_suggestions(
18
+ database: sqlite3.Connection,
19
+ ) -> dict[str, dict[str, object]]:
20
+ rows = database.execute(
21
+ "SELECT versions.version_id,versions.probe_json,assets.relative_path "
22
+ "FROM current_inventory AS current "
23
+ "JOIN inventory_items AS items ON items.run_id=current.run_id "
24
+ "JOIN assets ON assets.asset_id=items.asset_id "
25
+ "JOIN asset_versions AS versions ON versions.version_id=items.version_id "
26
+ "WHERE current.slot=1 AND assets.role='source' AND items.kind='video' "
27
+ "AND items.status='usable' ORDER BY assets.relative_path",
28
+ ).fetchall()
29
+ captures: dict[str, datetime] = {}
30
+ locations: dict[str, str] = {}
31
+ sources: dict[str, str] = {}
32
+ for row in rows:
33
+ probe = _probe(row["probe_json"])
34
+ captured, source = _capture_time(row["relative_path"], probe)
35
+ if captured is not None:
36
+ captures[row["version_id"]] = captured
37
+ sources[row["version_id"]] = source
38
+ location = probe.get("location")
39
+ if isinstance(location, str) and location.strip() and len(location) <= 160:
40
+ locations[row["version_id"]] = location.strip()
41
+
42
+ day_numbers = {
43
+ capture_date: index
44
+ for index, capture_date in enumerate(sorted({value.date() for value in captures.values()}), start=1)
45
+ }
46
+ result: dict[str, dict[str, object]] = {}
47
+ for row in rows:
48
+ version_id = row["version_id"]
49
+ target = captures.get(version_id)
50
+ suggestion = _empty()
51
+ suggestion["location"] = locations.get(version_id)
52
+ if target is not None:
53
+ suggestion["trip_day"] = day_numbers[target.date()]
54
+ suggestion["day_part"] = _day_part(target.hour)
55
+ suggestion["capture_time"] = target.isoformat(timespec="seconds")
56
+ suggestion["time_source"] = sources[version_id]
57
+ result[version_id] = suggestion
58
+ return result
59
+
60
+
61
+ def _empty() -> dict[str, object]:
62
+ return {
63
+ "trip_day": None,
64
+ "day_part": None,
65
+ "location": None,
66
+ "capture_time": None,
67
+ "time_source": None,
68
+ }
69
+
70
+
71
+ def _probe(raw: object) -> dict[str, object]:
72
+ if not isinstance(raw, str):
73
+ return {}
74
+ try:
75
+ value = json.loads(raw)
76
+ except json.JSONDecodeError:
77
+ return {}
78
+ return value if isinstance(value, dict) else {}
79
+
80
+
81
+ def _capture_time(relative_path: str, probe: dict[str, object]) -> tuple[datetime | None, str]:
82
+ name = relative_path.rsplit("/", 1)[-1]
83
+ match = _FILENAME_TIME.search(name)
84
+ if match is not None:
85
+ try:
86
+ return datetime.strptime(match.group(1), "%Y%m%d%H%M%S"), "filename"
87
+ except ValueError:
88
+ pass
89
+ raw = probe.get("capture_time")
90
+ if not isinstance(raw, str):
91
+ return None, ""
92
+ try:
93
+ captured = datetime.fromisoformat(raw.replace("Z", "+00:00"))
94
+ except ValueError:
95
+ return None, ""
96
+ # Camera metadata represents the wall-clock time at the recording location.
97
+ # Converting it to the workstation timezone can move travel footage into a
98
+ # different day or day part, so preserve the recorded calendar values.
99
+ return captured.replace(tzinfo=None), "metadata"
100
+
101
+
102
+ def _day_part(hour: int) -> str:
103
+ if 4 <= hour < 6:
104
+ return "dawn"
105
+ if 6 <= hour < 12:
106
+ return "morning"
107
+ if 12 <= hour < 14:
108
+ return "noon"
109
+ if 14 <= hour < 18:
110
+ return "afternoon"
111
+ if 18 <= hour < 20:
112
+ return "evening"
113
+ if 20 <= hour:
114
+ return "night"
115
+ return "late_night"
@@ -0,0 +1,132 @@
1
+ """Standard-library-only release contract shared by bootstrap and analysis."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ import os
8
+ import stat
9
+ from pathlib import Path
10
+
11
+ NOTICE_VERSION = "asr-qwen3-1.7b-confidence-v1"
12
+ RELEASE_ID = "qwen3-asr-1.7b-confidence-v1"
13
+ SUPERSEDED_RELEASE_IDS = (
14
+ "mlx-whisper-small-v1",
15
+ "mlx-whisper-large-v3-turbo-v1",
16
+ "funasr-nano-consensus-v1",
17
+ )
18
+ MODEL_ID = "qwen3-asr-1.7b-int8"
19
+ MODEL_NAME = "Qwen3-ASR 1.7B(Int8)"
20
+ MODEL_REVISION = "a27b3ef0cd9c8115e13baa55b1be8992b3589756"
21
+ MODEL_REPOSITORY = "appautomaton/qwen3-asr-1.7b-int8-mlx"
22
+ MODEL_FILES = (
23
+ ("chat_template.json", 1_161, "75a8cfca24f00de72d796fbfed6858fc9614ef3dabd8696684cc3bc03a9c58ff"),
24
+ ("config.json", 5_849, "5e35ceadb80a954a4790152ab45a91366d2a5c84ae6e42a3d3efb810df3b3374"),
25
+ ("generation_config.json", 142, "1da527824d81e07118facff437e03f2e24a23311e3bdeb2368973fe77e5f275c"),
26
+ ("merges.txt", 1_671_853, "8831e4f1a044471340f7c0a83d7bd71306a5b867e95fd870f74d0c5308a904d5"),
27
+ ("model.safetensors", 2_506_670_749, "8a9aca31c5715d080f7d891dbac08146aeddf8c34cd53e46cf24d665dcd33786"),
28
+ ("preprocessor_config.json", 330, "45e120a4eda2c20c5d7f2ea9354e63536bf35e27aa573fb7cdf78017b378770d"),
29
+ ("tokenizer_config.json", 12_487, "4942d005604266809309cabc9f4e9cb89ce855d59b14681fdc0e1cc62ea26c4c"),
30
+ ("vocab.json", 2_776_833, "ca10d7e9fb3ed18575dd1e277a2579c16d108e32f27439684afa0e10b1440910"),
31
+ )
32
+ MODEL_DOWNLOADS = tuple(
33
+ (
34
+ filename,
35
+ f"https://huggingface.co/{MODEL_REPOSITORY}/resolve/{MODEL_REVISION}/{filename}",
36
+ size,
37
+ digest,
38
+ )
39
+ for filename, size, digest in MODEL_FILES
40
+ )
41
+ DOWNLOAD_BYTES = sum(item[1] for item in MODEL_FILES) + 260_000_000
42
+ INSTALLED_BYTES = sum(item[1] for item in MODEL_FILES) + 420_000_000
43
+ ASR_SOFTWARE_LICENSE = "MIT"
44
+ ASR_SOFTWARE_LICENSE_URL = "https://github.com/appautomaton/mlx-speech/blob/main/LICENSE"
45
+ MODEL_LICENSE = "Apache-2.0"
46
+ MODEL_LICENSE_URL = f"https://huggingface.co/{MODEL_REPOSITORY}"
47
+ LICENSE_NOTICE = (
48
+ "Qwen3-ASR 模型採 Apache-2.0,MLX Speech 執行程式採 MIT;Clipen 只下載固定版本,不會把模型檔收進 Repo。"
49
+ )
50
+ PROGRESS_RECORD_PREFIX = "CLIPEN_PROGRESS\t"
51
+
52
+
53
+ def release_root(data_root: Path) -> Path:
54
+ return Path(data_root) / "asr" / RELEASE_ID
55
+
56
+
57
+ def requirements_digest(requirements: Path) -> str:
58
+ digest = hashlib.sha256()
59
+ with Path(requirements).open("rb") as source:
60
+ while block := source.read(1024 * 1024):
61
+ digest.update(block)
62
+ return digest.hexdigest()
63
+
64
+
65
+ def quick_release_is_ready(data_root: Path, requirements: Path) -> bool:
66
+ """Cheap bootstrap check; the controller performs the full content hash."""
67
+
68
+ release = release_root(data_root)
69
+ receipt_path = release / "receipt.json"
70
+ if release.is_symlink() or not release.is_dir():
71
+ return False
72
+ if receipt_path.is_symlink() or not receipt_path.is_file():
73
+ return False
74
+ try:
75
+ receipt = json.loads(receipt_path.read_text(encoding="utf-8"))
76
+ required = {
77
+ "schema": 3,
78
+ "release_id": RELEASE_ID,
79
+ "notice_version": NOTICE_VERSION,
80
+ "model_id": MODEL_ID,
81
+ "model_revision": MODEL_REVISION,
82
+ "requirements_sha256": requirements_digest(requirements),
83
+ "runtime_python": "runtime/bin/python",
84
+ "model_path": "model",
85
+ }
86
+ if not isinstance(receipt, dict) or any(receipt.get(key) != value for key, value in required.items()):
87
+ return False
88
+ if set(receipt) != {*required, "model_manifest_sha256"}:
89
+ return False
90
+ manifest = receipt.get("model_manifest_sha256")
91
+ if not isinstance(manifest, str) or len(manifest) != 64:
92
+ return False
93
+ runtime_root = release / "runtime"
94
+ runtime_bin = runtime_root / "bin"
95
+ model_root = release / "model"
96
+ if any(path.is_symlink() or not path.is_dir() for path in (runtime_root, runtime_bin, model_root)):
97
+ return False
98
+ python = runtime_bin / "python"
99
+ if python.is_symlink() or not python.is_file() or not os.access(python, os.X_OK):
100
+ return False
101
+ for filename, size, _digest in MODEL_FILES:
102
+ path = model_root / filename
103
+ info = os.lstat(path)
104
+ if path.is_symlink() or not stat.S_ISREG(info.st_mode) or info.st_size != size:
105
+ return False
106
+ return True
107
+ except (OSError, UnicodeError, json.JSONDecodeError):
108
+ return False
109
+
110
+
111
+ __all__ = [
112
+ "ASR_SOFTWARE_LICENSE",
113
+ "ASR_SOFTWARE_LICENSE_URL",
114
+ "DOWNLOAD_BYTES",
115
+ "INSTALLED_BYTES",
116
+ "LICENSE_NOTICE",
117
+ "MODEL_DOWNLOADS",
118
+ "MODEL_FILES",
119
+ "MODEL_ID",
120
+ "MODEL_LICENSE",
121
+ "MODEL_LICENSE_URL",
122
+ "MODEL_NAME",
123
+ "MODEL_REPOSITORY",
124
+ "MODEL_REVISION",
125
+ "NOTICE_VERSION",
126
+ "PROGRESS_RECORD_PREFIX",
127
+ "RELEASE_ID",
128
+ "SUPERSEDED_RELEASE_IDS",
129
+ "quick_release_is_ready",
130
+ "release_root",
131
+ "requirements_digest",
132
+ ]