@clipen/clipen-cli 1.0.9 → 1.1.0

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 (53) hide show
  1. package/README.md +53 -43
  2. package/README.zh-TW.md +99 -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 +4 -2
  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 +70 -15
  13. package/src/clipen/cli.py +4 -1
  14. package/src/clipen/controller/app.py +102 -1
  15. package/src/clipen/controller/server.py +14 -6
  16. package/src/clipen/editing/agent_repository.py +29 -3
  17. package/src/clipen/editing/agent_tools.py +1 -0
  18. package/src/clipen/editing/aspect.py +27 -0
  19. package/src/clipen/editing/production_catalog.py +10 -3
  20. package/src/clipen/editing/production_media.py +1 -1
  21. package/src/clipen/editing/production_preview.py +7 -0
  22. package/src/clipen/editing/production_tools.py +7 -2
  23. package/src/clipen/editing/skill_tools.py +8 -0
  24. package/src/clipen/editing/slip.py +109 -0
  25. package/src/clipen/editing/tool_receipts.py +1 -0
  26. package/src/clipen/editing/versions.py +2 -0
  27. package/src/clipen/editing/visual_preview.py +11 -3
  28. package/src/clipen/editing/workbench.py +33 -1
  29. package/src/clipen/locale_en.py +18 -0
  30. package/src/clipen/mcp_editing/server.py +3 -1
  31. package/src/clipen/media/discovery.py +2 -2
  32. package/src/clipen/media/preview.py +5 -0
  33. package/src/clipen/media/storage.py +5 -2
  34. package/src/clipen/projects/models.py +2 -0
  35. package/src/clipen/projects/storage.py +84 -4
  36. package/src/clipen/providers/account.py +37 -6
  37. package/src/clipen/providers/claude.py +5 -3
  38. package/src/clipen/providers/claude_editing.py +5 -6
  39. package/src/clipen/providers/codex.py +19 -7
  40. package/src/clipen/providers/codex_editing.py +2 -1
  41. package/src/clipen/providers/editing_agent.py +24 -2
  42. package/src/clipen/providers/model_selection.py +67 -0
  43. package/src/clipen/rendering/cover.py +1 -1
  44. package/src/clipen/rendering/program_subtitles.py +3 -1
  45. package/src/clipen/rendering/renderer.py +13 -3
  46. package/src/clipen/skills/builtin/references/graphics.md +1 -1
  47. package/src/clipen/skills/builtin/templates.json +9 -0
  48. package/src/clipen/workspace.py +21 -0
  49. package/apps/web/dist/assets/index-DPgSvXZ1.js +0 -15
  50. package/apps/web/dist/assets/index-DmPWV61v.css +0 -1
  51. package/src/clipen/editing/EDITORIAL_REGRESSIONS.md +0 -38
  52. package/src/clipen/editing/REFACTOR_DESIGN.md +0 -241
  53. package/src/clipen/editing/REFACTOR_HANDOFF.md +0 -73
@@ -298,6 +298,7 @@ def create_app(
298
298
  media_previews: MediaPreviewRepository | None = None,
299
299
  edit_agents: EditAgentCoordinator | None = None,
300
300
  provider_account=None,
301
+ provider_model_root: Path | None = None,
301
302
  ) -> ASGIApp:
302
303
  static_root = config.static_root.resolve(strict=True)
303
304
 
@@ -360,6 +361,57 @@ def create_app(
360
361
  )
361
362
  return JSONResponse({"provider": {"id": provider.provider_id, "name": provider.name}, **details})
362
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
+
363
415
  async def power(request: Request) -> Response:
364
416
  # Lets the UI warn before production: on battery a closed lid still sleeps the Mac.
365
417
  if authority.authenticate(_cookie_value(request.headers, _SESSION_COOKIE)) is None:
@@ -893,6 +945,7 @@ def create_app(
893
945
  "target_duration_seconds",
894
946
  "music_asset_id",
895
947
  "template_id",
948
+ "aspect_ratio",
896
949
  },
897
950
  )
