@clipen/clipen-cli 1.0.7 → 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.
Files changed (99) hide show
  1. package/README.md +16 -6
  2. package/apps/web/dist/assets/index-DPgSvXZ1.js +15 -0
  3. package/apps/web/dist/assets/index-DmPWV61v.css +1 -0
  4. package/apps/web/dist/index.html +2 -2
  5. package/bin/clipen.js +229 -68
  6. package/package.json +8 -2
  7. package/pyproject.toml +1 -1
  8. package/src/clipen/__init__.py +1 -1
  9. package/src/clipen/analysis/qwen_worker.py +13 -4
  10. package/src/clipen/analysis/setup.py +2 -1
  11. package/src/clipen/analysis/setup_cli.py +58 -12
  12. package/src/clipen/bootstrap.py +499 -167
  13. package/src/clipen/cli.py +40 -15
  14. package/src/clipen/controller/app.py +120 -38
  15. package/src/clipen/controller/server.py +70 -27
  16. package/src/clipen/editing/agent_repository.py +8 -0
  17. package/src/clipen/editing/agent_tools.py +1 -1
  18. package/src/clipen/editing/caption_design.py +134 -0
  19. package/src/clipen/editing/change_report.py +17 -0
  20. package/src/clipen/editing/component_looks.py +3 -3
  21. package/src/clipen/editing/component_review.py +0 -38
  22. package/src/clipen/editing/coordinator.py +20 -0
  23. package/src/clipen/editing/evidence_jobs.py +3 -1
  24. package/src/clipen/editing/history_changes.py +56 -27
  25. package/src/clipen/editing/production_catalog.py +67 -13
  26. package/src/clipen/editing/production_media.py +13 -2
  27. package/src/clipen/editing/production_preview.py +11 -9
  28. package/src/clipen/editing/production_progress.py +48 -3
  29. package/src/clipen/editing/production_tools.py +11 -20
  30. package/src/clipen/editing/program_subtitles.py +5 -13
  31. package/src/clipen/editing/resolve_export.py +2 -183
  32. package/src/clipen/editing/skill_tools.py +142 -218
  33. package/src/clipen/editing/tool_receipts.py +2 -1
  34. package/src/clipen/editing/versions.py +55 -10
  35. package/src/clipen/editing/visual_preview.py +62 -0
  36. package/src/clipen/editing/workbench.py +21 -1
  37. package/src/clipen/i18n.py +155 -0
  38. package/src/clipen/locale_en.py +546 -0
  39. package/src/clipen/mcp_editing/__main__.py +8 -0
  40. package/src/clipen/media/storage.py +2 -2
  41. package/src/clipen/own_ffmpeg.py +113 -0
  42. package/src/clipen/projects/models.py +16 -1
  43. package/src/clipen/projects/picker.py +3 -1
  44. package/src/clipen/projects/storage.py +17 -1
  45. package/src/clipen/providers/claude_editing.py +3 -1
  46. package/src/clipen/providers/codex_editing.py +3 -1
  47. package/src/clipen/providers/editing_agent.py +42 -5
  48. package/src/clipen/providers/liveness.py +39 -0
  49. package/src/clipen/rendering/custom_components.py +216 -25
  50. package/src/clipen/rendering/custom_render.py +90 -54
  51. package/src/clipen/rendering/fetched_fonts.py +127 -0
  52. package/src/clipen/rendering/production_effects.py +24 -2
  53. package/src/clipen/rendering/program_components.py +18 -240
  54. package/src/clipen/rendering/renderer.py +23 -17
  55. package/src/clipen/rendering/titles.py +29 -12
  56. package/src/clipen/skills/builtin/SKILL.md +3 -3
  57. package/src/clipen/skills/builtin/assets/sample-daily-vlog.mp4 +0 -0
  58. package/src/clipen/skills/builtin/assets/sample-event-recap.mp4 +0 -0
  59. package/src/clipen/skills/builtin/assets/sample-food-review.mp4 +0 -0
  60. package/src/clipen/skills/builtin/assets/sample-product-demo.mp4 +0 -0
  61. package/src/clipen/skills/builtin/assets/sample-product-review.mp4 +0 -0
  62. package/src/clipen/skills/builtin/assets/sample-product-unboxing.mp4 +0 -0
  63. package/src/clipen/skills/builtin/assets/sample-shorts-highlight.mp4 +0 -0
  64. package/src/clipen/skills/builtin/assets/sample-travel-highlight.mp4 +0 -0
  65. package/src/clipen/skills/builtin/assets/sample-travel-vlog.mp4 +0 -0
  66. package/src/clipen/skills/builtin/assets/style-tpl-daily-vlog.png +0 -0
  67. package/src/clipen/skills/builtin/assets/style-tpl-event-recap.png +0 -0
  68. package/src/clipen/skills/builtin/assets/style-tpl-food-review.png +0 -0
  69. package/src/clipen/skills/builtin/assets/style-tpl-product-demo.png +0 -0
  70. package/src/clipen/skills/builtin/assets/style-tpl-product-review.png +0 -0
  71. package/src/clipen/skills/builtin/assets/style-tpl-product-unboxing.png +0 -0
  72. package/src/clipen/skills/builtin/assets/style-tpl-shorts-highlight.png +0 -0
  73. package/src/clipen/skills/builtin/assets/style-tpl-travel-highlight.png +0 -0
  74. package/src/clipen/skills/builtin/assets/style-tpl-travel-vlog.png +0 -0
  75. package/src/clipen/skills/builtin/display.en.json +89 -0
  76. package/src/clipen/skills/builtin/references/captions.md +12 -0
  77. package/src/clipen/skills/builtin/references/graphics.md +6 -6
  78. package/src/clipen/skills/builtin/template-skills/clipen-daily-vlog/SKILL.md +9 -4
  79. package/src/clipen/skills/builtin/template-skills/clipen-event-recap/SKILL.md +10 -5
  80. package/src/clipen/skills/builtin/template-skills/clipen-food-review/SKILL.md +9 -4
  81. package/src/clipen/skills/builtin/template-skills/clipen-product-demo/SKILL.md +10 -6
  82. package/src/clipen/skills/builtin/template-skills/clipen-product-review/SKILL.md +10 -6
  83. package/src/clipen/skills/builtin/template-skills/clipen-product-unboxing/SKILL.md +9 -7
  84. package/src/clipen/skills/builtin/template-skills/clipen-shorts-highlight/SKILL.md +10 -5
  85. package/src/clipen/skills/builtin/template-skills/clipen-travel-highlight/SKILL.md +10 -5
  86. package/src/clipen/skills/builtin/template-skills/clipen-travel-vlog/SKILL.md +10 -7
  87. package/src/clipen/skills/catalog.py +22 -8
  88. package/src/clipen/skills/package.py +1 -10
  89. package/src/clipen/terminal.py +344 -0
  90. package/src/clipen/workspace.py +97 -28
  91. package/apps/web/dist/assets/index-C3Zw0WaM.js +0 -14
  92. package/apps/web/dist/assets/index-CaxEZKLc.css +0 -1
  93. package/src/clipen/editing/resolve_titles.py +0 -291
  94. package/src/clipen/rendering/program_creator.py +0 -804
  95. package/src/clipen/rendering/program_identities.py +0 -350
  96. package/src/clipen/rendering/program_motion.py +0 -186
  97. package/src/clipen/rendering/program_studio.py +0 -227
  98. package/src/clipen/rendering/program_styles.py +0 -321
  99. package/src/clipen/skills/builtin/components.json +0 -133
