@clipen/clipen-cli 1.0.0 → 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 (127) hide show
  1. package/README.md +60 -50
  2. package/package.json +7 -4
  3. package/pyproject.toml +18 -2
  4. package/requirements/dev.txt +2 -0
  5. package/src/clipen/__init__.py +1 -1
  6. package/src/clipen/analysis/__init__.py +7 -7
  7. package/src/clipen/analysis/artifacts.py +4 -10
  8. package/src/clipen/analysis/audio.py +10 -8
  9. package/src/clipen/analysis/evidence_service.py +345 -167
  10. package/src/clipen/analysis/image_similarity.py +5 -14
  11. package/src/clipen/analysis/keyframes.py +5 -17
  12. package/src/clipen/analysis/models.py +5 -7
  13. package/src/clipen/analysis/qwen_worker.py +19 -54
  14. package/src/clipen/analysis/resources.py +2 -1
  15. package/src/clipen/analysis/runtime.py +1 -3
  16. package/src/clipen/analysis/service.py +16 -48
  17. package/src/clipen/analysis/setup.py +11 -25
  18. package/src/clipen/analysis/setup_cli.py +5 -15
  19. package/src/clipen/analysis/storage.py +96 -278
  20. package/src/clipen/analysis/transcription.py +40 -82
  21. package/src/clipen/analysis/visual.py +109 -48
  22. package/src/clipen/annotations/__init__.py +5 -2
  23. package/src/clipen/annotations/models.py +1 -1
  24. package/src/clipen/annotations/storage.py +132 -84
  25. package/src/clipen/annotations/suggestions.py +3 -8
  26. package/src/clipen/asr_release.py +4 -11
  27. package/src/clipen/bootstrap.py +65 -54
  28. package/src/clipen/{planning/models.py → candidates.py} +29 -47
  29. package/src/clipen/cli.py +2 -2
  30. package/src/clipen/controller/app.py +401 -214
  31. package/src/clipen/controller/server.py +28 -38
  32. package/src/clipen/domain/__init__.py +1 -1
  33. package/src/clipen/domain/media_time.py +3 -10
  34. package/src/clipen/domain/timeline.py +45 -47
  35. package/src/clipen/domain/validation.py +0 -1
  36. package/src/clipen/editing/__init__.py +1 -1
  37. package/src/clipen/editing/agent_models.py +4 -11
  38. package/src/clipen/editing/agent_repository.py +391 -170
  39. package/src/clipen/editing/agent_tools.py +180 -99
  40. package/src/clipen/editing/alignment.py +92 -52
  41. package/src/clipen/editing/alignment_setup.py +118 -70
  42. package/src/clipen/editing/alignment_worker.py +11 -9
  43. package/src/clipen/editing/change_report.py +95 -38
  44. package/src/clipen/editing/compiler.py +0 -1
  45. package/src/clipen/editing/component_looks.py +58 -34
  46. package/src/clipen/editing/component_review.py +34 -38
  47. package/src/clipen/editing/coordinator.py +213 -90
  48. package/src/clipen/editing/editorial_review.py +217 -95
  49. package/src/clipen/editing/evidence_jobs.py +457 -200
  50. package/src/clipen/editing/history_changes.py +129 -68
  51. package/src/clipen/editing/music_choices.py +8 -5
  52. package/src/clipen/editing/production_catalog.py +573 -136
  53. package/src/clipen/editing/production_limits.py +43 -17
  54. package/src/clipen/editing/production_media.py +376 -167
  55. package/src/clipen/editing/production_preview.py +322 -129
  56. package/src/clipen/editing/production_progress.py +164 -69
  57. package/src/clipen/editing/production_requirements.py +106 -39
  58. package/src/clipen/editing/production_tools.py +1064 -462
  59. package/src/clipen/editing/program_audio.py +211 -81
  60. package/src/clipen/editing/program_direction.py +59 -25
  61. package/src/clipen/editing/program_story.py +83 -45
  62. package/src/clipen/editing/program_subtitles.py +194 -96
  63. package/src/clipen/editing/programme_review.py +98 -50
  64. package/src/clipen/editing/prompt_history.py +64 -27
  65. package/src/clipen/editing/recut.py +65 -25
  66. package/src/clipen/editing/refinement_references.py +176 -86
  67. package/src/clipen/editing/resolve_export.py +449 -218
  68. package/src/clipen/editing/resolve_titles.py +162 -105
  69. package/src/clipen/editing/skill_tools.py +530 -154
  70. package/src/clipen/editing/source_dialogue.py +177 -67
  71. package/src/clipen/editing/speech_coverage.py +42 -22
  72. package/src/clipen/editing/speech_quality.py +6 -1
  73. package/src/clipen/editing/tool_receipts.py +78 -32
  74. package/src/clipen/editing/versions.py +122 -64
  75. package/src/clipen/editing/visual_preview.py +157 -61
  76. package/src/clipen/editing/workbench.py +104 -42
  77. package/src/clipen/finishing/audio.py +69 -30
  78. package/src/clipen/finishing/catalog.py +176 -93
  79. package/src/clipen/finishing/models.py +1 -1
  80. package/src/clipen/finishing/renderer.py +33 -14
  81. package/src/clipen/mcp_editing/__main__.py +3 -1
  82. package/src/clipen/mcp_editing/server.py +77 -34
  83. package/src/clipen/media/__init__.py +3 -3
  84. package/src/clipen/media/discovery.py +7 -20
  85. package/src/clipen/media/models.py +7 -18
  86. package/src/clipen/media/preview.py +14 -24
  87. package/src/clipen/media/probe.py +16 -44
  88. package/src/clipen/media/service.py +6 -19
  89. package/src/clipen/media/storage.py +33 -81
  90. package/src/clipen/music_vocabulary.py +33 -4
  91. package/src/clipen/power.py +8 -3
  92. package/src/clipen/projects/__init__.py +1 -1
  93. package/src/clipen/projects/deletion.py +19 -32
  94. package/src/clipen/projects/finishing_schema.py +3 -1
  95. package/src/clipen/projects/models.py +2 -5
  96. package/src/clipen/projects/picker.py +13 -37
  97. package/src/clipen/projects/service.py +8 -24
  98. package/src/clipen/projects/storage.py +226 -246
  99. package/src/clipen/provider_registry.py +4 -2
  100. package/src/clipen/providers/account.py +86 -35
  101. package/src/clipen/providers/claude.py +59 -25
  102. package/src/clipen/providers/claude_editing.py +14 -7
  103. package/src/clipen/providers/codex.py +73 -118
  104. package/src/clipen/providers/codex_editing.py +2 -2
  105. package/src/clipen/providers/editing_agent.py +19 -17
  106. package/src/clipen/providers/recovery.py +7 -8
  107. package/src/clipen/rendering/cover.py +18 -5
  108. package/src/clipen/rendering/custom_components.py +167 -79
  109. package/src/clipen/rendering/custom_render.py +62 -41
  110. package/src/clipen/rendering/production_effects.py +77 -45
  111. package/src/clipen/rendering/program_components.py +134 -73
  112. package/src/clipen/rendering/program_creator.py +432 -277
  113. package/src/clipen/rendering/program_identities.py +277 -182
  114. package/src/clipen/rendering/program_motion.py +140 -95
  115. package/src/clipen/rendering/program_studio.py +175 -116
  116. package/src/clipen/rendering/program_styles.py +231 -145
  117. package/src/clipen/rendering/program_subtitles.py +71 -34
  118. package/src/clipen/rendering/renderer.py +150 -121
  119. package/src/clipen/rendering/storage.py +9 -22
  120. package/src/clipen/rendering/titles.py +193 -86
  121. package/src/clipen/skills/__init__.py +1 -0
  122. package/src/clipen/skills/catalog.py +151 -55
  123. package/src/clipen/skills/library.py +13 -7
  124. package/src/clipen/skills/package.py +46 -23
  125. package/src/clipen/skills/visual_styles.py +29 -18
  126. package/src/clipen/workspace.py +15 -44
  127. package/src/clipen/planning/__init__.py +0 -9
