@clipen/clipen-cli 0.0.0-stage → 1.0.0

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