@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,143 @@
1
+ """Small, dependency-free visual fingerprints for Clipen-generated PNG previews."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from pathlib import Path
7
+ import struct
8
+ import zlib
9
+
10
+
11
+ _PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"
12
+ _GRID_SIZE = 8
13
+
14
+
15
+ @dataclass(frozen=True, slots=True)
16
+ class VisualFingerprint:
17
+ cells: tuple[int, ...]
18
+ mean_luma: int
19
+
20
+ def is_similar_to(self, other: "VisualFingerprint") -> bool:
21
+ if len(self.cells) != len(other.cells):
22
+ return False
23
+ mean_delta = abs(self.mean_luma - other.mean_luma) / 255
24
+ cell_delta = sum(abs(a - b) for a, b in zip(self.cells, other.cells)) / (
25
+ len(self.cells) * 255
26
+ )
27
+ return mean_delta <= 0.10 and cell_delta <= 0.085
28
+
29
+
30
+ def fingerprint_png(path: Path) -> VisualFingerprint:
31
+ """Fingerprint an RGB8 PNG emitted by Clipen's controlled FFmpeg pipeline."""
32
+
33
+ width, height, pixels = _decode_rgb8_png(path.read_bytes())
34
+ cells = []
35
+ for grid_y in range(_GRID_SIZE):
36
+ y0 = grid_y * height // _GRID_SIZE
37
+ y1 = max(y0 + 1, (grid_y + 1) * height // _GRID_SIZE)
38
+ for grid_x in range(_GRID_SIZE):
39
+ x0 = grid_x * width // _GRID_SIZE
40
+ x1 = max(x0 + 1, (grid_x + 1) * width // _GRID_SIZE)
41
+ total = count = 0
42
+ for y in range(y0, y1):
43
+ row = y * width * 3
44
+ for x in range(x0, x1):
45
+ offset = row + x * 3
46
+ red, green, blue = pixels[offset : offset + 3]
47
+ total += (77 * red + 150 * green + 29 * blue) >> 8
48
+ count += 1
49
+ cells.append(round(total / count))
50
+ return VisualFingerprint(tuple(cells), round(sum(cells) / len(cells)))
51
+
52
+
53
+ def _decode_rgb8_png(data: bytes) -> tuple[int, int, bytes]:
54
+ if not data.startswith(_PNG_SIGNATURE):
55
+ raise ValueError("preview is not a PNG")
56
+ width = height = None
57
+ compressed = bytearray()
58
+ position = len(_PNG_SIGNATURE)
59
+ while position + 12 <= len(data):
60
+ length = struct.unpack(">I", data[position : position + 4])[0]
61
+ kind = data[position + 4 : position + 8]
62
+ end = position + 12 + length
63
+ if end > len(data):
64
+ raise ValueError("PNG chunk is truncated")
65
+ payload = data[position + 8 : position + 8 + length]
66
+ if kind == b"IHDR":
67
+ if len(payload) != 13:
68
+ raise ValueError("preview PNG header is invalid")
69
+ width, height, depth, color, compression, filtering, interlace = struct.unpack(
70
+ ">IIBBBBB", payload
71
+ )
72
+ if (
73
+ not width
74
+ or not height
75
+ or width > 512
76
+ or height > 512
77
+ or depth != 8
78
+ or color != 2
79
+ or compression
80
+ or filtering
81
+ or interlace
82
+ ):
83
+ raise ValueError("unsupported preview PNG layout")
84
+ elif kind == b"IDAT":
85
+ compressed.extend(payload)
86
+ elif kind == b"IEND":
87
+ break
88
+ position = end
89
+ if width is None or height is None or not compressed:
90
+ raise ValueError("preview PNG is incomplete")
91
+
92
+ stride = width * 3
93
+ expected_size = height * (stride + 1)
94
+ decompressor = zlib.decompressobj()
95
+ try:
96
+ decoded = decompressor.decompress(bytes(compressed), expected_size + 1)
97
+ except zlib.error as error:
98
+ raise ValueError("preview PNG compression is invalid") from error
99
+ if (
100
+ len(decoded) != expected_size
101
+ or not decompressor.eof
102
+ or decompressor.unconsumed_tail
103
+ ):
104
+ raise ValueError("preview PNG data length is invalid")
105
+ rows: list[bytearray] = []
106
+ for row_index in range(height):
107
+ start = row_index * (stride + 1)
108
+ filter_type = decoded[start]
109
+ raw = decoded[start + 1 : start + 1 + stride]
110
+ previous = rows[-1] if rows else bytearray(stride)
111
+ row = _unfilter(raw, previous, filter_type, 3)
112
+ rows.append(row)
113
+ return width, height, b"".join(rows)
114
+
115
+
116
+ def _unfilter(raw: bytes, previous: bytearray, filter_type: int, bpp: int) -> bytearray:
117
+ row = bytearray(len(raw))
118
+ for index, value in enumerate(raw):
119
+ left = row[index - bpp] if index >= bpp else 0
120
+ above = previous[index]
121
+ upper_left = previous[index - bpp] if index >= bpp else 0
122
+ if filter_type == 0:
123
+ predictor = 0
124
+ elif filter_type == 1:
125
+ predictor = left
126
+ elif filter_type == 2:
127
+ predictor = above
128
+ elif filter_type == 3:
129
+ predictor = (left + above) // 2
130
+ elif filter_type == 4:
131
+ predictor = _paeth(left, above, upper_left)
132
+ else:
133
+ raise ValueError("unsupported PNG filter")
134
+ row[index] = (value + predictor) & 0xFF
135
+ return row
136
+
137
+
138
+ def _paeth(left: int, above: int, upper_left: int) -> int:
139
+ estimate = left + above - upper_left
140
+ distances = abs(estimate - left), abs(estimate - above), abs(estimate - upper_left)
141
+ if distances[0] <= distances[1] and distances[0] <= distances[2]:
142
+ return left
143
+ return above if distances[1] <= distances[2] else upper_left
@@ -0,0 +1,171 @@
1
+ """Deterministic, bounded keyframe selection for local visual evidence.
2
+
3
+ The selector follows the relevance-versus-coverage principle described by
4
+ Adaptive Keyframe Sampling (Tang et al., CVPR 2025), but is an independent
5
+ implementation. It consumes scores produced by Clipen; it does not contain
6
+ or copy code from the unlicensed reference repository.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from dataclasses import dataclass
12
+ import math
13
+ from typing import Iterable
14
+
15
+
16
+ @dataclass(frozen=True, slots=True)
17
+ class KeyframeCandidate:
18
+ pts: int
19
+ score: float
20
+ source: str
21
+
22
+ def __post_init__(self) -> None:
23
+ if isinstance(self.pts, bool) or not isinstance(self.pts, int):
24
+ raise ValueError("keyframe pts must be an integer")
25
+ if not isinstance(self.score, (int, float)) or isinstance(self.score, bool):
26
+ raise ValueError("keyframe score must be numeric")
27
+ if not math.isfinite(float(self.score)) or not 0 <= float(self.score) <= 1:
28
+ raise ValueError("keyframe score must be between zero and one")
29
+ if self.source not in {"codec", "uniform", "semantic"}:
30
+ raise ValueError("unknown keyframe candidate source")
31
+
32
+
33
+ @dataclass(frozen=True, slots=True)
34
+ class KeyframeSelection:
35
+ candidates: tuple[KeyframeCandidate, ...]
36
+ method: str
37
+ semantic_relevance: bool
38
+
39
+
40
+ class AdaptiveKeyframeSelector:
41
+ """Balance scored moments with temporal coverage under a bounded budget."""
42
+
43
+ MAXIMUM_BUDGET = 48
44
+
45
+ def __init__(self, *, split_threshold: float = 0.22, maximum_depth: int = 6):
46
+ if not 0 <= split_threshold <= 1:
47
+ raise ValueError("split threshold must be between zero and one")
48
+ if isinstance(maximum_depth, bool) or not 1 <= maximum_depth <= 16:
49
+ raise ValueError("maximum depth is invalid")
50
+ self.split_threshold = split_threshold
51
+ self.maximum_depth = maximum_depth
52
+
53
+ def select(
54
+ self,
55
+ start_pts: int,
56
+ end_pts: int,
57
+ candidates: Iterable[KeyframeCandidate],
58
+ budget: int,
59
+ ) -> KeyframeSelection:
60
+ if (
61
+ isinstance(start_pts, bool)
62
+ or isinstance(end_pts, bool)
63
+ or not isinstance(start_pts, int)
64
+ or not isinstance(end_pts, int)
65
+ or end_pts <= start_pts
66
+ ):
67
+ raise ValueError("keyframe source span is invalid")
68
+ if (
69
+ isinstance(budget, bool)
70
+ or not isinstance(budget, int)
71
+ or not 1 <= budget <= self.MAXIMUM_BUDGET
72
+ ):
73
+ raise ValueError("keyframe budget is invalid")
74
+
75
+ deduplicated: dict[int, KeyframeCandidate] = {}
76
+ for candidate in candidates:
77
+ if not start_pts <= candidate.pts < end_pts:
78
+ raise ValueError("keyframe candidate lies outside source span")
79
+ previous = deduplicated.get(candidate.pts)
80
+ if previous is None or self._priority(candidate) > self._priority(previous):
81
+ deduplicated[candidate.pts] = candidate
82
+ ordered = tuple(sorted(deduplicated.values(), key=lambda item: item.pts))
83
+ if not ordered:
84
+ raise ValueError("at least one keyframe candidate is required")
85
+
86
+ semantic_available = any(item.source == "semantic" for item in ordered)
87
+ chosen = self._choose(
88
+ ordered,
89
+ min(budget, len(ordered)),
90
+ start_pts,
91
+ end_pts,
92
+ 0,
93
+ semantic_available,
94
+ )
95
+ semantic = any(item.source == "semantic" for item in chosen)
96
+ method = "adaptive_relevance_coverage_v1" if len(ordered) > budget else "bounded_all_v1"
97
+ return KeyframeSelection(tuple(sorted(chosen, key=lambda item: item.pts)), method, semantic)
98
+
99
+ @staticmethod
100
+ def budget_for_duration(duration_seconds: float) -> int:
101
+ """Return a bounded upper limit; visual deduplication may retain fewer frames."""
102
+
103
+ if not isinstance(duration_seconds, (int, float)) or isinstance(duration_seconds, bool):
104
+ raise ValueError("keyframe duration must be numeric")
105
+ if not math.isfinite(float(duration_seconds)) or duration_seconds <= 0:
106
+ raise ValueError("keyframe duration must be positive")
107
+ if duration_seconds <= 2:
108
+ return 1
109
+ return min(
110
+ AdaptiveKeyframeSelector.MAXIMUM_BUDGET,
111
+ math.ceil(duration_seconds / 8) + 1,
112
+ )
113
+
114
+ @staticmethod
115
+ def uniform(start_pts: int, end_pts: int, count: int) -> tuple[KeyframeCandidate, ...]:
116
+ if end_pts <= start_pts or isinstance(count, bool) or not 1 <= count <= 256:
117
+ raise ValueError("uniform keyframe request is invalid")
118
+ duration = end_pts - start_pts
119
+ points = {
120
+ start_pts + duration * (index * 2 + 1) // (count * 2)
121
+ for index in range(count)
122
+ }
123
+ return tuple(KeyframeCandidate(point, 0.0, "uniform") for point in sorted(points))
124
+
125
+ def _choose(
126
+ self,
127
+ candidates: tuple[KeyframeCandidate, ...],
128
+ quota: int,
129
+ lower: int,
130
+ upper: int,
131
+ depth: int,
132
+ allow_relevance_focus: bool,
133
+ ) -> tuple[KeyframeCandidate, ...]:
134
+ if quota >= len(candidates):
135
+ return candidates
136
+ center = lower + (upper - lower) / 2
137
+ if quota == 1:
138
+ return (max(candidates, key=lambda item: (item.score, -abs(item.pts - center), -item.pts)),)
139
+
140
+ top = sorted(candidates, key=lambda item: (-item.score, abs(item.pts - center), item.pts))[:quota]
141
+ advantage = sum(item.score for item in top) / quota - sum(
142
+ item.score for item in candidates
143
+ ) / len(candidates)
144
+ if (allow_relevance_focus and advantage >= self.split_threshold) or depth >= self.maximum_depth:
145
+ return tuple(top)
146
+
147
+ midpoint = lower + (upper - lower) // 2
148
+ left = tuple(item for item in candidates if item.pts < midpoint)
149
+ right = tuple(item for item in candidates if item.pts >= midpoint)
150
+ if not left or not right:
151
+ return tuple(top)
152
+
153
+ left_quota = quota // 2
154
+ right_quota = quota - left_quota
155
+ if len(left) < left_quota:
156
+ right_quota += left_quota - len(left)
157
+ left_quota = len(left)
158
+ if len(right) < right_quota:
159
+ left_quota += right_quota - len(right)
160
+ right_quota = len(right)
161
+ return self._choose(
162
+ left, left_quota, lower, midpoint, depth + 1, allow_relevance_focus
163
+ ) + self._choose(
164
+ right, right_quota, midpoint, upper, depth + 1, allow_relevance_focus
165
+ )
166
+
167
+ @staticmethod
168
+ def _priority(candidate: KeyframeCandidate) -> tuple[float, int]:
169
+ source_priority = {"uniform": 0, "codec": 1, "semantic": 2}
170
+ return float(candidate.score), source_priority[candidate.source]
171
+
@@ -0,0 +1,230 @@
1
+ """Validated records for local media preparation and transcription."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from enum import Enum
7
+ import json
8
+ import re
9
+ from typing import Mapping
10
+
11
+ from clipen.domain.media_time import Rational, SourceSpan
12
+ from clipen.projects.models import validate_project_id
13
+
14
+
15
+ _ARTIFACT_ID = re.compile(r"art_[0-9a-f]{32}\Z")
16
+ _PREPARATION_ID = re.compile(r"prep_[0-9a-f]{32}\Z")
17
+ _OPERATION_ID = re.compile(r"op_[0-9a-f]{32}\Z")
18
+ _ATTEMPT_ID = re.compile(r"att_[0-9a-f]{32}\Z")
19
+ _VERSION_ID = re.compile(r"av_[0-9a-f]{32}\Z")
20
+ _SHA256 = re.compile(r"[0-9a-f]{64}\Z")
21
+ _RECIPE_ID = re.compile(r"[a-z][a-z0-9_.-]{0,127}\Z")
22
+
23
+
24
+ class ArtifactKind(str, Enum):
25
+ ANALYSIS_AUDIO = "analysis_audio"
26
+ TRANSCRIPT = "transcript"
27
+ COVERAGE_MANIFEST = "coverage_manifest"
28
+ CHECKPOINT = "checkpoint"
29
+
30
+
31
+ class PreparationState(str, Enum):
32
+ QUEUED = "queued"
33
+ RUNNING = "running"
34
+ CANCELLING = "cancelling"
35
+ SUCCEEDED = "succeeded"
36
+ FAILED = "failed"
37
+ CANCELLED = "cancelled"
38
+ INTERRUPTED = "interrupted"
39
+
40
+
41
+ class PreparationItemStatus(str, Enum):
42
+ PENDING = "pending"
43
+ PREPARED = "prepared"
44
+ TRANSCRIBED = "transcribed"
45
+ NO_AUDIO = "no_audio"
46
+ NO_SPEECH = "no_speech"
47
+ FAILED = "failed"
48
+
49
+
50
+ class PreparationChunkStatus(str, Enum):
51
+ PENDING = "pending"
52
+ TRANSCRIBED = "transcribed"
53
+ NO_SPEECH = "no_speech"
54
+
55
+
56
+ @dataclass(frozen=True)
57
+ class PreparationCounts:
58
+ total: int = 0
59
+ prepared: int = 0
60
+ transcribed: int = 0
61
+ no_audio: int = 0
62
+ no_speech: int = 0
63
+ issues: int = 0
64
+
65
+ def __post_init__(self) -> None:
66
+ values = (
67
+ self.total,
68
+ self.prepared,
69
+ self.transcribed,
70
+ self.no_audio,
71
+ self.no_speech,
72
+ self.issues,
73
+ )
74
+ if any(isinstance(value, bool) or not isinstance(value, int) or value < 0 for value in values):
75
+ raise ValueError("preparation counts must be non-negative integers")
76
+ if self.transcribed + self.no_audio + self.no_speech + self.issues > self.total:
77
+ raise ValueError("terminal preparation counts exceed total inputs")
78
+ if self.prepared > self.total:
79
+ raise ValueError("prepared count exceeds total inputs")
80
+
81
+ def to_public(self) -> dict[str, int]:
82
+ return {
83
+ "total": self.total,
84
+ "prepared": self.prepared,
85
+ "transcribed": self.transcribed,
86
+ "no_audio": self.no_audio,
87
+ "no_speech": self.no_speech,
88
+ "issues": self.issues,
89
+ }
90
+
91
+
92
+ @dataclass(frozen=True)
93
+ class PreparationRun:
94
+ run_id: str
95
+ project_id: str
96
+ project_revision: int
97
+ inventory_run_id: str
98
+ scope_id: str
99
+ operation_id: str
100
+ attempt_id: str
101
+ attempt_number: int
102
+ input_fingerprint: str
103
+ state: PreparationState
104
+ phase: str
105
+ counts: PreparationCounts
106
+ error_code: str | None
107
+ created_at: str
108
+ started_at: str | None = None
109
+ completed_at: str | None = None
110
+
111
+ def __post_init__(self) -> None:
112
+ if _PREPARATION_ID.fullmatch(self.run_id) is None:
113
+ raise ValueError("preparation run ID is invalid")
114
+ validate_project_id(self.project_id)
115
+ if self.project_revision < 1:
116
+ raise ValueError("preparation project revision is invalid")
117
+ if re.fullmatch(r"inv_[0-9a-f]{32}", self.inventory_run_id) is None:
118
+ raise ValueError("preparation inventory ID is invalid")
119
+ if re.fullmatch(r"scope_[0-9a-f]{32}", self.scope_id) is None:
120
+ raise ValueError("preparation scope ID is invalid")
121
+ validate_operation_id(self.operation_id)
122
+ validate_attempt_id(self.attempt_id)
123
+ if self.attempt_number < 1 or _SHA256.fullmatch(self.input_fingerprint) is None:
124
+ raise ValueError("preparation input identity is invalid")
125
+ if not re.fullmatch(r"[a-z][a-z0-9_]{0,63}", self.phase):
126
+ raise ValueError("preparation phase is invalid")
127
+ if self.error_code is not None and not re.fullmatch(
128
+ r"[a-z][a-z0-9_]{0,63}", self.error_code
129
+ ):
130
+ raise ValueError("preparation error code is invalid")
131
+ terminal = self.state in {
132
+ PreparationState.SUCCEEDED,
133
+ PreparationState.FAILED,
134
+ PreparationState.CANCELLED,
135
+ PreparationState.INTERRUPTED,
136
+ }
137
+ if terminal != (self.completed_at is not None):
138
+ raise ValueError("preparation completion timestamp does not match state")
139
+ if self.state is not PreparationState.QUEUED and self.started_at is None:
140
+ raise ValueError("started preparation state requires timestamp")
141
+
142
+ def to_public(self) -> dict[str, object]:
143
+ return {
144
+ "run_id": self.run_id,
145
+ "project_revision": self.project_revision,
146
+ "inventory_run_id": self.inventory_run_id,
147
+ "scope_id": self.scope_id,
148
+ "state": self.state.value,
149
+ "phase": self.phase,
150
+ "counts": self.counts.to_public(),
151
+ "error_code": self.error_code,
152
+ "created_at": self.created_at,
153
+ "started_at": self.started_at,
154
+ "completed_at": self.completed_at,
155
+ }
156
+
157
+
158
+ @dataclass(frozen=True)
159
+ class TimelineSegment:
160
+ source_span: SourceSpan
161
+ text: str
162
+ confidence: str | None = None
163
+
164
+ def __post_init__(self) -> None:
165
+ if not isinstance(self.text, str) or "\x00" in self.text:
166
+ raise ValueError("timeline segment text is invalid")
167
+ if len(self.text.encode("utf-8")) > 64 * 1024:
168
+ raise ValueError("timeline segment text is too large")
169
+ if self.confidence is not None and (
170
+ not isinstance(self.confidence, str)
171
+ or len(self.confidence) > 64
172
+ or re.fullmatch(r"(?:0(?:\.[0-9]+)?|1(?:\.0+)?)", self.confidence) is None
173
+ ):
174
+ raise ValueError("timeline segment confidence is invalid")
175
+
176
+
177
+ @dataclass(frozen=True)
178
+ class ArtifactRecord:
179
+ artifact_id: str
180
+ project_id: str
181
+ kind: ArtifactKind
182
+ relative_path: str
183
+ sha256: str
184
+ size_bytes: int
185
+ producer_operation_id: str
186
+ producer_attempt_id: str
187
+ recipe_id: str
188
+ lineage: Mapping[str, object]
189
+ created_at: str
190
+ source_span: SourceSpan | None = None
191
+
192
+ def __post_init__(self) -> None:
193
+ if _ARTIFACT_ID.fullmatch(self.artifact_id) is None:
194
+ raise ValueError("artifact ID is invalid")
195
+ validate_project_id(self.project_id)
196
+ if not self.relative_path.startswith("artifacts/sha256/") or ".." in self.relative_path.split("/"):
197
+ raise ValueError("artifact path is outside the managed store")
198
+ if _SHA256.fullmatch(self.sha256) is None:
199
+ raise ValueError("artifact digest is invalid")
200
+ if isinstance(self.size_bytes, bool) or not 0 <= self.size_bytes <= 64 * 1024**3:
201
+ raise ValueError("artifact size is invalid")
202
+ if _OPERATION_ID.fullmatch(self.producer_operation_id) is None:
203
+ raise ValueError("artifact producer operation is invalid")
204
+ if _ATTEMPT_ID.fullmatch(self.producer_attempt_id) is None:
205
+ raise ValueError("artifact producer attempt is invalid")
206
+ if _RECIPE_ID.fullmatch(self.recipe_id) is None:
207
+ raise ValueError("artifact recipe is invalid")
208
+ encoded = json.dumps(self.lineage, ensure_ascii=False, separators=(",", ":"))
209
+ if len(encoded.encode("utf-8")) > 64 * 1024:
210
+ raise ValueError("artifact lineage is too large")
211
+ if not self.created_at:
212
+ raise ValueError("artifact creation time is missing")
213
+
214
+
215
+ def validate_operation_id(value: object) -> str:
216
+ if not isinstance(value, str) or _OPERATION_ID.fullmatch(value) is None:
217
+ raise ValueError("operation ID is invalid")
218
+ return value
219
+
220
+
221
+ def validate_attempt_id(value: object) -> str:
222
+ if not isinstance(value, str) or _ATTEMPT_ID.fullmatch(value) is None:
223
+ raise ValueError("attempt ID is invalid")
224
+ return value
225
+
226
+
227
+ def validate_recipe_id(value: object) -> str:
228
+ if not isinstance(value, str) or _RECIPE_ID.fullmatch(value) is None:
229
+ raise ValueError("recipe ID is invalid")
230
+ return value