@@ -1,14 +1,16 @@
1
1
  """Skill discovery and source-anchored programme graphics exposed via MCP."""
2
- from dataclasses import dataclass, replace
2
+
3
3
  import base64
4
4
  import hashlib
5
5
  import os
6
+ from dataclasses import dataclass, replace
6
7
 
7
8
  from clipen.domain import TextClip, Track, TrackKind
8
9
  from clipen.projects import ProjectError
9
- from clipen.skills import get_skill, list_skills
10
+ from clipen.skills import list_skills
11
+ from clipen.skills.visual_styles import font_presets, public_font_styles, public_styles, style_presets
12
+
10
13
  from .agent_models import ToolResult
11
- from clipen.skills.visual_styles import style_presets, public_styles, font_presets, public_font_styles
12
14
 
13
15
  # The colours a person may change on a graphic: its accent, its light and its dark colour.
14
16
  COMPONENT_COLORS = frozenset({"accent", "paper", "ink"})
@@ -17,6 +19,7 @@ COMPONENT_COLORS = frozenset({"accent", "paper", "ink"})
17
19
  @dataclass(frozen=True)
18
20
  class SourceContext:
19
21
  """An actual user brief with unknown evidence, not a synthetic confirmed plan."""
22
+
20
23
  brief: str
21
24
  candidates: tuple = ()
22
25
  limitations: tuple = ("素材尚未分析的範圍是未知;請用來源工具按需取證。",)
@@ -40,6 +43,7 @@ class SkillTools:
40
43
 
41
44
  def _source_rows(self):
42
45
  from .production_media import source_rows
46
+
43
47
  rows = source_rows(self.repository.projects, self.project_id)
44
48
  session = self._session_value()
45
49
  granted = {(r["version_id"], r["stream_index"]) for r in session["sources"]}
@@ -50,65 +54,106 @@ class SkillTools:
50
54
 
51
55
  def _skill_summary(self):
52
56
  value = self._skill_value()
53
- return {**{key: value[key] for key in ("skill_id", "version", "name", "content_hash", "limitations")},
54
- **({'core':value['core'],'skill_chain':value['skill_chain']} if value.get('skill_chain') else {}),
55
- **({'template_skill':value['selected_template_skill']} if value.get('selected_template_skill') else {})}
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
+ }
56
62
 
57
63
  def _production_read_production_skill(self, args):
58
64
  skill = self._skill_value()
59
65
  resource = args.get("resource", "SKILL.md")
60
- if resource in skill.get('assets',{}):
61
- asset=skill['assets'][resource];data=base64.b64decode(asset['data'],validate=True)
62
- if len(data)>512*1024 or hashlib.sha256(data).hexdigest()!=asset['sha256']:
63
- raise ProjectError('skill_asset_invalid','Skill 範例資產未通過校驗。',status_code=409)
64
- path=self._workdir('skill-assets')/(asset['sha256']+'.png')
65
- if path.is_symlink():raise ProjectError('storage_unsafe','Skill 資產路徑不安全。',status_code=409)
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)
66
74
  if not path.exists():
67
- descriptor=os.open(path,os.O_CREAT|os.O_EXCL|os.O_WRONLY,0o600)
68
- with os.fdopen(descriptor,'wb') as output:output.write(data)
69
- elif hashlib.sha256(path.read_bytes()).hexdigest()!=asset['sha256']:
70
- raise ProjectError('skill_asset_invalid','Skill 範例資產內容已改變。',status_code=409)
71
- return ToolResult({'skill':self._skill_summary(),'resource':resource,'authority':'style_example_not_source_evidence',
72
- 'instruction':'Use as a visual style reference only; never copy sample speech/facts into the film.'},(path,))
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
+ )
73
89
  if resource not in skill["resources"]:
74
90
  raise ProjectError("skill_resource_not_found", "Skill 沒有這份資源。", status_code=404)
75
- content=skill['resources'][resource]
91
+ content = skill["resources"][resource]
76
92
  # The default read must actually deliver the selected instructions,