898
951
  run = await run_in_threadpool(
@@ -912,6 +965,7 @@ def create_app(
912
965
  "target_duration_seconds",
913
966
  "music_asset_id",
914
967
  "template_id",
968
+ "aspect_ratio",
915
969
  )
916
970
  if key in payload
917
971
  }
@@ -1080,7 +1134,7 @@ def create_app(
1080
1134
  payload.get("delete_id"),
1081
1135
  )
1082
1136
  elif operation == "frame":
1083
- require_fields(payload, {"expected_revision_id", "frame"}, {"component"})
1137
+ require_fields(payload, {"expected_revision_id", "frame"}, {"component", "slip"})
1084
1138
  from clipen.editing.visual_preview import frame
1085
1139
 
1086
1140
  result = await run_in_threadpool(
@@ -1091,6 +1145,7 @@ def create_app(
1091
1145
  payload["expected_revision_id"],
1092
1146
  payload["frame"],
1093
1147
  payload.get("component"),
1148
+ payload.get("slip"),
1094
1149
  )
1095
1150
  elif operation == "render":
1096
1151
  require_fields(payload, {"expected_revision_id"})
@@ -1167,6 +1222,49 @@ def create_app(
1167
1222
 
1168
1223
  shutil.rmtree(directory)
1169
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
+
1170
1268
  async def resume_production(request: Request) -> Response:
1171
1269
  try:
1172
1270
  payload = await read_json(request)
@@ -1540,6 +1638,7 @@ def create_app(
1540
1638
  "/api/projects/{project_id}/production/commands/resume/{run_id}", resume_production, methods=["POST"]
1541
1639
  ),
1542
1640
  Route("/api/projects/{project_id}/production/music", production_music, methods=["GET", "POST"]),
1641
+ Route("/api/projects/{project_id}/footage", add_footage, methods=["POST"]),
1543
1642
  Route("/api/projects/{project_id}/production/{run_id}/workbench", production_workbench, methods=["GET"]),
1544
1643
  Route("/api/projects/{project_id}/production/{run_id}/live/{part}", workbench_live, methods=["GET"]),
1545
1644
  Route("/component-fonts/{name:path}", component_font, methods=["GET"]),
@@ -1568,6 +1667,8 @@ def create_app(
1568
1667
  Route("/api/instance/reopen", reopen_instance, methods=["POST"]),
1569
1668
  Route("/api/status", status, methods=["GET"]),
1570
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"]),
1571
1672
  Route("/api/system/power", power, methods=["GET"]),
1572
1673
  Route(
1573
1674
  "/api/system/commands/remove-asr",
@@ -166,28 +166,35 @@ class ServerPaths:
166
166
  def provider_account(provider_id: str, attempt_root: Path, ttl: float = 60.0) -> Callable[[], dict]:
167
167
  """A cached, read-only lookup of the running model and remaining quota."""
168
168
  from clipen.providers.account import claude_account, codex_account
169
+ from clipen.providers.model_selection import CLAUDE_MODELS, selected_model
169
170
 
170
171
  lock, cache = threading.Lock(), {}
171
172
 
172
- def lookup() -> dict:
173
+ def lookup(selection: str | None) -> dict:
173
174
  if provider_id == "claude":
174
175
  from clipen.providers.claude import claude_environment
175
176
 
176
- return claude_account(attempt_root, claude_environment())
177
+ return {
178
+ **claude_account(attempt_root, claude_environment(), model_override=selection),
179
+ "models": [{"id": model, "name": name} for model, name in CLAUDE_MODELS.items()],
180
+ }
177
181
  if provider_id != "codex":
178
182
  return {"model": None, "quota": None}
179
183
  try:
180
184
  adapter = CodexExecAdapter(attempt_root)
181
185
  except ProviderUnavailable:
182
186
  return {"model": None, "quota": None}
183
- return codex_account(adapter.binary, adapter._environment)
187
+ return codex_account(adapter.binary, adapter._environment, model_override=selection, include_models=True)
184
188
 
185
189
  def cached() -> dict:
190
+ selection = selected_model(attempt_root, provider_id)
191
+ if provider_id == "claude":
192
+ return {**lookup(selection), "selected_model": selection}
186
193
  with lock:
187
- if cache and time.monotonic() - cache["at"] < ttl:
194
+ if cache and cache["selection"] == selection and time.monotonic() - cache["at"] < ttl:
188
195
  return cache["value"]
189
- value = lookup()
190
- cache.update(at=time.monotonic(), value=value)
196
+ value = {**lookup(selection), "selected_model": selection}
197
+ cache.update(at=time.monotonic(), value=value, selection=selection)
191
198
  return value
192
199
 
193
200
  return cached
@@ -459,6 +466,7 @@ async def _serve(
459
466
  media_previews=media_previews,
460
467
  edit_agents=edit_agents,
461
468
  provider_account=provider_account(provider.provider_id, paths.attempt_root),
469
+ provider_model_root=paths.attempt_root,
462
470
  )
463
471
  config = uvicorn.Config(
464
472
  app,
@@ -64,6 +64,7 @@ class EditAgentRepository:
64
64
  "target_duration_seconds",
65
65
  "music_asset_id",
66
66
  "template_id",
67
+ "aspect_ratio",
67
68
  }
68
69
  ):
69
70
  raise ProjectError("production_input_invalid", "請選擇剪輯樣板並填寫影片需求。", status_code=422)
@@ -102,6 +103,10 @@ class EditAgentRepository:
102
103
  # The template skill was chosen directly; keep its design brief in the intent.
103
104
  template = skill["template"]
104
105
  skill["selected_template_id"] = template["template_id"]
106
+ from .aspect import DEFAULT_ASPECT, canvas, checked
107
+
108
+ # The shape is chosen with the film; a template suggests one (short-form is vertical).
109
+ aspect = checked(production.get("aspect_ratio", (template or {}).get("aspect_ratio", DEFAULT_ASPECT)))
105
110
  target = production.get("target_duration_seconds", skill.get("default_duration_seconds", 60))
106
111
  if isinstance(target, bool) or not isinstance(target, int) or not 30 <= target <= 1200:
107
112
  raise ProjectError("production_input_invalid", "預計片長必須為 30 到 1200 秒。", status_code=422)
@@ -121,6 +126,7 @@ class EditAgentRepository:
121
126
  **({"font_style_id": selected_font} if font_supplied else {}),
122
127
  **({"target_duration_seconds": target} if "target_duration_seconds" in production else {}),
123
128
  **({"music_asset_id": production["music_asset_id"]} if "music_asset_id" in production else {}),
129
+ **({"aspect_ratio": aspect} if "aspect_ratio" in production else {}),
124
130
  }
125
131
  creative_direction = {**PROGRAM_DIRECTION, "production_requirements": FULL_PRODUCTION_REQUIREMENTS}
126
132
  creative_direction = validate_direction(creative_direction)
@@ -186,8 +192,7 @@ class EditAgentRepository:
186
192
  None,
187
193
  None,
188
194
  Rational(30, 1),
189
- 1280,
190
- 720,
195
+ *canvas(aspect),
191
196
  0,
192
197
  (Track("video-main", TrackKind.VIDEO, ()),),
193
198
  production_session_id=run_id,
@@ -231,6 +236,7 @@ class EditAgentRepository:
231
236
  "visual_style_id": selected,
232
237
  "font_style_id": selected_font,
233
238
  "target_duration_seconds": target,
239
+ "aspect_ratio": aspect,
234
240
  "music_choice": selected_music,
235
241
  # The AI writes in the language of the person who asked.
236
242
  **({"language": "en"} if english() else {}),
@@ -357,6 +363,7 @@ class EditAgentRepository:
357
363
  expected_references_version=None,
358
364
  provider=None,
359
365
  ):
366
+ from .production_media import source_rows
360
367
  from .refinement_references import hand_over, public_state, references
361
368
  from .workbench import music_choice
362
369
 
@@ -378,6 +385,8 @@ class EditAgentRepository:
378
385
  **({"provider": provider} if provider is not None else {}),
379
386
  }
