@clipen/clipen-cli 1.0.8 → 1.0.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/README.md +57 -39
  2. package/README.zh-TW.md +98 -0
  3. package/apps/web/dist/assets/index-BHFCflzf.js +15 -0
  4. package/apps/web/dist/assets/index-BtenOBwP.css +1 -0
  5. package/apps/web/dist/favicon.svg +1 -1
  6. package/apps/web/dist/index.html +2 -2
  7. package/bin/clipen.js +10 -17
  8. package/package.json +2 -2
  9. package/pyproject.toml +1 -1
  10. package/src/clipen/__init__.py +1 -1
  11. package/src/clipen/annotations/suggestions.py +1 -1
  12. package/src/clipen/bootstrap.py +190 -28
  13. package/src/clipen/controller/app.py +185 -22
  14. package/src/clipen/controller/server.py +19 -6
  15. package/src/clipen/editing/agent_repository.py +29 -3
  16. package/src/clipen/editing/agent_tools.py +2 -1
  17. package/src/clipen/editing/aspect.py +27 -0
  18. package/src/clipen/editing/caption_design.py +134 -0
  19. package/src/clipen/editing/component_looks.py +3 -3
  20. package/src/clipen/editing/component_review.py +0 -38
  21. package/src/clipen/editing/coordinator.py +14 -0
  22. package/src/clipen/editing/production_catalog.py +77 -16
  23. package/src/clipen/editing/production_media.py +14 -3
  24. package/src/clipen/editing/production_preview.py +18 -9
  25. package/src/clipen/editing/production_progress.py +2 -0
  26. package/src/clipen/editing/production_tools.py +18 -22
  27. package/src/clipen/editing/program_subtitles.py +5 -13
  28. package/src/clipen/editing/resolve_export.py +2 -183
  29. package/src/clipen/editing/skill_tools.py +150 -218
  30. package/src/clipen/editing/slip.py +109 -0
  31. package/src/clipen/editing/tool_receipts.py +3 -1
  32. package/src/clipen/editing/versions.py +4 -0
  33. package/src/clipen/editing/visual_preview.py +73 -3
  34. package/src/clipen/editing/workbench.py +53 -1
  35. package/src/clipen/locale_en.py +36 -0
  36. package/src/clipen/mcp_editing/server.py +3 -1
  37. package/src/clipen/media/discovery.py +2 -2
  38. package/src/clipen/media/preview.py +5 -0
  39. package/src/clipen/media/storage.py +5 -2
  40. package/src/clipen/own_ffmpeg.py +113 -0
  41. package/src/clipen/projects/models.py +2 -0
  42. package/src/clipen/projects/storage.py +84 -4
  43. package/src/clipen/providers/account.py +37 -6
  44. package/src/clipen/providers/claude.py +5 -3
  45. package/src/clipen/providers/claude_editing.py +5 -6
  46. package/src/clipen/providers/codex.py +19 -7
  47. package/src/clipen/providers/codex_editing.py +2 -1
  48. package/src/clipen/providers/editing_agent.py +30 -6
  49. package/src/clipen/providers/model_selection.py +67 -0
  50. package/src/clipen/rendering/cover.py +1 -1
  51. package/src/clipen/rendering/custom_components.py +216 -25
  52. package/src/clipen/rendering/custom_render.py +90 -54
  53. package/src/clipen/rendering/fetched_fonts.py +127 -0
  54. package/src/clipen/rendering/production_effects.py +24 -2
  55. package/src/clipen/rendering/program_components.py +18 -240
  56. package/src/clipen/rendering/program_subtitles.py +3 -1
  57. package/src/clipen/rendering/renderer.py +36 -20
  58. package/src/clipen/rendering/titles.py +29 -12
  59. package/src/clipen/skills/builtin/SKILL.md +3 -3
  60. package/src/clipen/skills/builtin/assets/sample-daily-vlog.mp4 +0 -0
  61. package/src/clipen/skills/builtin/assets/sample-event-recap.mp4 +0 -0
  62. package/src/clipen/skills/builtin/assets/sample-food-review.mp4 +0 -0
  63. package/src/clipen/skills/builtin/assets/sample-product-demo.mp4 +0 -0
  64. package/src/clipen/skills/builtin/assets/sample-product-review.mp4 +0 -0
  65. package/src/clipen/skills/builtin/assets/sample-product-unboxing.mp4 +0 -0
  66. package/src/clipen/skills/builtin/assets/sample-shorts-highlight.mp4 +0 -0
  67. package/src/clipen/skills/builtin/assets/sample-travel-highlight.mp4 +0 -0
  68. package/src/clipen/skills/builtin/assets/sample-travel-vlog.mp4 +0 -0
  69. package/src/clipen/skills/builtin/assets/style-tpl-daily-vlog.png +0 -0
  70. package/src/clipen/skills/builtin/assets/style-tpl-event-recap.png +0 -0
  71. package/src/clipen/skills/builtin/assets/style-tpl-food-review.png +0 -0
  72. package/src/clipen/skills/builtin/assets/style-tpl-product-demo.png +0 -0
  73. package/src/clipen/skills/builtin/assets/style-tpl-product-review.png +0 -0
  74. package/src/clipen/skills/builtin/assets/style-tpl-product-unboxing.png +0 -0
  75. package/src/clipen/skills/builtin/assets/style-tpl-shorts-highlight.png +0 -0
  76. package/src/clipen/skills/builtin/assets/style-tpl-travel-highlight.png +0 -0
  77. package/src/clipen/skills/builtin/assets/style-tpl-travel-vlog.png +0 -0
  78. package/src/clipen/skills/builtin/references/captions.md +12 -0
  79. package/src/clipen/skills/builtin/references/graphics.md +7 -6
  80. package/src/clipen/skills/builtin/template-skills/clipen-daily-vlog/SKILL.md +9 -4
  81. package/src/clipen/skills/builtin/template-skills/clipen-event-recap/SKILL.md +10 -5
  82. package/src/clipen/skills/builtin/template-skills/clipen-food-review/SKILL.md +9 -4
  83. package/src/clipen/skills/builtin/template-skills/clipen-product-demo/SKILL.md +10 -6
  84. package/src/clipen/skills/builtin/template-skills/clipen-product-review/SKILL.md +10 -6
  85. package/src/clipen/skills/builtin/template-skills/clipen-product-unboxing/SKILL.md +9 -7
  86. package/src/clipen/skills/builtin/template-skills/clipen-shorts-highlight/SKILL.md +10 -5
  87. package/src/clipen/skills/builtin/template-skills/clipen-travel-highlight/SKILL.md +10 -5
  88. package/src/clipen/skills/builtin/template-skills/clipen-travel-vlog/SKILL.md +10 -7
  89. package/src/clipen/skills/builtin/templates.json +9 -0
  90. package/src/clipen/skills/catalog.py +0 -8
  91. package/src/clipen/skills/package.py +1 -10
  92. package/apps/web/dist/assets/index-CJ80KHsQ.css +0 -1
  93. package/apps/web/dist/assets/index-C_4u_hVf.js +0 -16
  94. package/src/clipen/editing/EDITORIAL_REGRESSIONS.md +0 -38
  95. package/src/clipen/editing/REFACTOR_DESIGN.md +0 -241
  96. package/src/clipen/editing/REFACTOR_HANDOFF.md +0 -73
  97. package/src/clipen/editing/resolve_titles.py +0 -291
  98. package/src/clipen/rendering/program_creator.py +0 -804
  99. package/src/clipen/rendering/program_identities.py +0 -350
  100. package/src/clipen/rendering/program_motion.py +0 -186
  101. package/src/clipen/rendering/program_studio.py +0 -227
  102. package/src/clipen/rendering/program_styles.py +0 -321
  103. package/src/clipen/skills/builtin/components.json +0 -133