@@ -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
@@ -17,9 +17,20 @@ class ProjectError(RuntimeError):
17
17
  def __init__(self, code: str, message: str, *, status_code: int = 400) -> None:
18
18
  super().__init__(message)
19
19
  self.code = code
20
- self.message = message
20
+ self._message = message
21
21
  self.status_code = status_code
22
22
 
23
+ @property
24
+ def message(self) -> str:
25
+ """The message in the language of whoever reads it now: the request, or the AI's attempt."""
26
+ from clipen.i18n import tr
27
+
28
+ return tr(self._message)
29
+
30
+ @message.setter
31
+ def message(self, value: str) -> None:
32
+ self._message = value
33
+
23
34
 
24
35
  class DirectoryRole(str, Enum):
25
36
  SOURCE = "source"
@@ -135,6 +146,9 @@ class ProjectSnapshot:
135
146
  updated_at: str
136
147
  directories: tuple[DirectoryReference, ...] = ()
137
148
  last_activity_at: str | None = field(default=None, compare=False)
149
+ # Where the project stands, for its card on the home page: whether its footage was checked and
150
+ # how its latest AI production ended. Derived when listing; never stored.
151
+ standing: Mapping[str, object] | None = field(default=None, compare=False)
138
152
 
139
153
  def __post_init__(self) -> None:
