@clipen/clipen-cli 1.0.8 → 1.0.10

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 (103) hide show
  1. package/README.md +57 -39
  2. package/README.zh-TW.md +98 -0
  3. package/apps/web/dist/assets/index-BHFCflzf.js +15 -0
  4. package/apps/web/dist/assets/index-BtenOBwP.css +1 -0
  5. package/apps/web/dist/favicon.svg +1 -1
  6. package/apps/web/dist/index.html +2 -2
  7. package/bin/clipen.js +10 -17
  8. package/package.json +2 -2
  9. package/pyproject.toml +1 -1
  10. package/src/clipen/__init__.py +1 -1
  11. package/src/clipen/annotations/suggestions.py +1 -1
  12. package/src/clipen/bootstrap.py +190 -28
  13. package/src/clipen/controller/app.py +185 -22
  14. package/src/clipen/controller/server.py +19 -6
  15. package/src/clipen/editing/agent_repository.py +29 -3
  16. package/src/clipen/editing/agent_tools.py +2 -1
  17. package/src/clipen/editing/aspect.py +27 -0
  18. package/src/clipen/editing/caption_design.py +134 -0
  19. package/src/clipen/editing/component_looks.py +3 -3
  20. package/src/clipen/editing/component_review.py +0 -38
  21. package/src/clipen/editing/coordinator.py +14 -0
  22. package/src/clipen/editing/production_catalog.py +77 -16
  23. package/src/clipen/editing/production_media.py +14 -3
  24. package/src/clipen/editing/production_preview.py +18 -9
  25. package/src/clipen/editing/production_progress.py +2 -0
  26. package/src/clipen/editing/production_tools.py +18 -22
  27. package/src/clipen/editing/program_subtitles.py +5 -13
  28. package/src/clipen/editing/resolve_export.py +2 -183
  29. package/src/clipen/editing/skill_tools.py +150 -218
  30. package/src/clipen/editing/slip.py +109 -0
  31. package/src/clipen/editing/tool_receipts.py +3 -1
  32. package/src/clipen/editing/versions.py +4 -0
  33. package/src/clipen/editing/visual_preview.py +73 -3
  34. package/src/clipen/editing/workbench.py +53 -1
  35. package/src/clipen/locale_en.py +36 -0
  36. package/src/clipen/mcp_editing/server.py +3 -1
  37. package/src/clipen/media/discovery.py +2 -2
  38. package/src/clipen/media/preview.py +5 -0
  39. package/src/clipen/media/storage.py +5 -2
  40. package/src/clipen/own_ffmpeg.py +113 -0
  41. package/src/clipen/projects/models.py +2 -0
  42. package/src/clipen/projects/storage.py +84 -4
  43. package/src/clipen/providers/account.py +37 -6
  44. package/src/clipen/providers/claude.py +5 -3
  45. package/src/clipen/providers/claude_editing.py +5 -6
  46. package/src/clipen/providers/codex.py +19 -7
  47. package/src/clipen/providers/codex_editing.py +2 -1
  48. package/src/clipen/providers/editing_agent.py +30 -6
  49. package/src/clipen/providers/model_selection.py +67 -0
  50. package/src/clipen/rendering/cover.py +1 -1
  51. package/src/clipen/rendering/custom_components.py +216 -25
  52. package/src/clipen/rendering/custom_render.py +90 -54
  53. package/src/clipen/rendering/fetched_fonts.py +127 -0
  54. package/src/clipen/rendering/production_effects.py +24 -2
  55. package/src/clipen/rendering/program_components.py +18 -240
  56. package/src/clipen/rendering/program_subtitles.py +3 -1
  57. package/src/clipen/rendering/renderer.py +36 -20
  58. package/src/clipen/rendering/titles.py +29 -12
  59. package/src/clipen/skills/builtin/SKILL.md +3 -3
  60. package/src/clipen/skills/builtin/assets/sample-daily-vlog.mp4 +0 -0
  61. package/src/clipen/skills/builtin/assets/sample-event-recap.mp4 +0 -0
  62. package/src/clipen/skills/builtin/assets/sample-food-review.mp4 +0 -0
  63. package/src/clipen/skills/builtin/assets/sample-product-demo.mp4 +0 -0
  64. package/src/clipen/skills/builtin/assets/sample-product-review.mp4 +0 -0
  65. package/src/clipen/skills/builtin/assets/sample-product-unboxing.mp4 +0 -0
  66. package/src/clipen/skills/builtin/assets/sample-shorts-highlight.mp4 +0 -0
  67. package/src/clipen/skills/builtin/assets/sample-travel-highlight.mp4 +0 -0
  68. package/src/clipen/skills/builtin/assets/sample-travel-vlog.mp4 +0 -0
  69. package/src/clipen/skills/builtin/assets/style-tpl-daily-vlog.png +0 -0
  70. package/src/clipen/skills/builtin/assets/style-tpl-event-recap.png +0 -0
  71. package/src/clipen/skills/builtin/assets/style-tpl-food-review.png +0 -0
  72. package/src/clipen/skills/builtin/assets/style-tpl-product-demo.png +0 -0
  73. package/src/clipen/skills/builtin/assets/style-tpl-product-review.png +0 -0
  74. package/src/clipen/skills/builtin/assets/style-tpl-product-unboxing.png +0 -0
  75. package/src/clipen/skills/builtin/assets/style-tpl-shorts-highlight.png +0 -0
  76. package/src/clipen/skills/builtin/assets/style-tpl-travel-highlight.png +0 -0
  77. package/src/clipen/skills/builtin/assets/style-tpl-travel-vlog.png +0 -0
  78. package/src/clipen/skills/builtin/references/captions.md +12 -0
  79. package/src/clipen/skills/builtin/references/graphics.md +7 -6
  80. package/src/clipen/skills/builtin/template-skills/clipen-daily-vlog/SKILL.md +9 -4
  81. package/src/clipen/skills/builtin/template-skills/clipen-event-recap/SKILL.md +10 -5
  82. package/src/clipen/skills/builtin/template-skills/clipen-food-review/SKILL.md +9 -4
  83. package/src/clipen/skills/builtin/template-skills/clipen-product-demo/SKILL.md +10 -6
  84. package/src/clipen/skills/builtin/template-skills/clipen-product-review/SKILL.md +10 -6
  85. package/src/clipen/skills/builtin/template-skills/clipen-product-unboxing/SKILL.md +9 -7
  86. package/src/clipen/skills/builtin/template-skills/clipen-shorts-highlight/SKILL.md +10 -5
  87. package/src/clipen/skills/builtin/template-skills/clipen-travel-highlight/SKILL.md +10 -5
  88. package/src/clipen/skills/builtin/template-skills/clipen-travel-vlog/SKILL.md +10 -7
  89. package/src/clipen/skills/builtin/templates.json +9 -0
  90. package/src/clipen/skills/catalog.py +0 -8
  91. package/src/clipen/skills/package.py +1 -10
  92. package/apps/web/dist/assets/index-CJ80KHsQ.css +0 -1
  93. package/apps/web/dist/assets/index-C_4u_hVf.js +0 -16
  94. package/src/clipen/editing/EDITORIAL_REGRESSIONS.md +0 -38
  95. package/src/clipen/editing/REFACTOR_DESIGN.md +0 -241
  96. package/src/clipen/editing/REFACTOR_HANDOFF.md +0 -73
  97. package/src/clipen/editing/resolve_titles.py +0 -291
  98. package/src/clipen/rendering/program_creator.py +0 -804
  99. package/src/clipen/rendering/program_identities.py +0 -350
  100. package/src/clipen/rendering/program_motion.py +0 -186
  101. package/src/clipen/rendering/program_studio.py +0 -227
  102. package/src/clipen/rendering/program_styles.py +0 -321
  103. package/src/clipen/skills/builtin/components.json +0 -133
