@clipen/clipen-cli 1.0.5 → 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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@clipen/clipen-cli",
3
- "version": "1.0.5",
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.5"
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.5"
3
+ __version__ = "1.0.7"
@@ -379,6 +379,9 @@ def _terminate(process: subprocess.Popen[bytes]) -> None:
379
379
  except ProcessLookupError:
380
380
  process.wait(timeout=2)
381
381
  return
382
+ except PermissionError:
383
+ # macOS refuses to signal a group whose members have all exited; end the leader itself.
384
+ process.terminate()
382
385
  else:
383
386
  process.terminate()
384
387
  try:
@@ -389,6 +392,8 @@ def _terminate(process: subprocess.Popen[bytes]) -> None:
389
392
  os.killpg(process.pid, signal.SIGKILL)
390
393
  except ProcessLookupError:
391
394
  pass
395
+ except PermissionError:
396
+ process.kill()
392
397
  else:
393
398
  process.kill()
394
399
  process.wait(timeout=2)
@@ -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
 
@@ -904,6 +928,9 @@ class ASRSetupManager:
904
928
  os.killpg(process.pid, signal.SIGTERM)
905
929
  except ProcessLookupError:
906
930
  return
931
+ except PermissionError:
932
+ # macOS refuses to signal a group whose members have all exited; end the leader itself.
933
+ process.terminate()
907
934
  else:
908
935
  process.terminate()
909
936
  try:
@@ -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:
@@ -891,6 +891,9 @@ def _terminate(process: subprocess.Popen[bytes]) -> None:
891
891
  except ProcessLookupError:
892
892
  process.wait(timeout=2)
893
893
  return
894
+ except PermissionError:
895
+ # macOS refuses to signal a group whose members have all exited; end the leader itself.
896
+ process.terminate()
894
897
  else:
895
898
  process.terminate()
896
899
  try:
@@ -901,6 +904,8 @@ def _terminate(process: subprocess.Popen[bytes]) -> None:
901
904
  os.killpg(process.pid, signal.SIGKILL)
902
905
  except ProcessLookupError:
903
906
  pass
907
+ except PermissionError:
908
+ process.kill()
904
909
  else:
905
910
  process.kill()
906
911
  process.wait(timeout=2)
@@ -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():
@@ -188,8 +188,14 @@ class EditAgentCoordinator:
188
188
  if row is None:
189
189
  return None
190
190
  entry = json.loads(row["payload_json"])
191
+ store = PreviewRenderRepository(self.repository.projects)
192
+ render = store.get(project_id, entry["render_id"])
193
+ if render["state"] == "running":
194
+ from clipen.rendering.stage import read_stage
195
+
196
+ render["stage"] = read_stage(store.output_path(project_id, entry["render_id"], prepare=False))
191
197
  return {
192
- **PreviewRenderRepository(self.repository.projects).get(project_id, entry["render_id"]),
198
+ **render,
193
199
  "revision_id": entry["revision_id"],
194
200
  "stale": entry["revision_id"] != draft.revision_id or entry.get("recipe_id") != recipe_id,
195
201
  "media_url": f"/api/projects/{project_id}/preview/{entry['render_id']}/media",
@@ -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"}}
@@ -15,6 +15,7 @@ from clipen.media import MediaPreviewRepository
15
15
  from clipen.projects import ProjectError
16
16
  from clipen.projects.storage import utc_now
17
17
  from clipen.rendering import FfmpegPreviewRenderer, PreviewRenderRepository
18
+ from clipen.rendering.stage import current_stage, set_stage, stage_path
18
19
 
19
20
  from .agent_models import ToolResult
20
21
 
@@ -133,9 +134,24 @@ def render_preview(tools):
133
134
  if store.get(tools.project_id, render["render_id"])["state"] == "cancelling":
134
135
  cancel.set()
135
136
 
137
+ stage_file = None
138
+ said = [None]
139
+
140
+ def say(stage):
141
+ # The step under way goes to a small file beside the film, for the status to show.
142
+ if stage != said[0] and stage_file is not None:
143
+ said[0] = stage
144
+ try:
145
+ stage_file.write_text(stage or "", encoding="utf-8")
146
+ except OSError:
147
+ pass
148
+
136
149
  def progress(value):
137
150
  check()
138
151
  store.update_progress(tools.project_id, render["render_id"], value)
152
+ # FFmpeg's progress can arrive on a reader thread that does not know the step; keep the last one.
153
+ if current_stage() is not None:
154
+ say(current_stage())
139
155
 
140
156
  # Some steps run for minutes between progress reports, so a cancel or the end of the run
141
157
  # is also picked up here rather than only when the renderer next reports.
@@ -153,10 +169,14 @@ def render_preview(tools):
153
169
  try:
154
170
  staging = store.output_path(tools.project_id, render["render_id"], staging=True)
155
171
  final = store.output_path(tools.project_id, render["render_id"])
172
+ stage_file = stage_path(final)
173
+ set_stage(None)
156
174
  store.mark_running(tools.project_id, render["render_id"])
157
175
  renderer.render(tools.project_id, revision.timeline, staging, cancel, progress)
158
176
  if cancel.is_set():
159
177
  raise ProjectError("user_cancelled", "已取消預覽。", status_code=409)
178
+ set_stage("檢查輸出的影片")
179
+ say("檢查輸出的影片")
160
180
  verify_output(staging, revision.timeline, cancel)
161
181
  os.replace(staging, final)
162
182
  final.chmod(0o600)
@@ -190,6 +210,9 @@ def render_preview(tools):
190
210
  )
191
211
  finally:
192
212
  finished.set()
213
+ set_stage(None)
214
+ if stage_file is not None:
215
+ stage_file.unlink(missing_ok=True)
193
216
  if staging is not None:
194
217
  staging.unlink(missing_ok=True)
195
218
  if staging is not None:
@@ -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):
@@ -403,6 +403,9 @@ def _terminate(process: subprocess.Popen[bytes]) -> None:
403
403
  except ProcessLookupError:
404
404
  process.wait(timeout=2)
405
405
  return
406
+ except PermissionError:
407
+ # macOS refuses to signal a group whose members have all exited; end the leader itself.
408
+ process.terminate()
406
409
  else:
407
410
  process.terminate()
408
411
  try:
@@ -413,6 +416,8 @@ def _terminate(process: subprocess.Popen[bytes]) -> None:
413
416
  os.killpg(process.pid, signal.SIGKILL)
414
417
  except ProcessLookupError:
415
418
  pass
419
+ except PermissionError:
420
+ process.kill()
416
421
  else:
417
422
  process.kill()
418
423
  process.wait(timeout=2)
@@ -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()