77
93
  # even if the director has not discovered the nested resources yet.
78
94
  # Sessions frozen before the core/skill split carry one selected skill.
79
- applied=skill.get('skill_chain') or ([skill['selected_template_skill']] if skill.get('selected_template_skill') else [])
80
- if resource=='SKILL.md':
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":
81
99
  for selected in applied:
82
- kind={'custom':'custom'}.get(selected.get('source'),'template' if 'skill_chain' not in skill else 'built-in')
83
- content+='\n\n---\n\n'+f"Selected {kind} Skill: {selected['skill_id']} v{selected['version']}\nResource: {selected['resource']}\n\n"+skill['resources'][selected['resource']]
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
+ )
84
108
  else:
85
- applied=[]
86
- return ToolResult({"skill": self._skill_summary(), "resource": resource,
87
- "content": content, 'applied_template_skills':applied,
88
- "available_resources": list(skill["resources"])+list(skill.get('assets',{}))})
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
+ )
89
119
 
90
120
  def _production_list_program_components(self, args):
91
121
  """How graphics are made now, the looks they share, and the ones already in the film."""
92
122
  from clipen.rendering.custom_components import FONT_CHOICES
123
+
93
124
  from . import component_looks
94
125
  from .production_catalog import CUSTOM_COMPONENT_HELP
95
126
  from .production_media import load_text_styles
127
+
96
128
  styles = load_text_styles(self.repository.projects, self.project_id)
97
129
  timeline = self._timeline()
98
- existing = [{"element_id": item.item_id, "start_frame": item.start_frame, "duration_frames": item.duration_frames,
99
- "text": item.text, "designed_freely": styles.get(item.style_id, {}).get("component_id") == "custom",
100
- "look_id": (styles.get(item.style_id, {}).get("look") or {}).get("look_id")}
101
- for track in timeline.tracks if track.track_id == "program-components" or track.track_id.startswith("program-components-")
102
- for item in track.items]
103
- return ToolResult({"skill": self._skill_summary(), "how": "free_design_only", "tool": "add_custom_component",
104
- "guidance": CUSTOM_COMPONENT_HELP,
105
- "canvas": {"width": timeline.width, "height": timeline.height},
106
- "existing_graphics": existing,
107
- "looks": component_looks.listing(self),
108
- "font_choices": [{"family": family, "label": label} for family, label in FONT_CHOICES.items()],
109
- "older_graphics": "Graphics not designed_freely use retired built-in templates. Keep them, remove them with remove_program_component, "
110
- "or replace them: remove, then design the new one with add_custom_component."})
111
-
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
+ )
112
157
 
113
158
  def _component_draft(self, args):
114
159
  """A programme graphic as a person's changes would leave it, checked but not saved.
@@ -118,15 +163,31 @@ class SkillTools:
118
163
  anything left out keeps its current value.
119
164
  Returns the changed clip, its style profile and the clip as it is now."""
120
165
  from clipen.finishing.models import digest
166
+
121
167
  from .production_media import load_text_styles
168
+
122
169
  if not isinstance(args, dict) or not isinstance(args.get("element_id"), str):
123
170
  raise ProjectError("agent_input_invalid", "元件設定格式不正確。", status_code=422)
124
171
  timeline = self._timeline()
125
- item = next((i for t in timeline.tracks if t.track_id == "program-components" or t.track_id.startswith("program-components-")
126
- for i in t.items if i.item_id == args["element_id"]), None)
127
- profile = load_text_styles(self.repository.projects, self.project_id).get(item.style_id, {}) if isinstance(item, TextClip) else {}
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
+ )
128
187
  if profile.get("kind") != "program_component":
129
- raise ProjectError("component_not_found", "找不到這個畫面元件,影片可能已經更新,請重新讀取。", status_code=404)
188
+ raise ProjectError(
189
+ "component_not_found", "找不到這個畫面元件,影片可能已經更新,請重新讀取。", status_code=404
190
+ )
130
191
  if profile.get("component_id") == "custom":
131
192
  return self._custom_draft(args, timeline, item, profile)
132
193
  saved_text, _, saved_detail = item.text.partition("\n")
@@ -137,54 +198,100 @@ class SkillTools:
137
198
  if not text:
138
199
  raise ProjectError("component_text_empty", "元件的主要文字不能空白。", status_code=422)
139
200
  if "\n" in text or "\n" in detail:
140
- raise ProjectError("component_text_overflow", "主要文字與補充文字各寫一行,換行由元件處理。", status_code=422)
201
+ raise ProjectError(
202
+ "component_text_overflow", "主要文字與補充文字各寫一行,換行由元件處理。", status_code=422
203
+ )
141
204
  skill = self._skill_value()
142
205
  component = next((c for c in skill["components"] if c["component_id"] == profile.get("component_id")), None)
143
206
  limit = component["max_characters"] if component else 48
144
207
  if len(text) > limit or len(detail) > 48:
145
- raise ProjectError("component_text_overflow", f"這個元件的主要文字最多 {limit} 個字,補充文字最多 48 個字。", status_code=422)
208
+ raise ProjectError(
209
+ "component_text_overflow",
210
+ f"這個元件的主要文字最多 {limit} 個字,補充文字最多 48 個字。",
211
+ status_code=422,
212
+ )
213
+
146
214
  def number(key, low, high):
147
215
  value = args.get(key, profile.get(key))
148
216
  if isinstance(value, bool) or not isinstance(value, (int, float)) or not low <= value <= high:
149
217
  raise ProjectError("component_unsafe_position", "元件要留在畫面裡。", status_code=422)
150
218
  return round(float(value), 4)
151
- x, y = number("x", 0, .95), number("y", 0, .95)
219
+
220
+ x, y = number("x", 0, 0.95), number("y", 0, 0.95)
152
221
  shot, start, duration = self._component_time(args, item, profile)
153
222
  visual_style, presets = style_presets(skill, args.get("visual_style_id", profile.get("visual_style_id")))