@@ -36,6 +36,7 @@ from .errors import (
36
36
  ProviderUnavailable,
37
37
  ProviderUsageLimitError,
38
38
  )
39
+ from .model_selection import selected_model
39
40
  from .recovery import ProviderUsage
40
41
 
41
42
  # Flags the bounded editing attempt depends on; an older CLI without them
@@ -86,8 +87,9 @@ def claude_preferences(environment: Mapping[str, str] | None = None) -> tuple[st
86
87
  )
87
88
 
88
89
 
89
- def model_arguments(environment: Mapping[str, str] | None = None) -> tuple[str, ...]:
90
- model, effort = claude_preferences(environment)
90
+ def model_arguments(environment: Mapping[str, str] | None = None, *, model: str | None = None) -> tuple[str, ...]:
91
+ configured, effort = claude_preferences(environment)
92
+ model = model or configured
91
93
  return (*(("--model", model) if model else ()), *(("--effort", effort) if effort else ()))
92
94
 
93
95
 
@@ -329,7 +331,7 @@ class ClaudeExecAdapter(CodexExecAdapter):
329
331
  "project",
330
332
  "--no-session-persistence",
331
333
  "--disable-slash-commands",
332
- *model_arguments(self._environment),
334
+ *model_arguments(self._environment, model=selected_model(self._attempt_root, "claude")),
333
335
  )