@@ -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"
@@ -187,3 +195,65 @@ def frame(repository, project_id, run_id, expected_revision_id, frame_number, co
187
195
  "scope": "editing_still",
188
196
  "component_box": box,
189
197
  }
198
+
199
+
200
+ def live_page(repository, project_id, run_id, expected_revision_id, component):
201
+ """A free design as a page the person's browser plays live, with their unsaved changes."""
202
+ from clipen.rendering import custom_components
203
+
204
+ from .workbench import tools_for
205
+
206
+ revision = repository.current_revision(project_id, run_id)
207
+ if revision.revision_id != expected_revision_id:
208
+ raise ProjectError("revision_conflict", "影片已更新,正在重新讀取編輯畫面。", status_code=409)
209
+ draft, profile, _ = tools_for(repository, project_id, run_id)._component_draft(component, checked=False)
210
+ if not custom_components.is_custom(profile):
211
+ raise ProjectError("component_not_live", "這個元件不能在瀏覽器即時播放。", status_code=422)
212
+ return custom_components.live_page(revision.timeline, draft, profile)
213
+
214
+
215
+ def caption_page(repository, project_id, run_id, expected_revision_id, item_id, draft=None):
216
+ """A caption as its design draws it, as a page the person's browser plays live; draft holds
217
+ a person's unsaved words, delivery and emphasis."""
218
+ from clipen.rendering import custom_components
219
+
220
+ revision = repository.current_revision(project_id, run_id)
221
+ if revision.revision_id != expected_revision_id:
222
+ raise ProjectError("revision_conflict", "影片已更新,正在重新讀取編輯畫面。", status_code=409)
223
+ styles = load_text_styles(repository.projects, project_id)
224
+ item = next(
225
+ (
226
+ i
227
+ for t in revision.timeline.tracks
228
+ if t.track_id == "agent-subtitles"
229
+ for i in t.items
230
+ if i.item_id == item_id
231
+ ),
232
+ None,
233
+ )
234
+ profile = styles.get(item.style_id, {}) if item is not None else {}
235
+ if item is not None and draft:
236
+ from .workbench import tools_for
237
+
238
+ item, edited = tools_for(repository, project_id, run_id)._caption_draft({**draft, "element_id": item_id})
239
+ profile = edited or profile
240
+ design = styles.get(profile.get("design") or "")
241
+ if design is None:
242
+ raise ProjectError("caption_not_live", "這句字幕不是 AI 設計的樣式,不能即時播放。", status_code=422)
243
+ page = custom_components.caption_profile(
244
+ design, item.text, profile.get("emphasis", ()), profile.get("delivery", "dialogue")
245
+ )
246
+ return custom_components.live_page(revision.timeline, item, page)
247
+
248
+
249
+ def kept_cut(repository, project_id, run_id, expected_revision_id):
250
+ """The film without its text layer, as the last render left it, to play under a live design."""
251
+ revision = repository.current_revision(project_id, run_id)
252
+ if revision.revision_id != expected_revision_id:
253
+ raise ProjectError("revision_conflict", "影片已更新,正在重新讀取編輯畫面。", status_code=409)
254
+ path = FfmpegPreviewRenderer(MediaPreviewRepository(repository.projects)).media_cache_path(
255
+ project_id, revision.timeline
256
+ )
257
+ if path is None or not path.is_file():
258
+ raise ProjectError("clip_needs_render", "先輸出一次這一版影片,才能看動態預覽。", status_code=409)
259
+ return path
@@ -12,10 +12,60 @@ from .refinement_references import public_state, sent
12
12
 