154
223
  font_style, presets = font_presets(skill, presets, args.get("font_style_id", profile.get("font_style_id")))
155
224
  scale = args.get("scale", profile.get("scale", 1))
156
- if isinstance(scale, bool) or not isinstance(scale, (int, float)) or not .6 <= scale <= 1.6:
225
+ if isinstance(scale, bool) or not isinstance(scale, (int, float)) or not 0.6 <= scale <= 1.6:
157
226
  raise ProjectError("component_scale_invalid", "元件大小要在 60% 到 160% 之間。", status_code=422)
158
227
  colors = args.get("colors", profile.get("colors", {}))
159
- if not isinstance(colors, dict) or not set(colors) <= COMPONENT_COLORS or not all(
160
- isinstance(v, str) and len(v) == 7 and v[0] == "#" and all(c in "0123456789abcdefABCDEF" for c in v[1:]) for v in colors.values()):
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
+ ):
161
236
  raise ProjectError("component_color_invalid", "顏色格式不正確。", status_code=422)
162
237
  # A person's colours replace the style's, keeping each colour's own transparency.
163
238
  for name, value in colors.items():
164
- presets["palette"][name] = [int(value[1:3], 16), int(value[3:5], 16), int(value[5:7], 16), presets["palette"][name][3]]
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
+ ]
165
245
  changed_profile = {key: value for key, value in profile.items() if key not in {"scale", "colors"}}
166
- changed_profile.update({"presets": presets, "visual_style_id": visual_style, "font_style_id": font_style,
167
- "x": x, "y": y, "anchor_item_id": shot.item_id, "start_offset_frames": start})
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
+ )
168
257
  # Designed size and the style's colours are left out, so untouched graphics keep their identity.
169
258
  if round(float(scale), 2) != 1:
170
259
  changed_profile["scale"] = round(float(scale), 2)
171
260
  if colors:
172
261
  changed_profile["colors"] = {name: value.lower() for name, value in sorted(colors.items())}
173
262
  style_id = "agent.component." + digest(changed_profile)[:24]
174
- draft = replace(item, text=text + ("\n" + detail if detail else ""), start_frame=shot.start_frame + start,
175
- duration_frames=duration, style_id=style_id)
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
+ )
176
270
  from PIL import Image, ImageDraw
271
+
177
272
  from clipen.rendering.program_components import draw_program_component
178
273
  from clipen.rendering.titles import TitleCardRenderer, TitleRenderError
274
+
179
275
  font = TitleCardRenderer._font_path()
180
276
  if font is None:
181
277
  raise ProjectError("preview_title_font_missing", "缺少可用的中文字型。", status_code=409)
182
278
  try:
183
- draw_program_component(ImageDraw.Draw(Image.new("RGBA", (timeline.width, timeline.height))), font, timeline, draft, changed_profile, 8)
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
+ )
184
287
  except TitleRenderError as error:
185
- message = ("這套字型無法顯示部分字元,請換個寫法或換字體。" if error.code == "program_component_missing_glyph"
186
- else "缺少這套字型,請換一套字體。" if error.code == "program_font_unavailable"
187
- else "元件超出畫面了,請縮小一點、縮短文字或往左上移。")
288
+ message = (
289
+ "這套字型無法顯示部分字元,請換個寫法或換字體。"
290
+ if error.code == "program_component_missing_glyph"
291
+ else "缺少這套字型,請換一套字體。"
292
+ if error.code == "program_font_unavailable"
293
+ else "元件超出畫面了,請縮小一點、縮短文字或往左上移。"
294
+ )
188
295
  raise ProjectError(error.code, message, status_code=422) from error
189
296
  return draft, changed_profile, item
190
297
 
@@ -192,15 +299,24 @@ class SkillTools:
192
299
  """A free design as a person's move or retime would leave it: x, y shift the whole page."""
193
300
  from clipen.finishing.models import digest
194
301
  from clipen.rendering import custom_components
302
+
195
303
  def shift(key):
196
304
  value = args.get(key, profile.get(key, 0))
197
305
  if isinstance(value, bool) or not isinstance(value, (int, float)) or not -1 < value < 1:
198
306
  raise ProjectError("component_unsafe_position", "元件要留在畫面裡。", status_code=422)
199
307
  return round(float(value), 4)
308
+
200
309
  shot, start, duration = self._component_time(args, item, profile)
201
- changed = {**profile, "x": shift("x"), "y": shift("y"), "anchor_item_id": shot.item_id, "start_offset_frames": start}
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
+ }
202
317
  if args.get("look_id") is not None and args["look_id"] != (profile.get("look") or {}).get("look_id"):
203
318
  from . import component_looks
319
+
204
320
  look = component_looks.current(self).get(args["look_id"])
205
321
  if look is None:
206
322
  raise ProjectError("component_look_not_found", "沒有這個外觀,請重新讀取。", status_code=422)
@@ -208,42 +324,78 @@ class SkillTools:
208
324
  fields = profile.get("fields") or {"texts": [], "colors": []}
209
325
  edits = {kind: dict((profile.get("edits") or {}).get(kind, {})) for kind in ("texts", "colors")}
210
326
  for kind, check_value, problem in (
211
- ("texts", lambda v: isinstance(v, str) and v.strip() and len(v) <= 120, "文字不能空白,最多 120 個字。"),
212
- ("colors", lambda v: isinstance(v, str) and len(v) == 7 and v[0] == "#" and all(c in "0123456789abcdefABCDEF" for c in v[1:]), "顏色格式不正確。")):
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
+ ):
213
337
  given = args.get(kind)
214
338
  if given is None:
215
339
  continue
216
340
  designed = {f["key"]: f["value"] for f in fields[kind]}
217
- if not isinstance(given, dict) or not set(given) <= set(designed) or not all(check_value(v) for v in given.values()):
218
- raise ProjectError("component_field_invalid", problem if isinstance(given, dict) and set(given) <= set(designed) else "這個元件沒有這個可編輯欄位。", status_code=422)
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
+ )
219
353
  # Only what differs from the design is kept, so an untouched field follows a redesign.
