@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
@@ -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,146 @@ 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(_star(terminal))
1153
+
1154
+
1155
+ _NPM_PACKAGE = "@clipen/clipen-cli"
1156
+ GITHUB = "https://github.com/IMGMANISME/clipen"
1157
+
1158
+
1159
+ def _star(terminal: Terminal) -> str:
1160
+ """The one line that asks for a star, closing the screens people see when things went well."""
1161
+ return (
1162
+ terminal.brand("★ ")
1163
+ + terminal.dim(tr("喜歡 Clipen 的話,到 GitHub 給顆星:", "Like Clipen? Give it a star on GitHub: "))
1164
+ + terminal.link(GITHUB)
1101
1165
  )
1102
- print(tr("介面語言:clipen language en|zh-TW|auto", "Language: clipen language en | zh-TW | auto"), file=stream)
1166
+
1167
+
1168
+ def _latest_version() -> str:
1169
+ """The newest Clipen published on npm."""
1170
+ from urllib.request import Request, urlopen
1171
+
1172
+ request = Request(f"https://registry.npmjs.org/{_NPM_PACKAGE}/latest", headers={"User-Agent": "Clipen"})
1173
+ with urlopen(request, timeout=15) as response:
1174
+ return str(json.load(response)["version"])
1175
+
1176
+
1177
+ def _version_key(version: str) -> tuple[int, ...]:
1178
+ return tuple(int(part) for part in re.findall(r"\d+", version.split("-")[0]))
1179
+
1180
+
1181
+ def _update(repo_root: Path) -> int:
1182
+ """`clipen update`: install the newest Clipen from npm, through the same installer npx runs."""
1183
+ terminal = Terminal()
1184
+ terminal.intro(f"Clipen {__version__}")
1185
+ if not (repo_root / ".clipen-npm").is_file():
1186
+ return _update_source(terminal, repo_root)
1187
+ try:
1188
+ with terminal.spinner(tr("正在檢查新版", "Checking for a new version")) as spinner:
1189
+ latest = _latest_version()
1190
+ spinner.done(tr("已檢查新版", "Checked for a new version"))
1191
+ except (OSError, ValueError, KeyError) as error:
1192
+ terminal.error(
1193
+ tr("無法檢查新版,請確認網路後再試。", "Could not check for a new version; check your connection.")
1194
+ )
1195
+ terminal.outro(terminal.dim(str(error)))
1196
+ return 1
1197
+ if _version_key(latest) <= _version_key(__version__):
1198
+ terminal.outro(tr(f"已經是最新版 Clipen {__version__}", f"Clipen {__version__} is the latest version"))
1199
+ return 0
1200
+ npx = shutil.which("npx")
1201
+ if npx is None:
1202
+ terminal.outro(tr("更新需要 Node.js:https://nodejs.org", "Updating needs Node.js: https://nodejs.org"))
1203
+ return 1
1204
+ terminal.outro(tr(f"開始更新到 {latest}…", f"Updating to {latest}…"))
1205
+ return subprocess.run([npx, "--yes", f"{_NPM_PACKAGE}@{latest}", "install"], check=False).returncode
1206
+
1207
+
1208
+ def _update_source(terminal: Terminal, repo_root: Path) -> int:
1209
+ """A source checkout pulls its branch and installs again; it never merges or discards local work."""
1210
+ git = shutil.which("git")
1211
+ if git is None or not (repo_root / ".git").exists():
1212
+ terminal.outro(
1213
+ tr(
1214
+ f"這份 Clipen 不是 git 專案,無法自動更新:請重新下載 {repo_root} 的原始碼。",
1215
+ f"This Clipen is not a git checkout and cannot update itself; download {repo_root} again.",
1216
+ )
1217
+ )
1218
+ return 1
1219
+
1220
+ def git_run(*arguments: str) -> subprocess.CompletedProcess[str]:
1221
+ return subprocess.run([git, "-C", str(repo_root), *arguments], capture_output=True, text=True, check=False)
1222
+
1223
+ if git_run("status", "--porcelain", "--untracked-files=no").stdout.strip():
1224
+ terminal.outro(
1225
+ tr(
1226
+ f"{repo_root} 有還沒提交的修改,先提交或收起來再更新。",
1227
+ f"{repo_root} has uncommitted changes; commit or stash them, then update.",
1228
+ )
1229
+ )
1230
+ return 1
1231
+ branch = git_run("rev-parse", "--abbrev-ref", "HEAD").stdout.strip()
1232
+ if git_run("rev-parse", "--abbrev-ref", "@{upstream}").returncode != 0:
1233
+ terminal.outro(
1234
+ tr(
1235
+ f"{branch} 分支沒有對應的遠端分支,切回 main 再更新。",
1236
+ f"{branch} has no remote branch to update from; switch to main, then update.",
1237
+ )
1238
+ )
1239
+ return 1
1240
+ before = git_run("rev-parse", "HEAD").stdout.strip()
1241
+ try:
1242
+ with terminal.spinner(tr(f"正在取得 {branch} 的最新程式碼", f"Getting the latest {branch}")) as spinner:
1243
+ pulled = git_run("pull", "--ff-only")
1244
+ if pulled.returncode != 0:
1245
+ raise BootstrapError(next(iter((pulled.stderr or pulled.stdout).strip().splitlines()[-1:]), ""))
1246
+ spinner.done(tr(f"已取得 {branch} 的最新程式碼", f"Got the latest {branch}"))
1247
+ except BootstrapError as error:
1248
+ terminal.outro(
1249
+ tr(
1250
+ f"無法自動更新 {branch},請在 {repo_root} 手動執行 git pull。{error}",
1251
+ f"Could not update {branch}; run git pull in {repo_root} yourself. {error}",
1252
+ ).rstrip()
1253
+ )
1254
+ return 1
1255
+ if git_run("rev-parse", "HEAD").stdout.strip() == before:
1256
+ terminal.outro(tr(f"已經是最新版({branch})", f"Already up to date ({branch})"))
1257
+ return 0
1258
+ terminal.outro(tr("程式碼已更新,接著重新安裝…", "Code updated; installing again…"))
1259
+ # The pulled code installs itself, in a new process, rather than this already-loaded older one.
1260
+ return subprocess.run([sys.executable, "-I", str(repo_root / "clipen"), "install"], check=False).returncode
1103
1261
 
