@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,360 @@
1
+ """Validated values for durable, source-read-only media inventories."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from enum import Enum
7
+ import hashlib
8
+ import json
9
+ from pathlib import PurePosixPath
10
+ import re
11
+ from typing import Mapping, Any
12
+
13
+ from clipen.projects.models import DirectoryRole, ProjectError, validate_project_id
14
+
15
+
16
+ _RUN_ID = re.compile(r"inv_[0-9a-f]{32}\Z")
17
+ _SHA256 = re.compile(r"[0-9a-f]{64}\Z")
18
+ _CODE = re.compile(r"[a-z][a-z0-9_]{0,63}\Z")
19
+
20
+
21
+ class InventoryState(str, Enum):
22
+ QUEUED = "queued"
23
+ RUNNING = "running"
24
+ CANCELLING = "cancelling"
25
+ SUCCEEDED = "succeeded"
26
+ FAILED = "failed"
27
+ CANCELLED = "cancelled"
28
+ INTERRUPTED = "interrupted"
29
+
30
+
31
+ class AssetKind(str, Enum):
32
+ VIDEO = "video"
33
+ AUDIO = "audio"
34
+ IMAGE = "image"
35
+ UNKNOWN = "unknown"
36
+
37
+
38
+ class ItemStatus(str, Enum):
39
+ USABLE = "usable"
40
+ NEEDS_ATTENTION = "needs_attention"
41
+ IGNORED = "ignored"
42
+
43
+
44
+ class ProbeStatus(str, Enum):
45
+ PENDING = "pending"
46
+ READY = "ready"
47
+ UNSUPPORTED = "unsupported"
48
+ UNREADABLE = "unreadable"
49
+ TIMEOUT = "timeout"
50
+ CHANGED = "changed"
51
+ INTERNAL_ERROR = "internal_error"
52
+
53
+
54
+ @dataclass(frozen=True)
55
+ class InventoryCounts:
56
+ discovered: int = 0
57
+ probed: int = 0
58
+ usable: int = 0
59
+ issues: int = 0
60
+ ignored: int = 0
61
+
62
+ def __post_init__(self) -> None:
63
+ values = (self.discovered, self.probed, self.usable, self.issues, self.ignored)
64
+ if any(
65
+ isinstance(value, bool) or not isinstance(value, int) or value < 0
66
+ for value in values
67
+ ):
68
+ raise ValueError("inventory counts must be non-negative integers")
69
+ if self.usable + self.issues + self.ignored > self.discovered:
70
+ raise ValueError("inventory categorized counts exceed discovered count")
71
+ if self.probed > self.discovered:
72
+ raise ValueError("inventory probed count exceeds discovered count")
73
+
74
+ def to_public(self) -> dict[str, int]:
75
+ return {
76
+ "discovered": self.discovered,
77
+ "probed": self.probed,
78
+ "usable": self.usable,
79
+ "issues": self.issues,
80
+ "ignored": self.ignored,
81
+ }
82
+
83
+
84
+ @dataclass(frozen=True)
85
+ class InventoryRoot:
86
+ role: DirectoryRole
87
+ canonical_path: str
88
+ device: int
89
+ inode: int
90
+ saved_at: str
91
+
92
+ def __post_init__(self) -> None:
93
+ if not self.canonical_path.startswith("/") or "\x00" in self.canonical_path:
94
+ raise ValueError("inventory root path must be absolute")
95
+ if self.device < 0 or self.inode < 0 or not self.saved_at:
96
+ raise ValueError("inventory root identity is invalid")
97
+
98
+ def to_storage(self) -> dict[str, object]:
99
+ return {
100
+ "role": self.role.value,
101
+ "canonical_path": self.canonical_path,
102
+ "device": self.device,
103
+ "inode": self.inode,
104
+ "saved_at": self.saved_at,
105
+ }
106
+
107
+ @classmethod
108
+ def from_storage(cls, value: Mapping[str, Any]) -> "InventoryRoot":
109
+ return cls(
110
+ DirectoryRole(value["role"]),
111
+ str(value["canonical_path"]),
112
+ int(value["device"]),
113
+ int(value["inode"]),
114
+ str(value["saved_at"]),
115
+ )
116
+
117
+
118
+ @dataclass(frozen=True)
119
+ class InventoryRun:
120
+ run_id: str
121
+ project_id: str
122
+ project_revision: int
123
+ input_fingerprint: str
124
+ roots: tuple[InventoryRoot, ...]
125
+ state: InventoryState
126
+ phase: str
127
+ counts: InventoryCounts
128
+ error_code: str | None
129
+ created_at: str
130
+ started_at: str | None = None
131
+ completed_at: str | None = None
132
+
133
+ def __post_init__(self) -> None:
134
+ validate_run_id(self.run_id)
135
+ validate_project_id(self.project_id)
136
+ if self.project_revision < 1 or not _SHA256.fullmatch(self.input_fingerprint):
137
+ raise ValueError("inventory run identity is invalid")
138
+ if not self.roots or len({root.role for root in self.roots}) != len(self.roots):
139
+ raise ValueError("inventory roots must be non-empty and unique")
140
+ if DirectoryRole.SOURCE not in {root.role for root in self.roots}:
141
+ raise ValueError("inventory requires a source root")
142
+ if not _CODE.fullmatch(self.phase) or not self.created_at:
143
+ raise ValueError("inventory lifecycle metadata is invalid")
144
+ if self.error_code is not None and not _CODE.fullmatch(self.error_code):
145
+ raise ValueError("inventory error code is invalid")
146
+ terminal = self.state in {
147
+ InventoryState.SUCCEEDED,
148
+ InventoryState.FAILED,
149
+ InventoryState.CANCELLED,
150
+ InventoryState.INTERRUPTED,
151
+ }
152
+ if terminal != (self.completed_at is not None):
153
+ raise ValueError("inventory completion timestamp does not match state")
154
+ if self.state is not InventoryState.QUEUED and self.started_at is None:
155
+ raise ValueError("started inventory state requires started_at")
156
+
157
+ def to_public(self) -> dict[str, object]:
158
+ return {
159
+ "run_id": self.run_id,
160
+ "project_revision": self.project_revision,
161
+ "roles": [root.role.value for root in self.roots],
162
+ "state": self.state.value,
163
+ "phase": self.phase,
164
+ "counts": self.counts.to_public(),
165
+ "error_code": self.error_code,
166
+ "created_at": self.created_at,
167
+ "started_at": self.started_at,
168
+ "completed_at": self.completed_at,
169
+ }
170
+
171
+
172
+ @dataclass(frozen=True)
173
+ class MediaStream:
174
+ stream_index: int
175
+ kind: str
176
+ codec: str
177
+ details: Mapping[str, object]
178
+
179
+ def __post_init__(self) -> None:
180
+ if self.stream_index < 0 or self.kind not in {"video", "audio"}:
181
+ raise ValueError("media stream identity is invalid")
182
+ if not self.codec or len(self.codec) > 80:
183
+ raise ValueError("media stream codec is invalid")
184
+ encoded = json.dumps(self.details, ensure_ascii=False, separators=(",", ":"))
185
+ if len(encoded.encode("utf-8")) > 16_384:
186
+ raise ValueError("media stream details are too large")
187
+
188
+
189
+ @dataclass(frozen=True)
190
+ class AssetCandidate:
191
+ role: DirectoryRole
192
+ relative_path: str
193
+ kind: AssetKind
194
+ status: ItemStatus
195
+ issue_code: str | None
196
+ size_bytes: int | None
197
+ mtime_ns: int | None
198
+ fingerprint: str | None
199
+ probe_status: ProbeStatus | None
200
+ probe: Mapping[str, object] | None = None
201
+ streams: tuple[MediaStream, ...] = ()
202
+
203
+ def __post_init__(self) -> None:
204
+ validate_relative_path(self.relative_path)
205
+ if self.issue_code is not None and not _CODE.fullmatch(self.issue_code):
206
+ raise ValueError("asset issue code is invalid")
207
+ version_values = (self.size_bytes, self.mtime_ns, self.fingerprint, self.probe_status)
208
+ has_version = any(value is not None for value in version_values)
209
+ if has_version and any(value is None for value in version_values):
210
+ raise ValueError("asset version fields must be provided together")
211
+ if self.size_bytes is not None and self.size_bytes < 0:
212
+ raise ValueError("asset size must be non-negative")
213
+ if self.mtime_ns is not None and self.mtime_ns < 0:
214
+ raise ValueError("asset mtime must be non-negative")
215
+ if self.fingerprint is not None and not _SHA256.fullmatch(self.fingerprint):
216
+ raise ValueError("asset fingerprint is invalid")
217
+ if self.probe is not None:
218
+ if not has_version:
219
+ raise ValueError("asset probe metadata requires a version")
220
+ encoded = json.dumps(self.probe, ensure_ascii=False, separators=(",", ":"))
221
+ if len(encoded.encode("utf-8")) > 256_000:
222
+ raise ValueError("asset probe metadata is too large")
223
+ if self.streams and self.probe_status is not ProbeStatus.READY:
224
+ raise ValueError("streams require a ready probe")
225
+ indices = [stream.stream_index for stream in self.streams]
226
+ if len(indices) != len(set(indices)):
227
+ raise ValueError("media stream indices must be unique")
228
+ if self.status is ItemStatus.USABLE:
229
+ if self.probe_status is not ProbeStatus.READY or self.issue_code is not None:
230
+ raise ValueError("usable assets require a ready probe without an issue")
231
+ elif self.issue_code is None:
232
+ raise ValueError("non-usable assets require an issue code")
233
+
234
+ @property
235
+ def display_name(self) -> str:
236
+ return PurePosixPath(self.relative_path).name
237
+
238
+ def asset_id(self, project_id: str) -> str:
239
+ validate_project_id(project_id)
240
+ value = f"clipen-asset:v1:{project_id}:{self.role.value}:{self.relative_path}"
241
+ return "ast_" + hashlib.sha256(value.encode("utf-8")).hexdigest()[:32]
242
+
243
+ def version_id(self, project_id: str) -> str | None:
244
+ if self.fingerprint is None:
245
+ return None
246
+ value = (
247
+ f"clipen-version:v1:{self.asset_id(project_id)}:{self.size_bytes}:"
248
+ f"{self.mtime_ns}:{self.fingerprint}"
249
+ )
250
+ return "av_" + hashlib.sha256(value.encode("utf-8")).hexdigest()[:32]
251
+
252
+
253
+ @dataclass(frozen=True)
254
+ class InventoryItem:
255
+ asset_id: str
256
+ role: DirectoryRole
257
+ relative_path: str
258
+ display_name: str
259
+ kind: AssetKind
260
+ status: ItemStatus
261
+ issue_code: str | None
262
+ size_bytes: int | None
263
+ probe_status: ProbeStatus | None
264
+ probe: Mapping[str, object] | None = None
265
+ streams: tuple[MediaStream, ...] = ()
266
+
267
+ def __post_init__(self) -> None:
268
+ if not re.fullmatch(r"ast_[0-9a-f]{32}", self.asset_id):
269
+ raise ValueError("inventory item identity is invalid")
270
+ validate_relative_path(self.relative_path)
271
+ if self.display_name != PurePosixPath(self.relative_path).name:
272
+ raise ValueError("inventory item display name is invalid")
273
+ if self.issue_code is not None and not _CODE.fullmatch(self.issue_code):
274
+ raise ValueError("inventory item issue code is invalid")
275
+ if self.size_bytes is not None and self.size_bytes < 0:
276
+ raise ValueError("inventory item size is invalid")
277
+ if self.status is ItemStatus.USABLE and self.probe_status is not ProbeStatus.READY:
278
+ raise ValueError("usable inventory item must have a ready probe")
279
+ if self.status is not ItemStatus.USABLE and self.issue_code is None:
280
+ raise ValueError("non-usable inventory item requires an issue")
281
+ if self.probe is not None:
282
+ encoded = json.dumps(self.probe, ensure_ascii=False, separators=(",", ":"))
283
+ if len(encoded.encode("utf-8")) > 256_000:
284
+ raise ValueError("inventory item probe metadata is too large")
285
+ if self.streams and self.probe_status is not ProbeStatus.READY:
286
+ raise ValueError("inventory item streams require a ready probe")
287
+
288
+ def to_public(self) -> dict[str, object]:
289
+ return {
290
+ "asset_id": self.asset_id,
291
+ "role": self.role.value,
292
+ "relative_path": self.relative_path,
293
+ "display_name": self.display_name,
294
+ "kind": self.kind.value,
295
+ "status": self.status.value,
296
+ "issue_code": self.issue_code,
297
+ "size_bytes": self.size_bytes,
298
+ "probe_status": None if self.probe_status is None else self.probe_status.value,
299
+ "probe": self.probe,
300
+ "streams": [
301
+ {
302
+ "stream_index": stream.stream_index,
303
+ "kind": stream.kind,
304
+ "codec": stream.codec,
305
+ "details": stream.details,
306
+ }
307
+ for stream in self.streams
308
+ ],
309
+ }
310
+
311
+
312
+ @dataclass(frozen=True)
313
+ class InventoryPage:
314
+ items: tuple[InventoryItem, ...]
315
+ total: int
316
+ offset: int
317
+ limit: int
318
+
319
+ def __post_init__(self) -> None:
320
+ if self.total < 0 or self.offset < 0 or not 1 <= self.limit <= 200:
321
+ raise ValueError("inventory page bounds are invalid")
322
+ if len(self.items) > self.limit:
323
+ raise ValueError("inventory page contents are invalid")
324
+
325
+ def to_public(self) -> dict[str, object]:
326
+ next_offset = self.offset + len(self.items)
327
+ return {
328
+ "items": [item.to_public() for item in self.items],
329
+ "total": self.total,
330
+ "offset": self.offset,
331
+ "limit": self.limit,
332
+ "next_offset": next_offset if next_offset < self.total else None,
333
+ }
334
+
335
+
336
+ def validate_run_id(value: object) -> str:
337
+ if not isinstance(value, str) or _RUN_ID.fullmatch(value) is None:
338
+ raise ProjectError("inventory_not_found", "找不到這次素材檢查。", status_code=404)
339
+ return value
340
+
341
+
342
+ def validate_relative_path(value: object) -> str:
343
+ if not isinstance(value, str) or not value or len(value.encode("utf-8")) > 4096:
344
+ raise ValueError("asset relative path is invalid")
345
+ if "\x00" in value or "\\" in value:
346
+ raise ValueError("asset relative path is invalid")
347
+ path = PurePosixPath(value)
348
+ if (
349
+ path.is_absolute()
350
+ or path.as_posix() != value
351
+ or any(part in {"", ".", ".."} for part in path.parts)
352
+ ):
353
+ raise ValueError("asset relative path is unsafe")
354
+ return value
355
+
356
+
357
+ def make_run_id(project_id: str, request_id: str) -> str:
358
+ validate_project_id(project_id)
359
+ value = f"clipen-inventory:v1:{project_id}:{request_id}"
360
+ return "inv_" + hashlib.sha256(value.encode("utf-8")).hexdigest()[:32]
@@ -0,0 +1,147 @@
1
+ """Read-only, range-capable access to user-authorized source media."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ import json
7
+ import mimetypes
8
+ import os
9
+ from pathlib import Path, PurePosixPath
10
+ import re
11
+ import sqlite3
12
+ from typing import Iterator
13
+
14
+ from clipen.projects import DirectoryRole, ProjectError, ProjectRepository
15
+ from clipen.projects.models import validate_project_id
16
+
17
+ from .discovery import DiscoveryError, open_file_beneath
18
+ from .models import InventoryRoot
19
+
20
+
21
+ _VERSION_ID = re.compile(r"av_[0-9a-f]{32}\Z")
22
+ _VIDEO_TYPES = {".mp4": "video/mp4", ".m4v": "video/mp4", ".mov": "video/quicktime"}
23
+ _AUDIO_TYPES = {".m4a": "audio/mp4", ".mp3": "audio/mpeg", ".wav": "audio/wav", ".aac": "audio/aac"}
24
+
25
+
26
+ @dataclass
27
+ class MediaPreview:
28
+ descriptor: int
29
+ size: int
30
+ media_type: str
31
+ audio_stream_indices: tuple[int, ...] = ()
32
+ video_stream_indices: tuple[int, ...] = ()
33
+
34
+ def chunks(self, start: int, end: int, chunk_size: int = 1024 * 1024) -> Iterator[bytes]:
35
+ position = start
36
+ try:
37
+ while position <= end:
38
+ chunk = os.pread(self.descriptor, min(chunk_size, end - position + 1), position)
39
+ if not chunk:
40
+ break
41
+ position += len(chunk)
42
+ yield chunk
43
+ finally:
44
+ os.close(self.descriptor)
45
+
46
+ def close(self) -> None:
47
+ os.close(self.descriptor)
48
+
49
+
50
+ class MediaPreviewRepository:
51
+ def __init__(self, projects: ProjectRepository) -> None:
52
+ self.projects = projects
53
+
54
+ def locate(self, project_id: str, version_id: str) -> tuple[Path, dict[int, dict]]:
55
+ """The unchanged source file on disk and its probed streams, for handing to another editor."""
56
+ self.open(project_id, version_id).close()
57
+ with self.projects.connect(project_id) as database:
58
+ row = database.execute(
59
+ "SELECT assets.relative_path,directories.canonical_path FROM asset_versions AS versions "
60
+ "JOIN assets ON assets.asset_id=versions.asset_id "
61
+ "JOIN project_directories AS directories ON directories.role=assets.role "
62
+ "WHERE versions.version_id=? AND assets.project_id=?",
63
+ (version_id, project_id),
64
+ ).fetchone()
65
+ streams = database.execute(
66
+ "SELECT stream_index,kind,details_json FROM media_streams WHERE version_id=?",
67
+ (version_id,),
68
+ ).fetchall()
69
+ path = Path(row["canonical_path"]).joinpath(*PurePosixPath(row["relative_path"]).parts)
70
+ return path, {
71
+ stream["stream_index"]: {**json.loads(stream["details_json"]), "kind": stream["kind"]}
72
+ for stream in streams
73
+ }
74
+
75
+ def open(self, project_id: str, version_id: str) -> MediaPreview:
76
+ validate_project_id(project_id)
77
+ if not isinstance(version_id, str) or _VERSION_ID.fullmatch(version_id) is None:
78
+ raise ProjectError("media_not_found", "找不到這個素材。", status_code=404)
79
+ try:
80
+ with self.projects.connect(project_id) as database:
81
+ row = database.execute(
82
+ "SELECT assets.role,assets.relative_path,versions.size_bytes,versions.mtime_ns,"
83
+ "directories.canonical_path,directories.device,directories.inode,directories.saved_at "
84
+ "FROM asset_versions AS versions "
85
+ "JOIN assets ON assets.asset_id=versions.asset_id "
86
+ "JOIN project_directories AS directories ON directories.role=assets.role "
87
+ "WHERE versions.version_id=? AND assets.project_id=?",
88
+ (version_id, project_id),
89
+ ).fetchone()
90
+ streams = database.execute(
91
+ "SELECT stream_index,kind,details_json FROM media_streams "
92
+ "WHERE version_id=? ORDER BY stream_index",
93
+ (version_id,),
94
+ ).fetchall()
95
+ if row is None:
96
+ raise ProjectError("media_not_found", "找不到這個素材。", status_code=404)
97
+ audio_stream_indices = tuple(
98
+ stream["stream_index"] for stream in streams if stream["kind"] == "audio"
99
+ )
100
+ video_streams = [stream for stream in streams if stream["kind"] == "video"]
101
+ primary_video_streams = tuple(
102
+ stream["stream_index"]
103
+ for stream in video_streams
104
+ if not json.loads(stream["details_json"]).get("attached_pic", False)
105
+ )
106
+ video_stream_indices = primary_video_streams or tuple(
107
+ stream["stream_index"] for stream in video_streams
108
+ )
109
+ root = InventoryRoot(
110
+ DirectoryRole(row["role"]), row["canonical_path"], row["device"],
111
+ row["inode"], row["saved_at"],
112
+ )
113
+ descriptor = open_file_beneath(root, row["relative_path"])
114
+ details = os.fstat(descriptor)
115
+ if details.st_size != row["size_bytes"] or details.st_mtime_ns != row["mtime_ns"]:
116
+ os.close(descriptor)
117
+ raise ProjectError(
118
+ "media_changed", "素材已變更,請重新檢查素材。", status_code=409
119
+ )
120
+ suffix = PurePosixPath(row["relative_path"]).suffix.lower()
121
+ media_type = _VIDEO_TYPES.get(suffix) or _AUDIO_TYPES.get(suffix)
122
+ if media_type is None:
123
+ media_type = mimetypes.guess_type(row["relative_path"])[0]
124
+ if media_type is None or not media_type.startswith(("video/", "audio/")):
125
+ os.close(descriptor)
126
+ raise ProjectError(
127
+ "media_preview_unsupported",
128
+ "這個素材無法在瀏覽器中直接播放。",
129
+ status_code=415,
130
+ )
131
+ return MediaPreview(
132
+ descriptor,
133
+ details.st_size,
134
+ media_type,
135
+ audio_stream_indices,
136
+ video_stream_indices,
137
+ )
138
+ except ProjectError:
139
+ raise
140
+ except DiscoveryError as error:
141
+ raise ProjectError(
142
+ "media_offline", "目前無法讀取素材,請確認外接硬碟已連接。", status_code=409
143
+ ) from error
144
+ except (json.JSONDecodeError, OSError, sqlite3.Error, TypeError, ValueError) as error:
145
+ raise ProjectError(
146
+ "media_unavailable", "Clipen 無法安全開啟這個素材。", status_code=500
147
+ ) from error