220
- edits[kind] = {k: (v.strip() if kind == "texts" else v.lower()) for k, v in given.items()
221
- if (v.strip() if kind == "texts" else v.lower()) != designed[k]}
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
+ }
222
359
  changed.pop("edits", None)
223
360
  if any(edits.values()):
224
361
  changed["edits"] = {kind: values for kind, values in edits.items() if values}
225
- draft = replace(item, start_frame=shot.start_frame + start, duration_frames=duration,
226
- style_id="agent.component." + digest(changed)[:24])
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
+ )
227
368
  try:
228
369
  custom_components.check(timeline, draft, changed)
229
370
  if changed.get("look") != profile.get("look"):
230
371
  custom_components.check_fonts(timeline, draft, changed)
231
372
  except custom_components.CustomRenderError as error:
232
373
  if error.code == "custom_component_font_outside_look":
233
- raise ProjectError(error.code, f"這個元件的設計用了「{changed['look']['name']}」外觀沒有的字型({error.detail}),換不過去;請交給 AI 改。", status_code=422) from error
374
+ raise ProjectError(
375
+ error.code,
376
+ f"這個元件的設計用了「{changed['look']['name']}」外觀沒有的字型({error.detail}),換不過去;請交給 AI 改。",
377
+ status_code=422,
378
+ ) from error
234
379
  raise ProjectError(error.code, _custom_problem(error), status_code=422) from error
235
380
  return draft, changed, item
236
381
 
237
382
  def _edit_component(self, args):
238
383
  """A person changes one programme graphic: wording, place, look, typeface or timing."""
239
384
  from .production_media import atomic_json, load_text_styles, text_style_path
385
+
240
386
  draft, profile, item = self._component_draft(args)
241
387
  lane = args.get("lane")
242
388
  if lane is not None and (isinstance(lane, bool) or not isinstance(lane, int) or not 0 <= lane < 12):
243
389
  raise ProjectError("component_lane_invalid", "沒有這一軌。", status_code=422)
244
- current = next(n for n, t in enumerate(self._component_tracks()) if any(i.item_id == item.item_id for i in t.items))
245
- if (draft.text, draft.start_frame, draft.duration_frames, draft.style_id) == (item.text, item.start_frame, item.duration_frames, item.style_id) \
246
- and lane in (None, current):
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):
247
399
  raise ProjectError("component_unchanged", "沒有任何變動。", status_code=422)
248
400
  tracks = self._component_lanes(draft, lane)
249
401
  styles = load_text_styles(self.repository.projects, self.project_id)
@@ -254,20 +406,33 @@ class SkillTools:
254
406
  def _production_set_component_look(self, args):
255
407
  """The Agent creates or changes a look; graphics already using it follow."""
256
408
  from . import component_looks
257
- return self._apply_look(component_looks.normalize({k: v for k, v in args.items() if k != "summary"}), args["summary"])
409
+
410
+ return self._apply_look(
411
+ component_looks.normalize({k: v for k, v in args.items() if k != "summary"}), args["summary"]
412
+ )
258
413
 
259
414
  def _edit_component_look(self, args):
260
415
  """A person picks other typefaces or colours for a look; its keys stay as the Agent named them."""
261
416
  from . import component_looks
417
+
262
418
  base = component_looks.current(self).get(args.get("look_id"))
263
419
  if base is None:
264
420
  raise ProjectError("component_look_not_found", "找不到這個外觀,請重新讀取。", status_code=404)
265
421
  fonts, colors = args.get("fonts") or {}, args.get("colors") or {}
266
- if not isinstance(fonts, dict) or not isinstance(colors, dict) or not set(fonts) <= {f["key"] for f in base["fonts"]} \
267
- or not set(colors) <= {c["key"] for c in base["colors"]}:
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
+ ):
268
428
  raise ProjectError("component_look_invalid", "這個外觀沒有這個字型或顏色。", status_code=422)
269
- look = component_looks.normalize({**base, "fonts": [{**f, "family": fonts.get(f["key"], f["family"])} for f in base["fonts"]],
270
- "colors": [{**c, "value": colors.get(c["key"], c["value"])} for c in base["colors"]]})
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
+ )
271
436
  if look == base:
272
437
  raise ProjectError("component_unchanged", "沒有任何變動。", status_code=422)
273
438
  return self._apply_look(look, args.get("summary") or "使用者修改外觀")
@@ -276,11 +441,17 @@ class SkillTools:
276
441
  """Save a look and redraw every graphic that uses it; refused if one would then need a typeface the look lacks."""
277
442
  from clipen.finishing.models import digest
278
443
  from clipen.rendering import custom_components
444
+
279
445
  from . import component_looks
280
446
  from .production_media import atomic_json, load_text_styles, text_style_path
447
+
281
448
  looks = component_looks.current(self)
282
449
  if look["look_id"] not in looks and len(looks) >= component_looks.MAX_LOOKS:
283
- raise ProjectError("component_look_limit", f"外觀最多 {component_looks.MAX_LOOKS} 套;請沿用或修改既有的外觀。", status_code=422)
450
+ raise ProjectError(
451
+ "component_look_limit",
452
+ f"外觀最多 {component_looks.MAX_LOOKS} 套;請沿用或修改既有的外觀。",
453
+ status_code=422,
454
+ )
284
455
  timeline = self._timeline()
285
456
  changed, problems = {}, []
286
457
  for item, profile in component_looks.on_film(self, timeline):
@@ -296,8 +467,13 @@ class SkillTools:
296
467
  problems.append(f"「{item.text}」({error.detail})")
297
468
  changed[item.item_id] = (draft, updated)
298
469
  if problems:
299
- raise ProjectError("custom_component_font_outside_look", "改了之後,這些元件會用到外觀以外的字型:" + "、".join(problems)
300
- + "。保留它們用到的字型 key,或先更新這些元件。", status_code=422)
470
+ raise ProjectError(
471
+ "custom_component_font_outside_look",
472
+ "改了之後,這些元件會用到外觀以外的字型:"
473
+ + "、".join(problems)
474
+ + "。保留它們用到的字型 key,或先更新這些元件。",
475
+ status_code=422,
476
+ )
301
477
  looks[look["look_id"]] = look