1104
1262
 
1105
1263
  def _language(arguments: Sequence[str]) -> int:
@@ -1135,14 +1293,20 @@ def main(repo_root: Path, arguments: Sequence[str]) -> int:
1135
1293
 
1136
1294
 
1137
1295
  def _main(repo_root: Path, arguments: Sequence[str]) -> int:
1138
- if list(arguments) in (["--help"], ["-h"]):
1296
+ if list(arguments) in ([], ["--help"], ["-h"]):
1139
1297
  _print_usage(sys.stdout, repo_root)
1140
1298
  return 0
1141
1299
  from clipen.provider_registry import PROVIDERS
1142
1300
 
1301
+ if list(arguments) == ["update"]:
1302
+ return _update(repo_root)
1143
1303
  launch = len(arguments) == 1 and arguments[0] in PROVIDERS
1144
1304
  if list(arguments) not in (["install"], ["uninstall"]) and not launch:
1145
- _print_usage(sys.stderr, repo_root)
1305
+ terminal = Terminal(sys.stderr)
1306
+ terminal.write(
1307
+ f"{terminal.paint('31', '✗')} {tr('沒有這個指令:', 'No such command: ')}{terminal.bold(' '.join(arguments))}"
1308
+ )
1309
+ terminal.write(terminal.dim(tr("執行 clipen 查看可用指令。", "Run clipen to see the commands.")))
1146
1310
  return 2
1147
1311
  try:
1148
1312
  _require_posix_file_locking()
@@ -1167,14 +1331,12 @@ def _main(repo_root: Path, arguments: Sequence[str]) -> int:
1167
1331
  f"{terminal.brand('2')} cd to the folder for your projects",
1168
1332
  ),
1169
1333
  tr(
1170
- f"{terminal.brand('3')} 輸入 {terminal.bold('clipen codex')}",
1171
- f"{terminal.brand('3')} Type {terminal.bold('clipen codex')}",
1334
+ f"{terminal.brand('3')} 輸入 {terminal.bold('clipen claude')} 或 {terminal.bold('clipen codex')}",
1335
+ f"{terminal.brand('3')} Type {terminal.bold('clipen claude')} or {terminal.bold('clipen codex')}",
1172
1336
  ),
1173
1337
  ],
1174
1338
  )
1175
- terminal.outro(
1176
- terminal.dim(tr("想改用 Claude Code?輸入 clipen claude", "Prefer Claude Code? Type clipen claude"))
1177
- )
1339
+ terminal.outro(_star(terminal))
1178
1340
  return 0
1179
1341
  if list(arguments) == ["uninstall"]:
1180
1342
  uninstall_installation()