13
13
  # Changes go through review notes to the AI; the user picks which version is current and edits graphics directly.
14
14
  USER_TOOLS = frozenset(
15
- {"restore_revision", "set_component_text", "edit_component", "edit_component_look", "remove_program_component"}
15
+ {
16
+ "restore_revision",
17
+ "edit_component",
18
+ "edit_component_look",
19
+ "remove_program_component",
20
+ "edit_caption",
21
+ "slip_clip",
22
+ }
16
23
  )
17
24
 
18
25
 
26
+ def _captions(repository, project_id, timeline):
27
+ """Every caption a person may correct: its delivery and emphasis, and whether its design plays live."""
28
+ from .production_media import load_text_styles
29
+
30
+ styles = load_text_styles(repository.projects, project_id)
31
+ result = {}
32
+ for track in timeline.tracks:
33
+ if track.track_id != "agent-subtitles":
34
+ continue
35
+ for item in track.items:
36
+ profile = styles.get(item.style_id, {})
37
+ result[item.item_id] = {
38
+ "delivery": profile.get("delivery", "dialogue"),
39
+ "emphasis": profile.get("emphasis", []),
40
+ "live": bool(styles.get(profile.get("design") or "")),
41
+ }
42
+ return result
43
+
44
+
45
+ def _shots(repository, project_id, run_id, timeline):
46
+ """How far each shot can slip in its footage, in frames earlier and later."""
47
+ from clipen.domain import TrackKind
48
+
49
+ from .slip import room
50
+
51
+ try:
52
+ tools = tools_for(repository, project_id, run_id)
53
+ video = next(t for t in timeline.tracks if t.kind is TrackKind.VIDEO)
54
+ except (ProjectError, StopIteration):
55
+ return {}
56
+ result = {}
57
+ for item in video.items:
58
+ earlier, later = room(tools, item)
59
+ span = item.source.span
60
+ unit = span.time_base.numerator / span.time_base.denominator
61
+ result[item.item_id] = {
62
+ "earlier": earlier,
63
+ "later": later,
64
+ "source_start_seconds": round(int(span.start_pts) * unit, 3),
65
+ }
66
+ return result
67
+
68
+
19
69
  def idle(repository, project_id, run_id):
20
70
  run = repository.get(project_id, run_id)
21
71
  latest = repository.latest(project_id)
