@clipen/clipen-cli 1.0.8 → 1.0.9

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 (80) hide show
  1. package/README.md +13 -4
  2. package/apps/web/dist/assets/index-DPgSvXZ1.js +15 -0
  3. package/apps/web/dist/assets/index-DmPWV61v.css +1 -0
  4. package/apps/web/dist/index.html +2 -2
  5. package/bin/clipen.js +6 -15
  6. package/package.json +1 -1
  7. package/pyproject.toml +1 -1
  8. package/src/clipen/__init__.py +1 -1
  9. package/src/clipen/bootstrap.py +130 -23
  10. package/src/clipen/controller/app.py +83 -21
  11. package/src/clipen/controller/server.py +5 -0
  12. package/src/clipen/editing/agent_tools.py +1 -1
  13. package/src/clipen/editing/caption_design.py +134 -0
  14. package/src/clipen/editing/component_looks.py +3 -3
  15. package/src/clipen/editing/component_review.py +0 -38
  16. package/src/clipen/editing/coordinator.py +14 -0
  17. package/src/clipen/editing/production_catalog.py +67 -13
  18. package/src/clipen/editing/production_media.py +13 -2
  19. package/src/clipen/editing/production_preview.py +11 -9
  20. package/src/clipen/editing/production_progress.py +2 -0
  21. package/src/clipen/editing/production_tools.py +11 -20
  22. package/src/clipen/editing/program_subtitles.py +5 -13
  23. package/src/clipen/editing/resolve_export.py +2 -183
  24. package/src/clipen/editing/skill_tools.py +142 -218
  25. package/src/clipen/editing/tool_receipts.py +2 -1
  26. package/src/clipen/editing/versions.py +2 -0
  27. package/src/clipen/editing/visual_preview.py +62 -0
  28. package/src/clipen/editing/workbench.py +21 -1
  29. package/src/clipen/locale_en.py +18 -0
  30. package/src/clipen/media/storage.py +2 -2
  31. package/src/clipen/own_ffmpeg.py +113 -0
  32. package/src/clipen/providers/editing_agent.py +6 -4
  33. package/src/clipen/rendering/custom_components.py +216 -25
  34. package/src/clipen/rendering/custom_render.py +90 -54
  35. package/src/clipen/rendering/fetched_fonts.py +127 -0
  36. package/src/clipen/rendering/production_effects.py +24 -2
  37. package/src/clipen/rendering/program_components.py +18 -240
  38. package/src/clipen/rendering/renderer.py +23 -17
  39. package/src/clipen/rendering/titles.py +29 -12
  40. package/src/clipen/skills/builtin/SKILL.md +3 -3
  41. package/src/clipen/skills/builtin/assets/sample-daily-vlog.mp4 +0 -0
  42. package/src/clipen/skills/builtin/assets/sample-event-recap.mp4 +0 -0
  43. package/src/clipen/skills/builtin/assets/sample-food-review.mp4 +0 -0
  44. package/src/clipen/skills/builtin/assets/sample-product-demo.mp4 +0 -0
  45. package/src/clipen/skills/builtin/assets/sample-product-review.mp4 +0 -0
  46. package/src/clipen/skills/builtin/assets/sample-product-unboxing.mp4 +0 -0
  47. package/src/clipen/skills/builtin/assets/sample-shorts-highlight.mp4 +0 -0
  48. package/src/clipen/skills/builtin/assets/sample-travel-highlight.mp4 +0 -0
  49. package/src/clipen/skills/builtin/assets/sample-travel-vlog.mp4 +0 -0
  50. package/src/clipen/skills/builtin/assets/style-tpl-daily-vlog.png +0 -0
  51. package/src/clipen/skills/builtin/assets/style-tpl-event-recap.png +0 -0
  52. package/src/clipen/skills/builtin/assets/style-tpl-food-review.png +0 -0
  53. package/src/clipen/skills/builtin/assets/style-tpl-product-demo.png +0 -0
  54. package/src/clipen/skills/builtin/assets/style-tpl-product-review.png +0 -0
  55. package/src/clipen/skills/builtin/assets/style-tpl-product-unboxing.png +0 -0
  56. package/src/clipen/skills/builtin/assets/style-tpl-shorts-highlight.png +0 -0
  57. package/src/clipen/skills/builtin/assets/style-tpl-travel-highlight.png +0 -0
  58. package/src/clipen/skills/builtin/assets/style-tpl-travel-vlog.png +0 -0
  59. package/src/clipen/skills/builtin/references/captions.md +12 -0
  60. package/src/clipen/skills/builtin/references/graphics.md +6 -5
  61. package/src/clipen/skills/builtin/template-skills/clipen-daily-vlog/SKILL.md +9 -4
  62. package/src/clipen/skills/builtin/template-skills/clipen-event-recap/SKILL.md +10 -5
  63. package/src/clipen/skills/builtin/template-skills/clipen-food-review/SKILL.md +9 -4
  64. package/src/clipen/skills/builtin/template-skills/clipen-product-demo/SKILL.md +10 -6
  65. package/src/clipen/skills/builtin/template-skills/clipen-product-review/SKILL.md +10 -6
  66. package/src/clipen/skills/builtin/template-skills/clipen-product-unboxing/SKILL.md +9 -7
  67. package/src/clipen/skills/builtin/template-skills/clipen-shorts-highlight/SKILL.md +10 -5
  68. package/src/clipen/skills/builtin/template-skills/clipen-travel-highlight/SKILL.md +10 -5
  69. package/src/clipen/skills/builtin/template-skills/clipen-travel-vlog/SKILL.md +10 -7
  70. package/src/clipen/skills/catalog.py +0 -8
  71. package/src/clipen/skills/package.py +1 -10
  72. package/apps/web/dist/assets/index-CJ80KHsQ.css +0 -1
  73. package/apps/web/dist/assets/index-C_4u_hVf.js +0 -16
  74. package/src/clipen/editing/resolve_titles.py +0 -291
  75. package/src/clipen/rendering/program_creator.py +0 -804
  76. package/src/clipen/rendering/program_identities.py +0 -350
  77. package/src/clipen/rendering/program_motion.py +0 -186
  78. package/src/clipen/rendering/program_studio.py +0 -227
  79. package/src/clipen/rendering/program_styles.py +0 -321
  80. package/src/clipen/skills/builtin/components.json +0 -133