302
478
  component_looks.store(self, looks)
303
479
  public = component_looks.public(look, len(changed))
@@ -307,7 +483,10 @@ class SkillTools:
307
483
  for draft, updated in changed.values():
308
484
  styles[draft.style_id] = updated
309
485
  atomic_json(text_style_path(self.repository.projects, self.project_id), styles)
310
- tracks = tuple(replace(t, items=tuple(changed[i.item_id][0] if i.item_id in changed else i for i in t.items)) for t in timeline.tracks)
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
+ )
311
490
  return self._save(replace(timeline, tracks=tracks), summary, look=public, updated_components=sorted(changed))
312
491
 
313
492
  def _component_time(self, args, item, profile):
@@ -321,24 +500,43 @@ class SkillTools:
321
500
  moved = shot_id != profile.get("anchor_item_id")
322
501
  start = args.get("start_offset_frames", 0 if moved else item.start_frame - shot.start_frame)
323
502
  duration = args.get("duration_frames", item.duration_frames)
324
- if any(isinstance(v, bool) or not isinstance(v, int) for v in (start, duration)) or not 0 <= start < shot.duration_frames \
325
- or duration < 6 or shot.start_frame + start + duration > self._timeline().duration_frames:
326
- raise ProjectError("component_time_out_of_bounds", "元件要從這個鏡頭裡開始、在影片結束前結束,至少顯示 0.2 秒。", status_code=422)
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
+ )
327
514
  return shot, start, duration
328
515
 
329
516
  def _component_tracks(self):
330
- return [t for t in self._timeline().tracks if t.track_id == "program-components" or t.track_id.startswith("program-components-")]
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
+ ]
331
522
 
332
523
  def _component_lanes(self, item, lane=None):
333
524
  """The timeline's tracks with item placed. Graphics keep their lanes; ones that overlap in time sit on
334
525
  separate lanes, and a later lane is drawn on top. lane asks for a particular lane (0 is the lowest)."""
335
526
  timeline = self._timeline()
336
- components = lambda track: track.track_id == "program-components" or track.track_id.startswith("program-components-")
527
+ components = lambda track: track.track_id == "program-components" or track.track_id.startswith(
528
+ "program-components-"
529
+ )
337
530
  tracks = tuple(t for t in timeline.tracks if not components(t))
338
531
  lanes = [[i for i in t.items if i.item_id != item.item_id] for t in self._component_tracks()]
339
- here = next((n for n, t in enumerate(self._component_tracks()) if any(i.item_id == item.item_id for i in t.items)), None)
340
- free = lambda n: n < len(lanes) and all(i.start_frame + i.duration_frames <= item.start_frame
341
- or item.start_frame + item.duration_frames <= i.start_frame for i in lanes[n])
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
+ )
342
540
  if lane is not None:
343
541
  if lane > len(lanes):
344
542
  raise ProjectError("component_lane_invalid", "沒有這一軌。", status_code=422)
@@ -346,17 +544,22 @@ class SkillTools:
346
544
  raise ProjectError("component_lane_busy", "那一軌在這段時間已經有元件了。", status_code=422)
347
545
  target = lane
348
546
  else:
349
- target = here if here is not None and free(here) else next((n for n in range(len(lanes)) if free(n)), len(lanes))
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
+ )
350
550
  if target == len(lanes):
351
551
  lanes.append([])
352
552
  lanes[target].append(item)
353
553
  lanes = [sorted(l, key=lambda i: (i.start_frame, i.item_id)) for l in lanes if l]
354
- return tracks + tuple(Track("program-components" if n == 0 else f"program-components-{n+1}", TrackKind.TITLE, tuple(l))
355
- for n, l in enumerate(lanes))
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
+ )
356
558
 
357
559
  def _component_editing(self):
358
560
  """What the review page needs to edit graphics: each one's settings and the run's styles."""
359
561
  from .production_media import load_text_styles
562
+
360
563
  skill = self._skill_value()
361
564
  styles = load_text_styles(self.repository.projects, self.project_id)
362
565
  shots = {i.item_id: i for i in self._video().items}
@@ -373,64 +576,135 @@ class SkillTools:
373
576
  continue
374
577
  custom = profile["component_id"] == "custom"
375
578
  result[item.item_id] = {
376
- "component_id": profile["component_id"], "custom": custom,
579
+ "component_id": profile["component_id"],
580
+ "custom": custom,
377
581
  "name": item.text if custom else names.get(profile["component_id"], profile["component_id"]),
378
- "max_characters": limits.get(profile["component_id"], 48), "x": profile.get("x"), "y": profile.get("y"),
379
- "visual_style_id": profile.get("visual_style_id"), "font_style_id": profile.get("font_style_id"),
380
- "scale": profile.get("scale", 1), "colors": profile.get("colors", {}),
381
- **({"fields": profile.get("fields") or {"texts": [], "colors": []}, "edits": profile.get("edits") or {},
382
- "look_id": (profile.get("look") or {}).get("look_id")} if custom else {}),
383
- "shot_start_frame": shot.start_frame, "shot_duration_frames": shot.duration_frames}
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
+
384
602
  def palette(identifier):
385
603
  colours = style_presets(skill, identifier)[1]["palette"]
386
604
  return {name: "#%02x%02x%02x" % tuple(colours[name][:3]) for name in sorted(COMPONENT_COLORS)}
605
+
387
606
  from clipen.rendering.custom_components import FONT_CHOICES
607
+
388
608
  from . import component_looks
389
- return {"looks": component_looks.listing(self), "font_choices": [{"family": f, "label": l} for f, l in FONT_CHOICES.items()],
390
- "components": result, "visual_styles": [{"id": v["visual_style_id"], "name": v["name"], "colors": palette(v["visual_style_id"])} for v in public_styles(skill)],
391
- "font_styles": [{"id": f["font_style_id"], "name": f["name"]} for f in public_font_styles(skill)]}
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
+ }
392
620
 
