@clipen/clipen-cli 1.0.4 → 1.0.6

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.
@@ -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)
@@ -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",
@@ -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:
@@ -113,8 +113,13 @@ def versions(database, run_id, provider, styles=None, current=None):
113
113
  elif kind == "provider_switched":
114
114
  current_ai = payload.get("to", current_ai)
115
115
  elif kind == "run_finished":
116
- add("ai_complete", f"{_name(current_ai)} {'打磨' if request else '製作'}完成", row["created_at"], request)
116
+ label = f"{_name(current_ai)} {'打磨' if request else '製作'}完成"
117
+ add("ai_complete", label, row["created_at"], request)
117
118
  if result and result[-1]["revision_id"] == latest:
119
+ # A stopped request that was continued and then finished without further changes ends
120
+ # on the version it stopped at: that version is the finished film now, not a draft.
121
+ if result[-1]["kind"] == "ai_partial":
122
+ result[-1].update(kind="ai_complete", label=label, created_at=row["created_at"])
118
123
  result[-1]["report"] = _report(payload, sent)
119
124
  start = latest
120
125
  elif kind in _STOPS:
@@ -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)
@@ -197,9 +197,16 @@ def record_claude_account(attempt_root: Path, events: list[dict], requested: str
197
197
 
198
198
 
199
199
  def _claude_name(model: str) -> str:
200
- """claude-sonnet-5-20261001 reads as Claude Sonnet 5."""
201
- words = [w for w in model.split("-") if not (w.isdigit() and len(w) == 8)]
202
- return " ".join(w.capitalize() for w in words) or model
200
+ """claude-sonnet-5-20261001 reads as Claude Sonnet 5, and claude-sonnet-5-5 as Claude Sonnet 5.5."""
201
+ words: list[str] = []
202
+ for word in model.split("-"):
203
+ if word.isdigit() and len(word) == 8:
204
+ continue # a release date
205
+ if word.isdigit() and words and words[-1].replace(".", "").isdigit():
206
+ words[-1] += "." + word # the parts of one version number
207
+ else:
208
+ words.append(word.capitalize())
209
+ return " ".join(words) or model
203
210
 
204
211
 
205
212
  def claude_account(attempt_root: Path, environment: Mapping[str, str] | None = None) -> dict:
@@ -52,6 +52,8 @@ class FfmpegPreviewRenderer:
52
52
  if isinstance(i, MediaClip)
53
53
  for e in i.effects
54
54
  )
55
+ from .stage import set_stage
56
+
55
57
  if not layers:
56
58
  return self._render_base(project_id, timeline, output, cancel, progress)
57
59
  from clipen.editing.production_media import mix_audio_layers
@@ -60,6 +62,7 @@ class FfmpegPreviewRenderer:
60
62
  with tempfile.TemporaryDirectory(prefix=".agent-mix-", dir=output.parent) as temp:
61
63
  base = Path(temp) / "camera.mp4"
62
64
  self._render_base(project_id, timeline, base, cancel, lambda p: progress(p * 0.85))
65
+ set_stage("混合配樂與原音")
63
66
  mix_audio_layers(self.media, project_id, timeline, base, output, cancel)
64
67
  progress(1.0)
65
68
 
@@ -167,6 +170,9 @@ class FfmpegPreviewRenderer:
167
170
  return output
168
171
 
169
172
  def _render_media(self, project_id, timeline, output, cancel, progress, *, preserve_audio_gain=False):
173
+ from .stage import set_stage
174
+
175
+ set_stage("剪接畫面與聲音")
170
176
  try:
171
177
  return self._render_media_once(
172
178
  project_id, timeline, output, cancel, progress, preserve_audio_gain=preserve_audio_gain
@@ -0,0 +1,33 @@
1
+ """What a render is doing right now, in words a person reads next to its progress bar.
2
+
3
+ Renders report progress as a number through many nested callbacks; the step
4
+ they are on is set here by the step itself, per thread, so a render running
5
+ in one thread never reads another's.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import threading
11
+ from pathlib import Path
12
+
13
+ _local = threading.local()
14
+
15
+
16
+ def set_stage(text: str | None) -> None:
17
+ _local.stage = text
18
+
19
+
20
+ def current_stage() -> str | None:
21
+ return getattr(_local, "stage", None)
22
+
23
+
24
+ def stage_path(film: Path) -> Path:
25
+ """The hidden file beside a film being rendered that names its current step."""
26
+ return film.with_name(f".{film.stem}.stage")
27
+
28
+
29
+ def read_stage(film: Path) -> str | None:
30
+ try:
31
+ return stage_path(film).read_text(encoding="utf-8").strip()[:80] or None
32
+ except OSError:
33
+ return None
@@ -356,12 +356,16 @@ def compose_dense_titles(
356
356
  # every frame of every graphic, so it reports progress and stops when cancelled.
357
357
  components = [i for i in items if (custom_styles or {}).get(i.style_id, {}).get("kind") == "program_component"]
358
358
  boundaries = set(boundaries)
359
+ from .stage import set_stage
360
+
359
361
  for count, item in enumerate(components):
360
362
  if cancel.is_set():
361
363
  raise TitleRenderError("cancelled")
364
+ set_stage(f"畫自由設計元件 {count + 1}/{len(components)}")
362
365
  report(0.2 * count / len(components))
363
366
  boundaries |= component_boundaries(item, custom_styles[item.style_id], timeline, cancel)
364
367
  boundaries = sorted(boundaries)
368
+ set_stage("繪製字幕與元件")
365
369
  lines = ["ffconcat version 1.0"]
366
370
  events = max(1, len(boundaries) - 1)
367
371
  for index, (start, end) in enumerate(zip(boundaries, boundaries[1:])):
@@ -391,6 +395,7 @@ def compose_dense_titles(
391
395
  )
392
396
  manifest = directory / "text-events.ffconcat"
393
397
  manifest.write_text("\n".join(lines) + "\n")
398
+ set_stage("把字幕與元件疊上影片")
394
399
  report(0.4)
395
400
  seconds = timeline.duration_frames / fps
396
401
  progress_file = directory / "overlay-progress.txt"