140
154
  validate_project_id(self.project_id)
@@ -170,6 +184,7 @@ class ProjectSnapshot:
170
184
  "updated_at": self.updated_at,
171
185
  "last_activity_at": self.last_activity_at or self.updated_at,
172
186
  "directories": [reference.to_public() for reference in self.directories],
187
+ **({"standing": dict(self.standing)} if self.standing is not None else {}),
173
188
  }
174
189
 
175
190
  @classmethod
@@ -43,7 +43,9 @@ class MacOSDirectoryPicker(NativeDirectoryPicker):
43
43
  }
44
44
 
45
45
  def choose(self, role: DirectoryRole) -> Path | None:
46
- return self.choose_folder(self._PROMPTS[role])
46
+ from clipen.i18n import tr
47
+
48
+ return self.choose_folder(tr(self._PROMPTS[role]))
47
49
 
48
50
  def choose_folder(self, prompt: str) -> Path | None:
49
51
  if sys.platform != "darwin":
@@ -365,7 +365,23 @@ class ProjectRepository:
365
365
  UNION ALL SELECT MAX(created_at) FROM inventory_runs
366
366
  UNION ALL SELECT MAX(completed_at) FROM preview_renders
367
367
  )""").fetchone()[0]
368
- projects.append(replace(project, last_activity_at=max(project.updated_at, activity or project.updated_at)))
368
+ checked = (
369
+ db.execute("SELECT 1 FROM inventory_runs WHERE state='succeeded' LIMIT 1").fetchone() is not None
370
+ )
371
+ run = db.execute(
372
+ "SELECT state,error_code FROM edit_agent_runs ORDER BY created_at DESC,rowid DESC LIMIT 1"
373
+ ).fetchone()
374
+ standing = {
375
+ "footage_checked": checked,
376
+ "production": None if run is None else {"state": run["state"], "error_code": run["error_code"]},
377
+ }
378
+ projects.append(
379
+ replace(
380
+ project,
381
+ last_activity_at=max(project.updated_at, activity or project.updated_at),
382
+ standing=standing,
383
+ )
384
+ )
369
385
  projects.sort(key=lambda project: project.last_activity_at or project.updated_at, reverse=True)
370
386
  return tuple(projects)
371
387
 
@@ -48,7 +48,9 @@ class ClaudeEditingAgent(BoundedEditingAgent):
48
48
  server = {
49
49
  "type": "stdio",
50
50
  "command": str(self.python),
51
- "args": mcp_server_arguments(self.projects_root, project_id, run_id, self.local_runtime),
51
+ "args": mcp_server_arguments(
52
+ self.projects_root, project_id, run_id, self.local_runtime, getattr(self, "_language", "zh-TW")
53
+ ),
52
54
  }
53
55
  return (
54
56
  str(self.binary),
@@ -47,7 +47,9 @@ class CodexEditingAgent(BoundedEditingAgent):
47
47
  workspace: Path,
48
48
  output_path: Path,
49
49
  ) -> tuple[str, ...]:
50
- args = mcp_server_arguments(self.projects_root, project_id, run_id, self.local_runtime)
50
+ args = mcp_server_arguments(
51
+ self.projects_root, project_id, run_id, self.local_runtime, getattr(self, "_language", "zh-TW")
52
+ )
51
53
  return (
52
54
  str(self.binary),
53
55
  "--ask-for-approval",
@@ -22,6 +22,7 @@ from typing import Mapping
22
22
 
23
23
  from clipen.editing.agent import AgentRun, EditAgentRepository
24
24
  from clipen.editing.production_catalog import AGENT_NAMES
25
+ from clipen.providers import liveness
25
26
  from clipen.providers.recovery import ProviderUsage
26
27
 
27
28
  from .errors import (
@@ -123,13 +124,15 @@ and continue it; do not discard a retained draft after an interrupted attempt. D
123
124
  You choose when and how to call tools; no fixed shot/effect quota or scripted sequence.
124
125
  Before graphics, read references/graphics.md and list_program_components. Design every
125
126
  graphic yourself with add_custom_component (any HTML/CSS/SVG/JS); there are no built-in
126
- templates. Plan the visual hierarchy of opening, segment changes and key moments. First
127
- define a look for each kind of graphic with set_component_look (its typefaces and colours),
128
- then give every graphic its look_id and write fonts as var(--look-font-...); to change a
129
- typeface, change the look so every graphic of that kind follows. Mark the main words and colours so people
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
130
131
  can change them themselves, look at each returned still, and protect faces and subtitles.
131
132
  Search licensed public music, arrange it, preserve natural sound and source credits.
132
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.
133
136
  Repair timing uncertainty rather than claiming estimated subtitles are aligned.
134
137
  Render exact revisions, inspect actual results, revise specific failures. Local cut
135
138
  tools preserve unaffected post-production; inspect any dependencies they invalidate.
@@ -140,6 +143,32 @@ for rendering, inspection and finish_edit; report concrete incomplete work if bl
140
143
  The person reads Traditional Chinese: write the change report and your closing message
141
144
  in Traditional Chinese, whatever language these instructions use.
142
145
  """