380
387
  )
388
+ # Footage checked since the film began (added later, or new in the footage folder) joins it now.
389
+ checked = source_rows(self.projects, project_id)
381
390
  with self.projects.connect(project_id) as db:
382
391
  db.execute("BEGIN IMMEDIATE")
383
392
  receipt = db.execute("SELECT * FROM edit_agent_command_receipts WHERE request_id=?", (request,)).fetchone()
@@ -394,7 +403,9 @@ class EditAgentRepository:
394
403
  raise ProjectError("edit_agent_busy", "請先停止目前的 AI 製作。", status_code=409)
395
404
  if run.current_revision_id != expected_revision_id:
396
405
  raise ProjectError("revision_conflict", "影片已更新,請重新讀取後提出修改。", status_code=409)
397
- session = db.execute("SELECT intent_json FROM production_sessions WHERE run_id=?", (normalized,)).fetchone()
406
+ session = db.execute(
407
+ "SELECT intent_json, sources_json FROM production_sessions WHERE run_id=?", (normalized,)
408
+ ).fetchone()
398
409
  if session is None:
399
410
  raise ProjectError("production_required", "這個版本不支援持續修訂。", status_code=422)
400
411
  intent = json.loads(session["intent_json"])
@@ -412,6 +423,21 @@ class EditAgentRepository:
412
423
  "created_at": utc_now(),