@@ -1201,7 +1363,7 @@ def _main(repo_root: Path, arguments: Sequence[str]) -> int:
1201
1363
 
1202
1364
  python = runtime_python(runtime)
1203
1365
  environment = {
1204
- **sealed_environment(os.environ),
1366
+ **own_ffmpeg.on_path(clipen_data_root(), sealed_environment(os.environ)),
1205
1367
  "CLIPEN_REPO_ROOT": str(repo_root.resolve(strict=True)),
1206
1368
  }
1207
1369
  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/"):
@@ -280,6 +298,7 @@ def create_app(
280
298
  media_previews: MediaPreviewRepository | None = None,
281
299
  edit_agents: EditAgentCoordinator | None = None,
282
300
  provider_account=None,
301
+ provider_model_root: Path | None = None,
283
302
  ) -> ASGIApp:
284
303
  static_root = config.static_root.resolve(strict=True)
285
304
 
@@ -342,6 +361,57 @@ def create_app(
342
361
  )
343
362
  return JSONResponse({"provider": {"id": provider.provider_id, "name": provider.name}, **details})
344
363
 
364
+ async def model_selection_status(_: Request) -> Response:
365
+ from clipen.providers.model_selection import model_selection_locked
366
+
367
+ locked = provider_model_root is None or await run_in_threadpool(model_selection_locked, provider_model_root)
368
+ return JSONResponse({"locked": locked})
369
+
370
+ async def choose_model(request: Request) -> Response:
371
+ from clipen.providers.model_selection import model_selection_locked, save_model, valid_model_id
372
+
373
+ def busy_error() -> ProjectError:
374
+ return ProjectError(
375
+ "model_selection_locked",
376
+ tr("AI 正在執行,完成後才能切換模型。", "Wait for the AI to finish before switching models."),
377
+ status_code=409,
378
+ )
379
+
380
+ try:
381
+ if provider_model_root is None or provider_account is None or provider.state is not ProviderState.READY:
382
+ raise ProjectError(
383
+ "provider_unavailable", tr("AI 尚未準備就緒。", "The AI provider is not ready."), status_code=503
384
+ )
385
+ if await run_in_threadpool(model_selection_locked, provider_model_root):
386
+ raise busy_error()
387
+ payload = await read_json(request)
388
+ require_fields(payload, {"model"})
389
+ model = payload["model"]
390
+ if model is not None:
391
+ if not valid_model_id(model):
392
+ raise ProjectError("model_invalid", tr("模型名稱無效。", "Invalid model name."), status_code=400)
393
+ details = await run_in_threadpool(provider_account)
394
+ if not any(entry["id"] == model for entry in details.get("models", [])):
395
+ raise ProjectError(
396
+ "model_unavailable",
397
+ tr("目前無法選用這個模型。", "This model is currently unavailable."),
398
+ status_code=400,
399
+ )
400
+ await run_in_threadpool(save_model, provider_model_root, provider.provider_id, model)
401
+ return Response(status_code=204)
402
+ except ProjectError as error:
403
+ return await project_error_response(error)
404
+ except BlockingIOError:
405
+ return await project_error_response(busy_error())
406
+ except OSError:
407
+ return await project_error_response(
408
+ ProjectError(
409
+ "model_save_failed",
410
+ tr("無法儲存模型選擇。", "Could not save the model selection."),
411
+ status_code=500,
412
+ )
413
+ )
414
+
345
415
  async def power(request: Request) -> Response:
346
416
  # Lets the UI warn before production: on battery a closed lid still sleeps the Mac.
347
417
  if authority.authenticate(_cookie_value(request.headers, _SESSION_COOKIE)) is None:
@@ -717,6 +787,66 @@ def create_app(
717
787
  except ProjectError as error:
718
788
  return await project_error_response(error)
719
789
 
790
+ async def workbench_live(request: Request) -> Response:
791
+ # A free design playing in the person's browser, and the cut it plays over.
792
+ try:
793
+ from clipen.editing.visual_preview import kept_cut, live_page
794
+
795
+ coordinator = require_edit_agents()
796
+ project, run = request.path_params["project_id"], request.path_params["run_id"]
797
+ revision = request.query_params.get("revision", "")
798
+ if request.path_params["part"] == "cut":
799
+ path = await run_in_threadpool(kept_cut, coordinator.repository, project, run, revision)
800
+ return FileResponse(path, media_type="video/mp4", headers={"Cache-Control": "private, no-store"})
801
+ if request.path_params["part"] == "caption":
802
+ from clipen.editing.visual_preview import caption_page
803
+
804
+ item = request.query_params.get("item", "")
805
+ draft = None
806
+ if request.query_params.get("draft"):
807
+ try:
808
+ padded = request.query_params["draft"]
809
+ draft = json.loads(base64.urlsafe_b64decode(padded + "=" * (-len(padded) % 4)))
810
+ except (ValueError, UnicodeDecodeError) as error:
811
+ raise ProjectError("caption_text_invalid", "字幕設定格式不正確。", status_code=422) from error
812
+ page = await run_in_threadpool(
813
+ caption_page, coordinator.repository, project, run, revision, item, draft
814
+ )
815
+ return Response(page, media_type="text/html; charset=utf-8", headers={"Cache-Control": "no-store"})
816
+ if request.path_params["part"] != "page":
817
+ raise ProjectError("not_found", "找不到這個項目。", status_code=404)
818
+ try:
819
+ padded = request.query_params.get("draft", "")
820
+ draft = json.loads(base64.urlsafe_b64decode(padded + "=" * (-len(padded) % 4)))
821
+ except (ValueError, UnicodeDecodeError) as error:
822
+ raise ProjectError("component_invalid", "元件設定格式不正確。", status_code=422) from error
823
+ page = await run_in_threadpool(live_page, coordinator.repository, project, run, revision, draft)
824
+ return Response(page, media_type="text/html; charset=utf-8", headers={"Cache-Control": "no-store"})
825
+ except ProjectError as error:
826
+ return await project_error_response(error)
827
+
828
+ async def component_font(request: Request) -> Response:
829
+ # The fonts Clipen carries, for a live design in its sealed frame (which has no origin of its own).
830
+ from importlib.resources import files
831
+
832
+ from clipen.rendering.custom_render import FONTS
833
+
834
+ name = request.path_params["name"]
835
+ if name.startswith("fetched/"):
836
+ from clipen.rendering.fetched_fonts import root
837
+
838
+ base = root().resolve()
839
+ path = (base / name[len("fetched/") :]).resolve()
840
+ if not (path.is_relative_to(base) and path.is_file() and path.suffix.lower() in {".ttf", ".otf"}):
841
+ return Response(status_code=404)
842
+ elif name in FONTS:
843
+ path = Path(str(files("clipen.rendering").joinpath("fonts", name)))
844
+ else:
845
+ return Response(status_code=404)
846
+ return FileResponse(
847
+ path, media_type="font/ttf", headers={"Access-Control-Allow-Origin": "*", "Cache-Control": "max-age=86400"}
848
+ )
849
+
720
850
  async def project_cover(request: Request) -> Response:
721
851
  # A still cut from the project's own footage for its card on the home page.
722
852
  try:
@@ -815,6 +945,7 @@ def create_app(
815
945
  "target_duration_seconds",
816
946
  "music_asset_id",
817
947
  "template_id",
948
+ "aspect_ratio",
818
949
  },
819
950
  )
820
951
  run = await run_in_threadpool(
@@ -834,6 +965,7 @@ def create_app(
834
965
  "target_duration_seconds",
835
966
  "music_asset_id",
836
967
  "template_id",
968
+ "aspect_ratio",
837
969
  )
838
970
  if key in payload
839
971
  }
@@ -1002,7 +1134,7 @@ def create_app(
1002
1134
  payload.get("delete_id"),
1003
1135
  )
1004
1136
  elif operation == "frame":
1005
- require_fields(payload, {"expected_revision_id", "frame"}, {"component"})
1137
+ require_fields(payload, {"expected_revision_id", "frame"}, {"component", "slip"})
1006
1138
  from clipen.editing.visual_preview import frame
1007
1139
 