@@ -42,14 +42,26 @@ _PRELUDE = """
42
42
  if (node.hasAttribute && node.hasAttribute('data-clipen-text')) apply(node);
43
43
  node.querySelectorAll && node.querySelectorAll('[data-clipen-text]').forEach(apply);
44
44
  };
45
- if (Object.keys(texts).length) {
46
- new MutationObserver((records) => records.forEach((r) => r.addedNodes.forEach(word))).observe(document, { childList: true, subtree: true });
45
+ // A caption design gets the caption's words (emphasis already marked as <em>) and how it is delivered.
46
+ const caption = edits.caption;
47
+ const fill = (node) => {
48
+ if (!caption || node.nodeType !== 1) return;
49
+ const apply = (el) => { if (!el.__clipenSet) { el.innerHTML = caption.html; el.__clipenSet = true; } };
50
+ if (node.hasAttribute && node.hasAttribute('data-clipen-caption')) apply(node);
51
+ node.querySelectorAll && node.querySelectorAll('[data-clipen-caption]').forEach(apply);
52
+ };
53
+ if (Object.keys(texts).length || caption) {
54
+ new MutationObserver((records) => records.forEach((r) => r.addedNodes.forEach((n) => { word(n); fill(n); }))).observe(document, { childList: true, subtree: true });
47
55
  }
48
56
  const paint = () => document.documentElement && Object.entries(colors).forEach(([key, value]) => document.documentElement.style.setProperty('--clipen-' + key, value));
49
57
  // The page is the picture: no default margins, though the page may set its own. The look it uses
50
58
  // (shared fonts and colours as --look-* variables) comes first, so the page's own rules build on it.
51
59
  document.addEventListener('DOMContentLoaded', () => {
52
60
  document.querySelectorAll('[data-clipen-text]').forEach(word);
61
+ document.querySelectorAll('[data-clipen-caption]').forEach(fill);
62
+ // How long the picture shows, so an exit can be timed to its end.
63
+ document.documentElement.style.setProperty('--clipen-duration', (window.clipen.durationFrames / window.clipen.fps) + 's');
64
+ if (caption) document.documentElement.dataset.delivery = caption.delivery;
53
65
  paint();
54
66
  const base = document.createElement('style');
55
67
  base.textContent = ':where(html, body) { margin: 0; padding: 0; background: transparent; }\\n' + __LOOK__;
@@ -173,10 +185,21 @@ def _browser(playwright):
173
185
  PAGE = "https://clipen.local/component.html"
174
186
 
175
187
 
176
- def _route(route, html):
188
+ def _route(route, job):
177
189
  url = route.request.url
178
190
  if url == PAGE:
179
- return route.fulfill(status=200, body=html, headers={"content-type": "text/html; charset=utf-8"})
191
+ return route.fulfill(status=200, body=job["html"], headers={"content-type": "text/html; charset=utf-8"})
192
+ # Fonts the AI fetched by name, from Clipen's own font folder and nowhere else.
193
+ fetched = FONT_ORIGIN + "fetched/"
194
+ if url.startswith(fetched) and job.get("fetched_fonts"):
195
+ base = Path(job["fetched_fonts"]).resolve()
196
+ path = (base / url[len(fetched) :]).resolve()
197
+ if path.is_relative_to(base) and path.is_file() and path.suffix.lower() in {".ttf", ".otf"}:
198
+ return route.fulfill(
199
+ status=200,
200
+ body=path.read_bytes(),
201
+ headers={"content-type": "font/ttf", "access-control-allow-origin": "*"},
202
+ )
180
203
  if url.startswith(FONT_ORIGIN) and url[len(FONT_ORIGIN) :] in FONTS:
181
204
  path = Path(str(files("clipen.rendering").joinpath("fonts", url[len(FONT_ORIGIN) :])))
182
205
  return route.fulfill(
@@ -186,11 +209,10 @@ def _route(route, html):
186
209
 
187
210
 
188
211
  def render(job):
189
- from playwright.sync_api import Error, TimeoutError, sync_playwright
212
+ """One page, or with "pages" many pages of the same design (one per caption) in one Chrome run."""
213
+ from playwright.sync_api import sync_playwright
190
214
 
191
- out = Path(job["out"])
192
- width, height, fps = int(job["width"]), int(job["height"]), float(job["fps"])
193
- info = {"width": width, "height": height, "fps": fps, "durationFrames": int(job["duration"])}
215
+ width, height = int(job["width"]), int(job["height"])
194
216
  with sync_playwright() as playwright:
195
217
  browser = _browser(playwright)
196
218
  try:
@@ -202,56 +224,70 @@ def render(job):
202
224
  offline=False,
203
225
  service_workers="block",
204
226
  )
205
- context.route("**/*", lambda route: _route(route, job["html"]))
206
- page = context.new_page()
207
- page.set_default_timeout(float(job.get("frame_timeout", 10)) * 1000)
208
- problems = []
209
- page.on("pageerror", lambda error: problems.append(str(error)))
210
- page.add_init_script(
211
- _PRELUDE.replace("__INFO__", json.dumps(info))
212
- .replace("__EDITS__", json.dumps(job.get("edits") or {}, ensure_ascii=False))
213
- .replace("__LOOK__", json.dumps(job.get("look") or "", ensure_ascii=False))
214
- )
215
- try:
216
- page.goto(PAGE, wait_until="load")
217
- page.evaluate("document.fonts.ready.then(() => true)")
218
- # A picture the sealed page could not fetch is hidden instead of drawn as a broken icon.
219
- page.evaluate(
220
- "document.querySelectorAll('img').forEach((i) => { if (!i.complete || !i.naturalWidth) i.style.visibility = 'hidden' })"
221
- )
222
- except TimeoutError:
223
- fail("custom_component_load_timeout")
224
- except Error as error:
225
- fail("custom_component_load_failed", str(error))
226
- if job.get("describe"):
227
- (out / "fields.json").write_text(
228
- json.dumps(page.evaluate(_FIELDS), ensure_ascii=False), encoding="utf-8"
229
- )
230
- if job["frames"]:
231
- try:
232
- one_face_per_role(page, job.get("faces"), int(job["duration"]), fps)
233
- except TimeoutError:
234
- fail("custom_component_frame_timeout", "faces")
235
- except Error as error:
236
- fail("custom_component_script_error", problems[0] if problems else str(error))
237
- for frame in job["frames"]:
238
- try:
239
- page.evaluate(_SEEK, [int(frame), fps])
240
- if problems:
241
- fail("custom_component_script_error", problems[0])
242
- data = page.screenshot(omit_background=True, type="png", animations="allow")
243
- except TimeoutError:
244
- fail("custom_component_frame_timeout", f"frame {frame}")
245
- except Error as error:
246
- fail("custom_component_script_error", problems[0] if problems else str(error))
247
- target = out / f"f{int(frame):05d}.png"
248
- temporary = target.with_suffix(".part")
249
- temporary.write_bytes(data)
250
- os.replace(temporary, target)
227
+ context.route("**/*", lambda route: _route(route, job))
228
+ for one in job.get("pages") or [job]:
229
+ _draw_page(context, job, one)
251
230
  finally:
252
231
  browser.close()
253
232
 
254
233
 
234
+ def _draw_page(context, job, one):
235
+ from playwright.sync_api import Error, TimeoutError
236
+
237
+ out = Path(one["out"])
238
+ fps = float(job["fps"])
239
+ info = {
240
+ "width": int(job["width"]),
241
+ "height": int(job["height"]),
242
+ "fps": fps,
243
+ "durationFrames": int(one["duration"]),
244
+ }
245
+ page = context.new_page()
246
+ page.set_default_timeout(float(job.get("frame_timeout", 10)) * 1000)
247
+ problems = []
248
+ page.on("pageerror", lambda error: problems.append(str(error)))
249
+ page.add_init_script(
250
+ _PRELUDE.replace("__INFO__", json.dumps(info))
251
+ .replace("__EDITS__", json.dumps(one.get("edits") or {}, ensure_ascii=False))
252
+ .replace("__LOOK__", json.dumps(job.get("look") or "", ensure_ascii=False))
253
+ )
254
+ try:
255
+ page.goto(PAGE, wait_until="load")
256
+ page.evaluate("document.fonts.ready.then(() => true)")
257
+ # A picture the sealed page could not fetch is hidden instead of drawn as a broken icon.
258
+ page.evaluate(
259
+ "document.querySelectorAll('img').forEach((i) => { if (!i.complete || !i.naturalWidth) i.style.visibility = 'hidden' })"
260
+ )
261
+ except TimeoutError:
262
+ fail("custom_component_load_timeout")
263
+ except Error as error:
264
+ fail("custom_component_load_failed", str(error))
265
+ if one.get("describe"):
266
+ (out / "fields.json").write_text(json.dumps(page.evaluate(_FIELDS), ensure_ascii=False), encoding="utf-8")
267
+ if one["frames"]:
268
+ try:
269
+ one_face_per_role(page, one.get("faces"), int(one["duration"]), fps)
270
+ except TimeoutError:
271
+ fail("custom_component_frame_timeout", "faces")
272
+ except Error as error:
273
+ fail("custom_component_script_error", problems[0] if problems else str(error))
274
+ for frame in one["frames"]:
275
+ try:
276
+ page.evaluate(_SEEK, [int(frame), fps])
277
+ if problems:
278
+ fail("custom_component_script_error", problems[0])
279
+ data = page.screenshot(omit_background=True, type="png", animations="allow")
280
+ except TimeoutError:
281
+ fail("custom_component_frame_timeout", f"frame {frame}")
282
+ except Error as error:
283
+ fail("custom_component_script_error", problems[0] if problems else str(error))
284
+ target = out / f"f{int(frame):05d}.png"
285
+ temporary = target.with_suffix(".part")
286
+ temporary.write_bytes(data)
287
+ os.replace(temporary, target)
288
+ page.close()
289
+
290
+
255
291
  if __name__ == "__main__":
256
292
  try:
257
293
  render(json.load(sys.stdin))
@@ -0,0 +1,127 @@
1
+ """Open fonts the AI asks for by name: fetched once from Google Fonts and kept on this Mac.
2
+
3
+ Pages stay offline: Clipen downloads the font file itself, checks it is openly licensed
4
+ (OFL, Apache or UFL, which allow it in a film), and serves it to the page from
5
+ https://clipen.local/fonts/fetched/<folder>/<file> like the fonts it carries.
6
+ """
7
+
8
+ import json
9
+ import os
10
+ import re
11
+ import urllib.error
12
+ import urllib.request
13
+ from pathlib import Path
14
+
15
+ SOURCE = "https://raw.githubusercontent.com/google/fonts/main"
16
+ LICENSES = {"ofl": "OFL-1.1", "apache": "Apache-2.0", "ufl": "UFL-1.0"}
17
+ MAX_FONT_BYTES = 40_000_000
18
+
19
+
20
+ class FontUnavailable(RuntimeError):
21
+ pass
22
+
23
+
24
+ def root():
25
+ configured = os.environ.get("CLIPEN_FONT_CACHE")
26
+ if configured:
27
+ return Path(configured)
28
+ from clipen.bootstrap import clipen_data_root
29
+
30
+ return clipen_data_root() / "fonts"
31
+
32
+
33
+ def folder_name(family):
34
+ return re.sub(r"[^a-z0-9]", "", family.lower())
35
+
36
+
37
+ def available():
38
+ """Fonts fetched so far, by family: {"path": "<folder>/<file>", "license": ...}."""
39
+ found = {}
40
+ base = root()
41
+ if not base.is_dir():
42
+ return found
43
+ for record in sorted(base.glob("*/font.json")):
44
+ try:
45
+ entry = json.loads(record.read_text(encoding="utf-8"))
46
+ except (OSError, ValueError):
47
+ continue
48
+ if (base / entry.get("path", "")).is_file():
49
+ found[entry["family"]] = entry
50
+ return found
51
+
52
+
53
+ def _get(url, urlopen):
54
+ try:
55
+ with urlopen(url, timeout=30) as response:
56
+ return response.read(MAX_FONT_BYTES + 1)
57
+ except urllib.error.HTTPError as error:
58
+ if error.code == 404:
59
+ return None
60
+ raise FontUnavailable(f"下載字型失敗(HTTP {error.code})") from error
61
+ except (urllib.error.URLError, TimeoutError, OSError) as error:
62
+ raise FontUnavailable("連不上 Google Fonts,請確認網路後再試。") from error
63
+
64
+
65
+ def _metadata(text):
66
+ """The family name and its font files from a METADATA.pb, without a protobuf parser."""
67
+ name = re.search(r'^name: "([^"]+)"', text, re.MULTILINE)
68
+ files = []
69
+ for block in re.findall(r"fonts \{(.*?)\}", text, re.DOTALL):
70
+ filename = re.search(r'filename: "([^"]+)"', block)
71
+ if filename:
72
+ style = re.search(r'style: "([^"]+)"', block)
73
+ weight = re.search(r"weight: (\d+)", block)
74
+ files.append(
75
+ (filename.group(1), style.group(1) if style else "normal", int(weight.group(1)) if weight else 400)
76
+ )
77
+ return (name.group(1) if name else None), files
78
+
79
+
80
+ def fetch(family, urlopen=urllib.request.urlopen):
81
+ """Fetch one open font family (its upright face) and return its entry, or raise FontUnavailable."""
82
+ family = family.strip()
83
+ folder = folder_name(family)
84
+ if not folder:
85
+ raise FontUnavailable("字型名稱不正確。")
86
+ known = available()
87
+ if family in known:
88
+ return known[family]
89
+ for directory, license_name in LICENSES.items():
90
+ page = _get(f"{SOURCE}/{directory}/{folder}/METADATA.pb", urlopen)
91
+ if page is None:
92
+ continue
93
+ name, files = _metadata(page.decode("utf-8", "replace"))
94
+ upright = [f for f in files if f[1] == "normal"] or files
95
+ if not name or not upright:
96
+ break
97
+ # A variable font carries every weight; otherwise the regular weight.
98
+ chosen = next((f for f in upright if "[" in f[0]), None) or min(upright, key=lambda f: abs(f[2] - 400))
99
+ data = _get(f"{SOURCE}/{directory}/{folder}/{chosen[0]}", urlopen)
100
+ if not data or len(data) > MAX_FONT_BYTES:
101
+ raise FontUnavailable("字型檔案太大或無法下載。")
102
+ target = root() / folder
103
+ target.mkdir(parents=True, exist_ok=True)
104
+ (target / ".part").write_bytes(data)
105
+ os.replace(target / ".part", target / chosen[0])
106
+ entry = {
107
+ "family": name,
108
+ "path": f"{folder}/{chosen[0]}",
109
+ "license": license_name,
110
+ "variable": "[" in chosen[0],
111
+ "source": f"https://fonts.google.com/specimen/{name.replace(' ', '+')}",
112
+ }
113
+ (target / "font.json").write_text(json.dumps(entry, ensure_ascii=False), encoding="utf-8")
114
+ return entry
115
+ raise FontUnavailable(
116
+ f"Google Fonts 找不到開源授權的「{family}」,請確認名稱(例如 Noto Serif TC、LXGW WenKai TC)。"
117
+ )
118
+
119
+
120
+ def faces_css():
121
+ """@font-face rules for every fetched font, as pages load them."""
122
+ return "".join(
123
+ f'@font-face {{ font-family: "{family}"; src: url(https://clipen.local/fonts/fetched/{entry["path"]});'
124
+ + (" font-weight: 1 1000;" if entry.get("variable") else "")
125
+ + " }\n"
126
+ for family, entry in available().items()
127
+ )
@@ -46,13 +46,35 @@ def mosaic_filters(filters, label, item, timeline, index):
46
46
 
47
47
 
48
48
  def grade_filters(item):
49
+ """The clip's colour grade as FFmpeg filters: exposure and contrast, colour temperature and tint,
50
+ shadow and highlight curves, vignette and film grain; each part only when it is set."""
49
51
  grade = next((e.parameters for e in item.effects if e.effect_id == "video.grade"), None)
50
52
  if grade is None:
51
53
  return ""
52
54
  values = (float(grade["contrast"]), float(grade["saturation"]), float(grade["brightness"]))
53
- if not (0.5 <= values[0] <= 2 and 0 <= values[1] <= 2 and -0.3 <= values[2] <= 0.3):
55
+ gamma = float(grade.get("gamma", 1))
56
+ extra = {k: float(grade.get(k, 0)) for k in ("temperature", "tint", "shadows", "highlights", "vignette", "grain")}
57
+ if not (
58
+ 0.5 <= values[0] <= 2
59
+ and 0 <= values[1] <= 2
60
+ and -0.3 <= values[2] <= 0.3
61
+ and 0.5 <= gamma <= 2
62
+ and all(-1 <= extra[k] <= 1 for k in ("temperature", "tint", "shadows", "highlights"))
63
+ and all(0 <= extra[k] <= 1 for k in ("vignette", "grain"))
64
+ ):
54
65
  raise ValueError("invalid grade")
55
- return f",eq=contrast={values[0]:.6f}:saturation={values[1]:.6f}:brightness={values[2]:.6f}"
66
+ result = f",eq=contrast={values[0]:.6f}:saturation={values[1]:.6f}:brightness={values[2]:.6f}:gamma={gamma:.6f}"
67
+ if extra["temperature"] or extra["tint"]:
68
+ warm, green = extra["temperature"] * 0.18, extra["tint"] * 0.18
69
+ result += f",colorbalance=rm={warm:.4f}:gm={-green:.4f}:bm={-warm:.4f}"
70
+ if extra["shadows"] or extra["highlights"]:
71
+ low, high = 0.25 + 0.12 * extra["shadows"], 0.75 + 0.12 * extra["highlights"]
72
+ result += f",curves=all='0/0 0.25/{low:.4f} 0.75/{high:.4f} 1/1'"
73
+ if extra["vignette"]:
74
+ result += f",vignette=a={0.15 + 0.6 * extra['vignette']:.4f}"
75
+ if extra["grain"]:
76
+ result += f",noise=alls={round(40 * extra['grain'])}:allf=t"
77
+ return result
56
78
 
57
79
 
58
80
  def transition_filters(item, following, timeline):
@@ -1,254 +1,32 @@
1
- """Deterministic in-picture graphics for versioned programme skill packages."""
1
+ """In-picture graphics: every one is a web page the AI designed, drawn by custom_components.
2
2
 
