@clipen/clipen-cli 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (232) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +79 -2
  3. package/apps/web/dist/assets/index-D5D2HiB1.js +14 -0
  4. package/apps/web/dist/assets/index-DIMuOXSu.css +1 -0
  5. package/apps/web/dist/favicon.svg +1 -0
  6. package/apps/web/dist/index.html +16 -0
  7. package/bin/clipen.js +157 -0
  8. package/clipen +18 -0
  9. package/install +25 -0
  10. package/package.json +52 -4
  11. package/pyproject.toml +28 -0
  12. package/requirements/asr-runtime.txt +13 -0
  13. package/requirements/runtime.txt +20 -0
  14. package/src/clipen/__init__.py +3 -0
  15. package/src/clipen/analysis/__init__.py +89 -0
  16. package/src/clipen/analysis/artifacts.py +416 -0
  17. package/src/clipen/analysis/audio.py +392 -0
  18. package/src/clipen/analysis/evidence.py +102 -0
  19. package/src/clipen/analysis/evidence_service.py +751 -0
  20. package/src/clipen/analysis/image_similarity.py +143 -0
  21. package/src/clipen/analysis/keyframes.py +171 -0
  22. package/src/clipen/analysis/models.py +230 -0
  23. package/src/clipen/analysis/qwen_worker.py +629 -0
  24. package/src/clipen/analysis/resources.py +21 -0
  25. package/src/clipen/analysis/runtime.py +64 -0
  26. package/src/clipen/analysis/service.py +626 -0
  27. package/src/clipen/analysis/setup.py +935 -0
  28. package/src/clipen/analysis/setup_cli.py +117 -0
  29. package/src/clipen/analysis/storage.py +2046 -0
  30. package/src/clipen/analysis/transcription.py +948 -0
  31. package/src/clipen/analysis/visual.py +176 -0
  32. package/src/clipen/annotations/__init__.py +10 -0
  33. package/src/clipen/annotations/models.py +22 -0
  34. package/src/clipen/annotations/storage.py +380 -0
  35. package/src/clipen/annotations/suggestions.py +120 -0
  36. package/src/clipen/asr_release.py +139 -0
  37. package/src/clipen/bootstrap.py +967 -0
  38. package/src/clipen/cli.py +84 -0
  39. package/src/clipen/controller/__init__.py +17 -0
  40. package/src/clipen/controller/app.py +1470 -0
  41. package/src/clipen/controller/server.py +543 -0
  42. package/src/clipen/domain/__init__.py +30 -0
  43. package/src/clipen/domain/errors.py +5 -0
  44. package/src/clipen/domain/media_time.py +117 -0
  45. package/src/clipen/domain/timeline.py +584 -0
  46. package/src/clipen/domain/validation.py +15 -0
  47. package/src/clipen/editing/EDITORIAL_REGRESSIONS.md +38 -0
  48. package/src/clipen/editing/PROGRAM_FORMAT.md +102 -0
  49. package/src/clipen/editing/README.md +115 -0
  50. package/src/clipen/editing/REFACTOR_DESIGN.md +241 -0
  51. package/src/clipen/editing/REFACTOR_HANDOFF.md +73 -0
  52. package/src/clipen/editing/__init__.py +15 -0
  53. package/src/clipen/editing/agent.py +13 -0
  54. package/src/clipen/editing/agent_models.py +134 -0
  55. package/src/clipen/editing/agent_repository.py +757 -0
  56. package/src/clipen/editing/agent_tools.py +532 -0
  57. package/src/clipen/editing/alignment.py +110 -0
  58. package/src/clipen/editing/alignment_setup.py +108 -0
  59. package/src/clipen/editing/alignment_worker.py +22 -0
  60. package/src/clipen/editing/change_report.py +71 -0
  61. package/src/clipen/editing/compiler.py +41 -0
  62. package/src/clipen/editing/component_looks.py +107 -0
  63. package/src/clipen/editing/component_review.py +78 -0
  64. package/src/clipen/editing/coordinator.py +374 -0
  65. package/src/clipen/editing/editorial_review.py +187 -0
  66. package/src/clipen/editing/evidence_jobs.py +295 -0
  67. package/src/clipen/editing/history_changes.py +131 -0
  68. package/src/clipen/editing/music_choices.py +15 -0
  69. package/src/clipen/editing/production_catalog.py +192 -0
  70. package/src/clipen/editing/production_limits.py +59 -0
  71. package/src/clipen/editing/production_media.py +226 -0
  72. package/src/clipen/editing/production_preview.py +180 -0
  73. package/src/clipen/editing/production_progress.py +141 -0
  74. package/src/clipen/editing/production_requirements.py +50 -0
  75. package/src/clipen/editing/production_tools.py +596 -0
  76. package/src/clipen/editing/program_audio.py +118 -0
  77. package/src/clipen/editing/program_direction.py +49 -0
  78. package/src/clipen/editing/program_story.py +53 -0
  79. package/src/clipen/editing/program_subtitles.py +134 -0
  80. package/src/clipen/editing/programme_review.py +73 -0
  81. package/src/clipen/editing/prompt_history.py +47 -0
  82. package/src/clipen/editing/recut.py +127 -0
  83. package/src/clipen/editing/refinement_references.py +188 -0
  84. package/src/clipen/editing/resolve_export.py +616 -0
  85. package/src/clipen/editing/resolve_titles.py +234 -0
  86. package/src/clipen/editing/skill_tools.py +575 -0
  87. package/src/clipen/editing/source_dialogue.py +82 -0
  88. package/src/clipen/editing/speech_coverage.py +30 -0
  89. package/src/clipen/editing/speech_quality.py +6 -0
  90. package/src/clipen/editing/tool_receipts.py +52 -0
  91. package/src/clipen/editing/versions.py +161 -0
  92. package/src/clipen/editing/visual_preview.py +93 -0
  93. package/src/clipen/editing/workbench.py +74 -0
  94. package/src/clipen/filesystem.py +25 -0
  95. package/src/clipen/finishing/README.md +103 -0
  96. package/src/clipen/finishing/__init__.py +1 -0
  97. package/src/clipen/finishing/audio.py +149 -0
  98. package/src/clipen/finishing/catalog.py +181 -0
  99. package/src/clipen/finishing/models.py +14 -0
  100. package/src/clipen/finishing/renderer.py +26 -0
  101. package/src/clipen/mcp_editing/__init__.py +5 -0
  102. package/src/clipen/mcp_editing/__main__.py +40 -0
  103. package/src/clipen/mcp_editing/server.py +353 -0
  104. package/src/clipen/media/__init__.py +50 -0
  105. package/src/clipen/media/discovery.py +266 -0
  106. package/src/clipen/media/models.py +360 -0
  107. package/src/clipen/media/preview.py +147 -0
  108. package/src/clipen/media/probe.py +446 -0
  109. package/src/clipen/media/service.py +317 -0
  110. package/src/clipen/media/storage.py +742 -0
  111. package/src/clipen/music_vocabulary.py +5 -0
  112. package/src/clipen/planning/__init__.py +9 -0
  113. package/src/clipen/planning/models.py +240 -0
  114. package/src/clipen/power.py +23 -0
  115. package/src/clipen/projects/__init__.py +26 -0
  116. package/src/clipen/projects/agent_schema.py +94 -0
  117. package/src/clipen/projects/annotation_schema.py +40 -0
  118. package/src/clipen/projects/deletion.py +269 -0
  119. package/src/clipen/projects/evidence_schema.py +52 -0
  120. package/src/clipen/projects/finishing_schema.py +34 -0
  121. package/src/clipen/projects/models.py +192 -0
  122. package/src/clipen/projects/picker.py +256 -0
  123. package/src/clipen/projects/preview_schema.py +29 -0
  124. package/src/clipen/projects/service.py +175 -0
  125. package/src/clipen/projects/storage.py +1478 -0
  126. package/src/clipen/projects/timeline_schema.py +32 -0
  127. package/src/clipen/projects/validation_schema.py +28 -0
  128. package/src/clipen/provider_registry.py +75 -0
  129. package/src/clipen/providers/__init__.py +43 -0
  130. package/src/clipen/providers/account.py +194 -0
  131. package/src/clipen/providers/claude.py +375 -0
  132. package/src/clipen/providers/claude_editing.py +111 -0
  133. package/src/clipen/providers/codex.py +1036 -0
  134. package/src/clipen/providers/codex_editing.py +91 -0
  135. package/src/clipen/providers/editing_agent.py +565 -0
  136. package/src/clipen/providers/errors.py +51 -0
  137. package/src/clipen/providers/recovery.py +270 -0
  138. package/src/clipen/py.typed +1 -0
  139. package/src/clipen/rendering/__init__.py +12 -0
  140. package/src/clipen/rendering/cover.py +126 -0
  141. package/src/clipen/rendering/custom_components.py +240 -0
  142. package/src/clipen/rendering/custom_render.py +197 -0
  143. package/src/clipen/rendering/fonts/anton-OFL.txt +93 -0
  144. package/src/clipen/rendering/fonts/bebasneue-OFL.txt +93 -0
  145. package/src/clipen/rendering/fonts/caveat-OFL.txt +93 -0
  146. package/src/clipen/rendering/fonts/chenyu-OFL.txt +93 -0
  147. package/src/clipen/rendering/fonts/delagothicone-OFL.txt +93 -0
  148. package/src/clipen/rendering/fonts/hachimarupop-OFL.txt +93 -0
  149. package/src/clipen/rendering/fonts/iansui-OFL.txt +93 -0
  150. package/src/clipen/rendering/fonts/manifest.json +145 -0
  151. package/src/clipen/rendering/fonts/playfairdisplay-OFL.txt +93 -0
  152. package/src/clipen/rendering/fonts/rocknrollone-OFL.txt +93 -0
  153. package/src/clipen/rendering/fonts/yomogi-OFL.txt +94 -0
  154. package/src/clipen/rendering/fonts/yuseimagic-OFL.txt +93 -0
  155. package/src/clipen/rendering/fonts/zenkurenaido-OFL.txt +93 -0
  156. package/src/clipen/rendering/fonts/zenmarugothic-OFL.txt +93 -0
  157. package/src/clipen/rendering/production_effects.py +64 -0
  158. package/src/clipen/rendering/program_components.py +193 -0
  159. package/src/clipen/rendering/program_creator.py +649 -0
  160. package/src/clipen/rendering/program_identities.py +255 -0
  161. package/src/clipen/rendering/program_motion.py +141 -0
  162. package/src/clipen/rendering/program_studio.py +168 -0
  163. package/src/clipen/rendering/program_styles.py +235 -0
  164. package/src/clipen/rendering/program_subtitles.py +52 -0
  165. package/src/clipen/rendering/renderer.py +708 -0
  166. package/src/clipen/rendering/storage.py +243 -0
  167. package/src/clipen/rendering/titles.py +360 -0
  168. package/src/clipen/skills/__init__.py +4 -0
  169. package/src/clipen/skills/builtin/SKILL.md +72 -0
  170. package/src/clipen/skills/builtin/assets/sample-daily-vlog.mp4 +0 -0
  171. package/src/clipen/skills/builtin/assets/sample-event-recap.mp4 +0 -0
  172. package/src/clipen/skills/builtin/assets/sample-food-review.mp4 +0 -0
  173. package/src/clipen/skills/builtin/assets/sample-product-demo.mp4 +0 -0
  174. package/src/clipen/skills/builtin/assets/sample-product-review.mp4 +0 -0
  175. package/src/clipen/skills/builtin/assets/sample-product-unboxing.mp4 +0 -0
  176. package/src/clipen/skills/builtin/assets/sample-shorts-highlight.mp4 +0 -0
  177. package/src/clipen/skills/builtin/assets/sample-travel-highlight.mp4 +0 -0
  178. package/src/clipen/skills/builtin/assets/sample-travel-vlog.mp4 +0 -0
  179. package/src/clipen/skills/builtin/assets/style-cinema.png +0 -0
  180. package/src/clipen/skills/builtin/assets/style-editorial.png +0 -0
  181. package/src/clipen/skills/builtin/assets/style-tpl-daily-vlog.png +0 -0
  182. package/src/clipen/skills/builtin/assets/style-tpl-event-recap.png +0 -0
  183. package/src/clipen/skills/builtin/assets/style-tpl-food-review.png +0 -0
  184. package/src/clipen/skills/builtin/assets/style-tpl-product-demo.png +0 -0
  185. package/src/clipen/skills/builtin/assets/style-tpl-product-review.png +0 -0
  186. package/src/clipen/skills/builtin/assets/style-tpl-product-unboxing.png +0 -0
  187. package/src/clipen/skills/builtin/assets/style-tpl-shorts-highlight.png +0 -0
  188. package/src/clipen/skills/builtin/assets/style-tpl-travel-highlight.png +0 -0
  189. package/src/clipen/skills/builtin/assets/style-tpl-travel-vlog.png +0 -0
  190. package/src/clipen/skills/builtin/assets/style-variety.png +0 -0
  191. package/src/clipen/skills/builtin/components.json +133 -0
  192. package/src/clipen/skills/builtin/font_sources.json +20 -0
  193. package/src/clipen/skills/builtin/font_styles.json +329 -0
  194. package/src/clipen/skills/builtin/manifest.json +32 -0
  195. package/src/clipen/skills/builtin/presets.json +8 -0
  196. package/src/clipen/skills/builtin/references/captions.md +14 -0
  197. package/src/clipen/skills/builtin/references/channel-design.md +37 -0
  198. package/src/clipen/skills/builtin/references/editing.md +30 -0
  199. package/src/clipen/skills/builtin/references/font-chenyu-OFL.txt +93 -0
  200. package/src/clipen/skills/builtin/references/font-iansui-OFL.txt +93 -0
  201. package/src/clipen/skills/builtin/references/graphics.md +59 -0
  202. package/src/clipen/skills/builtin/references/review.md +16 -0
  203. package/src/clipen/skills/builtin/references/sound.md +8 -0
  204. package/src/clipen/skills/builtin/references/story.md +7 -0
  205. package/src/clipen/skills/builtin/skills/travel-program/SKILL.md +27 -0
  206. package/src/clipen/skills/builtin/skills/travel-program/manifest.json +6 -0
  207. package/src/clipen/skills/builtin/template-skills/clipen-daily-vlog/SKILL.md +33 -0
  208. package/src/clipen/skills/builtin/template-skills/clipen-daily-vlog/manifest.json +8 -0
  209. package/src/clipen/skills/builtin/template-skills/clipen-event-recap/SKILL.md +34 -0
  210. package/src/clipen/skills/builtin/template-skills/clipen-event-recap/manifest.json +8 -0
  211. package/src/clipen/skills/builtin/template-skills/clipen-food-review/SKILL.md +33 -0
  212. package/src/clipen/skills/builtin/template-skills/clipen-food-review/manifest.json +8 -0
  213. package/src/clipen/skills/builtin/template-skills/clipen-product-demo/SKILL.md +35 -0
  214. package/src/clipen/skills/builtin/template-skills/clipen-product-demo/manifest.json +8 -0
  215. package/src/clipen/skills/builtin/template-skills/clipen-product-review/SKILL.md +36 -0
  216. package/src/clipen/skills/builtin/template-skills/clipen-product-review/manifest.json +8 -0
  217. package/src/clipen/skills/builtin/template-skills/clipen-product-unboxing/SKILL.md +39 -0
  218. package/src/clipen/skills/builtin/template-skills/clipen-product-unboxing/manifest.json +8 -0
  219. package/src/clipen/skills/builtin/template-skills/clipen-shorts-highlight/SKILL.md +38 -0
  220. package/src/clipen/skills/builtin/template-skills/clipen-shorts-highlight/manifest.json +8 -0
  221. package/src/clipen/skills/builtin/template-skills/clipen-travel-highlight/SKILL.md +34 -0
  222. package/src/clipen/skills/builtin/template-skills/clipen-travel-highlight/manifest.json +8 -0
  223. package/src/clipen/skills/builtin/template-skills/clipen-travel-vlog/SKILL.md +37 -0
  224. package/src/clipen/skills/builtin/template-skills/clipen-travel-vlog/manifest.json +8 -0
  225. package/src/clipen/skills/builtin/templates.json +284 -0
  226. package/src/clipen/skills/builtin/visual_styles.json +1074 -0
  227. package/src/clipen/skills/catalog.py +218 -0
  228. package/src/clipen/skills/library.py +131 -0
  229. package/src/clipen/skills/package.py +231 -0
  230. package/src/clipen/skills/visual_styles.py +44 -0
  231. package/src/clipen/workspace.py +210 -0
  232. package/uninstall +25 -0