1008
1140
  result = await run_in_threadpool(
@@ -1013,6 +1145,7 @@ def create_app(
1013
1145
  payload["expected_revision_id"],
1014
1146
  payload["frame"],
1015
1147
  payload.get("component"),
1148
+ payload.get("slip"),
1016
1149
  )
1017
1150
  elif operation == "render":
1018
1151
  require_fields(payload, {"expected_revision_id"})
@@ -1026,30 +1159,12 @@ def create_app(
1026
1159
  )
1027
1160
  elif operation == "resolve":
1028
1161
  require_fields(payload, set())
1029
- from clipen.editing.resolve_export import export_resolve, reveal, start_watching
1162
+ from clipen.editing.resolve_export import export_resolve, reveal
1030
1163
  from clipen.editing.workbench import idle
1031
1164
 
1032
1165
  await run_in_threadpool(idle, coordinator.repository, project, run)
1033
1166
  result = await run_in_threadpool(export_resolve, coordinator.repository, project, run)
1034
1167
  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
1168
  else:
1054
1169
  raise ProjectError("command_invalid", "不支援這個編輯操作。", status_code=404)
1055
1170
  return JSONResponse(result)
@@ -1107,6 +1222,49 @@ def create_app(
1107
1222
 
1108
1223
  shutil.rmtree(directory)
1109
1224
 
1225
+ async def add_footage(request: Request) -> Response:
1226
+ """One file added to the project's footage, from any folder or dropped on the page: copied into the
1227
+ project's own added-footage folder, ready for the next footage check."""
1228
+ from clipen.media.discovery import kind_for_name
1229
+ from clipen.media.models import AssetKind
1230
+
1231
+ project = request.path_params["project_id"]
1232
+ target = None
1233
+ try:
1234
+ projects = require_workspace().repository
1235
+ projects.get_project(project)
1236
+ with projects.connect(project) as db:
1237
+ if db.execute(
1238
+ "SELECT 1 FROM inventory_runs WHERE state IN ('queued','running','cancelling')"
1239
+ ).fetchone():
1240
+ raise ProjectError("inventory_busy", "素材正在檢查,等檢查完成再加入。", status_code=409)
1241
+ name = request.query_params.get("filename", "")
1242
+ if not name or len(name) > 200 or "/" in name or "\\" in name or "\x00" in name or name.startswith("."):
1243
+ raise ProjectError("footage_invalid", "檔名無效。", status_code=422)
1244
+ if kind_for_name(name) not in {AssetKind.VIDEO, AssetKind.AUDIO}:
1245
+ raise ProjectError("footage_invalid", "只能加入影片或聲音檔。", status_code=422)
1246
+ folder = await run_in_threadpool(projects.added_footage_folder, project)
1247
+ # Never replace a file already added: a second "IMG_0001.MOV" becomes "IMG_0001 2.MOV".
1248
+ stem, suffix = Path(name).stem, Path(name).suffix
1249
+ target, n = folder / name, 2
1250
+ while target.exists():
1251
+ target, n = folder / f"{stem} {n}{suffix}", n + 1
1252
+ size = 0
1253
+ with target.open("xb") as output:
1254
+ target.chmod(0o600)
1255
+ async for chunk in request.stream():
1256
+ size += len(chunk)
1257
+ output.write(chunk)
1258
+ if not size:
1259
+ raise ProjectError("footage_invalid", "檔案是空的。", status_code=422)
1260
+ added, target = target.name, None
1261
+ return JSONResponse({"name": added, "size_bytes": size}, status_code=201)
1262
+ except ProjectError as error:
1263
+ return await project_error_response(error)
1264
+ finally:
1265
+ if target is not None:
1266
+ target.unlink(missing_ok=True)
1267
+
1110
1268
  async def resume_production(request: Request) -> Response:
1111
1269
  try:
1112
1270
  payload = await read_json(request)
@@ -1480,7 +1638,10 @@ def create_app(
1480
1638
  "/api/projects/{project_id}/production/commands/resume/{run_id}", resume_production, methods=["POST"]
1481
1639
  ),
1482
1640
  Route("/api/projects/{project_id}/production/music", production_music, methods=["GET", "POST"]),
1641
+ Route("/api/projects/{project_id}/footage", add_footage, methods=["POST"]),
1483
1642
  Route("/api/projects/{project_id}/production/{run_id}/workbench", production_workbench, methods=["GET"]),
1643
+ Route("/api/projects/{project_id}/production/{run_id}/live/{part}", workbench_live, methods=["GET"]),
1644
+ Route("/component-fonts/{name:path}", component_font, methods=["GET"]),
1484
1645
  Route(
1485
1646
  "/api/projects/{project_id}/production/{run_id}/workbench/{operation}",
1486
1647
  production_workbench,
@@ -1506,6 +1667,8 @@ def create_app(
1506
1667
  Route("/api/instance/reopen", reopen_instance, methods=["POST"]),
1507
1668
  Route("/api/status", status, methods=["GET"]),
1508
1669
  Route("/api/provider/account", account, methods=["GET"]),
1670
+ Route("/api/provider/model-selection", model_selection_status, methods=["GET"]),
1671
+ Route("/api/provider/commands/choose-model", choose_model, methods=["POST"]),
1509
1672
  Route("/api/system/power", power, methods=["GET"]),
1510
1673
  Route(
1511
1674
  "/api/system/commands/remove-asr",