393
621
  def _component_issues(self):
394
622
  from PIL import Image, ImageDraw
623
+
395
624
  from clipen.rendering.program_components import component_bounds
396
625
  from clipen.rendering.titles import TitleCardRenderer, TitleRenderError
626
+
397
627
  from .production_media import load_text_styles
398
- timeline=self._timeline();styles=load_text_styles(self.repository.projects,self.project_id)
399
- shots={i.item_id:i for i in self._video().items}
400
- elements=[i for t in timeline.tracks if (t.track_id=='program-components' or t.track_id.startswith('program-components-')) for i in t.items]
401
- font=TitleCardRenderer._font_path();issues=[];boxes=[]
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 = []
402
641
  for element in elements:
403
- profile=styles.get(element.style_id,{})
404
- anchor=shots.get(profile.get('anchor_item_id'))
405
- if profile.get('kind')!='program_component' or anchor is None:
406
- issues.append({'code':'component_anchor_missing','item_id':element.item_id});continue
407
- if not anchor.start_frame<=element.start_frame<anchor.start_frame+anchor.duration_frames or element.start_frame+element.duration_frames>timeline.duration_frames:
408
- issues.append({'code':'component_anchor_out_of_bounds','item_id':element.item_id});continue
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
409
653
  if font is None:
410
- issues.append({'code':'preview_title_font_missing','item_id':element.item_id});continue
654
+ issues.append({"code": "preview_title_font_missing", "item_id": element.item_id})
655
+ continue
411
656
  try:
412
- box,_,_=component_bounds(ImageDraw.Draw(Image.new('RGBA',(1,1))),font,timeline,element,profile)
413
- boxes.append((element,box))
414
- except TitleRenderError as error:issues.append({'code':error.code,'item_id':element.item_id})
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})
415
663
  # Subtitles may be rebuilt after a graphic was placed; recheck the pair here.
416
- from .component_review import RESTATE_RATIO,concurrent_subtitles,restated_ratio
417
- if profile.get('authority')!='user' and profile.get('component_id')!='custom' and restated_ratio(element.text.partition('\n')[0],concurrent_subtitles(timeline,element.start_frame,element.duration_frames))>=RESTATE_RATIO:
418
- issues.append({'code':'component_restates_subtitle','item_id':element.item_id,'advisory':True,
419
- 'message':'元件文字和同時出現的字幕大部分重複;不是刻意強調的話可以改寫。'})
420
- for n,(a,left) in enumerate(boxes):
421
- for b,right in boxes[n+1:]:
422
- if (a.start_frame<b.start_frame+b.duration_frames and b.start_frame<a.start_frame+a.duration_frames
423
- and left[0]<right[2] and right[0]<left[2] and left[1]<right[3] and right[1]<left[3]):
424
- issues.append({'code':'program_component_collision','item_ids':[a.item_id,b.item_id]})
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]})
425
694
  return issues
426
695
 
427
696
  def _component_design_notes(self):
428
697
  from .component_review import design_notes
429
698
  from .production_media import load_text_styles
430
- timeline=self._timeline()
431
- elements=[i for t in timeline.tracks if (t.track_id=='program-components' or t.track_id.startswith('program-components-')) for i in t.items]
432
- return design_notes(timeline,elements,load_text_styles(self.repository.projects,self.project_id))
433
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))
434
708
 
435
709
  def _production_add_custom_component(self, args):
436
710
  return self._write_custom_component(args, updating=False)
@@ -442,7 +716,9 @@ class SkillTools:
442
716
  """A graphic the Agent designs itself as a web page; only technical checks apply."""
443
717
  from clipen.finishing.models import digest
444
718
  from clipen.rendering import custom_components
719
+
445
720
  from .production_media import atomic_json, load_text_styles, text_style_path
721
+
446
722
  timeline = self._timeline()
447
723
  styles = load_text_styles(self.repository.projects, self.project_id)
448
724
  current = next((i for t in timeline.tracks for i in t.items if i.item_id == args["element_id"]), None)
@@ -451,33 +727,87 @@ class SkillTools:
451
727
  raise ProjectError("component_not_found", "找不到要更新的自由元件。", status_code=404)
452
728
  if not updating and current is not None:
453
729
  raise ProjectError("component_identity_conflict", "這個 element_id 已經被使用。", status_code=409)
454
- settings = {**({"item_id": previous["anchor_item_id"], "start_offset_frames": previous["start_offset_frames"],
455
- "duration_frames": current.duration_frames, "name": current.text, "html": previous["html"],
456
- "evidence": previous.get("evidence", "")} if updating else {}), **args}
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
+ }
457
745
  shot = next((i for i in self._video().items if i.item_id == settings["item_id"]), None)
458
746
  if shot is None:
459
747
  raise ProjectError("component_anchor_missing", "畫面元件需要有效的鏡頭錨點。", status_code=422)
460
- if settings["start_offset_frames"] >= shot.duration_frames or shot.start_frame + settings["start_offset_frames"] + settings["duration_frames"] > self._timeline().duration_frames:
461
- raise ProjectError("component_time_out_of_bounds", f"元件要從這個鏡頭裡開始(這個鏡頭長 {shot.duration_frames} 格),並在影片結束前結束。", 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
+ )
462
758
  skill = self._skill_value()
463
- profile = {"kind": "program_component", "component_id": custom_components.CUSTOM,
464
- "skill_id": skill["skill_id"], "skill_version": skill["version"], "skill_hash": skill["content_hash"],
465
- "html": settings["html"], "anchor_item_id": shot.item_id, "start_offset_frames": settings["start_offset_frames"],
466
- "evidence": settings.get("evidence", ""), "x": previous.get("x", 0) if updating else 0, "y": previous.get("y", 0) if updating else 0}
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
+ }
467
772
  from . import component_looks
773
+
468
774
  look_id = args.get("look_id") or (previous.get("look") or {}).get("look_id")
469
775
  if not look_id:
470
- raise ProjectError("component_look_required", "先用 set_component_look 定下這類元件的外觀(字型與配色),再用 look_id 指定。", status_code=422)
776
+ raise ProjectError(
777
+ "component_look_required",
778
+ "先用 set_component_look 定下這類元件的外觀(字型與配色),再用 look_id 指定。",
779
+ status_code=422,
780
+ )
471
781
  look = component_looks.current(self).get(look_id)
472
782
  if look is None:
473
- raise ProjectError("component_look_not_found", "沒有這個外觀;先用 set_component_look 建立,或從 list_program_components 的 looks 選一個。", status_code=422)
783
+ raise ProjectError(
784
+ "component_look_not_found",
785
+ "沒有這個外觀;先用 set_component_look 建立,或從 list_program_components 的 looks 選一個。",
786
+ status_code=422,
787
+ )
474
788
  profile["look"] = look
475
- item = TextClip(args["element_id"], shot.start_frame + settings["start_offset_frames"], settings["duration_frames"], settings["name"].strip() or "自由元件", "pending")
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
+ )
476
796
  try:
477
797
  profile["fields"] = custom_components.fields(timeline, item, profile)
478
798
  # A person's word and colour changes survive a redesign wherever the new page keeps that field.
479
- keep = {kind: {k: v for k, v in (previous.get("edits") or {}).get(kind, {}).items() if k in {f["key"] for f in profile["fields"][kind]}}
480
- for kind in ("texts", "colors")} if updating else {}
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
+ )
481
811
  if any(keep.values()):
482
812
  profile["edits"] = {kind: values for kind, values in keep.items() if values}
483
813
  item = replace(item, style_id="agent.component." + digest(profile)[:24])
@@ -488,10 +818,24 @@ class SkillTools:
488
818
  styles[item.style_id] = profile
489
819
  atomic_json(text_style_path(self.repository.projects, self.project_id), styles)
490
820
  editable = {kind: [f["label"] for f in profile["fields"][kind]] for kind in ("texts", "colors")}
491
- result = self._save(replace(timeline, tracks=self._component_lanes(item)), args["summary"], element_id=item.item_id,
492
- anchor_item_id=shot.item_id, editable_by_people=editable, look_id=look_id,
493
- 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.",
494
- **({} if any(editable.values()) else {"notes": ["沒有標出可編輯的文字或顏色,使用者只能請你重做。用 data-clipen-text 與 --clipen-* 顏色變數標出主要文字和顏色。"]}))
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
+ )
495
839
  return ToolResult(result.payload, self._custom_still(result.payload["revision"]["revision_id"], item))
496
840
 
497
841
  def _custom_still(self, revision_id, item):
@@ -499,22 +843,38 @@ class SkillTools:
499
843
  to judge legibility, and a sheet of frames from entry to exit, so it can judge the motion too."""
500
844
  import base64
501
845
  from io import BytesIO
846
+
502
847
  from PIL import Image, ImageDraw, ImageFont
848
+
503
849
  from clipen.rendering import custom_components
850
+
504
851
  from .visual_preview import frame
852
+
505
853
  timeline = self._timeline()
506
854
  fps = timeline.frame_rate.numerator / timeline.frame_rate.denominator
507
855
  last = item.duration_frames - 1
508
856
  # Dense through the entry, where most motion is, then the middle and the exit.
509
- moments = sorted({0, min(last, round(fps * .1)), min(last, round(fps * .25)), min(last, round(fps * .5)),
510
- item.duration_frames // 2, max(0, last - round(fps * .3)), max(0, last - round(fps * .1)), last})
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
+ )
511
869
  offline = False
512
870
 
513
871
  def picture(relative):
514
872
  nonlocal offline
515
873
  if not offline:
516
874
  try:
517
- still = frame(self.repository, self.project_id, self.run_id, revision_id, item.start_frame + relative)
875
+ still = frame(
876
+ self.repository, self.project_id, self.run_id, revision_id, item.start_frame + relative
877
+ )
518
878
  with Image.open(BytesIO(base64.b64decode(still["image_data_url"].split(",", 1)[1]))) as image:
519
879
  return image.convert("RGB")
520
880
  except ProjectError:
@@ -548,10 +908,23 @@ class SkillTools:
548
908
 
549
909
  def _production_remove_program_component(self, args):
550
910
  timeline = self._timeline()
551
- if not any(i.item_id == args["element_id"] for t in timeline.tracks if (t.track_id == "program-components" or t.track_id.startswith("program-components-")) for i in t.items):
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
+ ):
552
917
  raise ProjectError("component_not_found", "找不到這個畫面元件。", status_code=404)
553
- return self._save(replace(timeline, tracks=tuple(replace(t, items=tuple(i for i in t.items if i.item_id != args["element_id"]))
554
- for t in timeline.tracks)), args["summary"])
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
+ )
555
928
 
556
929
 
557
930
  def _custom_problem(error):
@@ -566,10 +939,13 @@ def _custom_problem(error):
566
939
  "custom_component_script_error": "頁面的程式出錯" + detail + "。",
567
940
  "custom_component_frame_timeout": "有一格超過 10 秒還沒畫完;clipenFrame 要能直接畫出指定的那一格。",
568
941
  "custom_component_renderer_missing": "這台電腦沒有可用的 Chrome,無法繪製自由元件" + detail + "。",
569
- "custom_component_font_outside_look": "頁面用了外觀以外的字型" + detail + ";文字的字型要寫成 var(--look-font-鍵名)。想換字或加一套字,先用 set_component_look 改外觀。",
942
+ "custom_component_font_outside_look": "頁面用了外觀以外的字型"
943
+ + detail
944
+ + ";文字的字型要寫成 var(--look-font-鍵名)。想換字或加一套字,先用 set_component_look 改外觀。",
570
945
  }.get(error.code, "自由元件繪製失敗" + detail + "。")
571
946
 
572
947
 
573
948
  def load_style(tools, style_id):
574
949
  from .production_media import load_text_styles
950
+
575
951
  return load_text_styles(tools.repository.projects, tools.project_id)[style_id]