146
+ _ENGLISH = (
147
+ (
148
+ "The person reads Traditional Chinese: write the change report and your closing message\n"
149
+ "in Traditional Chinese, whatever language these instructions use.",
150
+ "The person reads English: write the change report and your closing message in English.\n"
151
+ "Write titles, chapter cards, labels and other on-screen text in English too, whatever\n"
152
+ "language the skill's defaults or examples use; captions keep the language that was spoken.",
153
+ ),
154
+ (
155
+ "The person reads Traditional Chinese: write the change report, every reply to a note and\n"
156
+ "your closing message in Traditional Chinese, whatever language these instructions use.",
157
+ "The person reads English: write the change report, every reply to a note and your\n"
158
+ "closing message in English. Write new on-screen text in English, whatever language the\n"
159
+ "skill's defaults or examples use; captions keep the language that was spoken.",
160
+ ),
161
+ ("Correct subtitles faithfully in Traditional Chinese.", "Correct subtitles faithfully in the language spoken."),
162
+ )
163
+
164
+
165
+ def _in_english(prompt):
166
+ """The prompt for a person who reads English: only the lines about language change."""
167
+ for chinese, english in _ENGLISH:
168
+ prompt = prompt.replace(chinese, english)
169
+ return prompt
170
+
171
+
143
172
  _MCP_TOOLS = (
144
173
  "get_edit_status",
145
174
  "search_media",
@@ -282,8 +311,9 @@ def mcp_server_arguments(
282
311
  project_id: str,
283
312
  run_id: str,
284
313
  local_runtime: tuple[Path, Path] | None,
314
+ language: str = "zh-TW",
285
315
  ) -> list[str]:
286
- """Arguments that start the Clipen MCP server bound to one edit run."""
316
+ """Arguments that start the Clipen MCP server bound to one edit run, speaking the run's language."""
287
317
  args = [
288
318
  "-m",
289
319
  "clipen.mcp_editing",
@@ -296,6 +326,8 @@ def mcp_server_arguments(
296
326
  ]
297
327
  if local_runtime:
298
328
  args += ["--data-root", str(local_runtime[0]), "--asr-requirements", str(local_runtime[1])]
329
+ if language != "zh-TW":
330
+ args += ["--language", language]
299
331
  return args
300
332
 
301
333
 
@@ -398,6 +430,9 @@ class BoundedEditingAgent:
398
430
  raise ValueError("editing timeout must be between 30 and 14400 seconds")
399
431
  run = self.repository.get(project_id, run_id)
400
432
  self._prompt = _PRODUCTION_PROMPT if session else _PROMPT
433
+ self._language = (session or {}).get("intent", {}).get("language", "zh-TW")
434
+ if self._language == "en":
435
+ self._prompt = _in_english(self._prompt)
401
436
  if run.provider != self.provider_id:
402
437
  raise ValueError("editing run belongs to another provider")
403
438
  attempt_id = "agent-" + uuid.uuid4().hex
@@ -412,8 +447,10 @@ class BoundedEditingAgent:
412
447
  self._slept = []
413
448
  try:
414
449
  try:
450
+ liveness.watch(run_id, events)
415
451
  returncode = self._run(command, workspace, events, diagnostics, timeout_seconds, cancel)
416
452
  finally:
453
+ liveness.forget(run_id, events)
417
454
  record = getattr(self.repository, "record_machine_sleep", None)
418
455
  if self._slept and record is not None:
419
456
  record(project_id, run_id, self._slept)
@@ -0,0 +1,39 @@
1
+ """When each running AI attempt last wrote output, so the UI can tell working from stuck.
2
+
3
+ The provider streams its events into a file while it works; that file's modification time is
4
+ the last moment the AI process said anything, including the long thinking between tool calls
5
+ that leaves no tool activity behind. Kept in memory: it only means something while Clipen runs.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import threading
11
+ from datetime import datetime, timezone
12
+ from pathlib import Path
13
+
14
+ _lock = threading.Lock()
15
+ _attempts: dict[str, Path] = {}
16
+
17
+
18
+ def watch(run_id: str, events: Path) -> None:
19
+ with _lock:
20
+ _attempts[run_id] = events
21
+
22
+
23
+ def forget(run_id: str, events: Path) -> None:
24
+ with _lock:
25
+ if _attempts.get(run_id) == events:
26
+ del _attempts[run_id]
27
+
28
+
29
+ def last_output(run_id: str) -> str | None:
30
+ """The ISO time the run's AI process last wrote output, or None when no process runs for it."""
31
+ with _lock:
32
+ events = _attempts.get(run_id)
33
+ if events is None:
34
+ return None
35
+ try:
36
+ written = events.stat().st_mtime
37
+ except OSError:
38
+ return None
39
+ return datetime.fromtimestamp(written, timezone.utc).isoformat(timespec="microseconds")
@@ -21,7 +21,7 @@ from pathlib import Path
21
21
 
22
22
  from .titles import TitleRenderError
23
23
 
24
- MAX_HTML_BYTES = 200_000
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
- return {kind: dict(sorted((edits.get(kind) or {}).items())) for kind in ("texts", "colors") if edits.get(kind)}
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, with the faces
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 faces + ":root { " + " ".join(names) + " }"
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
- look_css(profile.get("look")),
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": look_css(profile.get("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": look_css(profile.get("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