@@ -72,6 +122,8 @@ def state(repository, project_id, run_id):
72
122
  return {
73
123
  "revision": revision.to_public(include_timeline=True),
74
124
  "component_editing": editing,
125
+ "captions": _captions(repository, project_id, revision.timeline),
126
+ "shots": _shots(repository, project_id, run_id, revision.timeline),
75
127
  "history": history,
76
128
  "ai_usage": usage,
77
129
  "references": public_state(intent, revision.timeline),
@@ -263,8 +263,23 @@ MESSAGES = {
263
263
  "指定來源沒有這個影像串流。": "That source has no such video stream.",
264
264
  "取樣時間沒有可解碼畫面。": "There is no decodable frame at that time.",
265
265
  "混音片段超出影片或來源長度。": "An audio piece runs past the film or its source.",
266
+ # controller/app.py: footage added later
267
+ "只能加入影片或聲音檔。": "Only video or sound files can be added.",
268
+ "檔名無效。": "The file name is invalid.",
269
+ "檔案是空的。": "The file is empty.",
270
+ "素材正在檢查,等檢查完成再加入。": "The footage is being checked; add files once it is done.",
271
+ # projects/storage.py
272
+ "追加素材資料夾不安全。": "The added-footage folder is unsafe.",
273
+ # editing/slip.py
274
+ "請指定要往前或往後移動幾格。": "Say how many frames to move it earlier or later.",
275
+ "找不到這個鏡頭。": "That shot was not found.",
276
+ "微調設定無效。": "The slip settings are invalid.",
277
+ # editing/aspect.py
278
+ "畫面比例必須是 16:9、9:16、1:1 或 4:5。": "The aspect ratio must be 16:9, 9:16, 1:1 or 4:5.",
266
279
  # editing/production_preview.py
267
280
  "請先使用 validate_sequence 修正時間軸。": "Fix the timeline with validate_sequence first.",
281
+ "這一版用到的配樂或音效找不到了,請重新選一首配樂再輸出。": "The music or sound effects in this version are missing; pick the music again, then render.",
282
+ "這一版有地方需要修正才能輸出,請交給 AI 修改,或回到上一個版本。": "This version needs fixing before it can render; hand it to AI, or go back to an earlier version.",
268
283
  "預覽不屬於這次剪輯。": "That preview belongs to another edit.",
269
284
  "預覽檔案已遺失或變更。": "The preview file is missing or changed.",
270
285
  "檢視時間超出預覽範圍。": "That time is outside the preview.",
@@ -363,6 +378,21 @@ MESSAGES = {
363
378
  "預覽時間不在影片內。": "That time is outside the film.",
364
379
  "這個時間沒有畫面片段。": "There is no shot at this time.",
365
380
  "找不到預覽字型。": "The preview font was not found.",
381
+ "先輸出一次這一版影片,才能看動態預覽。": "Render this version once to see the graphic moving.",
382
+ "這個元件不能在瀏覽器即時播放。": "This graphic cannot play live in the browser.",
383
+ "先用 set_caption_design 設計字幕的樣子,再建立字幕。": "Design how captions look with set_caption_design before making them.",
384
+ "字幕頁面要有一個標了 data-clipen-caption 的元素,Clipen 會把每句字幕放進去。": "The caption page needs one element marked data-clipen-caption; Clipen puts each caption into it.",
385
+ "沒有這個外觀;先用 set_component_look 建立字幕用的外觀,或從 list_program_components 的 looks 選一個。": "There is no such look. Create one for captions with set_component_look, or pick one from the looks in list_program_components.",
386
+ "字幕設計檔案不安全。": "The caption design file is not safe.",
387
+ "找不到這句字幕,影片可能已經更新,請重新讀取。": "This caption is gone; the film may have changed. Reload.",
388
+ "字幕要是一行、1–80 個字。": "A caption is one line of 1 to 80 characters.",
389
+ "語氣只能是一般對話、重點句或小聲帶過。": "Delivery is dialogue, punchline or quiet.",
390
+ "強調的字要是字串清單。": "Emphasised words must be a list of text.",
391
+ "字幕設定格式不正確。": "The caption settings are not valid.",
392
+ "沒有這個字幕設計;用 set_caption_design 回傳的 design_id。": "There is no such caption design. Use a design_id set_caption_design returned.",
393
+ "這句字幕不是 AI 設計的樣式,不能即時播放。": "This caption is not drawn by the AI's design, so it cannot play live.",
394
+ "這個元件用的是已停用的內建模板,不能再修改;刪掉它,或請 AI 重新設計一個。": "This graphic uses a retired built-in template and can no longer be changed. Delete it, or ask the AI to design a new one.",
395
+ "找不到這個項目。": "Not found.",
366
396
  "來源沒有指定的影像串流。": "The source has no such video stream.",
367
397
  "文字超出版面或無法顯示,請縮短文字或調整位置。": "The text runs off the frame or cannot be drawn. Shorten it or move it.",
368
398
  # editing/workbench.py
@@ -525,4 +555,10 @@ PATTERNS = (
525
555
  "Downloading and installing speech recognition packages ({0}/{1})…",
526
556
  ),
527
557
  (re.compile(r"畫自由設計元件 (\d+)/(\d+)"), "Drawing custom graphic {0}/{1}"),
558
+ (re.compile(r"畫字幕 (\d+) 句"), "Drawing {0} captions"),
559
+ (
560
+ re.compile(r"這個鏡頭最多只能往前 ([0-9.]+) 秒、往後 ([0-9.]+) 秒,再過去就沒有毛片了。"),
561
+ "This shot can move at most {0} s earlier and {1} s later; past that there is no footage.",
562
+ ),
563
+ (re.compile(r"這支影片是 (\S+),畫布只能是 (\S+)。"), "This film is {0}; its canvas can only be {1}."),
528
564
  )
@@ -124,7 +124,9 @@ _TOOLS = (
124
124
  "description": (
125
125
  "Use {} for safe defaults, or exact numeric keys: "
126
126
  "punch_in {scale,center_x,center_y}; slow_push "
127
- "{scale_from,scale_to}; reframe {x,y}; speed_ramp {rate}."
127
+ "{scale_from,scale_to}; reframe {x,y}; speed_ramp {rate}. "
128
+ "Footage always fills the film's frame and the overflow is cropped; reframe "
129
+ "{x,y} picks what stays: x 0 keeps the left edge, 1 the right; y 0 the top, 1 the bottom."
128
130
  ),
129
131
  "properties": {
130
132
  "scale": {"type": "number", "minimum": 1.01, "maximum": 2},
@@ -188,7 +188,7 @@ class MediaDiscovery:
188
188
  "non_media",
189
189
  )
190
190
  continue
191
- kind = _kind_for_name(name)
191
+ kind = kind_for_name(name)
192
192
  yield DiscoveredAsset(
193
193
  role,
194
194
  relative,
@@ -205,7 +205,7 @@ class MediaDiscovery:
205
205
  raise DiscoveryError("too_many_files")
206
206
 
207
207
 
208
- def _kind_for_name(name: str) -> AssetKind:
208
+ def kind_for_name(name: str) -> AssetKind:
209
209
  extension = PurePosixPath(name).suffix.lower()
210
210
  if extension in _VIDEO_EXTENSIONS:
211
211
  return AssetKind.VIDEO
@@ -106,6 +106,11 @@ class MediaPreviewRepository:
106
106
  row["inode"],
107
107
  row["saved_at"],
108
108
  )
109
+ if root.role is DirectoryRole.ADDED:
110
+ # The project's own folder: wherever the project is now, not where it was checked.
111
+ folder = self.projects.added_footage_folder(project_id)
112
+ info = folder.stat()
113
+ root = InventoryRoot(DirectoryRole.ADDED, str(folder), info.st_dev, info.st_ino, row["saved_at"])
109
114
  descriptor = open_file_beneath(root, row["relative_path"])
110
115
  details = os.fstat(descriptor)
111
116
  if details.st_size != row["size_bytes"] or details.st_mtime_ns != row["mtime_ns"]:
@@ -89,6 +89,9 @@ class InventoryRepository:
89
89
  revision = validate_revision(expected_revision)
90
90
  request_hash = command_digest({"expected_revision": revision})
91
91
  run_id = make_run_id(project_id, normalized_request)
92
+ # Added footage lives in the project's own folder; point at it where the project is now.
93
+ if (self.projects.root / project_id / self.projects.ADDED_FOOTAGE).is_dir():
94
+ self.projects.added_footage_folder(project_id)
92
95
  with self.projects.connect(project_id) as connection:
93
96
  try:
94
97
  connection.execute("BEGIN IMMEDIATE")
@@ -119,7 +122,7 @@ class InventoryRepository:
119
122
  status_code=409,
120
123
  )
121
124
  rows = connection.execute(
122
- "SELECT role, canonical_path, device, inode, saved_at FROM project_directories ORDER BY role"
125
+ "SELECT role, canonical_path, device, inode, saved_at FROM project_directories WHERE role IN ('source', 'added') ORDER BY role"
123
126
  ).fetchall()
124
127
  roots = tuple(
125
128
  InventoryRoot(
@@ -399,7 +402,7 @@ class InventoryRepository:
399
402
  status_code=409,
400
403
  )
401
404
  root_rows = connection.execute(
402
- "SELECT role, canonical_path, device, inode, saved_at FROM project_directories ORDER BY role"
405
+ "SELECT role, canonical_path, device, inode, saved_at FROM project_directories WHERE role IN ('source', 'added') ORDER BY role"
403
406
  ).fetchall()
404
407
  current_roots = tuple(
405
408
  InventoryRoot(
@@ -0,0 +1,113 @@
1
+ """Clipen's own ffmpeg, for a Mac that has none: a fixed static build, downloaded and checked into
2
+ Clipen's folder. It is put on the PATH of Clipen's own processes only, never on the person's shell,
3
+ so an ffmpeg they install later is left alone."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import hashlib
8
+ import os
9
+ import shutil
10
+ import uuid
11
+ import zipfile
12
+ from pathlib import Path
13
+ from typing import Callable, Mapping
14
+ from urllib.request import Request, urlopen
15
+
16
+ from clipen.i18n import tr
17
+
18
+ VERSION = "9.1-1795207104"
19
+ _SOURCE = "https://ffmpeg.martin-riedl.de/download/macos/arm64/1795207104_9.1"
20
+ # Each tool: its archive's size and SHA-256, as published beside the archive.
21
+ TOOLS = {
22
+ "ffmpeg": (28_623_086, "1f66e9a690a7f1c9e60b012379f8869c11818d1797f45b21dbb2f2564ba61ae1"),
23
+ "ffprobe": (28_541_295, "6ef2df5f575042923a28537ab37adf936f28bf3e7b85de23a1447ed447ec1dbd"),
24
+ }
25
+ DOWNLOAD_BYTES = sum(size for size, _ in TOOLS.values())
26
+ # The unpacked tools; nothing larger is accepted from an archive.
27
+ _MAX_TOOL_BYTES = 200_000_000
28
+
29
+
30
+ class FfmpegUnavailable(RuntimeError):
31
+ pass
32
+
33
+
34
+ def folder(data_root: Path) -> Path:
35
+ return data_root / "ffmpeg" / VERSION
36
+
37
+
38
+ def installed(data_root: Path) -> Path | None:
39
+ """The folder holding Clipen's own ffmpeg and ffprobe, once they are in place."""
40
+ root = folder(data_root)
41
+ return root if all((root / name).is_file() for name in TOOLS) else None
42
+
43
+
44
+ def needed(data_root: Path, environment: Mapping[str, str]) -> bool:
45
+ """Whether Clipen must fetch its own: the Mac has no ffmpeg and ffprobe, and Clipen has none yet."""
46
+ if installed(data_root) is not None:
47
+ return False
48
+ path = environment.get("PATH", os.defpath)
49
+ return not all(shutil.which(name, path=path) for name in TOOLS)
50
+
51
+
52
+ def on_path(data_root: Path, environment: Mapping[str, str]) -> dict[str, str]:
53
+ """The environment with Clipen's own ffmpeg first on PATH, when Clipen has one."""
54
+ root = installed(data_root)
55
+ if root is None:
56
+ return dict(environment)
57
+ return {**environment, "PATH": f"{root}{os.pathsep}{environment.get('PATH', os.defpath)}"}
58
+
59
+
60
+ def install(data_root: Path, on_progress: Callable[[int, int], None] = lambda done, total: None) -> Path:
61
+ """Download, check and unpack both tools; nothing unchecked is ever kept."""
62
+ target = folder(data_root)
63
+ if installed(data_root) is not None:
64
+ return target
65
+ target.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
66
+ staging = target.parent / f".{VERSION}.staging-{uuid.uuid4().hex}"
67
+ staging.mkdir(mode=0o700)
68
+ done = 0
69
+ try:
70
+ for name, (size, sha256) in TOOLS.items():
71
+ archive = staging / f"{name}.zip"
72
+ digest = hashlib.sha256()
73
+ request = Request(f"{_SOURCE}/{name}.zip", headers={"User-Agent": "Clipen"})
74
+ try:
75
+ with urlopen(request, timeout=30) as response, archive.open("xb") as output:
76
+ while block := response.read(1024 * 1024):
77
+ if output.tell() + len(block) > size:
78
+ raise FfmpegUnavailable(
79
+ tr("ffmpeg 下載的檔案比預期大。", "The ffmpeg download is larger than expected.")
80
+ )
81
+ digest.update(block)
82
+ output.write(block)
83
+ done += len(block)
84
+ on_progress(done, DOWNLOAD_BYTES)
85
+ except OSError as error:
86
+ raise FfmpegUnavailable(
87
+ tr(
88
+ "無法下載 ffmpeg,請確認網路後再試。",
89
+ "Could not download ffmpeg; check your connection and try again.",
90
+ )
91
+ ) from error
92
+ if archive.stat().st_size != size or digest.hexdigest() != sha256:
93
+ raise FfmpegUnavailable(
94
+ tr(
95
+ "ffmpeg 的檢查碼不符,已刪除下載的檔案;請稍後再試或回報問題。",
96
+ "ffmpeg failed its checksum and was deleted; try again later or report the problem.",
97
+ )
98
+ )
99
+ with zipfile.ZipFile(archive) as bundle:
100
+ member = bundle.getinfo(name)
101
+ if member.file_size > _MAX_TOOL_BYTES:
102
+ raise FfmpegUnavailable(
103
+ tr("ffmpeg 解壓縮後的檔案太大。", "The unpacked ffmpeg is larger than expected.")
104
+ )
105
+ with bundle.open(member) as source, (staging / name).open("xb") as output:
106
+ shutil.copyfileobj(source, output)
107
+ (staging / name).chmod(0o755)
108
+ archive.unlink()
109
+ staging.rename(target)
110
+ except BaseException:
111
+ shutil.rmtree(staging, ignore_errors=True)
112
+ raise
113
+ return target
@@ -35,6 +35,8 @@ class ProjectError(RuntimeError):
35
35
  class DirectoryRole(str, Enum):
36
36
  SOURCE = "source"
37
37
  REFERENCE = "reference"
38
+ # Footage added later, from anywhere: copied into the project's own folder, checked beside the footage folder.
39
+ ADDED = "added"
38
40
 
39
41
 
40
42
  class DirectoryAvailability(str, Enum):
@@ -36,7 +36,7 @@ from .preview_schema import PREVIEW_SCHEMA
36
36
  from .timeline_schema import TIMELINE_SCHEMA
37
37
  from .validation_schema import VALIDATION_WORKFLOW_SCHEMA
38
38
 
39
- PROJECT_SCHEMA_VERSION = 19
39
+ PROJECT_SCHEMA_VERSION = 20
40
40
  # Tables of the retired confirmed-plan flow, children before parents. Version 19
41
41
  # archives any rows they still hold beside the database and drops them.
42
42
  RETIRED_PLANNING_TABLES = ("current_plan", "plan_revisions", "planning_runs", "plan_command_receipts")
@@ -76,7 +76,7 @@ CREATE TABLE inventory_command_receipts (
76
76
  CREATE TABLE assets (
77
77
  asset_id TEXT PRIMARY KEY,
78
78
  project_id TEXT NOT NULL REFERENCES project(project_id),
79
- role TEXT NOT NULL CHECK (role IN ('source', 'reference')),
79
+ role TEXT NOT NULL CHECK (role IN ('source', 'reference', 'added')),
80
80
  relative_path TEXT NOT NULL,
81
81
  first_seen_at TEXT NOT NULL,
82
82
  UNIQUE(project_id, role, relative_path)
@@ -452,6 +452,40 @@ class ProjectRepository:
452
452
  ),
453
453
  )
454
454
 
455
+ ADDED_FOOTAGE = "added-footage"
456
+
457
+ def added_footage_folder(self, project_id: str) -> Path:
458
+ """The project's own folder for footage added later, made and registered on first use.
459
+
460
+ It is the project's, so it is found where the project now is: a project copied, restored or
461
+ moved keeps its added footage, though the folder's path and inode change with it."""
462
+ validate_project_id(project_id)
463
+ folder = self.root / project_id / self.ADDED_FOOTAGE
464
+ if folder.is_symlink():
465
+ raise ProjectError("storage_unsafe", "追加素材資料夾不安全。", status_code=409)
466
+ folder.mkdir(mode=0o700, exist_ok=True)
467
+ info = folder.stat()
468
+ with self.connect(project_id) as connection:
469
+ connection.execute("BEGIN IMMEDIATE")
470
+ row = connection.execute(
471
+ "SELECT canonical_path, device, inode FROM project_directories WHERE role = 'added'"
472
+ ).fetchone()
473
+ if row is None or (row["canonical_path"], row["device"], row["inode"]) != (
474
+ str(folder),
475
+ info.st_dev,
476
+ info.st_ino,
477
+ ):
478
+ connection.execute(
479
+ "INSERT INTO project_directories "
480
+ "(role, canonical_path, display_path, display_name, device, inode, saved_at) "
481
+ "VALUES ('added', ?, ?, ?, ?, ?, ?) "
482
+ "ON CONFLICT(role) DO UPDATE SET canonical_path = excluded.canonical_path, "
483
+ "display_path = excluded.display_path, device = excluded.device, inode = excluded.inode",
484
+ (str(folder), str(folder), "追加素材", info.st_dev, info.st_ino, utc_now()),
485
+ )
486
+ connection.commit()
487
+ return folder
488
+
455
489
  def set_directory(
456
490
  self,
457
491
  project_id: str,
@@ -621,7 +655,7 @@ class ProjectRepository:
621
655
  updated_at TEXT NOT NULL
622
656
  );
623
657
  CREATE TABLE project_directories (
624
- role TEXT PRIMARY KEY CHECK (role IN ('source', 'reference')),
658
+ role TEXT PRIMARY KEY CHECK (role IN ('source', 'reference', 'added')),
625
659
  canonical_path TEXT NOT NULL,
626
660
  display_path TEXT NOT NULL,
627
661
  display_name TEXT NOT NULL,
@@ -649,7 +683,7 @@ class ProjectRepository:
649
683
  + PRODUCTION_SESSION_SCHEMA
650
684
  + FINISHING_SCHEMA
651
685
  + """
652
- PRAGMA user_version = 19;
686
+ PRAGMA user_version = 20;
653
687
  """
654
688
  )
655
689
  connection.execute(
@@ -746,6 +780,9 @@ class ProjectRepository:
746
780
  if version == 18:
747
781
  self._migrate_v18_to_v19(connection, project_dir)
748
782
  version = 19
783
+ if version == 19:
784
+ self._migrate_v19_to_v20(connection)
785
+ version = 20
749
786
  if version != PROJECT_SCHEMA_VERSION:
750
787
  connection.close()
751
788
  raise ProjectError(
@@ -787,6 +824,49 @@ class ProjectRepository:
787
824
  finally:
788
825
  connection.execute("PRAGMA foreign_keys=ON")
789
826
 
827
+ @staticmethod
828
+ def _migrate_v19_to_v20(connection: sqlite3.Connection) -> None:
829
+ """Let footage added later sit beside the footage folder, under its own 'added' role.
830
+
831
+ SQLite cannot change a CHECK in place, so both tables are rebuilt with the new role allowed
832
+ and their rows copied; foreign keys are off for the swap and must still hold afterwards."""
833
+ connection.execute("PRAGMA foreign_keys = OFF")
834
+ try:
835
+ connection.execute("BEGIN IMMEDIATE")
836
+ connection.execute(
837
+ "CREATE TABLE project_directories_v20 ("
838
+ "role TEXT PRIMARY KEY CHECK (role IN ('source', 'reference', 'added')), "
839
+ "canonical_path TEXT NOT NULL, display_path TEXT NOT NULL, display_name TEXT NOT NULL, "
840
+ "device INTEGER NOT NULL, inode INTEGER NOT NULL, saved_at TEXT NOT NULL)"
841
+ )
842
+ connection.execute(
843
+ "INSERT INTO project_directories_v20 SELECT role, canonical_path, display_path, display_name, "
844
+ "device, inode, saved_at FROM project_directories"
845
+ )
846
+ connection.execute("DROP TABLE project_directories")
847
+ connection.execute("ALTER TABLE project_directories_v20 RENAME TO project_directories")
848
+ connection.execute(
849
+ "CREATE TABLE assets_v20 ("
850
+ "asset_id TEXT PRIMARY KEY, project_id TEXT NOT NULL REFERENCES project(project_id), "
851
+ "role TEXT NOT NULL CHECK (role IN ('source', 'reference', 'added')), "
852
+ "relative_path TEXT NOT NULL, first_seen_at TEXT NOT NULL, "
853
+ "UNIQUE(project_id, role, relative_path))"
854
+ )
855
+ connection.execute(
856
+ "INSERT INTO assets_v20 SELECT asset_id, project_id, role, relative_path, first_seen_at FROM assets"
857
+ )
858
+ connection.execute("DROP TABLE assets")
859
+ connection.execute("ALTER TABLE assets_v20 RENAME TO assets")
860
+ if connection.execute("PRAGMA foreign_key_check").fetchone() is not None:
861
+ raise sqlite3.DatabaseError("allowing added footage broke foreign keys")
862
+ connection.execute("PRAGMA user_version = 20")
863
+ connection.commit()
864
+ except Exception:
865
+ connection.rollback()
866
+ raise
867
+ finally:
868
+ connection.execute("PRAGMA foreign_keys = ON")
869
+
790
870
  @staticmethod
791
871
  def _migrate_v18_to_v19(connection: sqlite3.Connection, project_dir: Path) -> None:
792
872
  """Drop the retired confirmed-plan tables without losing what they held.
@@ -154,16 +154,36 @@ def resolve_codex_model(preferences: tuple[str | None, str | None], models: list
154
154
  }
155
155
 
156
156
 
157
- def codex_account(binary: str | Path, environment: Mapping[str, str], timeout: float = 10.0) -> dict:
157
+ def codex_account(
158
+ binary: str | Path,
159
+ environment: Mapping[str, str],
160
+ timeout: float = 10.0,
161
+ *,
162
+ model_override: str | None = None,
163
+ include_models: bool = False,
164
+ ) -> dict:
158
165
  """The model Clipen runs (see resolve_codex_model) and live usage limits."""
159
166
  from .codex import codex_preferences
160
167
 
161
168
  answers = _rpc(str(binary), environment, [("account/rateLimits/read", None), ("model/list", {})], timeout)
162
169
  limits = (answers.get(1) or {}).get("rateLimits")
163
- resolved = resolve_codex_model(codex_preferences(environment), _models((answers.get(2) or {}).get("data")))
170
+ models = _models((answers.get(2) or {}).get("data"))
171
+ configured, effort = codex_preferences(environment)
172
+ resolved = resolve_codex_model((model_override or configured, effort), models)
164
173
  model = (
165
174
  None if resolved is None else {key: resolved[key] for key in ("id", "name", "effort", "source", "unavailable")}
166
175
  )
176
+ if model_override:
177
+ if model and model["id"] == model_override:
178
+ model["source"] = "clipen"
179
+ else:
180
+ model = {
181
+ "id": model_override,
182
+ "name": model_override,
183
+ "effort": None,
184
+ "source": "clipen",
185
+ "unavailable": model_override if models else None,
186
+ }
167
187
  quota = None
168
188
  if isinstance(limits, dict):
169
189
  windows = [w for w in (_window(limits.get("primary")), _window(limits.get("secondary"))) if w]
@@ -173,7 +193,10 @@ def codex_account(binary: str | Path, environment: Mapping[str, str], timeout: f
173
193
  "windows": windows,
174
194
  "limited": bool(limits.get("rateLimitReachedType")),
175
195
  }
176
- return {"model": model, "quota": quota}
196
+ result = {"model": model, "quota": quota}
197
+ if include_models:
198
+ result["models"] = [{"id": entry["model"], "name": entry["name"] or entry["model"]} for entry in models]
199
+ return result
177
200
 
178
201
 
179
202
  def record_claude_account(attempt_root: Path, events: list[dict], requested: str | None = None) -> None:
@@ -209,12 +232,16 @@ def _claude_name(model: str) -> str:
209
232
  return " ".join(words) or model
210
233
 
211
234
 
212
- def claude_account(attempt_root: Path, environment: Mapping[str, str] | None = None) -> dict:
235
+ def claude_account(
236
+ attempt_root: Path, environment: Mapping[str, str] | None = None, *, model_override: str | None = None
237
+ ) -> dict:
213
238
  """The last run's model and limit status, with the effort and model chosen in Claude Code settings."""
214
239
  from .claude import claude_preferences
215
240
 
216
241
  wanted, effort = claude_preferences(environment)
217
242
  source = "claude_config" if wanted or effort else "default"
243
+ if model_override:
244
+ wanted, source = model_override, "clipen"
218
245
  path = attempt_root / _SNAPSHOT
219
246
  try:
220
247
  if path.is_symlink() or path.stat().st_size > 4096:
@@ -228,11 +255,15 @@ def claude_account(attempt_root: Path, environment: Mapping[str, str] | None = N
228
255
  # A model chosen after the last run is what the next run uses.
229
256
  if wanted and (not isinstance(model, str) or snapshot.get("requested") != wanted):
230
257
  model = wanted
258
+ elif not wanted and snapshot.get("requested"):
259
+ model = None
231
260
  limit = snapshot.get("limit") if isinstance(snapshot.get("limit"), dict) else {}
261
+ reset = limit.get("resetsAt")
262
+ resets_at = reset if type(reset) is int and reset > 0 else None
232
263
  observed = snapshot.get("observed_at") if isinstance(snapshot.get("observed_at"), int) else None
233
264
  quota = (
234
265
  None
235
- if not limit
266
+ if not limit or (resets_at is not None and resets_at <= time.time())
236
267
  else {
237
268
  "source": "last_run",
238
269
  "observed_at": observed,
@@ -240,7 +271,7 @@ def claude_account(attempt_root: Path, environment: Mapping[str, str] | None = N
240
271
  "windows": [],
241
272
  "limited": limit.get("status") not in (None, "allowed", "allowed_warning"),
242
273
  "warning": limit.get("status") == "allowed_warning",
243
- "resets_at": limit.get("resetsAt") if isinstance(limit.get("resetsAt"), int) else None,
274
+ "resets_at": resets_at,
244
275
  "kind": limit.get("rateLimitType") if isinstance(limit.get("rateLimitType"), str) else None,
245
276
  }
246
277
  )