@clipen/clipen-cli 0.0.0-stage → 1.0.1

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 (232) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +89 -2
  3. package/apps/web/dist/assets/index-D5D2HiB1.js +14 -0
  4. package/apps/web/dist/assets/index-DIMuOXSu.css +1 -0
  5. package/apps/web/dist/favicon.svg +1 -0
  6. package/apps/web/dist/index.html +16 -0
  7. package/bin/clipen.js +157 -0
  8. package/clipen +18 -0
  9. package/install +25 -0
  10. package/package.json +55 -4
  11. package/pyproject.toml +44 -0
  12. package/requirements/asr-runtime.txt +13 -0
  13. package/requirements/dev.txt +2 -0
  14. package/requirements/runtime.txt +20 -0
  15. package/src/clipen/__init__.py +3 -0
  16. package/src/clipen/analysis/__init__.py +89 -0
  17. package/src/clipen/analysis/artifacts.py +410 -0
  18. package/src/clipen/analysis/audio.py +394 -0
  19. package/src/clipen/analysis/evidence.py +102 -0
  20. package/src/clipen/analysis/evidence_service.py +929 -0
  21. package/src/clipen/analysis/image_similarity.py +134 -0
  22. package/src/clipen/analysis/keyframes.py +159 -0
  23. package/src/clipen/analysis/models.py +228 -0
  24. package/src/clipen/analysis/qwen_worker.py +594 -0
  25. package/src/clipen/analysis/resources.py +22 -0
  26. package/src/clipen/analysis/runtime.py +62 -0
  27. package/src/clipen/analysis/service.py +594 -0
  28. package/src/clipen/analysis/setup.py +921 -0
  29. package/src/clipen/analysis/setup_cli.py +107 -0
  30. package/src/clipen/analysis/storage.py +1864 -0
  31. package/src/clipen/analysis/transcription.py +906 -0
  32. package/src/clipen/analysis/visual.py +237 -0
  33. package/src/clipen/annotations/__init__.py +13 -0
  34. package/src/clipen/annotations/models.py +22 -0
  35. package/src/clipen/annotations/storage.py +428 -0
  36. package/src/clipen/annotations/suggestions.py +115 -0
  37. package/src/clipen/asr_release.py +132 -0
  38. package/src/clipen/bootstrap.py +978 -0
  39. package/src/clipen/candidates.py +222 -0
  40. package/src/clipen/cli.py +84 -0
  41. package/src/clipen/controller/__init__.py +17 -0
  42. package/src/clipen/controller/app.py +1657 -0
  43. package/src/clipen/controller/server.py +533 -0
  44. package/src/clipen/domain/__init__.py +30 -0
  45. package/src/clipen/domain/errors.py +5 -0
  46. package/src/clipen/domain/media_time.py +110 -0
  47. package/src/clipen/domain/timeline.py +582 -0
  48. package/src/clipen/domain/validation.py +14 -0
  49. package/src/clipen/editing/EDITORIAL_REGRESSIONS.md +38 -0
  50. package/src/clipen/editing/PROGRAM_FORMAT.md +102 -0
  51. package/src/clipen/editing/README.md +115 -0
  52. package/src/clipen/editing/REFACTOR_DESIGN.md +241 -0
  53. package/src/clipen/editing/REFACTOR_HANDOFF.md +73 -0
  54. package/src/clipen/editing/__init__.py +15 -0
  55. package/src/clipen/editing/agent.py +13 -0
  56. package/src/clipen/editing/agent_models.py +127 -0
  57. package/src/clipen/editing/agent_repository.py +978 -0
  58. package/src/clipen/editing/agent_tools.py +613 -0
  59. package/src/clipen/editing/alignment.py +150 -0
  60. package/src/clipen/editing/alignment_setup.py +156 -0
  61. package/src/clipen/editing/alignment_worker.py +24 -0
  62. package/src/clipen/editing/change_report.py +128 -0
  63. package/src/clipen/editing/compiler.py +40 -0
  64. package/src/clipen/editing/component_looks.py +131 -0
  65. package/src/clipen/editing/component_review.py +74 -0
  66. package/src/clipen/editing/coordinator.py +497 -0
  67. package/src/clipen/editing/editorial_review.py +309 -0
  68. package/src/clipen/editing/evidence_jobs.py +552 -0
  69. package/src/clipen/editing/history_changes.py +192 -0
  70. package/src/clipen/editing/music_choices.py +18 -0
  71. package/src/clipen/editing/production_catalog.py +629 -0
  72. package/src/clipen/editing/production_limits.py +85 -0
  73. package/src/clipen/editing/production_media.py +435 -0
  74. package/src/clipen/editing/production_preview.py +373 -0
  75. package/src/clipen/editing/production_progress.py +236 -0
  76. package/src/clipen/editing/production_requirements.py +117 -0
  77. package/src/clipen/editing/production_tools.py +1198 -0
  78. package/src/clipen/editing/program_audio.py +248 -0
  79. package/src/clipen/editing/program_direction.py +83 -0
  80. package/src/clipen/editing/program_story.py +91 -0
  81. package/src/clipen/editing/program_subtitles.py +232 -0
  82. package/src/clipen/editing/programme_review.py +121 -0
  83. package/src/clipen/editing/prompt_history.py +84 -0
  84. package/src/clipen/editing/recut.py +167 -0
  85. package/src/clipen/editing/refinement_references.py +278 -0
  86. package/src/clipen/editing/resolve_export.py +847 -0
  87. package/src/clipen/editing/resolve_titles.py +291 -0
  88. package/src/clipen/editing/skill_tools.py +951 -0
  89. package/src/clipen/editing/source_dialogue.py +192 -0
  90. package/src/clipen/editing/speech_coverage.py +50 -0
  91. package/src/clipen/editing/speech_quality.py +11 -0
  92. package/src/clipen/editing/tool_receipts.py +98 -0
  93. package/src/clipen/editing/versions.py +219 -0
  94. package/src/clipen/editing/visual_preview.py +189 -0
  95. package/src/clipen/editing/workbench.py +136 -0
  96. package/src/clipen/filesystem.py +25 -0
  97. package/src/clipen/finishing/README.md +103 -0
  98. package/src/clipen/finishing/__init__.py +1 -0
  99. package/src/clipen/finishing/audio.py +188 -0
  100. package/src/clipen/finishing/catalog.py +264 -0
  101. package/src/clipen/finishing/models.py +14 -0
  102. package/src/clipen/finishing/renderer.py +45 -0
  103. package/src/clipen/mcp_editing/__init__.py +5 -0
  104. package/src/clipen/mcp_editing/__main__.py +42 -0
  105. package/src/clipen/mcp_editing/server.py +396 -0
  106. package/src/clipen/media/__init__.py +50 -0
  107. package/src/clipen/media/discovery.py +253 -0
  108. package/src/clipen/media/models.py +349 -0
  109. package/src/clipen/media/preview.py +137 -0
  110. package/src/clipen/media/probe.py +418 -0
  111. package/src/clipen/media/service.py +304 -0
  112. package/src/clipen/media/storage.py +694 -0
  113. package/src/clipen/music_vocabulary.py +34 -0
  114. package/src/clipen/power.py +28 -0
  115. package/src/clipen/projects/__init__.py +26 -0
  116. package/src/clipen/projects/agent_schema.py +94 -0
  117. package/src/clipen/projects/annotation_schema.py +40 -0
  118. package/src/clipen/projects/deletion.py +256 -0
  119. package/src/clipen/projects/evidence_schema.py +52 -0
  120. package/src/clipen/projects/finishing_schema.py +36 -0
  121. package/src/clipen/projects/models.py +189 -0
  122. package/src/clipen/projects/picker.py +232 -0
  123. package/src/clipen/projects/preview_schema.py +29 -0
  124. package/src/clipen/projects/service.py +159 -0
  125. package/src/clipen/projects/storage.py +1458 -0
  126. package/src/clipen/projects/timeline_schema.py +32 -0
  127. package/src/clipen/projects/validation_schema.py +28 -0
  128. package/src/clipen/provider_registry.py +77 -0
  129. package/src/clipen/providers/__init__.py +43 -0
  130. package/src/clipen/providers/account.py +245 -0
  131. package/src/clipen/providers/claude.py +409 -0
  132. package/src/clipen/providers/claude_editing.py +118 -0
  133. package/src/clipen/providers/codex.py +991 -0
  134. package/src/clipen/providers/codex_editing.py +91 -0
  135. package/src/clipen/providers/editing_agent.py +567 -0
  136. package/src/clipen/providers/errors.py +51 -0
  137. package/src/clipen/providers/recovery.py +269 -0
  138. package/src/clipen/py.typed +1 -0
  139. package/src/clipen/rendering/__init__.py +12 -0
  140. package/src/clipen/rendering/cover.py +139 -0
  141. package/src/clipen/rendering/custom_components.py +328 -0
  142. package/src/clipen/rendering/custom_render.py +218 -0
  143. package/src/clipen/rendering/fonts/anton-OFL.txt +93 -0
  144. package/src/clipen/rendering/fonts/bebasneue-OFL.txt +93 -0
  145. package/src/clipen/rendering/fonts/caveat-OFL.txt +93 -0
  146. package/src/clipen/rendering/fonts/chenyu-OFL.txt +93 -0
  147. package/src/clipen/rendering/fonts/delagothicone-OFL.txt +93 -0
  148. package/src/clipen/rendering/fonts/hachimarupop-OFL.txt +93 -0
  149. package/src/clipen/rendering/fonts/iansui-OFL.txt +93 -0
  150. package/src/clipen/rendering/fonts/manifest.json +145 -0
  151. package/src/clipen/rendering/fonts/playfairdisplay-OFL.txt +93 -0
  152. package/src/clipen/rendering/fonts/rocknrollone-OFL.txt +93 -0
  153. package/src/clipen/rendering/fonts/yomogi-OFL.txt +94 -0
  154. package/src/clipen/rendering/fonts/yuseimagic-OFL.txt +93 -0
  155. package/src/clipen/rendering/fonts/zenkurenaido-OFL.txt +93 -0
  156. package/src/clipen/rendering/fonts/zenmarugothic-OFL.txt +93 -0
  157. package/src/clipen/rendering/production_effects.py +96 -0
  158. package/src/clipen/rendering/program_components.py +254 -0
  159. package/src/clipen/rendering/program_creator.py +804 -0
  160. package/src/clipen/rendering/program_identities.py +350 -0
  161. package/src/clipen/rendering/program_motion.py +186 -0
  162. package/src/clipen/rendering/program_studio.py +227 -0
  163. package/src/clipen/rendering/program_styles.py +321 -0
  164. package/src/clipen/rendering/program_subtitles.py +89 -0
  165. package/src/clipen/rendering/renderer.py +737 -0
  166. package/src/clipen/rendering/storage.py +230 -0
  167. package/src/clipen/rendering/titles.py +467 -0
  168. package/src/clipen/skills/__init__.py +5 -0
  169. package/src/clipen/skills/builtin/SKILL.md +72 -0
  170. package/src/clipen/skills/builtin/assets/sample-daily-vlog.mp4 +0 -0
  171. package/src/clipen/skills/builtin/assets/sample-event-recap.mp4 +0 -0
  172. package/src/clipen/skills/builtin/assets/sample-food-review.mp4 +0 -0
  173. package/src/clipen/skills/builtin/assets/sample-product-demo.mp4 +0 -0
  174. package/src/clipen/skills/builtin/assets/sample-product-review.mp4 +0 -0
  175. package/src/clipen/skills/builtin/assets/sample-product-unboxing.mp4 +0 -0
  176. package/src/clipen/skills/builtin/assets/sample-shorts-highlight.mp4 +0 -0
  177. package/src/clipen/skills/builtin/assets/sample-travel-highlight.mp4 +0 -0
  178. package/src/clipen/skills/builtin/assets/sample-travel-vlog.mp4 +0 -0
  179. package/src/clipen/skills/builtin/assets/style-cinema.png +0 -0
  180. package/src/clipen/skills/builtin/assets/style-editorial.png +0 -0
  181. package/src/clipen/skills/builtin/assets/style-tpl-daily-vlog.png +0 -0
  182. package/src/clipen/skills/builtin/assets/style-tpl-event-recap.png +0 -0
  183. package/src/clipen/skills/builtin/assets/style-tpl-food-review.png +0 -0
  184. package/src/clipen/skills/builtin/assets/style-tpl-product-demo.png +0 -0
  185. package/src/clipen/skills/builtin/assets/style-tpl-product-review.png +0 -0
  186. package/src/clipen/skills/builtin/assets/style-tpl-product-unboxing.png +0 -0
  187. package/src/clipen/skills/builtin/assets/style-tpl-shorts-highlight.png +0 -0
  188. package/src/clipen/skills/builtin/assets/style-tpl-travel-highlight.png +0 -0
  189. package/src/clipen/skills/builtin/assets/style-tpl-travel-vlog.png +0 -0
  190. package/src/clipen/skills/builtin/assets/style-variety.png +0 -0
  191. package/src/clipen/skills/builtin/components.json +133 -0
  192. package/src/clipen/skills/builtin/font_sources.json +20 -0
  193. package/src/clipen/skills/builtin/font_styles.json +329 -0
  194. package/src/clipen/skills/builtin/manifest.json +32 -0
  195. package/src/clipen/skills/builtin/presets.json +8 -0
  196. package/src/clipen/skills/builtin/references/captions.md +14 -0
  197. package/src/clipen/skills/builtin/references/channel-design.md +37 -0
  198. package/src/clipen/skills/builtin/references/editing.md +30 -0
  199. package/src/clipen/skills/builtin/references/font-chenyu-OFL.txt +93 -0
  200. package/src/clipen/skills/builtin/references/font-iansui-OFL.txt +93 -0
  201. package/src/clipen/skills/builtin/references/graphics.md +59 -0
  202. package/src/clipen/skills/builtin/references/review.md +16 -0
  203. package/src/clipen/skills/builtin/references/sound.md +8 -0
  204. package/src/clipen/skills/builtin/references/story.md +7 -0
  205. package/src/clipen/skills/builtin/skills/travel-program/SKILL.md +27 -0
  206. package/src/clipen/skills/builtin/skills/travel-program/manifest.json +6 -0
  207. package/src/clipen/skills/builtin/template-skills/clipen-daily-vlog/SKILL.md +33 -0
  208. package/src/clipen/skills/builtin/template-skills/clipen-daily-vlog/manifest.json +8 -0
  209. package/src/clipen/skills/builtin/template-skills/clipen-event-recap/SKILL.md +34 -0
  210. package/src/clipen/skills/builtin/template-skills/clipen-event-recap/manifest.json +8 -0
  211. package/src/clipen/skills/builtin/template-skills/clipen-food-review/SKILL.md +33 -0
  212. package/src/clipen/skills/builtin/template-skills/clipen-food-review/manifest.json +8 -0
  213. package/src/clipen/skills/builtin/template-skills/clipen-product-demo/SKILL.md +35 -0
  214. package/src/clipen/skills/builtin/template-skills/clipen-product-demo/manifest.json +8 -0
  215. package/src/clipen/skills/builtin/template-skills/clipen-product-review/SKILL.md +36 -0
  216. package/src/clipen/skills/builtin/template-skills/clipen-product-review/manifest.json +8 -0
  217. package/src/clipen/skills/builtin/template-skills/clipen-product-unboxing/SKILL.md +39 -0
  218. package/src/clipen/skills/builtin/template-skills/clipen-product-unboxing/manifest.json +8 -0
  219. package/src/clipen/skills/builtin/template-skills/clipen-shorts-highlight/SKILL.md +38 -0
  220. package/src/clipen/skills/builtin/template-skills/clipen-shorts-highlight/manifest.json +8 -0
  221. package/src/clipen/skills/builtin/template-skills/clipen-travel-highlight/SKILL.md +34 -0
  222. package/src/clipen/skills/builtin/template-skills/clipen-travel-highlight/manifest.json +8 -0
  223. package/src/clipen/skills/builtin/template-skills/clipen-travel-vlog/SKILL.md +37 -0
  224. package/src/clipen/skills/builtin/template-skills/clipen-travel-vlog/manifest.json +8 -0
  225. package/src/clipen/skills/builtin/templates.json +284 -0
  226. package/src/clipen/skills/builtin/visual_styles.json +1074 -0
  227. package/src/clipen/skills/catalog.py +314 -0
  228. package/src/clipen/skills/library.py +137 -0
  229. package/src/clipen/skills/package.py +254 -0
  230. package/src/clipen/skills/visual_styles.py +55 -0
  231. package/src/clipen/workspace.py +181 -0
  232. package/uninstall +25 -0
