@clipen/clipen-cli 1.0.8 → 1.0.9
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 +13 -4
- package/apps/web/dist/assets/index-DPgSvXZ1.js +15 -0
- package/apps/web/dist/assets/index-DmPWV61v.css +1 -0
- package/apps/web/dist/index.html +2 -2
- package/bin/clipen.js +6 -15
- package/package.json +1 -1
- package/pyproject.toml +1 -1
- package/src/clipen/__init__.py +1 -1
- package/src/clipen/bootstrap.py +130 -23
- package/src/clipen/controller/app.py +83 -21
- package/src/clipen/controller/server.py +5 -0
- package/src/clipen/editing/agent_tools.py +1 -1
- package/src/clipen/editing/caption_design.py +134 -0
- package/src/clipen/editing/component_looks.py +3 -3
- package/src/clipen/editing/component_review.py +0 -38
- package/src/clipen/editing/coordinator.py +14 -0
- package/src/clipen/editing/production_catalog.py +67 -13
- package/src/clipen/editing/production_media.py +13 -2
- package/src/clipen/editing/production_preview.py +11 -9
- package/src/clipen/editing/production_progress.py +2 -0
- package/src/clipen/editing/production_tools.py +11 -20
- package/src/clipen/editing/program_subtitles.py +5 -13
- package/src/clipen/editing/resolve_export.py +2 -183
- package/src/clipen/editing/skill_tools.py +142 -218
- package/src/clipen/editing/tool_receipts.py +2 -1
- package/src/clipen/editing/versions.py +2 -0
- package/src/clipen/editing/visual_preview.py +62 -0
- package/src/clipen/editing/workbench.py +21 -1
- package/src/clipen/locale_en.py +18 -0
- package/src/clipen/media/storage.py +2 -2
- package/src/clipen/own_ffmpeg.py +113 -0
- package/src/clipen/providers/editing_agent.py +6 -4
- package/src/clipen/rendering/custom_components.py +216 -25
- package/src/clipen/rendering/custom_render.py +90 -54
- package/src/clipen/rendering/fetched_fonts.py +127 -0
- package/src/clipen/rendering/production_effects.py +24 -2
- package/src/clipen/rendering/program_components.py +18 -240
- package/src/clipen/rendering/renderer.py +23 -17
- package/src/clipen/rendering/titles.py +29 -12
- package/src/clipen/skills/builtin/SKILL.md +3 -3
- 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-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/references/captions.md +12 -0
- package/src/clipen/skills/builtin/references/graphics.md +6 -5
- package/src/clipen/skills/builtin/template-skills/clipen-daily-vlog/SKILL.md +9 -4
- package/src/clipen/skills/builtin/template-skills/clipen-event-recap/SKILL.md +10 -5
- package/src/clipen/skills/builtin/template-skills/clipen-food-review/SKILL.md +9 -4
- package/src/clipen/skills/builtin/template-skills/clipen-product-demo/SKILL.md +10 -6
- package/src/clipen/skills/builtin/template-skills/clipen-product-review/SKILL.md +10 -6
- package/src/clipen/skills/builtin/template-skills/clipen-product-unboxing/SKILL.md +9 -7
- package/src/clipen/skills/builtin/template-skills/clipen-shorts-highlight/SKILL.md +10 -5
- package/src/clipen/skills/builtin/template-skills/clipen-travel-highlight/SKILL.md +10 -5
- package/src/clipen/skills/builtin/template-skills/clipen-travel-vlog/SKILL.md +10 -7
- package/src/clipen/skills/catalog.py +0 -8
- package/src/clipen/skills/package.py +1 -10
- package/apps/web/dist/assets/index-CJ80KHsQ.css +0 -1
- package/apps/web/dist/assets/index-C_4u_hVf.js +0 -16
- package/src/clipen/editing/resolve_titles.py +0 -291
- package/src/clipen/rendering/program_creator.py +0 -804
- package/src/clipen/rendering/program_identities.py +0 -350
- package/src/clipen/rendering/program_motion.py +0 -186
- package/src/clipen/rendering/program_studio.py +0 -227
- package/src/clipen/rendering/program_styles.py +0 -321
- package/src/clipen/skills/builtin/components.json +0 -133
package/src/clipen/locale_en.py
CHANGED
|
@@ -265,6 +265,8 @@ MESSAGES = {
|
|
|
265
265
|
"混音片段超出影片或來源長度。": "An audio piece runs past the film or its source.",
|
|
266
266
|
# editing/production_preview.py
|
|
267
267
|
"請先使用 validate_sequence 修正時間軸。": "Fix the timeline with validate_sequence first.",
|
|
268
|
+
"這一版用到的配樂或音效找不到了,請重新選一首配樂再輸出。": "The music or sound effects in this version are missing; pick the music again, then render.",
|
|
269
|
+
"這一版有地方需要修正才能輸出,請交給 AI 修改,或回到上一個版本。": "This version needs fixing before it can render; hand it to AI, or go back to an earlier version.",
|
|
268
270
|
"預覽不屬於這次剪輯。": "That preview belongs to another edit.",
|
|
269
271
|
"預覽檔案已遺失或變更。": "The preview file is missing or changed.",
|
|
270
272
|
"檢視時間超出預覽範圍。": "That time is outside the preview.",
|
|
@@ -363,6 +365,21 @@ MESSAGES = {
|
|
|
363
365
|
"預覽時間不在影片內。": "That time is outside the film.",
|
|
364
366
|
"這個時間沒有畫面片段。": "There is no shot at this time.",
|
|
365
367
|
"找不到預覽字型。": "The preview font was not found.",
|
|
368
|
+
"先輸出一次這一版影片,才能看動態預覽。": "Render this version once to see the graphic moving.",
|
|
369
|
+
"這個元件不能在瀏覽器即時播放。": "This graphic cannot play live in the browser.",
|
|
370
|
+
"先用 set_caption_design 設計字幕的樣子,再建立字幕。": "Design how captions look with set_caption_design before making them.",
|
|
371
|
+
"字幕頁面要有一個標了 data-clipen-caption 的元素,Clipen 會把每句字幕放進去。": "The caption page needs one element marked data-clipen-caption; Clipen puts each caption into it.",
|
|
372
|
+
"沒有這個外觀;先用 set_component_look 建立字幕用的外觀,或從 list_program_components 的 looks 選一個。": "There is no such look. Create one for captions with set_component_look, or pick one from the looks in list_program_components.",
|
|
373
|
+
"字幕設計檔案不安全。": "The caption design file is not safe.",
|
|
374
|
+
"找不到這句字幕,影片可能已經更新,請重新讀取。": "This caption is gone; the film may have changed. Reload.",
|
|
375
|
+
"字幕要是一行、1–80 個字。": "A caption is one line of 1 to 80 characters.",
|
|
376
|
+
"語氣只能是一般對話、重點句或小聲帶過。": "Delivery is dialogue, punchline or quiet.",
|
|
377
|
+
"強調的字要是字串清單。": "Emphasised words must be a list of text.",
|
|
378
|
+
"字幕設定格式不正確。": "The caption settings are not valid.",
|
|
379
|
+
"沒有這個字幕設計;用 set_caption_design 回傳的 design_id。": "There is no such caption design. Use a design_id set_caption_design returned.",
|
|
380
|
+
"這句字幕不是 AI 設計的樣式,不能即時播放。": "This caption is not drawn by the AI's design, so it cannot play live.",
|
|
381
|
+
"這個元件用的是已停用的內建模板,不能再修改;刪掉它,或請 AI 重新設計一個。": "This graphic uses a retired built-in template and can no longer be changed. Delete it, or ask the AI to design a new one.",
|
|
382
|
+
"找不到這個項目。": "Not found.",
|
|
366
383
|
"來源沒有指定的影像串流。": "The source has no such video stream.",
|
|
367
384
|
"文字超出版面或無法顯示,請縮短文字或調整位置。": "The text runs off the frame or cannot be drawn. Shorten it or move it.",
|
|
368
385
|
# editing/workbench.py
|
|
@@ -525,4 +542,5 @@ PATTERNS = (
|
|
|
525
542
|
"Downloading and installing speech recognition packages ({0}/{1})…",
|
|
526
543
|
),
|
|
527
544
|
(re.compile(r"畫自由設計元件 (\d+)/(\d+)"), "Drawing custom graphic {0}/{1}"),
|
|
545
|
+
(re.compile(r"畫字幕 (\d+) 句"), "Drawing {0} captions"),
|
|
528
546
|
)
|
|
@@ -119,7 +119,7 @@ class InventoryRepository:
|
|
|
119
119
|
status_code=409,
|
|
120
120
|
)
|
|
121
121
|
rows = connection.execute(
|
|
122
|
-
"SELECT role, canonical_path, device, inode, saved_at FROM project_directories
|
|
122
|
+
"SELECT role, canonical_path, device, inode, saved_at FROM project_directories WHERE role = 'source'"
|
|
123
123
|
).fetchall()
|
|
124
124
|
roots = tuple(
|
|
125
125
|
InventoryRoot(
|
|
@@ -399,7 +399,7 @@ class InventoryRepository:
|
|
|
399
399
|
status_code=409,
|
|
400
400
|
)
|
|
401
401
|
root_rows = connection.execute(
|
|
402
|
-
"SELECT role, canonical_path, device, inode, saved_at FROM project_directories
|
|
402
|
+
"SELECT role, canonical_path, device, inode, saved_at FROM project_directories WHERE role = 'source'"
|
|
403
403
|
).fetchall()
|
|
404
404
|
current_roots = tuple(
|
|
405
405
|
InventoryRoot(
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
"""Clipen's own ffmpeg, for a Mac that has none: a fixed static build, downloaded and checked into
|
|
2
|
+
Clipen's folder. It is put on the PATH of Clipen's own processes only, never on the person's shell,
|
|
3
|
+
so an ffmpeg they install later is left alone."""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import hashlib
|
|
8
|
+
import os
|
|
9
|
+
import shutil
|
|
10
|
+
import uuid
|
|
11
|
+
import zipfile
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import Callable, Mapping
|
|
14
|
+
from urllib.request import Request, urlopen
|
|
15
|
+
|
|
16
|
+
from clipen.i18n import tr
|
|
17
|
+
|
|
18
|
+
VERSION = "9.1-1795207104"
|
|
19
|
+
_SOURCE = "https://ffmpeg.martin-riedl.de/download/macos/arm64/1795207104_9.1"
|
|
20
|
+
# Each tool: its archive's size and SHA-256, as published beside the archive.
|
|
21
|
+
TOOLS = {
|
|
22
|
+
"ffmpeg": (28_623_086, "1f66e9a690a7f1c9e60b012379f8869c11818d1797f45b21dbb2f2564ba61ae1"),
|
|
23
|
+
"ffprobe": (28_541_295, "6ef2df5f575042923a28537ab37adf936f28bf3e7b85de23a1447ed447ec1dbd"),
|
|
24
|
+
}
|
|
25
|
+
DOWNLOAD_BYTES = sum(size for size, _ in TOOLS.values())
|
|
26
|
+
# The unpacked tools; nothing larger is accepted from an archive.
|
|
27
|
+
_MAX_TOOL_BYTES = 200_000_000
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class FfmpegUnavailable(RuntimeError):
|
|
31
|
+
pass
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def folder(data_root: Path) -> Path:
|
|
35
|
+
return data_root / "ffmpeg" / VERSION
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def installed(data_root: Path) -> Path | None:
|
|
39
|
+
"""The folder holding Clipen's own ffmpeg and ffprobe, once they are in place."""
|
|
40
|
+
root = folder(data_root)
|
|
41
|
+
return root if all((root / name).is_file() for name in TOOLS) else None
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def needed(data_root: Path, environment: Mapping[str, str]) -> bool:
|
|
45
|
+
"""Whether Clipen must fetch its own: the Mac has no ffmpeg and ffprobe, and Clipen has none yet."""
|
|
46
|
+
if installed(data_root) is not None:
|
|
47
|
+
return False
|
|
48
|
+
path = environment.get("PATH", os.defpath)
|
|
49
|
+
return not all(shutil.which(name, path=path) for name in TOOLS)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def on_path(data_root: Path, environment: Mapping[str, str]) -> dict[str, str]:
|
|
53
|
+
"""The environment with Clipen's own ffmpeg first on PATH, when Clipen has one."""
|
|
54
|
+
root = installed(data_root)
|
|
55
|
+
if root is None:
|
|
56
|
+
return dict(environment)
|
|
57
|
+
return {**environment, "PATH": f"{root}{os.pathsep}{environment.get('PATH', os.defpath)}"}
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def install(data_root: Path, on_progress: Callable[[int, int], None] = lambda done, total: None) -> Path:
|
|
61
|
+
"""Download, check and unpack both tools; nothing unchecked is ever kept."""
|
|
62
|
+
target = folder(data_root)
|
|
63
|
+
if installed(data_root) is not None:
|
|
64
|
+
return target
|
|
65
|
+
target.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
66
|
+
staging = target.parent / f".{VERSION}.staging-{uuid.uuid4().hex}"
|
|
67
|
+
staging.mkdir(mode=0o700)
|
|
68
|
+
done = 0
|
|
69
|
+
try:
|
|
70
|
+
for name, (size, sha256) in TOOLS.items():
|
|
71
|
+
archive = staging / f"{name}.zip"
|
|
72
|
+
digest = hashlib.sha256()
|
|
73
|
+
request = Request(f"{_SOURCE}/{name}.zip", headers={"User-Agent": "Clipen"})
|
|
74
|
+
try:
|
|
75
|
+
with urlopen(request, timeout=30) as response, archive.open("xb") as output:
|
|
76
|
+
while block := response.read(1024 * 1024):
|
|
77
|
+
if output.tell() + len(block) > size:
|
|
78
|
+
raise FfmpegUnavailable(
|
|
79
|
+
tr("ffmpeg 下載的檔案比預期大。", "The ffmpeg download is larger than expected.")
|
|
80
|
+
)
|
|
81
|
+
digest.update(block)
|
|
82
|
+
output.write(block)
|
|
83
|
+
done += len(block)
|
|
84
|
+
on_progress(done, DOWNLOAD_BYTES)
|
|
85
|
+
except OSError as error:
|
|
86
|
+
raise FfmpegUnavailable(
|
|
87
|
+
tr(
|
|
88
|
+
"無法下載 ffmpeg,請確認網路後再試。",
|
|
89
|
+
"Could not download ffmpeg; check your connection and try again.",
|
|
90
|
+
)
|
|
91
|
+
) from error
|
|
92
|
+
if archive.stat().st_size != size or digest.hexdigest() != sha256:
|
|
93
|
+
raise FfmpegUnavailable(
|
|
94
|
+
tr(
|
|
95
|
+
"ffmpeg 的檢查碼不符,已刪除下載的檔案;請稍後再試或回報問題。",
|
|
96
|
+
"ffmpeg failed its checksum and was deleted; try again later or report the problem.",
|
|
97
|
+
)
|
|
98
|
+
)
|
|
99
|
+
with zipfile.ZipFile(archive) as bundle:
|
|
100
|
+
member = bundle.getinfo(name)
|
|
101
|
+
if member.file_size > _MAX_TOOL_BYTES:
|
|
102
|
+
raise FfmpegUnavailable(
|
|
103
|
+
tr("ffmpeg 解壓縮後的檔案太大。", "The unpacked ffmpeg is larger than expected.")
|
|
104
|
+
)
|
|
105
|
+
with bundle.open(member) as source, (staging / name).open("xb") as output:
|
|
106
|
+
shutil.copyfileobj(source, output)
|
|
107
|
+
(staging / name).chmod(0o755)
|
|
108
|
+
archive.unlink()
|
|
109
|
+
staging.rename(target)
|
|
110
|
+
except BaseException:
|
|
111
|
+
shutil.rmtree(staging, ignore_errors=True)
|
|
112
|
+
raise
|
|
113
|
+
return target
|
|
@@ -124,13 +124,15 @@ and continue it; do not discard a retained draft after an interrupted attempt. D
|
|
|
124
124
|
You choose when and how to call tools; no fixed shot/effect quota or scripted sequence.
|
|
125
125
|
Before graphics, read references/graphics.md and list_program_components. Design every
|
|
126
126
|
graphic yourself with add_custom_component (any HTML/CSS/SVG/JS); there are no built-in
|
|
127
|
-
templates. Plan the visual hierarchy of opening, segment changes and key moments.
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
127
|
+
templates. Plan the visual hierarchy of opening, segment changes and key moments. Use any
|
|
128
|
+
typeface by name: fonts installed on this Mac, the ones Clipen carries, or any open Google
|
|
129
|
+
Fonts family after get_font. Looks (set_component_look) are optional, to keep one kind of
|
|
130
|
+
graphic consistent. A full-picture graphic across a cut is a transition of your own design. Mark the main words and colours so people
|
|
131
131
|
can change them themselves, look at each returned still, and protect faces and subtitles.
|
|
132
132
|
Search licensed public music, arrange it, preserve natural sound and source credits.
|
|
133
133
|
Metadata/measurements are not listening and stills are not continuous-motion review.
|
|
134
|
+
Design how captions look yourself with set_caption_design (one page, filled with each
|
|
135
|
+
caption) before replace_subtitles; there is no built-in caption style.
|
|
134
136
|
Repair timing uncertainty rather than claiming estimated subtitles are aligned.
|
|
135
137
|
Render exact revisions, inspect actual results, revise specific failures. Local cut
|
|
136
138
|
tools preserve unaffected post-production; inspect any dependencies they invalidate.
|
|
@@ -21,7 +21,7 @@ from pathlib import Path
|
|
|
21
21
|
|
|
22
22
|
from .titles import TitleRenderError
|
|
23
23
|
|
|
24
|
-
MAX_HTML_BYTES =
|
|
24
|
+
MAX_HTML_BYTES = 2_000_000
|
|
25
25
|
FRAME_TIMEOUT_SECONDS = 10
|
|
26
26
|
CUSTOM = "custom"
|
|
27
27
|
_locks = {}
|
|
@@ -47,7 +47,10 @@ def _fps(timeline):
|
|
|
47
47
|
|
|
48
48
|
def _edits(profile):
|
|
49
49
|
edits = profile.get("edits") or {}
|
|
50
|
-
|
|
50
|
+
result = {kind: dict(sorted((edits.get(kind) or {}).items())) for kind in ("texts", "colors") if edits.get(kind)}
|
|
51
|
+
if edits.get("caption"):
|
|
52
|
+
result["caption"] = edits["caption"]
|
|
53
|
+
return result
|
|
51
54
|
|
|
52
55
|
|
|
53
56
|
def _bundled():
|
|
@@ -215,19 +218,24 @@ def one_face(role, shown):
|
|
|
215
218
|
|
|
216
219
|
|
|
217
220
|
def look_css(look):
|
|
218
|
-
"""The CSS a look gives a page: --look-font-<key> and --look-<key> variables on :root
|
|
219
|
-
Clipen carries declared for every typeface the look may draw with, fallbacks included."""
|
|
221
|
+
"""The CSS a look gives a page: --look-font-<key> and --look-<key> variables on :root."""
|
|
220
222
|
if not look:
|
|
221
223
|
return ""
|
|
222
|
-
used = dict.fromkeys(name for f in look["fonts"] for name in [f["family"], *FALLBACKS.get(f["family"], [])])
|
|
223
|
-
faces = "".join(
|
|
224
|
-
f'@font-face {{ font-family: "{family}"; src: url(https://clipen.local/fonts/{BUNDLED[family]["file"]}); }}\n'
|
|
225
|
-
for family in used
|
|
226
|
-
if family in BUNDLED
|
|
227
|
-
)
|
|
228
224
|
names = [f"--look-font-{f['key']}: {font_stack(f['family'])};" for f in look["fonts"]]
|
|
229
225
|
names += [f"--look-{c['key']}: {c['value']};" for c in look["colors"]]
|
|
230
|
-
return
|
|
226
|
+
return ":root { " + " ".join(names) + " }"
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def page_css(look):
|
|
230
|
+
"""Every font a page may draw with, by name: the ones Clipen carries and the ones the AI fetched,
|
|
231
|
+
then the look's variables if the page uses a look. Faces load only when a page uses them."""
|
|
232
|
+
from .fetched_fonts import faces_css
|
|
233
|
+
|
|
234
|
+
carried = "".join(
|
|
235
|
+
f'@font-face {{ font-family: "{family}"; src: url(https://clipen.local/fonts/{entry["file"]}); }}\n'
|
|
236
|
+
for family, entry in BUNDLED.items()
|
|
237
|
+
)
|
|
238
|
+
return carried + faces_css() + look_css(look)
|
|
231
239
|
|
|
232
240
|
|
|
233
241
|
def _key(profile, timeline, duration):
|
|
@@ -240,7 +248,7 @@ def _key(profile, timeline, duration):
|
|
|
240
248
|
timeline.frame_rate.denominator,
|
|
241
249
|
duration,
|
|
242
250
|
_edits(profile),
|
|
243
|
-
|
|
251
|
+
page_css(profile.get("look")),
|
|
244
252
|
# Bumped when the way a role picks one face changes, so old frames are drawn again.
|
|
245
253
|
"one-face-1",
|
|
246
254
|
],
|
|
@@ -282,7 +290,7 @@ def frames(timeline, item, profile, wanted, cancel=None):
|
|
|
282
290
|
"out": str(folder),
|
|
283
291
|
"frame_timeout": FRAME_TIMEOUT_SECONDS,
|
|
284
292
|
"edits": _edits(profile),
|
|
285
|
-
"look":
|
|
293
|
+
"look": page_css(profile.get("look")),
|
|
286
294
|
"faces": face_plan(profile),
|
|
287
295
|
}
|
|
288
296
|
_run(job, timeout=30 + FRAME_TIMEOUT_SECONDS + len(missing) * 1.5, cancel=cancel)
|
|
@@ -309,7 +317,7 @@ def fields(timeline, item, profile):
|
|
|
309
317
|
"out": str(folder),
|
|
310
318
|
"frame_timeout": FRAME_TIMEOUT_SECONDS,
|
|
311
319
|
"describe": True,
|
|
312
|
-
"look":
|
|
320
|
+
"look": page_css(profile.get("look")),
|
|
313
321
|
},
|
|
314
322
|
timeout=30 + FRAME_TIMEOUT_SECONDS,
|
|
315
323
|
)
|
|
@@ -322,19 +330,11 @@ def fields(timeline, item, profile):
|
|
|
322
330
|
}
|
|
323
331
|
|
|
324
332
|
|
|
325
|
-
def check_fonts(timeline, item, profile):
|
|
326
|
-
"""A graphic that uses a look draws its text only in that look's typefaces."""
|
|
327
|
-
look = profile.get("look")
|
|
328
|
-
if not look:
|
|
329
|
-
return
|
|
330
|
-
allowed = {f["family"] for f in look["fonts"]}
|
|
331
|
-
stray = [family for family in fields(timeline, item, profile)["fonts"] if family not in allowed]
|
|
332
|
-
if stray:
|
|
333
|
-
raise CustomRenderError("custom_component_font_outside_look", "、".join(stray))
|
|
334
|
-
|
|
335
|
-
|
|
336
333
|
def _run(job, timeout, cancel=None):
|
|
337
334
|
"""Draws in a child Chrome run; a cancelled render stops it instead of waiting for every frame."""
|
|
335
|
+
from .fetched_fonts import root
|
|
336
|
+
|
|
337
|
+
job = {**job, "fetched_fonts": str(root())}
|
|
338
338
|
environment = {
|
|
339
339
|
**os.environ,
|
|
340
340
|
"PYTHONPATH": os.pathsep.join(
|
|
@@ -447,3 +447,194 @@ def check(timeline, item, profile):
|
|
|
447
447
|
paths = frames(timeline, item, profile, sample)
|
|
448
448
|
if all(_image(paths[n]).getchannel("A").getbbox() is None for n in sample):
|
|
449
449
|
raise CustomRenderError("custom_component_empty")
|
|
450
|
+
|
|
451
|
+
|
|
452
|
+
# Where the person's browser loads the fonts Clipen carries, for a design playing live on the page.
|
|
453
|
+
LIVE_FONTS = "/component-fonts/"
|
|
454
|
+
|
|
455
|
+
# Lets the page that embeds a live design set its frame, as Chrome does when drawing the film, and
|
|
456
|
+
# reports where the design draws so the page can offer a box to drag.
|
|
457
|
+
_LIVE = """
|
|
458
|
+
<script>
|
|
459
|
+
(() => {
|
|
460
|
+
const seek = __SEEK__;
|
|
461
|
+
const measure = () => {
|
|
462
|
+
const vw = innerWidth, vh = innerHeight;
|
|
463
|
+
let l = Infinity, t = Infinity, r = -Infinity, b = -Infinity;
|
|
464
|
+
document.querySelectorAll('body *').forEach((el) => {
|
|
465
|
+
const s = getComputedStyle(el);
|
|
466
|
+
if (s.display === 'none' || s.visibility === 'hidden' || parseFloat(s.opacity) === 0) return;
|
|
467
|
+
const text = Array.from(el.childNodes).some((n) => n.nodeType === 3 && n.textContent.trim());
|
|
468
|
+
const media = ['IMG', 'CANVAS', 'svg', 'SVG', 'VIDEO'].includes(el.tagName);
|
|
469
|
+
const paint = !/^(transparent|rgba\\(.*,\\s*0\\))$/.test(s.backgroundColor) || s.backgroundImage !== 'none' || parseFloat(s.borderTopWidth) > 0 || parseFloat(s.borderBottomWidth) > 0;
|
|
470
|
+
if (!text && !media && !paint) return;
|
|
471
|
+
const box = el.getBoundingClientRect();
|
|
472
|
+
if (box.width < 1 || box.height < 1 || (box.width >= vw * 0.98 && box.height >= vh * 0.98)) return;
|
|
473
|
+
l = Math.min(l, box.left); t = Math.min(t, box.top); r = Math.max(r, box.right); b = Math.max(b, box.bottom);
|
|
474
|
+
});
|
|
475
|
+
return l === Infinity ? null : { x: l / vw, y: t / vh, width: (r - l) / vw, height: (b - t) / vh };
|
|
476
|
+
};
|
|
477
|
+
addEventListener('message', async (event) => {
|
|
478
|
+
if (event.source !== parent || !event.data || typeof event.data.frame !== 'number') return;
|
|
479
|
+
await seek([event.data.frame, event.data.fps]);
|
|
480
|
+
parent.postMessage({ clipenFrame: event.data.frame, box: measure() }, '*');
|
|
481
|
+
});
|
|
482
|
+
addEventListener('load', () => document.fonts.ready.then(() => parent.postMessage({ clipenReady: true }, '*')));
|
|
483
|
+
})();
|
|
484
|
+
</script>
|
|
485
|
+
"""
|
|
486
|
+
|
|
487
|
+
|
|
488
|
+
def live_page(timeline, item, profile):
|
|
489
|
+
"""The design as a page the person's browser plays, with the same clock, words, colours and look as the film."""
|
|
490
|
+
from .custom_render import _PRELUDE, _SEEK
|
|
491
|
+
|
|
492
|
+
def safe(value):
|
|
493
|
+
# Kept inside a <script>, so nothing typed can close it.
|
|
494
|
+
return json.dumps(value, ensure_ascii=False).replace("</", "<\\/")
|
|
495
|
+
|
|
496
|
+
info = {
|
|
497
|
+
"width": timeline.width,
|
|
498
|
+
"height": timeline.height,
|
|
499
|
+
"fps": _fps(timeline),
|
|
500
|
+
"durationFrames": item.duration_frames,
|
|
501
|
+
}
|
|
502
|
+
prelude = (
|
|
503
|
+
_PRELUDE.replace("__INFO__", safe(info))
|
|
504
|
+
.replace("__EDITS__", safe(_edits(profile)))
|
|
505
|
+
.replace("__LOOK__", safe(page_css(profile.get("look"))))
|
|
506
|
+
)
|
|
507
|
+
head = "<script>" + prelude + "</script>" + _LIVE.replace("__SEEK__", _SEEK.strip())
|
|
508
|
+
html = profile["html"]
|
|
509
|
+
doctype = re.match(r"\s*<!doctype[^>]*>", html, re.IGNORECASE)
|
|
510
|
+
page = html[: doctype.end()] + head + html[doctype.end() :] if doctype else "<!doctype html>" + head + html
|
|
511
|
+
return page.replace("https://clipen.local/fonts/", LIVE_FONTS)
|
|
512
|
+
|
|
513
|
+
|
|
514
|
+
# Captions: a page the AI designs, filled with each caption's words. By default it moves only while it
|
|
515
|
+
# enters and leaves and holds still between, so a caption costs a handful of frames; a design may
|
|
516
|
+
# instead move throughout, at the cost of drawing every frame.
|
|
517
|
+
SAMPLE_CAPTION = {"text": "這是一句字幕的樣子", "emphasis": ["字幕"], "delivery": "dialogue"}
|
|
518
|
+
|
|
519
|
+
|
|
520
|
+
def caption_html(text, emphasis):
|
|
521
|
+
"""The caption's words for the page, escaped, with its emphasised words marked as <em>."""
|
|
522
|
+
import html
|
|
523
|
+
|
|
524
|
+
marked = [False] * len(text)
|
|
525
|
+
for word in emphasis or ():
|
|
526
|
+
start = 0
|
|
527
|
+
while word and (start := text.find(word, start)) >= 0:
|
|
528
|
+
marked[start : start + len(word)] = [True] * len(word)
|
|
529
|
+
start += len(word)
|
|
530
|
+
parts, run = [], ""
|
|
531
|
+
for index, character in enumerate(text):
|
|
532
|
+
if index and marked[index] != marked[index - 1]:
|
|
533
|
+
parts.append(f"<em>{html.escape(run)}</em>" if marked[index - 1] else html.escape(run))
|
|
534
|
+
run = ""
|
|
535
|
+
run += character
|
|
536
|
+
if run:
|
|
537
|
+
parts.append(f"<em>{html.escape(run)}</em>" if marked[-1] else html.escape(run))
|
|
538
|
+
return "".join(parts)
|
|
539
|
+
|
|
540
|
+
|
|
541
|
+
def caption_profile(design, text, emphasis=(), delivery="dialogue"):
|
|
542
|
+
"""A caption drawn by its design, as a free design is: the whole page, never moved."""
|
|
543
|
+
return {
|
|
544
|
+
"component_id": CUSTOM,
|
|
545
|
+
"html": design["html"],
|
|
546
|
+
"look": design.get("look"),
|
|
547
|
+
"x": 0,
|
|
548
|
+
"y": 0,
|
|
549
|
+
"edits": {"caption": {"html": caption_html(text, emphasis), "delivery": delivery}},
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
|
|
553
|
+
def caption_frame(design, duration, relative):
|
|
554
|
+
"""The frame of a caption's page that shows at relative: its own while entering or leaving, else the still one."""
|
|
555
|
+
entry, leave = design.get("entry_frames", 0), design.get("exit_frames", 0)
|
|
556
|
+
if design.get("throughout") or duration <= entry + leave + 1 or relative < entry or relative >= duration - leave:
|
|
557
|
+
return min(max(0, relative), duration - 1)
|
|
558
|
+
return entry
|
|
559
|
+
|
|
560
|
+
|
|
561
|
+
def caption_moments(design, duration):
|
|
562
|
+
"""Relative frames where a caption's picture may change: each entering and leaving frame and the still one."""
|
|
563
|
+
return sorted(
|
|
564
|
+
{caption_frame(design, duration, n) for n in range(duration)} | {duration - design.get("exit_frames", 0)}
|
|
565
|
+
)
|
|
566
|
+
|
|
567
|
+
|
|
568
|
+
def draw_caption(draw_, timeline, item, design, profile, relative_frame):
|
|
569
|
+
page = caption_profile(design, item.text, profile.get("emphasis", ()), profile.get("delivery", "dialogue"))
|
|
570
|
+
return draw(draw_, timeline, item, page, caption_frame(design, item.duration_frames, relative_frame or 0))
|
|
571
|
+
|
|
572
|
+
|
|
573
|
+
def draw_captions(timeline, captions, cancel=None, progress=None):
|
|
574
|
+
"""Draw every caption's frames ahead, many captions to a Chrome run and a few runs at once.
|
|
575
|
+
|
|
576
|
+
captions is a list of (item, design, profile); frames already drawn are kept."""
|
|
577
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
578
|
+
|
|
579
|
+
pages = {}
|
|
580
|
+
for item, design, profile in captions:
|
|
581
|
+
page = caption_profile(design, item.text, profile.get("emphasis", ()), profile.get("delivery", "dialogue"))
|
|
582
|
+
duration = item.duration_frames
|
|
583
|
+
key = _key(page, timeline, duration)
|
|
584
|
+
folder = cache_root() / key
|
|
585
|
+
wanted = {caption_frame(design, duration, n) for n in range(duration)}
|
|
586
|
+
missing = sorted(n for n in wanted if not (folder / f"f{n:05d}.png").is_file())
|
|
587
|
+
if missing and key not in pages:
|
|
588
|
+
folder.mkdir(parents=True, exist_ok=True)
|
|
589
|
+
pages[key] = (
|
|
590
|
+
design,
|
|
591
|
+
{
|
|
592
|
+
"out": str(folder),
|
|
593
|
+
"duration": duration,
|
|
594
|
+
"edits": _edits(page),
|
|
595
|
+
"faces": face_plan(page),
|
|
596
|
+
"frames": missing,
|
|
597
|
+
},
|
|
598
|
+
)
|
|
599
|
+
designs = {}
|
|
600
|
+
for design, page in pages.values():
|
|
601
|
+
designs.setdefault((design["html"], json.dumps(design.get("look"), sort_keys=True)), (design, []))[1].append(
|
|
602
|
+
page
|
|
603
|
+
)
|
|
604
|
+
jobs = []
|
|
605
|
+
for design, group in designs.values():
|
|
606
|
+
# Starting Chrome costs about as much as a dozen frames, so a run takes at least several captions.
|
|
607
|
+
size = max(MIN_CAPTIONS_PER_RUN, -(-len(group) // CAPTION_RUNS))
|
|
608
|
+
for start in range(0, len(group), size):
|
|
609
|
+
part = group[start : start + size]
|
|
610
|
+
jobs.append(
|
|
611
|
+
{
|
|
612
|
+
"html": design["html"],
|
|
613
|
+
"width": timeline.width,
|
|
614
|
+
"height": timeline.height,
|
|
615
|
+
"fps": _fps(timeline),
|
|
616
|
+
"frame_timeout": FRAME_TIMEOUT_SECONDS,
|
|
617
|
+
"look": page_css(design.get("look")),
|
|
618
|
+
"pages": part,
|
|
619
|
+
}
|
|
620
|
+
)
|
|
621
|
+
if not jobs:
|
|
622
|
+
return
|
|
623
|
+
done = [0]
|
|
624
|
+
total = sum(len(job["pages"]) for job in jobs)
|
|
625
|
+
|
|
626
|
+
def one(job):
|
|
627
|
+
frames = sum(len(page["frames"]) for page in job["pages"])
|
|
628
|
+
_run(job, timeout=30 + FRAME_TIMEOUT_SECONDS + frames * 1.5 + len(job["pages"]) * 2, cancel=cancel)
|
|
629
|
+
done[0] += len(job["pages"])
|
|
630
|
+
if progress:
|
|
631
|
+
progress(done[0] / total)
|
|
632
|
+
|
|
633
|
+
with ThreadPoolExecutor(min(CAPTION_RUNS, len(jobs))) as pool:
|
|
634
|
+
for future in [pool.submit(one, job) for job in jobs]:
|
|
635
|
+
future.result()
|
|
636
|
+
|
|
637
|
+
|
|
638
|
+
# Captions are independent, so a few Chrome runs draw them side by side.
|
|
639
|
+
CAPTION_RUNS = max(1, min(3, (os.cpu_count() or 2) // 2))
|
|
640
|
+
MIN_CAPTIONS_PER_RUN = 8
|