@@ -0,0 +1,742 @@
1
+ """Transactional storage and publish semantics for media inventories."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ import sqlite3
8
+
9
+ from clipen.projects.models import (
10
+ DirectoryRole,
11
+ ProjectError,
12
+ validate_project_id,
13
+ validate_request_id,
14
+ validate_revision,
15
+ )
16
+ from clipen.projects.storage import ProjectRepository, command_digest, utc_now
17
+
18
+ from .models import (
19
+ AssetCandidate,
20
+ AssetKind,
21
+ InventoryCounts,
22
+ InventoryItem,
23
+ InventoryPage,
24
+ InventoryRoot,
25
+ InventoryRun,
26
+ InventoryState,
27
+ ItemStatus,
28
+ MediaStream,
29
+ ProbeStatus,
30
+ make_run_id,
31
+ validate_run_id,
32
+ )
33
+
34
+
35
+ _TERMINAL_STATES = frozenset(
36
+ {
37
+ InventoryState.SUCCEEDED,
38
+ InventoryState.FAILED,
39
+ InventoryState.CANCELLED,
40
+ InventoryState.INTERRUPTED,
41
+ }
42
+ )
43
+ _TRANSITIONS = {
44
+ InventoryState.QUEUED: {
45
+ InventoryState.RUNNING,
46
+ InventoryState.CANCELLED,
47
+ InventoryState.INTERRUPTED,
48
+ },
49
+ InventoryState.RUNNING: {
50
+ InventoryState.CANCELLING,
51
+ InventoryState.SUCCEEDED,
52
+ InventoryState.FAILED,
53
+ InventoryState.CANCELLED,
54
+ InventoryState.INTERRUPTED,
55
+ },
56
+ InventoryState.CANCELLING: {
57
+ InventoryState.CANCELLED,
58
+ InventoryState.FAILED,
59
+ InventoryState.INTERRUPTED,
60
+ },
61
+ }
62
+
63
+
64
+ class InventoryRepository:
65
+ def __init__(self, projects: ProjectRepository) -> None:
66
+ self.projects = projects
67
+
68
+ def create_run(
69
+ self,
70
+ project_id: str,
71
+ request_id: object,
72
+ expected_revision: object,
73
+ ) -> InventoryRun:
74
+ run, _ = self.create_run_with_status(project_id, request_id, expected_revision)
75
+ return run
76
+
77
+ def create_run_with_status(
78
+ self,
79
+ project_id: str,
80
+ request_id: object,
81
+ expected_revision: object,
82
+ ) -> tuple[InventoryRun, bool]:
83
+ """Create a queued run and report whether this call created it.
84
+
85
+ The boolean prevents a replayed request from accidentally scheduling an old
86
+ queued run in a new controller process.
87
+ """
88
+ validate_project_id(project_id)
89
+ normalized_request = validate_request_id(request_id)
90
+ revision = validate_revision(expected_revision)
91
+ request_hash = command_digest({"expected_revision": revision})
92
+ run_id = make_run_id(project_id, normalized_request)
93
+ with self.projects.connect(project_id) as connection:
94
+ try:
95
+ connection.execute("BEGIN IMMEDIATE")
96
+ receipt = connection.execute(
97
+ "SELECT command_type, request_hash, run_id "
98
+ "FROM inventory_command_receipts WHERE request_id = ?",
99
+ (normalized_request,),
100
+ ).fetchone()
101
+ if receipt is not None:
102
+ if (
103
+ receipt["command_type"] != "start_inventory"
104
+ or receipt["request_hash"] != request_hash
105
+ ):
106
+ raise ProjectError(
107
+ "request_reused",
108
+ "這次操作的識別資訊已用於不同內容。",
109
+ status_code=409,
110
+ )
111
+ replay = self._read_run(connection, receipt["run_id"])
112
+ connection.rollback()
113
+ return replay, False
114
+
115
+ project = connection.execute(
116
+ "SELECT revision FROM project WHERE project_id = ?", (project_id,)
117
+ ).fetchone()
118
+ if project is None:
119
+ raise ProjectError("project_not_found", "找不到這個作品。", status_code=404)
120
+ if project["revision"] != revision:
121
+ raise ProjectError(
122
+ "revision_conflict",
123
+ "作品已在其他分頁更新,請重新載入最新內容。",
124
+ status_code=409,
125
+ )
126
+ rows = connection.execute(
127
+ "SELECT role, canonical_path, device, inode, saved_at "
128
+ "FROM project_directories ORDER BY role"
129
+ ).fetchall()
130
+ roots = tuple(
131
+ InventoryRoot(
132
+ DirectoryRole(row["role"]),
133
+ row["canonical_path"],
134
+ row["device"],
135
+ row["inode"],
136
+ row["saved_at"],
137
+ )
138
+ for row in rows
139
+ )
140
+ if DirectoryRole.SOURCE not in {root.role for root in roots}:
141
+ raise ProjectError(
142
+ "source_required",
143
+ "請先選擇毛片資料夾。",
144
+ status_code=409,
145
+ )
146
+ incomplete = connection.execute(
147
+ "SELECT run_id FROM inventory_runs "
148
+ "WHERE state IN ('queued', 'running', 'cancelling') LIMIT 1"
149
+ ).fetchone()
150
+ if incomplete is not None:
151
+ raise ProjectError(
152
+ "inventory_busy",
153
+ "已有一個素材檢查正在進行。",
154
+ status_code=409,
155
+ )
156
+ roots_json = json.dumps(
157
+ [root.to_storage() for root in roots],
158
+ ensure_ascii=False,
159
+ sort_keys=True,
160
+ separators=(",", ":"),
161
+ )
162
+ fingerprint = hashlib.sha256(
163
+ json.dumps(
164
+ {
165
+ "project_revision": revision,
166
+ "roots": json.loads(roots_json),
167
+ },
168
+ ensure_ascii=False,
169
+ sort_keys=True,
170
+ separators=(",", ":"),
171
+ ).encode("utf-8")
172
+ ).hexdigest()
173
+ now = utc_now()
174
+ connection.execute(
175
+ "INSERT INTO inventory_runs "
176
+ "(run_id, project_id, request_id, project_revision, input_fingerprint, "
177
+ "roots_json, state, phase, created_at) "
178
+ "VALUES (?, ?, ?, ?, ?, ?, 'queued', 'preparing', ?)",
179
+ (
180
+ run_id,
181
+ project_id,
182
+ normalized_request,
183
+ revision,
184
+ fingerprint,
185
+ roots_json,
186
+ now,
187
+ ),
188
+ )
189
+ connection.execute(
190
+ "INSERT INTO inventory_command_receipts "
191
+ "(request_id, command_type, request_hash, run_id, created_at) "
192
+ "VALUES (?, 'start_inventory', ?, ?, ?)",
193
+ (normalized_request, request_hash, run_id, now),
194
+ )
195
+ created = self._read_run(connection, run_id)
196
+ connection.commit()
197
+ return created, True
198
+ except ProjectError:
199
+ connection.rollback()
200
+ raise
201
+ except (json.JSONDecodeError, KeyError, TypeError, ValueError) as error:
202
+ connection.rollback()
203
+ raise ProjectError(
204
+ "storage_corrupt", "Clipen 無法讀取素材檢查紀錄。", status_code=500
205
+ ) from error
206
+ except sqlite3.Error as error:
207
+ connection.rollback()
208
+ raise ProjectError(
209
+ "storage_failed", "Clipen 無法建立素材檢查。", status_code=500
210
+ ) from error
211
+
212
+ def get_run(self, project_id: str, run_id: object) -> InventoryRun:
213
+ validate_project_id(project_id)
214
+ normalized_run = validate_run_id(run_id)
215
+ with self.projects.connect(project_id) as connection:
216
+ run = self._read_run(connection, normalized_run)
217
+ if run.project_id != project_id:
218
+ raise ProjectError("inventory_not_found", "找不到這次素材檢查。", status_code=404)
219
+ return run
220
+
221
+ def current_run(self, project_id: str) -> InventoryRun | None:
222
+ validate_project_id(project_id)
223
+ with self.projects.connect(project_id) as connection:
224
+ row = connection.execute(
225
+ "SELECT run_id FROM current_inventory WHERE slot = 1"
226
+ ).fetchone()
227
+ return None if row is None else self._read_run(connection, row["run_id"])
228
+
229
+ def latest_run(self, project_id: str) -> InventoryRun | None:
230
+ validate_project_id(project_id)
231
+ with self.projects.connect(project_id) as connection:
232
+ row = connection.execute(
233
+ "SELECT run_id FROM inventory_runs ORDER BY created_at DESC LIMIT 1"
234
+ ).fetchone()
235
+ return None if row is None else self._read_run(connection, row["run_id"])
236
+
237
+ def list_items(
238
+ self,
239
+ project_id: str,
240
+ run_id: object,
241
+ *,
242
+ offset: int = 0,
243
+ limit: int = 100,
244
+ ) -> InventoryPage:
245
+ validate_project_id(project_id)
246
+ normalized_run = validate_run_id(run_id)
247
+ if (
248
+ isinstance(offset, bool)
249
+ or not isinstance(offset, int)
250
+ or offset < 0
251
+ or isinstance(limit, bool)
252
+ or not isinstance(limit, int)
253
+ or not 1 <= limit <= 200
254
+ ):
255
+ raise ProjectError(
256
+ "pagination_invalid", "素材清單頁碼無效。", status_code=422
257
+ )
258
+ with self.projects.connect(project_id) as connection:
259
+ run = self._read_run(connection, normalized_run)
260
+ if run.project_id != project_id:
261
+ raise ProjectError(
262
+ "inventory_not_found", "找不到這次素材檢查。", status_code=404
263
+ )
264
+ total = connection.execute(
265
+ "SELECT COUNT(*) FROM inventory_items WHERE run_id = ?",
266
+ (normalized_run,),
267
+ ).fetchone()[0]
268
+ rows = connection.execute(
269
+ "SELECT i.asset_id, a.role, a.relative_path, i.display_name, i.kind, "
270
+ "i.status, i.issue_code, v.version_id, v.size_bytes, v.probe_status, "
271
+ "v.probe_json FROM inventory_items i "
272
+ "JOIN assets a ON a.asset_id = i.asset_id "
273
+ "LEFT JOIN asset_versions v ON v.version_id = i.version_id "
274
+ "WHERE i.run_id = ? "
275
+ "ORDER BY CASE i.status WHEN 'needs_attention' THEN 0 "
276
+ "WHEN 'usable' THEN 1 ELSE 2 END, i.display_name COLLATE NOCASE, i.asset_id "
277
+ "LIMIT ? OFFSET ?",
278
+ (normalized_run, limit, offset),
279
+ ).fetchall()
280
+ version_ids = [row["version_id"] for row in rows if row["version_id"]]
281
+ streams_by_version: dict[str, list[MediaStream]] = {}
282
+ if version_ids:
283
+ placeholders = ",".join("?" for _ in version_ids)
284
+ stream_rows = connection.execute(
285
+ "SELECT version_id, stream_index, kind, codec, details_json "
286
+ f"FROM media_streams WHERE version_id IN ({placeholders}) "
287
+ "ORDER BY version_id, stream_index",
288
+ version_ids,
289
+ ).fetchall()
290
+ for stream_row in stream_rows:
291
+ try:
292
+ details = json.loads(stream_row["details_json"])
293
+ stream = MediaStream(
294
+ stream_row["stream_index"],
295
+ stream_row["kind"],
296
+ stream_row["codec"],
297
+ details,
298
+ )
299
+ except (json.JSONDecodeError, TypeError, ValueError) as error:
300
+ raise ProjectError(
301
+ "storage_corrupt",
302
+ "Clipen 無法讀取素材清單。",
303
+ status_code=500,
304
+ ) from error
305
+ streams_by_version.setdefault(stream_row["version_id"], []).append(
306
+ stream
307
+ )
308
+ try:
309
+ items = tuple(
310
+ InventoryItem(
311
+ row["asset_id"],
312
+ DirectoryRole(row["role"]),
313
+ row["relative_path"],
314
+ row["display_name"],
315
+ AssetKind(row["kind"]),
316
+ ItemStatus(row["status"]),
317
+ row["issue_code"],
318
+ row["size_bytes"],
319
+ None
320
+ if row["probe_status"] is None
321
+ else ProbeStatus(row["probe_status"]),
322
+ None
323
+ if row["probe_json"] is None
324
+ else json.loads(row["probe_json"]),
325
+ tuple(streams_by_version.get(row["version_id"], ())),
326
+ )
327
+ for row in rows
328
+ )
329
+ return InventoryPage(items, total, offset, limit)
330
+ except (json.JSONDecodeError, TypeError, ValueError) as error:
331
+ raise ProjectError(
332
+ "storage_corrupt", "Clipen 無法讀取素材清單。", status_code=500
333
+ ) from error
334
+
335
+ def request_cancel(self, project_id: str, run_id: object) -> InventoryRun:
336
+ """Idempotently request cancellation without reviving terminal work."""
337
+ validate_project_id(project_id)
338
+ normalized_run = validate_run_id(run_id)
339
+ with self.projects.connect(project_id) as connection:
340
+ try:
341
+ connection.execute("BEGIN IMMEDIATE")
342
+ current = self._read_run(connection, normalized_run)
343
+ if current.project_id != project_id:
344
+ raise ProjectError(
345
+ "inventory_not_found", "找不到這次素材檢查。", status_code=404
346
+ )
347
+ if current.state in _TERMINAL_STATES or current.state is InventoryState.CANCELLING:
348
+ connection.rollback()
349
+ return current
350
+ now = utc_now()
351
+ if current.state is InventoryState.QUEUED:
352
+ connection.execute(
353
+ "UPDATE inventory_runs SET state = 'cancelled', phase = 'cancelled', "
354
+ "error_code = NULL, started_at = ?, completed_at = ? WHERE run_id = ?",
355
+ (now, now, normalized_run),
356
+ )
357
+ else:
358
+ connection.execute(
359
+ "UPDATE inventory_runs SET state = 'cancelling', "
360
+ "phase = 'cancelling' WHERE run_id = ?",
361
+ (normalized_run,),
362
+ )
363
+ updated = self._read_run(connection, normalized_run)
364
+ connection.commit()
365
+ return updated
366
+ except ProjectError:
367
+ connection.rollback()
368
+ raise
369
+ except sqlite3.Error as error:
370
+ connection.rollback()
371
+ raise ProjectError(
372
+ "storage_failed", "Clipen 無法取消素材檢查。", status_code=500
373
+ ) from error
374
+
375
+ def transition(
376
+ self,
377
+ project_id: str,
378
+ run_id: object,
379
+ target: InventoryState,
380
+ *,
381
+ phase: str,
382
+ error_code: str | None = None,
383
+ ) -> InventoryRun:
384
+ validate_project_id(project_id)
385
+ normalized_run = validate_run_id(run_id)
386
+ if not phase or len(phase) > 40 or not phase.replace("_", "a").isalnum():
387
+ raise ValueError("inventory phase is invalid")
388
+ if target is InventoryState.SUCCEEDED:
389
+ raise ValueError("use publish() to complete a successful inventory")
390
+ with self.projects.connect(project_id) as connection:
391
+ try:
392
+ connection.execute("BEGIN IMMEDIATE")
393
+ current = self._read_run(connection, normalized_run)
394
+ if current.project_id != project_id:
395
+ raise ProjectError(
396
+ "inventory_not_found", "找不到這次素材檢查。", status_code=404
397
+ )
398
+ if target not in _TRANSITIONS.get(current.state, set()):
399
+ raise ProjectError(
400
+ "inventory_state_conflict",
401
+ "這次素材檢查的狀態已經改變。",
402
+ status_code=409,
403
+ )
404
+ now = utc_now()
405
+ started = current.started_at or now
406
+ completed = now if target in _TERMINAL_STATES else None
407
+ connection.execute(
408
+ "UPDATE inventory_runs SET state = ?, phase = ?, error_code = ?, "
409
+ "started_at = ?, completed_at = ? WHERE run_id = ?",
410
+ (target.value, phase, error_code, started, completed, normalized_run),
411
+ )
412
+ updated = self._read_run(connection, normalized_run)
413
+ connection.commit()
414
+ return updated
415
+ except ProjectError:
416
+ connection.rollback()
417
+ raise
418
+ except sqlite3.Error as error:
419
+ connection.rollback()
420
+ raise ProjectError(
421
+ "storage_failed", "Clipen 無法更新素材檢查。", status_code=500
422
+ ) from error
423
+
424
+ def publish(self, project_id: str, run_id: object) -> InventoryRun:
425
+ validate_project_id(project_id)
426
+ normalized_run = validate_run_id(run_id)
427
+ with self.projects.connect(project_id) as connection:
428
+ try:
429
+ connection.execute("BEGIN IMMEDIATE")
430
+ current = self._read_run(connection, normalized_run)
431
+ if current.project_id != project_id or current.state is not InventoryState.RUNNING:
432
+ raise ProjectError(
433
+ "inventory_state_conflict",
434
+ "這次素材檢查目前不能完成。",
435
+ status_code=409,
436
+ )
437
+ root_rows = connection.execute(
438
+ "SELECT role, canonical_path, device, inode, saved_at "
439
+ "FROM project_directories ORDER BY role"
440
+ ).fetchall()
441
+ current_roots = tuple(
442
+ InventoryRoot(
443
+ DirectoryRole(row["role"]),
444
+ row["canonical_path"],
445
+ row["device"],
446
+ row["inode"],
447
+ row["saved_at"],
448
+ )
449
+ for row in root_rows
450
+ )
451
+ if current_roots != current.roots:
452
+ raise ProjectError(
453
+ "inventory_input_changed",
454
+ "素材位置已更新,請重新檢查素材。",
455
+ status_code=409,
456
+ )
457
+ counts = connection.execute(
458
+ "SELECT COUNT(*) AS discovered, "
459
+ "SUM(CASE WHEN v.probe_status IS NOT NULL "
460
+ " AND v.probe_status != 'pending' THEN 1 ELSE 0 END) AS probed, "
461
+ "SUM(CASE WHEN i.status = 'usable' THEN 1 ELSE 0 END) AS usable, "
462
+ "SUM(CASE WHEN i.status = 'needs_attention' THEN 1 ELSE 0 END) AS issues, "
463
+ "SUM(CASE WHEN i.status = 'ignored' THEN 1 ELSE 0 END) AS ignored "
464
+ "FROM inventory_items i LEFT JOIN asset_versions v "
465
+ "ON v.version_id = i.version_id WHERE i.run_id = ?",
466
+ (normalized_run,),
467
+ ).fetchone()
468
+ observed = InventoryCounts(
469
+ counts["discovered"],
470
+ counts["probed"] or 0,
471
+ counts["usable"] or 0,
472
+ counts["issues"] or 0,
473
+ counts["ignored"] or 0,
474
+ )
475
+ if observed != current.counts:
476
+ raise ProjectError(
477
+ "inventory_incomplete",
478
+ "素材檢查結果尚未整理完成。",
479
+ status_code=409,
480
+ )
481
+ now = utc_now()
482
+ connection.execute(
483
+ "UPDATE inventory_runs SET state = 'succeeded', phase = 'completed', "
484
+ "error_code = NULL, completed_at = ? WHERE run_id = ?",
485
+ (now, normalized_run),
486
+ )
487
+ connection.execute(
488
+ "INSERT INTO current_inventory (slot, run_id) VALUES (1, ?) "
489
+ "ON CONFLICT(slot) DO UPDATE SET run_id = excluded.run_id",
490
+ (normalized_run,),
491
+ )
492
+ published = self._read_run(connection, normalized_run)
493
+ connection.commit()
494
+ return published
495
+ except ProjectError:
496
+ connection.rollback()
497
+ raise
498
+ except sqlite3.Error as error:
499
+ connection.rollback()
500
+ raise ProjectError(
501
+ "storage_failed", "Clipen 無法發布素材檢查結果。", status_code=500
502
+ ) from error
503
+
504
+ def stage_item(
505
+ self,
506
+ project_id: str,
507
+ run_id: object,
508
+ candidate: AssetCandidate,
509
+ ) -> InventoryRun:
510
+ return self.stage_items(project_id, run_id, (candidate,))
511
+
512
+ def stage_items(
513
+ self,
514
+ project_id: str,
515
+ run_id: object,
516
+ candidates: tuple[AssetCandidate, ...],
517
+ ) -> InventoryRun:
518
+ validate_project_id(project_id)
519
+ normalized_run = validate_run_id(run_id)
520
+ if not candidates or len(candidates) > 100:
521
+ raise ValueError("inventory stage batch must contain 1 to 100 items")
522
+ with self.projects.connect(project_id) as connection:
523
+ try:
524
+ connection.execute("BEGIN IMMEDIATE")
525
+ run = self._read_run(connection, normalized_run)
526
+ if run.project_id != project_id or run.state is not InventoryState.RUNNING:
527
+ raise ProjectError(
528
+ "inventory_state_conflict",
529
+ "這次素材檢查目前不能保存結果。",
530
+ status_code=409,
531
+ )
532
+ now = utc_now()
533
+ probed_increment = 0
534
+ usable_increment = 0
535
+ issue_increment = 0
536
+ ignored_increment = 0
537
+ for candidate in candidates:
538
+ self._insert_candidate(
539
+ connection,
540
+ project_id,
541
+ normalized_run,
542
+ candidate,
543
+ now,
544
+ )
545
+ probed_increment += int(
546
+ candidate.probe_status is not None
547
+ and candidate.probe_status.value != "pending"
548
+ )
549
+ usable_increment += int(candidate.status is ItemStatus.USABLE)
550
+ issue_increment += int(candidate.status is ItemStatus.NEEDS_ATTENTION)
551
+ ignored_increment += int(candidate.status is ItemStatus.IGNORED)
552
+ connection.execute(
553
+ "UPDATE inventory_runs SET discovered_count = discovered_count + ?, "
554
+ "probed_count = probed_count + ?, usable_count = usable_count + ?, "
555
+ "issue_count = issue_count + ?, ignored_count = ignored_count + ? "
556
+ "WHERE run_id = ?",
557
+ (
558
+ len(candidates),
559
+ probed_increment,
560
+ usable_increment,
561
+ issue_increment,
562
+ ignored_increment,
563
+ normalized_run,
564
+ ),
565
+ )
566
+ updated = self._read_run(connection, normalized_run)
567
+ connection.commit()
568
+ return updated
569
+ except ProjectError:
570
+ connection.rollback()
571
+ raise
572
+ except (TypeError, ValueError) as error:
573
+ connection.rollback()
574
+ raise ProjectError(
575
+ "inventory_item_invalid", "Clipen 無法保存這個素材項目。", status_code=500
576
+ ) from error
577
+ except sqlite3.Error as error:
578
+ connection.rollback()
579
+ raise ProjectError(
580
+ "storage_failed", "Clipen 無法保存素材檢查結果。", status_code=500
581
+ ) from error
582
+
583
+ @staticmethod
584
+ def _insert_candidate(
585
+ connection: sqlite3.Connection,
586
+ project_id: str,
587
+ run_id: str,
588
+ candidate: AssetCandidate,
589
+ now: str,
590
+ ) -> None:
591
+ asset_id = candidate.asset_id(project_id)
592
+ version_id = candidate.version_id(project_id)
593
+ existing = connection.execute(
594
+ "SELECT 1 FROM inventory_items WHERE run_id = ? AND asset_id = ?",
595
+ (run_id, asset_id),
596
+ ).fetchone()
597
+ if existing is not None:
598
+ raise ProjectError(
599
+ "inventory_item_conflict",
600
+ "素材檢查出現重複項目。",
601
+ status_code=409,
602
+ )
603
+ connection.execute(
604
+ "INSERT INTO assets (asset_id, project_id, role, relative_path, first_seen_at) "
605
+ "VALUES (?, ?, ?, ?, ?) ON CONFLICT(asset_id) DO NOTHING",
606
+ (asset_id, project_id, candidate.role.value, candidate.relative_path, now),
607
+ )
608
+ if version_id is not None:
609
+ probe_json = (
610
+ None
611
+ if candidate.probe is None
612
+ else json.dumps(
613
+ candidate.probe,
614
+ ensure_ascii=False,
615
+ sort_keys=True,
616
+ separators=(",", ":"),
617
+ )
618
+ )
619
+ connection.execute(
620
+ "INSERT INTO asset_versions "
621
+ "(version_id, asset_id, size_bytes, mtime_ns, fingerprint, "
622
+ "probe_status, probe_json, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?) "
623
+ "ON CONFLICT(version_id) DO NOTHING",
624
+ (
625
+ version_id,
626
+ asset_id,
627
+ candidate.size_bytes,
628
+ candidate.mtime_ns,
629
+ candidate.fingerprint,
630
+ candidate.probe_status.value,
631
+ probe_json,
632
+ now,
633
+ ),
634
+ )
635
+ for stream in candidate.streams:
636
+ connection.execute(
637
+ "INSERT INTO media_streams "
638
+ "(version_id, stream_index, kind, codec, details_json) "
639
+ "VALUES (?, ?, ?, ?, ?) ON CONFLICT DO NOTHING",
640
+ (
641
+ version_id,
642
+ stream.stream_index,
643
+ stream.kind,
644
+ stream.codec,
645
+ json.dumps(
646
+ stream.details,
647
+ ensure_ascii=False,
648
+ sort_keys=True,
649
+ separators=(",", ":"),
650
+ ),
651
+ ),
652
+ )
653
+ # Enrich legacy probe rows with newly understood disposition flags.
654
+ # Do not replace the immutable source version or its time mapping.
655
+ flags = {key: stream.details[key] for key in ("attached_pic", "timed_thumbnails") if key in stream.details}
656
+ if flags:
657
+ existing_details = connection.execute(
658
+ "SELECT details_json FROM media_streams WHERE version_id=? AND stream_index=?",
659
+ (version_id, stream.stream_index),
660
+ ).fetchone()[0]
661
+ details = json.loads(existing_details)
662
+ if any(details.get(key) != value for key, value in flags.items()):
663
+ details.update(flags)
664
+ connection.execute(
665
+ "UPDATE media_streams SET details_json=? WHERE version_id=? AND stream_index=?",
666
+ (json.dumps(details, sort_keys=True, separators=(",", ":")), version_id, stream.stream_index),
667
+ )
668
+ connection.execute(
669
+ "INSERT INTO inventory_items "
670
+ "(run_id, asset_id, version_id, display_name, kind, status, issue_code) "
671
+ "VALUES (?, ?, ?, ?, ?, ?, ?)",
672
+ (
673
+ run_id,
674
+ asset_id,
675
+ version_id,
676
+ candidate.display_name,
677
+ candidate.kind.value,
678
+ candidate.status.value,
679
+ candidate.issue_code,
680
+ ),
681
+ )
682
+
683
+ def interrupt_incomplete(self, project_id: str) -> int:
684
+ validate_project_id(project_id)
685
+ with self.projects.connect(project_id) as connection:
686
+ try:
687
+ connection.execute("BEGIN IMMEDIATE")
688
+ now = utc_now()
689
+ cursor = connection.execute(
690
+ "UPDATE inventory_runs SET state = 'interrupted', phase = 'interrupted', "
691
+ "error_code = 'controller_restarted', "
692
+ "started_at = COALESCE(started_at, ?), completed_at = ? "
693
+ "WHERE state IN ('queued', 'running', 'cancelling')",
694
+ (now, now),
695
+ )
696
+ connection.commit()
697
+ return cursor.rowcount
698
+ except sqlite3.Error as error:
699
+ connection.rollback()
700
+ raise ProjectError(
701
+ "storage_failed", "Clipen 無法恢復素材檢查。", status_code=500
702
+ ) from error
703
+
704
+ @staticmethod
705
+ def _read_run(connection: sqlite3.Connection, run_id: str) -> InventoryRun:
706
+ row = connection.execute(
707
+ "SELECT run_id, project_id, project_revision, input_fingerprint, roots_json, "
708
+ "state, phase, discovered_count, probed_count, usable_count, issue_count, "
709
+ "ignored_count, error_code, created_at, started_at, completed_at "
710
+ "FROM inventory_runs WHERE run_id = ?",
711
+ (run_id,),
712
+ ).fetchone()
713
+ if row is None:
714
+ raise ProjectError("inventory_not_found", "找不到這次素材檢查。", status_code=404)
715
+ try:
716
+ roots_value = json.loads(row["roots_json"])
717
+ if not isinstance(roots_value, list):
718
+ raise ValueError("inventory roots must be a list")
719
+ return InventoryRun(
720
+ run_id=row["run_id"],
721
+ project_id=row["project_id"],
722
+ project_revision=row["project_revision"],
723
+ input_fingerprint=row["input_fingerprint"],
724
+ roots=tuple(InventoryRoot.from_storage(value) for value in roots_value),
725
+ state=InventoryState(row["state"]),
726
+ phase=row["phase"],
727
+ counts=InventoryCounts(
728
+ row["discovered_count"],
729
+ row["probed_count"],
730
+ row["usable_count"],
731
+ row["issue_count"],
732
+ row["ignored_count"],
733
+ ),
734
+ error_code=row["error_code"],
735
+ created_at=row["created_at"],
736
+ started_at=row["started_at"],
737
+ completed_at=row["completed_at"],
738
+ )
739
+ except (json.JSONDecodeError, KeyError, TypeError, ValueError) as error:
740
+ raise ProjectError(
741
+ "storage_corrupt", "Clipen 無法讀取素材檢查紀錄。", status_code=500
742
+ ) from error