@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,694 @@
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
+ _TERMINAL_STATES = frozenset(
35
+ {
36
+ InventoryState.SUCCEEDED,
37
+ InventoryState.FAILED,
38
+ InventoryState.CANCELLED,
39
+ InventoryState.INTERRUPTED,
40
+ }
41
+ )
42
+ _TRANSITIONS = {
43
+ InventoryState.QUEUED: {
44
+ InventoryState.RUNNING,
45
+ InventoryState.CANCELLED,
46
+ InventoryState.INTERRUPTED,
47
+ },
48
+ InventoryState.RUNNING: {
49
+ InventoryState.CANCELLING,
50
+ InventoryState.SUCCEEDED,
51
+ InventoryState.FAILED,
52
+ InventoryState.CANCELLED,
53
+ InventoryState.INTERRUPTED,
54
+ },
55
+ InventoryState.CANCELLING: {
56
+ InventoryState.CANCELLED,
57
+ InventoryState.FAILED,
58
+ InventoryState.INTERRUPTED,
59
+ },
60
+ }
61
+
62
+
63
+ class InventoryRepository:
64
+ def __init__(self, projects: ProjectRepository) -> None:
65
+ self.projects = projects
66
+
67
+ def create_run(
68
+ self,
69
+ project_id: str,
70
+ request_id: object,
71
+ expected_revision: object,
72
+ ) -> InventoryRun:
73
+ run, _ = self.create_run_with_status(project_id, request_id, expected_revision)
74
+ return run
75
+
76
+ def create_run_with_status(
77
+ self,
78
+ project_id: str,
79
+ request_id: object,
80
+ expected_revision: object,
81
+ ) -> tuple[InventoryRun, bool]:
82
+ """Create a queued run and report whether this call created it.
83
+
84
+ The boolean prevents a replayed request from accidentally scheduling an old
85
+ queued run in a new controller process.
86
+ """
87
+ validate_project_id(project_id)
88
+ normalized_request = validate_request_id(request_id)
89
+ revision = validate_revision(expected_revision)
90
+ request_hash = command_digest({"expected_revision": revision})
91
+ run_id = make_run_id(project_id, normalized_request)
92
+ with self.projects.connect(project_id) as connection:
93
+ try:
94
+ connection.execute("BEGIN IMMEDIATE")
95
+ receipt = connection.execute(
96
+ "SELECT command_type, request_hash, run_id FROM inventory_command_receipts WHERE request_id = ?",
97
+ (normalized_request,),
98
+ ).fetchone()
99
+ if receipt is not None:
100
+ if receipt["command_type"] != "start_inventory" or receipt["request_hash"] != request_hash:
101
+ raise ProjectError(
102
+ "request_reused",
103
+ "這次操作的識別資訊已用於不同內容。",
104
+ status_code=409,
105
+ )
106
+ replay = self._read_run(connection, receipt["run_id"])
107
+ connection.rollback()
108
+ return replay, False
109
+
110
+ project = connection.execute(
111
+ "SELECT revision FROM project WHERE project_id = ?", (project_id,)
112
+ ).fetchone()
113
+ if project is None:
114
+ raise ProjectError("project_not_found", "找不到這個作品。", status_code=404)
115
+ if project["revision"] != revision:
116
+ raise ProjectError(
117
+ "revision_conflict",
118
+ "作品已在其他分頁更新,請重新載入最新內容。",
119
+ status_code=409,
120
+ )
121
+ rows = connection.execute(
122
+ "SELECT role, canonical_path, device, inode, saved_at FROM project_directories ORDER BY role"
123
+ ).fetchall()
124
+ roots = tuple(
125
+ InventoryRoot(
126
+ DirectoryRole(row["role"]),
127
+ row["canonical_path"],
128
+ row["device"],
129
+ row["inode"],
130
+ row["saved_at"],
131
+ )
132
+ for row in rows
133
+ )
134
+ if DirectoryRole.SOURCE not in {root.role for root in roots}:
135
+ raise ProjectError(
136
+ "source_required",
137
+ "請先選擇毛片資料夾。",
138
+ status_code=409,
139
+ )
140
+ incomplete = connection.execute(
141
+ "SELECT run_id FROM inventory_runs WHERE state IN ('queued', 'running', 'cancelling') LIMIT 1"
142
+ ).fetchone()
143
+ if incomplete is not None:
144
+ raise ProjectError(
145
+ "inventory_busy",
146
+ "已有一個素材檢查正在進行。",
147
+ status_code=409,
148
+ )
149
+ roots_json = json.dumps(
150
+ [root.to_storage() for root in roots],
151
+ ensure_ascii=False,
152
+ sort_keys=True,
153
+ separators=(",", ":"),
154
+ )
155
+ fingerprint = hashlib.sha256(
156
+ json.dumps(
157
+ {
158
+ "project_revision": revision,
159
+ "roots": json.loads(roots_json),
160
+ },
161
+ ensure_ascii=False,
162
+ sort_keys=True,
163
+ separators=(",", ":"),
164
+ ).encode("utf-8")
165
+ ).hexdigest()
166
+ now = utc_now()
167
+ connection.execute(
168
+ "INSERT INTO inventory_runs "
169
+ "(run_id, project_id, request_id, project_revision, input_fingerprint, "
170
+ "roots_json, state, phase, created_at) "
171
+ "VALUES (?, ?, ?, ?, ?, ?, 'queued', 'preparing', ?)",
172
+ (
173
+ run_id,
174
+ project_id,
175
+ normalized_request,
176
+ revision,
177
+ fingerprint,
178
+ roots_json,
179
+ now,
180
+ ),
181
+ )
182
+ connection.execute(
183
+ "INSERT INTO inventory_command_receipts "
184
+ "(request_id, command_type, request_hash, run_id, created_at) "
185
+ "VALUES (?, 'start_inventory', ?, ?, ?)",
186
+ (normalized_request, request_hash, run_id, now),
187
+ )
188
+ created = self._read_run(connection, run_id)
189
+ connection.commit()
190
+ return created, True
191
+ except ProjectError:
192
+ connection.rollback()
193
+ raise
194
+ except (json.JSONDecodeError, KeyError, TypeError, ValueError) as error:
195
+ connection.rollback()
196
+ raise ProjectError("storage_corrupt", "Clipen 無法讀取素材檢查紀錄。", status_code=500) from error
197
+ except sqlite3.Error as error:
198
+ connection.rollback()
199
+ raise ProjectError("storage_failed", "Clipen 無法建立素材檢查。", status_code=500) from error
200
+
201
+ def get_run(self, project_id: str, run_id: object) -> InventoryRun:
202
+ validate_project_id(project_id)
203
+ normalized_run = validate_run_id(run_id)
204
+ with self.projects.connect(project_id) as connection:
205
+ run = self._read_run(connection, normalized_run)
206
+ if run.project_id != project_id:
207
+ raise ProjectError("inventory_not_found", "找不到這次素材檢查。", status_code=404)
208
+ return run
209
+
210
+ def current_run(self, project_id: str) -> InventoryRun | None:
211
+ validate_project_id(project_id)
212
+ with self.projects.connect(project_id) as connection:
213
+ row = connection.execute("SELECT run_id FROM current_inventory WHERE slot = 1").fetchone()
214
+ return None if row is None else self._read_run(connection, row["run_id"])
215
+
216
+ def latest_run(self, project_id: str) -> InventoryRun | None:
217
+ validate_project_id(project_id)
218
+ with self.projects.connect(project_id) as connection:
219
+ row = connection.execute("SELECT run_id FROM inventory_runs ORDER BY created_at DESC LIMIT 1").fetchone()
220
+ return None if row is None else self._read_run(connection, row["run_id"])
221
+
222
+ def list_items(
223
+ self,
224
+ project_id: str,
225
+ run_id: object,
226
+ *,
227
+ offset: int = 0,
228
+ limit: int = 100,
229
+ ) -> InventoryPage:
230
+ validate_project_id(project_id)
231
+ normalized_run = validate_run_id(run_id)
232
+ if (
233
+ isinstance(offset, bool)
234
+ or not isinstance(offset, int)
235
+ or offset < 0
236
+ or isinstance(limit, bool)
237
+ or not isinstance(limit, int)
238
+ or not 1 <= limit <= 200
239
+ ):
240
+ raise ProjectError("pagination_invalid", "素材清單頁碼無效。", status_code=422)
241
+ with self.projects.connect(project_id) as connection:
242
+ run = self._read_run(connection, normalized_run)
243
+ if run.project_id != project_id:
244
+ raise ProjectError("inventory_not_found", "找不到這次素材檢查。", status_code=404)
245
+ total = connection.execute(
246
+ "SELECT COUNT(*) FROM inventory_items WHERE run_id = ?",
247
+ (normalized_run,),
248
+ ).fetchone()[0]
249
+ rows = connection.execute(
250
+ "SELECT i.asset_id, a.role, a.relative_path, i.display_name, i.kind, "
251
+ "i.status, i.issue_code, v.version_id, v.size_bytes, v.probe_status, "
252
+ "v.probe_json FROM inventory_items i "
253
+ "JOIN assets a ON a.asset_id = i.asset_id "
254
+ "LEFT JOIN asset_versions v ON v.version_id = i.version_id "
255
+ "WHERE i.run_id = ? "
256
+ "ORDER BY CASE i.status WHEN 'needs_attention' THEN 0 "
257
+ "WHEN 'usable' THEN 1 ELSE 2 END, i.display_name COLLATE NOCASE, i.asset_id "
258
+ "LIMIT ? OFFSET ?",
259
+ (normalized_run, limit, offset),
260
+ ).fetchall()
261
+ version_ids = [row["version_id"] for row in rows if row["version_id"]]
262
+ streams_by_version: dict[str, list[MediaStream]] = {}
263
+ if version_ids:
264
+ placeholders = ",".join("?" for _ in version_ids)
265
+ stream_rows = connection.execute(
266
+ "SELECT version_id, stream_index, kind, codec, details_json "
267
+ f"FROM media_streams WHERE version_id IN ({placeholders}) "
268
+ "ORDER BY version_id, stream_index",
269
+ version_ids,
270
+ ).fetchall()
271
+ for stream_row in stream_rows:
272
+ try:
273
+ details = json.loads(stream_row["details_json"])
274
+ stream = MediaStream(
275
+ stream_row["stream_index"],
276
+ stream_row["kind"],
277
+ stream_row["codec"],
278
+ details,
279
+ )
280
+ except (json.JSONDecodeError, TypeError, ValueError) as error:
281
+ raise ProjectError(
282
+ "storage_corrupt",
283
+ "Clipen 無法讀取素材清單。",
284
+ status_code=500,
285
+ ) from error
286
+ streams_by_version.setdefault(stream_row["version_id"], []).append(stream)
287
+ try:
288
+ items = tuple(
289
+ InventoryItem(
290
+ row["asset_id"],
291
+ DirectoryRole(row["role"]),
292
+ row["relative_path"],
293
+ row["display_name"],
294
+ AssetKind(row["kind"]),
295
+ ItemStatus(row["status"]),
296
+ row["issue_code"],
297
+ row["size_bytes"],
298
+ None if row["probe_status"] is None else ProbeStatus(row["probe_status"]),
299
+ None if row["probe_json"] is None else json.loads(row["probe_json"]),
300
+ tuple(streams_by_version.get(row["version_id"], ())),
301
+ )
302
+ for row in rows
303
+ )
304
+ return InventoryPage(items, total, offset, limit)
305
+ except (json.JSONDecodeError, TypeError, ValueError) as error:
306
+ raise ProjectError("storage_corrupt", "Clipen 無法讀取素材清單。", status_code=500) from error
307
+
308
+ def request_cancel(self, project_id: str, run_id: object) -> InventoryRun:
309
+ """Idempotently request cancellation without reviving terminal work."""
310
+ validate_project_id(project_id)
311
+ normalized_run = validate_run_id(run_id)
312
+ with self.projects.connect(project_id) as connection:
313
+ try:
314
+ connection.execute("BEGIN IMMEDIATE")
315
+ current = self._read_run(connection, normalized_run)
316
+ if current.project_id != project_id:
317
+ raise ProjectError("inventory_not_found", "找不到這次素材檢查。", status_code=404)
318
+ if current.state in _TERMINAL_STATES or current.state is InventoryState.CANCELLING:
319
+ connection.rollback()
320
+ return current
321
+ now = utc_now()
322
+ if current.state is InventoryState.QUEUED:
323
+ connection.execute(
324
+ "UPDATE inventory_runs SET state = 'cancelled', phase = 'cancelled', "
325
+ "error_code = NULL, started_at = ?, completed_at = ? WHERE run_id = ?",
326
+ (now, now, normalized_run),
327
+ )
328
+ else:
329
+ connection.execute(
330
+ "UPDATE inventory_runs SET state = 'cancelling', phase = 'cancelling' WHERE run_id = ?",
331
+ (normalized_run,),
332
+ )
333
+ updated = self._read_run(connection, normalized_run)
334
+ connection.commit()
335
+ return updated
336
+ except ProjectError:
337
+ connection.rollback()
338
+ raise
339
+ except sqlite3.Error as error:
340
+ connection.rollback()
341
+ raise ProjectError("storage_failed", "Clipen 無法取消素材檢查。", status_code=500) from error
342
+
343
+ def transition(
344
+ self,
345
+ project_id: str,
346
+ run_id: object,
347
+ target: InventoryState,
348
+ *,
349
+ phase: str,
350
+ error_code: str | None = None,
351
+ ) -> InventoryRun:
352
+ validate_project_id(project_id)
353
+ normalized_run = validate_run_id(run_id)
354
+ if not phase or len(phase) > 40 or not phase.replace("_", "a").isalnum():
355
+ raise ValueError("inventory phase is invalid")
356
+ if target is InventoryState.SUCCEEDED:
357
+ raise ValueError("use publish() to complete a successful inventory")
358
+ with self.projects.connect(project_id) as connection:
359
+ try:
360
+ connection.execute("BEGIN IMMEDIATE")
361
+ current = self._read_run(connection, normalized_run)
362
+ if current.project_id != project_id:
363
+ raise ProjectError("inventory_not_found", "找不到這次素材檢查。", status_code=404)
364
+ if target not in _TRANSITIONS.get(current.state, set()):
365
+ raise ProjectError(
366
+ "inventory_state_conflict",
367
+ "這次素材檢查的狀態已經改變。",
368
+ status_code=409,
369
+ )
370
+ now = utc_now()
371
+ started = current.started_at or now
372
+ completed = now if target in _TERMINAL_STATES else None
373
+ connection.execute(
374
+ "UPDATE inventory_runs SET state = ?, phase = ?, error_code = ?, "
375
+ "started_at = ?, completed_at = ? WHERE run_id = ?",
376
+ (target.value, phase, error_code, started, completed, normalized_run),
377
+ )
378
+ updated = self._read_run(connection, normalized_run)
379
+ connection.commit()
380
+ return updated
381
+ except ProjectError:
382
+ connection.rollback()
383
+ raise
384
+ except sqlite3.Error as error:
385
+ connection.rollback()
386
+ raise ProjectError("storage_failed", "Clipen 無法更新素材檢查。", status_code=500) from error
387
+
388
+ def publish(self, project_id: str, run_id: object) -> InventoryRun:
389
+ validate_project_id(project_id)
390
+ normalized_run = validate_run_id(run_id)
391
+ with self.projects.connect(project_id) as connection:
392
+ try:
393
+ connection.execute("BEGIN IMMEDIATE")
394
+ current = self._read_run(connection, normalized_run)
395
+ if current.project_id != project_id or current.state is not InventoryState.RUNNING:
396
+ raise ProjectError(
397
+ "inventory_state_conflict",
398
+ "這次素材檢查目前不能完成。",
399
+ status_code=409,
400
+ )
401
+ root_rows = connection.execute(
402
+ "SELECT role, canonical_path, device, inode, saved_at FROM project_directories ORDER BY role"
403
+ ).fetchall()
404
+ current_roots = tuple(
405
+ InventoryRoot(
406
+ DirectoryRole(row["role"]),
407
+ row["canonical_path"],
408
+ row["device"],
409
+ row["inode"],
410
+ row["saved_at"],
411
+ )
412
+ for row in root_rows
413
+ )
414
+ if current_roots != current.roots:
415
+ raise ProjectError(
416
+ "inventory_input_changed",
417
+ "素材位置已更新,請重新檢查素材。",
418
+ status_code=409,
419
+ )
420
+ counts = connection.execute(
421
+ "SELECT COUNT(*) AS discovered, "
422
+ "SUM(CASE WHEN v.probe_status IS NOT NULL "
423
+ " AND v.probe_status != 'pending' THEN 1 ELSE 0 END) AS probed, "
424
+ "SUM(CASE WHEN i.status = 'usable' THEN 1 ELSE 0 END) AS usable, "
425
+ "SUM(CASE WHEN i.status = 'needs_attention' THEN 1 ELSE 0 END) AS issues, "
426
+ "SUM(CASE WHEN i.status = 'ignored' THEN 1 ELSE 0 END) AS ignored "
427
+ "FROM inventory_items i LEFT JOIN asset_versions v "
428
+ "ON v.version_id = i.version_id WHERE i.run_id = ?",
429
+ (normalized_run,),
430
+ ).fetchone()
431
+ observed = InventoryCounts(
432
+ counts["discovered"],
433
+ counts["probed"] or 0,
434
+ counts["usable"] or 0,
435
+ counts["issues"] or 0,
436
+ counts["ignored"] or 0,
437
+ )
438
+ if observed != current.counts:
439
+ raise ProjectError(
440
+ "inventory_incomplete",
441
+ "素材檢查結果尚未整理完成。",
442
+ status_code=409,
443
+ )
444
+ now = utc_now()
445
+ connection.execute(
446
+ "UPDATE inventory_runs SET state = 'succeeded', phase = 'completed', "
447
+ "error_code = NULL, completed_at = ? WHERE run_id = ?",
448
+ (now, normalized_run),
449
+ )
450
+ connection.execute(
451
+ "INSERT INTO current_inventory (slot, run_id) VALUES (1, ?) "
452
+ "ON CONFLICT(slot) DO UPDATE SET run_id = excluded.run_id",
453
+ (normalized_run,),
454
+ )
455
+ published = self._read_run(connection, normalized_run)
456
+ connection.commit()
457
+ return published
458
+ except ProjectError:
459
+ connection.rollback()
460
+ raise
461
+ except sqlite3.Error as error:
462
+ connection.rollback()
463
+ raise ProjectError("storage_failed", "Clipen 無法發布素材檢查結果。", status_code=500) from error
464
+
465
+ def stage_items(
466
+ self,
467
+ project_id: str,
468
+ run_id: object,
469
+ candidates: tuple[AssetCandidate, ...],
470
+ ) -> InventoryRun:
471
+ validate_project_id(project_id)
472
+ normalized_run = validate_run_id(run_id)
473
+ if not candidates or len(candidates) > 100:
474
+ raise ValueError("inventory stage batch must contain 1 to 100 items")
475
+ with self.projects.connect(project_id) as connection:
476
+ try:
477
+ connection.execute("BEGIN IMMEDIATE")
478
+ run = self._read_run(connection, normalized_run)
479
+ if run.project_id != project_id or run.state is not InventoryState.RUNNING:
480
+ raise ProjectError(
481
+ "inventory_state_conflict",
482
+ "這次素材檢查目前不能保存結果。",
483
+ status_code=409,
484
+ )
485
+ now = utc_now()
486
+ probed_increment = 0
487
+ usable_increment = 0
488
+ issue_increment = 0
489
+ ignored_increment = 0
490
+ for candidate in candidates:
491
+ self._insert_candidate(
492
+ connection,
493
+ project_id,
494
+ normalized_run,
495
+ candidate,
496
+ now,
497
+ )
498
+ probed_increment += int(
499
+ candidate.probe_status is not None and candidate.probe_status.value != "pending"
500
+ )
501
+ usable_increment += int(candidate.status is ItemStatus.USABLE)
502
+ issue_increment += int(candidate.status is ItemStatus.NEEDS_ATTENTION)
503
+ ignored_increment += int(candidate.status is ItemStatus.IGNORED)
504
+ connection.execute(
505
+ "UPDATE inventory_runs SET discovered_count = discovered_count + ?, "
506
+ "probed_count = probed_count + ?, usable_count = usable_count + ?, "
507
+ "issue_count = issue_count + ?, ignored_count = ignored_count + ? "
508
+ "WHERE run_id = ?",
509
+ (
510
+ len(candidates),
511
+ probed_increment,
512
+ usable_increment,
513
+ issue_increment,
514
+ ignored_increment,
515
+ normalized_run,
516
+ ),
517
+ )
518
+ updated = self._read_run(connection, normalized_run)
519
+ connection.commit()
520
+ return updated
521
+ except ProjectError:
522
+ connection.rollback()
523
+ raise
524
+ except (TypeError, ValueError) as error:
525
+ connection.rollback()
526
+ raise ProjectError(
527
+ "inventory_item_invalid", "Clipen 無法保存這個素材項目。", status_code=500
528
+ ) from error
529
+ except sqlite3.Error as error:
530
+ connection.rollback()
531
+ raise ProjectError("storage_failed", "Clipen 無法保存素材檢查結果。", status_code=500) from error
532
+
533
+ @staticmethod
534
+ def _insert_candidate(
535
+ connection: sqlite3.Connection,
536
+ project_id: str,
537
+ run_id: str,
538
+ candidate: AssetCandidate,
539
+ now: str,
540
+ ) -> None:
541
+ asset_id = candidate.asset_id(project_id)
542
+ version_id = candidate.version_id(project_id)
543
+ existing = connection.execute(
544
+ "SELECT 1 FROM inventory_items WHERE run_id = ? AND asset_id = ?",
545
+ (run_id, asset_id),
546
+ ).fetchone()
547
+ if existing is not None:
548
+ raise ProjectError(
549
+ "inventory_item_conflict",
550
+ "素材檢查出現重複項目。",
551
+ status_code=409,
552
+ )
553
+ connection.execute(
554
+ "INSERT INTO assets (asset_id, project_id, role, relative_path, first_seen_at) "
555
+ "VALUES (?, ?, ?, ?, ?) ON CONFLICT(asset_id) DO NOTHING",
556
+ (asset_id, project_id, candidate.role.value, candidate.relative_path, now),
557
+ )
558
+ if version_id is not None:
559
+ probe_json = (
560
+ None
561
+ if candidate.probe is None
562
+ else json.dumps(
563
+ candidate.probe,
564
+ ensure_ascii=False,
565
+ sort_keys=True,
566
+ separators=(",", ":"),
567
+ )
568
+ )
569
+ connection.execute(
570
+ "INSERT INTO asset_versions "
571
+ "(version_id, asset_id, size_bytes, mtime_ns, fingerprint, "
572
+ "probe_status, probe_json, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?) "
573
+ "ON CONFLICT(version_id) DO NOTHING",
574
+ (
575
+ version_id,
576
+ asset_id,
577
+ candidate.size_bytes,
578
+ candidate.mtime_ns,
579
+ candidate.fingerprint,
580
+ candidate.probe_status.value,
581
+ probe_json,
582
+ now,
583
+ ),
584
+ )
585
+ for stream in candidate.streams:
586
+ connection.execute(
587
+ "INSERT INTO media_streams "
588
+ "(version_id, stream_index, kind, codec, details_json) "
589
+ "VALUES (?, ?, ?, ?, ?) ON CONFLICT DO NOTHING",
590
+ (
591
+ version_id,
592
+ stream.stream_index,
593
+ stream.kind,
594
+ stream.codec,
595
+ json.dumps(
596
+ stream.details,
597
+ ensure_ascii=False,
598
+ sort_keys=True,
599
+ separators=(",", ":"),
600
+ ),
601
+ ),
602
+ )
603
+ # Enrich legacy probe rows with newly understood disposition flags.
604
+ # Do not replace the immutable source version or its time mapping.
605
+ flags = {
606
+ key: stream.details[key] for key in ("attached_pic", "timed_thumbnails") if key in stream.details
607
+ }
608
+ if flags:
609
+ existing_details = connection.execute(
610
+ "SELECT details_json FROM media_streams WHERE version_id=? AND stream_index=?",
611
+ (version_id, stream.stream_index),
612
+ ).fetchone()[0]
613
+ details = json.loads(existing_details)
614
+ if any(details.get(key) != value for key, value in flags.items()):
615
+ details.update(flags)
616
+ connection.execute(
617
+ "UPDATE media_streams SET details_json=? WHERE version_id=? AND stream_index=?",
618
+ (
619
+ json.dumps(details, sort_keys=True, separators=(",", ":")),
620
+ version_id,
621
+ stream.stream_index,
622
+ ),
623
+ )
624
+ connection.execute(
625
+ "INSERT INTO inventory_items "
626
+ "(run_id, asset_id, version_id, display_name, kind, status, issue_code) "
627
+ "VALUES (?, ?, ?, ?, ?, ?, ?)",
628
+ (
629
+ run_id,
630
+ asset_id,
631
+ version_id,
632
+ candidate.display_name,
633
+ candidate.kind.value,
634
+ candidate.status.value,
635
+ candidate.issue_code,
636
+ ),
637
+ )
638
+
639
+ def interrupt_incomplete(self, project_id: str) -> int:
640
+ validate_project_id(project_id)
641
+ with self.projects.connect(project_id) as connection:
642
+ try:
643
+ connection.execute("BEGIN IMMEDIATE")
644
+ now = utc_now()
645
+ cursor = connection.execute(
646
+ "UPDATE inventory_runs SET state = 'interrupted', phase = 'interrupted', "
647
+ "error_code = 'controller_restarted', "
648
+ "started_at = COALESCE(started_at, ?), completed_at = ? "
649
+ "WHERE state IN ('queued', 'running', 'cancelling')",
650
+ (now, now),
651
+ )
652
+ connection.commit()
653
+ return cursor.rowcount
654
+ except sqlite3.Error as error:
655
+ connection.rollback()
656
+ raise ProjectError("storage_failed", "Clipen 無法恢復素材檢查。", status_code=500) from error
657
+
658
+ @staticmethod
659
+ def _read_run(connection: sqlite3.Connection, run_id: str) -> InventoryRun:
660
+ row = connection.execute(
661
+ "SELECT run_id, project_id, project_revision, input_fingerprint, roots_json, "
662
+ "state, phase, discovered_count, probed_count, usable_count, issue_count, "
663
+ "ignored_count, error_code, created_at, started_at, completed_at "
664
+ "FROM inventory_runs WHERE run_id = ?",
665
+ (run_id,),
666
+ ).fetchone()
667
+ if row is None:
668
+ raise ProjectError("inventory_not_found", "找不到這次素材檢查。", status_code=404)
669
+ try:
670
+ roots_value = json.loads(row["roots_json"])
671
+ if not isinstance(roots_value, list):
672
+ raise ValueError("inventory roots must be a list")
673
+ return InventoryRun(
674
+ run_id=row["run_id"],
675
+ project_id=row["project_id"],
676
+ project_revision=row["project_revision"],
677
+ input_fingerprint=row["input_fingerprint"],
678
+ roots=tuple(InventoryRoot.from_storage(value) for value in roots_value),
679
+ state=InventoryState(row["state"]),
680
+ phase=row["phase"],
681
+ counts=InventoryCounts(
682
+ row["discovered_count"],
683
+ row["probed_count"],
684
+ row["usable_count"],
685
+ row["issue_count"],
686
+ row["ignored_count"],
687
+ ),
688
+ error_code=row["error_code"],
689
+ created_at=row["created_at"],
690
+ started_at=row["started_at"],
691
+ completed_at=row["completed_at"],
692
+ )
693
+ except (json.JSONDecodeError, KeyError, TypeError, ValueError) as error:
694
+ raise ProjectError("storage_corrupt", "Clipen 無法讀取素材檢查紀錄。", status_code=500) from error