334
336
 
335
337
  def _stdin_payload(self, attempt: CodexAttempt) -> bytes:
@@ -9,7 +9,6 @@ from typing import Mapping
9
9
  from .claude import (
10
10
  _stream_events,
11
11
  claude_environment,
12
- claude_preferences,
13
12
  model_arguments,
14
13
  raise_for_claude_failure,
15
14
  raise_for_failed_result,
@@ -19,6 +18,7 @@ from .claude import (
19
18
  from .codex import _decode_capture
20
19
  from .editing_agent import _MAX_CAPTURE_BYTES, _MCP_TOOLS, BoundedEditingAgent, mcp_server_arguments
21
20
  from .errors import ProviderProtocolError
21
+ from .model_selection import selected_model
22
22
  from .recovery import ProviderUsage
23
23
 
24
24
  MCP_SERVER = "clipen"
@@ -76,21 +76,20 @@ class ClaudeEditingAgent(BoundedEditingAgent):
76
76
  "--setting-sources",
77
77
  "project",
78
78
  "--disable-slash-commands",
79
- *model_arguments(self.environment),
79
+ *model_arguments(self.environment, model=selected_model(self.attempt_root, "claude")),
80
80
  )
81
81
 
82
82
  def events_and_usage(self, stdout: bytes) -> tuple[tuple[str, ...], ProviderUsage | None]:
83
83
  events = _stream_events(stdout, _MAX_CAPTURE_BYTES)
84
84
  return stream_event_types(events), stream_usage(events)
85
85
 
86
- def record_account(self, stdout: bytes) -> None:
86
+ def record_account(self, stdout: bytes, command: tuple[str, ...]) -> None:
87
87
  # Claude Code has no quota query; keep what this attempt reported.
88
88
  from .account import record_claude_account
89
89
 
90
90
  try:
91
- record_claude_account(
92
- self.attempt_root, _stream_events(stdout, _MAX_CAPTURE_BYTES), claude_preferences(self.environment)[0]
93
- )
91
+ model = command[command.index("--model") + 1] if "--model" in command else None
92
+ record_claude_account(self.attempt_root, _stream_events(stdout, _MAX_CAPTURE_BYTES), model)
94
93
  except (OSError, ProviderProtocolError):
95
94
  pass
96
95
 
@@ -34,6 +34,7 @@ from .errors import (
34
34
  ProviderUnavailable,
35
35
  ProviderUsageLimitError,
36
36
  )
37
+ from .model_selection import model_lock, selected_model
37
38
  from .recovery import (
38
39
  AttemptReceiptError,
39
40
  AttemptReceiptStore,
@@ -150,19 +151,26 @@ def codex_preferences(environment: Mapping[str, str] | None = None) -> tuple[str
150
151
  return (model if model and _MODEL.fullmatch(model) else None, effort if effort in _EFFORTS else None)
151
152
 
152
153
 
153
- def model_config(binary: str | Path, environment: Mapping[str, str] | None = None) -> tuple[str, ...]:
154
+ def model_config(
155
+ binary: str | Path, environment: Mapping[str, str] | None = None, *, model: str | None = None
156
+ ) -> tuple[str, ...]:
154
157
  """`-c` overrides for the user's model and effort, kept only when this account supports them."""
155
- preferences = codex_preferences(environment)
158
+ configured, effort = codex_preferences(environment)
159
+ preferences = (model or configured, effort)
156
160
  if preferences == (None, None):
157
161
  return ()
158
162
  from .account import available_models, resolve_codex_model
159
163
 
160
164
  resolved = resolve_codex_model(preferences, available_models(binary, environment or os.environ))
161
- if resolved is None:
162
- return ()
165
+ applied_model = model or (resolved["id"] if resolved and resolved["apply_model"] else None)
166
+ applied_effort = (
167
+ resolved["effort"]
168
+ if resolved and resolved["apply_effort"] and (model is None or resolved["id"] == model)
169
+ else None
170
+ )
163
171
  return (
164
- *(("-c", f"model={json.dumps(resolved['id'])}") if resolved["apply_model"] else ()),
165
- *(("-c", f"model_reasoning_effort={json.dumps(resolved['effort'])}") if resolved["apply_effort"] else ()),
172
+ *(("-c", f"model={json.dumps(applied_model)}") if applied_model else ()),
173
+ *(("-c", f"model_reasoning_effort={json.dumps(applied_effort)}") if applied_effort else ()),
166
174
  )
167
175
 
168
176
 
@@ -510,7 +518,7 @@ class CodexExecAdapter:
510
518
  "--output-last-message",
511
519
  str(resolved_output),
512
520
  *(part for image in attempt.images for part in ("--image", str(image.resolve()))),
513
- *model_config(self._binary, self._environment),
521
+ *model_config(self._binary, self._environment, model=selected_model(self._attempt_root, "codex")),
514
522
  "--cd",
515
523
  str(workspace),
516
524
  "-",
@@ -521,6 +529,10 @@ class CodexExecAdapter:
521
529
  attempt: CodexAttempt,
522
530
  cancel_token: CancellationToken | None = None,
523
531
  ) -> CodexAttemptResult:
532
+ with model_lock(self._attempt_root):
533
+ return self._execute(attempt, cancel_token)
534
+
535
+ def _execute(self, attempt: CodexAttempt, cancel_token: CancellationToken | None) -> CodexAttemptResult:
524
536
  if cancel_token is not None and cancel_token.is_set():
525
537
  raise ProviderCancelled(f"Codex attempt {attempt.attempt_id} was cancelled")
526
538
  workspace = _isolated_workspace(attempt.workspace)
@@ -23,6 +23,7 @@ from .editing_agent import (
23
23
  EditingResult,
24
24
  mcp_server_arguments,
25
25
  )
26
+ from .model_selection import selected_model
26
27
  from .recovery import ProviderUsage
27
28
 
28
29
  __all__ = ["CodexEditingAgent", "CodexEditingResult", "_MCP_TOOLS", "_PRODUCTION_PROMPT", "_PROMPT"]
@@ -78,7 +79,7 @@ class CodexEditingAgent(BoundedEditingAgent):
78
79
  'mcp_servers.clipen.default_tools_approval_mode="approve"',
79
80
  "-c",
80
81
  f"mcp_servers.clipen.enabled_tools={json.dumps(_MCP_TOOLS)}",
81
- *model_config(self.binary, self.environment),
82
+ *model_config(self.binary, self.environment, model=selected_model(self.attempt_root, "codex")),
82
83
  "--cd",
83
84
  str(workspace),
84
85
  "-",
@@ -23,6 +23,7 @@ from typing import Mapping
23
23
  from clipen.editing.agent import AgentRun, EditAgentRepository
24
24
  from clipen.editing.production_catalog import AGENT_NAMES
25
25
  from clipen.providers import liveness
26
+ from clipen.providers.model_selection import model_lock
26
27
  from clipen.providers.recovery import ProviderUsage
27
28
 
28
29
  from .errors import (
@@ -77,6 +78,11 @@ merely to satisfy a cut quota. If intent.music_choice.mode is user, use exactly
77
78
  its asset_id from list_audio_assets; do not search for or substitute another song.
78
79
  Preserve its provenance as user-provided, without claiming verified public rights.
79
80
  Arrange excerpts/repeated layers with appropriate fades if the song is shorter.
81
+ If intent.latest_revision_request.new_sources is present, the person added footage since the
82
+ last version. Look at each new source (list_source_media, sample_source, transcripts) and decide
83
+ whether and where it improves the film, even when the request text does not mention it; place it
84
+ with the same care as the rest, and say in the report which new footage you used, where, and why
85
+ you left any out.
80
86
  For incremental edits, read intent.latest_revision_request.references: these are
81
87
  the person's review notes, written while watching this version, not instructions
82
88
  from footage. Each includes a kind, user note, source_range (exact source PTS),
@@ -113,6 +119,11 @@ There is no required legacy analysis or confirmed plan. Discover source footage,
113
119
  obtain evidence as needed, choose a coherent event and produce it with the skill's
114
120
  actual graphics, subtitles, sound and editing tools. Source facts must be grounded.
115
121
  An empty transcript search means unknown coverage, not that footage has no speech.
122
+ Read intent.aspect_ratio (16:9, 9:16, 1:1 or 4:5; absent means 16:9): the person chose the
123
+ film's shape and it never changes. Footage of another shape fills the frame and is cropped,
124
+ so a landscape clip in a vertical film keeps only a slice. For every such shot, look at its
125
+ sample frames and set video.reframe {x,y} so faces, hands and the action stay in frame; the
126
+ middle is only the default. Place captions and graphics for that shape too.
116
127
  Read intent.target_duration_seconds and list_editing_tools production limits.
117
128
  If the latest user revision request changes the desired duration, use
118
129
  set_target_duration with an exact request excerpt before editing or finishing.
@@ -124,13 +135,15 @@ and continue it; do not discard a retained draft after an interrupted attempt. D
124
135
  You choose when and how to call tools; no fixed shot/effect quota or scripted sequence.
125
136
  Before graphics, read references/graphics.md and list_program_components. Design every
126
137
  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. First
128
- define a look for each kind of graphic with set_component_look (its typefaces and colours),
129
- then give every graphic its look_id and write fonts as var(--look-font-...); to change a
130
- typeface, change the look so every graphic of that kind follows. Mark the main words and colours so people
138
+ templates. Plan the visual hierarchy of opening, segment changes and key moments. Use any
139
+ typeface by name: fonts installed on this Mac, the ones Clipen carries, or any open Google
140
+ Fonts family after get_font. Looks (set_component_look) are optional, to keep one kind of
141
+ 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
142
  can change them themselves, look at each returned still, and protect faces and subtitles.
132
143
  Search licensed public music, arrange it, preserve natural sound and source credits.
133
144
  Metadata/measurements are not listening and stills are not continuous-motion review.
145
+ Design how captions look yourself with set_caption_design (one page, filled with each
146
+ caption) before replace_subtitles; there is no built-in caption style.
134
147
  Repair timing uncertainty rather than claiming estimated subtitles are aligned.
135
148
  Render exact revisions, inspect actual results, revise specific failures. Local cut
136
149
  tools preserve unaffected post-production; inspect any dependencies they invalidate.
@@ -417,6 +430,17 @@ class BoundedEditingAgent:
417
430
  *,
418
431
  timeout_seconds: float | None = None,
419
432
  cancel: threading.Event | None = None,
433
+ ) -> EditingResult:
434
+ with model_lock(self.attempt_root):
435
+ return self._execute(project_id, run_id, timeout_seconds=timeout_seconds, cancel=cancel)
436
+
437
+ def _execute(
438
+ self,
439
+ project_id: str,
440
+ run_id: str,
441
+ *,
442
+ timeout_seconds: float | None,
443
+ cancel: threading.Event | None,
420
444
  ) -> EditingResult:
421
445
  session = self.repository.production_session(project_id, run_id)
422
446
  if timeout_seconds is None:
@@ -455,7 +479,7 @@ class BoundedEditingAgent:
455
479
  # Read the (possibly large) event log once for every check.
456
480
  stdout = events.read_bytes()
457
481
  event_types, usage = self.events_and_usage(stdout)
458
- self.record_account(stdout)
482
+ self.record_account(stdout, command)
459
483
  self.raise_for_failure(stdout, diagnostics.read_bytes(), returncode)
460
484
  del stdout
461
485
  finished = self.repository.get(project_id, run_id)
@@ -559,7 +583,7 @@ class BoundedEditingAgent:
559
583
  except OSError:
560
584
  pass
561
585
 
562
- def record_account(self, stdout: bytes) -> None:
586
+ def record_account(self, stdout: bytes, command: tuple[str, ...]) -> None:
563
587
  """Remember account details the provider reported, for the status bar."""
564
588
 
565
589
  def closing_message(self, stdout: bytes, final_message: Path) -> str | None:
@@ -0,0 +1,67 @@
1
+ """Clipen's local model override, stored independently for each provider."""
2
+
3
+ import fcntl
4
+ import os
5
+ import re
6
+ import tempfile
7
+ from contextlib import contextmanager
8
+ from pathlib import Path
9
+
10
+ CLAUDE_MODELS = {"sonnet": "Sonnet", "opus": "Opus", "haiku": "Haiku"}
11
+ _MODEL_ID = re.compile(r"[A-Za-z0-9][A-Za-z0-9._:\[\]-]{0,127}")
12
+
13
+
14
+ def valid_model_id(value: object) -> bool:
15
+ return isinstance(value, str) and _MODEL_ID.fullmatch(value) is not None
16
+
17
+
18
+ def selected_model(root: Path, provider: str) -> str | None:
19
+ path = root / f"{provider}-model"
20
+ try:
21
+ if path.is_symlink() or path.stat().st_size > 128:
22
+ return None
23
+ value = path.read_text(encoding="utf-8")
24
+ except (OSError, UnicodeError):
25
+ return None
26
+ return value if valid_model_id(value) else None
27
+
28
+
29
+ @contextmanager
30
+ def model_lock(root: Path, *, exclusive: bool = False):
31
+ # A shared lock covers each AI invocation, including nested evidence calls.
32
+ flags = os.O_RDWR | os.O_CREAT | getattr(os, "O_NOFOLLOW", 0)
33
+ descriptor = os.open(root / ".model-selection.lock", flags, 0o600)
34
+ try:
35
+ operation = fcntl.LOCK_EX | fcntl.LOCK_NB if exclusive else fcntl.LOCK_SH
36
+ fcntl.flock(descriptor, operation)
37
+ yield
38
+ finally:
39
+ os.close(descriptor)
40
+
41
+
42
+ def model_selection_locked(root: Path) -> bool:
43
+ try:
44
+ with model_lock(root, exclusive=True):
45
+ return False
46
+ except BlockingIOError:
47
+ return True
48
+
49
+
50
+ def save_model(root: Path, provider: str, model: str | None) -> None:
51
+ with model_lock(root, exclusive=True):
52
+ _write_model(root, provider, model)
53
+
54
+
55
+ def _write_model(root: Path, provider: str, model: str | None) -> None:
56
+ path = root / f"{provider}-model"
57
+ if model is None:
58
+ path.unlink(missing_ok=True)
59
+ return
60
+ with tempfile.NamedTemporaryFile(dir=root, mode="w", encoding="utf-8", delete=False) as file:
61
+ temporary = Path(file.name)
62
+ try:
63
+ file.write(model)
64
+ file.close()
65
+ os.replace(temporary, path)
66
+ finally:
67
+ temporary.unlink(missing_ok=True)
@@ -71,7 +71,7 @@ class ProjectCoverRepository:
71
71
  videos = database.execute(
72
72
  "SELECT versions.version_id FROM asset_versions AS versions "
73
73
  "JOIN assets ON assets.asset_id=versions.asset_id "
74
- "WHERE assets.project_id=? AND assets.role='source' AND versions.probe_status='ready' "
74
+ "WHERE assets.project_id=? AND assets.role IN ('source','added') AND versions.probe_status='ready' "
75
75
  "AND EXISTS(SELECT 1 FROM media_streams AS streams "
76
76
  "WHERE streams.version_id=versions.version_id AND streams.kind='video') "
77
77
  "ORDER BY assets.relative_path, versions.created_at DESC LIMIT ?",
@@ -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