@clipen/clipen-cli 0.0.0-stage → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +89 -2
- package/apps/web/dist/assets/index-D5D2HiB1.js +14 -0
- package/apps/web/dist/assets/index-DIMuOXSu.css +1 -0
- package/apps/web/dist/favicon.svg +1 -0
- package/apps/web/dist/index.html +16 -0
- package/bin/clipen.js +157 -0
- package/clipen +18 -0
- package/install +25 -0
- package/package.json +55 -4
- package/pyproject.toml +44 -0
- package/requirements/asr-runtime.txt +13 -0
- package/requirements/dev.txt +2 -0
- package/requirements/runtime.txt +20 -0
- package/src/clipen/__init__.py +3 -0
- package/src/clipen/analysis/__init__.py +89 -0
- package/src/clipen/analysis/artifacts.py +410 -0
- package/src/clipen/analysis/audio.py +394 -0
- package/src/clipen/analysis/evidence.py +102 -0
- package/src/clipen/analysis/evidence_service.py +929 -0
- package/src/clipen/analysis/image_similarity.py +134 -0
- package/src/clipen/analysis/keyframes.py +159 -0
- package/src/clipen/analysis/models.py +228 -0
- package/src/clipen/analysis/qwen_worker.py +594 -0
- package/src/clipen/analysis/resources.py +22 -0
- package/src/clipen/analysis/runtime.py +62 -0
- package/src/clipen/analysis/service.py +594 -0
- package/src/clipen/analysis/setup.py +921 -0
- package/src/clipen/analysis/setup_cli.py +107 -0
- package/src/clipen/analysis/storage.py +1864 -0
- package/src/clipen/analysis/transcription.py +906 -0
- package/src/clipen/analysis/visual.py +237 -0
- package/src/clipen/annotations/__init__.py +13 -0
- package/src/clipen/annotations/models.py +22 -0
- package/src/clipen/annotations/storage.py +428 -0
- package/src/clipen/annotations/suggestions.py +115 -0
- package/src/clipen/asr_release.py +132 -0
- package/src/clipen/bootstrap.py +978 -0
- package/src/clipen/candidates.py +222 -0
- package/src/clipen/cli.py +84 -0
- package/src/clipen/controller/__init__.py +17 -0
- package/src/clipen/controller/app.py +1657 -0
- package/src/clipen/controller/server.py +533 -0
- package/src/clipen/domain/__init__.py +30 -0
- package/src/clipen/domain/errors.py +5 -0
- package/src/clipen/domain/media_time.py +110 -0
- package/src/clipen/domain/timeline.py +582 -0
- package/src/clipen/domain/validation.py +14 -0
- package/src/clipen/editing/EDITORIAL_REGRESSIONS.md +38 -0
- package/src/clipen/editing/PROGRAM_FORMAT.md +102 -0
- package/src/clipen/editing/README.md +115 -0
- package/src/clipen/editing/REFACTOR_DESIGN.md +241 -0
- package/src/clipen/editing/REFACTOR_HANDOFF.md +73 -0
- package/src/clipen/editing/__init__.py +15 -0
- package/src/clipen/editing/agent.py +13 -0
- package/src/clipen/editing/agent_models.py +127 -0
- package/src/clipen/editing/agent_repository.py +978 -0
- package/src/clipen/editing/agent_tools.py +613 -0
- package/src/clipen/editing/alignment.py +150 -0
- package/src/clipen/editing/alignment_setup.py +156 -0
- package/src/clipen/editing/alignment_worker.py +24 -0
- package/src/clipen/editing/change_report.py +128 -0
- package/src/clipen/editing/compiler.py +40 -0
- package/src/clipen/editing/component_looks.py +131 -0
- package/src/clipen/editing/component_review.py +74 -0
- package/src/clipen/editing/coordinator.py +497 -0
- package/src/clipen/editing/editorial_review.py +309 -0
- package/src/clipen/editing/evidence_jobs.py +552 -0
- package/src/clipen/editing/history_changes.py +192 -0
- package/src/clipen/editing/music_choices.py +18 -0
- package/src/clipen/editing/production_catalog.py +629 -0
- package/src/clipen/editing/production_limits.py +85 -0
- package/src/clipen/editing/production_media.py +435 -0
- package/src/clipen/editing/production_preview.py +373 -0
- package/src/clipen/editing/production_progress.py +236 -0
- package/src/clipen/editing/production_requirements.py +117 -0
- package/src/clipen/editing/production_tools.py +1198 -0
- package/src/clipen/editing/program_audio.py +248 -0
- package/src/clipen/editing/program_direction.py +83 -0
- package/src/clipen/editing/program_story.py +91 -0
- package/src/clipen/editing/program_subtitles.py +232 -0
- package/src/clipen/editing/programme_review.py +121 -0
- package/src/clipen/editing/prompt_history.py +84 -0
- package/src/clipen/editing/recut.py +167 -0
- package/src/clipen/editing/refinement_references.py +278 -0
- package/src/clipen/editing/resolve_export.py +847 -0
- package/src/clipen/editing/resolve_titles.py +291 -0
- package/src/clipen/editing/skill_tools.py +951 -0
- package/src/clipen/editing/source_dialogue.py +192 -0
- package/src/clipen/editing/speech_coverage.py +50 -0
- package/src/clipen/editing/speech_quality.py +11 -0
- package/src/clipen/editing/tool_receipts.py +98 -0
- package/src/clipen/editing/versions.py +219 -0
- package/src/clipen/editing/visual_preview.py +189 -0
- package/src/clipen/editing/workbench.py +136 -0
- package/src/clipen/filesystem.py +25 -0
- package/src/clipen/finishing/README.md +103 -0
- package/src/clipen/finishing/__init__.py +1 -0
- package/src/clipen/finishing/audio.py +188 -0
- package/src/clipen/finishing/catalog.py +264 -0
- package/src/clipen/finishing/models.py +14 -0
- package/src/clipen/finishing/renderer.py +45 -0
- package/src/clipen/mcp_editing/__init__.py +5 -0
- package/src/clipen/mcp_editing/__main__.py +42 -0
- package/src/clipen/mcp_editing/server.py +396 -0
- package/src/clipen/media/__init__.py +50 -0
- package/src/clipen/media/discovery.py +253 -0
- package/src/clipen/media/models.py +349 -0
- package/src/clipen/media/preview.py +137 -0
- package/src/clipen/media/probe.py +418 -0
- package/src/clipen/media/service.py +304 -0
- package/src/clipen/media/storage.py +694 -0
- package/src/clipen/music_vocabulary.py +34 -0
- package/src/clipen/power.py +28 -0
- package/src/clipen/projects/__init__.py +26 -0
- package/src/clipen/projects/agent_schema.py +94 -0
- package/src/clipen/projects/annotation_schema.py +40 -0
- package/src/clipen/projects/deletion.py +256 -0
- package/src/clipen/projects/evidence_schema.py +52 -0
- package/src/clipen/projects/finishing_schema.py +36 -0
- package/src/clipen/projects/models.py +189 -0
- package/src/clipen/projects/picker.py +232 -0
- package/src/clipen/projects/preview_schema.py +29 -0
- package/src/clipen/projects/service.py +159 -0
- package/src/clipen/projects/storage.py +1458 -0
- package/src/clipen/projects/timeline_schema.py +32 -0
- package/src/clipen/projects/validation_schema.py +28 -0
- package/src/clipen/provider_registry.py +77 -0
- package/src/clipen/providers/__init__.py +43 -0
- package/src/clipen/providers/account.py +245 -0
- package/src/clipen/providers/claude.py +409 -0
- package/src/clipen/providers/claude_editing.py +118 -0
- package/src/clipen/providers/codex.py +991 -0
- package/src/clipen/providers/codex_editing.py +91 -0
- package/src/clipen/providers/editing_agent.py +567 -0
- package/src/clipen/providers/errors.py +51 -0
- package/src/clipen/providers/recovery.py +269 -0
- package/src/clipen/py.typed +1 -0
- package/src/clipen/rendering/__init__.py +12 -0
- package/src/clipen/rendering/cover.py +139 -0
- package/src/clipen/rendering/custom_components.py +328 -0
- package/src/clipen/rendering/custom_render.py +218 -0
- package/src/clipen/rendering/fonts/anton-OFL.txt +93 -0
- package/src/clipen/rendering/fonts/bebasneue-OFL.txt +93 -0
- package/src/clipen/rendering/fonts/caveat-OFL.txt +93 -0
- package/src/clipen/rendering/fonts/chenyu-OFL.txt +93 -0
- package/src/clipen/rendering/fonts/delagothicone-OFL.txt +93 -0
- package/src/clipen/rendering/fonts/hachimarupop-OFL.txt +93 -0
- package/src/clipen/rendering/fonts/iansui-OFL.txt +93 -0
- package/src/clipen/rendering/fonts/manifest.json +145 -0
- package/src/clipen/rendering/fonts/playfairdisplay-OFL.txt +93 -0
- package/src/clipen/rendering/fonts/rocknrollone-OFL.txt +93 -0
- package/src/clipen/rendering/fonts/yomogi-OFL.txt +94 -0
- package/src/clipen/rendering/fonts/yuseimagic-OFL.txt +93 -0
- package/src/clipen/rendering/fonts/zenkurenaido-OFL.txt +93 -0
- package/src/clipen/rendering/fonts/zenmarugothic-OFL.txt +93 -0
- package/src/clipen/rendering/production_effects.py +96 -0
- package/src/clipen/rendering/program_components.py +254 -0
- package/src/clipen/rendering/program_creator.py +804 -0
- package/src/clipen/rendering/program_identities.py +350 -0
- package/src/clipen/rendering/program_motion.py +186 -0
- package/src/clipen/rendering/program_studio.py +227 -0
- package/src/clipen/rendering/program_styles.py +321 -0
- package/src/clipen/rendering/program_subtitles.py +89 -0
- package/src/clipen/rendering/renderer.py +737 -0
- package/src/clipen/rendering/storage.py +230 -0
- package/src/clipen/rendering/titles.py +467 -0
- package/src/clipen/skills/__init__.py +5 -0
- package/src/clipen/skills/builtin/SKILL.md +72 -0
- package/src/clipen/skills/builtin/assets/sample-daily-vlog.mp4 +0 -0
- package/src/clipen/skills/builtin/assets/sample-event-recap.mp4 +0 -0
- package/src/clipen/skills/builtin/assets/sample-food-review.mp4 +0 -0
- package/src/clipen/skills/builtin/assets/sample-product-demo.mp4 +0 -0
- package/src/clipen/skills/builtin/assets/sample-product-review.mp4 +0 -0
- package/src/clipen/skills/builtin/assets/sample-product-unboxing.mp4 +0 -0
- package/src/clipen/skills/builtin/assets/sample-shorts-highlight.mp4 +0 -0
- package/src/clipen/skills/builtin/assets/sample-travel-highlight.mp4 +0 -0
- package/src/clipen/skills/builtin/assets/sample-travel-vlog.mp4 +0 -0
- package/src/clipen/skills/builtin/assets/style-cinema.png +0 -0
- package/src/clipen/skills/builtin/assets/style-editorial.png +0 -0
- package/src/clipen/skills/builtin/assets/style-tpl-daily-vlog.png +0 -0
- package/src/clipen/skills/builtin/assets/style-tpl-event-recap.png +0 -0
- package/src/clipen/skills/builtin/assets/style-tpl-food-review.png +0 -0
- package/src/clipen/skills/builtin/assets/style-tpl-product-demo.png +0 -0
- package/src/clipen/skills/builtin/assets/style-tpl-product-review.png +0 -0
- package/src/clipen/skills/builtin/assets/style-tpl-product-unboxing.png +0 -0
- package/src/clipen/skills/builtin/assets/style-tpl-shorts-highlight.png +0 -0
- package/src/clipen/skills/builtin/assets/style-tpl-travel-highlight.png +0 -0
- package/src/clipen/skills/builtin/assets/style-tpl-travel-vlog.png +0 -0
- package/src/clipen/skills/builtin/assets/style-variety.png +0 -0
- package/src/clipen/skills/builtin/components.json +133 -0
- package/src/clipen/skills/builtin/font_sources.json +20 -0
- package/src/clipen/skills/builtin/font_styles.json +329 -0
- package/src/clipen/skills/builtin/manifest.json +32 -0
- package/src/clipen/skills/builtin/presets.json +8 -0
- package/src/clipen/skills/builtin/references/captions.md +14 -0
- package/src/clipen/skills/builtin/references/channel-design.md +37 -0
- package/src/clipen/skills/builtin/references/editing.md +30 -0
- package/src/clipen/skills/builtin/references/font-chenyu-OFL.txt +93 -0
- package/src/clipen/skills/builtin/references/font-iansui-OFL.txt +93 -0
- package/src/clipen/skills/builtin/references/graphics.md +59 -0
- package/src/clipen/skills/builtin/references/review.md +16 -0
- package/src/clipen/skills/builtin/references/sound.md +8 -0
- package/src/clipen/skills/builtin/references/story.md +7 -0
- package/src/clipen/skills/builtin/skills/travel-program/SKILL.md +27 -0
- package/src/clipen/skills/builtin/skills/travel-program/manifest.json +6 -0
- package/src/clipen/skills/builtin/template-skills/clipen-daily-vlog/SKILL.md +33 -0
- package/src/clipen/skills/builtin/template-skills/clipen-daily-vlog/manifest.json +8 -0
- package/src/clipen/skills/builtin/template-skills/clipen-event-recap/SKILL.md +34 -0
- package/src/clipen/skills/builtin/template-skills/clipen-event-recap/manifest.json +8 -0
- package/src/clipen/skills/builtin/template-skills/clipen-food-review/SKILL.md +33 -0
- package/src/clipen/skills/builtin/template-skills/clipen-food-review/manifest.json +8 -0
- package/src/clipen/skills/builtin/template-skills/clipen-product-demo/SKILL.md +35 -0
- package/src/clipen/skills/builtin/template-skills/clipen-product-demo/manifest.json +8 -0
- package/src/clipen/skills/builtin/template-skills/clipen-product-review/SKILL.md +36 -0
- package/src/clipen/skills/builtin/template-skills/clipen-product-review/manifest.json +8 -0
- package/src/clipen/skills/builtin/template-skills/clipen-product-unboxing/SKILL.md +39 -0
- package/src/clipen/skills/builtin/template-skills/clipen-product-unboxing/manifest.json +8 -0
- package/src/clipen/skills/builtin/template-skills/clipen-shorts-highlight/SKILL.md +38 -0
- package/src/clipen/skills/builtin/template-skills/clipen-shorts-highlight/manifest.json +8 -0
- package/src/clipen/skills/builtin/template-skills/clipen-travel-highlight/SKILL.md +34 -0
- package/src/clipen/skills/builtin/template-skills/clipen-travel-highlight/manifest.json +8 -0
- package/src/clipen/skills/builtin/template-skills/clipen-travel-vlog/SKILL.md +37 -0
- package/src/clipen/skills/builtin/template-skills/clipen-travel-vlog/manifest.json +8 -0
- package/src/clipen/skills/builtin/templates.json +284 -0
- package/src/clipen/skills/builtin/visual_styles.json +1074 -0
- package/src/clipen/skills/catalog.py +314 -0
- package/src/clipen/skills/library.py +137 -0
- package/src/clipen/skills/package.py +254 -0
- package/src/clipen/skills/visual_styles.py +55 -0
- package/src/clipen/workspace.py +181 -0
- package/uninstall +25 -0
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
"""Small, dependency-free visual fingerprints for Clipen-generated PNG previews."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import struct
|
|
6
|
+
import zlib
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
_PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"
|
|
11
|
+
_GRID_SIZE = 8
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclass(frozen=True, slots=True)
|
|
15
|
+
class VisualFingerprint:
|
|
16
|
+
cells: tuple[int, ...]
|
|
17
|
+
mean_luma: int
|
|
18
|
+
|
|
19
|
+
def is_similar_to(self, other: "VisualFingerprint") -> bool:
|
|
20
|
+
if len(self.cells) != len(other.cells):
|
|
21
|
+
return False
|
|
22
|
+
mean_delta = abs(self.mean_luma - other.mean_luma) / 255
|
|
23
|
+
cell_delta = sum(abs(a - b) for a, b in zip(self.cells, other.cells)) / (len(self.cells) * 255)
|
|
24
|
+
return mean_delta <= 0.10 and cell_delta <= 0.085
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def fingerprint_png(path: Path) -> VisualFingerprint:
|
|
28
|
+
"""Fingerprint an RGB8 PNG emitted by Clipen's controlled FFmpeg pipeline."""
|
|
29
|
+
|
|
30
|
+
width, height, pixels = _decode_rgb8_png(path.read_bytes())
|
|
31
|
+
cells = []
|
|
32
|
+
for grid_y in range(_GRID_SIZE):
|
|
33
|
+
y0 = grid_y * height // _GRID_SIZE
|
|
34
|
+
y1 = max(y0 + 1, (grid_y + 1) * height // _GRID_SIZE)
|
|
35
|
+
for grid_x in range(_GRID_SIZE):
|
|
36
|
+
x0 = grid_x * width // _GRID_SIZE
|
|
37
|
+
x1 = max(x0 + 1, (grid_x + 1) * width // _GRID_SIZE)
|
|
38
|
+
total = count = 0
|
|
39
|
+
for y in range(y0, y1):
|
|
40
|
+
row = y * width * 3
|
|
41
|
+
for x in range(x0, x1):
|
|
42
|
+
offset = row + x * 3
|
|
43
|
+
red, green, blue = pixels[offset : offset + 3]
|
|
44
|
+
total += (77 * red + 150 * green + 29 * blue) >> 8
|
|
45
|
+
count += 1
|
|
46
|
+
cells.append(round(total / count))
|
|
47
|
+
return VisualFingerprint(tuple(cells), round(sum(cells) / len(cells)))
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _decode_rgb8_png(data: bytes) -> tuple[int, int, bytes]:
|
|
51
|
+
if not data.startswith(_PNG_SIGNATURE):
|
|
52
|
+
raise ValueError("preview is not a PNG")
|
|
53
|
+
width = height = None
|
|
54
|
+
compressed = bytearray()
|
|
55
|
+
position = len(_PNG_SIGNATURE)
|
|
56
|
+
while position + 12 <= len(data):
|
|
57
|
+
length = struct.unpack(">I", data[position : position + 4])[0]
|
|
58
|
+
kind = data[position + 4 : position + 8]
|
|
59
|
+
end = position + 12 + length
|
|
60
|
+
if end > len(data):
|
|
61
|
+
raise ValueError("PNG chunk is truncated")
|
|
62
|
+
payload = data[position + 8 : position + 8 + length]
|
|
63
|
+
if kind == b"IHDR":
|
|
64
|
+
if len(payload) != 13:
|
|
65
|
+
raise ValueError("preview PNG header is invalid")
|
|
66
|
+
width, height, depth, color, compression, filtering, interlace = struct.unpack(">IIBBBBB", payload)
|
|
67
|
+
if (
|
|
68
|
+
not width
|
|
69
|
+
or not height
|
|
70
|
+
or width > 512
|
|
71
|
+
or height > 512
|
|
72
|
+
or depth != 8
|
|
73
|
+
or color != 2
|
|
74
|
+
or compression
|
|
75
|
+
or filtering
|
|
76
|
+
or interlace
|
|
77
|
+
):
|
|
78
|
+
raise ValueError("unsupported preview PNG layout")
|
|
79
|
+
elif kind == b"IDAT":
|
|
80
|
+
compressed.extend(payload)
|
|
81
|
+
elif kind == b"IEND":
|
|
82
|
+
break
|
|
83
|
+
position = end
|
|
84
|
+
if width is None or height is None or not compressed:
|
|
85
|
+
raise ValueError("preview PNG is incomplete")
|
|
86
|
+
|
|
87
|
+
stride = width * 3
|
|
88
|
+
expected_size = height * (stride + 1)
|
|
89
|
+
decompressor = zlib.decompressobj()
|
|
90
|
+
try:
|
|
91
|
+
decoded = decompressor.decompress(bytes(compressed), expected_size + 1)
|
|
92
|
+
except zlib.error as error:
|
|
93
|
+
raise ValueError("preview PNG compression is invalid") from error
|
|
94
|
+
if len(decoded) != expected_size or not decompressor.eof or decompressor.unconsumed_tail:
|
|
95
|
+
raise ValueError("preview PNG data length is invalid")
|
|
96
|
+
rows: list[bytearray] = []
|
|
97
|
+
for row_index in range(height):
|
|
98
|
+
start = row_index * (stride + 1)
|
|
99
|
+
filter_type = decoded[start]
|
|
100
|
+
raw = decoded[start + 1 : start + 1 + stride]
|
|
101
|
+
previous = rows[-1] if rows else bytearray(stride)
|
|
102
|
+
row = _unfilter(raw, previous, filter_type, 3)
|
|
103
|
+
rows.append(row)
|
|
104
|
+
return width, height, b"".join(rows)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _unfilter(raw: bytes, previous: bytearray, filter_type: int, bpp: int) -> bytearray:
|
|
108
|
+
row = bytearray(len(raw))
|
|
109
|
+
for index, value in enumerate(raw):
|
|
110
|
+
left = row[index - bpp] if index >= bpp else 0
|
|
111
|
+
above = previous[index]
|
|
112
|
+
upper_left = previous[index - bpp] if index >= bpp else 0
|
|
113
|
+
if filter_type == 0:
|
|
114
|
+
predictor = 0
|
|
115
|
+
elif filter_type == 1:
|
|
116
|
+
predictor = left
|
|
117
|
+
elif filter_type == 2:
|
|
118
|
+
predictor = above
|
|
119
|
+
elif filter_type == 3:
|
|
120
|
+
predictor = (left + above) // 2
|
|
121
|
+
elif filter_type == 4:
|
|
122
|
+
predictor = _paeth(left, above, upper_left)
|
|
123
|
+
else:
|
|
124
|
+
raise ValueError("unsupported PNG filter")
|
|
125
|
+
row[index] = (value + predictor) & 0xFF
|
|
126
|
+
return row
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _paeth(left: int, above: int, upper_left: int) -> int:
|
|
130
|
+
estimate = left + above - upper_left
|
|
131
|
+
distances = abs(estimate - left), abs(estimate - above), abs(estimate - upper_left)
|
|
132
|
+
if distances[0] <= distances[1] and distances[0] <= distances[2]:
|
|
133
|
+
return left
|
|
134
|
+
return above if distances[1] <= distances[2] else upper_left
|
|
@@ -0,0 +1,159 @@
|
|
|
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
|
+
import math
|
|
12
|
+
from dataclasses import dataclass
|
|
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 isinstance(budget, bool) or not isinstance(budget, int) or not 1 <= budget <= self.MAXIMUM_BUDGET:
|
|
69
|
+
raise ValueError("keyframe budget is invalid")
|
|
70
|
+
|
|
71
|
+
deduplicated: dict[int, KeyframeCandidate] = {}
|
|
72
|
+
for candidate in candidates:
|
|
73
|
+
if not start_pts <= candidate.pts < end_pts:
|
|
74
|
+
raise ValueError("keyframe candidate lies outside source span")
|
|
75
|
+
previous = deduplicated.get(candidate.pts)
|
|
76
|
+
if previous is None or self._priority(candidate) > self._priority(previous):
|
|
77
|
+
deduplicated[candidate.pts] = candidate
|
|
78
|
+
ordered = tuple(sorted(deduplicated.values(), key=lambda item: item.pts))
|
|
79
|
+
if not ordered:
|
|
80
|
+
raise ValueError("at least one keyframe candidate is required")
|
|
81
|
+
|
|
82
|
+
semantic_available = any(item.source == "semantic" for item in ordered)
|
|
83
|
+
chosen = self._choose(
|
|
84
|
+
ordered,
|
|
85
|
+
min(budget, len(ordered)),
|
|
86
|
+
start_pts,
|
|
87
|
+
end_pts,
|
|
88
|
+
0,
|
|
89
|
+
semantic_available,
|
|
90
|
+
)
|
|
91
|
+
semantic = any(item.source == "semantic" for item in chosen)
|
|
92
|
+
method = "adaptive_relevance_coverage_v1" if len(ordered) > budget else "bounded_all_v1"
|
|
93
|
+
return KeyframeSelection(tuple(sorted(chosen, key=lambda item: item.pts)), method, semantic)
|
|
94
|
+
|
|
95
|
+
@staticmethod
|
|
96
|
+
def budget_for_duration(duration_seconds: float) -> int:
|
|
97
|
+
"""Return a bounded upper limit; visual deduplication may retain fewer frames."""
|
|
98
|
+
|
|
99
|
+
if not isinstance(duration_seconds, (int, float)) or isinstance(duration_seconds, bool):
|
|
100
|
+
raise ValueError("keyframe duration must be numeric")
|
|
101
|
+
if not math.isfinite(float(duration_seconds)) or duration_seconds <= 0:
|
|
102
|
+
raise ValueError("keyframe duration must be positive")
|
|
103
|
+
if duration_seconds <= 2:
|
|
104
|
+
return 1
|
|
105
|
+
return min(
|
|
106
|
+
AdaptiveKeyframeSelector.MAXIMUM_BUDGET,
|
|
107
|
+
math.ceil(duration_seconds / 8) + 1,
|
|
108
|
+
)
|
|
109
|
+
|
|
110
|
+
@staticmethod
|
|
111
|
+
def uniform(start_pts: int, end_pts: int, count: int) -> tuple[KeyframeCandidate, ...]:
|
|
112
|
+
if end_pts <= start_pts or isinstance(count, bool) or not 1 <= count <= 256:
|
|
113
|
+
raise ValueError("uniform keyframe request is invalid")
|
|
114
|
+
duration = end_pts - start_pts
|
|
115
|
+
points = {start_pts + duration * (index * 2 + 1) // (count * 2) for index in range(count)}
|
|
116
|
+
return tuple(KeyframeCandidate(point, 0.0, "uniform") for point in sorted(points))
|
|
117
|
+
|
|
118
|
+
def _choose(
|
|
119
|
+
self,
|
|
120
|
+
candidates: tuple[KeyframeCandidate, ...],
|
|
121
|
+
quota: int,
|
|
122
|
+
lower: int,
|
|
123
|
+
upper: int,
|
|
124
|
+
depth: int,
|
|
125
|
+
allow_relevance_focus: bool,
|
|
126
|
+
) -> tuple[KeyframeCandidate, ...]:
|
|
127
|
+
if quota >= len(candidates):
|
|
128
|
+
return candidates
|
|
129
|
+
center = lower + (upper - lower) / 2
|
|
130
|
+
if quota == 1:
|
|
131
|
+
return (max(candidates, key=lambda item: (item.score, -abs(item.pts - center), -item.pts)),)
|
|
132
|
+
|
|
133
|
+
top = sorted(candidates, key=lambda item: (-item.score, abs(item.pts - center), item.pts))[:quota]
|
|
134
|
+
advantage = sum(item.score for item in top) / quota - sum(item.score for item in candidates) / len(candidates)
|
|
135
|
+
if (allow_relevance_focus and advantage >= self.split_threshold) or depth >= self.maximum_depth:
|
|
136
|
+
return tuple(top)
|
|
137
|
+
|
|
138
|
+
midpoint = lower + (upper - lower) // 2
|
|
139
|
+
left = tuple(item for item in candidates if item.pts < midpoint)
|
|
140
|
+
right = tuple(item for item in candidates if item.pts >= midpoint)
|
|
141
|
+
if not left or not right:
|
|
142
|
+
return tuple(top)
|
|
143
|
+
|
|
144
|
+
left_quota = quota // 2
|
|
145
|
+
right_quota = quota - left_quota
|
|
146
|
+
if len(left) < left_quota:
|
|
147
|
+
right_quota += left_quota - len(left)
|
|
148
|
+
left_quota = len(left)
|
|
149
|
+
if len(right) < right_quota:
|
|
150
|
+
left_quota += right_quota - len(right)
|
|
151
|
+
right_quota = len(right)
|
|
152
|
+
return self._choose(left, left_quota, lower, midpoint, depth + 1, allow_relevance_focus) + self._choose(
|
|
153
|
+
right, right_quota, midpoint, upper, depth + 1, allow_relevance_focus
|
|
154
|
+
)
|
|
155
|
+
|
|
156
|
+
@staticmethod
|
|
157
|
+
def _priority(candidate: KeyframeCandidate) -> tuple[float, int]:
|
|
158
|
+
source_priority = {"uniform": 0, "codec": 1, "semantic": 2}
|
|
159
|
+
return float(candidate.score), source_priority[candidate.source]
|
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
"""Validated records for local media preparation and transcription."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import re
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from enum import Enum
|
|
9
|
+
from typing import Mapping
|
|
10
|
+
|
|
11
|
+
from clipen.domain.media_time import Rational as Rational # re-exported for the analysis modules
|
|
12
|
+
from clipen.domain.media_time import SourceSpan
|
|
13
|
+
from clipen.projects.models import validate_project_id
|
|
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(r"[a-z][a-z0-9_]{0,63}", self.error_code):
|
|
128
|
+
raise ValueError("preparation error code is invalid")
|
|
129
|
+
terminal = self.state in {
|
|
130
|
+
PreparationState.SUCCEEDED,
|
|
131
|
+
PreparationState.FAILED,
|
|
132
|
+
PreparationState.CANCELLED,
|
|
133
|
+
PreparationState.INTERRUPTED,
|
|
134
|
+
}
|
|
135
|
+
if terminal != (self.completed_at is not None):
|
|
136
|
+
raise ValueError("preparation completion timestamp does not match state")
|
|
137
|
+
if self.state is not PreparationState.QUEUED and self.started_at is None:
|
|
138
|
+
raise ValueError("started preparation state requires timestamp")
|
|
139
|
+
|
|
140
|
+
def to_public(self) -> dict[str, object]:
|
|
141
|
+
return {
|
|
142
|
+
"run_id": self.run_id,
|
|
143
|
+
"project_revision": self.project_revision,
|
|
144
|
+
"inventory_run_id": self.inventory_run_id,
|
|
145
|
+
"scope_id": self.scope_id,
|
|
146
|
+
"state": self.state.value,
|
|
147
|
+
"phase": self.phase,
|
|
148
|
+
"counts": self.counts.to_public(),
|
|
149
|
+
"error_code": self.error_code,
|
|
150
|
+
"created_at": self.created_at,
|
|
151
|
+
"started_at": self.started_at,
|
|
152
|
+
"completed_at": self.completed_at,
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
@dataclass(frozen=True)
|
|
157
|
+
class TimelineSegment:
|
|
158
|
+
source_span: SourceSpan
|
|
159
|
+
text: str
|
|
160
|
+
confidence: str | None = None
|
|
161
|
+
|
|
162
|
+
def __post_init__(self) -> None:
|
|
163
|
+
if not isinstance(self.text, str) or "\x00" in self.text:
|
|
164
|
+
raise ValueError("timeline segment text is invalid")
|
|
165
|
+
if len(self.text.encode("utf-8")) > 64 * 1024:
|
|
166
|
+
raise ValueError("timeline segment text is too large")
|
|
167
|
+
if self.confidence is not None and (
|
|
168
|
+
not isinstance(self.confidence, str)
|
|
169
|
+
or len(self.confidence) > 64
|
|
170
|
+
or re.fullmatch(r"(?:0(?:\.[0-9]+)?|1(?:\.0+)?)", self.confidence) is None
|
|
171
|
+
):
|
|
172
|
+
raise ValueError("timeline segment confidence is invalid")
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
@dataclass(frozen=True)
|
|
176
|
+
class ArtifactRecord:
|
|
177
|
+
artifact_id: str
|
|
178
|
+
project_id: str
|
|
179
|
+
kind: ArtifactKind
|
|
180
|
+
relative_path: str
|
|
181
|
+
sha256: str
|
|
182
|
+
size_bytes: int
|
|
183
|
+
producer_operation_id: str
|
|
184
|
+
producer_attempt_id: str
|
|
185
|
+
recipe_id: str
|
|
186
|
+
lineage: Mapping[str, object]
|
|
187
|
+
created_at: str
|
|
188
|
+
source_span: SourceSpan | None = None
|
|
189
|
+
|
|
190
|
+
def __post_init__(self) -> None:
|
|
191
|
+
if _ARTIFACT_ID.fullmatch(self.artifact_id) is None:
|
|
192
|
+
raise ValueError("artifact ID is invalid")
|
|
193
|
+
validate_project_id(self.project_id)
|
|
194
|
+
if not self.relative_path.startswith("artifacts/sha256/") or ".." in self.relative_path.split("/"):
|
|
195
|
+
raise ValueError("artifact path is outside the managed store")
|
|
196
|
+
if _SHA256.fullmatch(self.sha256) is None:
|
|
197
|
+
raise ValueError("artifact digest is invalid")
|
|
198
|
+
if isinstance(self.size_bytes, bool) or not 0 <= self.size_bytes <= 64 * 1024**3:
|
|
199
|
+
raise ValueError("artifact size is invalid")
|
|
200
|
+
if _OPERATION_ID.fullmatch(self.producer_operation_id) is None:
|
|
201
|
+
raise ValueError("artifact producer operation is invalid")
|
|
202
|
+
if _ATTEMPT_ID.fullmatch(self.producer_attempt_id) is None:
|
|
203
|
+
raise ValueError("artifact producer attempt is invalid")
|
|
204
|
+
if _RECIPE_ID.fullmatch(self.recipe_id) is None:
|
|
205
|
+
raise ValueError("artifact recipe is invalid")
|
|
206
|
+
encoded = json.dumps(self.lineage, ensure_ascii=False, separators=(",", ":"))
|
|
207
|
+
if len(encoded.encode("utf-8")) > 64 * 1024:
|
|
208
|
+
raise ValueError("artifact lineage is too large")
|
|
209
|
+
if not self.created_at:
|
|
210
|
+
raise ValueError("artifact creation time is missing")
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def validate_operation_id(value: object) -> str:
|
|
214
|
+
if not isinstance(value, str) or _OPERATION_ID.fullmatch(value) is None:
|
|
215
|
+
raise ValueError("operation ID is invalid")
|
|
216
|
+
return value
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def validate_attempt_id(value: object) -> str:
|
|
220
|
+
if not isinstance(value, str) or _ATTEMPT_ID.fullmatch(value) is None:
|
|
221
|
+
raise ValueError("attempt ID is invalid")
|
|
222
|
+
return value
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def validate_recipe_id(value: object) -> str:
|
|
226
|
+
if not isinstance(value, str) or _RECIPE_ID.fullmatch(value) is None:
|
|
227
|
+
raise ValueError("recipe ID is invalid")
|
|
228
|
+
return value
|