@clipen/clipen-cli 1.0.0 → 1.0.2
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/README.md +56 -48
- package/apps/web/dist/assets/{index-D5D2HiB1.js → index-DPHwA954.js} +1 -1
- package/apps/web/dist/index.html +1 -1
- package/bin/clipen.js +1 -1
- package/package.json +7 -6
- package/pyproject.toml +18 -2
- package/requirements/dev.txt +2 -0
- package/src/clipen/__init__.py +1 -1
- package/src/clipen/analysis/__init__.py +7 -7
- package/src/clipen/analysis/artifacts.py +4 -10
- package/src/clipen/analysis/audio.py +10 -8
- package/src/clipen/analysis/evidence_service.py +345 -167
- package/src/clipen/analysis/image_similarity.py +5 -14
- package/src/clipen/analysis/keyframes.py +5 -17
- package/src/clipen/analysis/models.py +5 -7
- package/src/clipen/analysis/qwen_worker.py +19 -54
- package/src/clipen/analysis/resources.py +2 -1
- package/src/clipen/analysis/runtime.py +1 -3
- package/src/clipen/analysis/service.py +16 -48
- package/src/clipen/analysis/setup.py +11 -25
- package/src/clipen/analysis/setup_cli.py +5 -15
- package/src/clipen/analysis/storage.py +96 -278
- package/src/clipen/analysis/transcription.py +40 -82
- package/src/clipen/analysis/visual.py +109 -48
- package/src/clipen/annotations/__init__.py +5 -2
- package/src/clipen/annotations/models.py +1 -1
- package/src/clipen/annotations/storage.py +132 -84
- package/src/clipen/annotations/suggestions.py +3 -8
- package/src/clipen/asr_release.py +4 -11
- package/src/clipen/bootstrap.py +71 -61
- package/src/clipen/{planning/models.py → candidates.py} +29 -47
- package/src/clipen/cli.py +4 -9
- package/src/clipen/controller/app.py +401 -214
- package/src/clipen/controller/server.py +28 -38
- package/src/clipen/domain/__init__.py +1 -1
- package/src/clipen/domain/media_time.py +3 -10
- package/src/clipen/domain/timeline.py +45 -47
- package/src/clipen/domain/validation.py +0 -1
- package/src/clipen/editing/__init__.py +1 -1
- package/src/clipen/editing/agent_models.py +4 -11
- package/src/clipen/editing/agent_repository.py +393 -172
- package/src/clipen/editing/agent_tools.py +180 -99
- package/src/clipen/editing/alignment.py +92 -52
- package/src/clipen/editing/alignment_setup.py +118 -70
- package/src/clipen/editing/alignment_worker.py +11 -9
- package/src/clipen/editing/change_report.py +95 -38
- package/src/clipen/editing/compiler.py +0 -1
- package/src/clipen/editing/component_looks.py +58 -34
- package/src/clipen/editing/component_review.py +34 -38
- package/src/clipen/editing/coordinator.py +213 -92
- package/src/clipen/editing/editorial_review.py +217 -95
- package/src/clipen/editing/evidence_jobs.py +457 -200
- package/src/clipen/editing/history_changes.py +129 -68
- package/src/clipen/editing/music_choices.py +8 -5
- package/src/clipen/editing/production_catalog.py +573 -136
- package/src/clipen/editing/production_limits.py +43 -17
- package/src/clipen/editing/production_media.py +376 -167
- package/src/clipen/editing/production_preview.py +322 -129
- package/src/clipen/editing/production_progress.py +164 -69
- package/src/clipen/editing/production_requirements.py +106 -39
- package/src/clipen/editing/production_tools.py +1064 -462
- package/src/clipen/editing/program_audio.py +211 -81
- package/src/clipen/editing/program_direction.py +59 -25
- package/src/clipen/editing/program_story.py +83 -45
- package/src/clipen/editing/program_subtitles.py +194 -96
- package/src/clipen/editing/programme_review.py +98 -50
- package/src/clipen/editing/prompt_history.py +64 -27
- package/src/clipen/editing/recut.py +65 -25
- package/src/clipen/editing/refinement_references.py +176 -86
- package/src/clipen/editing/resolve_export.py +449 -218
- package/src/clipen/editing/resolve_titles.py +162 -105
- package/src/clipen/editing/skill_tools.py +530 -154
- package/src/clipen/editing/source_dialogue.py +177 -67
- package/src/clipen/editing/speech_coverage.py +42 -22
- package/src/clipen/editing/speech_quality.py +6 -1
- package/src/clipen/editing/tool_receipts.py +78 -32
- package/src/clipen/editing/versions.py +122 -64
- package/src/clipen/editing/visual_preview.py +157 -61
- package/src/clipen/editing/workbench.py +104 -42
- package/src/clipen/finishing/audio.py +69 -30
- package/src/clipen/finishing/catalog.py +176 -93
- package/src/clipen/finishing/models.py +1 -1
- package/src/clipen/finishing/renderer.py +33 -14
- package/src/clipen/mcp_editing/__main__.py +3 -1
- package/src/clipen/mcp_editing/server.py +77 -34
- package/src/clipen/media/__init__.py +3 -3
- package/src/clipen/media/discovery.py +7 -20
- package/src/clipen/media/models.py +7 -18
- package/src/clipen/media/preview.py +14 -24
- package/src/clipen/media/probe.py +16 -44
- package/src/clipen/media/service.py +6 -19
- package/src/clipen/media/storage.py +33 -81
- package/src/clipen/music_vocabulary.py +33 -4
- package/src/clipen/power.py +8 -3
- package/src/clipen/projects/__init__.py +1 -1
- package/src/clipen/projects/deletion.py +19 -32
- package/src/clipen/projects/finishing_schema.py +3 -1
- package/src/clipen/projects/models.py +2 -5
- package/src/clipen/projects/picker.py +13 -37
- package/src/clipen/projects/service.py +8 -24
- package/src/clipen/projects/storage.py +226 -246
- package/src/clipen/provider_registry.py +9 -20
- package/src/clipen/providers/account.py +86 -35
- package/src/clipen/providers/claude.py +59 -25
- package/src/clipen/providers/claude_editing.py +14 -7
- package/src/clipen/providers/codex.py +73 -118
- package/src/clipen/providers/codex_editing.py +2 -2
- package/src/clipen/providers/editing_agent.py +19 -17
- package/src/clipen/providers/recovery.py +7 -8
- package/src/clipen/rendering/cover.py +18 -5
- package/src/clipen/rendering/custom_components.py +167 -79
- package/src/clipen/rendering/custom_render.py +62 -41
- package/src/clipen/rendering/production_effects.py +77 -45
- package/src/clipen/rendering/program_components.py +134 -73
- package/src/clipen/rendering/program_creator.py +432 -277
- package/src/clipen/rendering/program_identities.py +277 -182
- package/src/clipen/rendering/program_motion.py +140 -95
- package/src/clipen/rendering/program_studio.py +175 -116
- package/src/clipen/rendering/program_styles.py +231 -145
- package/src/clipen/rendering/program_subtitles.py +71 -34
- package/src/clipen/rendering/renderer.py +150 -121
- package/src/clipen/rendering/storage.py +9 -22
- package/src/clipen/rendering/titles.py +193 -86
- package/src/clipen/skills/__init__.py +1 -0
- package/src/clipen/skills/catalog.py +151 -55
- package/src/clipen/skills/library.py +13 -7
- package/src/clipen/skills/package.py +46 -23
- package/src/clipen/skills/visual_styles.py +29 -18
- package/src/clipen/workspace.py +15 -44
- package/install +0 -25
- package/src/clipen/planning/__init__.py +0 -9
- package/uninstall +0 -25
|
@@ -5,34 +5,36 @@ Frames are drawn by ``custom_render`` in a sealed headless Chrome, cached on
|
|
|
5
5
|
disk by content, and composited like any other programme graphic, so the
|
|
6
6
|
preview, the film and the Resolve export show the same picture.
|
|
7
7
|
"""
|
|
8
|
+
|
|
8
9
|
import hashlib
|
|
9
10
|
import json
|
|
10
11
|
import os
|
|
11
|
-
from pathlib import Path
|
|
12
12
|
import subprocess
|
|
13
13
|
import sys
|
|
14
14
|
import tempfile
|
|
15
15
|
import threading
|
|
16
|
+
from pathlib import Path
|
|
16
17
|
|
|
17
18
|
from .titles import TitleRenderError
|
|
18
19
|
|
|
19
20
|
MAX_HTML_BYTES = 200_000
|
|
20
21
|
FRAME_TIMEOUT_SECONDS = 10
|
|
21
|
-
CUSTOM =
|
|
22
|
+
CUSTOM = "custom"
|
|
22
23
|
_locks = {}
|
|
23
24
|
_guard = threading.Lock()
|
|
24
25
|
|
|
25
26
|
|
|
26
27
|
def is_custom(profile):
|
|
27
|
-
return profile.get(
|
|
28
|
+
return profile.get("component_id") == CUSTOM
|
|
28
29
|
|
|
29
30
|
|
|
30
31
|
def cache_root():
|
|
31
|
-
configured = os.environ.get(
|
|
32
|
+
configured = os.environ.get("CLIPEN_CUSTOM_COMPONENT_CACHE")
|
|
32
33
|
if configured:
|
|
33
34
|
return Path(configured)
|
|
34
35
|
from clipen.bootstrap import clipen_data_root
|
|
35
|
-
|
|
36
|
+
|
|
37
|
+
return clipen_data_root() / "cache" / "custom-components"
|
|
36
38
|
|
|
37
39
|
|
|
38
40
|
def _fps(timeline):
|
|
@@ -40,63 +42,109 @@ def _fps(timeline):
|
|
|
40
42
|
|
|
41
43
|
|
|
42
44
|
def _edits(profile):
|
|
43
|
-
edits = profile.get(
|
|
44
|
-
return {kind: dict(sorted((edits.get(kind) or {}).items())) for kind in (
|
|
45
|
+
edits = profile.get("edits") or {}
|
|
46
|
+
return {kind: dict(sorted((edits.get(kind) or {}).items())) for kind in ("texts", "colors") if edits.get(kind)}
|
|
45
47
|
|
|
46
48
|
|
|
47
49
|
def _bundled():
|
|
48
50
|
"""Fonts Clipen carries itself (pinned in fonts/manifest.json), by family name: nothing to install."""
|
|
49
51
|
from importlib.resources import files
|
|
50
|
-
|
|
51
|
-
|
|
52
|
+
|
|
53
|
+
manifest = json.loads(files("clipen.rendering").joinpath("fonts", "manifest.json").read_text(encoding="utf-8"))
|
|
54
|
+
return {entry["family"]: entry for entry in manifest.values()}
|
|
52
55
|
|
|
53
56
|
|
|
54
57
|
BUNDLED = _bundled()
|
|
55
58
|
# Typefaces a look may use: what every Mac has, plus the fonts Clipen carries.
|
|
56
59
|
_SYSTEM = {
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
60
|
+
"PingFang TC": "蘋方",
|
|
61
|
+
"Heiti TC": "黑體",
|
|
62
|
+
"Songti TC": "宋體",
|
|
63
|
+
"Hiragino Sans": "冬青黑體",
|
|
64
|
+
"Hiragino Mincho ProN": "冬青明朝",
|
|
65
|
+
"Helvetica Neue": "Helvetica Neue",
|
|
66
|
+
"Avenir Next": "Avenir Next",
|
|
67
|
+
"Futura": "Futura",
|
|
68
|
+
"Gill Sans": "Gill Sans",
|
|
69
|
+
"Optima": "Optima",
|
|
70
|
+
"Didot": "Didot",
|
|
71
|
+
"Baskerville": "Baskerville",
|
|
72
|
+
"Georgia": "Georgia",
|
|
73
|
+
"Rockwell": "Rockwell",
|
|
74
|
+
"Copperplate": "Copperplate",
|
|
75
|
+
"Impact": "Impact",
|
|
76
|
+
"Arial Black": "Arial Black",
|
|
77
|
+
"Chalkduster": "Chalkduster",
|
|
78
|
+
"Marker Felt": "Marker Felt",
|
|
79
|
+
"Noteworthy": "Noteworthy",
|
|
80
|
+
"Menlo": "Menlo",
|
|
61
81
|
}
|
|
62
|
-
FONT_CHOICES = {**{family: entry[
|
|
82
|
+
FONT_CHOICES = {**{family: entry["label"] for family, entry in BUNDLED.items()}, **_SYSTEM}
|
|
63
83
|
# Where a typeface lacks a character (Japanese kana in a Chinese hand, Chinese in a Japanese one,
|
|
64
84
|
# anything in a Latin face) the next face of the same feel draws it, so a line keeps its style.
|
|
65
|
-
_HAND = [
|
|
85
|
+
_HAND = ["Clipen Chenyu", "Yomogi", "Clipen Iansui"]
|
|
66
86
|
FALLBACKS = {
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
87
|
+
"Clipen Chenyu": ["Yomogi", "Clipen Iansui"],
|
|
88
|
+
"Clipen Iansui": [],
|
|
89
|
+
"Yusei Magic": ["Clipen Chenyu", "Clipen Iansui"],
|
|
90
|
+
"Yomogi": ["Clipen Chenyu", "Clipen Iansui"],
|
|
91
|
+
"Zen Kurenaido": ["Clipen Iansui"],
|
|
92
|
+
"Hachi Maru Pop": ["Yomogi", "Clipen Chenyu", "Clipen Iansui"],
|
|
93
|
+
"Dela Gothic One": ["Heiti TC"],
|
|
94
|
+
"RocknRoll One": ["Zen Maru Gothic", "PingFang TC"],
|
|
95
|
+
"Zen Maru Gothic": ["PingFang TC"],
|
|
96
|
+
"Bebas Neue": ["Heiti TC"],
|
|
97
|
+
"Anton": ["Heiti TC"],
|
|
98
|
+
"Caveat": _HAND,
|
|
99
|
+
"Playfair Display": ["Songti TC"],
|
|
100
|
+
"Chalkduster": _HAND,
|
|
101
|
+
"Marker Felt": _HAND,
|
|
102
|
+
"Noteworthy": _HAND,
|
|
103
|
+
"Songti TC": ["Hiragino Mincho ProN"],
|
|
104
|
+
"Hiragino Mincho ProN": ["Songti TC"],
|
|
105
|
+
"Didot": ["Songti TC"],
|
|
106
|
+
"Baskerville": ["Songti TC"],
|
|
107
|
+
"Georgia": ["Songti TC"],
|
|
74
108
|
}
|
|
75
109
|
|
|
76
110
|
|
|
77
111
|
def font_stack(family):
|
|
78
112
|
"""The CSS font list for a typeface: itself, faces of the same feel for missing characters, then PingFang."""
|
|
79
|
-
chain = [family, *FALLBACKS.get(family, []),
|
|
80
|
-
return
|
|
113
|
+
chain = [family, *FALLBACKS.get(family, []), "PingFang TC"]
|
|
114
|
+
return ", ".join(f'"{name}"' for name in dict.fromkeys(chain)) + ", sans-serif"
|
|
81
115
|
|
|
82
116
|
|
|
83
117
|
def look_css(look):
|
|
84
118
|
"""The CSS a look gives a page: --look-font-<key> and --look-<key> variables on :root, with the faces
|
|
85
119
|
Clipen carries declared for every typeface the look may draw with, fallbacks included."""
|
|
86
120
|
if not look:
|
|
87
|
-
return
|
|
88
|
-
used = dict.fromkeys(name for f in look[
|
|
89
|
-
faces =
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
121
|
+
return ""
|
|
122
|
+
used = dict.fromkeys(name for f in look["fonts"] for name in [f["family"], *FALLBACKS.get(f["family"], [])])
|
|
123
|
+
faces = "".join(
|
|
124
|
+
f'@font-face {{ font-family: "{family}"; src: url(https://clipen.local/fonts/{BUNDLED[family]["file"]}); }}\n'
|
|
125
|
+
for family in used
|
|
126
|
+
if family in BUNDLED
|
|
127
|
+
)
|
|
128
|
+
names = [f"--look-font-{f['key']}: {font_stack(f['family'])};" for f in look["fonts"]]
|
|
129
|
+
names += [f"--look-{c['key']}: {c['value']};" for c in look["colors"]]
|
|
130
|
+
return faces + ":root { " + " ".join(names) + " }"
|
|
94
131
|
|
|
95
132
|
|
|
96
133
|
def _key(profile, timeline, duration):
|
|
97
|
-
material = json.dumps(
|
|
98
|
-
|
|
99
|
-
|
|
134
|
+
material = json.dumps(
|
|
135
|
+
[
|
|
136
|
+
profile["html"],
|
|
137
|
+
timeline.width,
|
|
138
|
+
timeline.height,
|
|
139
|
+
timeline.frame_rate.numerator,
|
|
140
|
+
timeline.frame_rate.denominator,
|
|
141
|
+
duration,
|
|
142
|
+
_edits(profile),
|
|
143
|
+
look_css(profile.get("look")),
|
|
144
|
+
],
|
|
145
|
+
ensure_ascii=False,
|
|
146
|
+
sort_keys=True,
|
|
147
|
+
)
|
|
100
148
|
return hashlib.sha256(material.encode()).hexdigest()[:32]
|
|
101
149
|
|
|
102
150
|
|
|
@@ -106,7 +154,7 @@ def _lock(key):
|
|
|
106
154
|
|
|
107
155
|
|
|
108
156
|
class CustomRenderError(TitleRenderError):
|
|
109
|
-
def __init__(self, code, detail=
|
|
157
|
+
def __init__(self, code, detail=""):
|
|
110
158
|
super().__init__(code)
|
|
111
159
|
self.detail = detail
|
|
112
160
|
|
|
@@ -114,74 +162,110 @@ class CustomRenderError(TitleRenderError):
|
|
|
114
162
|
def frames(timeline, item, profile, wanted):
|
|
115
163
|
"""Paths of the requested relative frames, drawing the missing ones in one Chrome run."""
|
|
116
164
|
duration = item.duration_frames
|
|
117
|
-
wanted = sorted({min(max(0, int(n)), duration-1) for n in wanted})
|
|
165
|
+
wanted = sorted({min(max(0, int(n)), duration - 1) for n in wanted})
|
|
118
166
|
key = _key(profile, timeline, duration)
|
|
119
167
|
folder = cache_root() / key
|
|
120
|
-
paths = {n: folder / f
|
|
168
|
+
paths = {n: folder / f"f{n:05d}.png" for n in wanted}
|
|
121
169
|
with _lock(key):
|
|
122
170
|
missing = [n for n, path in paths.items() if not path.is_file()]
|
|
123
171
|
if missing:
|
|
124
172
|
folder.mkdir(parents=True, exist_ok=True)
|
|
125
|
-
job = {
|
|
126
|
-
|
|
127
|
-
|
|
173
|
+
job = {
|
|
174
|
+
"html": profile["html"],
|
|
175
|
+
"width": timeline.width,
|
|
176
|
+
"height": timeline.height,
|
|
177
|
+
"fps": _fps(timeline),
|
|
178
|
+
"duration": duration,
|
|
179
|
+
"frames": missing,
|
|
180
|
+
"out": str(folder),
|
|
181
|
+
"frame_timeout": FRAME_TIMEOUT_SECONDS,
|
|
182
|
+
"edits": _edits(profile),
|
|
183
|
+
"look": look_css(profile.get("look")),
|
|
184
|
+
}
|
|
128
185
|
_run(job, timeout=30 + FRAME_TIMEOUT_SECONDS + len(missing) * 1.5)
|
|
129
186
|
return paths
|
|
130
187
|
|
|
131
188
|
|
|
132
189
|
def fields(timeline, item, profile):
|
|
133
190
|
"""The words and colours the page marked as editable, with the values the design gives them."""
|
|
134
|
-
plain = {key: value for key, value in profile.items() if key !=
|
|
191
|
+
plain = {key: value for key, value in profile.items() if key != "edits"}
|
|
135
192
|
key = _key(plain, timeline, item.duration_frames)
|
|
136
193
|
folder = cache_root() / key
|
|
137
|
-
path = folder /
|
|
194
|
+
path = folder / "fields.json"
|
|
138
195
|
with _lock(key):
|
|
139
196
|
if not path.is_file():
|
|
140
197
|
folder.mkdir(parents=True, exist_ok=True)
|
|
141
|
-
_run(
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
198
|
+
_run(
|
|
199
|
+
{
|
|
200
|
+
"html": profile["html"],
|
|
201
|
+
"width": timeline.width,
|
|
202
|
+
"height": timeline.height,
|
|
203
|
+
"fps": _fps(timeline),
|
|
204
|
+
"duration": item.duration_frames,
|
|
205
|
+
"frames": [],
|
|
206
|
+
"out": str(folder),
|
|
207
|
+
"frame_timeout": FRAME_TIMEOUT_SECONDS,
|
|
208
|
+
"describe": True,
|
|
209
|
+
"look": look_css(profile.get("look")),
|
|
210
|
+
},
|
|
211
|
+
timeout=30 + FRAME_TIMEOUT_SECONDS,
|
|
212
|
+
)
|
|
213
|
+
found = json.loads(path.read_text(encoding="utf-8"))
|
|
145
214
|
# Bounded so a page cannot flood the review panel.
|
|
146
|
-
return {
|
|
147
|
-
|
|
148
|
-
|
|
215
|
+
return {
|
|
216
|
+
"texts": [f for f in found.get("texts", []) if isinstance(f.get("key"), str)][:12],
|
|
217
|
+
"colors": [f for f in found.get("colors", []) if isinstance(f.get("key"), str)][:8],
|
|
218
|
+
"fonts": [f for f in found.get("fonts", []) if isinstance(f, str)][:20],
|
|
219
|
+
}
|
|
149
220
|
|
|
150
221
|
|
|
151
222
|
def check_fonts(timeline, item, profile):
|
|
152
223
|
"""A graphic that uses a look draws its text only in that look's typefaces."""
|
|
153
|
-
look = profile.get(
|
|
224
|
+
look = profile.get("look")
|
|
154
225
|
if not look:
|
|
155
226
|
return
|
|
156
|
-
allowed = {f[
|
|
157
|
-
stray = [family for family in fields(timeline, item, profile)[
|
|
227
|
+
allowed = {f["family"] for f in look["fonts"]}
|
|
228
|
+
stray = [family for family in fields(timeline, item, profile)["fonts"] if family not in allowed]
|
|
158
229
|
if stray:
|
|
159
|
-
raise CustomRenderError(
|
|
230
|
+
raise CustomRenderError("custom_component_font_outside_look", "、".join(stray))
|
|
160
231
|
|
|
161
232
|
|
|
162
233
|
def _run(job, timeout):
|
|
163
|
-
environment = {
|
|
234
|
+
environment = {
|
|
235
|
+
**os.environ,
|
|
236
|
+
"PYTHONPATH": os.pathsep.join(
|
|
237
|
+
filter(None, [str(Path(__file__).resolve().parents[2]), os.environ.get("PYTHONPATH")])
|
|
238
|
+
),
|
|
239
|
+
}
|
|
164
240
|
try:
|
|
165
|
-
finished = subprocess.run(
|
|
166
|
-
|
|
241
|
+
finished = subprocess.run(
|
|
242
|
+
[sys.executable, "-m", "clipen.rendering.custom_render"],
|
|
243
|
+
input=json.dumps(job),
|
|
244
|
+
capture_output=True,
|
|
245
|
+
text=True,
|
|
246
|
+
timeout=timeout,
|
|
247
|
+
env=environment,
|
|
248
|
+
cwd=tempfile.gettempdir(),
|
|
249
|
+
)
|
|
167
250
|
except subprocess.TimeoutExpired:
|
|
168
|
-
raise CustomRenderError(
|
|
251
|
+
raise CustomRenderError("custom_component_frame_timeout") from None
|
|
169
252
|
if finished.returncode != 0:
|
|
170
253
|
try:
|
|
171
254
|
problem = json.loads(finished.stderr.strip().splitlines()[-1])
|
|
172
255
|
except (ValueError, IndexError):
|
|
173
|
-
problem = {
|
|
174
|
-
raise CustomRenderError(problem.get(
|
|
256
|
+
problem = {"code": "custom_component_render_failed", "detail": finished.stderr[-400:]}
|
|
257
|
+
raise CustomRenderError(problem.get("code", "custom_component_render_failed"), problem.get("detail", ""))
|
|
175
258
|
|
|
176
259
|
|
|
177
260
|
def _image(path):
|
|
178
261
|
from PIL import Image
|
|
262
|
+
|
|
179
263
|
with Image.open(path) as image:
|
|
180
|
-
return image.convert(
|
|
264
|
+
return image.convert("RGBA")
|
|
181
265
|
|
|
182
266
|
|
|
183
267
|
def _offset(timeline, profile):
|
|
184
|
-
return round(profile.get(
|
|
268
|
+
return round(profile.get("x", 0) * timeline.width), round(profile.get("y", 0) * timeline.height)
|
|
185
269
|
|
|
186
270
|
|
|
187
271
|
def _resting_frame(item):
|
|
@@ -191,50 +275,54 @@ def _resting_frame(item):
|
|
|
191
275
|
def bounds(timeline, item, profile, relative_frame=None):
|
|
192
276
|
"""Where the graphic draws something, in pixels, after the user's move."""
|
|
193
277
|
frame = _resting_frame(item) if relative_frame is None else relative_frame
|
|
194
|
-
box =
|
|
278
|
+
box = (
|
|
279
|
+
_image(frames(timeline, item, profile, [frame])[min(max(0, frame), item.duration_frames - 1)])
|
|
280
|
+
.getchannel("A")
|
|
281
|
+
.getbbox()
|
|
282
|
+
)
|
|
195
283
|
if box is None:
|
|
196
284
|
return None
|
|
197
285
|
dx, dy = _offset(timeline, profile)
|
|
198
|
-
return (box[0]+dx, box[1]+dy, box[2]+dx, box[3]+dy)
|
|
286
|
+
return (box[0] + dx, box[1] + dy, box[2] + dx, box[3] + dy)
|
|
199
287
|
|
|
200
288
|
|
|
201
289
|
def draw(draw_, timeline, item, profile, relative_frame=None):
|
|
202
|
-
frame = _resting_frame(item) if relative_frame is None else min(max(0, relative_frame), item.duration_frames-1)
|
|
290
|
+
frame = _resting_frame(item) if relative_frame is None else min(max(0, relative_frame), item.duration_frames - 1)
|
|
203
291
|
picture = _image(frames(timeline, item, profile, [frame])[frame])
|
|
204
292
|
dx, dy = _offset(timeline, profile)
|
|
205
293
|
target = draw_._image
|
|
206
294
|
# Crop whatever a move pushed off the picture; alpha_composite takes no negative offsets.
|
|
207
295
|
left, top = max(0, -dx), max(0, -dy)
|
|
208
|
-
right, bottom = min(picture.width, timeline.width-dx), min(picture.height, timeline.height-dy)
|
|
296
|
+
right, bottom = min(picture.width, timeline.width - dx), min(picture.height, timeline.height - dy)
|
|
209
297
|
if right > left and bottom > top:
|
|
210
298
|
piece = picture.crop((left, top, right, bottom))
|
|
211
|
-
if target.mode ==
|
|
212
|
-
target.alpha_composite(piece, dest=(dx+left, dy+top))
|
|
299
|
+
if target.mode == "RGBA":
|
|
300
|
+
target.alpha_composite(piece, dest=(dx + left, dy + top))
|
|
213
301
|
else:
|
|
214
|
-
target.paste(piece, (dx+left, dy+top), piece)
|
|
215
|
-
box = picture.getchannel(
|
|
216
|
-
return None if box is None else (box[0]+dx, box[1]+dy, box[2]+dx, box[3]+dy)
|
|
302
|
+
target.paste(piece, (dx + left, dy + top), piece)
|
|
303
|
+
box = picture.getchannel("A").getbbox()
|
|
304
|
+
return None if box is None else (box[0] + dx, box[1] + dy, box[2] + dx, box[3] + dy)
|
|
217
305
|
|
|
218
306
|
|
|
219
307
|
def changes(timeline, item, profile):
|
|
220
308
|
"""Absolute frames where the picture differs from the frame before, so still stretches cost one image."""
|
|
221
309
|
paths = frames(timeline, item, profile, range(item.duration_frames))
|
|
222
|
-
marks, previous = {item.start_frame, item.start_frame+item.duration_frames}, None
|
|
310
|
+
marks, previous = {item.start_frame, item.start_frame + item.duration_frames}, None
|
|
223
311
|
for n in range(item.duration_frames):
|
|
224
312
|
digest = hashlib.sha256(_image(paths[n]).tobytes()).digest()
|
|
225
313
|
if digest != previous:
|
|
226
|
-
marks.add(item.start_frame+n)
|
|
314
|
+
marks.add(item.start_frame + n)
|
|
227
315
|
previous = digest
|
|
228
316
|
return marks
|
|
229
317
|
|
|
230
318
|
|
|
231
319
|
def check(timeline, item, profile):
|
|
232
320
|
"""Technical checks only: the page loads, runs and draws something at the start, middle and end."""
|
|
233
|
-
if not isinstance(profile.get(
|
|
234
|
-
raise CustomRenderError(
|
|
235
|
-
if len(profile[
|
|
236
|
-
raise CustomRenderError(
|
|
237
|
-
sample = sorted({0, _resting_frame(item), item.duration_frames-1})
|
|
321
|
+
if not isinstance(profile.get("html"), str) or not profile["html"].strip():
|
|
322
|
+
raise CustomRenderError("custom_component_html_missing")
|
|
323
|
+
if len(profile["html"].encode()) > MAX_HTML_BYTES:
|
|
324
|
+
raise CustomRenderError("custom_component_html_too_large")
|
|
325
|
+
sample = sorted({0, _resting_frame(item), item.duration_frames - 1})
|
|
238
326
|
paths = frames(timeline, item, profile, sample)
|
|
239
|
-
if all(_image(paths[n]).getchannel(
|
|
240
|
-
raise CustomRenderError(
|
|
327
|
+
if all(_image(paths[n]).getchannel("A").getbbox() is None for n in sample):
|
|
328
|
+
raise CustomRenderError("custom_component_empty")
|
|
@@ -7,14 +7,20 @@ no network: every request is refused except Clipen's own bundled fonts, served
|
|
|
7
7
|
from ``https://clipen.local/fonts/``. Time is Clipen's to set, so the same frame
|
|
8
8
|
always draws the same picture.
|
|
9
9
|
"""
|
|
10
|
+
|
|
10
11
|
import json
|
|
11
|
-
from importlib.resources import files
|
|
12
12
|
import os
|
|
13
|
-
from pathlib import Path
|
|
14
13
|
import sys
|
|
14
|
+
from importlib.resources import files
|
|
15
|
+
from pathlib import Path
|
|
15
16
|
|
|
16
|
-
FONT_ORIGIN =
|
|
17
|
-
FONTS = {
|
|
17
|
+
FONT_ORIGIN = "https://clipen.local/fonts/"
|
|
18
|
+
FONTS = {
|
|
19
|
+
entry["file"]
|
|
20
|
+
for entry in json.loads(
|
|
21
|
+
files("clipen.rendering").joinpath("fonts", "manifest.json").read_text(encoding="utf-8")
|
|
22
|
+
).values()
|
|
23
|
+
}
|
|
18
24
|
|
|
19
25
|
# Runs before the page's own scripts: a fixed clock and random sequence.
|
|
20
26
|
_PRELUDE = """
|
|
@@ -111,87 +117,102 @@ async ([frame, fps]) => {
|
|
|
111
117
|
"""
|
|
112
118
|
|
|
113
119
|
|
|
114
|
-
def fail(code, detail=
|
|
115
|
-
sys.stderr.write(json.dumps({
|
|
120
|
+
def fail(code, detail=""):
|
|
121
|
+
sys.stderr.write(json.dumps({"code": code, "detail": detail[:400]}, ensure_ascii=False))
|
|
116
122
|
sys.exit(2)
|
|
117
123
|
|
|
118
124
|
|
|
119
125
|
def _browser(playwright):
|
|
120
126
|
errors = []
|
|
121
|
-
for options in ({
|
|
127
|
+
for options in ({"channel": "chrome"}, {}):
|
|
122
128
|
try:
|
|
123
|
-
return playwright.chromium.launch(headless=True, args=[
|
|
129
|
+
return playwright.chromium.launch(headless=True, args=["--disable-gpu", "--no-first-run"], **options)
|
|
124
130
|
except Exception as error: # Chrome may be missing; try the bundled build next.
|
|
125
131
|
errors.append(str(error).splitlines()[0])
|
|
126
|
-
fail(
|
|
132
|
+
fail("custom_component_renderer_missing", " / ".join(errors))
|
|
127
133
|
|
|
128
134
|
|
|
129
|
-
PAGE =
|
|
135
|
+
PAGE = "https://clipen.local/component.html"
|
|
130
136
|
|
|
131
137
|
|
|
132
138
|
def _route(route, html):
|
|
133
139
|
url = route.request.url
|
|
134
140
|
if url == PAGE:
|
|
135
|
-
return route.fulfill(status=200, body=html, headers={
|
|
136
|
-
if url.startswith(FONT_ORIGIN) and url[len(FONT_ORIGIN):] in FONTS:
|
|
137
|
-
path = Path(str(files(
|
|
138
|
-
return route.fulfill(
|
|
141
|
+
return route.fulfill(status=200, body=html, headers={"content-type": "text/html; charset=utf-8"})
|
|
142
|
+
if url.startswith(FONT_ORIGIN) and url[len(FONT_ORIGIN) :] in FONTS:
|
|
143
|
+
path = Path(str(files("clipen.rendering").joinpath("fonts", url[len(FONT_ORIGIN) :])))
|
|
144
|
+
return route.fulfill(
|
|
145
|
+
status=200, body=path.read_bytes(), headers={"content-type": "font/ttf", "access-control-allow-origin": "*"}
|
|
146
|
+
)
|
|
139
147
|
return route.abort()
|
|
140
148
|
|
|
141
149
|
|
|
142
150
|
def render(job):
|
|
143
151
|
from playwright.sync_api import Error, TimeoutError, sync_playwright
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
152
|
+
|
|
153
|
+
out = Path(job["out"])
|
|
154
|
+
width, height, fps = int(job["width"]), int(job["height"]), float(job["fps"])
|
|
155
|
+
info = {"width": width, "height": height, "fps": fps, "durationFrames": int(job["duration"])}
|
|
147
156
|
with sync_playwright() as playwright:
|
|
148
157
|
browser = _browser(playwright)
|
|
149
158
|
try:
|
|
150
159
|
# A fresh context is a fresh, throw-away profile: nothing of the user's Chrome is visible.
|
|
151
|
-
context = browser.new_context(
|
|
152
|
-
|
|
153
|
-
|
|
160
|
+
context = browser.new_context(
|
|
161
|
+
viewport={"width": width, "height": height},
|
|
162
|
+
device_scale_factor=1,
|
|
163
|
+
java_script_enabled=True,
|
|
164
|
+
offline=False,
|
|
165
|
+
service_workers="block",
|
|
166
|
+
)
|
|
167
|
+
context.route("**/*", lambda route: _route(route, job["html"]))
|
|
154
168
|
page = context.new_page()
|
|
155
|
-
page.set_default_timeout(float(job.get(
|
|
169
|
+
page.set_default_timeout(float(job.get("frame_timeout", 10)) * 1000)
|
|
156
170
|
problems = []
|
|
157
|
-
page.on(
|
|
158
|
-
page.add_init_script(
|
|
159
|
-
|
|
171
|
+
page.on("pageerror", lambda error: problems.append(str(error)))
|
|
172
|
+
page.add_init_script(
|
|
173
|
+
_PRELUDE.replace("__INFO__", json.dumps(info))
|
|
174
|
+
.replace("__EDITS__", json.dumps(job.get("edits") or {}, ensure_ascii=False))
|
|
175
|
+
.replace("__LOOK__", json.dumps(job.get("look") or "", ensure_ascii=False))
|
|
176
|
+
)
|
|
160
177
|
try:
|
|
161
|
-
page.goto(PAGE, wait_until=
|
|
162
|
-
page.evaluate(
|
|
178
|
+
page.goto(PAGE, wait_until="load")
|
|
179
|
+
page.evaluate("document.fonts.ready.then(() => true)")
|
|
163
180
|
# A picture the sealed page could not fetch is hidden instead of drawn as a broken icon.
|
|
164
|
-
page.evaluate(
|
|
181
|
+
page.evaluate(
|
|
182
|
+
"document.querySelectorAll('img').forEach((i) => { if (!i.complete || !i.naturalWidth) i.style.visibility = 'hidden' })"
|
|
183
|
+
)
|
|
165
184
|
except TimeoutError:
|
|
166
|
-
fail(
|
|
185
|
+
fail("custom_component_load_timeout")
|
|
167
186
|
except Error as error:
|
|
168
|
-
fail(
|
|
169
|
-
if job.get(
|
|
170
|
-
(out /
|
|
171
|
-
|
|
187
|
+
fail("custom_component_load_failed", str(error))
|
|
188
|
+
if job.get("describe"):
|
|
189
|
+
(out / "fields.json").write_text(
|
|
190
|
+
json.dumps(page.evaluate(_FIELDS), ensure_ascii=False), encoding="utf-8"
|
|
191
|
+
)
|
|
192
|
+
for frame in job["frames"]:
|
|
172
193
|
try:
|
|
173
194
|
page.evaluate(_SEEK, [int(frame), fps])
|
|
174
195
|
if problems:
|
|
175
|
-
fail(
|
|
176
|
-
data = page.screenshot(omit_background=True, type=
|
|
196
|
+
fail("custom_component_script_error", problems[0])
|
|
197
|
+
data = page.screenshot(omit_background=True, type="png", animations="allow")
|
|
177
198
|
except TimeoutError:
|
|
178
|
-
fail(
|
|
199
|
+
fail("custom_component_frame_timeout", f"frame {frame}")
|
|
179
200
|
except Error as error:
|
|
180
|
-
fail(
|
|
181
|
-
target = out / f
|
|
182
|
-
temporary = target.with_suffix(
|
|
201
|
+
fail("custom_component_script_error", problems[0] if problems else str(error))
|
|
202
|
+
target = out / f"f{int(frame):05d}.png"
|
|
203
|
+
temporary = target.with_suffix(".part")
|
|
183
204
|
temporary.write_bytes(data)
|
|
184
205
|
os.replace(temporary, target)
|
|
185
206
|
finally:
|
|
186
207
|
browser.close()
|
|
187
208
|
|
|
188
209
|
|
|
189
|
-
if __name__ ==
|
|
210
|
+
if __name__ == "__main__":
|
|
190
211
|
try:
|
|
191
212
|
render(json.load(sys.stdin))
|
|
192
213
|
except SystemExit:
|
|
193
214
|
raise
|
|
194
215
|
except ImportError as error:
|
|
195
|
-
fail(
|
|
216
|
+
fail("custom_component_renderer_missing", str(error))
|
|
196
217
|
except Exception as error:
|
|
197
|
-
fail(
|
|
218
|
+
fail("custom_component_render_failed", f"{type(error).__name__}: {error}")
|