@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.
Files changed (80) hide show
  1. package/README.md +13 -4
  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 +6 -15
  6. package/package.json +1 -1
  7. package/pyproject.toml +1 -1
  8. package/src/clipen/__init__.py +1 -1
  9. package/src/clipen/bootstrap.py +130 -23
  10. package/src/clipen/controller/app.py +83 -21
  11. package/src/clipen/controller/server.py +5 -0
  12. package/src/clipen/editing/agent_tools.py +1 -1
  13. package/src/clipen/editing/caption_design.py +134 -0
  14. package/src/clipen/editing/component_looks.py +3 -3
  15. package/src/clipen/editing/component_review.py +0 -38
  16. package/src/clipen/editing/coordinator.py +14 -0
  17. package/src/clipen/editing/production_catalog.py +67 -13
  18. package/src/clipen/editing/production_media.py +13 -2
  19. package/src/clipen/editing/production_preview.py +11 -9
  20. package/src/clipen/editing/production_progress.py +2 -0
  21. package/src/clipen/editing/production_tools.py +11 -20
  22. package/src/clipen/editing/program_subtitles.py +5 -13
  23. package/src/clipen/editing/resolve_export.py +2 -183
  24. package/src/clipen/editing/skill_tools.py +142 -218
  25. package/src/clipen/editing/tool_receipts.py +2 -1
  26. package/src/clipen/editing/versions.py +2 -0
  27. package/src/clipen/editing/visual_preview.py +62 -0
  28. package/src/clipen/editing/workbench.py +21 -1
  29. package/src/clipen/locale_en.py +18 -0
  30. package/src/clipen/media/storage.py +2 -2
  31. package/src/clipen/own_ffmpeg.py +113 -0
  32. package/src/clipen/providers/editing_agent.py +6 -4
  33. package/src/clipen/rendering/custom_components.py +216 -25
  34. package/src/clipen/rendering/custom_render.py +90 -54
  35. package/src/clipen/rendering/fetched_fonts.py +127 -0
  36. package/src/clipen/rendering/production_effects.py +24 -2
  37. package/src/clipen/rendering/program_components.py +18 -240
  38. package/src/clipen/rendering/renderer.py +23 -17
  39. package/src/clipen/rendering/titles.py +29 -12
  40. package/src/clipen/skills/builtin/SKILL.md +3 -3
  41. package/src/clipen/skills/builtin/assets/sample-daily-vlog.mp4 +0 -0
  42. package/src/clipen/skills/builtin/assets/sample-event-recap.mp4 +0 -0
  43. package/src/clipen/skills/builtin/assets/sample-food-review.mp4 +0 -0
  44. package/src/clipen/skills/builtin/assets/sample-product-demo.mp4 +0 -0
  45. package/src/clipen/skills/builtin/assets/sample-product-review.mp4 +0 -0
  46. package/src/clipen/skills/builtin/assets/sample-product-unboxing.mp4 +0 -0
  47. package/src/clipen/skills/builtin/assets/sample-shorts-highlight.mp4 +0 -0
  48. package/src/clipen/skills/builtin/assets/sample-travel-highlight.mp4 +0 -0
  49. package/src/clipen/skills/builtin/assets/sample-travel-vlog.mp4 +0 -0
  50. package/src/clipen/skills/builtin/assets/style-tpl-daily-vlog.png +0 -0
  51. package/src/clipen/skills/builtin/assets/style-tpl-event-recap.png +0 -0
  52. package/src/clipen/skills/builtin/assets/style-tpl-food-review.png +0 -0
  53. package/src/clipen/skills/builtin/assets/style-tpl-product-demo.png +0 -0
  54. package/src/clipen/skills/builtin/assets/style-tpl-product-review.png +0 -0
  55. package/src/clipen/skills/builtin/assets/style-tpl-product-unboxing.png +0 -0
  56. package/src/clipen/skills/builtin/assets/style-tpl-shorts-highlight.png +0 -0
  57. package/src/clipen/skills/builtin/assets/style-tpl-travel-highlight.png +0 -0
  58. package/src/clipen/skills/builtin/assets/style-tpl-travel-vlog.png +0 -0
  59. package/src/clipen/skills/builtin/references/captions.md +12 -0
  60. package/src/clipen/skills/builtin/references/graphics.md +6 -5
  61. package/src/clipen/skills/builtin/template-skills/clipen-daily-vlog/SKILL.md +9 -4
  62. package/src/clipen/skills/builtin/template-skills/clipen-event-recap/SKILL.md +10 -5
  63. package/src/clipen/skills/builtin/template-skills/clipen-food-review/SKILL.md +9 -4
  64. package/src/clipen/skills/builtin/template-skills/clipen-product-demo/SKILL.md +10 -6
  65. package/src/clipen/skills/builtin/template-skills/clipen-product-review/SKILL.md +10 -6
  66. package/src/clipen/skills/builtin/template-skills/clipen-product-unboxing/SKILL.md +9 -7
  67. package/src/clipen/skills/builtin/template-skills/clipen-shorts-highlight/SKILL.md +10 -5
  68. package/src/clipen/skills/builtin/template-skills/clipen-travel-highlight/SKILL.md +10 -5
  69. package/src/clipen/skills/builtin/template-skills/clipen-travel-vlog/SKILL.md +10 -7
  70. package/src/clipen/skills/catalog.py +0 -8
  71. package/src/clipen/skills/package.py +1 -10
  72. package/apps/web/dist/assets/index-CJ80KHsQ.css +0 -1
  73. package/apps/web/dist/assets/index-C_4u_hVf.js +0 -16
  74. package/src/clipen/editing/resolve_titles.py +0 -291
  75. package/src/clipen/rendering/program_creator.py +0 -804
  76. package/src/clipen/rendering/program_identities.py +0 -350
  77. package/src/clipen/rendering/program_motion.py +0 -186
  78. package/src/clipen/rendering/program_studio.py +0 -227
  79. package/src/clipen/rendering/program_styles.py +0 -321
  80. package/src/clipen/skills/builtin/components.json +0 -133
