@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,1864 @@
1
+ """Transactional preparation operations bound to an immutable media inventory."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ import os
8
+ import re
9
+ import sqlite3
10
+ from dataclasses import dataclass
11
+ from fractions import Fraction
12
+ from typing import Any, Mapping
13
+
14
+ from clipen.annotations.suggestions import annotation_suggestions
15
+ from clipen.media import InventoryRoot
16
+ from clipen.projects.models import (
17
+ DirectoryRole,
18
+ ProjectError,
19
+ validate_project_id,
20
+ validate_request_id,
21
+ validate_revision,
22
+ )
23
+ from clipen.projects.storage import ProjectRepository, command_digest, utc_now
24
+
25
+ from .audio import AudioPreparationInput, PreparedAudioChunk
26
+ from .models import (
27
+ PreparationChunkStatus,
28
+ PreparationCounts,
29
+ PreparationItemStatus,
30
+ PreparationRun,
31
+ PreparationState,
32
+ Rational,
33
+ SourceSpan,
34
+ TimelineSegment,
35
+ )
36
+ from .transcription import TranscriptionResult
37
+
38
+ _TERMINAL_STATES = frozenset(
39
+ {
40
+ PreparationState.SUCCEEDED,
41
+ PreparationState.FAILED,
42
+ PreparationState.CANCELLED,
43
+ PreparationState.INTERRUPTED,
44
+ }
45
+ )
46
+ _TRANSITIONS = {
47
+ PreparationState.QUEUED: {
48
+ PreparationState.RUNNING,
49
+ PreparationState.CANCELLED,
50
+ PreparationState.INTERRUPTED,
51
+ },
52
+ PreparationState.RUNNING: {
53
+ PreparationState.CANCELLING,
54
+ PreparationState.FAILED,
55
+ PreparationState.INTERRUPTED,
56
+ },
57
+ PreparationState.CANCELLING: {
58
+ PreparationState.CANCELLED,
59
+ PreparationState.FAILED,
60
+ PreparationState.INTERRUPTED,
61
+ },
62
+ }
63
+
64
+
65
+ @dataclass(frozen=True)
66
+ class PreparationTarget:
67
+ version_id: str
68
+ role: DirectoryRole
69
+ relative_path: str
70
+ display_name: str
71
+ stream_index: int
72
+ audio: AudioPreparationInput | None
73
+ initial_status: PreparationItemStatus
74
+ issue_code: str | None = None
75
+
76
+ def __post_init__(self) -> None:
77
+ if self.stream_index < -1:
78
+ raise ValueError("preparation target stream is invalid")
79
+ if self.initial_status is PreparationItemStatus.PENDING:
80
+ if self.audio is None or self.stream_index < 0 or self.issue_code is not None:
81
+ raise ValueError("pending preparation target requires valid audio")
82
+ elif self.initial_status is PreparationItemStatus.NO_AUDIO:
83
+ if self.audio is not None or self.stream_index != -1 or self.issue_code is not None:
84
+ raise ValueError("no-audio target is inconsistent")
85
+ elif self.initial_status is PreparationItemStatus.FAILED:
86
+ if self.audio is not None or self.issue_code is None:
87
+ raise ValueError("failed preparation target requires an issue")
88
+ else:
89
+ raise ValueError("new preparation target has an invalid initial state")
90
+
91
+ def to_public(self) -> dict[str, object]:
92
+ return {
93
+ "version_id": self.version_id,
94
+ "role": self.role.value,
95
+ "display_name": self.display_name,
96
+ "stream_index": None if self.stream_index < 0 else self.stream_index,
97
+ "status": self.initial_status.value,
98
+ "issue_code": self.issue_code,
99
+ }
100
+
101
+
102
+ @dataclass(frozen=True)
103
+ class PreparationScope:
104
+ scope_id: str
105
+ project_id: str
106
+ project_revision: int
107
+ inventory_run_id: str
108
+ targets: tuple[PreparationTarget, ...]
109
+ estimated_audio_bytes: int
110
+ duration_seconds: str
111
+
112
+ def __post_init__(self) -> None:
113
+ if re.fullmatch(r"scope_[0-9a-f]{32}", self.scope_id) is None:
114
+ raise ValueError("preparation scope ID is invalid")
115
+ validate_project_id(self.project_id)
116
+ if self.project_revision < 1 or not self.targets:
117
+ raise ValueError("preparation scope is incomplete")
118
+ if self.estimated_audio_bytes < 0:
119
+ raise ValueError("preparation estimate is invalid")
120
+
121
+ def to_public(self) -> dict[str, object]:
122
+ pending = sum(target.initial_status is PreparationItemStatus.PENDING for target in self.targets)
123
+ no_audio = sum(target.initial_status is PreparationItemStatus.NO_AUDIO for target in self.targets)
124
+ issues = sum(target.initial_status is PreparationItemStatus.FAILED for target in self.targets)
125
+ return {
126
+ "scope_id": self.scope_id,
127
+ "inventory_run_id": self.inventory_run_id,
128
+ "project_revision": self.project_revision,
129
+ "counts": {
130
+ "audio_streams": pending,
131
+ "no_audio": no_audio,
132
+ "issues": issues,
133
+ },
134
+ "duration_seconds": self.duration_seconds,
135
+ "estimated_audio_bytes": self.estimated_audio_bytes,
136
+ "items": [target.to_public() for target in self.targets],
137
+ }
138
+
139
+
140
+ @dataclass(frozen=True)
141
+ class PreparationWorkItem:
142
+ target: PreparationTarget
143
+ status: PreparationItemStatus
144
+ audio_artifact_id: str | None
145
+ transcript_revision_id: str | None
146
+ error_code: str | None
147
+
148
+
149
+ @dataclass(frozen=True)
150
+ class PreparationChunk:
151
+ ordinal: int
152
+ start_sample: int
153
+ end_sample: int
154
+ source_span: SourceSpan
155
+ status: PreparationChunkStatus
156
+ transcript_artifact_id: str | None
157
+ result: TranscriptionResult | None
158
+
159
+ def __post_init__(self) -> None:
160
+ if self.ordinal < 0 or self.start_sample < 0 or self.end_sample <= self.start_sample:
161
+ raise ValueError("stored preparation chunk range is invalid")
162
+ completed = self.status in {
163
+ PreparationChunkStatus.TRANSCRIBED,
164
+ PreparationChunkStatus.NO_SPEECH,
165
+ }
166
+ if completed != (self.transcript_artifact_id is not None and self.result is not None):
167
+ raise ValueError("stored preparation chunk result is inconsistent")
168
+
169
+
170
+ class PreparationRepository:
171
+ def __init__(self, projects: ProjectRepository) -> None:
172
+ self.projects = projects
173
+
174
+ def preflight(self, project_id: str) -> PreparationScope:
175
+ validate_project_id(project_id)
176
+ with self.projects.connect(project_id) as connection:
177
+ project = connection.execute("SELECT revision FROM project WHERE project_id = ?", (project_id,)).fetchone()
178
+ current = connection.execute(
179
+ "SELECT i.run_id, r.roots_json FROM current_inventory i "
180
+ "JOIN inventory_runs r ON r.run_id = i.run_id WHERE i.slot = 1"
181
+ ).fetchone()
182
+ if project is None:
183
+ raise ProjectError("project_not_found", "找不到這個作品。", status_code=404)
184
+ if current is None:
185
+ raise ProjectError(
186
+ "inventory_required",
187
+ "請先完成素材檢查。",
188
+ status_code=409,
189
+ )
190
+ try:
191
+ raw_roots = json.loads(current["roots_json"])
192
+ roots = {root.role: root for root in (InventoryRoot.from_storage(value) for value in raw_roots)}
193
+ except (json.JSONDecodeError, TypeError, ValueError, KeyError) as error:
194
+ raise ProjectError("storage_corrupt", "Clipen 無法讀取素材範圍。", status_code=500) from error
195
+ for root in roots.values():
196
+ _verify_inventory_root(root)
197
+ rows = connection.execute(
198
+ "SELECT a.role, a.relative_path, i.display_name, i.kind, i.version_id, "
199
+ "v.size_bytes, v.mtime_ns, v.fingerprint, s.stream_index, s.details_json "
200
+ "FROM inventory_items i JOIN assets a ON a.asset_id = i.asset_id "
201
+ "JOIN asset_versions v ON v.version_id = i.version_id "
202
+ "LEFT JOIN media_streams s ON s.version_id = i.version_id "
203
+ "AND s.kind = 'audio' WHERE i.run_id = ? AND i.status = 'usable' "
204
+ "AND i.kind IN ('video', 'audio') "
205
+ "ORDER BY a.role, a.relative_path, s.stream_index",
206
+ (current["run_id"],),
207
+ ).fetchall()
208
+ if not rows:
209
+ raise ProjectError(
210
+ "preparation_empty",
211
+ "目前沒有可準備的影音素材。",
212
+ status_code=409,
213
+ )
214
+ targets: list[PreparationTarget] = []
215
+ duration = Fraction(0)
216
+ seen_no_audio: set[str] = set()
217
+ for row in rows:
218
+ role = DirectoryRole(row["role"])
219
+ root = roots.get(role)
220
+ if root is None:
221
+ raise ProjectError("storage_corrupt", "Clipen 無法讀取素材範圍。", status_code=500)
222
+ if row["stream_index"] is None:
223
+ if row["version_id"] not in seen_no_audio:
224
+ seen_no_audio.add(row["version_id"])
225
+ targets.append(
226
+ PreparationTarget(
227
+ row["version_id"],
228
+ role,
229
+ row["relative_path"],
230
+ row["display_name"],
231
+ -1,
232
+ None,
233
+ PreparationItemStatus.NO_AUDIO,
234
+ )
235
+ )
236
+ continue
237
+ try:
238
+ details = json.loads(row["details_json"])
239
+ span = _source_span(row["version_id"], row["stream_index"], details)
240
+ audio = AudioPreparationInput(
241
+ root,
242
+ row["relative_path"],
243
+ row["version_id"],
244
+ row["stream_index"],
245
+ row["size_bytes"],
246
+ row["mtime_ns"],
247
+ row["fingerprint"],
248
+ span,
249
+ )
250
+ duration += Fraction(span.duration_pts) * Fraction(span.time_base.numerator, span.time_base.denominator)
251
+ targets.append(
252
+ PreparationTarget(
253
+ row["version_id"],
254
+ role,
255
+ row["relative_path"],
256
+ row["display_name"],
257
+ row["stream_index"],
258
+ audio,
259
+ PreparationItemStatus.PENDING,
260
+ )
261
+ )
262
+ except (json.JSONDecodeError, TypeError, ValueError, KeyError, ZeroDivisionError):
263
+ targets.append(
264
+ PreparationTarget(
265
+ row["version_id"],
266
+ role,
267
+ row["relative_path"],
268
+ row["display_name"],
269
+ row["stream_index"],
270
+ None,
271
+ PreparationItemStatus.FAILED,
272
+ "audio_time_metadata_missing",
273
+ )
274
+ )
275
+ identity = {
276
+ "project_revision": project["revision"],
277
+ "inventory_run_id": current["run_id"],
278
+ "targets": [
279
+ {
280
+ "version_id": target.version_id,
281
+ "stream_index": target.stream_index,
282
+ "status": target.initial_status.value,
283
+ "issue_code": target.issue_code,
284
+ }
285
+ for target in targets
286
+ ],
287
+ }
288
+ encoded = json.dumps(identity, sort_keys=True, separators=(",", ":")).encode()
289
+ scope_id = "scope_" + hashlib.sha256(encoded).hexdigest()[:32]
290
+ estimated = math_ceil_fraction(duration * 16_000 * 2) + len(targets) * 4096
291
+ return PreparationScope(
292
+ scope_id,
293
+ project_id,
294
+ project["revision"],
295
+ current["run_id"],
296
+ tuple(targets),
297
+ estimated,
298
+ _fraction_decimal(duration),
299
+ )
300
+
301
+ def create_run_with_status(
302
+ self,
303
+ project_id: str,
304
+ request_id: object,
305
+ expected_revision: object,
306
+ scope_id: object,
307
+ *,
308
+ recipe: Mapping[str, object],
309
+ model: Mapping[str, object],
310
+ ) -> tuple[PreparationRun, bool, tuple[str, ...]]:
311
+ validate_project_id(project_id)
312
+ normalized_request = validate_request_id(request_id)
313
+ revision = validate_revision(expected_revision)
314
+ if not isinstance(scope_id, str):
315
+ raise ProjectError("scope_invalid", "分析範圍無效。", status_code=422)
316
+ recipe_json = _bounded_json(recipe, "analysis recipe")
317
+ model_json = _bounded_json(model, "ASR model")
318
+ request_hash = command_digest(
319
+ {
320
+ "expected_revision": revision,
321
+ "scope_id": scope_id,
322
+ "recipe": json.loads(recipe_json),
323
+ "model": json.loads(model_json),
324
+ }
325
+ )
326
+ # A receipt is the durable response to an already accepted command. Read it
327
+ # before recomputing the live scope so retries stay idempotent even after a
328
+ # later project edit or inventory refresh.
329
+ with self.projects.connect(project_id) as connection:
330
+ receipt = connection.execute(
331
+ "SELECT command_type, request_hash, run_id FROM preparation_command_receipts WHERE request_id = ?",
332
+ (normalized_request,),
333
+ ).fetchone()
334
+ if receipt is not None:
335
+ if receipt["command_type"] != "start_preparation" or receipt["request_hash"] != request_hash:
336
+ raise ProjectError(
337
+ "request_reused",
338
+ "這次操作的識別資訊已用於不同內容。",
339
+ status_code=409,
340
+ )
341
+ return self._read_run(connection, receipt["run_id"]), False, ()
342
+
343
+ scope = self.preflight(project_id)
344
+ if scope.scope_id != scope_id or scope.project_revision != revision:
345
+ raise ProjectError(
346
+ "scope_changed",
347
+ "素材或作品內容已改變,請重新確認分析範圍。",
348
+ status_code=409,
349
+ )
350
+ run_id = _derived_id("prep", project_id, normalized_request)
351
+ operation_id = _derived_id("op", run_id, scope_id)
352
+ attempt_id = _derived_id("att", operation_id, "1")
353
+ input_fingerprint = hashlib.sha256(
354
+ json.dumps(
355
+ {
356
+ "scope_id": scope_id,
357
+ "recipe": json.loads(recipe_json),
358
+ "model": json.loads(model_json),
359
+ },
360
+ sort_keys=True,
361
+ separators=(",", ":"),
362
+ ).encode()
363
+ ).hexdigest()
364
+ with self.projects.connect(project_id) as connection:
365
+ try:
366
+ connection.execute("BEGIN IMMEDIATE")
367
+ receipt = connection.execute(
368
+ "SELECT command_type, request_hash, run_id FROM preparation_command_receipts WHERE request_id = ?",
369
+ (normalized_request,),
370
+ ).fetchone()
371
+ if receipt is not None:
372
+ if receipt["command_type"] != "start_preparation" or receipt["request_hash"] != request_hash:
373
+ raise ProjectError(
374
+ "request_reused",
375
+ "這次操作的識別資訊已用於不同內容。",
376
+ status_code=409,
377
+ )
378
+ replay = self._read_run(connection, receipt["run_id"])
379
+ connection.rollback()
380
+ return replay, False, ()
381
+ live = connection.execute(
382
+ "SELECT p.revision, c.run_id AS inventory_run_id FROM project p "
383
+ "LEFT JOIN current_inventory c ON c.slot = 1 "
384
+ "WHERE p.project_id = ?",
385
+ (project_id,),
386
+ ).fetchone()
387
+ if (
388
+ live is None
389
+ or live["revision"] != scope.project_revision
390
+ or live["inventory_run_id"] != scope.inventory_run_id
391
+ ):
392
+ raise ProjectError(
393
+ "scope_changed",
394
+ "素材或作品內容已改變,請重新確認分析範圍。",
395
+ status_code=409,
396
+ )
397
+ busy = connection.execute(
398
+ "SELECT run_id FROM preparation_runs WHERE state IN ('queued', 'running', 'cancelling') LIMIT 1"
399
+ ).fetchone()
400
+ if busy is not None:
401
+ raise ProjectError(
402
+ "preparation_busy",
403
+ "已有一個素材分析正在進行。",
404
+ status_code=409,
405
+ )
406
+ retired_artifact_paths = self._remove_previous_analysis(connection)
407
+ now = utc_now()
408
+ initial_no_audio = sum(
409
+ target.initial_status is PreparationItemStatus.NO_AUDIO for target in scope.targets
410
+ )
411
+ initial_issues = sum(target.initial_status is PreparationItemStatus.FAILED for target in scope.targets)
412
+ connection.execute(
413
+ "INSERT INTO preparation_runs "
414
+ "(run_id, project_id, request_id, project_revision, inventory_run_id, "
415
+ "scope_id, operation_id, attempt_id, attempt_number, input_fingerprint, "
416
+ "recipe_json, model_json, state, phase, total_count, no_audio_count, "
417
+ "issue_count, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1, ?, ?, ?, "
418
+ "'queued', 'preparing', ?, ?, ?, ?)",
419
+ (
420
+ run_id,
421
+ project_id,
422
+ normalized_request,
423
+ revision,
424
+ scope.inventory_run_id,
425
+ scope_id,
426
+ operation_id,
427
+ attempt_id,
428
+ input_fingerprint,
429
+ recipe_json,
430
+ model_json,
431
+ len(scope.targets),
432
+ initial_no_audio,
433
+ initial_issues,
434
+ now,
435
+ ),
436
+ )
437
+ for target in scope.targets:
438
+ connection.execute(
439
+ "INSERT INTO preparation_items "
440
+ "(run_id, version_id, stream_index, status, error_code) "
441
+ "VALUES (?, ?, ?, ?, ?)",
442
+ (
443
+ run_id,
444
+ target.version_id,
445
+ target.stream_index,
446
+ target.initial_status.value,
447
+ target.issue_code,
448
+ ),
449
+ )
450
+ connection.execute(
451
+ "INSERT INTO preparation_command_receipts "
452
+ "(request_id, command_type, request_hash, run_id, created_at) "
453
+ "VALUES (?, 'start_preparation', ?, ?, ?)",
454
+ (normalized_request, request_hash, run_id, now),
455
+ )
456
+ self._append_event(
457
+ connection,
458
+ project_id,
459
+ operation_id,
460
+ "queued",
461
+ {"phase": "preparing"},
462
+ now,
463
+ )
464
+ created = self._read_run(connection, run_id)
465
+ connection.commit()
466
+ return created, True, retired_artifact_paths
467
+ except ProjectError:
468
+ connection.rollback()
469
+ raise
470
+ except sqlite3.Error as error:
471
+ connection.rollback()
472
+ raise ProjectError("storage_failed", "Clipen 無法建立素材分析。", status_code=500) from error
473
+
474
+ @staticmethod
475
+ def _remove_previous_analysis(connection: sqlite3.Connection) -> tuple[str, ...]:
476
+ """Remove the prior preparation graph after a replacement is validated.
477
+
478
+ Source inventory and evidence analysis are deliberately outside this graph.
479
+ Blob deletion is deferred until after commit so a database rollback can never
480
+ leave a live artifact record pointing at a missing file.
481
+ """
482
+ paths = tuple(
483
+ row["relative_path"]
484
+ for row in connection.execute(
485
+ "SELECT DISTINCT relative_path FROM artifacts "
486
+ "WHERE producer_operation_id IN "
487
+ "(SELECT operation_id FROM preparation_runs)"
488
+ ).fetchall()
489
+ )
490
+ connection.execute("DELETE FROM current_preparation")
491
+ # Items reference transcript revisions, while chunks cascade from items.
492
+ # Delete the item side first to break that intentional checkpoint link.
493
+ connection.execute("DELETE FROM preparation_items")
494
+ connection.execute("DELETE FROM transcription_revisions")
495
+ connection.execute("DELETE FROM preparation_command_receipts")
496
+ connection.execute(
497
+ "DELETE FROM operation_events WHERE operation_id IN (SELECT operation_id FROM preparation_runs)"
498
+ )
499
+ # Keep any record that another feature has explicitly adopted. This is
500
+ # defensive today and prevents future evidence/export references from being
501
+ # invalidated when preparation results are replaced.
502
+ connection.execute(
503
+ "DELETE FROM artifacts "
504
+ "WHERE producer_operation_id IN "
505
+ "(SELECT operation_id FROM preparation_runs) "
506
+ "AND NOT EXISTS ("
507
+ "SELECT 1 FROM evidence_images "
508
+ "WHERE evidence_images.artifact_id = artifacts.artifact_id)"
509
+ )
510
+ connection.execute("DELETE FROM preparation_runs")
511
+ return paths
512
+
513
+ def get_run(self, project_id: str, run_id: str) -> PreparationRun:
514
+ validate_project_id(project_id)
515
+ with self.projects.connect(project_id) as connection:
516
+ run = self._read_run(connection, run_id)
517
+ if run.project_id != project_id:
518
+ raise ProjectError("preparation_not_found", "找不到這次素材分析。", status_code=404)
519
+ return run
520
+
521
+ def recipe(self, project_id: str, run_id: str) -> Mapping[str, object]:
522
+ validate_project_id(project_id)
523
+ with self.projects.connect(project_id) as connection:
524
+ run = self._read_run(connection, run_id)
525
+ if run.project_id != project_id:
526
+ raise ProjectError("preparation_not_found", "找不到這次素材分析。", status_code=404)
527
+ row = connection.execute("SELECT recipe_json FROM preparation_runs WHERE run_id = ?", (run_id,)).fetchone()
528
+ try:
529
+ value = json.loads(row["recipe_json"])
530
+ if not isinstance(value, dict):
531
+ raise ValueError("recipe is not an object")
532
+ return value
533
+ except (json.JSONDecodeError, KeyError, TypeError, ValueError) as error:
534
+ raise ProjectError("storage_corrupt", "Clipen 無法讀取分析設定。", status_code=500) from error
535
+
536
+ def latest_run(self, project_id: str) -> PreparationRun | None:
537
+ validate_project_id(project_id)
538
+ with self.projects.connect(project_id) as connection:
539
+ row = connection.execute("SELECT run_id FROM preparation_runs ORDER BY created_at DESC LIMIT 1").fetchone()
540
+ return None if row is None else self._read_run(connection, row["run_id"])
541
+
542
+ def current_run(self, project_id: str) -> PreparationRun | None:
543
+ validate_project_id(project_id)
544
+ with self.projects.connect(project_id) as connection:
545
+ row = connection.execute("SELECT run_id FROM current_preparation WHERE slot = 1").fetchone()
546
+ return None if row is None else self._read_run(connection, row["run_id"])
547
+
548
+ def result_items(
549
+ self,
550
+ project_id: str,
551
+ run_id: str,
552
+ *,
553
+ offset: int = 0,
554
+ limit: int = 25,
555
+ trip_day: int | None = None,
556
+ review_state: str = "all",
557
+ ) -> dict[str, object]:
558
+ """Return a bounded, path-free page of transcription result summaries."""
559
+ validate_project_id(project_id)
560
+ self._validate_result_page(offset, limit)
561
+ if trip_day is not None and (
562
+ isinstance(trip_day, bool) or not isinstance(trip_day, int) or not 1 <= trip_day <= 365
563
+ ):
564
+ raise ProjectError("analysis_filter_invalid", "旅行日篩選無效。", status_code=422)
565
+ if review_state not in {"all", "pending", "reviewed"}:
566
+ raise ProjectError("analysis_filter_invalid", "處理狀態篩選無效。", status_code=422)
567
+ with self.projects.connect(project_id) as connection:
568
+ run = self._read_run(connection, run_id)
569
+ if run.project_id != project_id:
570
+ raise ProjectError("preparation_not_found", "找不到這次素材分析。", status_code=404)
571
+ suggestions = annotation_suggestions(connection)
572
+ material_rows = {
573
+ row["version_id"]: row
574
+ for row in connection.execute(
575
+ "SELECT annotations.version_id,annotations.trip_day,annotations.day_part "
576
+ "FROM material_annotations AS annotations "
577
+ "JOIN preparation_items AS items ON items.version_id=annotations.version_id "
578
+ "WHERE items.run_id=? GROUP BY annotations.version_id",
579
+ (run_id,),
580
+ ).fetchall()
581
+ }
582
+ version_counts = connection.execute(
583
+ "SELECT version_id,COUNT(*) AS item_count FROM preparation_items WHERE run_id=? GROUP BY version_id",
584
+ (run_id,),
585
+ ).fetchall()
586
+ effective_days: dict[str, int | None] = {}
587
+ day_counts: dict[int, int] = {}
588
+ for version in version_counts:
589
+ annotation = material_rows.get(version["version_id"])
590
+ suggested = suggestions.get(version["version_id"], {})
591
+ day = annotation["trip_day"] if annotation is not None else suggested.get("trip_day")
592
+ effective_days[version["version_id"]] = day if isinstance(day, int) else None
593
+ if isinstance(day, int):
594
+ day_counts[day] = day_counts.get(day, 0) + version["item_count"]
595
+
596
+ where = ["pi.run_id = ?"]
597
+ parameters: list[object] = [run_id]
598
+ if trip_day is not None:
599
+ matching_versions = [version_id for version_id, day in effective_days.items() if day == trip_day]
600
+ if matching_versions:
601
+ where.append(f"pi.version_id IN ({','.join('?' for _ in matching_versions)})")
602
+ parameters.extend(matching_versions)
603
+ else:
604
+ where.append("0 = 1")
605
+ if review_state == "pending":
606
+ where.append("ma.version_id IS NULL AND ta.version_id IS NULL")
607
+ elif review_state == "reviewed":
608
+ where.append("(ma.version_id IS NOT NULL OR ta.version_id IS NOT NULL)")
609
+ joins = (
610
+ " LEFT JOIN material_annotations ma ON ma.version_id=pi.version_id "
611
+ "LEFT JOIN transcript_annotations ta ON ta.version_id=pi.version_id "
612
+ " AND ta.stream_index=pi.stream_index "
613
+ )
614
+ total = connection.execute(
615
+ "SELECT COUNT(*) FROM preparation_items pi" + joins + " WHERE " + " AND ".join(where),
616
+ parameters,
617
+ ).fetchone()[0]
618
+ rows = connection.execute(
619
+ "SELECT pi.version_id, pi.stream_index, pi.status, pi.error_code, "
620
+ "pi.review_required, "
621
+ "pi.transcript_revision_id, ii.display_name, ii.kind, a.role, tr.language, "
622
+ "tr.source_span_json, ma.revision AS material_revision, ma.usage, "
623
+ "ma.trip_day AS annotated_trip_day, ma.day_part AS annotated_day_part, "
624
+ "ta.revision AS annotation_revision, ta.confirmed AS transcript_confirmed, "
625
+ "ta.discarded AS transcript_discarded, "
626
+ "ta.source_revision_id AS annotation_source_revision, "
627
+ "(SELECT COUNT(*) FROM transcript_segments ts "
628
+ " WHERE ts.revision_id = pi.transcript_revision_id) AS segment_count, "
629
+ "(SELECT text FROM transcript_segments ts "
630
+ " WHERE ts.revision_id = pi.transcript_revision_id "
631
+ " ORDER BY ordinal LIMIT 1) AS preview_text, "
632
+ "(SELECT start_pts FROM transcript_segments ts "
633
+ " WHERE ts.revision_id = pi.transcript_revision_id "
634
+ " ORDER BY ordinal LIMIT 1) AS preview_start_pts "
635
+ "FROM preparation_items pi "
636
+ "JOIN preparation_runs pr ON pr.run_id = pi.run_id "
637
+ "JOIN asset_versions av ON av.version_id = pi.version_id "
638
+ "JOIN assets a ON a.asset_id = av.asset_id "
639
+ "JOIN inventory_items ii ON ii.run_id = pr.inventory_run_id "
640
+ " AND ii.asset_id = a.asset_id "
641
+ "LEFT JOIN transcription_revisions tr "
642
+ " ON tr.revision_id = pi.transcript_revision_id " + joins + "WHERE " + " AND ".join(where) + " "
643
+ "ORDER BY ii.display_name COLLATE NOCASE, pi.stream_index "
644
+ "LIMIT ? OFFSET ?",
645
+ (*parameters, limit, offset),
646
+ ).fetchall()
647
+ try:
648
+ items = []
649
+ for row in rows:
650
+ source = None
651
+ if row["source_span_json"] is not None:
652
+ span = SourceSpan.from_storage(json.loads(row["source_span_json"]))
653
+ source = {
654
+ "start_pts": span.start_pts,
655
+ "end_pts": span.end_pts,
656
+ "time_base": span.time_base.to_storage(),
657
+ }
658
+ preview = row["preview_text"]
659
+ if preview is not None and not isinstance(preview, str):
660
+ raise ValueError("transcript preview is invalid")
661
+ public_status = (
662
+ "needs_review"
663
+ if row["status"] == PreparationItemStatus.TRANSCRIBED.value and row["review_required"] == 1
664
+ else PreparationItemStatus(row["status"]).value
665
+ )
666
+ suggestion = suggestions.get(row["version_id"], {})
667
+ effective_day = (
668
+ row["annotated_trip_day"] if row["material_revision"] is not None else suggestion.get("trip_day")
669
+ )
670
+ effective_day_part = (
671
+ row["annotated_day_part"] if row["material_revision"] is not None else suggestion.get("day_part")
672
+ )
673
+ transcript_confirmed = (
674
+ row["transcript_confirmed"] == 1
675
+ and row["annotation_source_revision"] == row["transcript_revision_id"]
676
+ )
677
+ transcript_discarded = row["transcript_discarded"] == 1
678
+ if row["usage"] == "exclude":
679
+ user_state = "excluded"
680
+ elif row["usage"] == "must_use":
681
+ user_state = "priority"
682
+ elif transcript_confirmed:
683
+ user_state = "confirmed"
684
+ elif row["material_revision"] is not None or row["annotation_revision"] is not None:
685
+ user_state = "reviewed"
686
+ else:
687
+ user_state = "pending"
688
+ items.append(
689
+ {
690
+ "version_id": row["version_id"],
691
+ "stream_index": row["stream_index"],
692
+ "display_name": row["display_name"],
693
+ "kind": row["kind"],
694
+ "role": DirectoryRole(row["role"]).value,
695
+ "status": public_status,
696
+ "issue_code": row["error_code"],
697
+ "language": row["language"],
698
+ "source": source,
699
+ "segment_count": row["segment_count"],
700
+ "preview_text": (None if preview is None or transcript_discarded else preview[:280]),
701
+ "preview_start_pts": row["preview_start_pts"],
702
+ "preview_truncated": (not transcript_discarded and preview is not None and len(preview) > 280),
703
+ "transcript_discarded": transcript_discarded,
704
+ "user_state": user_state,
705
+ "trip_day": effective_day,
706
+ "day_part": effective_day_part,
707
+ }
708
+ )
709
+ return {
710
+ "run_id": run_id,
711
+ "items": items,
712
+ "total": total,
713
+ "offset": offset,
714
+ "limit": limit,
715
+ "next_offset": offset + len(items) if offset + len(items) < total else None,
716
+ "filters": {
717
+ "trip_days": [{"day": day, "count": count} for day, count in sorted(day_counts.items())],
718
+ "review_state": review_state,
719
+ "trip_day": trip_day,
720
+ },
721
+ }
722
+ except (json.JSONDecodeError, KeyError, TypeError, ValueError) as error:
723
+ raise ProjectError("storage_corrupt", "Clipen 無法讀取逐字稿清單。", status_code=500) from error
724
+
725
+ def transcript_segments(
726
+ self,
727
+ project_id: str,
728
+ run_id: str,
729
+ version_id: str,
730
+ stream_index: int,
731
+ *,
732
+ offset: int = 0,
733
+ limit: int = 100,
734
+ ) -> dict[str, object]:
735
+ """Return one bounded page of source-timed transcript segments."""
736
+ validate_project_id(project_id)
737
+ self._validate_result_page(offset, limit)
738
+ if re.fullmatch(r"av_[0-9a-f]{32}", version_id) is None:
739
+ raise ProjectError("transcript_not_found", "找不到這份逐字稿。", status_code=404)
740
+ if isinstance(stream_index, bool) or not isinstance(stream_index, int) or stream_index < 0:
741
+ raise ProjectError("transcript_not_found", "找不到這份逐字稿。", status_code=404)
742
+ with self.projects.connect(project_id) as connection:
743
+ run = self._read_run(connection, run_id)
744
+ if run.project_id != project_id:
745
+ raise ProjectError("preparation_not_found", "找不到這次素材分析。", status_code=404)
746
+ item = connection.execute(
747
+ "SELECT pi.status, pi.transcript_revision_id, ii.display_name, a.role, "
748
+ "tr.language, tr.source_span_json "
749
+ "FROM preparation_items pi "
750
+ "JOIN preparation_runs pr ON pr.run_id = pi.run_id "
751
+ "JOIN asset_versions av ON av.version_id = pi.version_id "
752
+ "JOIN assets a ON a.asset_id = av.asset_id "
753
+ "JOIN inventory_items ii ON ii.run_id = pr.inventory_run_id "
754
+ " AND ii.asset_id = a.asset_id "
755
+ "LEFT JOIN transcription_revisions tr "
756
+ " ON tr.revision_id = pi.transcript_revision_id "
757
+ "WHERE pi.run_id = ? AND pi.version_id = ? AND pi.stream_index = ?",
758
+ (run_id, version_id, stream_index),
759
+ ).fetchone()
760
+ if item is None:
761
+ raise ProjectError("transcript_not_found", "找不到這份逐字稿。", status_code=404)
762
+ revision_id = item["transcript_revision_id"]
763
+ if revision_id is None or item["status"] != PreparationItemStatus.TRANSCRIBED.value:
764
+ raise ProjectError("transcript_unavailable", "這個素材沒有可查看的逐字稿。", status_code=409)
765
+ total = connection.execute(
766
+ "SELECT COUNT(*) FROM transcript_segments WHERE revision_id = ?",
767
+ (revision_id,),
768
+ ).fetchone()[0]
769
+ rows = connection.execute(
770
+ "SELECT start_pts, end_pts, text, confidence, ordinal "
771
+ "FROM transcript_segments WHERE revision_id = ? "
772
+ "ORDER BY ordinal LIMIT ? OFFSET ?",
773
+ (revision_id, limit, offset),
774
+ ).fetchall()
775
+ try:
776
+ source = SourceSpan.from_storage(json.loads(item["source_span_json"]))
777
+ segments = []
778
+ for row in rows:
779
+ span = SourceSpan(
780
+ version_id,
781
+ stream_index,
782
+ row["start_pts"],
783
+ row["end_pts"],
784
+ source.time_base,
785
+ )
786
+ segments.append(
787
+ {
788
+ "ordinal": row["ordinal"],
789
+ "start_pts": span.start_pts,
790
+ "end_pts": span.end_pts,
791
+ "text": row["text"],
792
+ "confidence": row["confidence"],
793
+ }
794
+ )
795
+ return {
796
+ "run_id": run_id,
797
+ "revision_id": revision_id,
798
+ "version_id": version_id,
799
+ "stream_index": stream_index,
800
+ "display_name": item["display_name"],
801
+ "role": DirectoryRole(item["role"]).value,
802
+ "language": item["language"],
803
+ "source_start_pts": source.start_pts,
804
+ "time_base": source.time_base.to_storage(),
805
+ "segments": segments,
806
+ "total": total,
807
+ "offset": offset,
808
+ "limit": limit,
809
+ "next_offset": offset + len(segments) if offset + len(segments) < total else None,
810
+ }
811
+ except (json.JSONDecodeError, KeyError, TypeError, ValueError) as error:
812
+ raise ProjectError("storage_corrupt", "Clipen 無法讀取逐字稿內容。", status_code=500) from error
813
+
814
+ @staticmethod
815
+ def _validate_result_page(offset: int, limit: int) -> None:
816
+ if (
817
+ isinstance(offset, bool)
818
+ or not isinstance(offset, int)
819
+ or offset < 0
820
+ or offset > 1_000_000
821
+ or isinstance(limit, bool)
822
+ or not isinstance(limit, int)
823
+ or not 1 <= limit <= 100
824
+ ):
825
+ raise ValueError("transcript result page is invalid")
826
+
827
+ def list_events(
828
+ self,
829
+ project_id: str,
830
+ run_id: str,
831
+ *,
832
+ after_sequence: int = 0,
833
+ limit: int = 100,
834
+ ) -> tuple[dict[str, object], ...]:
835
+ validate_project_id(project_id)
836
+ if (
837
+ isinstance(after_sequence, bool)
838
+ or not isinstance(after_sequence, int)
839
+ or after_sequence < 0
840
+ or isinstance(limit, bool)
841
+ or not isinstance(limit, int)
842
+ or not 1 <= limit <= 500
843
+ ):
844
+ raise ValueError("operation event bounds are invalid")
845
+ with self.projects.connect(project_id) as connection:
846
+ run = self._read_run(connection, run_id)
847
+ if run.project_id != project_id:
848
+ raise ProjectError("preparation_not_found", "找不到這次素材分析。", status_code=404)
849
+ rows = connection.execute(
850
+ "SELECT sequence, event_type, payload_json, created_at "
851
+ "FROM operation_events WHERE project_id = ? AND operation_id = ? "
852
+ "AND sequence > ? ORDER BY sequence LIMIT ?",
853
+ (project_id, run.operation_id, after_sequence, limit),
854
+ ).fetchall()
855
+ events = []
856
+ try:
857
+ for row in rows:
858
+ payload = json.loads(row["payload_json"])
859
+ if not isinstance(payload, dict):
860
+ raise ValueError("event payload is not an object")
861
+ events.append(
862
+ {
863
+ "sequence": row["sequence"],
864
+ "type": row["event_type"],
865
+ "payload": payload,
866
+ "created_at": row["created_at"],
867
+ }
868
+ )
869
+ except (json.JSONDecodeError, TypeError, ValueError) as error:
870
+ raise ProjectError("storage_corrupt", "Clipen 無法讀取分析進度。", status_code=500) from error
871
+ return tuple(events)
872
+
873
+ def list_work_items(self, project_id: str, run_id: str) -> tuple[PreparationWorkItem, ...]:
874
+ run = self.get_run(project_id, run_id)
875
+ scope = self.preflight(project_id)
876
+ if scope.scope_id != run.scope_id or scope.inventory_run_id != run.inventory_run_id:
877
+ raise ProjectError(
878
+ "scope_changed",
879
+ "素材或作品內容已改變,無法繼續這次分析。",
880
+ status_code=409,
881
+ )
882
+ targets = {(target.version_id, target.stream_index): target for target in scope.targets}
883
+ with self.projects.connect(project_id) as connection:
884
+ rows = connection.execute(
885
+ "SELECT version_id, stream_index, status, audio_artifact_id, "
886
+ "transcript_revision_id, error_code FROM preparation_items "
887
+ "WHERE run_id = ? ORDER BY version_id, stream_index",
888
+ (run_id,),
889
+ ).fetchall()
890
+ try:
891
+ return tuple(
892
+ PreparationWorkItem(
893
+ targets[(row["version_id"], row["stream_index"])],
894
+ PreparationItemStatus(row["status"]),
895
+ row["audio_artifact_id"],
896
+ row["transcript_revision_id"],
897
+ row["error_code"],
898
+ )
899
+ for row in rows
900
+ )
901
+ except (KeyError, TypeError, ValueError) as error:
902
+ raise ProjectError("storage_corrupt", "Clipen 無法讀取分析項目。", status_code=500) from error
903
+
904
+ def register_chunks(
905
+ self,
906
+ project_id: str,
907
+ run_id: str,
908
+ version_id: str,
909
+ stream_index: int,
910
+ chunks: tuple[PreparedAudioChunk, ...],
911
+ ) -> tuple[PreparationChunk, ...]:
912
+ if not chunks:
913
+ raise ValueError("preparation requires at least one audio chunk")
914
+ with self.projects.connect(project_id) as connection:
915
+ try:
916
+ connection.execute("BEGIN IMMEDIATE")
917
+ run = self._read_run(connection, run_id)
918
+ if run.project_id != project_id or run.state is not PreparationState.RUNNING:
919
+ raise ProjectError(
920
+ "preparation_state_conflict",
921
+ "這次素材分析目前不能保存切塊。",
922
+ status_code=409,
923
+ )
924
+ item = connection.execute(
925
+ "SELECT status FROM preparation_items WHERE run_id = ? AND version_id = ? AND stream_index = ?",
926
+ (run_id, version_id, stream_index),
927
+ ).fetchone()
928
+ if item is None or item["status"] != PreparationItemStatus.PREPARED.value:
929
+ raise ProjectError(
930
+ "preparation_item_conflict",
931
+ "這個分析項目尚未準備好。",
932
+ status_code=409,
933
+ )
934
+ existing = connection.execute(
935
+ "SELECT ordinal, start_sample, end_sample, source_span_json, status, "
936
+ "transcript_artifact_id, result_json FROM preparation_chunks "
937
+ "WHERE run_id = ? AND version_id = ? AND stream_index = ? "
938
+ "ORDER BY ordinal",
939
+ (run_id, version_id, stream_index),
940
+ ).fetchall()
941
+ if existing:
942
+ observed = tuple(
943
+ (row["start_sample"], row["end_sample"], row["source_span_json"]) for row in existing
944
+ )
945
+ requested = tuple(
946
+ (
947
+ chunk.start_sample,
948
+ chunk.end_sample,
949
+ json.dumps(
950
+ chunk.source_span.to_storage(),
951
+ sort_keys=True,
952
+ separators=(",", ":"),
953
+ ),
954
+ )
955
+ for chunk in chunks
956
+ )
957
+ if observed != requested:
958
+ raise ProjectError(
959
+ "chunk_recipe_changed",
960
+ "音訊切塊方式已改變,無法沿用先前進度。",
961
+ status_code=409,
962
+ )
963
+ else:
964
+ for ordinal, chunk in enumerate(chunks):
965
+ connection.execute(
966
+ "INSERT INTO preparation_chunks "
967
+ "(run_id, version_id, stream_index, ordinal, start_sample, "
968
+ "end_sample, source_span_json, status) "
969
+ "VALUES (?, ?, ?, ?, ?, ?, ?, 'pending')",
970
+ (
971
+ run_id,
972
+ version_id,
973
+ stream_index,
974
+ ordinal,
975
+ chunk.start_sample,
976
+ chunk.end_sample,
977
+ json.dumps(
978
+ chunk.source_span.to_storage(),
979
+ sort_keys=True,
980
+ separators=(",", ":"),
981
+ ),
982
+ ),
983
+ )
984
+ existing = connection.execute(
985
+ "SELECT ordinal, start_sample, end_sample, source_span_json, status, "
986
+ "transcript_artifact_id, result_json FROM preparation_chunks "
987
+ "WHERE run_id = ? AND version_id = ? AND stream_index = ? "
988
+ "ORDER BY ordinal",
989
+ (run_id, version_id, stream_index),
990
+ ).fetchall()
991
+ result = tuple(self._read_chunk(row) for row in existing)
992
+ connection.commit()
993
+ return result
994
+ except ProjectError:
995
+ connection.rollback()
996
+ raise
997
+ except sqlite3.Error as error:
998
+ connection.rollback()
999
+ raise ProjectError("storage_failed", "Clipen 無法保存音訊切塊。", status_code=500) from error
1000
+
1001
+ def settle_chunk(
1002
+ self,
1003
+ project_id: str,
1004
+ run_id: str,
1005
+ version_id: str,
1006
+ stream_index: int,
1007
+ ordinal: int,
1008
+ artifact_id: str,
1009
+ result: TranscriptionResult,
1010
+ ) -> PreparationChunk:
1011
+ status = PreparationChunkStatus.NO_SPEECH if result.no_speech_detected else PreparationChunkStatus.TRANSCRIBED
1012
+ result_json = _encoded_json(result.to_storage(), "transcript result", 32 * 1024 * 1024)
1013
+ with self.projects.connect(project_id) as connection:
1014
+ try:
1015
+ connection.execute("BEGIN IMMEDIATE")
1016
+ run = self._read_run(connection, run_id)
1017
+ if run.project_id != project_id or run.state is not PreparationState.RUNNING:
1018
+ raise ProjectError(
1019
+ "preparation_state_conflict",
1020
+ "這次素材分析目前不能保存逐字稿。",
1021
+ status_code=409,
1022
+ )
1023
+ row = connection.execute(
1024
+ "SELECT ordinal, start_sample, end_sample, source_span_json, status, "
1025
+ "transcript_artifact_id, result_json FROM preparation_chunks "
1026
+ "WHERE run_id = ? AND version_id = ? AND stream_index = ? AND ordinal = ?",
1027
+ (run_id, version_id, stream_index, ordinal),
1028
+ ).fetchone()
1029
+ if row is None:
1030
+ raise ProjectError("preparation_chunk_not_found", "找不到這個音訊切塊。", status_code=404)
1031
+ if row["status"] != PreparationChunkStatus.PENDING.value:
1032
+ completed = self._read_chunk(row)
1033
+ if completed.transcript_artifact_id != artifact_id or completed.result != result:
1034
+ raise ProjectError(
1035
+ "preparation_chunk_conflict",
1036
+ "這個音訊切塊已保存不同結果。",
1037
+ status_code=409,
1038
+ )
1039
+ connection.rollback()
1040
+ return completed
1041
+ connection.execute(
1042
+ "UPDATE preparation_chunks SET status = ?, transcript_artifact_id = ?, "
1043
+ "result_json = ? WHERE run_id = ? AND version_id = ? "
1044
+ "AND stream_index = ? AND ordinal = ?",
1045
+ (
1046
+ status.value,
1047
+ artifact_id,
1048
+ result_json,
1049
+ run_id,
1050
+ version_id,
1051
+ stream_index,
1052
+ ordinal,
1053
+ ),
1054
+ )
1055
+ stored = connection.execute(
1056
+ "SELECT ordinal, start_sample, end_sample, source_span_json, status, "
1057
+ "transcript_artifact_id, result_json FROM preparation_chunks "
1058
+ "WHERE run_id = ? AND version_id = ? AND stream_index = ? AND ordinal = ?",
1059
+ (run_id, version_id, stream_index, ordinal),
1060
+ ).fetchone()
1061
+ chunk = self._read_chunk(stored)
1062
+ connection.commit()
1063
+ return chunk
1064
+ except ProjectError:
1065
+ connection.rollback()
1066
+ raise
1067
+ except sqlite3.Error as error:
1068
+ connection.rollback()
1069
+ raise ProjectError("storage_failed", "Clipen 無法保存逐字稿切塊。", status_code=500) from error
1070
+
1071
+ def publish_transcript_revision(
1072
+ self,
1073
+ project_id: str,
1074
+ run_id: str,
1075
+ version_id: str,
1076
+ stream_index: int,
1077
+ *,
1078
+ artifact_id: str,
1079
+ language: str,
1080
+ model: Mapping[str, object],
1081
+ recipe_id: str,
1082
+ source_span: SourceSpan,
1083
+ segments: tuple[TimelineSegment, ...],
1084
+ needs_review: bool = False,
1085
+ ) -> str:
1086
+ if not re.fullmatch(r"[a-z]{2,3}(?:-[A-Z]{2})?", language):
1087
+ raise ValueError("transcript language is invalid")
1088
+ if not re.fullmatch(r"[a-z][a-z0-9_.-]{0,127}", recipe_id):
1089
+ raise ValueError("transcript recipe is invalid")
1090
+ if any(
1091
+ segment.source_span.version_id != version_id or segment.source_span.stream_index != stream_index
1092
+ for segment in segments
1093
+ ):
1094
+ raise ValueError("timeline segment belongs to another source")
1095
+ if not isinstance(needs_review, bool) or (needs_review and not segments):
1096
+ raise ValueError("transcript review status is invalid")
1097
+ model_json = _bounded_json(model, "ASR model")
1098
+ source_json = json.dumps(source_span.to_storage(), sort_keys=True, separators=(",", ":"))
1099
+ identity = {
1100
+ "run_id": run_id,
1101
+ "version_id": version_id,
1102
+ "stream_index": stream_index,
1103
+ "artifact_id": artifact_id,
1104
+ "language": language,
1105
+ "recipe_id": recipe_id,
1106
+ "needs_review": needs_review,
1107
+ }
1108
+ revision_id = (
1109
+ "trn_"
1110
+ + hashlib.sha256(json.dumps(identity, sort_keys=True, separators=(",", ":")).encode()).hexdigest()[:32]
1111
+ )
1112
+ with self.projects.connect(project_id) as connection:
1113
+ try:
1114
+ connection.execute("BEGIN IMMEDIATE")
1115
+ run = self._read_run(connection, run_id)
1116
+ if run.project_id != project_id or run.state is not PreparationState.RUNNING:
1117
+ raise ProjectError(
1118
+ "preparation_state_conflict",
1119
+ "這次素材分析目前不能發布逐字稿。",
1120
+ status_code=409,
1121
+ )
1122
+ item = connection.execute(
1123
+ "SELECT status, transcript_revision_id FROM preparation_items "
1124
+ "WHERE run_id = ? AND version_id = ? AND stream_index = ?",
1125
+ (run_id, version_id, stream_index),
1126
+ ).fetchone()
1127
+ if item is None:
1128
+ raise ProjectError("preparation_item_not_found", "找不到這個分析項目。", status_code=404)
1129
+ if item["transcript_revision_id"] is not None:
1130
+ if item["transcript_revision_id"] != revision_id:
1131
+ raise ProjectError(
1132
+ "preparation_item_conflict",
1133
+ "這個分析項目已發布不同逐字稿。",
1134
+ status_code=409,
1135
+ )
1136
+ connection.rollback()
1137
+ return revision_id
1138
+ if item["status"] != PreparationItemStatus.PREPARED.value:
1139
+ raise ProjectError(
1140
+ "preparation_item_conflict",
1141
+ "這個分析項目尚未準備好。",
1142
+ status_code=409,
1143
+ )
1144
+ chunk_counts = connection.execute(
1145
+ "SELECT COUNT(*) AS total, SUM(CASE WHEN status != 'pending' "
1146
+ "THEN 1 ELSE 0 END) AS complete FROM preparation_chunks "
1147
+ "WHERE run_id = ? AND version_id = ? AND stream_index = ?",
1148
+ (run_id, version_id, stream_index),
1149
+ ).fetchone()
1150
+ if chunk_counts["total"] < 1 or chunk_counts["complete"] != chunk_counts["total"]:
1151
+ raise ProjectError(
1152
+ "preparation_incomplete",
1153
+ "逐字稿仍有尚未完成的音訊切塊。",
1154
+ status_code=409,
1155
+ )
1156
+ artifact = connection.execute(
1157
+ "SELECT project_id, kind, producer_operation_id FROM artifacts WHERE artifact_id = ?",
1158
+ (artifact_id,),
1159
+ ).fetchone()
1160
+ if (
1161
+ artifact is None
1162
+ or artifact["project_id"] != project_id
1163
+ or artifact["kind"] != "transcript"
1164
+ or artifact["producer_operation_id"] != run.operation_id
1165
+ ):
1166
+ raise ProjectError("artifact_not_found", "找不到完整逐字稿成果。", status_code=409)
1167
+ status = "no_speech_detected" if not segments else "needs_review" if needs_review else "transcribed"
1168
+ now = utc_now()
1169
+ connection.execute(
1170
+ "INSERT INTO transcription_revisions "
1171
+ "(revision_id, project_id, run_id, version_id, stream_index, "
1172
+ "artifact_id, status, language, model_json, recipe_id, "
1173
+ "source_span_json, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
1174
+ (
1175
+ revision_id,
1176
+ project_id,
1177
+ run_id,
1178
+ version_id,
1179
+ stream_index,
1180
+ artifact_id,
1181
+ status,
1182
+ language,
1183
+ model_json,
1184
+ recipe_id,
1185
+ source_json,
1186
+ now,
1187
+ ),
1188
+ )
1189
+ for ordinal, segment in enumerate(segments):
1190
+ segment_identity = (
1191
+ f"{revision_id}\0{ordinal}\0{segment.source_span.start_pts}\0"
1192
+ f"{segment.source_span.end_pts}\0{segment.text}"
1193
+ )
1194
+ segment_id = "seg_" + hashlib.sha256(segment_identity.encode("utf-8")).hexdigest()[:32]
1195
+ connection.execute(
1196
+ "INSERT INTO transcript_segments "
1197
+ "(revision_id, segment_id, start_pts, end_pts, text, confidence, ordinal) "
1198
+ "VALUES (?, ?, ?, ?, ?, ?, ?)",
1199
+ (
1200
+ revision_id,
1201
+ segment_id,
1202
+ segment.source_span.start_pts,
1203
+ segment.source_span.end_pts,
1204
+ segment.text,
1205
+ segment.confidence,
1206
+ ordinal,
1207
+ ),
1208
+ )
1209
+ item_status = PreparationItemStatus.NO_SPEECH if not segments else PreparationItemStatus.TRANSCRIBED
1210
+ connection.execute(
1211
+ "UPDATE preparation_items SET status = ?, transcript_revision_id = ?, "
1212
+ "review_required = ?, error_code = ? "
1213
+ "WHERE run_id = ? AND version_id = ? AND stream_index = ?",
1214
+ (
1215
+ item_status.value,
1216
+ revision_id,
1217
+ int(needs_review),
1218
+ "transcript_low_confidence" if needs_review else None,
1219
+ run_id,
1220
+ version_id,
1221
+ stream_index,
1222
+ ),
1223
+ )
1224
+ self._refresh_counts(connection, run_id)
1225
+ self._append_event(
1226
+ connection,
1227
+ project_id,
1228
+ run.operation_id,
1229
+ "progress",
1230
+ {
1231
+ "version_id": version_id,
1232
+ "stream_index": stream_index,
1233
+ "status": item_status.value,
1234
+ },
1235
+ now,
1236
+ )
1237
+ connection.commit()
1238
+ return revision_id
1239
+ except ProjectError:
1240
+ connection.rollback()
1241
+ raise
1242
+ except sqlite3.Error as error:
1243
+ connection.rollback()
1244
+ raise ProjectError("storage_failed", "Clipen 無法發布逐字稿。", status_code=500) from error
1245
+
1246
+ def transition(
1247
+ self,
1248
+ project_id: str,
1249
+ run_id: str,
1250
+ target: PreparationState,
1251
+ *,
1252
+ phase: str,
1253
+ error_code: str | None = None,
1254
+ ) -> PreparationRun:
1255
+ validate_project_id(project_id)
1256
+ if not re.fullmatch(r"[a-z][a-z0-9_]{0,63}", phase):
1257
+ raise ValueError("preparation phase is invalid")
1258
+ if error_code is not None and not re.fullmatch(r"[a-z][a-z0-9_]{0,63}", error_code):
1259
+ raise ValueError("preparation error code is invalid")
1260
+ if target is PreparationState.SUCCEEDED:
1261
+ raise ValueError("use publish() to complete a preparation")
1262
+ with self.projects.connect(project_id) as connection:
1263
+ try:
1264
+ connection.execute("BEGIN IMMEDIATE")
1265
+ current = self._read_run(connection, run_id)
1266
+ if current.project_id != project_id:
1267
+ raise ProjectError("preparation_not_found", "找不到這次素材分析。", status_code=404)
1268
+ if target not in _TRANSITIONS.get(current.state, set()):
1269
+ raise ProjectError(
1270
+ "preparation_state_conflict",
1271
+ "這次素材分析的狀態已經改變。",
1272
+ status_code=409,
1273
+ )
1274
+ now = utc_now()
1275
+ started = current.started_at or now
1276
+ completed = now if target in _TERMINAL_STATES else None
1277
+ connection.execute(
1278
+ "UPDATE preparation_runs SET state = ?, phase = ?, error_code = ?, "
1279
+ "started_at = ?, completed_at = ? WHERE run_id = ?",
1280
+ (target.value, phase, error_code, started, completed, run_id),
1281
+ )
1282
+ self._append_event(
1283
+ connection,
1284
+ project_id,
1285
+ current.operation_id,
1286
+ target.value,
1287
+ {"phase": phase, "error_code": error_code},
1288
+ now,
1289
+ )
1290
+ updated = self._read_run(connection, run_id)
1291
+ connection.commit()
1292
+ return updated
1293
+ except ProjectError:
1294
+ connection.rollback()
1295
+ raise
1296
+ except sqlite3.Error as error:
1297
+ connection.rollback()
1298
+ raise ProjectError("storage_failed", "Clipen 無法更新素材分析。", status_code=500) from error
1299
+
1300
+ def request_cancel(self, project_id: str, run_id: str) -> PreparationRun:
1301
+ validate_project_id(project_id)
1302
+ with self.projects.connect(project_id) as connection:
1303
+ try:
1304
+ connection.execute("BEGIN IMMEDIATE")
1305
+ current = self._read_run(connection, run_id)
1306
+ if current.project_id != project_id:
1307
+ raise ProjectError("preparation_not_found", "找不到這次素材分析。", status_code=404)
1308
+ if current.state in _TERMINAL_STATES or current.state is PreparationState.CANCELLING:
1309
+ connection.rollback()
1310
+ return current
1311
+ now = utc_now()
1312
+ if current.state is PreparationState.QUEUED:
1313
+ connection.execute(
1314
+ "UPDATE preparation_runs SET state = 'cancelled', phase = 'cancelled', "
1315
+ "started_at = ?, completed_at = ? WHERE run_id = ?",
1316
+ (now, now, run_id),
1317
+ )
1318
+ event_type = "cancelled"
1319
+ else:
1320
+ connection.execute(
1321
+ "UPDATE preparation_runs SET state = 'cancelling', phase = 'cancelling' WHERE run_id = ?",
1322
+ (run_id,),
1323
+ )
1324
+ event_type = "cancel_requested"
1325
+ self._append_event(
1326
+ connection,
1327
+ project_id,
1328
+ current.operation_id,
1329
+ event_type,
1330
+ {"phase": event_type},
1331
+ now,
1332
+ )
1333
+ updated = self._read_run(connection, run_id)
1334
+ connection.commit()
1335
+ return updated
1336
+ except ProjectError:
1337
+ connection.rollback()
1338
+ raise
1339
+ except sqlite3.Error as error:
1340
+ connection.rollback()
1341
+ raise ProjectError("storage_failed", "Clipen 無法取消素材分析。", status_code=500) from error
1342
+
1343
+ def resume_interrupted(self, project_id: str, run_id: str, request_id: object) -> tuple[PreparationRun, bool]:
1344
+ validate_project_id(project_id)
1345
+ normalized_request = validate_request_id(request_id)
1346
+ request_hash = command_digest({"run_id": run_id})
1347
+ with self.projects.connect(project_id) as connection:
1348
+ receipt = connection.execute(
1349
+ "SELECT command_type, request_hash, run_id FROM preparation_command_receipts WHERE request_id = ?",
1350
+ (normalized_request,),
1351
+ ).fetchone()
1352
+ if receipt is not None:
1353
+ if receipt["command_type"] != "resume_preparation" or receipt["request_hash"] != request_hash:
1354
+ raise ProjectError(
1355
+ "request_reused",
1356
+ "這次操作的識別資訊已用於不同內容。",
1357
+ status_code=409,
1358
+ )
1359
+ return self._read_run(connection, receipt["run_id"]), False
1360
+ scope = self.preflight(project_id)
1361
+ with self.projects.connect(project_id) as connection:
1362
+ try:
1363
+ connection.execute("BEGIN IMMEDIATE")
1364
+ receipt = connection.execute(
1365
+ "SELECT command_type, request_hash, run_id FROM preparation_command_receipts WHERE request_id = ?",
1366
+ (normalized_request,),
1367
+ ).fetchone()
1368
+ if receipt is not None:
1369
+ if receipt["command_type"] != "resume_preparation" or receipt["request_hash"] != request_hash:
1370
+ raise ProjectError(
1371
+ "request_reused",
1372
+ "這次操作的識別資訊已用於不同內容。",
1373
+ status_code=409,
1374
+ )
1375
+ replay = self._read_run(connection, receipt["run_id"])
1376
+ connection.rollback()
1377
+ return replay, False
1378
+ current = self._read_run(connection, run_id)
1379
+ if current.project_id != project_id:
1380
+ raise ProjectError("preparation_not_found", "找不到這次素材分析。", status_code=404)
1381
+ if current.state is not PreparationState.INTERRUPTED:
1382
+ raise ProjectError(
1383
+ "preparation_state_conflict",
1384
+ "只有被中斷的素材分析可以接續。",
1385
+ status_code=409,
1386
+ )
1387
+ live = connection.execute(
1388
+ "SELECT p.revision, c.run_id AS inventory_run_id FROM project p "
1389
+ "LEFT JOIN current_inventory c ON c.slot = 1 "
1390
+ "WHERE p.project_id = ?",
1391
+ (project_id,),
1392
+ ).fetchone()
1393
+ if (
1394
+ scope.scope_id != current.scope_id
1395
+ or scope.inventory_run_id != current.inventory_run_id
1396
+ or live is None
1397
+ or live["revision"] != scope.project_revision
1398
+ or live["inventory_run_id"] != scope.inventory_run_id
1399
+ ):
1400
+ raise ProjectError(
1401
+ "scope_changed",
1402
+ "素材或作品內容已改變,無法接續這次分析。",
1403
+ status_code=409,
1404
+ )
1405
+ busy = connection.execute(
1406
+ "SELECT run_id FROM preparation_runs WHERE run_id != ? "
1407
+ "AND state IN ('queued', 'running', 'cancelling') LIMIT 1",
1408
+ (run_id,),
1409
+ ).fetchone()
1410
+ if busy is not None:
1411
+ raise ProjectError(
1412
+ "preparation_busy",
1413
+ "已有一個素材分析正在進行。",
1414
+ status_code=409,
1415
+ )
1416
+ attempt_number = current.attempt_number + 1
1417
+ attempt_id = _derived_id("att", current.operation_id, str(attempt_number))
1418
+ now = utc_now()
1419
+ connection.execute(
1420
+ "UPDATE preparation_runs SET attempt_id = ?, attempt_number = ?, "
1421
+ "state = 'queued', phase = 'preparing', error_code = NULL, "
1422
+ "started_at = NULL, completed_at = NULL WHERE run_id = ?",
1423
+ (attempt_id, attempt_number, run_id),
1424
+ )
1425
+ connection.execute(
1426
+ "INSERT INTO preparation_command_receipts "
1427
+ "(request_id, command_type, request_hash, run_id, created_at) "
1428
+ "VALUES (?, 'resume_preparation', ?, ?, ?)",
1429
+ (normalized_request, request_hash, run_id, now),
1430
+ )
1431
+ self._append_event(
1432
+ connection,
1433
+ project_id,
1434
+ current.operation_id,
1435
+ "queued",
1436
+ {"phase": "preparing", "attempt_number": attempt_number},
1437
+ now,
1438
+ )
1439
+ resumed = self._read_run(connection, run_id)
1440
+ connection.commit()
1441
+ return resumed, True
1442
+ except ProjectError:
1443
+ connection.rollback()
1444
+ raise
1445
+ except sqlite3.Error as error:
1446
+ connection.rollback()
1447
+ raise ProjectError("storage_failed", "Clipen 無法接續素材分析。", status_code=500) from error
1448
+
1449
+ def settle_item(
1450
+ self,
1451
+ project_id: str,
1452
+ run_id: str,
1453
+ version_id: str,
1454
+ stream_index: int,
1455
+ status: PreparationItemStatus,
1456
+ *,
1457
+ audio_artifact_id: str | None = None,
1458
+ transcript_revision_id: str | None = None,
1459
+ error_code: str | None = None,
1460
+ checkpoint: Mapping[str, object] | None = None,
1461
+ ) -> PreparationRun:
1462
+ validate_project_id(project_id)
1463
+ if status not in {
1464
+ PreparationItemStatus.PREPARED,
1465
+ PreparationItemStatus.TRANSCRIBED,
1466
+ PreparationItemStatus.NO_SPEECH,
1467
+ PreparationItemStatus.FAILED,
1468
+ }:
1469
+ raise ValueError("item cannot settle to the requested status")
1470
+ if status is PreparationItemStatus.PREPARED and audio_artifact_id is None:
1471
+ raise ValueError("prepared item requires an audio artifact")
1472
+ if status in {PreparationItemStatus.TRANSCRIBED, PreparationItemStatus.NO_SPEECH}:
1473
+ if transcript_revision_id is None:
1474
+ raise ValueError("transcribed item requires a transcript revision")
1475
+ if status is PreparationItemStatus.FAILED and error_code is None:
1476
+ raise ValueError("failed item requires an error code")
1477
+ if error_code is not None and not re.fullmatch(r"[a-z][a-z0-9_]{0,63}", error_code):
1478
+ raise ValueError("preparation item error code is invalid")
1479
+ checkpoint_json = None if checkpoint is None else _bounded_json(checkpoint, "checkpoint")
1480
+ with self.projects.connect(project_id) as connection:
1481
+ try:
1482
+ connection.execute("BEGIN IMMEDIATE")
1483
+ run = self._read_run(connection, run_id)
1484
+ if run.project_id != project_id or run.state is not PreparationState.RUNNING:
1485
+ raise ProjectError(
1486
+ "preparation_state_conflict",
1487
+ "這次素材分析目前不能保存結果。",
1488
+ status_code=409,
1489
+ )
1490
+ item = connection.execute(
1491
+ "SELECT status, audio_artifact_id FROM preparation_items "
1492
+ "WHERE run_id = ? AND version_id = ? AND stream_index = ?",
1493
+ (run_id, version_id, stream_index),
1494
+ ).fetchone()
1495
+ if item is None:
1496
+ raise ProjectError("preparation_item_not_found", "找不到這個分析項目。", status_code=404)
1497
+ current_status = PreparationItemStatus(item["status"])
1498
+ allowed = (
1499
+ current_status is PreparationItemStatus.PENDING
1500
+ and status in {PreparationItemStatus.PREPARED, PreparationItemStatus.FAILED}
1501
+ ) or (
1502
+ current_status is PreparationItemStatus.PREPARED
1503
+ and status
1504
+ in {
1505
+ PreparationItemStatus.TRANSCRIBED,
1506
+ PreparationItemStatus.NO_SPEECH,
1507
+ PreparationItemStatus.FAILED,
1508
+ }
1509
+ )
1510
+ if not allowed:
1511
+ raise ProjectError(
1512
+ "preparation_item_conflict",
1513
+ "這個分析項目的狀態已經改變。",
1514
+ status_code=409,
1515
+ )
1516
+ retained_audio = audio_artifact_id or item["audio_artifact_id"]
1517
+ connection.execute(
1518
+ "UPDATE preparation_items SET status = ?, error_code = ?, "
1519
+ "checkpoint_json = ?, audio_artifact_id = ?, transcript_revision_id = ?, "
1520
+ "review_required = 0 "
1521
+ "WHERE run_id = ? AND version_id = ? AND stream_index = ?",
1522
+ (
1523
+ status.value,
1524
+ error_code,
1525
+ checkpoint_json,
1526
+ retained_audio,
1527
+ transcript_revision_id,
1528
+ run_id,
1529
+ version_id,
1530
+ stream_index,
1531
+ ),
1532
+ )
1533
+ self._refresh_counts(connection, run_id)
1534
+ now = utc_now()
1535
+ self._append_event(
1536
+ connection,
1537
+ project_id,
1538
+ run.operation_id,
1539
+ "progress",
1540
+ {
1541
+ "version_id": version_id,
1542
+ "stream_index": stream_index,
1543
+ "status": status.value,
1544
+ "error_code": error_code,
1545
+ },
1546
+ now,
1547
+ )
1548
+ updated = self._read_run(connection, run_id)
1549
+ connection.commit()
1550
+ return updated
1551
+ except ProjectError:
1552
+ connection.rollback()
1553
+ raise
1554
+ except sqlite3.Error as error:
1555
+ connection.rollback()
1556
+ raise ProjectError("storage_failed", "Clipen 無法保存分析進度。", status_code=500) from error
1557
+
1558
+ def publish(self, project_id: str, run_id: str) -> PreparationRun:
1559
+ validate_project_id(project_id)
1560
+ with self.projects.connect(project_id) as connection:
1561
+ try:
1562
+ connection.execute("BEGIN IMMEDIATE")
1563
+ run = self._read_run(connection, run_id)
1564
+ if run.project_id != project_id or run.state is not PreparationState.RUNNING:
1565
+ raise ProjectError(
1566
+ "preparation_state_conflict",
1567
+ "這次素材分析目前不能完成。",
1568
+ status_code=409,
1569
+ )
1570
+ incomplete = connection.execute(
1571
+ "SELECT COUNT(*) FROM preparation_items WHERE run_id = ? AND status IN ('pending', 'prepared')",
1572
+ (run_id,),
1573
+ ).fetchone()[0]
1574
+ if incomplete:
1575
+ raise ProjectError(
1576
+ "preparation_incomplete",
1577
+ "素材分析仍有尚未完成的項目。",
1578
+ status_code=409,
1579
+ )
1580
+ self._refresh_counts(connection, run_id)
1581
+ now = utc_now()
1582
+ settled = self._read_run(connection, run_id)
1583
+ analyzable = settled.counts.total - settled.counts.no_audio
1584
+ if (
1585
+ analyzable > 0
1586
+ and settled.counts.transcribed == 0
1587
+ and settled.counts.no_speech == 0
1588
+ and settled.counts.issues == analyzable
1589
+ ):
1590
+ codes = [
1591
+ row["error_code"]
1592
+ for row in connection.execute(
1593
+ "SELECT DISTINCT error_code FROM preparation_items "
1594
+ "WHERE run_id = ? AND status = 'failed' "
1595
+ "AND error_code IS NOT NULL",
1596
+ (run_id,),
1597
+ ).fetchall()
1598
+ ]
1599
+ error_code = codes[0] if len(codes) == 1 else "preparation_all_items_failed"
1600
+ connection.execute(
1601
+ "UPDATE preparation_runs SET state = 'failed', phase = 'failed', "
1602
+ "error_code = ?, completed_at = ? WHERE run_id = ?",
1603
+ (error_code, now, run_id),
1604
+ )
1605
+ self._append_event(
1606
+ connection,
1607
+ project_id,
1608
+ run.operation_id,
1609
+ "failed",
1610
+ {"phase": "failed", "error_code": error_code},
1611
+ now,
1612
+ )
1613
+ failed = self._read_run(connection, run_id)
1614
+ connection.commit()
1615
+ return failed
1616
+ connection.execute(
1617
+ "UPDATE preparation_runs SET state = 'succeeded', phase = 'completed', "
1618
+ "error_code = NULL, completed_at = ? WHERE run_id = ?",
1619
+ (now, run_id),
1620
+ )
1621
+ connection.execute(
1622
+ "INSERT INTO current_preparation (slot, run_id) VALUES (1, ?) "
1623
+ "ON CONFLICT(slot) DO UPDATE SET run_id = excluded.run_id",
1624
+ (run_id,),
1625
+ )
1626
+ self._append_event(
1627
+ connection,
1628
+ project_id,
1629
+ run.operation_id,
1630
+ "succeeded",
1631
+ {"phase": "completed"},
1632
+ now,
1633
+ )
1634
+ published = self._read_run(connection, run_id)
1635
+ connection.commit()
1636
+ return published
1637
+ except ProjectError:
1638
+ connection.rollback()
1639
+ raise
1640
+ except sqlite3.Error as error:
1641
+ connection.rollback()
1642
+ raise ProjectError("storage_failed", "Clipen 無法完成素材分析。", status_code=500) from error
1643
+
1644
+ def interrupt_incomplete(self, project_id: str) -> int:
1645
+ validate_project_id(project_id)
1646
+ with self.projects.connect(project_id) as connection:
1647
+ try:
1648
+ connection.execute("BEGIN IMMEDIATE")
1649
+ rows = connection.execute(
1650
+ "SELECT run_id, operation_id, started_at FROM preparation_runs "
1651
+ "WHERE state IN ('queued', 'running', 'cancelling')"
1652
+ ).fetchall()
1653
+ now = utc_now()
1654
+ for row in rows:
1655
+ connection.execute(
1656
+ "UPDATE preparation_runs SET state = 'interrupted', "
1657
+ "phase = 'interrupted', error_code = 'controller_restarted', "
1658
+ "started_at = ?, completed_at = ? WHERE run_id = ?",
1659
+ (row["started_at"] or now, now, row["run_id"]),
1660
+ )
1661
+ self._append_event(
1662
+ connection,
1663
+ project_id,
1664
+ row["operation_id"],
1665
+ "interrupted",
1666
+ {"phase": "interrupted", "error_code": "controller_restarted"},
1667
+ now,
1668
+ )
1669
+ connection.commit()
1670
+ return len(rows)
1671
+ except sqlite3.Error as error:
1672
+ connection.rollback()
1673
+ raise ProjectError("storage_failed", "Clipen 無法恢復素材分析狀態。", status_code=500) from error
1674
+
1675
+ @staticmethod
1676
+ def _refresh_counts(connection: sqlite3.Connection, run_id: str) -> None:
1677
+ counts = connection.execute(
1678
+ "SELECT COUNT(*) AS total, "
1679
+ "SUM(CASE WHEN status IN ('prepared', 'transcribed', 'no_speech') "
1680
+ "THEN 1 ELSE 0 END) AS prepared, "
1681
+ "SUM(CASE WHEN status = 'transcribed' AND review_required = 0 "
1682
+ "THEN 1 ELSE 0 END) AS transcribed, "
1683
+ "SUM(CASE WHEN status = 'no_audio' THEN 1 ELSE 0 END) AS no_audio, "
1684
+ "SUM(CASE WHEN status = 'no_speech' THEN 1 ELSE 0 END) AS no_speech, "
1685
+ "SUM(CASE WHEN status = 'failed' OR review_required = 1 "
1686
+ "THEN 1 ELSE 0 END) AS issues "
1687
+ "FROM preparation_items WHERE run_id = ?",
1688
+ (run_id,),
1689
+ ).fetchone()
1690
+ connection.execute(
1691
+ "UPDATE preparation_runs SET total_count = ?, prepared_count = ?, "
1692
+ "transcribed_count = ?, no_audio_count = ?, no_speech_count = ?, "
1693
+ "issue_count = ? WHERE run_id = ?",
1694
+ (
1695
+ counts["total"],
1696
+ counts["prepared"] or 0,
1697
+ counts["transcribed"] or 0,
1698
+ counts["no_audio"] or 0,
1699
+ counts["no_speech"] or 0,
1700
+ counts["issues"] or 0,
1701
+ run_id,
1702
+ ),
1703
+ )
1704
+
1705
+ @staticmethod
1706
+ def _append_event(
1707
+ connection: sqlite3.Connection,
1708
+ project_id: str,
1709
+ operation_id: str,
1710
+ event_type: str,
1711
+ payload: Mapping[str, object],
1712
+ created_at: str,
1713
+ ) -> None:
1714
+ seed = json.dumps(
1715
+ {
1716
+ "operation": operation_id,
1717
+ "type": event_type,
1718
+ "payload": payload,
1719
+ "created_at": created_at,
1720
+ },
1721
+ sort_keys=True,
1722
+ separators=(",", ":"),
1723
+ ).encode()
1724
+ event_id = "evt_" + hashlib.sha256(seed).hexdigest()[:32]
1725
+ connection.execute(
1726
+ "INSERT INTO operation_events "
1727
+ "(event_id, project_id, operation_id, event_type, payload_json, created_at) "
1728
+ "VALUES (?, ?, ?, ?, ?, ?)",
1729
+ (
1730
+ event_id,
1731
+ project_id,
1732
+ operation_id,
1733
+ event_type,
1734
+ json.dumps(payload, sort_keys=True, separators=(",", ":")),
1735
+ created_at,
1736
+ ),
1737
+ )
1738
+
1739
+ @staticmethod
1740
+ def _read_run(connection: sqlite3.Connection, run_id: object) -> PreparationRun:
1741
+ if not isinstance(run_id, str) or re.fullmatch(r"prep_[0-9a-f]{32}", run_id) is None:
1742
+ raise ProjectError("preparation_not_found", "找不到這次素材分析。", status_code=404)
1743
+ row = connection.execute(
1744
+ "SELECT run_id, project_id, project_revision, inventory_run_id, scope_id, "
1745
+ "operation_id, attempt_id, attempt_number, input_fingerprint, state, phase, "
1746
+ "total_count, prepared_count, transcribed_count, no_audio_count, "
1747
+ "no_speech_count, issue_count, error_code, created_at, started_at, completed_at "
1748
+ "FROM preparation_runs WHERE run_id = ?",
1749
+ (run_id,),
1750
+ ).fetchone()
1751
+ if row is None:
1752
+ raise ProjectError("preparation_not_found", "找不到這次素材分析。", status_code=404)
1753
+ try:
1754
+ return PreparationRun(
1755
+ row["run_id"],
1756
+ row["project_id"],
1757
+ row["project_revision"],
1758
+ row["inventory_run_id"],
1759
+ row["scope_id"],
1760
+ row["operation_id"],
1761
+ row["attempt_id"],
1762
+ row["attempt_number"],
1763
+ row["input_fingerprint"],
1764
+ PreparationState(row["state"]),
1765
+ row["phase"],
1766
+ PreparationCounts(
1767
+ row["total_count"],
1768
+ row["prepared_count"],
1769
+ row["transcribed_count"],
1770
+ row["no_audio_count"],
1771
+ row["no_speech_count"],
1772
+ row["issue_count"],
1773
+ ),
1774
+ row["error_code"],
1775
+ row["created_at"],
1776
+ row["started_at"],
1777
+ row["completed_at"],
1778
+ )
1779
+ except (TypeError, ValueError) as error:
1780
+ raise ProjectError("storage_corrupt", "Clipen 無法讀取素材分析。", status_code=500) from error
1781
+
1782
+ @staticmethod
1783
+ def _read_chunk(row: sqlite3.Row) -> PreparationChunk:
1784
+ try:
1785
+ raw_span = json.loads(row["source_span_json"])
1786
+ raw_result = None if row["result_json"] is None else json.loads(row["result_json"])
1787
+ return PreparationChunk(
1788
+ row["ordinal"],
1789
+ row["start_sample"],
1790
+ row["end_sample"],
1791
+ SourceSpan.from_storage(raw_span),
1792
+ PreparationChunkStatus(row["status"]),
1793
+ row["transcript_artifact_id"],
1794
+ None if raw_result is None else TranscriptionResult.from_storage(raw_result),
1795
+ )
1796
+ except (json.JSONDecodeError, KeyError, TypeError, ValueError) as error:
1797
+ raise ProjectError("storage_corrupt", "Clipen 無法讀取逐字稿切塊。", status_code=500) from error
1798
+
1799
+
1800
+ def _source_span(version_id: str, stream_index: int, details: Mapping[str, Any]) -> SourceSpan:
1801
+ time_base = details["time_base"]
1802
+ start_pts = details["start_pts"]
1803
+ duration = details["duration_ts"]
1804
+ if not isinstance(time_base, str) or "/" not in time_base:
1805
+ raise ValueError("audio time base is missing")
1806
+ numerator, denominator = (int(part) for part in time_base.split("/", 1))
1807
+ start = int(str(start_pts))
1808
+ end = start + int(str(duration))
1809
+ return SourceSpan(
1810
+ version_id,
1811
+ stream_index,
1812
+ str(start),
1813
+ str(end),
1814
+ Rational(numerator, denominator),
1815
+ )
1816
+
1817
+
1818
+ def _verify_inventory_root(root: InventoryRoot) -> None:
1819
+ flags = os.O_RDONLY | getattr(os, "O_DIRECTORY", 0) | getattr(os, "O_NOFOLLOW", 0)
1820
+ try:
1821
+ descriptor = os.open(root.canonical_path, flags)
1822
+ except OSError as error:
1823
+ raise ProjectError("root_unavailable", "素材磁碟目前無法使用。", status_code=409) from error
1824
+ try:
1825
+ if os.fstat(descriptor).st_ino != root.inode:
1826
+ raise ProjectError("root_changed", "素材位置已改變,請重新檢查素材。", status_code=409)
1827
+ finally:
1828
+ os.close(descriptor)
1829
+
1830
+
1831
+ def _derived_id(prefix: str, *values: str) -> str:
1832
+ digest = hashlib.sha256("\0".join((prefix, *values)).encode()).hexdigest()[:32]
1833
+ return f"{prefix}_{digest}"
1834
+
1835
+
1836
+ def _bounded_json(value: Mapping[str, object], label: str) -> str:
1837
+ if not isinstance(value, Mapping):
1838
+ raise ValueError(f"{label} must be an object")
1839
+ return _encoded_json(value, label, 64 * 1024)
1840
+
1841
+
1842
+ def _encoded_json(value: object, label: str, maximum_bytes: int) -> str:
1843
+ try:
1844
+ encoded = json.dumps(
1845
+ value,
1846
+ ensure_ascii=False,
1847
+ sort_keys=True,
1848
+ separators=(",", ":"),
1849
+ )
1850
+ except (TypeError, ValueError) as error:
1851
+ raise ValueError(f"{label} is invalid") from error
1852
+ if len(encoded.encode("utf-8")) > maximum_bytes:
1853
+ raise ValueError(f"{label} is too large")
1854
+ return encoded
1855
+
1856
+
1857
+ def math_ceil_fraction(value: Fraction) -> int:
1858
+ return -(-value.numerator // value.denominator)
1859
+
1860
+
1861
+ def _fraction_decimal(value: Fraction) -> str:
1862
+ if value.denominator == 1:
1863
+ return str(value.numerator)
1864
+ return format(value.numerator / value.denominator, ".6f").rstrip("0").rstrip(".")