@clipen/clipen-cli 1.0.6 → 1.0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -60,13 +60,13 @@ clipen claude # 或 clipen codex
60
60
  - [Node.js](https://nodejs.org) 18 以上
61
61
  - 已登入的 [Claude Code](https://claude.com/claude-code) 或 [Codex CLI](https://github.com/openai/codex)
62
62
 
63
- 安裝程式會在需要時下載固定版本的 Python,不動系統 Python、不需要 sudo,並安裝本機語音辨識模型(約 3 GB)。沒有 ffmpeg 時會提示 `brew install ffmpeg`。
63
+ 安裝程式會下載 Clipen 專用的固定版本 Python(約 25 MB),不使用也不修改你電腦上原有的 Python、不需要 sudo,並安裝本機語音辨識模型(約 3 GB)。全部放在 `~/Library/Application Support/Clipen`。沒有 ffmpeg 時會提示 `brew install ffmpeg`。
64
64
 
65
65
  | 指令 | 做什麼 |
66
66
  | --- | --- |
67
67
  | `clipen claude`/`clipen codex` | 在目前資料夾啟動工作台 |
68
68
  | `npx @clipen/clipen-cli@latest` | 更新到最新版,作品資料保留 |
69
- | `clipen uninstall` | 移除程式、模型與指令,保留作品、毛片與匯出檔 |
69
+ | `clipen uninstall` | 移除 Clipen 專用的 Python、程式、模型與指令,保留作品、毛片與匯出檔 |
70
70
 
71
71
  作品存在資料夾裡的 `.clipen` 子目錄,毛片留在原本的位置。
72
72
 
package/bin/clipen.js CHANGED
@@ -2,9 +2,9 @@
2
2
  // `npx @clipen/clipen-cli`: sets Clipen up on an Apple-silicon Mac with nothing installed beforehand.
3
3
  //
4
4
  // npx unpacks this package into a cache that may be cleared at any time, so the program is
5
- // copied into Clipen's own folder first; the `clipen` command then runs from there. A Mac's own
6
- // python3 is too old, so when no Python 3.10+ is found a fixed standalone build is downloaded and
7
- // checked. Fonts are not in the package; they are downloaded from the sources pinned in
5
+ // copied into Clipen's own folder first; the `clipen` command then runs from there. Clipen runs on
6
+ // its own fixed standalone Python, downloaded and checked into its folder: a Python the person
7
+ // installed (system, Homebrew, pyenv) is never used, so changing or removing it cannot break Clipen. Fonts are not in the package; they are downloaded from the sources pinned in
8
8
  // fonts/manifest.json and checked against their SHA-256. Then the Python installer takes over.
9
9
  'use strict'
10
10
  const { spawnSync } = require('node:child_process')
@@ -60,22 +60,10 @@ async function download(url, target, expected) {
60
60
  fs.renameSync(partial, target)
61
61
  }
62
62
 
63
- /** A Python 3.10 or newer already here: one Clipen fetched before, Homebrew's, or one on PATH. */
63
+ /** Clipen's own Python, if it was fetched before. */
64
64
  function findPython() {
65
65
  const managed = path.join(dataRoot(), 'python', PYTHON.tag, 'bin', 'python3')
66
- const candidates = [managed]
67
- // CLIPEN_PYTHON_SEARCH (directories, colon-separated) narrows the search, e.g. to try a Mac with no Python.
68
- const dirs = process.env.CLIPEN_PYTHON_SEARCH?.split(':') ?? [...(process.env.PATH || '').split(':'), '/opt/homebrew/bin', '/usr/local/bin']
69
- for (const dir of dirs) {
70
- for (const name of ['python3.13', 'python3.12', 'python3.11', 'python3.10', 'python3']) candidates.push(path.join(dir, name))
71
- }
72
- for (const candidate of candidates) {
73
- if (!fs.existsSync(candidate)) continue
74
- const probe = spawnSync(candidate, ['-c', 'import sys; print("%d %d" % sys.version_info[:2])'], { encoding: 'utf8' })
75
- const [major, minor] = (probe.stdout || '').trim().split(' ').map(Number)
76
- if (probe.status === 0 && major === 3 && minor >= 10) return candidate
77
- }
78
- return null
66
+ return fs.existsSync(managed) ? managed : null
79
67
  }
80
68
 
81
69
  async function standalonePython() {
@@ -138,19 +126,20 @@ async function main() {
138
126
  let python = findPython()
139
127
  const app = path.join(dataRoot(), 'app', VERSION)
140
128
  const needs = [
141
- ...(python ? [] : [`Python ${PYTHON.tag.split('+')[0]}(約 ${Math.round(PYTHON.bytes / 1e6)} MB,來自 python-build-standalone,下載後核對檢查碼)`]),
129
+ ...(python ? [] : [`Python ${PYTHON.tag.split('+')[0]}(約 ${Math.round(PYTHON.bytes / 1e6)} MB,Clipen 專用,來自 python-build-standalone,下載後核對檢查碼)`]),
142
130
  ...(fs.existsSync(path.join(app, '.clipen-npm')) ? [] : [`Clipen ${VERSION} 程式(放在 ${app})與內附字型(約 40 MB,開源授權,下載後核對檢查碼)`]),
143
131
  ]
144
132
  if (needs.length) {
145
133
  console.log('Clipen 會先準備:')
146
134
  for (const item of needs) console.log(` • ${item}`)
147
- console.log('不會修改系統 Python,也不會使用 sudo。')
135
+ console.log('全部放在 Clipen 自己的資料夾;不會使用或修改你電腦上原有的 Python,也不會使用 sudo。')
148
136
  if (!(await ask('繼續?[Y/n] '))) { console.log('已取消,沒有下載任何東西。'); return }
149
137
  }
150
138
  if (!python) python = await standalonePython()
151
139
  const target = await program()
152
140
  if (command[0] === 'install') tools()
153
- const run = spawnSync(python, [path.join(target, 'clipen'), ...command], { stdio: 'inherit' })
141
+ // -I: the person's PYTHONPATH, PYTHONHOME and user site never reach Clipen's Python.
142
+ const run = spawnSync(python, ['-I', path.join(target, 'clipen'), ...command], { stdio: 'inherit' })
154
143
  process.exit(run.status ?? 1)
155
144
  }
156
145
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@clipen/clipen-cli",
3
- "version": "1.0.6",
3
+ "version": "1.0.7",
4
4
  "description": "讓 AI 用 Claude Code 或 Codex 幫你剪影片,再用時間線上的審片注記修改",
5
5
  "keywords": [
6
6
  "video-editing",
package/pyproject.toml CHANGED
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "clipen"
7
- version = "1.0.6"
7
+ version = "1.0.7"
8
8
  description = "Let AI cut your video with Claude Code or Codex, and review it with notes on the timeline"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"
@@ -1,3 +1,3 @@
1
1
  """Clipen product package."""
2
2
 
3
- __version__ = "1.0.6"
3
+ __version__ = "1.0.7"
@@ -853,6 +853,30 @@ class ASRSetupManager:
853
853
  os.fsync(output.fileno())
854
854
  os.chmod(path, 0o600)
855
855
 
856
+ def reseat_runtime(self) -> bool:
857
+ """Rebuild a ready release's runtime on the Python running now when it was built on another one
858
+ (an older Clipen used the person's own Python). The downloaded model stays where it is."""
859
+ from clipen.own_python import built_here
860
+
861
+ self._read_release()
862
+ runtime = self.release / "runtime"
863
+ if built_here(runtime):
864
+ return False
865
+ staging = self.root / f".staging-{secrets.token_hex(16)}"
866
+ retired = self.root / f".staging-{secrets.token_hex(16)}"
867
+ try:
868
+ staging.mkdir(mode=0o700)
869
+ self._runtime_installer(staging / "runtime", self.requirements, self._cancel)
870
+ os.replace(runtime, retired)
871
+ os.replace(staging / "runtime", runtime)
872
+ self._read_release()
873
+ finally:
874
+ self._remove_tree(staging, missing_ok=True)
875
+ self._remove_tree(retired, missing_ok=True)
876
+ with self._lock:
877
+ self._status = self._initial_status()
878
+ return True
879
+
856
880
  def _remove_release(self) -> None:
857
881
  self._remove_tree(self.release, missing_ok=True)
858
882
 
@@ -50,6 +50,9 @@ def main(arguments: list[str] | None = None) -> int:
50
50
  try:
51
51
  state = manager.status().state
52
52
  if state is ASRSetupState.READY:
53
+ print("正在確認語音辨識環境使用 Clipen 自己的 Python…", flush=True)
54
+ if manager.reseat_runtime():
55
+ print("✓ 已改用 Clipen 自己的 Python 重建語音辨識環境(模型沿用)", flush=True)
53
56
  print("✓ 本機語音辨識已準備完成", flush=True)
54
57
  return 0
55
58
  if state is ASRSetupState.FAILED:
@@ -33,6 +33,7 @@ from clipen.asr_release import (
33
33
  quick_release_is_ready,
34
34
  release_root,
35
35
  )
36
+ from clipen.own_python import sealed_environment
36
37
 
37
38
  try:
38
39
  import fcntl as _fcntl
@@ -53,9 +54,14 @@ _REMOVABLE_DIRECTORIES = (
53
54
  "runtime", # Legacy source runtime.
54
55
  "runtimes",
55
56
  "asr",
57
+ "alignment",
56
58
  "models",
57
59
  "cache",
58
60
  "logs",
61
+ # What `npx @clipen/clipen-cli` set up: Clipen's own Python and its copies of the program. They go
62
+ # last, since the uninstaller itself runs from them.
63
+ "app",
64
+ "python",
59
65
  )
60
66
  _REMOVABLE_FILES = (
61
67
  "setup.json", # Legacy setup receipt.
@@ -134,6 +140,9 @@ def _runtime_fingerprint(repo_root: Path, *, project_version: bytes | None) -> s
134
140
  digest = hashlib.sha256()
135
141
  digest.update(f"schema={_RUNTIME_SCHEMA}\n".encode())
136
142
  digest.update(f"python={sys.version_info.major}.{sys.version_info.minor}\n".encode())
143
+ # The interpreter the runtime is built on: one built on another Python (a person's pyenv or Homebrew)
144
+ # is rebuilt on Clipen's own, so removing theirs can never break Clipen.
145
+ digest.update(f"interpreter={Path(sys.base_prefix).resolve()}\n".encode())
137
146
  digest.update(f"platform={platform.system()}-{platform.machine()}\n".encode())
138
147
  digest.update(f"repo={repo_root.resolve(strict=True)}\n".encode())
139
148
  digest.update(f"bootstrap-tools={_PIP_VERSION},{_SETUPTOOLS_VERSION},{_WHEEL_VERSION}\n".encode())
@@ -255,7 +264,7 @@ def _confirm_setup(
255
264
  )
256
265
  print(LICENSE_NOTICE, file=stdout)
257
266
  print("依網路速度可能需要數分鐘;安裝期間會持續顯示目前階段與經過時間。", file=stdout)
258
- print("不會修改系統 Python,也不會使用 sudo。", file=stdout)
267
+ print("不會使用或修改你電腦上原有的 Python,也不會使用 sudo。", file=stdout)
259
268
  print("AI(Codex/Claude)登入與模型呼叫不會在設定階段執行。", file=stdout)
260
269
  if not stdin.isatty():
261
270
  raise BootstrapError("第一次設定需要在互動式 Terminal 中確認。")
@@ -328,7 +337,8 @@ def _command_script(repo_root: Path) -> str:
328
337
  raise BootstrapError("Repo 內的 clipen launcher 不存在或不可執行")
329
338
  # Run the launcher with the Python that set Clipen up: a Mac's own python3 is too old.
330
339
  python = Path(sys.executable).resolve()
331
- return f'#!/bin/sh\n{_COMMAND_MARKER}\nexec {shlex.quote(str(python))} {shlex.quote(str(launcher))} "$@"\n'
340
+ # -I: the person's PYTHONPATH, PYTHONHOME and user site never reach Clipen's Python.
341
+ return f'#!/bin/sh\n{_COMMAND_MARKER}\nexec {shlex.quote(str(python))} -I {shlex.quote(str(launcher))} "$@"\n'
332
342
 
333
343
 
334
344
  def _shell_profile(home: Path, environment: Mapping[str, str]) -> Path:
@@ -475,11 +485,7 @@ def _run_logged(command: Sequence[str], *, cwd: Path, log: TextIO) -> None:
475
485
  stderr=subprocess.STDOUT,
476
486
  check=False,
477
487
  timeout=15 * 60,
478
- env={
479
- **os.environ,
480
- "PIP_DISABLE_PIP_VERSION_CHECK": "1",
481
- "PYTHONNOUSERSITE": "1",
482
- },
488
+ env=sealed_environment(os.environ),
483
489
  )
484
490
  if completed.returncode != 0:
485
491
  raise BootstrapError(f"runtime 安裝命令失敗(結束代碼 {completed.returncode})")
@@ -578,8 +584,7 @@ def _install_asr_bundle(
578
584
  errors="replace",
579
585
  bufsize=1,
580
586
  env={
581
- **os.environ,
582
- "PYTHONNOUSERSITE": "1",
587
+ **sealed_environment(os.environ),
583
588
  "CLIPEN_REPO_ROOT": str(repo_root),
584
589
  },
585
590
  )
@@ -717,7 +722,8 @@ def ensure_installation(
717
722
  if installed_runtime is None:
718
723
  return None
719
724
  runtime = installed_runtime
720
- if not asr_ready:
725
+ # A rebuilt runtime may be on a different Python from the one speech recognition was set up on.
726
+ if not asr_ready or not runtime_ready:
721
727
  log_root = selected_data_root / "logs"
722
728
  log_root.mkdir(mode=0o700, parents=True, exist_ok=True)
723
729
  if log_root.is_symlink():
@@ -846,7 +852,7 @@ def uninstall_installation(
846
852
 
847
853
  print("移除 Clipen", file=stdout)
848
854
  print("將會移除:", file=stdout)
849
- print(" • Clipen runtime 與本機語音辨識模型", file=stdout)
855
+ print(" • Clipen 專用的 Python、程式、runtime 與本機語音辨識和對齊模型", file=stdout)
850
856
  print(f" • `clipen` 指令:{command_path}", file=stdout)
851
857
  print(f" • PATH 設定:{profile_path}", file=stdout)
852
858
  print("會保留 Clipen 作品資料、毛片、參考作品與匯出檔案。", file=stdout)
@@ -893,10 +899,11 @@ def uninstall_installation(
893
899
  for name in _REMOVABLE_FILES:
894
900
  _validate_removable_path(resolved_data_root / name, resolved_data_root, directory=False)
895
901
 
902
+ program = ("app", "python")
896
903
  if selected_data_root.exists():
897
904
  for name in _REMOVABLE_DIRECTORIES:
898
905
  path = resolved_data_root / name
899
- if path.exists():
906
+ if name not in program and path.exists():
900
907
  shutil.rmtree(path)
901
908
  for name in _REMOVABLE_FILES:
902
909
  path = resolved_data_root / name
@@ -909,6 +916,10 @@ def uninstall_installation(
909
916
  bin_root.rmdir()
910
917
  if updated_profile != profile:
911
918
  _atomic_write(profile_path, updated_profile, profile_mode)
919
+ for name in program:
920
+ path = resolved_data_root / name
921
+ if selected_data_root.exists() and path.exists():
922
+ shutil.rmtree(path)
912
923
  print("✓ Clipen 已移除", file=stdout)
913
924
  print("作品資料與所有毛片均已保留。", file=stdout)
914
925
  return True
@@ -965,9 +976,8 @@ def main(repo_root: Path, arguments: Sequence[str]) -> int:
965
976
 
966
977
  python = runtime_python(runtime)
967
978
  environment = {
968
- **os.environ,
979
+ **sealed_environment(os.environ),
969
980
  "CLIPEN_REPO_ROOT": str(repo_root.resolve(strict=True)),
970
- "PYTHONNOUSERSITE": "1",
971
981
  }
972
982
  os.execve(
973
983
  python,
@@ -35,6 +35,33 @@ def root_for(data_root):
35
35
 
36
36
 
37
37
  def verified_runtime(root):
38
+ """The runtime's Python and the model, when both are intact and the runtime is on Clipen's own Python."""
39
+ from clipen.own_python import built_here
40
+
41
+ binding = _verified(root)
42
+ return binding if binding and built_here(Path(root) / "runtime") else None
43
+
44
+
45
+ def _build_runtime(destination, cancel):
46
+ from clipen.finishing.audio import run_process
47
+
48
+ venv.EnvBuilder(with_pip=True).create(destination)
49
+ run_process(
50
+ [
51
+ str(destination / "bin/python"),
52
+ "-m",
53
+ "pip",
54
+ "install",
55
+ "--disable-pip-version-check",
56
+ "--no-cache-dir",
57
+ "mlx-audio==0.6.0",
58
+ ],
59
+ cancel,
60
+ timeout=900,
61
+ )
62
+
63
+
64
+ def _verified(root):
38
65
  root = Path(root)
39
66
  receipt = root / "ready.json"
40
67
  model = root / "model"
@@ -71,8 +98,6 @@ def install_runtime(data_root, cancel, progress=lambda _: None):
71
98
  raise ProjectError("alignment_unavailable", "本機對齊目錄尚未設定。", status_code=409)
72
99
  import fcntl
73
100
 
74
- from clipen.finishing.audio import run_process
75
-
76
101
  from .production_media import atomic_json
77
102
 
78
103
  root = root_for(data_root)
@@ -96,6 +121,18 @@ def install_runtime(data_root, cancel, progress=lambda _: None):
96
121
  cancel.wait(0.2)
97
122
  if verified_runtime(root):
98
123
  return {"ready": True, "model": MODEL, "revision": REVISION, "reused": True}
124
+ if _verified(root):
125
+ # Intact, but built on another Python (an older Clipen used the person's own): rebuild only
126
+ # the runtime on Clipen's, and keep the downloaded model.
127
+ progress({"phase": "runtime"})
128
+ staging = root.parent / (".setup-" + uuid.uuid4().hex)
129
+ staging.mkdir(mode=0o700)
130
+ _build_runtime(staging / "runtime", cancel)
131
+ retired = root.parent / (".setup-" + uuid.uuid4().hex)
132
+ os.replace(root / "runtime", retired)
133
+ os.replace(staging / "runtime", root / "runtime")
134
+ shutil.rmtree(retired, ignore_errors=True)
135
+ return {"ready": True, "model": MODEL, "revision": REVISION, "reused": True}
99
136
  if root.exists():
100
137
  # An invalid prior environment is preserved for diagnosis. Never
101
138
  # silently delete an existing user installation during a retry.
@@ -108,19 +145,7 @@ def install_runtime(data_root, cancel, progress=lambda _: None):
108
145
  staging.mkdir(mode=0o700)
109
146
  (staging / "model").mkdir(mode=0o700)
110
147
  progress({"phase": "runtime"})
111
- venv.EnvBuilder(with_pip=True).create(staging / "runtime")
112
- run_process(
113
- [
114
- str(staging / "runtime/bin/python"),
115
- "-m",
116
- "pip",
117
- "install",
118
- "--disable-pip-version-check",
119
- "mlx-audio==0.6.0",
120
- ],
121
- cancel,
122
- timeout=900,
123
- )
148
+ _build_runtime(staging / "runtime", cancel)
124
149
  total = sum(FILES.values())
125
150
  completed = 0
126
151
  for name, size in FILES.items():
@@ -473,9 +473,9 @@ LOOK_HELP = (
473
473
  "refused if one of them would then need a typeface the look no longer has. Typefaces: list_program_components gives font_choices "
474
474
  "(system fonts, plus fonts Clipen carries: Chinese handwriting 'Clipen Chenyu' and brush 'Clipen Iansui', Japanese handwriting "
475
475
  "'Yusei Magic', 'Yomogi', 'Zen Kurenaido', 'Hachi Maru Pop', Japanese display 'Dela Gothic One', 'RocknRoll One', 'Zen Maru Gothic', "
476
- "Latin 'Bebas Neue', 'Anton', 'Caveat', 'Playfair Display'). A character a typeface lacks is drawn by a face of the same feel "
477
- "(Japanese kana in Clipen Chenyu fall to Yomogi), so mixed Chinese and Japanese keep one style; prefer a Japanese face for mainly "
478
- "Japanese text. At most 8 looks, 3 typefaces and 6 colours each."
476
+ "Latin 'Bebas Neue', 'Anton', 'Caveat', 'Playfair Display'). When a typeface lacks a Chinese or Japanese character the graphic "
477
+ "shows, that font key draws all its Chinese and Japanese in the next face of the same feel that has them all (Clipen Chenyu "
478
+ "showing kana moves to Yomogi), never two faces in one word; pick a face that covers the words to keep the one you chose. At most 8 looks, 3 typefaces and 6 colours each."
479
479
  )
480
480
  SKILL_TOOLS = (
481
481
  schema(
@@ -53,6 +53,24 @@ class AgentAudioStore:
53
53
  raise ProjectError("agent_audio_limit", "這個作品已達 48 個音訊候選上限。", status_code=409)
54
54
  atomic_json(self.manifest, records)
55
55
 
56
+ def measure_whole(self, asset_id, cancel):
57
+ """Measure again a track stored when only its first 90 seconds were analysed."""
58
+ from clipen.finishing.audio import ANALYZED_SECONDS_LIMIT, measure_audio
59
+
60
+ records = self.records()
61
+ record = next((r for r in records if r["asset"]["asset_id"] == asset_id), None)
62
+ if record is None:
63
+ return
64
+ asset = record["asset"]
65
+ if asset.get("analyzed_seconds", 0) >= min(asset["duration_seconds"], ANALYZED_SECONDS_LIMIT) - 1:
66
+ return
67
+ fd, _ = open_asset(self.context(asset_id), asset_id)
68
+ try:
69
+ asset.update(measure_audio(fd, asset["stream_index"], cancel))
70
+ finally:
71
+ os.close(fd)
72
+ atomic_json(self.manifest, records)
73
+
56
74
  def public_assets(self):
57
75
  return [
58
76
  {k: v for k, v in r["asset"].items() if k not in {"relative_path", "fingerprint", "mtime_ns", "size_bytes"}}
@@ -634,7 +634,9 @@ class ProductionTools:
634
634
  )
635
635
 
636
636
  def _production_inspect_audio(self, args):
637
- value = next((a for a in self._asset_store().public_assets() if a["asset_id"] == args["asset_id"]), None)
637
+ store = self._asset_store()
638
+ store.measure_whole(args["asset_id"], self._cancel_event())
639
+ value = next((a for a in store.public_assets() if a["asset_id"] == args["asset_id"]), None)
638
640
  if value is None:
639
641
  raise problem("找不到已取得的音訊。")
640
642
  return ToolResult({"asset": value, "heard_by_model": False})
@@ -83,43 +83,9 @@ def inspect_library(role, reference, cancel, progress):
83
83
  raise ValueError("duration unsupported")
84
84
  fd = open_file_beneath(root, entry.relative_path)
85
85
  try:
86
- # Inspect at most 90 seconds: enough for a one-minute proof.
87
- pcm = run_process(
88
- [
89
- "ffmpeg",
90
- "-v",
91
- "error",
92
- "-nostdin",
93
- "-i",
94
- f"/dev/fd/{fd}",
95
- "-map",
96
- f"0:{stream.stream_index}",
97
- "-t",
98
- "90",
99
- "-vn",
100
- "-ac",
101
- "1",
102
- "-ar",
103
- "8000",
104
- "-f",
105
- "s16le",
106
- "pipe:1",
107
- ],
108
- cancel,
109
- pass_fds=(fd,),
110
- timeout=45,
111
- max_bytes=2 * 1024 * 1024,
112
- )
86
+ measured = measure_audio(fd, stream.stream_index, cancel)
113
87
  finally:
114
88
  os.close(fd)
115
- samples = array("h")
116
- samples.frombytes(pcm)
117
- if sys.byteorder != "little":
118
- samples.byteswap()
119
- rms = math.sqrt(sum(v * v for v in samples) / max(1, len(samples))) / 32768
120
- if rms < 0.0001:
121
- raise ValueError("silent audio")
122
- beats, bpm = detect_beats(samples)
123
89
  asset = {
124
90
  "asset_id": "fa_" + digest([role, reference, entry.relative_path, result.fingerprint])[:32],
125
91
  "role": role,
@@ -130,11 +96,7 @@ def inspect_library(role, reference, cancel, progress):
130
96
  "fingerprint": result.fingerprint,
131
97
  "stream_index": stream.stream_index,
132
98
  "duration_seconds": duration,
133
- "rms_db": round(20 * math.log10(rms), 2),
134
- "peak_db": round(20 * math.log10(max(abs(v) for v in samples) / 32768), 2),
135
- "beats_seconds": beats,
136
- "bpm": bpm,
137
- "analyzed_seconds": len(samples) / 8000,
99
+ **measured,
138
100
  }
139
101
  assets.append(asset)
140
102
  progress(min(0.95, len(assets) / 24))
@@ -145,6 +107,55 @@ def inspect_library(role, reference, cancel, progress):
145
107
  return assets, issues
146
108
 
147
109
 
110
+ # The longest film Clipen makes; a song is measured up to here so every cut can land on a beat.
111
+ ANALYZED_SECONDS_LIMIT = 1200
112
+
113
+
114
+ def measure_audio(fd, stream_index, cancel):
115
+ """Loudness, peak and beats of one audio stream, read as 8 kHz mono up to ANALYZED_SECONDS_LIMIT."""
116
+ pcm = run_process(
117
+ [
118
+ "ffmpeg",
119
+ "-v",
120
+ "error",
121
+ "-nostdin",
122
+ "-i",
123
+ f"/dev/fd/{fd}",
124
+ "-map",
125
+ f"0:{stream_index}",
126
+ "-t",
127
+ str(ANALYZED_SECONDS_LIMIT),
128
+ "-vn",
129
+ "-ac",
130
+ "1",
131
+ "-ar",
132
+ "8000",
133
+ "-f",
134
+ "s16le",
135
+ "pipe:1",
136
+ ],
137
+ cancel,
138
+ pass_fds=(fd,),
139
+ timeout=180,
140
+ max_bytes=ANALYZED_SECONDS_LIMIT * 8000 * 2 + 4096,
141
+ )
142
+ samples = array("h")
143
+ samples.frombytes(pcm)
144
+ if sys.byteorder != "little":
145
+ samples.byteswap()
146
+ rms = math.sqrt(sum(v * v for v in samples) / max(1, len(samples))) / 32768
147
+ if rms < 0.0001:
148
+ raise ValueError("silent audio")
149
+ beats, bpm = detect_beats(samples)
150
+ return {
151
+ "rms_db": round(20 * math.log10(rms), 2),
152
+ "peak_db": round(20 * math.log10(max(abs(v) for v in samples) / 32768), 2),
153
+ "beats_seconds": beats,
154
+ "bpm": bpm,
155
+ "analyzed_seconds": len(samples) / 8000,
156
+ }
157
+
158
+
148
159
  def detect_beats(samples):
149
160
  """Energy-onset autocorrelation, with no fabricated beats for flat audio."""
150
161
  hop = 160 # 20 ms, 50 observations per second
@@ -156,17 +167,20 @@ def detect_beats(samples):
156
167
  score, lag = max(scores)
157
168
  if score <= 0:
158
169
  return [], None
159
- # Return observed onset peaks near the periodic pulse; do not invent timestamps.
170
+ # Return observed onset peaks near the periodic pulse; do not invent timestamps. Each found beat
171
+ # sets where the next is looked for, so a pulse that is no whole number of hops does not drift.
160
172
  phase = max(range(lag), key=lambda p: sum(onsets[p::lag]))
161
- beats = []
162
- for index in range(phase, len(onsets), lag):
173
+ strongest, beats, index = max(onsets), [], phase
174
+ while index < len(onsets):
163
175
  low, high = max(0, index - 3), min(len(onsets), index + 4)
164
176
  peak = max(range(low, high), key=lambda i: onsets[i])
165
- if onsets[peak] > max(onsets) * 0.08:
177
+ if onsets[peak] > strongest * 0.08:
166
178
  value = round((peak + 1) * hop / 8000, 3)
167
179
  if not beats or value - beats[-1] > 0.20:
168
180
  beats.append(value)
169
- return beats[:300], round(3000 / lag, 1)
181
+ index = peak
182
+ index += lag
183
+ return beats, round(3000 / lag, 1)
170
184
 
171
185
 
172
186
  def open_asset(context, asset_id):
@@ -0,0 +1,43 @@
1
+ """Clipen runs on its own Python, sealed off from the Python setup of the person whose Mac it is on."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import sys
7
+ from collections.abc import Mapping
8
+ from pathlib import Path
9
+
10
+ # Settings a person's shell may carry for their own Python and pip; none of them reach Clipen.
11
+ _FOREIGN_PREFIXES = ("PYTHON", "PIP_", "CONDA_", "PYENV_", "UV_")
12
+ _FOREIGN_NAMES = {"VIRTUAL_ENV", "PYENV_VERSION", "__PYVENV_LAUNCHER__"}
13
+
14
+
15
+ def sealed_environment(environment: Mapping[str, str]) -> dict[str, str]:
16
+ """The environment Clipen's Python and pip run in: the person's own Python settings, pip
17
+ configuration, caches and user site never take part."""
18
+ sealed = {
19
+ key: value
20
+ for key, value in environment.items()
21
+ if key not in _FOREIGN_NAMES and not key.startswith(_FOREIGN_PREFIXES)
22
+ }
23
+ sealed.update(
24
+ {
25
+ "PYTHONNOUSERSITE": "1",
26
+ "PIP_CONFIG_FILE": os.devnull,
27
+ "PIP_NO_CACHE_DIR": "1",
28
+ "PIP_DISABLE_PIP_VERSION_CHECK": "1",
29
+ }
30
+ )
31
+ return sealed
32
+
33
+
34
+ def built_here(environment_root: Path) -> bool:
35
+ """Whether a virtual environment was built on the Python running now, rather than on another one
36
+ (such as a person's pyenv or Homebrew Python, which they may change or remove)."""
37
+ try:
38
+ lines = (Path(environment_root) / "pyvenv.cfg").read_text(encoding="utf-8").splitlines()
39
+ except (OSError, UnicodeError):
40
+ return False
41
+ homes = [line.split("=", 1)[1].strip() for line in lines if line.split("=", 1)[0].strip() == "home"]
42
+ base = Path(getattr(sys, "_base_executable", sys.executable)).parent
43
+ return len(homes) == 1 and Path(homes[0]).resolve() == base.resolve()
@@ -6,9 +6,12 @@ disk by content, and composited like any other programme graphic, so the
6
6
  preview, the film and the Resolve export show the same picture.
7
7
  """
8
8
 
9
+ import functools
9
10
  import hashlib
10
11
  import json
11
12
  import os
13
+ import re
14
+ import struct
12
15
  import subprocess
13
16
  import sys
14
17
  import tempfile
@@ -109,10 +112,106 @@ FALLBACKS = {
109
112
  }
110
113
 
111
114
 
115
+ def _chain(family):
116
+ return list(dict.fromkeys([family, *FALLBACKS.get(family, []), "PingFang TC"]))
117
+
118
+
119
+ def _stack(chain):
120
+ return ", ".join(f'"{name}"' for name in chain) + ", sans-serif"
121
+
122
+
112
123
  def font_stack(family):
113
124
  """The CSS font list for a typeface: itself, faces of the same feel for missing characters, then PingFang."""
114
- chain = [family, *FALLBACKS.get(family, []), "PingFang TC"]
115
- return ", ".join(f'"{name}"' for name in dict.fromkeys(chain)) + ", sans-serif"
125
+ return _stack(_chain(family))
126
+
127
+
128
+ # Chinese, Japanese kana and half-width kana: where faces of one feel still differ from one another.
129
+ _CJK = re.compile("[぀-ヿㇰ-ㇿ㐀-䶿一-鿿豈-﫿ヲ-゚]")
130
+
131
+
132
+ @functools.lru_cache(maxsize=None)
133
+ def covered(family):
134
+ """The characters a carried font draws, read from its cmap table."""
135
+ from importlib.resources import files
136
+
137
+ data = files("clipen.rendering").joinpath("fonts", BUNDLED[family]["file"]).read_bytes()
138
+ tables = {
139
+ data[12 + 16 * i : 16 + 16 * i]: struct.unpack(">I", data[20 + 16 * i : 24 + 16 * i])[0]
140
+ for i in range(struct.unpack(">H", data[4:6])[0])
141
+ }
142
+ cmap = tables[b"cmap"]
143
+ subtables = {}
144
+ for i in range(struct.unpack(">H", data[cmap + 2 : cmap + 4])[0]):
145
+ platform, encoding, offset = struct.unpack(">HHI", data[cmap + 4 + 8 * i : cmap + 12 + 8 * i])
146
+ subtables[(platform, encoding)] = cmap + offset
147
+ points = set()
148
+ full = subtables.get((3, 10)) or subtables.get((0, 4)) or subtables.get((0, 6))
149
+ if full is not None and struct.unpack(">H", data[full : full + 2])[0] == 12:
150
+ for g in range(struct.unpack(">I", data[full + 12 : full + 16])[0]):
151
+ first, last, _ = struct.unpack(">III", data[full + 16 + 12 * g : full + 28 + 12 * g])
152
+ points.update(range(first, last + 1))
153
+ return frozenset(points)
154
+ base = subtables.get((3, 1)) or subtables.get((0, 3))
155
+ if base is None or struct.unpack(">H", data[base : base + 2])[0] != 4:
156
+ return frozenset()
157
+ segments = struct.unpack(">H", data[base + 6 : base + 8])[0] // 2
158
+ ends = base + 14
159
+ starts, deltas, ranges = ends + 2 * segments + 2, ends + 4 * segments + 2, ends + 6 * segments + 2
160
+
161
+ def word(at):
162
+ return struct.unpack(">H", data[at : at + 2])[0]
163
+
164
+ for s in range(segments):
165
+ first, last, delta, offset = (
166
+ word(starts + 2 * s),
167
+ word(ends + 2 * s),
168
+ word(deltas + 2 * s),
169
+ word(ranges + 2 * s),
170
+ )
171
+ for point in range(first, min(last, 0xFFFE) + 1):
172
+ if offset:
173
+ glyph = word(ranges + 2 * s + offset + 2 * (point - first))
174
+ glyph = (glyph + delta) & 0xFFFF if glyph else 0
175
+ else:
176
+ glyph = (point + delta) & 0xFFFF
177
+ if glyph:
178
+ points.add(point)
179
+ return frozenset(points)
180
+
181
+
182
+ def face_plan(profile):
183
+ """Per look font role: the carried faces of its chain that lack Chinese or Japanese characters the page holds."""
184
+ look = profile.get("look")
185
+ if not look:
186
+ return []
187
+ words = "".join(str(v) for v in (_edits(profile).get("texts") or {}).values())
188
+ needed = set(_CJK.findall(profile["html"] + words))
189
+ if not needed:
190
+ return []
191
+ plan = []
192
+ for font in look["fonts"]:
193
+ chain = _chain(font["family"])
194
+ missing = {f: "".join(sorted(c for c in needed if ord(c) not in covered(f))) for f in chain if f in BUNDLED}
195
+ plan.append({"key": font["key"], "chain": chain, "missing": missing})
196
+ return plan
197
+
198
+
199
+ def one_face(role, shown):
200
+ """The stack that draws every Chinese or Japanese character a role shows in one face, or None when its own does.
201
+
202
+ Letting each missing character fall to the next face mixes two hands in one word (七里ヶ浜 in two styles);
203
+ instead the role moves to the first face of the same feel that has them all. Faces that draw none of
204
+ those characters, such as a Latin display face, stay first for the Latin letters. Fonts Mac carries
205
+ are taken to draw them all."""
206
+ chars = set(_CJK.findall("".join(shown)))
207
+ lacks = {face: chars & set(role["missing"].get(face, "")) for face in role["chain"]}
208
+ if not chars or not lacks[role["chain"][0]]:
209
+ return None
210
+ for index, face in enumerate(role["chain"]):
211
+ if not lacks[face]:
212
+ kept = [f for f in role["chain"][:index] if lacks[f] == chars]
213
+ return _stack(kept + role["chain"][index:])
214
+ return None
116
215
 
117
216
 
118
217
  def look_css(look):
@@ -142,6 +241,8 @@ def _key(profile, timeline, duration):
142
241
  duration,
143
242
  _edits(profile),
144
243
  look_css(profile.get("look")),
244
+ # Bumped when the way a role picks one face changes, so old frames are drawn again.
245
+ "one-face-1",
145
246
  ],
146
247
  ensure_ascii=False,
147
248
  sort_keys=True,
@@ -182,6 +283,7 @@ def frames(timeline, item, profile, wanted, cancel=None):
182
283
  "frame_timeout": FRAME_TIMEOUT_SECONDS,
183
284
  "edits": _edits(profile),
184
285
  "look": look_css(profile.get("look")),
286
+ "faces": face_plan(profile),
185
287
  }
186
288
  _run(job, timeout=30 + FRAME_TIMEOUT_SECONDS + len(missing) * 1.5, cancel=cancel)
187
289
  return paths
@@ -103,6 +103,44 @@ _FIELDS = """
103
103
  }
104
104
  """
105
105
 
106
+ # The words each typeface is asked to draw right now, keyed by the face asked for first.
107
+ _SHOWN = """
108
+ () => {
109
+ const shown = {};
110
+ document.querySelectorAll('body *').forEach((el) => {
111
+ const own = Array.from(el.childNodes).filter((n) => n.nodeType === 3).map((n) => n.textContent).join('').trim();
112
+ if (!own) return;
113
+ const first = getComputedStyle(el).fontFamily.split(',')[0].trim().replace(/^["']|["']$/g, '');
114
+ shown[first] = (shown[first] || '') + own;
115
+ });
116
+ return shown;
117
+ }
118
+ """
119
+
120
+
121
+ def one_face_per_role(page, plan, duration, fps):
122
+ """Give each look role one face for the Chinese and Japanese it shows anywhere in the graphic, before drawing.
123
+
124
+ Text a page writes over time is read at a few fixed moments, so every run of the same graphic decides alike."""
125
+ from clipen.rendering.custom_components import one_face
126
+
127
+ if not plan:
128
+ return
129
+ shown = {}
130
+ for frame in sorted({0, duration // 4, duration // 2, duration * 3 // 4, duration - 1}):
131
+ page.evaluate(_SEEK, [frame, fps])
132
+ for family, words in page.evaluate(_SHOWN).items():
133
+ shown.setdefault(family, []).append(words)
134
+ stacks = {role["key"]: one_face(role, shown.get(role["chain"][0], [])) for role in plan}
135
+ stacks = {key: stack for key, stack in stacks.items() if stack}
136
+ if stacks:
137
+ page.evaluate(
138
+ "(stacks) => Object.entries(stacks).forEach(([key, stack]) =>"
139
+ " document.documentElement.style.setProperty('--look-font-' + key, stack))",
140
+ stacks,
141
+ )
142
+
143
+
106
144
  _SEEK = """
107
145
  async ([frame, fps]) => {
108
146
  const ms = frame / fps * 1000;
@@ -189,6 +227,13 @@ def render(job):
189
227
  (out / "fields.json").write_text(
190
228
  json.dumps(page.evaluate(_FIELDS), ensure_ascii=False), encoding="utf-8"
191
229
  )
230
+ if job["frames"]:
231
+ try:
232
+ one_face_per_role(page, job.get("faces"), int(job["duration"]), fps)
233
+ except TimeoutError:
234
+ fail("custom_component_frame_timeout", "faces")
235
+ except Error as error:
236
+ fail("custom_component_script_error", problems[0] if problems else str(error))
192
237
  for frame in job["frames"]:
193
238
  try:
194
239
  page.evaluate(_SEEK, [int(frame), fps])
@@ -40,7 +40,7 @@
40
40
  - 頁面就是整個畫面(window.clipen.width × height,例如 1920×1080)。只畫元件本身,其餘保持透明,讓素材透出來。用 vw/vh 或依 window.clipen 計算尺寸,不同解析度才會一致。
41
41
  - 時間由 Clipen 控制:CSS 動畫與 Web Animations 會逐格精準播放;用程式畫的話,定義 `window.clipenFrame = (frame, seconds) => {...}`,在裡面畫出那一格。requestAnimationFrame 迴圈、計時器與真實時鐘不會前進。第 0 格是元件出現的第一格,window.clipen 也提供 fps 與 durationFrames。
42
42
  - 沒有網路:圖片與圖形請內嵌(data: URL、inline SVG)。
43
- - 字型只能用元件外觀裡的:寫成 `font-family: var(--look-font-鍵名)`,外觀的顏色是 `var(--look-鍵名)`。用了外觀以外的字型(包括沒指定字型時的瀏覽器預設字)會被擋下。可選的字型列在 list_program_components 的 font_choices:系統字體,加上 Clipen 內附、任何電腦都能用的字型(中文手寫 Clipen Chenyu、楷書筆意 Clipen Iansui;日文手寫 Yusei Magic、Yomogi、Zen Kurenaido、Hachi Maru Pop;日文標題 Dela Gothic One、RocknRoll One、Zen Maru Gothic;英文 Bebas Neue、Anton、Caveat、Playfair Display)。字型缺字時,Clipen 會自動用同樣感覺的字型補上(例如辰宇缺日文假名時用 Yomogi),中日混排也維持同一種風格;日文為主的元件優先選日文字型。想換字或加一套字,就改外觀;用這個外觀的元件會一起換。改外觀時不要拿掉元件還在用的字型鍵名。
43
+ - 字型只能用元件外觀裡的:寫成 `font-family: var(--look-font-鍵名)`,外觀的顏色是 `var(--look-鍵名)`。用了外觀以外的字型(包括沒指定字型時的瀏覽器預設字)會被擋下。可選的字型列在 list_program_components 的 font_choices:系統字體,加上 Clipen 內附、任何電腦都能用的字型(中文手寫 Clipen Chenyu、楷書筆意 Clipen Iansui;日文手寫 Yusei Magic、Yomogi、Zen Kurenaido、Hachi Maru Pop;日文標題 Dela Gothic One、RocknRoll One、Zen Maru Gothic;英文 Bebas Neue、Anton、Caveat、Playfair Display)。字型缺了元件要顯示的中日文字時,這個字型鍵名的中日文會整組換成同樣感覺、而且字都齊全的下一套字型(例如辰宇遇到日文假名就整組改用 Yomogi),一個詞裡不會混兩種字。想保留自己選的字型,就選字都齊全的那一套;日文為主的元件優先選日文字型。想換字或加一套字,就改外觀;用這個外觀的元件會一起換。改外觀時不要拿掉元件還在用的字型鍵名。
44
44
  - 標出使用者可以自己改的地方:主要文字放在加了 `data-clipen-text="鍵名"` 的元素裡(可加 `data-clipen-label="主標"` 當顯示名稱),元素內只放純文字;主要顏色寫成 `:root` 上的 `--clipen-名稱` 變數(例如 `--clipen-主色`、`--clipen-字色`),再用 `var(--clipen-主色)` 套用。使用者在審片頁改的字與顏色會在頁面腳本執行前套上;要逐字拆開做動畫時,在 DOMContentLoaded 之後依元素目前的文字拆。沒有標出時,使用者只能請你重做;每個元件都要標。
45
45
  - 除了字型要來自外觀,只有技術檢查:頁面要能載入、程式不出錯、每格 10 秒內畫完、確實畫出東西、200 KB 以內。
46
46
  - 工具會回傳兩張圖:元件停在畫面上的樣子,以及從進場到退場的多格對照(每格標了第幾格)。兩張都要看:字是否清楚、有沒有擋到臉或字幕、是否服務這一刻;動畫是否看得出順序、節奏是否合適、退場是否乾淨。不滿意就用 update_custom_component 改,只需要給要變的欄位。