@@ -20,7 +20,7 @@ from pathlib import Path
20
20
  from types import ModuleType
21
21
  from typing import Iterator, Mapping, Sequence, TextIO
22
22
 
23
- from clipen import __version__
23
+ from clipen import __version__, own_ffmpeg
24
24
  from clipen.asr_release import (
25
25
  ASR_SOFTWARE_LICENSE,
26
26
  DOWNLOAD_BYTES,
@@ -31,7 +31,7 @@ from clipen.asr_release import (
31
31
  )
32
32
  from clipen.i18n import current, normalize, save_language, saved_language, speaking, system_language, tr
33
33
  from clipen.own_python import sealed_environment
34
- from clipen.terminal import FRAME_OPEN, Terminal
34
+ from clipen.terminal import FRAME_OPEN, Terminal, display_width
35
35
 
36
36
  try:
37
37
  import fcntl as _fcntl
@@ -59,6 +59,8 @@ _REMOVABLE_DIRECTORIES = (
59
59
  "models",
60
60
  "cache",
61
61
  "logs",
62
+ "fonts", # Open fonts the AI fetched by name.
63
+ "ffmpeg",
62
64
  # What `npx @clipen/clipen-cli` set up: Clipen's own Python and its copies of the program. They go
63
65
  # last, since the uninstaller itself runs from them.
64
66
  "app",
@@ -237,10 +239,13 @@ def _confirm_setup(
237
239
  profile_path: Path | None = None,
238
240
  asr_root: Path | None = None,
239
241
  include_runtime: bool = True,
242
+ include_ffmpeg: bool = False,
240
243
  ) -> bool:
241
244
  """One short screen: how much is downloaded, how long it takes, and what changes on the Mac."""
242
245
  terminal = Terminal(stdout)
243
246
  download = (_RUNTIME_DOWNLOAD_BYTES if include_runtime else 0) + (DOWNLOAD_BYTES if asr_root is not None else 0)
247
+ if include_ffmpeg:
248
+ download += own_ffmpeg.DOWNLOAD_BYTES
244
249
  if not _chrome_ready(Path.home()):
245
250
  download += _CHROMIUM_DOWNLOAD_BYTES
246
251
  lines = [tr(f"需要下載約 {terminal.bold(_size(download))}", f"Downloads about {terminal.bold(_size(download))}")]
@@ -250,11 +255,20 @@ def _confirm_setup(
250
255
  if command_path is not None and profile_path is not None:
251
256
  lines.append(
252
257
  tr(
253
- f"會新增 {terminal.bold('clipen')} 指令,之後直接輸入 clipen codex 就能開始",
254
- f"Adds the {terminal.bold('clipen')} command; afterwards just type clipen codex to start",
258
+ f"會新增 {terminal.bold('clipen')} 指令(在 {profile_path.name} 加一行 PATH),之後直接輸入 clipen codex 就能開始",
259
+ f"Adds the {terminal.bold('clipen')} command (one PATH line in {profile_path.name}); afterwards just type clipen codex to start",
255
260
  )
256
261
  )
257
- fine_print = [tr("不會動到你原本的 Python,也不需要 sudo", "Leaves your own Python alone and needs no sudo")]
262
+ fine_print = [
263
+ tr(
264
+ "全部放在 ~/Library/Application Support/Clipen,不會安裝或修改你電腦上的其他程式,也不需要 sudo",
265
+ "Everything goes in ~/Library/Application Support/Clipen; nothing else on your Mac is installed or changed, and no sudo",
266
+ ),
267
+ tr(
268
+ "想移除時輸入 clipen uninstall,作品與毛片會保留",
269
+ "To remove it, type clipen uninstall; your projects and footage stay",
270
+ ),
271
+ ]
258
272
  if asr_root is not None:
259
273
  fine_print.insert(
260
274
  0,
@@ -350,6 +364,24 @@ def _ensure_chrome(runtime: Path, data_root: Path, home: Path, stdout: TextIO) -
350
364
  spinner.done(tr("瀏覽器就緒", "Browser ready"))
351
365
 
352
366
 
367
+ def _ensure_ffmpeg(data_root: Path, environment: Mapping[str, str], stdout: TextIO) -> None:
368
+ """Films are cut with ffmpeg; a Mac without it gets Clipen's own, kept in Clipen's folder."""
369
+ if not own_ffmpeg.needed(data_root, environment):
370
+ return
371
+ terminal = Terminal(stdout)
372
+ label = tr("正在下載影片處理工具(ffmpeg)", "Downloading the video tools (ffmpeg)")
373
+ with terminal.spinner(label) as spinner:
374
+
375
+ def progress(done: int, total: int) -> None:
376
+ spinner.update(f"{label} {terminal.progress_bar(done * 100 // total)} {_size(done)} / {_size(total)}")
377
+
378
+ try:
379
+ own_ffmpeg.install(data_root, progress)
380
+ except own_ffmpeg.FfmpegUnavailable as error:
381
+ raise BootstrapError(str(error)) from error
382
+ spinner.done(tr("影片處理工具就緒", "Video tools ready"))
383
+
384
+
353
385
  def _command_script(repo_root: Path) -> str:
354
386
  launcher = repo_root.resolve(strict=True) / "clipen"
355
387
  if launcher.is_symlink() or not launcher.is_file() or not os.access(launcher, os.X_OK):
@@ -565,7 +597,7 @@ def _install_runtime(staging: Path, repo_root: Path, fingerprint: str, log_path:
565
597
  venv.EnvBuilder(with_pip=True, clear=False, symlinks=False).create(staging)
566
598
  python = runtime_python(staging)
567
599
  if not python.is_file():
568
- raise BootstrapError(tr("無法建立 Clipen Python runtime", "Could not create Clipen's Python runtime"))
600
+ raise BootstrapError(tr("無法建立 Clipen 執行環境", "Could not create Clipen's runtime"))
569
601
 
570
602
  with log_path.open("w", encoding="utf-8") as log:
571
603
  _run_logged(
@@ -800,6 +832,7 @@ def ensure_installation(
800
832
  profile_path=None if command_ready else profile_path,
801
833
  asr_root=None if asr_ready else release_root(selected_data_root),
802
834
  include_runtime=not runtime_ready,
835
+ include_ffmpeg=own_ffmpeg.needed(selected_data_root, selected_environment),
803
836
  ):
804
837
  Terminal(stdout).outro(
805
838
  tr("已取消,既有 Clipen 資料沒有變動。", "Cancelled; your Clipen data is unchanged.")
@@ -841,6 +874,7 @@ def ensure_installation(
841
874
  )
842
875
  )
843
876
  _ensure_chrome(runtime, selected_data_root, selected_home, stdout)
877
+ _ensure_ffmpeg(selected_data_root, selected_environment, stdout)
844
878
  if not command_ready:
845
879
  _install_command(repo_root, selected_data_root, selected_home, selected_environment)
846
880
  Terminal(stdout).step(tr("已新增 clipen 指令", "Added the clipen command"))
@@ -848,6 +882,7 @@ def ensure_installation(
848
882
 
849
883
  if stdin.isatty():
850
884
  _ensure_chrome(runtime, selected_data_root, selected_home, stdout)
885
+ _ensure_ffmpeg(selected_data_root, selected_environment, stdout)
851
886
 
852
887
  if not command_ready:
853
888
  if not stdin.isatty():
@@ -1083,23 +1118,89 @@ def uninstall_installation(
1083
1118
 
1084
1119
 
1085
1120
  def _print_usage(stream: TextIO, repo_root: Path | None = None) -> None:
1121
+ """What `clipen` can do, in the frame the installer draws: the logo, how to start, the other commands."""
1086
1122
  npm = repo_root is not None and (repo_root / ".clipen-npm").is_file()
1087
- print(
1088
- tr(
1089
- f"第一次安裝:{'npx @clipen/clipen-cli' if npm else './clipen install'}",
1090
- f"First install: {'npx @clipen/clipen-cli' if npm else './clipen install'}",
1091
- ),
1092
- file=stream,
1123
+ terminal = Terminal(stream)
1124
+ terminal.logo(tr(f"v{__version__} · AI 剪輯工作台", f"v{__version__} · AI video editing studio"))
1125
+ terminal.intro(f"Clipen {__version__}")
1126
+
1127
+ start = [
1128
+ ("clipen claude", tr("用 Claude Code 開啟", "Open with Claude Code")),
1129
+ ("clipen codex", tr("用 Codex 開啟", "Open with Codex")),
1130
+ ]
1131
+ other = [
1132
+ *([] if npm else [("clipen install", tr("安裝", "Install"))]),
1133
+ ("clipen update", tr("更新到最新版", "Update to the latest version")),
1134
+ ("clipen language", tr("介面語言:en、zh-TW 或 auto", "Language: en, zh-TW or auto")),
1135
+ ("clipen uninstall", tr("移除 Clipen,作品資料保留", "Remove Clipen; projects are kept")),
1136
+ ]
1137
+ hint = tr(
1138
+ "在放毛片的資料夾裡執行,Clipen 會在瀏覽器打開。", "Run it in your footage folder; Clipen opens in the browser."
1093
1139
  )
1094
- print(tr("啟動 Clipen:clipen codex 或 clipen claude", "Start Clipen: clipen codex or clipen claude"), file=stream)
1095
- print(
1096
- tr(
1097
- f"移除 Clipen:{'clipen uninstall' if npm else './clipen uninstall'}",
1098
- f"Remove Clipen: {'clipen uninstall' if npm else './clipen uninstall'}",
1099
- ),
1100
- file=stream,
1140
+ # One column for every command and one width for both boxes, so the two read as one list.
1141
+ width = max(len(name) for name, _ in start + other)
1142
+ inner = max([display_width(hint)] + [width + 2 + display_width(summary) for _, summary in start + other])
1143
+
1144
+ def rows(commands: Sequence[tuple[str, str]]) -> list[str]:
1145
+ return [
1146
+ f"{terminal.brand(name.ljust(width))} {summary}" + " " * (inner - width - 2 - display_width(summary))
1147
+ for name, summary in commands
1148
+ ]
1149
+
1150
+ terminal.note(tr("開始剪片", "Start editing"), rows(start), [hint])
1151
+ terminal.note(tr("其他指令", "Other commands"), rows(other))
1152
+ terminal.outro(
1153
+ terminal.dim(tr("讓 AI 幫你剪影片,再用審片注記修改。", "AI edits your film; you revise it with review notes."))
1101
1154
  )
1102
- print(tr("介面語言:clipen language en|zh-TW|auto", "Language: clipen language en | zh-TW | auto"), file=stream)
1155
+
1156
+
1157
+ _NPM_PACKAGE = "@clipen/clipen-cli"
1158
+
1159
+
1160
+ def _latest_version() -> str:
1161
+ """The newest Clipen published on npm."""
1162
+ from urllib.request import Request, urlopen
1163
+
1164
+ request = Request(f"https://registry.npmjs.org/{_NPM_PACKAGE}/latest", headers={"User-Agent": "Clipen"})
1165
+ with urlopen(request, timeout=15) as response:
1166
+ return str(json.load(response)["version"])
1167
+
1168
+
1169
+ def _version_key(version: str) -> tuple[int, ...]:
1170
+ return tuple(int(part) for part in re.findall(r"\d+", version.split("-")[0]))
1171
+
1172
+
1173
+ def _update(repo_root: Path) -> int:
1174
+ """`clipen update`: install the newest Clipen from npm, through the same installer npx runs."""
1175
+ terminal = Terminal()
1176
+ terminal.intro(f"Clipen {__version__}")
1177
+ if not (repo_root / ".clipen-npm").is_file():
1178
+ terminal.outro(
1179
+ tr(
1180
+ f"這份 Clipen 是從原始碼安裝的:在 {repo_root} 執行 git pull,再執行 ./clipen install。",
1181
+ f"This Clipen was installed from source: in {repo_root}, run git pull, then ./clipen install.",
1182
+ )
1183
+ )
1184
+ return 0
1185
+ try:
1186
+ with terminal.spinner(tr("正在檢查新版", "Checking for a new version")) as spinner:
1187
+ latest = _latest_version()
1188
+ spinner.done(tr("已檢查新版", "Checked for a new version"))
1189
+ except (OSError, ValueError, KeyError) as error:
1190
+ terminal.error(
1191
+ tr("無法檢查新版,請確認網路後再試。", "Could not check for a new version; check your connection.")
1192
+ )
1193
+ terminal.outro(terminal.dim(str(error)))
1194
+ return 1
1195
+ if _version_key(latest) <= _version_key(__version__):
1196
+ terminal.outro(tr(f"已經是最新版 Clipen {__version__}", f"Clipen {__version__} is the latest version"))
1197
+ return 0
1198
+ npx = shutil.which("npx")
1199
+ if npx is None:
1200
+ terminal.outro(tr("更新需要 Node.js:https://nodejs.org", "Updating needs Node.js: https://nodejs.org"))
1201
+ return 1
1202
+ terminal.outro(tr(f"開始更新到 {latest}…", f"Updating to {latest}…"))
1203
+ return subprocess.run([npx, "--yes", f"{_NPM_PACKAGE}@{latest}", "install"], check=False).returncode
1103
1204
 
1104
1205
 
1105
1206
  def _language(arguments: Sequence[str]) -> int:
@@ -1135,14 +1236,20 @@ def main(repo_root: Path, arguments: Sequence[str]) -> int:
1135
1236
 
1136
1237
 
1137
1238
  def _main(repo_root: Path, arguments: Sequence[str]) -> int:
1138
- if list(arguments) in (["--help"], ["-h"]):
1239
+ if list(arguments) in ([], ["--help"], ["-h"]):
1139
1240
  _print_usage(sys.stdout, repo_root)
1140
1241
  return 0
1141
1242
  from clipen.provider_registry import PROVIDERS
1142
1243
 
1244
+ if list(arguments) == ["update"]:
1245
+ return _update(repo_root)
1143
1246
  launch = len(arguments) == 1 and arguments[0] in PROVIDERS
1144
1247
  if list(arguments) not in (["install"], ["uninstall"]) and not launch:
1145
- _print_usage(sys.stderr, repo_root)
1248
+ terminal = Terminal(sys.stderr)
1249
+ terminal.write(
1250
+ f"{terminal.paint('31', '✗')} {tr('沒有這個指令:', 'No such command: ')}{terminal.bold(' '.join(arguments))}"
1251
+ )
1252
+ terminal.write(terminal.dim(tr("執行 clipen 查看可用指令。", "Run clipen to see the commands.")))
1146
1253
  return 2
1147
1254
  try:
1148
1255
  _require_posix_file_locking()
@@ -1201,7 +1308,7 @@ def _main(repo_root: Path, arguments: Sequence[str]) -> int:
1201
1308
 
1202
1309
  python = runtime_python(runtime)
1203
1310
  environment = {
1204
- **sealed_environment(os.environ),
1311
+ **own_ffmpeg.on_path(clipen_data_root(), sealed_environment(os.environ)),
1205
1312
  "CLIPEN_REPO_ROOT": str(repo_root.resolve(strict=True)),
1206
1313
  }
1207
1314
  os.execve(
@@ -3,8 +3,10 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  import asyncio
6
+ import base64
6
7
  import hashlib
7
8
  import json
9
+ import re
8
10
  import secrets
9
11
  import threading
10
12
  from dataclasses import dataclass
@@ -42,6 +44,7 @@ from clipen.projects.models import validate_request_id
42
44
 
43
45
  _SESSION_COOKIE = "clipen_session"
44
46
  _CSRF_HEADER = "x-clipen-csrf"
47
+ _LIVE_PAGE = re.compile(r"/api/projects/[^/]+/production/[^/]+/live/(page|caption)")
45
48
  _INSTANCE_HEADER = "x-clipen-instance"
46
49
  _SESSION_LIFETIME_SECONDS = 12 * 60 * 60
47
50
  _MUTATING_METHODS = frozenset({"POST", "PUT", "PATCH", "DELETE"})
@@ -198,12 +201,16 @@ class LocalRequestGuard:
198
201
  return
199
202
 
200
203
  supplied_origin = headers.get("origin")
204
+ method = str(scope.get("method", "GET")).upper()
205
+ path = str(scope.get("path", ""))
206
+ # A live design runs in a sealed frame with no origin; it may only fetch the fonts Clipen carries.
207
+ if path.startswith("/component-fonts/") and method == "GET" and supplied_origin == "null":
208
+ await self.app(scope, receive, self._secure_send(scope, send))
209
+ return
201
210
  if supplied_origin is not None and supplied_origin != self.origin:
202
211
  await self._reject(scope, receive, send, 403, "invalid_origin")
203
212
  return
204
213
 
205
- method = str(scope.get("method", "GET")).upper()
206
- path = str(scope.get("path", ""))
207
214
  credentials = None
208
215
  if path.startswith("/api/") and path not in {
209
216
  "/api/health",
@@ -243,6 +250,17 @@ class LocalRequestGuard:
243
250
  headers["cross-origin-resource-policy"] = "same-origin"
244
251
  headers["permissions-policy"] = "camera=(), microphone=(), geolocation=(), payment=(), usb=()"
245
252
  path = str(scope.get("path", ""))
253
+ if _LIVE_PAGE.fullmatch(path.split("?", 1)[0]):
254
+ # The design an AI wrote runs sealed: no origin, no network, nothing but Clipen's fonts,
255
+ # inside Clipen's own page only.
256
+ headers["content-security-policy"] = (
257
+ "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; "
258
+ f"font-src {self.origin}; img-src data: blob:; base-uri 'none'; form-action 'none'; "
259
+ "frame-ancestors 'self'; sandbox allow-scripts"
260
+ )
261
+ headers["x-frame-options"] = "SAMEORIGIN"
262
+ elif path.startswith("/component-fonts/"):
263
+ headers["cross-origin-resource-policy"] = "cross-origin"
246
264
  if path.startswith("/api/") or path in {"", "/", "/index.html"}:
247
265
  headers["cache-control"] = "no-store"
248
266
  elif path.startswith("/assets/"):
@@ -717,6 +735,66 @@ def create_app(
717
735
  except ProjectError as error:
718
736
  return await project_error_response(error)
719
737
 
738
+ async def workbench_live(request: Request) -> Response:
739
+ # A free design playing in the person's browser, and the cut it plays over.
740
+ try:
741
+ from clipen.editing.visual_preview import kept_cut, live_page
742
+
743
+ coordinator = require_edit_agents()
744
+ project, run = request.path_params["project_id"], request.path_params["run_id"]
745
+ revision = request.query_params.get("revision", "")
746
+ if request.path_params["part"] == "cut":
747
+ path = await run_in_threadpool(kept_cut, coordinator.repository, project, run, revision)
748
+ return FileResponse(path, media_type="video/mp4", headers={"Cache-Control": "private, no-store"})
749
+ if request.path_params["part"] == "caption":
750
+ from clipen.editing.visual_preview import caption_page
751
+
752
+ item = request.query_params.get("item", "")
753
+ draft = None
754
+ if request.query_params.get("draft"):
755
+ try:
756
+ padded = request.query_params["draft"]
757
+ draft = json.loads(base64.urlsafe_b64decode(padded + "=" * (-len(padded) % 4)))
758
+ except (ValueError, UnicodeDecodeError) as error:
759
+ raise ProjectError("caption_text_invalid", "字幕設定格式不正確。", status_code=422) from error
760
+ page = await run_in_threadpool(
761
+ caption_page, coordinator.repository, project, run, revision, item, draft
762
+ )
763
+ return Response(page, media_type="text/html; charset=utf-8", headers={"Cache-Control": "no-store"})
764
+ if request.path_params["part"] != "page":
765
+ raise ProjectError("not_found", "找不到這個項目。", status_code=404)
766
+ try:
767
+ padded = request.query_params.get("draft", "")
768
+ draft = json.loads(base64.urlsafe_b64decode(padded + "=" * (-len(padded) % 4)))
769
+ except (ValueError, UnicodeDecodeError) as error:
770
+ raise ProjectError("component_invalid", "元件設定格式不正確。", status_code=422) from error
771
+ page = await run_in_threadpool(live_page, coordinator.repository, project, run, revision, draft)
772
+ return Response(page, media_type="text/html; charset=utf-8", headers={"Cache-Control": "no-store"})
773
+ except ProjectError as error:
774
+ return await project_error_response(error)
775
+
776
+ async def component_font(request: Request) -> Response:
777
+ # The fonts Clipen carries, for a live design in its sealed frame (which has no origin of its own).
778
+ from importlib.resources import files
779
+
780
+ from clipen.rendering.custom_render import FONTS
781
+
782
+ name = request.path_params["name"]
783
+ if name.startswith("fetched/"):
784
+ from clipen.rendering.fetched_fonts import root
785
+
786
+ base = root().resolve()
787
+ path = (base / name[len("fetched/") :]).resolve()
788
+ if not (path.is_relative_to(base) and path.is_file() and path.suffix.lower() in {".ttf", ".otf"}):
789
+ return Response(status_code=404)
790
+ elif name in FONTS:
791
+ path = Path(str(files("clipen.rendering").joinpath("fonts", name)))
792
+ else:
793
+ return Response(status_code=404)
794
+ return FileResponse(
795
+ path, media_type="font/ttf", headers={"Access-Control-Allow-Origin": "*", "Cache-Control": "max-age=86400"}
796
+ )
797
+
720
798
  async def project_cover(request: Request) -> Response:
721
799
  # A still cut from the project's own footage for its card on the home page.
722
800
  try:
@@ -1026,30 +1104,12 @@ def create_app(
1026
1104
  )
1027
1105
  elif operation == "resolve":
1028
1106
  require_fields(payload, set())
1029
- from clipen.editing.resolve_export import export_resolve, reveal, start_watching
1107
+ from clipen.editing.resolve_export import export_resolve, reveal
1030
1108
  from clipen.editing.workbench import idle
1031
1109
 
1032
1110
  await run_in_threadpool(idle, coordinator.repository, project, run)
1033
1111
  result = await run_in_threadpool(export_resolve, coordinator.repository, project, run)
1034
1112
  await run_in_threadpool(reveal, Path(result["fcpxml"]))
1035
- # Saving the timeline as .drt in Resolve is enough; Clipen makes the editable copy on its own.
1036
- if result.get("editable_overlays"):
1037
- start_watching(Path(result["folder"]))
1038
- elif operation in {"resolve_titles", "resolve_status"}:
1039
- require_fields(payload, {"folder"})
1040
- from clipen.editing.resolve_export import convert_timeline, export_folder, reveal, timeline_status
1041
-
1042
- exports = (await run_in_threadpool(export_folder, coordinator.repository, project)).resolve()
1043
- package = Path(str(payload["folder"])).resolve()
1044
- if package.parent != exports:
1045
- raise ProjectError(
1046
- "resolve_package_invalid", "只能轉換這個專案匯出到「Clipen 匯出」的資料夾。", status_code=422
1047
- )
1048
- if operation == "resolve_status":
1049
- return JSONResponse(await run_in_threadpool(timeline_status, package))
1050
- target, titles = await run_in_threadpool(convert_timeline, package)
1051
- await run_in_threadpool(reveal, target)
1052
- result = {"drt": str(target), "titles": titles}
1053
1113
  else:
1054
1114
  raise ProjectError("command_invalid", "不支援這個編輯操作。", status_code=404)
1055
1115
  return JSONResponse(result)
@@ -1481,6 +1541,8 @@ def create_app(
1481
1541
  ),
1482
1542
  Route("/api/projects/{project_id}/production/music", production_music, methods=["GET", "POST"]),
1483
1543
  Route("/api/projects/{project_id}/production/{run_id}/workbench", production_workbench, methods=["GET"]),
1544
+ Route("/api/projects/{project_id}/production/{run_id}/live/{part}", workbench_live, methods=["GET"]),
1545
+ Route("/component-fonts/{name:path}", component_font, methods=["GET"]),
1484
1546
  Route(
1485
1547
  "/api/projects/{project_id}/production/{run_id}/workbench/{operation}",
1486
1548
  production_workbench,
@@ -42,6 +42,7 @@ from clipen.projects import ProjectWorkspace
42
42
  from clipen.provider_registry import exec_adapter_factory
43
43
  from clipen.providers import CodexExecAdapter, ProviderUnavailable
44
44
  from clipen.providers.claude import ClaudeCliAdapter
45
+ from clipen.rendering import PreviewRenderRepository
45
46
  from clipen.terminal import Terminal, display_width
46
47
 
47
48
  from .app import (
@@ -425,8 +426,12 @@ async def _serve(
425
426
  )
426
427
  evidence_service.recover()
427
428
  preparation_repository = PreparationRepository(workspace.repository)
429
+ # A film left rendering when Clipen last stopped has no process behind it any more; left
430
+ # as running, the page would wait on it forever and newer saves would never render.
431
+ renders = PreviewRenderRepository(workspace.repository)
428
432
  for project in workspace.repository.list_projects():
429
433
  preparation_repository.interrupt_incomplete(project.project_id)
434
+ renders.interrupt_incomplete(project.project_id)
430
435
  if paths.asr_requirements is not None:
431
436
  analysis_runtime = ManagedAnalysisRuntime(
432
437
  preparation_repository,
@@ -72,8 +72,8 @@ class EditAgentTools(SkillTools, EvidenceTools, ProductionTools):
72
72
  if getattr(self, "_user_edit", False):
73
73
  # Only a person can reword a graphic directly; the AI revises through its own component tools.
74
74
  handlers["edit_component"] = self._edit_component
75
- handlers["set_component_text"] = self._edit_component
76
75
  handlers["edit_component_look"] = self._edit_component_look
76
+ handlers["edit_caption"] = self._edit_caption
77
77
  handler = (lambda args: self.production_call(name, args)) if name in EXTRA_NAMES else handlers.get(name)
78
78
  if handler is None:
79
79
  raise ProjectError("tool_not_allowed", "這個工具未獲 Clipen 授權。", status_code=404)
@@ -0,0 +1,134 @@
1
+ """Captions the AI designs: one web page every caption of the film is drawn with.
2
+
3
+ The page marks where the words go with data-clipen-caption; Clipen fills it with each
4
+ caption's words (emphasised words as <em>) and sets data-delivery on the root to
5
+ dialogue, punchline or quiet. The page may move only while a caption enters and
6
+ leaves (entry_frames, exit_frames); in between it holds still, so a long film's
7
+ captions cost a handful of frames each. Like a look, a new design restyles every
8
+ caption already on the film, and each caption keeps the design it was saved with.
9
+ """
10
+
11
+ import json
12
+ from dataclasses import replace
13
+
14
+ from clipen.domain import TextClip
15
+ from clipen.projects import ProjectError
16
+
17
+ from .agent_models import ToolResult
18
+
19
+ PREFIX = "agent.captions."
20
+
21
+
22
+ def _path(tools):
23
+ return tools.repository.projects.root / tools.project_id / f"caption-design-{tools.run_id}.json"
24
+
25
+
26
+ def current_id(tools):
27
+ """The design new captions are made with, or None before the AI has designed them."""
28
+ path = _path(tools)
29
+ if path.is_symlink():
30
+ raise ProjectError("storage_unsafe", "字幕設計檔案不安全。", status_code=409)
31
+ if not path.exists():
32
+ return None
33
+ return json.loads(path.read_text(encoding="utf-8")).get("design_id")
34
+
35
+
36
+ def chosen_id(tools, row):
37
+ """The design a caption asks for by design_id, or the latest one."""
38
+ if row.get("design_id"):
39
+ from .production_media import load_text_styles
40
+
41
+ design = load_text_styles(tools.repository.projects, tools.project_id).get(row["design_id"])
42
+ if not design or design.get("kind") != "caption_design":
43
+ raise ProjectError(
44
+ "caption_design_not_found",
45
+ "沒有這個字幕設計;用 set_caption_design 回傳的 design_id。",
46
+ status_code=422,
47
+ )
48
+ return row["design_id"]
49
+ return required_id(tools)
50
+
51
+
52
+ def required_id(tools):
53
+ design_id = current_id(tools)
54
+ if design_id is None:
55
+ raise ProjectError(
56
+ "caption_design_required",
57
+ "先用 set_caption_design 設計字幕的樣子,再建立字幕。",
58
+ status_code=422,
59
+ )
60
+ return design_id
61
+
62
+
63
+ def apply(tools, args):
64
+ """Check and save a caption design, then restyle every caption on the film with it."""
65
+ from clipen.finishing.models import digest
66
+ from clipen.rendering import custom_components
67
+
68
+ from . import component_looks
69
+ from .production_media import atomic_json, load_text_styles, text_style_path
70
+ from .skill_tools import _custom_problem
71
+
72
+ html = args.get("html")
73
+ if not isinstance(html, str) or "data-clipen-caption" not in html:
74
+ raise ProjectError(
75
+ "caption_design_invalid",
76
+ "字幕頁面要有一個標了 data-clipen-caption 的元素,Clipen 會把每句字幕放進去。",
77
+ status_code=422,
78
+ )
79
+ look = None
80
+ if args.get("look_id"):
81
+ look = component_looks.current(tools).get(args["look_id"])
82
+ if look is None:
83
+ raise ProjectError(
84
+ "component_look_not_found",
85
+ "沒有這個外觀;先用 set_component_look 建立字幕用的外觀,或從 list_program_components 的 looks 選一個。",
86
+ status_code=422,
87
+ )
88
+ design = {
89
+ "kind": "caption_design",
90
+ "html": html,
91
+ "look": look,
92
+ "entry_frames": args.get("entry_frames", 0),
93
+ "exit_frames": args.get("exit_frames", 0),
94
+ **({"throughout": True} if args.get("throughout") else {}),
95
+ }
96
+ design_id = PREFIX + digest(design)[:24]
97
+ timeline = tools._timeline()
98
+ sample = custom_components.SAMPLE_CAPTION
99
+ item = TextClip("caption-sample", 0, 60, sample["text"], design_id)
100
+ page = custom_components.caption_profile(design, sample["text"], sample["emphasis"], sample["delivery"])
101
+ try:
102
+ custom_components.check(timeline, item, page)
103
+ except custom_components.CustomRenderError as error:
104
+ raise ProjectError(error.code, _custom_problem(error), status_code=422) from error
105
+ styles = load_text_styles(tools.repository.projects, tools.project_id)
106
+ styles[design_id] = design
107
+ tracks, restyled = [], 0
108
+ for track in timeline.tracks:
109
+ items = []
110
+ for clip in track.items:
111
+ profile = styles.get(clip.style_id, {}) if isinstance(clip, TextClip) else {}
112
+ if (
113
+ args.get("apply_to_existing", True)
114
+ and profile.get("kind") == "program_subtitle"
115
+ and profile.get("design") != design_id
116
+ ):
117
+ updated = {**profile, "design": design_id}
118
+ identifier = "agent.text." + digest(updated)[:24]
119
+ styles[identifier] = updated
120
+ clip = replace(clip, style_id=identifier)
121
+ restyled += 1
122
+ items.append(clip)
123
+ tracks.append(replace(track, items=tuple(items)))
124
+ atomic_json(text_style_path(tools.repository.projects, tools.project_id), styles)
125
+ atomic_json(_path(tools), {"design_id": design_id})
126
+ result = {
127
+ "design_id": design_id,
128
+ "captions_restyled": restyled,
129
+ "inspection_required": "Render a preview and watch the captions: legibility over the footage, emphasis, and how they enter and leave.",
130
+ }
131
+ if not restyled:
132
+ return ToolResult(result)
133
+ saved = tools._save(replace(timeline, tracks=tuple(tracks)), args["summary"])
134
+ return ToolResult({**saved.payload, **result})
@@ -15,7 +15,6 @@ import json
15
15
  import re
16
16
 
17
17
  from clipen.projects import ProjectError
18
- from clipen.rendering.custom_components import FONT_CHOICES
19
18
 
20
19
  KEY = re.compile(r"^[A-Za-z0-9_\-一-鿿]{1,24}$")
21
20
  HEX = re.compile(r"^#[0-9a-fA-F]{6}$")
@@ -52,8 +51,9 @@ def normalize(value):
52
51
  entry.get("label") if isinstance(entry.get("label"), str) and entry["label"].strip() else entry["key"]
53
52
  )
54
53
  if kind == "font":
55
- if entry.get("family") not in FONT_CHOICES:
56
- raise _invalid("可用的字型:" + "、".join(FONT_CHOICES) + "。")
54
+ family = entry.get("family")
55
+ if not isinstance(family, str) or not family.strip() or len(family) > 60:
56
+ raise _invalid("字型要寫成字型名稱,例如 PingFang TC、Noto Serif TC。")
57
57
  result.append({"key": entry["key"], "label": label.strip()[:24], "family": entry["family"]})
58
58
  else:
59
59
  if not isinstance(entry.get("value"), str) or not HEX.match(entry["value"]):
@@ -1,43 +1,11 @@
1
1
  """Content checks that keep programme graphics tied to a moment, not a template."""
2
2
 
3
- import re
4
- import unicodedata
5
3
  from collections import Counter
6
4
 
7
- # Short reactions land on one beat; a long hold reads as a static label.
8
- RESTATE_RATIO = 0.5
9
5
  SAME_POSITION_DISTANCE = 0.03
10
6
  SAME_POSITION_RUN = 3
11
7
  UNIFORM_DURATION_SHARE = 0.5
12
8
  UNIFORM_DURATION_MINIMUM = 4
13
- _PARALLEL = re.compile(r"^[^,,・]{2,8}[,,][^,,・]{2,8}$")
14
-
15
-
16
- def significant(text):
17
- return "".join(c for c in unicodedata.normalize("NFKC", text) if unicodedata.category(c)[0] not in "PZCS")
18
-
19
-
20
- def _bigrams(text):
21
- text = significant(text)
22
- return [text[n : n + 2] for n in range(len(text) - 1)]
23
-
24
-
25
- def restated_ratio(text, subtitles):
26
- """Share of the graphic's character pairs copied from concurrent subtitles."""
27
- pairs = _bigrams(text)
28
- spoken = significant("".join(subtitles))
29
- return sum(pair in spoken for pair in pairs) / len(pairs) if pairs else 0.0
30
-
31
-
32
- def concurrent_subtitles(timeline, start, duration):
33
- end = start + duration
34
- return [
35
- i.text
36
- for t in timeline.tracks
37
- if t.track_id == "agent-subtitles"
38
- for i in t.items
39
- if i.start_frame < end and start < i.start_frame + i.duration_frames
40
- ]
41
9
 
42
10
 
43
11
  def design_notes(timeline, elements, styles):
@@ -61,14 +29,8 @@ def design_notes(timeline, elements, styles):
61
29
  duration, count = Counter(round(i.duration_frames / fps * 2) / 2 for i in ordered).most_common(1)[0]
62
30
  if count / len(ordered) > UNIFORM_DURATION_SHARE:
63
31
  notes.append({"code": "component_duration_uniform", "seconds": duration, "count": count})
64
- for element in ordered:
65
- kind = styles.get(element.style_id, {}).get("component_id")
66
- primary = element.text.partition("\n")[0]
67
- if kind not in {"program_title"} and _PARALLEL.match(primary):
68
- notes.append({"code": "component_parallel_phrasing", "item_id": element.item_id, "text": primary})
69
32
  messages = {
70
33
  "component_position_repeated": "連續多個元件擺在同一位置。請依每個畫面的人物、物件與空白處重新決定位置。",
71
34
  "component_duration_uniform": "多數元件的顯示時長相同,節奏像固定節拍。請依每個瞬間的閱讀需要調整。",
72
- "component_parallel_phrasing": "「A,B」對句常只是描述畫面。請改成畫面看不出的資訊或觀點,或移除這個元件。",
73
35
  }
74
36
  return [{**note, "message": messages[note["code"]]} for note in notes]