413
424
  "references": reference_snapshot,
414
425
  }
426
+ # Footage the film has not had yet is granted, kept beside every source it already uses,
427
+ # and named for the AI so it decides whether and where it belongs.
428
+ granted = json.loads(session["sources_json"])
429
+ held = {(s["version_id"], s["stream_index"]) for s in granted}
430
+ arrived = [s for s in checked if (s["version_id"], s["stream_index"]) not in held]
431
+ if arrived:
432
+ inventory = db.execute("SELECT run_id FROM current_inventory WHERE slot=1").fetchone()
433
+ db.execute(
434
+ "UPDATE production_sessions SET sources_json=?, inventory_run_id=? WHERE run_id=?",
435
+ (encoded(granted + arrived), inventory["run_id"], normalized),
436
+ )
437
+ intent["latest_revision_request"]["new_sources"] = [
438
+ {k: s[k] for k in ("version_id", "stream_index", "display_name", "kind", "duration_seconds")}
439
+ for s in arrived
440
+ ]
415
441
  # What the last change left for the person goes with the next request, so it is not lost.
416
442
  from .change_report import carried
417
443
 
@@ -74,6 +74,7 @@ class EditAgentTools(SkillTools, EvidenceTools, ProductionTools):
74
74
  handlers["edit_component"] = self._edit_component
75
75
  handlers["edit_component_look"] = self._edit_component_look
76
76
  handlers["edit_caption"] = self._edit_caption
77
+ handlers["slip_clip"] = self._slip_clip
77
78
  handler = (lambda args: self.production_call(name, args)) if name in EXTRA_NAMES else handlers.get(name)
78
79
  if handler is None:
79
80
  raise ProjectError("tool_not_allowed", "這個工具未獲 Clipen 授權。", status_code=404)
