@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,230 @@
1
+ """Durable state for local rough-cut preview renders."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import secrets
6
+ import sqlite3
7
+ from pathlib import Path
8
+
9
+ from clipen.filesystem import restrict_permissions
10
+ from clipen.projects import ProjectError, ProjectRepository
11
+ from clipen.projects.models import validate_project_id, validate_request_id
12
+ from clipen.projects.storage import utc_now
13
+
14
+
15
+ class PreviewRenderRepository:
16
+ def __init__(self, projects: ProjectRepository) -> None:
17
+ self.projects = projects
18
+
19
+ def create(self, project_id: str, request_id: object, timeline_id: str) -> dict[str, object]:
20
+ validate_project_id(project_id)
21
+ request = validate_request_id(request_id)
22
+ now = utc_now()
23
+ try:
24
+ with self.projects.connect(project_id) as database:
25
+ database.execute("BEGIN IMMEDIATE")
26
+ existing = database.execute("SELECT * FROM preview_renders WHERE request_id=?", (request,)).fetchone()
27
+ if existing is not None:
28
+ if existing["timeline_id"] != timeline_id:
29
+ database.rollback()
30
+ raise ProjectError(
31
+ "request_conflict",
32
+ "這次初剪輸出與既有操作衝突。",
33
+ status_code=409,
34
+ )
35
+ database.rollback()
36
+ return self._public(existing)
37
+ render_id = "render_" + secrets.token_hex(16)
38
+ database.execute(
39
+ "INSERT INTO preview_renders "
40
+ "(render_id,project_id,timeline_id,request_id,state,progress,created_at) "
41
+ "VALUES(?,?,?,?, 'queued',0,?)",
42
+ (render_id, project_id, timeline_id, request, now),
43
+ )
44
+ database.execute(
45
+ "INSERT INTO current_preview_render(slot,render_id) VALUES(1,?) "
46
+ "ON CONFLICT(slot) DO UPDATE SET render_id=excluded.render_id",
47
+ (render_id,),
48
+ )
49
+ database.commit()
50
+ return self.get(project_id, render_id)
51
+ except ProjectError:
52
+ raise
53
+ except sqlite3.Error as error:
54
+ raise ProjectError(
55
+ "storage_failed",
56
+ "Clipen 無法建立初剪輸出工作。",
57
+ status_code=500,
58
+ ) from error
59
+
60
+ def current(self, project_id: str) -> dict[str, object] | None:
61
+ validate_project_id(project_id)
62
+ with self.projects.connect(project_id) as database:
63
+ row = database.execute(
64
+ "SELECT renders.* FROM current_preview_render current "
65
+ "JOIN preview_renders renders ON renders.render_id=current.render_id WHERE current.slot=1"
66
+ ).fetchone()
67
+ return None if row is None else self._public(row)
68
+
69
+ def get(self, project_id: str, render_id: str) -> dict[str, object]:
70
+ validate_project_id(project_id)
71
+ with self.projects.connect(project_id) as database:
72
+ row = database.execute(
73
+ "SELECT * FROM preview_renders WHERE render_id=? AND project_id=?",
74
+ (render_id, project_id),
75
+ ).fetchone()
76
+ if row is None:
77
+ raise ProjectError("preview_not_found", "找不到這次初剪輸出。", status_code=404)
78
+ return self._public(row)
79
+
80
+ def media_path(self, project_id: str, render_id: str) -> Path:
81
+ """The finished film of a render, checked against what was recorded when it succeeded."""
82
+ render = self.get(project_id, render_id)
83
+ if render["state"] != "succeeded":
84
+ raise ProjectError("preview_not_ready", "影片尚未輸出完成。", status_code=409)
85
+ path = self.output_path(project_id, render_id, prepare=False)
86
+ if path.is_symlink() or not path.is_file() or path.stat().st_size != render["size_bytes"]:
87
+ raise ProjectError("preview_missing", "找不到已輸出的影片。", status_code=409)
88
+ return path
89
+
90
+ def finish_unsuccessful(
91
+ self,
92
+ project_id: str,
93
+ render_id: str,
94
+ state: str,
95
+ *,
96
+ error_code: str | None = None,
97
+ ) -> dict[str, object]:
98
+ if state not in {"failed", "cancelled"}:
99
+ raise ValueError("unsuccessful preview state is invalid")
100
+ now = utc_now()
101
+ fields = ["state=?", "error_code=?"]
102
+ values: list[object] = [state, error_code]
103
+ fields.append("completed_at=?")
104
+ values.append(now)
105
+ values.extend([render_id, project_id])
106
+ with self.projects.connect(project_id) as database:
107
+ database.execute(
108
+ f"UPDATE preview_renders SET {','.join(fields)} WHERE render_id=? AND project_id=?",
109
+ values,
110
+ )
111
+ return self.get(project_id, render_id)
112
+
113
+ def mark_running(self, project_id: str, render_id: str) -> dict[str, object]:
114
+ now = utc_now()
115
+ with self.projects.connect(project_id) as database:
116
+ database.execute(
117
+ "UPDATE preview_renders SET state='running',progress=0,"
118
+ "started_at=COALESCE(started_at,?) "
119
+ "WHERE render_id=? AND project_id=? AND state='queued'",
120
+ (now, render_id, project_id),
121
+ )
122
+ return self.get(project_id, render_id)
123
+
124
+ def update_progress(self, project_id: str, render_id: str, progress: float) -> dict[str, object]:
125
+ normalized = max(0.0, min(1.0, progress))
126
+ with self.projects.connect(project_id) as database:
127
+ database.execute(
128
+ "UPDATE preview_renders SET progress=? WHERE render_id=? AND project_id=? AND state='running'",
129
+ (normalized, render_id, project_id),
130
+ )
131
+ return self.get(project_id, render_id)
132
+
133
+ def request_cancel(self, project_id: str, render_id: str) -> dict[str, object]:
134
+ with self.projects.connect(project_id) as database:
135
+ database.execute(
136
+ "UPDATE preview_renders SET state='cancelling' "
137
+ "WHERE render_id=? AND project_id=? AND state IN ('queued','running')",
138
+ (render_id, project_id),
139
+ )
140
+ return self.get(project_id, render_id)
141
+
142
+ def complete(
143
+ self,
144
+ project_id: str,
145
+ render_id: str,
146
+ output_relative_path: str,
147
+ output_size_bytes: int,
148
+ ) -> dict[str, object]:
149
+ with self.projects.connect(project_id) as database:
150
+ database.execute(
151
+ "UPDATE preview_renders SET state='succeeded',progress=1,error_code=NULL,"
152
+ "output_relative_path=?,output_size_bytes=?,completed_at=? "
153
+ "WHERE render_id=? AND project_id=? AND state='running'",
154
+ (
155
+ output_relative_path,
156
+ output_size_bytes,
157
+ utc_now(),
158
+ render_id,
159
+ project_id,
160
+ ),
161
+ )
162
+ return self.get(project_id, render_id)
163
+
164
+ def interrupt_incomplete(self, project_id: str) -> None:
165
+ with self.projects.connect(project_id) as database:
166
+ database.execute(
167
+ "UPDATE preview_renders SET state='interrupted',error_code='controller_restarted',"
168
+ "completed_at=? WHERE state IN ('queued','running','cancelling')",
169
+ (utc_now(),),
170
+ )
171
+
172
+ def interrupt_attempt_renders(self, project_id: str, run_id: str) -> int:
173
+ """End this run's AI previews still marked in progress.
174
+
175
+ Agent previews render inside the AI's tool process, so they cannot
176
+ outlive an attempt; a row left running (the Mac slept, the process was
177
+ killed) would otherwise block every later preview as busy.
178
+ """
179
+ with self.projects.connect(project_id) as database:
180
+ cursor = database.execute(
181
+ "UPDATE preview_renders SET state='interrupted',error_code='attempt_ended',completed_at=? "
182
+ "WHERE state IN ('queued','running','cancelling') AND request_id LIKE ? ESCAPE '\\'",
183
+ (utc_now(), "agent-preview-" + run_id.replace("_", "\\_") + "-%"),
184
+ )
185
+ database.commit()
186
+ return cursor.rowcount
187
+
188
+ def output_path(
189
+ self,
190
+ project_id: str,
191
+ render_id: str,
192
+ *,
193
+ staging: bool = False,
194
+ prepare: bool = True,
195
+ ) -> Path:
196
+ validate_project_id(project_id)
197
+ root = self.projects.root / project_id
198
+ if root.is_symlink() or not root.is_dir():
199
+ raise ProjectError("project_not_found", "找不到這個作品。", status_code=404)
200
+ directory = root / "previews"
201
+ if prepare:
202
+ directory.mkdir(mode=0o700, exist_ok=True)
203
+ elif not directory.exists():
204
+ name = f".{render_id}.partial.mp4" if staging else f"{render_id}.mp4"
205
+ return directory / name
206
+ if directory.is_symlink() or not directory.is_dir():
207
+ raise ProjectError("storage_corrupt", "Clipen 無法安全建立初剪資料夾。", status_code=500)
208
+ if prepare:
209
+ restrict_permissions(directory, 0o700)
210
+ name = f".{render_id}.partial.mp4" if staging else f"{render_id}.mp4"
211
+ return directory / name
212
+
213
+ @staticmethod
214
+ def _public(row) -> dict[str, object]:
215
+ return {
216
+ "render_id": row["render_id"],
217
+ "timeline_id": row["timeline_id"],
218
+ "state": row["state"],
219
+ "progress": row["progress"],
220
+ "error_code": row["error_code"],
221
+ "size_bytes": row["output_size_bytes"],
222
+ "created_at": row["created_at"],
223
+ "started_at": row["started_at"],
224
+ "completed_at": row["completed_at"],
225
+ "playback_url": (
226
+ f"/api/projects/{row['project_id']}/preview/{row['render_id']}/media"
227
+ if row["state"] == "succeeded" and row["output_relative_path"]
228
+ else None
229
+ ),
230
+ }
@@ -0,0 +1,467 @@
1
+ """Rasterized title cards and a bounded FFmpeg overlay pass."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import re
7
+ import subprocess
8
+ import tempfile
9
+ import threading
10
+ from dataclasses import dataclass
11
+ from pathlib import Path
12
+ from typing import Callable, Iterable
13
+
14
+ from clipen.domain import EditTimeline, TextClip, TrackKind
15
+
16
+
17
+ class TitleRenderError(RuntimeError):
18
+ """Raised when a trusted timeline cannot be composed locally."""
19
+
20
+ def __init__(self, code: str) -> None:
21
+ super().__init__(code)
22
+ self.code = code
23
+
24
+
25
+ @dataclass(frozen=True, slots=True)
26
+ class RenderedTitle:
27
+ path: Path
28
+ start_seconds: float
29
+ duration_seconds: float
30
+
31
+
32
+ class TitleCardRenderer:
33
+ """Turn semantic title styles into transparent, full-canvas PNG overlays."""
34
+
35
+ # Each card becomes one bounded FFmpeg input during the finishing pass.
36
+ # Keep this below the point where full-HD RGBA frames can create avoidable
37
+ # memory pressure on consumer machines.
38
+ _MAX_TITLES = 32
39
+
40
+ def __init__(self, custom_styles=None):
41
+ self.custom_styles = custom_styles or {}
42
+
43
+ def render(self, timeline: EditTimeline, directory: Path) -> tuple[RenderedTitle, ...]:
44
+ items = tuple(item for track in timeline.tracks if track.kind is TrackKind.TITLE for item in track.items)
45
+ if len(items) > self._MAX_TITLES:
46
+ raise TitleRenderError("preview_title_limit_exceeded")
47
+ if not items:
48
+ return ()
49
+ try:
50
+ from PIL import Image, ImageDraw, ImageFont
51
+ except ImportError as error:
52
+ raise TitleRenderError("preview_title_runtime_missing") from error
53
+
54
+ font_path = self._font_path()
55
+ if font_path is None:
56
+ raise TitleRenderError("preview_title_font_missing")
57
+ frame_rate = timeline.frame_rate.numerator / timeline.frame_rate.denominator
58
+ rendered = []
59
+ for index, item in enumerate(items):
60
+ assert isinstance(item, TextClip)
61
+ image = Image.new("RGBA", (timeline.width, timeline.height), (0, 0, 0, 0))
62
+ draw = ImageDraw.Draw(image)
63
+ self._draw_card(draw, ImageFont, font_path, timeline, item)
64
+ path = directory / f"title-{index:04d}.png"
65
+ image.save(path, "PNG", optimize=True)
66
+ rendered.append(
67
+ RenderedTitle(
68
+ path,
69
+ item.start_frame / frame_rate,
70
+ item.duration_frames / frame_rate,
71
+ )
72
+ )
73
+ return tuple(rendered)
74
+
75
+ @staticmethod
76
+ def _font_path() -> Path | None:
77
+ configured = os.environ.get("CLIPEN_TITLE_FONT")
78
+ candidates = (
79
+ Path(configured).expanduser() if configured else None,
80
+ Path("/System/Library/Fonts/Hiragino Sans GB.ttc"),
81
+ Path("/System/Library/Fonts/STHeiti Light.ttc"),
82
+ Path("/System/Library/Fonts/PingFang.ttc"),
83
+ Path("/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc"),
84
+ Path("/usr/share/fonts/truetype/noto/NotoSansCJK-Regular.ttc"),
85
+ Path("C:/Windows/Fonts/msjh.ttc"),
86
+ )
87
+ return next((path for path in candidates if path is not None and path.is_file()), None)
88
+
89
+ def _draw_card(
90
+ self, draw, image_font, font_path: Path, timeline: EditTimeline, item: TextClip, relative_frame=None
91
+ ) -> None:
92
+ width, height = timeline.width, timeline.height
93
+ if self.custom_styles.get(item.style_id, {}).get("kind") == "program_component":
94
+ from .program_components import draw_program_component
95
+
96
+ draw_program_component(draw, font_path, timeline, item, self.custom_styles[item.style_id], relative_frame)
97
+ return
98
+ if self.custom_styles.get(item.style_id, {}).get("kind") == "program_subtitle":
99
+ from .program_subtitles import draw_program_subtitle
100
+
101
+ draw_program_subtitle(draw, font_path, timeline, item, self.custom_styles[item.style_id], relative_frame)
102
+ return
103
+ if item.style_id in self.custom_styles:
104
+ profile = self.custom_styles[item.style_id]
105
+ size = max(1, round(height * profile["font_size_ratio"]))
106
+ font = image_font.truetype(str(font_path), size)
107
+ maximum = round(width * profile["width_ratio"])
108
+ lines = self._wrap(draw, item.text, font, maximum)
109
+ line_height = max(1, round(size * 1.5))
110
+ pad = max(1, round(size * 0.25))
111
+ x = round(width * profile["x"])
112
+ y = round(height * profile["y"])
113
+ if y + line_height * len(lines) + pad > height or x + maximum > width:
114
+ raise TitleRenderError("preview_text_overflow")
115
+ for row in lines:
116
+ length = draw.textlength(row, font=font)
117
+ at = (
118
+ x
119
+ if profile["align"] == "left"
120
+ else x + (maximum - length) / (2 if profile["align"] == "center" else 1)
121
+ )
122
+ draw.rounded_rectangle(
123
+ (at - pad, y - pad, at + length + pad, y + line_height),
124
+ radius=pad,
125
+ fill=tuple(profile["background_color"]),
126
+ )
127
+ draw.text((at, y), row, font=font, fill=tuple(profile["text_color"]))
128
+ y += line_height
129
+ return
130
+ if item.style_id == "title.chapter":
131
+ size = max(28, round(height * 0.055))
132
+ font = image_font.truetype(str(font_path), size)
133
+ lines = self._wrap(draw, item.text, font, round(width * 0.55))
134
+ box = self._text_box(draw, lines, font, round(size * 0.34))
135
+ x, y = round(width * 0.065), round(height * 0.10)
136
+ pad_x, pad_y = round(size * 0.58), round(size * 0.36)
137
+ draw.rounded_rectangle(
138
+ (x - pad_x, y - pad_y, x + box[0] + pad_x, y + box[1] + pad_y),
139
+ radius=round(size * 0.42),
140
+ fill=(37, 83, 62, 230),
141
+ )
142
+ self._multiline(draw, (x, y), lines, font, (255, 255, 248, 255), size)
143
+ return
144
+
145
+ if item.style_id == "title.caption":
146
+ size = max(26, round(height * 0.043))
147
+ font = image_font.truetype(str(font_path), size)
148
+ lines = self._wrap(draw, item.text, font, round(width * 0.70))
149
+ box = self._text_box(draw, lines, font, round(size * 0.32))
150
+ x = round((width - box[0]) / 2)
151
+ y = round(height * 0.79 - box[1] / 2)
152
+ pad_x, pad_y = round(size * 0.62), round(size * 0.38)
153
+ draw.rounded_rectangle(
154
+ (x - pad_x + 4, y - pad_y + 7, x + box[0] + pad_x + 4, y + box[1] + pad_y + 7),
155
+ radius=round(size * 0.36),
156
+ fill=(0, 0, 0, 75),
157
+ )
158
+ draw.rounded_rectangle(
159
+ (x - pad_x, y - pad_y, x + box[0] + pad_x, y + box[1] + pad_y),
160
+ radius=round(size * 0.36),
161
+ fill=(250, 249, 242, 238),
162
+ )
163
+ self._multiline(draw, (x, y), lines, font, (24, 27, 24, 255), size)
164
+ return
165
+
166
+ size = max(34, round(height * 0.072))
167
+ font = image_font.truetype(str(font_path), size)
168
+ lines = self._wrap(draw, item.text, font, round(width * 0.78))
169
+ box = self._text_box(draw, lines, font, round(size * 0.30))
170
+ x = round((width - box[0]) / 2)
171
+ y = round((height - box[1]) / 2)
172
+ pad_x, pad_y = round(size * 0.66), round(size * 0.44)
173
+ draw.rounded_rectangle(
174
+ (x - pad_x + 5, y - pad_y + 9, x + box[0] + pad_x + 5, y + box[1] + pad_y + 9),
175
+ radius=round(size * 0.34),
176
+ fill=(0, 0, 0, 90),
177
+ )
178
+ draw.rounded_rectangle(
179
+ (x - pad_x, y - pad_y, x + box[0] + pad_x, y + box[1] + pad_y),
180
+ radius=round(size * 0.34),
181
+ fill=(19, 24, 21, 205),
182
+ )
183
+ self._multiline(draw, (x, y), lines, font, (255, 255, 250, 255), size)
184
+
185
+ @staticmethod
186
+ def _wrap(draw, text: str, font, maximum_width: int) -> tuple[str, ...]:
187
+ lines: list[str] = []
188
+ for paragraph in text.splitlines() or (text,):
189
+ current = ""
190
+ for character in paragraph:
191
+ candidate = current + character
192
+ if current and draw.textbbox((0, 0), candidate, font=font)[2] > maximum_width:
193
+ lines.append(current)
194
+ current = character
195
+ else:
196
+ current = candidate
197
+ if current:
198
+ lines.append(current)
199
+ return tuple(lines) or (text,)
200
+
201
+ @staticmethod
202
+ def _text_box(draw, lines: Iterable[str], font, spacing: int) -> tuple[int, int]:
203
+ boxes = [draw.textbbox((0, 0), line, font=font) for line in lines]
204
+ return max(box[2] - box[0] for box in boxes), sum(box[3] - box[1] for box in boxes) + spacing * (len(boxes) - 1)
205
+
206
+ @staticmethod
207
+ def _multiline(draw, origin, lines: Iterable[str], font, fill, font_size: int) -> None:
208
+ draw.multiline_text(
209
+ origin,
210
+ "\n".join(lines),
211
+ font=font,
212
+ fill=fill,
213
+ spacing=round(font_size * 0.30),
214
+ align="center",
215
+ stroke_width=max(1, round(font_size * 0.018)),
216
+ stroke_fill=(0, 0, 0, 45),
217
+ )
218
+
219
+
220
+ class FfmpegTitleCompositor:
221
+ """Overlay pre-rendered title cards without exposing timeline text to a shell."""
222
+
223
+ def __init__(
224
+ self,
225
+ executable: str = "ffmpeg",
226
+ *,
227
+ popen: Callable[..., subprocess.Popen[str]] = subprocess.Popen,
228
+ ) -> None:
229
+ self.executable = executable
230
+ self._popen = popen
231
+
232
+ def compose(
233
+ self,
234
+ source: Path,
235
+ titles: tuple[RenderedTitle, ...],
236
+ output: Path,
237
+ cancel: threading.Event,
238
+ duration_seconds: float,
239
+ progress: Callable[[float], None],
240
+ ) -> None:
241
+ command = [self.executable, "-hide_banner", "-loglevel", "error", "-y", "-i", str(source)]
242
+ filters = []
243
+ previous = "[0:v]"
244
+ for index, title in enumerate(titles, start=1):
245
+ command.extend(["-loop", "1", "-t", f"{title.duration_seconds:.6f}", "-i", str(title.path)])
246
+ fade = min(0.18, title.duration_seconds / 4)
247
+ fade_out = max(0.0, title.duration_seconds - fade)
248
+ filters.append(
249
+ f"[{index}:v]format=rgba,fade=t=in:st=0:d={fade:.3f}:alpha=1,"
250
+ f"fade=t=out:st={fade_out:.3f}:d={fade:.3f}:alpha=1,"
251
+ f"setpts=PTS+{title.start_seconds:.6f}/TB[title{index}]"
252
+ )
253
+ output_label = f"composed{index}"
254
+ filters.append(f"{previous}[title{index}]overlay=0:0:eof_action=pass:shortest=0[{output_label}]")
255
+ previous = f"[{output_label}]"
256
+ command.extend(
257
+ [
258
+ "-filter_complex",
259
+ ";".join(filters),
260
+ "-map",
261
+ previous,
262
+ "-map",
263
+ "0:a?",
264
+ "-c:v",
265
+ "libx264",
266
+ "-preset",
267
+ "veryfast",
268
+ "-crf",
269
+ "21",
270
+ "-pix_fmt",
271
+ "yuv420p",
272
+ "-c:a",
273
+ "copy",
274
+ "-movflags",
275
+ "+faststart",
276
+ "-progress",
277
+ "pipe:1",
278
+ "-nostats",
279
+ str(output),
280
+ ]
281
+ )
282
+ with tempfile.TemporaryFile() as errors:
283
+ try:
284
+ process = self._popen(command, stdout=subprocess.PIPE, stderr=errors, text=True)
285
+ except FileNotFoundError as error:
286
+ raise TitleRenderError("ffmpeg_unavailable") from error
287
+ except OSError as error:
288
+ raise TitleRenderError("ffmpeg_start_failed") from error
289
+ assert process.stdout is not None
290
+ terminated = False
291
+ try:
292
+ for line in process.stdout:
293
+ if cancel.is_set() and not terminated:
294
+ process.terminate()
295
+ terminated = True
296
+ if line.startswith("out_time_ms="):
297
+ value = line.split("=", 1)[1].strip()
298
+ if value.isdigit() and duration_seconds > 0:
299
+ progress(min(0.99, int(value) / 1_000_000 / duration_seconds))
300
+ finally:
301
+ close_stdout = getattr(process.stdout, "close", None)
302
+ if close_stdout is not None:
303
+ close_stdout()
304
+ code = process.wait()
305
+ if cancel.is_set():
306
+ raise TitleRenderError("cancelled")
307
+ if code != 0 or not output.is_file() or output.stat().st_size < 1:
308
+ raise TitleRenderError("ffmpeg_render_failed")
309
+ progress(1.0)
310
+
311
+
312
+ def compose_dense_titles(
313
+ executable, source, timeline, directory, output, cancel, custom_styles=None, progress=None, hardware=False
314
+ ):
315
+ """One event-based RGBA stream avoids opening dozens of full-HD inputs.
316
+
317
+ Reports progress while drawing (first 40%) and while FFmpeg overlays the
318
+ stream (the rest), so a long film never looks stuck at the same number.
319
+ """
320
+ report = progress or (lambda _value: None)
321
+ from PIL import Image, ImageDraw, ImageFont
322
+
323
+ from clipen.finishing.audio import run_process
324
+
325
+ items = [i for t in timeline.tracks if t.kind is TrackKind.TITLE for i in t.items]
326
+ if len(items) > (960 if timeline.production_session_id else 96):
327
+ raise TitleRenderError("preview_title_limit_exceeded")
328
+ font = TitleCardRenderer._font_path()
329
+ if font is None:
330
+ raise TitleRenderError("preview_title_font_missing")
331
+ renderer = TitleCardRenderer(custom_styles)
332
+ fps = timeline.frame_rate.numerator / timeline.frame_rate.denominator
333
+ boundaries = sorted(
334
+ {
335
+ 0,
336
+ timeline.duration_frames,
337
+ *(i.start_frame for i in items),
338
+ *(i.start_frame + i.duration_frames for i in items),
339
+ }
340
+ )
341
+ from .program_subtitles import animation_boundaries
342
+
343
+ boundaries = sorted(
344
+ set(boundaries)
345
+ | {
346
+ b
347
+ for i in items
348
+ if (custom_styles or {}).get(i.style_id, {}).get("kind") == "program_subtitle"
349
+ for b in animation_boundaries(i)
350
+ }
351
+ )
352
+ from .program_components import animation_boundaries as component_boundaries
353
+
354
+ boundaries = sorted(
355
+ set(boundaries)
356
+ | {
357
+ b
358
+ for i in items
359
+ if (custom_styles or {}).get(i.style_id, {}).get("kind") == "program_component"
360
+ for b in component_boundaries(i, custom_styles[i.style_id], timeline)
361
+ }
362
+ )
363
+ lines = ["ffconcat version 1.0"]
364
+ events = max(1, len(boundaries) - 1)
365
+ for index, (start, end) in enumerate(zip(boundaries, boundaries[1:])):
366
+ if cancel.is_set():
367
+ raise TitleRenderError("cancelled")
368
+ if index % 20 == 0:
369
+ report(0.4 * index / events)
370
+ image = Image.new("RGBA", (timeline.width, timeline.height), (0, 0, 0, 0))
371
+ draw = ImageDraw.Draw(image)
372
+ for item in items:
373
+ if item.start_frame <= start < item.start_frame + item.duration_frames:
374
+ renderer._draw_card(draw, ImageFont, font, timeline, item, start - item.start_frame)
375
+ name = f"text-event-{index}.png"
376
+ image.save(directory / name)
377
+ lines.extend(
378
+ (
379
+ f"file '{name}'",
380
+ f"option framerate {timeline.frame_rate.numerator}/{timeline.frame_rate.denominator}",
381
+ f"duration {(end - start) / fps:.9f}",
382
+ )
383
+ )
384
+ lines.extend(
385
+ (
386
+ f"file 'text-event-{len(boundaries) - 2}.png'",
387
+ f"option framerate {timeline.frame_rate.numerator}/{timeline.frame_rate.denominator}",
388
+ )
389
+ )
390
+ manifest = directory / "text-events.ffconcat"
391
+ manifest.write_text("\n".join(lines) + "\n")
392
+ report(0.4)
393
+ seconds = timeline.duration_frames / fps
394
+ progress_file = directory / "overlay-progress.txt"
395
+ done = threading.Event()
396
+
397
+ def watch():
398
+ # FFmpeg rewrites out_time_us in its progress file about twice a second.
399
+ while not done.wait(0.5):
400
+ try:
401
+ text = progress_file.read_text()
402
+ except OSError:
403
+ continue
404
+ times = [int(v) for v in re.findall(r"out_time_us=(\d+)", text)]
405
+ if times and seconds > 0:
406
+ report(0.4 + 0.6 * min(1.0, times[-1] / 1e6 / seconds))
407
+
408
+ watcher = threading.Thread(target=watch, daemon=True)
409
+ watcher.start()
410
+
411
+ def encode(video):
412
+ run_process(
413
+ [
414
+ executable,
415
+ "-v",
416
+ "error",
417
+ "-nostdin",
418
+ "-y",
419
+ "-progress",
420
+ str(progress_file),
421
+ "-filter_complex_threads",
422
+ "2",
423
+ "-i",
424
+ str(source),
425
+ "-f",
426
+ "concat",
427
+ "-safe",
428
+ "0",
429
+ "-i",
430
+ str(manifest),
431
+ "-filter_complex",
432
+ "[0:v][1:v]overlay=eof_action=repeat:format=auto,format=yuv420p[v]",
433
+ "-map",
434
+ "[v]",
435
+ "-map",
436
+ "0:a?",
437
+ "-t",
438
+ str(timeline.duration_frames / fps),
439
+ "-r",
440
+ f"{timeline.frame_rate.numerator}/{timeline.frame_rate.denominator}",
441
+ *video,
442
+ "-c:a",
443
+ "copy",
444
+ "-movflags",
445
+ "+faststart",
446
+ str(output),
447
+ ],
448
+ cancel,
449
+ timeout=max(300, round(timeline.duration_frames / fps * 3)),
450
+ )
451
+
452
+ software = ["-c:v", "libx264", "-preset", "veryfast", "-crf", "21"]
453
+ try:
454
+ if not hardware:
455
+ encode(software)
456
+ else:
457
+ # The Mac's video encoder is about a third faster; any machine that refuses it gets the software path.
458
+ try:
459
+ encode(["-c:v", "h264_videotoolbox", "-b:v", "8000k"])
460
+ except Exception:
461
+ if cancel.is_set():
462
+ raise
463
+ encode(software)
464
+ finally:
465
+ done.set()
466
+ watcher.join(timeout=2)
467
+ report(1.0)