@@ -0,0 +1,189 @@
1
+ """One-frame editing canvas using real source pixels and native text renderers.
2
+
3
+ This is a static editing view, not approval of transitions, motion or sound.
4
+ """
5
+
6
+ import base64
7
+ import math
8
+ import tempfile
9
+ import threading
10
+ from dataclasses import replace
11
+ from fractions import Fraction
12
+ from io import BytesIO
13
+ from pathlib import Path
14
+
15
+ from PIL import Image, ImageDraw, ImageFont
16
+
17
+ from clipen.domain import EffectRequest, TrackKind
18
+ from clipen.finishing.audio import run_process
19
+ from clipen.media import MediaPreviewRepository
20
+ from clipen.projects import ProjectError
21
+ from clipen.rendering.production_effects import grade_filters
22
+ from clipen.rendering.renderer import FfmpegPreviewRenderer
23
+ from clipen.rendering.titles import TitleCardRenderer, TitleRenderError
24
+
25
+ from .production_media import load_text_styles
26
+
27
+
28
+ def frame(repository, project_id, run_id, expected_revision_id, frame_number, component=None):
29
+ """One still of the current version.
30
+
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."""
33
+ revision = repository.current_revision(project_id, run_id)
34
+ timeline = revision.timeline
35
+ if revision.revision_id != expected_revision_id:
36
+ raise ProjectError("revision_conflict", "影片已更新,正在重新讀取編輯畫面。", status_code=409)
37
+ if (
38
+ isinstance(frame_number, bool)
39
+ or not isinstance(frame_number, int)
40
+ or not 0 <= frame_number < timeline.duration_frames
41
+ ):
42
+ raise ProjectError("frame_invalid", "預覽時間不在影片內。", status_code=422)
43
+ items = [i for t in timeline.tracks if t.kind is TrackKind.TITLE for i in t.items]
44
+ styles = load_text_styles(repository.projects, project_id)
45
+ draft = profile = None
46
+ if component is not None:
47
+ from .workbench import tools_for
48
+
49
+ draft, profile, _ = tools_for(repository, project_id, run_id)._component_draft(component)
50
+ styles = {**styles, draft.style_id: profile}
51
+ items = [draft if i.item_id == draft.item_id else i for i in items]
52
+ clip = next(
53
+ (
54
+ i
55
+ for t in timeline.tracks
56
+ if t.kind is TrackKind.VIDEO
57
+ for i in t.items
58
+ if i.start_frame <= frame_number < i.start_frame + i.duration_frames
59
+ ),
60
+ None,
61
+ )
62
+ if clip is None:
63
+ raise ProjectError("frame_invalid", "這個時間沒有畫面片段。", status_code=422)
64
+ fps = Fraction(timeline.frame_rate.numerator, timeline.frame_rate.denominator)
65
+ relative = frame_number - clip.start_frame
66
+ span = clip.source.span
67
+ unit = Fraction(span.time_base.numerator, span.time_base.denominator)
68
+ duration = span.duration_pts * unit
69
+ elapsed = Fraction(relative, 1) / fps
70
+ speed = FfmpegPreviewRenderer._speed_profile(clip)
71
+ if speed:
72
+ outside, center = speed
73
+ first = float(duration) * 0.4 / outside
74
+ middle = float(duration) * 0.2 / center
75
+ t = float(elapsed)
76
+ elapsed = Fraction(
77
+ str(
78
+ t * outside
79
+ if t < first
80
+ else float(duration) * 0.4 + (t - first) * center
81
+ if t < first + middle
82
+ else float(duration) * 0.6 + (t - first - middle) * outside
83
+ )
84
+ )
85
+ seconds = int(span.start_pts) * unit + min(
86
+ max(Fraction(0), elapsed), max(Fraction(0), duration - Fraction(1, 1) / fps)
87
+ )
88
+ media = MediaPreviewRepository(repository.projects)
89
+ source = media.open(project_id, span.version_id)
90
+ try:
91
+ if span.stream_index not in source.video_stream_indices:
92
+ raise ProjectError("frame_invalid", "來源沒有指定的影像串流。", status_code=422)
93
+ effects = []
94
+ for effect in clip.effects:
95
+ if effect.effect_id == "video.slow_push":
96
+ p = effect.parameters
97
+ scale = p.get("scale_from", 1) + (p.get("scale_to", 1.08) - p.get("scale_from", 1)) * relative / max(
98
+ 1, clip.duration_frames - 1
99
+ )
100
+ effects.append(EffectRequest("video.punch_in", {"scale": scale, "center_x": 0.5, "center_y": 0.5}))
101
+ else:
102
+ effects.append(effect)
103
+ 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"
105
+ filters += FfmpegPreviewRenderer._video_effect_filters(still_clip, timeline) + grade_filters(clip)
106
+ with tempfile.TemporaryDirectory(prefix="clipen-edit-frame-") as temporary:
107
+ output = Path(temporary) / "source.png"
108
+ run_process(
109
+ [
110
+ "ffmpeg",
111
+ "-v",
112
+ "error",
113
+ "-nostdin",
114
+ "-seek_timestamp",
115
+ "1",
116
+ "-ss",
117
+ f"{float(seconds):.9f}",
118
+ "-i",
119
+ f"/dev/fd/{source.descriptor}",
120
+ "-map",
121
+ f"0:{span.stream_index}",
122
+ "-frames:v",
123
+ "1",
124
+ "-vf",
125
+ filters,
126
+ "-threads",
127
+ "1",
128
+ str(output),
129
+ ],
130
+ threading.Event(),
131
+ pass_fds=(source.descriptor,),
132
+ timeout=30,
133
+ )
134
+ with Image.open(output) as pixels:
135
+ image = pixels.convert("RGBA")
136
+ finally:
137
+ source.close()
138
+ # Match the native mosaic geometry for this exact instant.
139
+ for effect in clip.effects:
140
+ if effect.effect_id != "video.mosaic":
141
+ continue
142
+ for region in effect.parameters["regions"]:
143
+ if not region["start_frame"] <= relative < region["start_frame"] + region["duration_frames"]:
144
+ continue
145
+ width = max(2, min(timeline.width, round(timeline.width * region["width"]) // 2 * 2))
146
+ height = max(2, min(timeline.height, round(timeline.height * region["height"]) // 2 * 2))
147
+ x = min(timeline.width - width, round(timeline.width * region["x"]) // 2 * 2)
148
+ y = min(timeline.height - height, round(timeline.height * region["y"]) // 2 * 2)
149
+ pixels = image.crop((x, y, x + width, y + height))
150
+ pixels = pixels.resize(
151
+ (max(1, math.ceil(width / region["block_size"])), max(1, math.ceil(height / region["block_size"]))),
152
+ Image.Resampling.BOX,
153
+ ).resize((width, height), Image.Resampling.NEAREST)
154
+ image.paste(pixels, (x, y))
155
+ font = TitleCardRenderer._font_path()
156
+ if font is None:
157
+ raise ProjectError("preview_title_font_missing", "找不到預覽字型。", status_code=422)
158
+ overlay = Image.new("RGBA", image.size, (0, 0, 0, 0))
159
+ draw = ImageDraw.Draw(overlay)
160
+ renderer = TitleCardRenderer(styles)
161
+ try:
162
+ for item in items:
163
+ if item.start_frame <= frame_number < item.start_frame + item.duration_frames:
164
+ renderer._draw_card(draw, ImageFont, font, timeline, item, frame_number - item.start_frame)
165
+ except TitleRenderError as error:
166
+ raise ProjectError(error.code, "文字超出版面或無法顯示,請縮短文字或調整位置。", status_code=422) from error
167
+ box = None
168
+ if draft is not None and draft.start_frame <= frame_number < draft.start_frame + draft.duration_frames:
169
+ from clipen.rendering.program_components import component_bounds
170
+
171
+ left, top, right, bottom = component_bounds(draw, font, timeline, draft, profile)[0]
172
+ box = {
173
+ "x": left / timeline.width,
174
+ "y": top / timeline.height,
175
+ "width": (right - left) / timeline.width,
176
+ "height": (bottom - top) / timeline.height,
177
+ }
178
+ image = Image.alpha_composite(image, overlay).convert("RGB")
179
+ image.thumbnail((960, 960))
180
+ encoded = BytesIO()
181
+ image.save(encoded, format="JPEG", quality=88)
182
+ return {
183
+ "revision_id": revision.revision_id,
184
+ "frame": frame_number,
185
+ "source_item_id": clip.item_id,
186
+ "image_data_url": "data:image/jpeg;base64," + base64.b64encode(encoded.getvalue()).decode(),
187
+ "scope": "editing_still",
188
+ "component_box": box,
189
+ }
@@ -0,0 +1,136 @@
1
+ """The review workbench: read the current film, restore a version, reword graphics, render and export it."""
2
+
3
+ import json
4
+ import threading
5
+
6
+ from clipen.projects import DirectoryReference, DirectoryRole, ProjectError
7
+ from clipen.projects.storage import utc_now
8
+
9
+ from .agent_tools import EditAgentTools
10
+ from .production_media import AgentAudioStore
11
+ from .refinement_references import public_state, sent
12
+
13
+ # Changes go through review notes to the AI; the user picks which version is current and edits graphics directly.
14
+ USER_TOOLS = frozenset(
15
+ {"restore_revision", "set_component_text", "edit_component", "edit_component_look", "remove_program_component"}
16
+ )
17
+
18
+
19
+ def idle(repository, project_id, run_id):
20
+ run = repository.get(project_id, run_id)
21
+ latest = repository.latest(project_id)
22
+ if latest is None or latest.run_id != run_id or run.state in {"queued", "running"}:
23
+ raise ProjectError("edit_agent_busy", "請先停止 AI 製作,再還原或輸出目前版本。", status_code=409)
24
+ if repository.production_session(project_id, run_id) is None:
25
+ raise ProjectError("production_required", "這個版本不是可編輯的影片製作。", status_code=409)
26
+ return run
27
+
28
+
29
+ def tools_for(repository, project_id, run_id):
30
+ tools = EditAgentTools(repository, project_id, run_id)
31
+ tools._user_edit = True
32
+ return tools
33
+
34
+
35
+ def state(repository, project_id, run_id):
36
+ revision = repository.current_revision(project_id, run_id)
37
+ from .versions import film_usage, versions
38
+
39
+ with repository.projects.connect(project_id) as db:
40
+ # One entry per complete edit; the AI's per-step revisions stay internal.
41
+ from .production_media import load_text_styles
42
+
43
+ history = versions(
44
+ db,
45
+ run_id,
46
+ repository.get(project_id, run_id).provider,
47
+ load_text_styles(repository.projects, project_id),
48
+ revision.revision_id,
49
+ )
50
+ usage = film_usage(db, run_id)
51
+ for version in history:
52
+ row = db.execute(
53
+ "SELECT payload_json FROM edit_agent_revisions WHERE revision_id=? AND run_id=?",
54
+ (version["revision_id"], run_id),
55
+ ).fetchone()
56
+ if row:
57
+ value = json.loads(row["payload_json"])
58
+ rate = value["frame_rate"]
59
+ version["duration_seconds"] = value["duration_frames"] * rate["den"] / rate["num"]
60
+ preview = db.execute(
61
+ "SELECT render_id FROM preview_renders WHERE timeline_id=? AND state='succeeded' ORDER BY created_at DESC LIMIT 1",
62
+ (version["revision_id"],),
63
+ ).fetchone()
64
+ version["preview_url"] = (
65
+ f"/api/projects/{project_id}/preview/{preview['render_id']}/media" if preview else None
66
+ )
67
+ intent = (repository.production_session(project_id, run_id) or {}).get("intent", {})
68
+ try:
69
+ editing = tools_for(repository, project_id, run_id)._component_editing()
70
+ except (ProjectError, KeyError, StopIteration):
71
+ editing = {"components": {}, "visual_styles": [], "font_styles": []}
72
+ return {
73
+ "revision": revision.to_public(include_timeline=True),
74
+ "component_editing": editing,
75
+ "history": history,
76
+ "ai_usage": usage,
77
+ "references": public_state(intent, revision.timeline),
78
+ "sent_notes": sent(intent),
79
+ "audio_assets": AgentAudioStore(repository.projects, project_id).public_assets(),
80
+ }
81
+
82
+
83
+ def edit(repository, project_id, run_id, name, arguments, expected, mutation_id):
84
+ idle(repository, project_id, run_id)
85
+ if name not in USER_TOOLS:
86
+ raise ProjectError(
87
+ "tool_not_allowed", "請用審片注記交給 AI 修改;這裡只能還原版本或編輯元件。", status_code=422
88
+ )
89
+ tools = tools_for(repository, project_id, run_id)
90
+ try:
91
+ result = tools.call(name, {**arguments, "expected_revision_id": expected, "mutation_id": mutation_id})
92
+ return result.payload
93
+ finally:
94
+ tools.close_production()
95
+
96
+
97
+ def import_music(repository, project_id, path, display_name):
98
+ from clipen.finishing.audio import inspect_library
99
+
100
+ store = AgentAudioStore(repository.projects, project_id)
101
+ directory = path.parent
102
+ info = directory.stat()
103
+ reference = DirectoryReference(
104
+ DirectoryRole.SOURCE, str(directory), directory.name, "使用者指定配樂", info.st_dev, info.st_ino, utc_now()
105
+ ).to_storage()
106
+ assets, issues = inspect_library("music", reference, threading.Event(), lambda _: None)
107
+ if len(assets) != 1:
108
+ raise ProjectError("music_invalid", "音樂檔無法解碼或沒有可用聲音。", status_code=422)
109
+ asset = assets[0]
110
+ asset["name"] = display_name
111
+ asset["provenance"] = {
112
+ "source": "user_upload",
113
+ "title": display_name,
114
+ "license": "user_supplied",
115
+ "rights_verified": False,
116
+ "attribution": "使用者提供;系統未驗證授權。",
117
+ "changes": "將依剪輯需要截取、調整音量及淡入淡出。",
118
+ }
119
+ store.add(assets, reference)
120
+ return next(a for a in store.public_assets() if a["asset_id"] == asset["asset_id"])
121
+
122
+
123
+ def music_choice(repository, project_id, asset_id):
124
+ if asset_id is None:
125
+ return None
126
+ asset = next(
127
+ (
128
+ a
129
+ for a in AgentAudioStore(repository.projects, project_id).public_assets()
130
+ if a["asset_id"] == asset_id and a["role"] == "music"
131
+ ),
132
+ None,
133
+ )
134
+ if asset is None:
135
+ raise ProjectError("music_missing", "指定的配樂不在本作品,請重新選擇。", status_code=422)
136
+ return {"mode": "user", "asset_id": asset_id, "name": asset["name"]}
@@ -0,0 +1,25 @@
1
+ """Filesystem helpers that also work on user-selected non-POSIX volumes."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from pathlib import Path
7
+
8
+
9
+ def restrict_permissions(path: Path, mode: int) -> None:
10
+ """Apply POSIX privacy bits, or verify access when the volume lacks them."""
11
+
12
+ try:
13
+ os.chmod(path, mode)
14
+ return
15
+ except OSError:
16
+ pass
17
+ if path.is_symlink() or not path.exists():
18
+ raise OSError(f"unsafe managed path: {path}")
19
+ required = os.R_OK
20
+ if mode & 0o200:
21
+ required |= os.W_OK
22
+ if path.is_dir():
23
+ required |= os.X_OK
24
+ if not os.access(path, required):
25
+ raise OSError(f"managed path permissions unavailable: {path}")
@@ -0,0 +1,103 @@
1
+ # AI finishing, workflow v2
2
+
3
+ The user confirms a direction proof and optionally describes the desired feel or
4
+ revision. One operation produces a film: it understands the confirmed story, finds
5
+ public music, compares candidates, recuts the actual source spans, renders locally,
6
+ and publishes the playable result with its decisions and music credit. No music
7
+ folder, manual song selection, parameter editing, or separate render command is
8
+ required. A later natural-language revision includes the previous decisions.
9
+
10
+ ## AI and evidence
11
+
12
+ There are at most two bounded Codex attempts per operation:
13
+
14
+ 1. A creative brief uses the confirmed requirements/sections, source observations,
15
+ trusted transcript provenance, and up to eight explicitly consented midpoint
16
+ thumbnails. It chooses a story arc, essential shots, and generic musical tags.
17
+ 2. The edit decision uses that brief and actual acquired music candidates, including
18
+ source-provided tags/genres and locally measured volume/onsets. It selects music,
19
+ explains the fit and alternatives, and chooses each shot's source trim, order,
20
+ purpose and audio treatment, plus supported finishing elements.
21
+
22
+ Codex does **not** receive raw music or listen to it through this CLI interface.
23
+ Mood/instrument descriptions come from catalog metadata, not an inference from BPM.
24
+ Single-frame thumbnails do not establish continuous motion. Those limitations are
25
+ included in the prompts; production taste still needs real user footage and review.
26
+
27
+ Search terms are limited to an enum of generic musical vocabulary. Private project
28
+ text is not sent to the catalog. Thumbnails, transcript, analysis and feedback go to
29
+ Codex only after consent that states the two-call budget and image scope.
30
+
31
+ ## Music sourcing
32
+
33
+ `catalog.py` searches the public Openverse audio API and refreshes each candidate's
34
+ metadata before downloading. It accepts instrumental tracks with complete CC0 or
35
+ CC BY metadata, title, creator, source page and canonical license link. Unknown,
36
+ NC, ND and SA entries are excluded by this initial implementation. Metadata is an
37
+ index's license assertion, not independent verification of ownership or original
38
+ source terms; the UI identifies it as such and links the original source and terms.
39
+
40
+ Each operation downloads at most three candidates (24 MiB per file) through a fixed
41
+ HTTPS host allowlist with public-address checks, bounded redirects, timeouts and
42
+ response sizes. Cancellation stops acquisition. Search outages and unusable files
43
+ are explicit failures; there is no silent switch to manual music or unlicensed audio.
44
+
45
+ Local inspection decodes at most 90 seconds per candidate at 8 kHz mono. It records
46
+ volume, peak, observed energy onsets and estimated tempo. The selected source window
47
+ must lie inside analyzed audio. Flat music may still be selected; it cannot acquire
48
+ invented beat markers. Only explicitly marked aligned cuts are checked against
49
+ observed beats. Narrative cuts need not all fall on a beat.
50
+
51
+ ## Edit and render contracts
52
+
53
+ `models.py` validates schema v2. Every edit cites supplied shot evidence and stays
54
+ inside its accepted direction shot's source range. It can trim, omit and reorder
55
+ shots while protecting the brief's essential shots. The target is 45–60 seconds,
56
+ with a bounded 30–75 second allowance. The application compiles source spans using
57
+ rational PTS and rebuilds positions and subtitle timing from the resulting order.
58
+
59
+ Retained speech must remain complete; partial utterances can be excluded or muted
60
+ as B-roll. Captions correspond exactly to retained complete cues. Films without
61
+ speech do not need invented captions. Cards, emphasis, transitions, SFX and motion
62
+ are optional decisions serving the film, not minimum-count completion gates.
63
+
64
+ The renderer retains the fixed, local FFmpeg/Pillow compositor: source camera audio,
65
+ CJK overlays, AI-directed regional music levels with short gain ramps, music ducking,
66
+ supported motion and dips, SDR grade, normalization and
67
+ peak limiting. It verifies dimensions, codecs, duration, frame rate/count and full
68
+ decode before publication. Human review remains pending, not silently passed.
69
+
70
+ ## Persistence and tests
71
+
72
+ Project schema v17 adds the single `produce` operation while preserving v16 trial
73
+ rows and their files. The former parameter draft workflow cannot be invoked as a
74
+ new production operation; old trials are not relabeled as v2 results. Requests are
75
+ idempotent, source snapshots immutable, failed retries preserve the last successful
76
+ film, and restart never replays a paid attempt. Usage is recorded per AI stage;
77
+ partial/unknown usage is explicit, never represented as a known zero.
78
+
79
+ The output includes a playable MP4, a decisions/timeline/source JSON record, the
80
+ music catalog snapshot, and a text credit with author, source, license and changes.
81
+ New success replaces the UI's result pointer; earlier files remain in managed storage.
82
+
83
+ Concurrent cards retain their original text and timing and stack vertically in the
84
+ upper half of the frame, leaving room for dialogue captions. Temporal overlap does
85
+ not discard otherwise valid AI output. Production inputs and raw AI decisions are
86
+ saved before local validation. Failed local work can resume using those snapshots
87
+ through `POST /api/projects/{project_id}/finishing/{run_id}/commands/resume`, without
88
+ provider calls or new music searches. A changed source context blocks this retry;
89
+ the original usage totals stay attached to the same run.
90
+
91
+ Run `PYTHONPATH=tests/python .venv/bin/python -m unittest test_finishing test_finishing_catalog`.
92
+ The tests cover actual recuts/subtitle remapping, feedback, two-stage orchestration,
93
+ source/license filtering, cancellation, recovery, and real FFmpeg composition.
94
+ Default tests use provider/network doubles and spend no AI quota. Live catalog smoke
95
+ tests are separate and do not establish the aesthetic quality of real AI edits.
96
+
97
+ Current scope: a continuous direction video track and its camera audio, up to 1080p
98
+ at 24/25/30/60 fps, SDR, supported semantic effects. Full films, HDR mastering,
99
+ independent graphics/audio tracks, and final Resolve delivery remain outside this
100
+ branch. Source references and semantic decisions remain editable for later delivery.
101
+
102
+ Sources: [Openverse audio API](https://api.openverse.org/v1/),
103
+ [Openverse media metadata](https://docs.openverse.org/meta/media_properties/api.html).
@@ -0,0 +1 @@
1
+ """Music, sound and media helpers for the finished programme."""
@@ -0,0 +1,188 @@
1
+ """Read-only local music inspection and bounded subprocess execution."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ import os
7
+ import subprocess
8
+ import sys
9
+ import tempfile
10
+ import time
11
+ from array import array
12
+ from pathlib import Path
13
+
14
+ from clipen.media.discovery import MediaDiscovery, open_file_beneath
15
+ from clipen.media.models import AssetKind, InventoryRoot
16
+ from clipen.media.probe import FFprobeAdapter, bounded_file_fingerprint
17
+ from clipen.projects import DirectoryReference, ProjectError
18
+ from clipen.projects.picker import refresh_availability
19
+
20
+ from .models import digest
21
+
22
+
23
+ def run_process(command, cancel, *, pass_fds=(), timeout=300, max_bytes=8 * 1024 * 1024):
24
+ """Drain through bounded files, poll cancellation even if FFmpeg is silent."""
25
+ with tempfile.TemporaryFile() as out, tempfile.TemporaryFile() as errors:
26
+ try:
27
+ process = subprocess.Popen(command, stdin=subprocess.DEVNULL, stdout=out, stderr=errors, pass_fds=pass_fds)
28
+ except OSError as error:
29
+ raise ProjectError(
30
+ "finishing_runtime_missing", "找不到可用的 FFmpeg/ffprobe。", status_code=409
31
+ ) from error
32
+ deadline = time.monotonic() + timeout
33
+ try:
34
+ while process.poll() is None:
35
+ if cancel.is_set():
36
+ raise ProjectError("user_cancelled", "已取消製作。", status_code=409)
37
+ if time.monotonic() >= deadline:
38
+ raise ProjectError("finishing_timeout", "本機製作超過時間上限。", status_code=409)
39
+ if os.fstat(out.fileno()).st_size > max_bytes or os.fstat(errors.fileno()).st_size > max_bytes:
40
+ raise ProjectError("finishing_output_limit", "本機工具輸出超過上限。", status_code=409)
41
+ cancel.wait(0.05)
42
+ if cancel.is_set():
43
+ raise ProjectError("user_cancelled", "已取消製作。", status_code=409)
44
+ if process.returncode:
45
+ raise ProjectError("finishing_render_failed", "本機製作失敗,請檢查素材格式與磁碟。", status_code=409)
46
+ out.seek(0)
47
+ result = out.read(max_bytes + 1)
48
+ if len(result) > max_bytes:
49
+ raise ProjectError("finishing_output_limit", "本機工具輸出超過上限。", status_code=409)
50
+ return result
51
+ finally:
52
+ if process.poll() is None:
53
+ process.terminate()
54
+ try:
55
+ process.wait(timeout=2)
56
+ except subprocess.TimeoutExpired:
57
+ process.kill()
58
+ process.wait()
59
+
60
+
61
+ def inventory_root(reference):
62
+ ref = DirectoryReference.from_storage(reference)
63
+ if refresh_availability(ref).availability.value != "available":
64
+ raise ProjectError("finishing_library_offline", "音樂或音效資料夾已變更或離線,請重新選擇。", status_code=409)
65
+ return InventoryRoot(ref.role, ref.canonical_path, ref.device, ref.inode, ref.saved_at)
66
+
67
+
68
+ def inspect_library(role, reference, cancel, progress):
69
+ root = inventory_root(reference)
70
+ probe = FFprobeAdapter()
71
+ assets, issues = [], []
72
+ for entry in MediaDiscovery(maximum_files=1000, maximum_seconds=60).scan(root, cancel):
73
+ if entry.kind != AssetKind.AUDIO or not entry.should_probe:
74
+ continue
75
+ if len(assets) >= 24:
76
+ issues.append({"name": "", "code": "library_limit_24"})
77
+ break
78
+ try:
79
+ result = probe.probe(root, entry, cancel)
80
+ stream = next(s for s in result.streams if s.kind == "audio")
81
+ duration = float(result.summary.get("duration_seconds", 0))
82
+ if not math.isfinite(duration) or not 0.1 <= duration <= 3600:
83
+ raise ValueError("duration unsupported")
84
+ fd = open_file_beneath(root, entry.relative_path)
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
+ )
113
+ finally:
114
+ 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
+ asset = {
124
+ "asset_id": "fa_" + digest([role, reference, entry.relative_path, result.fingerprint])[:32],
125
+ "role": role,
126
+ "name": Path(entry.relative_path).name,
127
+ "relative_path": entry.relative_path,
128
+ "size_bytes": result.size_bytes,
129
+ "mtime_ns": result.mtime_ns,
130
+ "fingerprint": result.fingerprint,
131
+ "stream_index": stream.stream_index,
132
+ "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,
138
+ }
139
+ assets.append(asset)
140
+ progress(min(0.95, len(assets) / 24))
141
+ except Exception as error:
142
+ if cancel.is_set():
143
+ raise
144
+ issues.append({"name": Path(entry.relative_path).name, "code": getattr(error, "code", "audio_unusable")})
145
+ return assets, issues
146
+
147
+
148
+ def detect_beats(samples):
149
+ """Energy-onset autocorrelation, with no fabricated beats for flat audio."""
150
+ hop = 160 # 20 ms, 50 observations per second
151
+ energy = [math.sqrt(sum(v * v for v in samples[i : i + hop]) / hop) for i in range(0, len(samples) - hop, hop)]
152
+ onsets = [max(0.0, energy[i] - energy[i - 1]) for i in range(1, len(energy))]
153
+ if not onsets or max(onsets) < 30:
154
+ return [], None
155
+ scores = [(sum(onsets[i] * onsets[i - lag] for i in range(lag, len(onsets))), lag) for lag in range(17, 51)]
156
+ score, lag = max(scores)
157
+ if score <= 0:
158
+ return [], None
159
+ # Return observed onset peaks near the periodic pulse; do not invent timestamps.
160
+ phase = max(range(lag), key=lambda p: sum(onsets[p::lag]))
161
+ beats = []
162
+ for index in range(phase, len(onsets), lag):
163
+ low, high = max(0, index - 3), min(len(onsets), index + 4)
164
+ peak = max(range(low, high), key=lambda i: onsets[i])
165
+ if onsets[peak] > max(onsets) * 0.08:
166
+ value = round((peak + 1) * hop / 8000, 3)
167
+ if not beats or value - beats[-1] > 0.20:
168
+ beats.append(value)
169
+ return beats[:300], round(3000 / lag, 1)
170
+
171
+
172
+ def open_asset(context, asset_id):
173
+ asset = next((a for a in context["assets"] if a["asset_id"] == asset_id), None)
174
+ if asset is None:
175
+ raise ProjectError("finishing_asset_missing", "找不到指定的音樂或音效。", status_code=409)
176
+ fd = open_file_beneath(inventory_root(context["directories"][asset["role"]]), asset["relative_path"])
177
+ try:
178
+ info = os.fstat(fd)
179
+ if (
180
+ info.st_size != asset["size_bytes"]
181
+ or info.st_mtime_ns != asset["mtime_ns"]
182
+ or bounded_file_fingerprint(fd, info.st_size) != asset["fingerprint"]
183
+ ):
184
+ raise ProjectError("media_changed", "音樂或音效已變更,請重新檢查。", status_code=409)
185
+ return fd, asset
186
+ except Exception:
187
+ os.close(fd)
188
+ raise