@@ -0,0 +1,27 @@
1
+ """A film's shape, chosen when it is set up and kept for every revision."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from clipen.projects import ProjectError
6
+
7
+ ASPECT_RATIOS = {"16:9": (16, 9), "9:16": (9, 16), "1:1": (1, 1), "4:5": (4, 5)}
8
+ DEFAULT_ASPECT = "16:9"
9
+ # The sizes a preview may use, by the length of its shorter side.
10
+ SHORT_SIDES = (360, 720, 1080)
11
+
12
+
13
+ def checked(aspect: object) -> str:
14
+ if aspect not in ASPECT_RATIOS:
15
+ raise ProjectError("production_input_invalid", "畫面比例必須是 16:9、9:16、1:1 或 4:5。", status_code=422)
16
+ return str(aspect)
17
+
18
+
19
+ def canvas(aspect: str, short_side: int = 720) -> tuple[int, int]:
20
+ """Width and height for the shape, its shorter side short_side pixels, both even."""
21
+ across, down = ASPECT_RATIOS[aspect]
22
+ long_side = round(short_side * max(across, down) / min(across, down) / 2) * 2
23
+ return (long_side, short_side) if across >= down else (short_side, long_side)
24
+
25
+
26
+ def aspect_of(width: int, height: int) -> str | None:
27
+ return next((name for name, (a, d) in ASPECT_RATIOS.items() if width * d == height * a), None)
@@ -129,8 +129,15 @@ EXTRA_TOOLS = (
129
129
  ),
130
130
  schema(
131
131
  "set_canvas",
132
- "Choose a bounded SDR preview canvas before styling. Changes the revision and invalidates previous render review; source media and timing remain intact.",
133
- {"width": {"enum": [640, 1280, 1920]}, "height": {"enum": [360, 720, 1080]}, **SUMMARY},
132
+ "Choose a bounded SDR preview canvas before styling, in the film's shape (intent.aspect_ratio: 16:9, 9:16, 1:1 or 4:5; "
133
+ "the person chose it and it cannot change). Sizes by the shorter side: 360, 720 or 1080 pixels, e.g. 1280x720 for 16:9, "
134
+ "720x1280 for 9:16, 720x720 for 1:1, 720x900 for 4:5. Changes the revision and invalidates previous render review; "
135
+ "source media and timing remain intact.",
136
+ {
137
+ "width": {"type": "integer", "minimum": 360, "maximum": 1920},
138
+ "height": {"type": "integer", "minimum": 360, "maximum": 1920},
139
+ **SUMMARY,
140
+ },
134
141
  ),
135
142
  schema(
136
143
  "set_target_duration",
@@ -455,7 +462,7 @@ CAPTION_DESIGN_HELP = (
455
462
  CUSTOM_COMPONENT_HELP = (
456
463
  "Design an in-picture graphic freely as one self-contained web page: any HTML, CSS, SVG, Canvas or JavaScript, any layout, "
457
464
  "typeface, colour, shape or motion. Every graphic in the film is made this way; there are no built-in components. "
458
- "The page is the whole picture (window.clipen.width x window.clipen.height pixels, e.g. 1920x1080); draw only the graphic and leave "
465
+ "The page is the whole picture (window.clipen.width x window.clipen.height pixels in the film's shape, e.g. 1920x1080 for 16:9, 1080x1920 for 9:16); draw only the graphic and leave "
459
466
  "the rest transparent, so the footage shows through. Clipen sets the time: CSS animations and the Web Animations API play by "
460
467
  "themselves, frame-accurately; for script-driven drawing define window.clipenFrame = (frame, seconds) => {...} (may be async) "
461
468
  "and draw that exact frame there. requestAnimationFrame loops, timers and real clocks do not advance. Frame 0 is the first frame "
@@ -427,7 +427,7 @@ def source_rows(projects, project_id):
427
427
  """The live inventory is the authority; prior planning windows are not a source boundary."""
428
428
  with projects.connect(project_id) as db:
429
429
  rows = db.execute(
430
- "SELECT i.version_id,i.display_name,s.stream_index,s.kind,s.details_json,v.probe_json FROM current_inventory c JOIN inventory_runs r ON r.run_id=c.run_id JOIN inventory_items i ON i.run_id=r.run_id JOIN assets a ON a.asset_id=i.asset_id JOIN asset_versions v ON v.version_id=i.version_id JOIN media_streams s ON s.version_id=i.version_id WHERE c.slot=1 AND r.state='succeeded' AND a.role='source' AND i.status='usable' AND s.kind IN ('video','audio') ORDER BY i.display_name,i.version_id,s.stream_index LIMIT 10001"
430
+ "SELECT i.version_id,i.display_name,s.stream_index,s.kind,s.details_json,v.probe_json FROM current_inventory c JOIN inventory_runs r ON r.run_id=c.run_id JOIN inventory_items i ON i.run_id=r.run_id JOIN assets a ON a.asset_id=i.asset_id JOIN asset_versions v ON v.version_id=i.version_id JOIN media_streams s ON s.version_id=i.version_id WHERE c.slot=1 AND r.state='succeeded' AND a.role IN ('source','added') AND i.status='usable' AND s.kind IN ('video','audio') ORDER BY i.display_name,i.version_id,s.stream_index LIMIT 10001"
431
431
  ).fetchall()
432
432
  if len(rows) > 10000:
433
433
  raise ProjectError("agent_source_limit", "素材串流超過上限,請拆分作品。", status_code=409)
@@ -80,6 +80,13 @@ def render_preview(tools):
80
80
  if entry["revision_id"] == revision.revision_id and entry.get("recipe_id") == recipe_id:
81
81
  saved = store.get(tools.project_id, entry["render_id"])
82
82
  if saved["state"] in {"queued", "running", "succeeded"}:
83
+ # Back on a version rendered before (after an undo or going back in History): its film is
84
+ # the latest one again, so the review page plays it.
85
+ _event(
86
+ tools,
87
+ "production_preview",
88
+ {"render_id": saved["render_id"], "revision_id": revision.revision_id, "recipe_id": recipe_id},
89
+ )
83
90
  return ToolResult({"render": saved, "revision_id": revision.revision_id, "reused": True})
84
91
  current = store.current(tools.project_id)
85
92
  if current and current["state"] in {"queued", "running", "cancelling"}:
@@ -239,8 +239,13 @@ class ProductionTools:
239
239
  )
240
240
 
241
241
  def _production_set_canvas(self, args):
242
- if args["width"] * 9 != args["height"] * 16:
243
- raise problem("目前樣片畫布需要 16:9。")
242
+ from .aspect import DEFAULT_ASPECT, SHORT_SIDES, canvas
243
+
244
+ aspect = self._session_value()["intent"].get("aspect_ratio", DEFAULT_ASPECT)
245
+ allowed = [canvas(aspect, side) for side in SHORT_SIDES]
246
+ if (args["width"], args["height"]) not in allowed:
247
+ sizes = "、".join(f"{w}×{h}" for w, h in allowed)
248
+ raise problem(f"這支影片是 {aspect},畫布只能是 {sizes}。")
244
249
  return self._save(replace(self._timeline(), width=args["width"], height=args["height"]), args["summary"])
245
250
 
246
251
  def _production_plan_episode(self, args):
@@ -315,6 +315,14 @@ class SkillTools:
315
315
  changed.update({"caption_text_edited": True, "wording_authority": "user", "verification": "user_corrected"})
316
316
  return replace(item, text=text, style_id="agent.text." + digest(changed)[:24]), changed
317
317
 
318
+ def _slip_clip(self, args):
319
+ """A person slips one shot: same place and length in the film, an earlier or later stretch of its footage."""
320
+ self._require_keys(args, {"item_id", "frames"}, optional={"summary"})
321
+ from .slip import slipped
322
+
323
+ timeline, details = slipped(self, args["item_id"], args["frames"])
324
+ return self._save(timeline, "微調鏡頭片段", **details)
325
+
318
326
  def _edit_caption(self, args):
319
327
  """A person corrects one caption: its words, how it is delivered, which words stand out."""
320
328
  from .production_media import atomic_json, load_text_styles, text_style_path
@@ -0,0 +1,109 @@
1
+ """Slip a shot: it keeps where and how long it plays in the film, and shows an earlier or later stretch
2
+ of its footage, for example to let a sentence finish that the cut stopped short."""
3
+
4
+ from dataclasses import replace
5
+ from fractions import Fraction
6
+ from math import floor
7
+
8
+ from clipen.domain import TextClip
9
+ from clipen.projects import ProjectError
10
+
11
+ # Picture treatment drawn for particular moments of the footage cannot follow it to other moments.
12
+ _PINNED_TO_MOMENTS = frozenset({"video.mosaic"})
13
+
14
+
15
+ def problem(message):
16
+ return ProjectError("slip_invalid", message, status_code=422)
17
+
18
+
19
+ def room(tools, item):
20
+ """How many frames the shot can slip earlier and later before it runs off its footage."""
21
+ span = item.source.span
22
+ row = next(
23
+ (
24
+ r
25
+ for r in tools._source_rows()
26
+ if r["version_id"] == span.version_id and r["stream_index"] == span.stream_index
27
+ ),
28
+ None,
29
+ )
30
+ if row is None:
31
+ return 0, 0
32
+ timeline = tools._timeline()
33
+ unit = Fraction(span.time_base.numerator, span.time_base.denominator)
34
+ fps = Fraction(timeline.frame_rate.numerator, timeline.frame_rate.denominator)
35
+ earlier = floor((int(span.start_pts) - int(row["start_pts"])) * unit * fps)
36
+ later = floor((int(row["end_pts"]) - int(span.end_pts)) * unit * fps)
37
+ return max(0, earlier), max(0, later)
38
+
39
+
40
+ def slipped(tools, item_id, frames):
41
+ """The timeline with the shot moved `frames` later in its footage (earlier when negative).
42
+
43
+ Its captions move with the speech they show and leave when that speech leaves the shot; graphics,
44
+ music and every other shot stay where they are."""
45
+ if isinstance(frames, bool) or not isinstance(frames, int) or frames == 0:
46
+ raise problem("請指定要往前或往後移動幾格。")
47
+ timeline = tools._timeline()
48
+ video = tools._video()
49
+ item = next((i for i in video.items if i.item_id == item_id), None)
50
+ if item is None:
51
+ raise problem("找不到這個鏡頭。")
52
+ fps = Fraction(timeline.frame_rate.numerator, timeline.frame_rate.denominator)
53
+ earlier, later = room(tools, item)
54
+ if not -earlier <= frames <= later:
55
+ raise problem(
56
+ f"這個鏡頭最多只能往前 {float(earlier / fps):.1f} 秒、往後 {float(later / fps):.1f} 秒,再過去就沒有毛片了。"
57
+ )
58
+ span = item.source.span
59
+ unit = Fraction(span.time_base.numerator, span.time_base.denominator)
60
+ shift = round(Fraction(frames) / fps / unit)
61
+ moved_span = replace(span, start_pts=str(int(span.start_pts) + shift), end_pts=str(int(span.end_pts) + shift))
62
+ removed_effects = [e.effect_id for e in item.effects if e.effect_id in _PINNED_TO_MOMENTS]
63
+ shot = replace(
64
+ item,
65
+ source=replace(item.source, span=moved_span, handle_before_pts=0, handle_after_pts=0),
66
+ effects=tuple(e for e in item.effects if e.effect_id not in _PINNED_TO_MOMENTS),
67
+ )
68
+
69
+ from .production_media import load_text_styles
70
+
71
+ styles = load_text_styles(tools.repository.projects, tools.project_id)
72
+ first, last = item.start_frame, item.start_frame + item.duration_frames
73
+ moved, removed = [], []
74
+ tracks = []
75
+ for track in timeline.tracks:
76
+ if track.track_id == video.track_id:
77
+ tracks.append(replace(track, items=tuple(shot if i.item_id == item_id else i for i in track.items)))
78
+ continue
79
+ if track.track_id != "agent-subtitles":
80
+ tracks.append(track)
81
+ continue
82
+ kept = []
83
+ for caption in track.items:
84
+ profile = styles.get(caption.style_id, {}) if isinstance(caption, TextClip) else {}
85
+ anchored = profile.get("anchor_item_id")
86
+ belongs = anchored == item_id or (
87
+ anchored is None
88
+ and first <= caption.start_frame
89
+ and caption.start_frame + caption.duration_frames <= last
90
+ )
91
+ if not belongs:
92
+ kept.append(caption)
93
+ continue
94
+ start = caption.start_frame - frames
95
+ if first <= start and start + caption.duration_frames <= last:
96
+ kept.append(replace(caption, start_frame=start))
97
+ moved.append(caption.item_id)
98
+ else:
99
+ removed.append({"item_id": caption.item_id, "text": getattr(caption, "text", "")})
100
+ tracks.append(replace(track, items=tuple(kept)))
101
+ seconds = float(Fraction(int(moved_span.start_pts)) * unit)
102
+ return replace(timeline, tracks=tuple(tracks)), {
103
+ "item_id": item_id,
104
+ "source_start_seconds": round(seconds, 3),
105
+ "source_end_seconds": round(float(Fraction(int(moved_span.end_pts)) * unit), 3),
106
+ "moved_captions": moved,
107
+ "removed_captions": removed,
108
+ "removed_effects": removed_effects,
109
+ }
@@ -37,6 +37,7 @@ TIMELINE_MUTATIONS = frozenset(
37
37
  "update_custom_component",
38
38
  "edit_component",
39
39
  "edit_caption",
40
+ "slip_clip",
40
41
  "set_component_look",
41
42
  "set_caption_design",
42
43
  "edit_component_look",
@@ -53,6 +53,7 @@ _MANUAL = {
53
53
  "set_component_text": "元件文字",
54
54
  "edit_component": "修改元件",
55
55
  "edit_caption": "修改字幕",
56
+ "slip_clip": "微調鏡頭片段",
56
57
  "edit_component_look": "元件外觀",
57
58
  }
58
59
 
@@ -79,6 +80,7 @@ _MANUAL_EN = {
79
80
  "set_component_text": "graphic text",
80
81
  "edit_component": "edited a graphic",
81
82
  "edit_caption": "edited a caption",
83
+ "slip_clip": "slipped a shot",
82
84
  "edit_component_look": "graphic look",
83
85
  }
84
86
 
@@ -25,15 +25,23 @@ from clipen.rendering.titles import TitleCardRenderer, TitleRenderError
25
25
  from .production_media import load_text_styles
26
26
 
27
27
 
28
- def frame(repository, project_id, run_id, expected_revision_id, frame_number, component=None):
28
+ def frame(repository, project_id, run_id, expected_revision_id, frame_number, component=None, slip=None):
29
29
  """One still of the current version.
