@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,951 @@
1
+ """Skill discovery and source-anchored programme graphics exposed via MCP."""
2
+
3
+ import base64
4
+ import hashlib
5
+ import os
6
+ from dataclasses import dataclass, replace
7
+
8
+ from clipen.domain import TextClip, Track, TrackKind
9
+ from clipen.projects import ProjectError
10
+ from clipen.skills import list_skills
11
+ from clipen.skills.visual_styles import font_presets, public_font_styles, public_styles, style_presets
12
+
13
+ from .agent_models import ToolResult
14
+
15
+ # The colours a person may change on a graphic: its accent, its light and its dark colour.
16
+ COMPONENT_COLORS = frozenset({"accent", "paper", "ink"})
17
+
18
+
19
+ @dataclass(frozen=True)
20
+ class SourceContext:
21
+ """An actual user brief with unknown evidence, not a synthetic confirmed plan."""
22
+
23
+ brief: str
24
+ candidates: tuple = ()
25
+ limitations: tuple = ("素材尚未分析的範圍是未知;請用來源工具按需取證。",)
26
+
27
+ def candidate_map(self):
28
+ return {candidate.candidate_id: candidate for candidate in self.candidates}
29
+
30
+
31
+ class SkillTools:
32
+ def _session_value(self):
33
+ """Every run is an AI production session; there is no session-less path."""
34
+ if getattr(self, "_session_cache", None) is None:
35
+ session = self.repository.production_session(self.project_id, self.run_id)
36
+ if session is None:
37
+ raise ProjectError("production_required", "這個版本需要 AI 節目製作工作。", status_code=422)
38
+ self._session_cache = session
39
+ return self._session_cache
40
+
41
+ def _skill_value(self):
42
+ return self._session_value()["skill"]
43
+
44
+ def _source_rows(self):
45
+ from .production_media import source_rows
46
+
47
+ rows = source_rows(self.repository.projects, self.project_id)
48
+ session = self._session_value()
49
+ granted = {(r["version_id"], r["stream_index"]) for r in session["sources"]}
50
+ return [r for r in rows if (r["version_id"], r["stream_index"]) in granted]
51
+
52
+ def _production_list_production_skills(self, args):
53
+ return ToolResult({"skills": list_skills(), "selected": self._skill_summary()})
54
+
55
+ def _skill_summary(self):
56
+ value = self._skill_value()
57
+ return {
58
+ **{key: value[key] for key in ("skill_id", "version", "name", "content_hash", "limitations")},
59
+ **({"core": value["core"], "skill_chain": value["skill_chain"]} if value.get("skill_chain") else {}),
60
+ **({"template_skill": value["selected_template_skill"]} if value.get("selected_template_skill") else {}),
61
+ }
62
+
63
+ def _production_read_production_skill(self, args):
64
+ skill = self._skill_value()
65
+ resource = args.get("resource", "SKILL.md")
66
+ if resource in skill.get("assets", {}):
67
+ asset = skill["assets"][resource]
68
+ data = base64.b64decode(asset["data"], validate=True)
69
+ if len(data) > 512 * 1024 or hashlib.sha256(data).hexdigest() != asset["sha256"]:
70
+ raise ProjectError("skill_asset_invalid", "Skill 範例資產未通過校驗。", status_code=409)
71
+ path = self._workdir("skill-assets") / (asset["sha256"] + ".png")
72
+ if path.is_symlink():
73
+ raise ProjectError("storage_unsafe", "Skill 資產路徑不安全。", status_code=409)
74
+ if not path.exists():
75
+ descriptor = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
76
+ with os.fdopen(descriptor, "wb") as output:
77
+ output.write(data)
78
+ elif hashlib.sha256(path.read_bytes()).hexdigest() != asset["sha256"]:
79
+ raise ProjectError("skill_asset_invalid", "Skill 範例資產內容已改變。", status_code=409)
80
+ return ToolResult(
81
+ {
82
+ "skill": self._skill_summary(),
83
+ "resource": resource,
84
+ "authority": "style_example_not_source_evidence",
85
+ "instruction": "Use as a visual style reference only; never copy sample speech/facts into the film.",
86
+ },
87
+ (path,),
88
+ )
89
+ if resource not in skill["resources"]:
90
+ raise ProjectError("skill_resource_not_found", "Skill 沒有這份資源。", status_code=404)
91
+ content = skill["resources"][resource]
92
+ # The default read must actually deliver the selected instructions,
93
+ # even if the director has not discovered the nested resources yet.
94
+ # Sessions frozen before the core/skill split carry one selected skill.
95
+ applied = skill.get("skill_chain") or (
96
+ [skill["selected_template_skill"]] if skill.get("selected_template_skill") else []
97
+ )
98
+ if resource == "SKILL.md":
99
+ for selected in applied:
100
+ kind = {"custom": "custom"}.get(
101
+ selected.get("source"), "template" if "skill_chain" not in skill else "built-in"
102
+ )
103
+ content += (
104
+ "\n\n---\n\n"
105
+ + f"Selected {kind} Skill: {selected['skill_id']} v{selected['version']}\nResource: {selected['resource']}\n\n"
106
+ + skill["resources"][selected["resource"]]
107
+ )
108
+ else:
109
+ applied = []
110
+ return ToolResult(
111
+ {
112
+ "skill": self._skill_summary(),
113
+ "resource": resource,
114
+ "content": content,
115
+ "applied_template_skills": applied,
116
+ "available_resources": list(skill["resources"]) + list(skill.get("assets", {})),
117
+ }
118
+ )
119
+
120
+ def _production_list_program_components(self, args):
121
+ """How graphics are made now, the looks they share, and the ones already in the film."""
122
+ from clipen.rendering.custom_components import FONT_CHOICES
123
+
124
+ from . import component_looks
125
+ from .production_catalog import CUSTOM_COMPONENT_HELP
126
+ from .production_media import load_text_styles
127
+
128
+ styles = load_text_styles(self.repository.projects, self.project_id)
129
+ timeline = self._timeline()
130
+ existing = [
131
+ {
132
+ "element_id": item.item_id,
133
+ "start_frame": item.start_frame,
134
+ "duration_frames": item.duration_frames,
135
+ "text": item.text,
136
+ "designed_freely": styles.get(item.style_id, {}).get("component_id") == "custom",
137
+ "look_id": (styles.get(item.style_id, {}).get("look") or {}).get("look_id"),
138
+ }
139
+ for track in timeline.tracks
140
+ if track.track_id == "program-components" or track.track_id.startswith("program-components-")
141
+ for item in track.items
142
+ ]
143
+ return ToolResult(
144
+ {
145
+ "skill": self._skill_summary(),
146
+ "how": "free_design_only",
147
+ "tool": "add_custom_component",
148
+ "guidance": CUSTOM_COMPONENT_HELP,
149
+ "canvas": {"width": timeline.width, "height": timeline.height},
150
+ "existing_graphics": existing,
151
+ "looks": component_looks.listing(self),
152
+ "font_choices": [{"family": family, "label": label} for family, label in FONT_CHOICES.items()],
153
+ "older_graphics": "Graphics not designed_freely use retired built-in templates. Keep them, remove them with remove_program_component, "
154
+ "or replace them: remove, then design the new one with add_custom_component.",
155
+ }
156
+ )
157
+
158
+ def _component_draft(self, args):
159
+ """A programme graphic as a person's changes would leave it, checked but not saved.
160
+
161
+ args holds element_id plus any of text, detail, x, y, scale, colors ({accent, paper, ink}
162
+ as #rrggbb), visual_style_id, font_style_id, start_offset_frames and duration_frames;
163
+ anything left out keeps its current value.
164
+ Returns the changed clip, its style profile and the clip as it is now."""
165
+ from clipen.finishing.models import digest
166
+
167
+ from .production_media import load_text_styles
168
+
169
+ if not isinstance(args, dict) or not isinstance(args.get("element_id"), str):
170
+ raise ProjectError("agent_input_invalid", "元件設定格式不正確。", status_code=422)
171
+ timeline = self._timeline()
172
+ item = next(
173
+ (
174
+ i
175
+ for t in timeline.tracks
176
+ if t.track_id == "program-components" or t.track_id.startswith("program-components-")
177
+ for i in t.items
178
+ if i.item_id == args["element_id"]
179
+ ),
180
+ None,
181
+ )
182
+ profile = (
183
+ load_text_styles(self.repository.projects, self.project_id).get(item.style_id, {})
184
+ if isinstance(item, TextClip)
185
+ else {}
186
+ )
187
+ if profile.get("kind") != "program_component":
188
+ raise ProjectError(
189
+ "component_not_found", "找不到這個畫面元件,影片可能已經更新,請重新讀取。", status_code=404
190
+ )
191
+ if profile.get("component_id") == "custom":
192
+ return self._custom_draft(args, timeline, item, profile)
193
+ saved_text, _, saved_detail = item.text.partition("\n")
194
+ text, detail = args.get("text", saved_text), args.get("detail", saved_detail)
195
+ if not isinstance(text, str) or not isinstance(detail, str):
196
+ raise ProjectError("agent_input_invalid", "元件文字格式不正確。", status_code=422)
197
+ text, detail = text.strip(), detail.strip()
198
+ if not text:
199
+ raise ProjectError("component_text_empty", "元件的主要文字不能空白。", status_code=422)
200
+ if "\n" in text or "\n" in detail:
201
+ raise ProjectError(
202
+ "component_text_overflow", "主要文字與補充文字各寫一行,換行由元件處理。", status_code=422
203
+ )
204
+ skill = self._skill_value()
205
+ component = next((c for c in skill["components"] if c["component_id"] == profile.get("component_id")), None)
206
+ limit = component["max_characters"] if component else 48
207
+ if len(text) > limit or len(detail) > 48:
208
+ raise ProjectError(
209
+ "component_text_overflow",
210
+ f"這個元件的主要文字最多 {limit} 個字,補充文字最多 48 個字。",
211
+ status_code=422,
212
+ )
213
+
214
+ def number(key, low, high):
215
+ value = args.get(key, profile.get(key))
216
+ if isinstance(value, bool) or not isinstance(value, (int, float)) or not low <= value <= high:
217
+ raise ProjectError("component_unsafe_position", "元件要留在畫面裡。", status_code=422)
218
+ return round(float(value), 4)
219
+
220
+ x, y = number("x", 0, 0.95), number("y", 0, 0.95)
221
+ shot, start, duration = self._component_time(args, item, profile)
222
+ visual_style, presets = style_presets(skill, args.get("visual_style_id", profile.get("visual_style_id")))
223
+ font_style, presets = font_presets(skill, presets, args.get("font_style_id", profile.get("font_style_id")))
224
+ scale = args.get("scale", profile.get("scale", 1))
225
+ if isinstance(scale, bool) or not isinstance(scale, (int, float)) or not 0.6 <= scale <= 1.6:
226
+ raise ProjectError("component_scale_invalid", "元件大小要在 60% 到 160% 之間。", status_code=422)
227
+ colors = args.get("colors", profile.get("colors", {}))
228
+ if (
229
+ not isinstance(colors, dict)
230
+ or not set(colors) <= COMPONENT_COLORS
231
+ or not all(
232
+ isinstance(v, str) and len(v) == 7 and v[0] == "#" and all(c in "0123456789abcdefABCDEF" for c in v[1:])
233
+ for v in colors.values()
234
+ )
235
+ ):
236
+ raise ProjectError("component_color_invalid", "顏色格式不正確。", status_code=422)
237
+ # A person's colours replace the style's, keeping each colour's own transparency.
238
+ for name, value in colors.items():
239
+ presets["palette"][name] = [
240
+ int(value[1:3], 16),
241
+ int(value[3:5], 16),
242
+ int(value[5:7], 16),
243
+ presets["palette"][name][3],
244
+ ]
245
+ changed_profile = {key: value for key, value in profile.items() if key not in {"scale", "colors"}}
246
+ changed_profile.update(
247
+ {
248
+ "presets": presets,
249
+ "visual_style_id": visual_style,
250
+ "font_style_id": font_style,
251
+ "x": x,
252
+ "y": y,
253
+ "anchor_item_id": shot.item_id,
254
+ "start_offset_frames": start,
255
+ }
256
+ )
257
+ # Designed size and the style's colours are left out, so untouched graphics keep their identity.
258
+ if round(float(scale), 2) != 1:
259
+ changed_profile["scale"] = round(float(scale), 2)
260
+ if colors:
261
+ changed_profile["colors"] = {name: value.lower() for name, value in sorted(colors.items())}
262
+ style_id = "agent.component." + digest(changed_profile)[:24]
263
+ draft = replace(
264
+ item,
265
+ text=text + ("\n" + detail if detail else ""),
266
+ start_frame=shot.start_frame + start,
267
+ duration_frames=duration,
268
+ style_id=style_id,
269
+ )
270
+ from PIL import Image, ImageDraw
271
+
272
+ from clipen.rendering.program_components import draw_program_component
273
+ from clipen.rendering.titles import TitleCardRenderer, TitleRenderError
274
+
275
+ font = TitleCardRenderer._font_path()
276
+ if font is None:
277
+ raise ProjectError("preview_title_font_missing", "缺少可用的中文字型。", status_code=409)
278
+ try:
279
+ draw_program_component(
280
+ ImageDraw.Draw(Image.new("RGBA", (timeline.width, timeline.height))),
281
+ font,
282
+ timeline,
283
+ draft,
284
+ changed_profile,
285
+ 8,
286
+ )
287
+ except TitleRenderError as error:
288
+ message = (
289
+ "這套字型無法顯示部分字元,請換個寫法或換字體。"
290
+ if error.code == "program_component_missing_glyph"
291
+ else "缺少這套字型,請換一套字體。"
292
+ if error.code == "program_font_unavailable"
293
+ else "元件超出畫面了,請縮小一點、縮短文字或往左上移。"
294
+ )
295
+ raise ProjectError(error.code, message, status_code=422) from error
296
+ return draft, changed_profile, item
297
+
298
+ def _custom_draft(self, args, timeline, item, profile):
299
+ """A free design as a person's move or retime would leave it: x, y shift the whole page."""
300
+ from clipen.finishing.models import digest
301
+ from clipen.rendering import custom_components
302
+
303
+ def shift(key):
304
+ value = args.get(key, profile.get(key, 0))
305
+ if isinstance(value, bool) or not isinstance(value, (int, float)) or not -1 < value < 1:
306
+ raise ProjectError("component_unsafe_position", "元件要留在畫面裡。", status_code=422)
307
+ return round(float(value), 4)
308
+
309
+ shot, start, duration = self._component_time(args, item, profile)
310
+ changed = {
311
+ **profile,
312
+ "x": shift("x"),
313
+ "y": shift("y"),
314
+ "anchor_item_id": shot.item_id,
315
+ "start_offset_frames": start,
316
+ }
317
+ if args.get("look_id") is not None and args["look_id"] != (profile.get("look") or {}).get("look_id"):
318
+ from . import component_looks
319
+
320
+ look = component_looks.current(self).get(args["look_id"])
321
+ if look is None:
322
+ raise ProjectError("component_look_not_found", "沒有這個外觀,請重新讀取。", status_code=422)
323
+ changed["look"] = look
324
+ fields = profile.get("fields") or {"texts": [], "colors": []}
325
+ edits = {kind: dict((profile.get("edits") or {}).get(kind, {})) for kind in ("texts", "colors")}
326
+ for kind, check_value, problem in (
327
+ ("texts", lambda v: isinstance(v, str) and v.strip() and len(v) <= 120, "文字不能空白,最多 120 個字。"),
328
+ (
329
+ "colors",
330
+ lambda v: isinstance(v, str)
331
+ and len(v) == 7
332
+ and v[0] == "#"
333
+ and all(c in "0123456789abcdefABCDEF" for c in v[1:]),
334
+ "顏色格式不正確。",
335
+ ),
336
+ ):
337
+ given = args.get(kind)
338
+ if given is None:
339
+ continue
340
+ designed = {f["key"]: f["value"] for f in fields[kind]}
341
+ if (
342
+ not isinstance(given, dict)
343
+ or not set(given) <= set(designed)
344
+ or not all(check_value(v) for v in given.values())
345
+ ):
346
+ raise ProjectError(
347
+ "component_field_invalid",
348
+ problem
349
+ if isinstance(given, dict) and set(given) <= set(designed)
350
+ else "這個元件沒有這個可編輯欄位。",
351
+ status_code=422,
352
+ )
353
+ # Only what differs from the design is kept, so an untouched field follows a redesign.
354
+ edits[kind] = {
355
+ k: (v.strip() if kind == "texts" else v.lower())
356
+ for k, v in given.items()
357
+ if (v.strip() if kind == "texts" else v.lower()) != designed[k]
358
+ }
359
+ changed.pop("edits", None)
360
+ if any(edits.values()):
361
+ changed["edits"] = {kind: values for kind, values in edits.items() if values}
362
+ draft = replace(
363
+ item,
364
+ start_frame=shot.start_frame + start,
365
+ duration_frames=duration,
366
+ style_id="agent.component." + digest(changed)[:24],
367
+ )
368
+ try:
369
+ custom_components.check(timeline, draft, changed)
370
+ if changed.get("look") != profile.get("look"):
371
+ custom_components.check_fonts(timeline, draft, changed)
372
+ except custom_components.CustomRenderError as error:
373
+ if error.code == "custom_component_font_outside_look":
374
+ raise ProjectError(
375
+ error.code,
376
+ f"這個元件的設計用了「{changed['look']['name']}」外觀沒有的字型({error.detail}),換不過去;請交給 AI 改。",
377
+ status_code=422,
378
+ ) from error
379
+ raise ProjectError(error.code, _custom_problem(error), status_code=422) from error
380
+ return draft, changed, item
381
+
382
+ def _edit_component(self, args):
383
+ """A person changes one programme graphic: wording, place, look, typeface or timing."""
384
+ from .production_media import atomic_json, load_text_styles, text_style_path
385
+
386
+ draft, profile, item = self._component_draft(args)
387
+ lane = args.get("lane")
388
+ if lane is not None and (isinstance(lane, bool) or not isinstance(lane, int) or not 0 <= lane < 12):
389
+ raise ProjectError("component_lane_invalid", "沒有這一軌。", status_code=422)
390
+ current = next(
391
+ n for n, t in enumerate(self._component_tracks()) if any(i.item_id == item.item_id for i in t.items)
392
+ )
393
+ if (draft.text, draft.start_frame, draft.duration_frames, draft.style_id) == (
394
+ item.text,
395
+ item.start_frame,
396
+ item.duration_frames,
397
+ item.style_id,
398
+ ) and lane in (None, current):
399
+ raise ProjectError("component_unchanged", "沒有任何變動。", status_code=422)
400
+ tracks = self._component_lanes(draft, lane)
401
+ styles = load_text_styles(self.repository.projects, self.project_id)
402
+ styles[draft.style_id] = profile
403
+ atomic_json(text_style_path(self.repository.projects, self.project_id), styles)
404
+ return self._save(replace(self._timeline(), tracks=tracks), args.get("summary") or "使用者修改元件")
405
+
406
+ def _production_set_component_look(self, args):
407
+ """The Agent creates or changes a look; graphics already using it follow."""
408
+ from . import component_looks
409
+
410
+ return self._apply_look(
411
+ component_looks.normalize({k: v for k, v in args.items() if k != "summary"}), args["summary"]
412
+ )
413
+
414
+ def _edit_component_look(self, args):
415
+ """A person picks other typefaces or colours for a look; its keys stay as the Agent named them."""
416
+ from . import component_looks
417
+
418
+ base = component_looks.current(self).get(args.get("look_id"))
419
+ if base is None:
420
+ raise ProjectError("component_look_not_found", "找不到這個外觀,請重新讀取。", status_code=404)
421
+ fonts, colors = args.get("fonts") or {}, args.get("colors") or {}
422
+ if (
423
+ not isinstance(fonts, dict)
424
+ or not isinstance(colors, dict)
425
+ or not set(fonts) <= {f["key"] for f in base["fonts"]}
426
+ or not set(colors) <= {c["key"] for c in base["colors"]}
427
+ ):
428
+ raise ProjectError("component_look_invalid", "這個外觀沒有這個字型或顏色。", status_code=422)
429
+ look = component_looks.normalize(
430
+ {
431
+ **base,
432
+ "fonts": [{**f, "family": fonts.get(f["key"], f["family"])} for f in base["fonts"]],
433
+ "colors": [{**c, "value": colors.get(c["key"], c["value"])} for c in base["colors"]],
434
+ }
435
+ )
436
+ if look == base:
437
+ raise ProjectError("component_unchanged", "沒有任何變動。", status_code=422)
438
+ return self._apply_look(look, args.get("summary") or "使用者修改外觀")
439
+
440
+ def _apply_look(self, look, summary):
441
+ """Save a look and redraw every graphic that uses it; refused if one would then need a typeface the look lacks."""
442
+ from clipen.finishing.models import digest
443
+ from clipen.rendering import custom_components
444
+
445
+ from . import component_looks
446
+ from .production_media import atomic_json, load_text_styles, text_style_path
447
+
448
+ looks = component_looks.current(self)
449
+ if look["look_id"] not in looks and len(looks) >= component_looks.MAX_LOOKS:
450
+ raise ProjectError(
451
+ "component_look_limit",
452
+ f"外觀最多 {component_looks.MAX_LOOKS} 套;請沿用或修改既有的外觀。",
453
+ status_code=422,
454
+ )
455
+ timeline = self._timeline()
456
+ changed, problems = {}, []
457
+ for item, profile in component_looks.on_film(self, timeline):
458
+ if (profile.get("look") or {}).get("look_id") != look["look_id"] or profile["look"] == look:
459
+ continue
460
+ updated = {**profile, "look": look}
461
+ draft = replace(item, style_id="agent.component." + digest(updated)[:24])
462
+ try:
463
+ custom_components.check_fonts(timeline, draft, updated)
464
+ except custom_components.CustomRenderError as error:
465
+ if error.code != "custom_component_font_outside_look":
466
+ raise ProjectError(error.code, _custom_problem(error), status_code=422) from error
467
+ problems.append(f"「{item.text}」({error.detail})")
468
+ changed[item.item_id] = (draft, updated)
469
+ if problems:
470
+ raise ProjectError(
471
+ "custom_component_font_outside_look",
472
+ "改了之後,這些元件會用到外觀以外的字型:"
473
+ + "、".join(problems)
474
+ + "。保留它們用到的字型 key,或先更新這些元件。",
475
+ status_code=422,
476
+ )
477
+ looks[look["look_id"]] = look
478
+ component_looks.store(self, looks)
479
+ public = component_looks.public(look, len(changed))
480
+ if not changed:
481
+ return ToolResult({"look": public, "updated_components": []})
482
+ styles = load_text_styles(self.repository.projects, self.project_id)
483
+ for draft, updated in changed.values():
484
+ styles[draft.style_id] = updated
485
+ atomic_json(text_style_path(self.repository.projects, self.project_id), styles)
486
+ tracks = tuple(
487
+ replace(t, items=tuple(changed[i.item_id][0] if i.item_id in changed else i for i in t.items))
488
+ for t in timeline.tracks
489
+ )
490
+ return self._save(replace(timeline, tracks=tracks), summary, look=public, updated_components=sorted(changed))
491
+
492
+ def _component_time(self, args, item, profile):
493
+ """Where a graphic sits in time: the shot it belongs to, its offset in that shot and its length.
494
+
495
+ item_id moves it onto another shot. It starts within that shot, so a recut keeps it on its footage, and may run on past the cut."""
496
+ shot_id = args.get("item_id", profile.get("anchor_item_id"))
497
+ shot = next((i for i in self._video().items if i.item_id == shot_id), None)
498
+ if shot is None:
499
+ raise ProjectError("component_anchor_missing", "這個元件所在的鏡頭已經不在影片裡。", status_code=409)
500
+ moved = shot_id != profile.get("anchor_item_id")
501
+ start = args.get("start_offset_frames", 0 if moved else item.start_frame - shot.start_frame)
502
+ duration = args.get("duration_frames", item.duration_frames)
503
+ if (
504
+ any(isinstance(v, bool) or not isinstance(v, int) for v in (start, duration))
505
+ or not 0 <= start < shot.duration_frames
506
+ or duration < 6
507
+ or shot.start_frame + start + duration > self._timeline().duration_frames
508
+ ):
509
+ raise ProjectError(
510
+ "component_time_out_of_bounds",
511
+ "元件要從這個鏡頭裡開始、在影片結束前結束,至少顯示 0.2 秒。",
512
+ status_code=422,
513
+ )
514
+ return shot, start, duration
515
+
516
+ def _component_tracks(self):
517
+ return [
518
+ t
519
+ for t in self._timeline().tracks
520
+ if t.track_id == "program-components" or t.track_id.startswith("program-components-")
521
+ ]
522
+
523
+ def _component_lanes(self, item, lane=None):
524
+ """The timeline's tracks with item placed. Graphics keep their lanes; ones that overlap in time sit on
525
+ separate lanes, and a later lane is drawn on top. lane asks for a particular lane (0 is the lowest)."""
526
+ timeline = self._timeline()
527
+ components = lambda track: track.track_id == "program-components" or track.track_id.startswith(
528
+ "program-components-"
529
+ )
530
+ tracks = tuple(t for t in timeline.tracks if not components(t))
531
+ lanes = [[i for i in t.items if i.item_id != item.item_id] for t in self._component_tracks()]
532
+ here = next(
533
+ (n for n, t in enumerate(self._component_tracks()) if any(i.item_id == item.item_id for i in t.items)), None
534
+ )
535
+ free = lambda n: n < len(lanes) and all(
536
+ i.start_frame + i.duration_frames <= item.start_frame
537
+ or item.start_frame + item.duration_frames <= i.start_frame
538
+ for i in lanes[n]
539
+ )
540
+ if lane is not None:
541
+ if lane > len(lanes):
542
+ raise ProjectError("component_lane_invalid", "沒有這一軌。", status_code=422)
543
+ if lane < len(lanes) and not free(lane):
544
+ raise ProjectError("component_lane_busy", "那一軌在這段時間已經有元件了。", status_code=422)
545
+ target = lane
546
+ else:
547
+ target = (
548
+ here if here is not None and free(here) else next((n for n in range(len(lanes)) if free(n)), len(lanes))
549
+ )
550
+ if target == len(lanes):
551
+ lanes.append([])
552
+ lanes[target].append(item)
553
+ lanes = [sorted(l, key=lambda i: (i.start_frame, i.item_id)) for l in lanes if l]
554
+ return tracks + tuple(
555
+ Track("program-components" if n == 0 else f"program-components-{n + 1}", TrackKind.TITLE, tuple(l))
556
+ for n, l in enumerate(lanes)
557
+ )
558
+
559
+ def _component_editing(self):
560
+ """What the review page needs to edit graphics: each one's settings and the run's styles."""
561
+ from .production_media import load_text_styles
562
+
563
+ skill = self._skill_value()
564
+ styles = load_text_styles(self.repository.projects, self.project_id)
565
+ shots = {i.item_id: i for i in self._video().items}
566
+ limits = {c["component_id"]: c["max_characters"] for c in skill["components"]}
567
+ names = {c["component_id"]: c.get("name", c["component_id"]) for c in skill["components"]}
568
+ result = {}
569
+ for track in self._timeline().tracks:
570
+ if not (track.track_id == "program-components" or track.track_id.startswith("program-components-")):
571
+ continue
572
+ for item in track.items:
573
+ profile = styles.get(item.style_id, {})
574
+ shot = shots.get(profile.get("anchor_item_id"))
575
+ if profile.get("kind") != "program_component" or shot is None:
576
+ continue
577
+ custom = profile["component_id"] == "custom"
578
+ result[item.item_id] = {
579
+ "component_id": profile["component_id"],
580
+ "custom": custom,
581
+ "name": item.text if custom else names.get(profile["component_id"], profile["component_id"]),
582
+ "max_characters": limits.get(profile["component_id"], 48),
583
+ "x": profile.get("x"),
584
+ "y": profile.get("y"),
585
+ "visual_style_id": profile.get("visual_style_id"),
586
+ "font_style_id": profile.get("font_style_id"),
587
+ "scale": profile.get("scale", 1),
588
+ "colors": profile.get("colors", {}),
589
+ **(
590
+ {
591
+ "fields": profile.get("fields") or {"texts": [], "colors": []},
592
+ "edits": profile.get("edits") or {},
593
+ "look_id": (profile.get("look") or {}).get("look_id"),
594
+ }
595
+ if custom
596
+ else {}
597
+ ),
598
+ "shot_start_frame": shot.start_frame,
599
+ "shot_duration_frames": shot.duration_frames,
600
+ }
601
+
602
+ def palette(identifier):
603
+ colours = style_presets(skill, identifier)[1]["palette"]
604
+ return {name: "#%02x%02x%02x" % tuple(colours[name][:3]) for name in sorted(COMPONENT_COLORS)}
605
+
606
+ from clipen.rendering.custom_components import FONT_CHOICES
607
+
608
+ from . import component_looks
609
+
610
+ return {
611
+ "looks": component_looks.listing(self),
612
+ "font_choices": [{"family": f, "label": l} for f, l in FONT_CHOICES.items()],
613
+ "components": result,
614
+ "visual_styles": [
615
+ {"id": v["visual_style_id"], "name": v["name"], "colors": palette(v["visual_style_id"])}
616
+ for v in public_styles(skill)
617
+ ],
618
+ "font_styles": [{"id": f["font_style_id"], "name": f["name"]} for f in public_font_styles(skill)],
619
+ }
620
+
621
+ def _component_issues(self):
622
+ from PIL import Image, ImageDraw
623
+
624
+ from clipen.rendering.program_components import component_bounds
625
+ from clipen.rendering.titles import TitleCardRenderer, TitleRenderError
626
+
627
+ from .production_media import load_text_styles
628
+
629
+ timeline = self._timeline()
630
+ styles = load_text_styles(self.repository.projects, self.project_id)
631
+ shots = {i.item_id: i for i in self._video().items}
632
+ elements = [
633
+ i
634
+ for t in timeline.tracks
635
+ if (t.track_id == "program-components" or t.track_id.startswith("program-components-"))
636
+ for i in t.items
637
+ ]
638
+ font = TitleCardRenderer._font_path()
639
+ issues = []
640
+ boxes = []
641
+ for element in elements:
642
+ profile = styles.get(element.style_id, {})
643
+ anchor = shots.get(profile.get("anchor_item_id"))
644
+ if profile.get("kind") != "program_component" or anchor is None:
645
+ issues.append({"code": "component_anchor_missing", "item_id": element.item_id})
646
+ continue
647
+ if (
648
+ not anchor.start_frame <= element.start_frame < anchor.start_frame + anchor.duration_frames
649
+ or element.start_frame + element.duration_frames > timeline.duration_frames
650
+ ):
651
+ issues.append({"code": "component_anchor_out_of_bounds", "item_id": element.item_id})
652
+ continue
653
+ if font is None:
654
+ issues.append({"code": "preview_title_font_missing", "item_id": element.item_id})
655
+ continue
656
+ try:
657
+ box, _, _ = component_bounds(
658
+ ImageDraw.Draw(Image.new("RGBA", (1, 1))), font, timeline, element, profile
659
+ )
660
+ boxes.append((element, box))
661
+ except TitleRenderError as error:
662
+ issues.append({"code": error.code, "item_id": element.item_id})
663
+ # Subtitles may be rebuilt after a graphic was placed; recheck the pair here.
664
+ from .component_review import RESTATE_RATIO, concurrent_subtitles, restated_ratio
665
+
666
+ if (
667
+ profile.get("authority") != "user"
668
+ and profile.get("component_id") != "custom"
669
+ and restated_ratio(
670
+ element.text.partition("\n")[0],
671
+ concurrent_subtitles(timeline, element.start_frame, element.duration_frames),
672
+ )
673
+ >= RESTATE_RATIO
674
+ ):
675
+ issues.append(
676
+ {
677
+ "code": "component_restates_subtitle",
678
+ "item_id": element.item_id,
679
+ "advisory": True,
680
+ "message": "元件文字和同時出現的字幕大部分重複;不是刻意強調的話可以改寫。",
681
+ }
682
+ )
683
+ for n, (a, left) in enumerate(boxes):
684
+ for b, right in boxes[n + 1 :]:
685
+ if (
686
+ a.start_frame < b.start_frame + b.duration_frames
687
+ and b.start_frame < a.start_frame + a.duration_frames
688
+ and left[0] < right[2]
689
+ and right[0] < left[2]
690
+ and left[1] < right[3]
691
+ and right[1] < left[3]
692
+ ):
693
+ issues.append({"code": "program_component_collision", "item_ids": [a.item_id, b.item_id]})
694
+ return issues
695
+
696
+ def _component_design_notes(self):
697
+ from .component_review import design_notes
698
+ from .production_media import load_text_styles
699
+
700
+ timeline = self._timeline()
701
+ elements = [
702
+ i
703
+ for t in timeline.tracks
704
+ if (t.track_id == "program-components" or t.track_id.startswith("program-components-"))
705
+ for i in t.items
706
+ ]
707
+ return design_notes(timeline, elements, load_text_styles(self.repository.projects, self.project_id))
708
+
709
+ def _production_add_custom_component(self, args):
710
+ return self._write_custom_component(args, updating=False)
711
+
712
+ def _production_update_custom_component(self, args):
713
+ return self._write_custom_component(args, updating=True)
714
+
715
+ def _write_custom_component(self, args, *, updating):
716
+ """A graphic the Agent designs itself as a web page; only technical checks apply."""
717
+ from clipen.finishing.models import digest
718
+ from clipen.rendering import custom_components
719
+
720
+ from .production_media import atomic_json, load_text_styles, text_style_path
721
+
722
+ timeline = self._timeline()
723
+ styles = load_text_styles(self.repository.projects, self.project_id)
724
+ current = next((i for t in timeline.tracks for i in t.items if i.item_id == args["element_id"]), None)
725
+ previous = styles.get(current.style_id, {}) if isinstance(current, TextClip) else {}
726
+ if updating and not custom_components.is_custom(previous):
727
+ raise ProjectError("component_not_found", "找不到要更新的自由元件。", status_code=404)
728
+ if not updating and current is not None:
729
+ raise ProjectError("component_identity_conflict", "這個 element_id 已經被使用。", status_code=409)
730
+ settings = {
731
+ **(
732
+ {
733
+ "item_id": previous["anchor_item_id"],
734
+ "start_offset_frames": previous["start_offset_frames"],
735
+ "duration_frames": current.duration_frames,
736
+ "name": current.text,
737
+ "html": previous["html"],
738
+ "evidence": previous.get("evidence", ""),
739
+ }
740
+ if updating
741
+ else {}
742
+ ),
743
+ **args,
744
+ }
745
+ shot = next((i for i in self._video().items if i.item_id == settings["item_id"]), None)
746
+ if shot is None:
747
+ raise ProjectError("component_anchor_missing", "畫面元件需要有效的鏡頭錨點。", status_code=422)
748
+ if (
749
+ settings["start_offset_frames"] >= shot.duration_frames
750
+ or shot.start_frame + settings["start_offset_frames"] + settings["duration_frames"]
751
+ > self._timeline().duration_frames
752
+ ):
753
+ raise ProjectError(
754
+ "component_time_out_of_bounds",
755
+ f"元件要從這個鏡頭裡開始(這個鏡頭長 {shot.duration_frames} 格),並在影片結束前結束。",
756
+ status_code=422,
757
+ )
758
+ skill = self._skill_value()
759
+ profile = {
760
+ "kind": "program_component",
761
+ "component_id": custom_components.CUSTOM,
762
+ "skill_id": skill["skill_id"],
763
+ "skill_version": skill["version"],
764
+ "skill_hash": skill["content_hash"],
765
+ "html": settings["html"],
766
+ "anchor_item_id": shot.item_id,
767
+ "start_offset_frames": settings["start_offset_frames"],
768
+ "evidence": settings.get("evidence", ""),
769
+ "x": previous.get("x", 0) if updating else 0,
770
+ "y": previous.get("y", 0) if updating else 0,
771
+ }
772
+ from . import component_looks
773
+
774
+ look_id = args.get("look_id") or (previous.get("look") or {}).get("look_id")
775
+ if not look_id:
776
+ raise ProjectError(
777
+ "component_look_required",
778
+ "先用 set_component_look 定下這類元件的外觀(字型與配色),再用 look_id 指定。",
779
+ status_code=422,
780
+ )
781
+ look = component_looks.current(self).get(look_id)
782
+ if look is None:
783
+ raise ProjectError(
784
+ "component_look_not_found",
785
+ "沒有這個外觀;先用 set_component_look 建立,或從 list_program_components 的 looks 選一個。",
786
+ status_code=422,
787
+ )
788
+ profile["look"] = look
789
+ item = TextClip(
790
+ args["element_id"],
791
+ shot.start_frame + settings["start_offset_frames"],
792
+ settings["duration_frames"],
793
+ settings["name"].strip() or "自由元件",
794
+ "pending",
795
+ )
796
+ try:
797
+ profile["fields"] = custom_components.fields(timeline, item, profile)
798
+ # A person's word and colour changes survive a redesign wherever the new page keeps that field.
799
+ keep = (
800
+ {
801
+ kind: {
802
+ k: v
803
+ for k, v in (previous.get("edits") or {}).get(kind, {}).items()
804
+ if k in {f["key"] for f in profile["fields"][kind]}
805
+ }
806
+ for kind in ("texts", "colors")
807
+ }
808
+ if updating
809
+ else {}
810
+ )
811
+ if any(keep.values()):
812
+ profile["edits"] = {kind: values for kind, values in keep.items() if values}
813
+ item = replace(item, style_id="agent.component." + digest(profile)[:24])
814
+ custom_components.check(timeline, item, profile)
815
+ custom_components.check_fonts(timeline, item, profile)
816
+ except custom_components.CustomRenderError as error:
817
+ raise ProjectError(error.code, _custom_problem(error), status_code=422) from error
818
+ styles[item.style_id] = profile
819
+ atomic_json(text_style_path(self.repository.projects, self.project_id), styles)
820
+ editable = {kind: [f["label"] for f in profile["fields"][kind]] for kind in ("texts", "colors")}
821
+ result = self._save(
822
+ replace(timeline, tracks=self._component_lanes(item)),
823
+ args["summary"],
824
+ element_id=item.item_id,
825
+ anchor_item_id=shot.item_id,
826
+ editable_by_people=editable,
827
+ look_id=look_id,
828
+ inspection_required="Look at both images: the resting still for legibility, faces and subtitles; the frame sheet (entry to exit, labelled by frame) for whether the motion reads and ends cleanly.",
829
+ **(
830
+ {}
831
+ if any(editable.values())
832
+ else {
833
+ "notes": [
834
+ "沒有標出可編輯的文字或顏色,使用者只能請你重做。用 data-clipen-text 與 --clipen-* 顏色變數標出主要文字和顏色。"
835
+ ]
836
+ }
837
+ ),
838
+ )
839
+ return ToolResult(result.payload, self._custom_still(result.payload["revision"]["revision_id"], item))
840
+
841
+ def _custom_still(self, revision_id, item):
842
+ """What the Agent looks at after saving: the graphic at rest over the actual footage, large enough
843
+ to judge legibility, and a sheet of frames from entry to exit, so it can judge the motion too."""
844
+ import base64
845
+ from io import BytesIO
846
+
847
+ from PIL import Image, ImageDraw, ImageFont
848
+
849
+ from clipen.rendering import custom_components
850
+
851
+ from .visual_preview import frame
852
+
853
+ timeline = self._timeline()
854
+ fps = timeline.frame_rate.numerator / timeline.frame_rate.denominator
855
+ last = item.duration_frames - 1
856
+ # Dense through the entry, where most motion is, then the middle and the exit.
857
+ moments = sorted(
858
+ {
859
+ 0,
860
+ min(last, round(fps * 0.1)),
861
+ min(last, round(fps * 0.25)),
862
+ min(last, round(fps * 0.5)),
863
+ item.duration_frames // 2,
864
+ max(0, last - round(fps * 0.3)),
865
+ max(0, last - round(fps * 0.1)),
866
+ last,
867
+ }
868
+ )
869
+ offline = False
870
+
871
+ def picture(relative):
872
+ nonlocal offline
873
+ if not offline:
874
+ try:
875
+ still = frame(
876
+ self.repository, self.project_id, self.run_id, revision_id, item.start_frame + relative
877
+ )
878
+ with Image.open(BytesIO(base64.b64decode(still["image_data_url"].split(",", 1)[1]))) as image:
879
+ return image.convert("RGB")
880
+ except ProjectError:
881
+ offline = True # Footage not connected: the design alone on grey still shows the motion.
882
+ image = Image.new("RGBA", (timeline.width, timeline.height), (128, 128, 128, 255))
883
+ custom_components.draw(ImageDraw.Draw(image), timeline, item, load_style(self, item.style_id), relative)
884
+ image = image.convert("RGB")
885
+ image.thumbnail((960, 960))
886
+ return image
887
+
888
+ folder = self._workdir("custom-components")
889
+ name = f"{item.item_id}-{revision_id[-12:]}"
890
+ resting = picture(item.duration_frames // 2)
891
+ still = folder / f"{name}.jpg"
892
+ resting.save(still, "JPEG", quality=88)
893
+ tiles = [(relative, picture(relative)) for relative in moments]
894
+ width = 320
895
+ height = round(width * tiles[0][1].height / tiles[0][1].width)
896
+ columns = 4
897
+ rows = (len(tiles) + columns - 1) // columns
898
+ sheet = Image.new("RGB", (columns * width, rows * (height + 22)), (16, 16, 18))
899
+ label = ImageFont.load_default(size=15)
900
+ draw = ImageDraw.Draw(sheet)
901
+ for index, (relative, image) in enumerate(tiles):
902
+ x, y = index % columns * width, index // columns * (height + 22)
903
+ sheet.paste(image.resize((width, height)), (x, y + 22))
904
+ draw.text((x + 6, y + 3), f"frame {relative} +{relative / fps:.2f}s", fill=(230, 230, 230), font=label)
905
+ frames = folder / f"{name}-motion.jpg"
906
+ sheet.save(frames, "JPEG", quality=80)
907
+ return (still, frames)
908
+
909
+ def _production_remove_program_component(self, args):
910
+ timeline = self._timeline()
911
+ if not any(
912
+ i.item_id == args["element_id"]
913
+ for t in timeline.tracks
914
+ if (t.track_id == "program-components" or t.track_id.startswith("program-components-"))
915
+ for i in t.items
916
+ ):
917
+ raise ProjectError("component_not_found", "找不到這個畫面元件。", status_code=404)
918
+ return self._save(
919
+ replace(
920
+ timeline,
921
+ tracks=tuple(
922
+ replace(t, items=tuple(i for i in t.items if i.item_id != args["element_id"]))
923
+ for t in timeline.tracks
924
+ ),
925
+ ),
926
+ args["summary"],
927
+ )
928
+
929
+
930
+ def _custom_problem(error):
931
+ """What went wrong with an Agent's page, in words it can act on."""
932
+ detail = f"({error.detail})" if getattr(error, "detail", "") else ""
933
+ return {
934
+ "custom_component_html_missing": "請提供元件的 HTML。",
935
+ "custom_component_html_too_large": "元件頁面超過 200 KB,請精簡或改用向量繪製。",
936
+ "custom_component_empty": "頁面在開頭、中間和結尾都沒有畫出任何東西;請確認元素可見,背景以外的地方保持透明。",
937
+ "custom_component_load_timeout": "頁面在 10 秒內沒有載入完成,可能有無窮迴圈或等待網路。",
938
+ "custom_component_load_failed": "頁面載入失敗" + detail + "。",
939
+ "custom_component_script_error": "頁面的程式出錯" + detail + "。",
940
+ "custom_component_frame_timeout": "有一格超過 10 秒還沒畫完;clipenFrame 要能直接畫出指定的那一格。",
941
+ "custom_component_renderer_missing": "這台電腦沒有可用的 Chrome,無法繪製自由元件" + detail + "。",
942
+ "custom_component_font_outside_look": "頁面用了外觀以外的字型"
943
+ + detail
944
+ + ";文字的字型要寫成 var(--look-font-鍵名)。想換字或加一套字,先用 set_component_look 改外觀。",
945
+ }.get(error.code, "自由元件繪製失敗" + detail + "。")
946
+
947
+
948
+ def load_style(tools, style_id):
949
+ from .production_media import load_text_styles
950
+
951
+ return load_text_styles(tools.repository.projects, tools.project_id)[style_id]