3
- import math
3
+ Graphics older films made with the retired built-in templates are no longer drawn; the AI or the
4
+ person can remove them, and the AI designs a new one in their place."""
4
5
 
5
- from PIL import Image, ImageDraw
6
-
7
- from . import custom_components, program_creator, program_identities
8
- from .program_motion import FAMILIES, draw_motion_graphic, layout, motion_frames
9
- from .program_styles import draw_styled_graphic, load_style_font, skin, style_font, styled_text_length, type_outline
10
- from .titles import TitleRenderError
6
+ from . import custom_components
11
7
 
12
8
 
13
9
  def animation_boundaries(item, profile, timeline=None, cancel=None):
14
- if custom_components.is_custom(profile):
15
- # A free design can change on any frame; the frames themselves say where.
16
- return (
17
- custom_components.changes(timeline, item, profile, cancel)
18
- if timeline is not None
19
- else set(range(item.start_frame, item.start_frame + item.duration_frames + 1))
20
- )
21
- motion = profile["presets"]["motion"]
22
- if program_creator.is_creator(profile):
23
- entry_length, exit_length = program_creator.frames(profile)
24
- else:
25
- entry_length, exit_length = (
26
- motion_frames(profile["component_id"], profile)
27
- if profile["component_id"] in FAMILIES
28
- else (motion["entry_frames"], motion["exit_frames"])
29
- )
30
- entry = min(entry_length, item.duration_frames)
31
- exit_frames = min(exit_length, item.duration_frames)
32
- return {
33
- item.start_frame + n
34
- for n in (*range(entry + 1), *range(item.duration_frames - exit_frames, item.duration_frames + 1))
35
- }
36
-
37
-
38
- def _bounds(draw, font_path, timeline, item, profile):
39
- if program_creator.is_creator(profile):
40
- return program_creator.layout(draw, font_path, timeline, item, profile)
41
- if program_identities.identity(profile):
42
- return program_identities.layout(draw, font_path, timeline, item, profile)
43
- if profile["component_id"] in FAMILIES:
44
- return layout(draw, font_path, timeline, item, profile)
45
- if skin(profile) == "studio":
46
- from .program_studio import layout as studio_layout
47
-
48
- return studio_layout(draw, font_path, timeline, item, profile)
49
- font_path = style_font(font_path, profile)
50
- typography = profile["presets"].get("typography", {})
51
- scale = (
52
- typography.get("reaction", 0.064)
53
- if profile["component_id"] == "reaction"
54
- else typography.get("component_primary", 0.038)
55
- )
56
- font = load_style_font(font_path, max(14, round(timeline.height * scale)), profile)
57
- primary, _, detail = item.text.partition("\n")
58
- detail_font = load_style_font(
59
- font_path, max(12, round(timeline.height * typography.get("component_detail", 0.024))), profile, role="detail"
60
- )
61
- width = max(styled_text_length(primary, font), styled_text_length(detail, detail_font) if detail else 0)
62
- pad = max(8, round(timeline.height * 0.016))
63
- x, y = round(timeline.width * profile["x"]), round(timeline.height * profile["y"])
64
- box_width = max(math.ceil(width) + pad * 2, round(timeline.width * 0.15))
65
- box_height = round(timeline.height * scale * 1.65) + pad
66
- if profile["component_id"] != "reaction":
67
- box_height += round(timeline.height * 0.025)
68
- if detail:
69
- box_height += round(timeline.height * 0.038)
70
- if (
71
- box_width > timeline.width * 0.58
72
- or x + box_width > timeline.width * 0.95
73
- or y + box_height > timeline.height * 0.77
74
- ):
75
- raise TitleRenderError("program_component_overflow")
76
- return (x, y, x + box_width, y + box_height), font, pad
77
-
78
-
79
- def _draw(draw, font_path, timeline, item, profile, relative_frame=None):
80
- if program_creator.is_creator(profile):
81
- return program_creator.draw_graphic(draw, font_path, timeline, item, profile, relative_frame)
82
- identity = program_identities.identity(profile)
83
- if profile["component_id"] in FAMILIES and not identity:
84
- return draw_motion_graphic(draw, font_path, timeline, item, profile, relative_frame)
85
- bounds, font, pad = _bounds(draw, font_path, timeline, item, profile)
86
- motion = profile["presets"]["motion"]
87
- relative = motion["entry_frames"] if relative_frame is None else relative_frame
88
- entering = min(1.0, max(0.0, (relative + 1) / motion["entry_frames"]))
89
- leaving = min(1.0, (item.duration_frames - relative) / motion["exit_frames"])
90
- opacity = min(entering, leaving)
91
- eased = 1 - (1 - entering) ** 3
92
- dx = round((1 - eased) * timeline.width * motion["entry_distance_ratio"])
93
- x, y, right, bottom = bounds
94
- x -= dx
95
- right -= dx
96
- palette = profile["presets"]["palette"]
97
-
98
- def color(name):
99
- r, g, b, a = palette[name]
100
- return (r, g, b, round(a * opacity))
101
-
102
- kind = profile["component_id"]
103
- primary, _, detail = item.text.partition("\n")
104
- stroke = max(2, round(timeline.height * 0.004))
105
- if identity:
106
- program_identities.draw_graphic(draw, font_path, timeline, item, profile, bounds, font, pad, relative_frame)
107
- elif skin(profile) != "variety":
108
- draw_styled_graphic(draw, font_path, timeline, item, profile, bounds, font, pad, relative_frame)
109
- elif kind == "reaction":
110
- draw.text(
111
- (x + pad, y + pad // 2),
112
- primary,
113
- font=font,
114
- fill=color("accent"),
115
- stroke_width=type_outline(profile, font, stroke * 2),
116
- stroke_fill=color("ink"),
117
- )
118
- if detail:
119
- detail_font = load_style_font(font_path, max(12, round(timeline.height * 0.024)), profile, role="detail")
120
- draw.text(
121
- (x + pad, y + pad + round(timeline.height * 0.075)),
122
- detail,
123
- font=detail_font,
124
- fill=color("paper"),
125
- stroke_width=stroke,
126
- stroke_fill=color("ink"),
127
- )
128
- # A short pair of ticks gives an actual reaction a shared programme
129
- # accent without turning every dialogue line into a reaction graphic.
130
- draw.line((x - pad // 2, y + pad, x - pad, y - pad // 2), fill=color("accent"), width=stroke)
131
- draw.line((right + pad // 2, y + pad, right + pad, y - pad // 2), fill=color("accent"), width=stroke)
132
- else:
133
- # Narrow editorial labels sit inside the footage, with no full-screen
134
- # background. A shared accent edge and typography form programme identity.
135
- draw.rectangle((x + 3, y + 4, right + 3, bottom + 4), fill=(0, 0, 0, round(75 * opacity)))
136
- draw.rectangle((x, y, right, bottom), fill=color("ink"))
137
- draw.rectangle((x, y, x + stroke * 2, bottom), fill=color("secondary" if kind == "person" else "accent"))
138
- typography = profile["presets"].get("typography", {})
139
- kicker_font = load_style_font(
140
- font_path,
141
- max(10, round(timeline.height * typography.get("component_kicker", 0.017))),
142
- profile,
143
- role="detail",
144
- )
145
- kicker = (
146
- profile.get("eyebrow")
147
- or {"location": "現場", "person": "人物", "fact": "資訊", "pointer": "看這裡", "circle": "細節"}[kind]
148
- )
149
- draw.text(
150
- (x + pad, y + pad // 2), kicker, font=kicker_font, fill=color("secondary" if kind == "person" else "accent")
151
- )
152
- primary_y = y + pad // 2 + round(timeline.height * 0.027)
153
- draw.text((x + pad, primary_y), primary, font=font, fill=color("paper"))
154
- if detail:
155
- detail_font = load_style_font(
156
- font_path,
157
- max(12, round(timeline.height * typography.get("component_detail", 0.024))),
158
- profile,
159
- role="detail",
160
- )
161
- draw.text(
162
- (x + pad, primary_y + round(timeline.height * 0.052)), detail, font=detail_font, fill=color("paper")
163
- )
164
- draw.line(
165
- (x + pad, bottom - pad // 2, right - pad, bottom - pad // 2),
166
- fill=color("accent"),
167
- width=max(1, stroke // 2),
168
- )
169
- if kind not in {"pointer", "circle"}:
170
- return bounds
171
- target = profile["target"]
172
- tx, ty = target["x"] * timeline.width, target["y"] * timeline.height
173
- radius = target["radius"] * min(timeline.width, timeline.height)
174
- if kind == "circle":
175
- rect = (tx - radius, ty - radius, tx + radius, ty + radius)
176
- draw.arc(rect, -90, -90 + max(2, round(360 * eased)), fill=color("accent"), width=stroke * 2)
177
- else:
178
- origin = (right, (y + bottom) / 2)
179
- angle = math.atan2(ty - origin[1], tx - origin[0])
180
- tip = (origin[0] + (tx - origin[0]) * eased, origin[1] + (ty - origin[1]) * eased)
181
- draw.line((origin, tip), fill=color("ink"), width=stroke * 3)
182
- draw.line((origin, tip), fill=color("accent"), width=stroke)
183
- size = max(9, timeline.height * 0.025)
184
- points = [
185
- tip,
186
- (tip[0] - size * math.cos(angle - 0.45), tip[1] - size * math.sin(angle - 0.45)),
187
- (tip[0] - size * math.cos(angle + 0.45), tip[1] - size * math.sin(angle + 0.45)),
188
- ]
189
- draw.polygon(points, fill=color("accent"))
190
- return bounds
191
-
192
-
193
- class _Canvas:
194
- """A timeline seen at another size, so every style's own proportions scale with it."""
195
-
196
- def __init__(self, timeline, width, height):
197
- self._timeline, self.width, self.height = timeline, width, height
198
-
199
- def __getattr__(self, name):
200
- return getattr(self._timeline, name)
201
-
202
-
203
- def _scaled(timeline, profile):
204
- """For a graphic a person resized: a larger or smaller canvas to draw it on, and where to place
205
- that canvas so the graphic keeps its top-left corner. None at its designed size."""
206
- scale = profile.get("scale", 1)
207
- if scale == 1:
208
- return None
209
- canvas = _Canvas(timeline, max(2, round(timeline.width * scale)), max(2, round(timeline.height * scale)))
210
- return canvas, (
211
- round(timeline.width * profile["x"]) - round(canvas.width * profile["x"]),
212
- round(timeline.height * profile["y"]) - round(canvas.height * profile["y"]),
10
+ if not custom_components.is_custom(profile):
11
+ return {item.start_frame, item.start_frame + item.duration_frames}
12
+ # A free design can change on any frame; the frames themselves say where.
13
+ return (
14
+ custom_components.changes(timeline, item, profile, cancel)
15
+ if timeline is not None
16
+ else set(range(item.start_frame, item.start_frame + item.duration_frames + 1))
213
17
  )
214
18
 
215
19
 
216
20
  def component_bounds(draw, font_path, timeline, item, profile):
217
- """The graphic's box on the picture, after any size a person chose."""
218
- if custom_components.is_custom(profile):
219
- box = custom_components.bounds(timeline, item, profile)
220
- dx, dy = round(profile.get("x", 0) * timeline.width), round(profile.get("y", 0) * timeline.height)
221
- return (box or (dx, dy, dx, dy)), None, 0
222
- scaled = _scaled(timeline, profile)
223
- if scaled is None:
224
- return _bounds(draw, font_path, timeline, item, profile)
225
- canvas, (dx, dy) = scaled
226
- (left, top, right, bottom), font, pad = _bounds(draw, font_path, canvas, item, profile)
227
- box = (left + dx, top + dy, right + dx, bottom + dy)
228
- # Enlarged, it must still clear the picture's edge and the subtitles at the bottom.
229
- if box[0] < 0 or box[1] < 0 or box[2] > timeline.width * 0.97 or box[3] > timeline.height * 0.8:
230
- raise TitleRenderError("program_component_overflow")
231
- return box, font, pad
21
+ """The graphic's box on the picture, or None for a retired built-in one that draws nothing."""
22
+ if not custom_components.is_custom(profile):
23
+ return None, None, 0
24
+ box = custom_components.bounds(timeline, item, profile)
25
+ dx, dy = round(profile.get("x", 0) * timeline.width), round(profile.get("y", 0) * timeline.height)
26
+ return (box or (dx, dy, dx, dy)), None, 0
232
27
 
233
28
 
234
29
  def draw_program_component(draw, font_path, timeline, item, profile, relative_frame=None):
235
30
  if custom_components.is_custom(profile):
236
31
  return custom_components.draw(draw, timeline, item, profile, relative_frame)
237
- scaled = _scaled(timeline, profile)
238
- if scaled is None:
239
- return _draw(draw, font_path, timeline, item, profile, relative_frame)
240
- canvas, (dx, dy) = scaled
241
- component_bounds(draw, font_path, timeline, item, profile)
242
- # Drawn at its new size on a canvas of its own, so type stays sharp instead of being resampled.
243
- layer = Image.new("RGBA", (canvas.width, canvas.height), (0, 0, 0, 0))
244
- result = _draw(ImageDraw.Draw(layer), font_path, canvas, item, profile, relative_frame)
245
- target = draw._image
246
- sx, sy, tx, ty = max(0, -dx), max(0, -dy), max(0, dx), max(0, dy)
247
- width, height = min(layer.width - sx, target.width - tx), min(layer.height - sy, target.height - ty)
248
- if width > 0 and height > 0:
249
- piece = layer.crop((sx, sy, sx + width, sy + height))
250
- if target.mode == "RGBA":
251
- target.alpha_composite(piece, (tx, ty))
252
- else:
253
- target.paste(piece, (tx, ty), piece)
254
- return result
32
+ return None