30
30
 
31
31
  component ({element_id, ...unsaved settings}) draws that graphic as the person's changes would
32
- leave it, and the result says where it sits so the page can let them drag it."""
32
+ leave it, and the result says where it sits so the page can let them drag it. slip ({item_id,
33
+ frames}) shows a shot slipped in its footage before the person saves it."""
33
34
  revision = repository.current_revision(project_id, run_id)
34
35
  timeline = revision.timeline
35
36
  if revision.revision_id != expected_revision_id:
36
37
  raise ProjectError("revision_conflict", "影片已更新,正在重新讀取編輯畫面。", status_code=409)
38
+ if slip is not None:
39
+ if not isinstance(slip, dict) or set(slip) != {"item_id", "frames"}:
40
+ raise ProjectError("frame_invalid", "微調設定無效。", status_code=422)
41
+ from .slip import slipped
42
+ from .workbench import tools_for
43
+
44
+ timeline, _ = slipped(tools_for(repository, project_id, run_id), slip["item_id"], slip["frames"])
37
45
  if (
38
46
  isinstance(frame_number, bool)
39
47
  or not isinstance(frame_number, int)
@@ -101,7 +109,7 @@ def frame(repository, project_id, run_id, expected_revision_id, frame_number, co
101
109
  else:
102
110
  effects.append(effect)
103
111
  still_clip = replace(clip, effects=tuple(effects))
104
- filters = f"scale={timeline.width}:{timeline.height}:force_original_aspect_ratio=decrease,pad={timeline.width}:{timeline.height}:(ow-iw)/2:(oh-ih)/2"
112
+ filters = FfmpegPreviewRenderer.fill_filter(clip, timeline)
105
113
  filters += FfmpegPreviewRenderer._video_effect_filters(still_clip, timeline) + grade_filters(clip)
106
114
  with tempfile.TemporaryDirectory(prefix="clipen-edit-frame-") as temporary:
107
115
  output = Path(temporary) / "source.png"