@clipen/clipen-cli 1.0.5 → 1.0.7

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.
@@ -6,9 +6,12 @@ disk by content, and composited like any other programme graphic, so the
6
6
  preview, the film and the Resolve export show the same picture.
7
7
  """
8
8
 
9
+ import functools
9
10
  import hashlib
10
11
  import json
11
12
  import os
13
+ import re
14
+ import struct
12
15
  import subprocess
13
16
  import sys
14
17
  import tempfile
@@ -109,10 +112,106 @@ FALLBACKS = {
109
112
  }
110
113
 
111
114
 
115
+ def _chain(family):
116
+ return list(dict.fromkeys([family, *FALLBACKS.get(family, []), "PingFang TC"]))
117
+
118
+
119
+ def _stack(chain):
120
+ return ", ".join(f'"{name}"' for name in chain) + ", sans-serif"
121
+
122
+
112
123
  def font_stack(family):
113
124
  """The CSS font list for a typeface: itself, faces of the same feel for missing characters, then PingFang."""
114
- chain = [family, *FALLBACKS.get(family, []), "PingFang TC"]
115
- return ", ".join(f'"{name}"' for name in dict.fromkeys(chain)) + ", sans-serif"
125
+ return _stack(_chain(family))
126
+
127
+
128
+ # Chinese, Japanese kana and half-width kana: where faces of one feel still differ from one another.
129
+ _CJK = re.compile("[぀-ヿㇰ-ㇿ㐀-䶿一-鿿豈-﫿ヲ-゚]")
130
+
131
+
132
+ @functools.lru_cache(maxsize=None)
133
+ def covered(family):
134
+ """The characters a carried font draws, read from its cmap table."""
135
+ from importlib.resources import files
136
+
137
+ data = files("clipen.rendering").joinpath("fonts", BUNDLED[family]["file"]).read_bytes()
138
+ tables = {
139
+ data[12 + 16 * i : 16 + 16 * i]: struct.unpack(">I", data[20 + 16 * i : 24 + 16 * i])[0]
140
+ for i in range(struct.unpack(">H", data[4:6])[0])
141
+ }
142
+ cmap = tables[b"cmap"]
143
+ subtables = {}
144
+ for i in range(struct.unpack(">H", data[cmap + 2 : cmap + 4])[0]):
145
+ platform, encoding, offset = struct.unpack(">HHI", data[cmap + 4 + 8 * i : cmap + 12 + 8 * i])
146
+ subtables[(platform, encoding)] = cmap + offset
147
+ points = set()
148
+ full = subtables.get((3, 10)) or subtables.get((0, 4)) or subtables.get((0, 6))
149
+ if full is not None and struct.unpack(">H", data[full : full + 2])[0] == 12:
150
+ for g in range(struct.unpack(">I", data[full + 12 : full + 16])[0]):
151
+ first, last, _ = struct.unpack(">III", data[full + 16 + 12 * g : full + 28 + 12 * g])
152
+ points.update(range(first, last + 1))
153
+ return frozenset(points)
154
+ base = subtables.get((3, 1)) or subtables.get((0, 3))
155
+ if base is None or struct.unpack(">H", data[base : base + 2])[0] != 4:
156
+ return frozenset()
157
+ segments = struct.unpack(">H", data[base + 6 : base + 8])[0] // 2
158
+ ends = base + 14
159
+ starts, deltas, ranges = ends + 2 * segments + 2, ends + 4 * segments + 2, ends + 6 * segments + 2
160
+
161
+ def word(at):
162
+ return struct.unpack(">H", data[at : at + 2])[0]
163
+
164
+ for s in range(segments):
165
+ first, last, delta, offset = (
166
+ word(starts + 2 * s),
167
+ word(ends + 2 * s),
168
+ word(deltas + 2 * s),
169
+ word(ranges + 2 * s),
170
+ )
171
+ for point in range(first, min(last, 0xFFFE) + 1):
172
+ if offset:
173
+ glyph = word(ranges + 2 * s + offset + 2 * (point - first))
174
+ glyph = (glyph + delta) & 0xFFFF if glyph else 0
175
+ else:
176
+ glyph = (point + delta) & 0xFFFF
177
+ if glyph:
178
+ points.add(point)
179
+ return frozenset(points)
180
+
181
+
182
+ def face_plan(profile):
183
+ """Per look font role: the carried faces of its chain that lack Chinese or Japanese characters the page holds."""
184
+ look = profile.get("look")
185
+ if not look:
186
+ return []
187
+ words = "".join(str(v) for v in (_edits(profile).get("texts") or {}).values())
188
+ needed = set(_CJK.findall(profile["html"] + words))
189
+ if not needed:
190
+ return []
191
+ plan = []
192
+ for font in look["fonts"]:
193
+ chain = _chain(font["family"])
194
+ missing = {f: "".join(sorted(c for c in needed if ord(c) not in covered(f))) for f in chain if f in BUNDLED}
195
+ plan.append({"key": font["key"], "chain": chain, "missing": missing})
196
+ return plan
197
+
198
+
199
+ def one_face(role, shown):
200
+ """The stack that draws every Chinese or Japanese character a role shows in one face, or None when its own does.
201
+
202
+ Letting each missing character fall to the next face mixes two hands in one word (七里ヶ浜 in two styles);
203
+ instead the role moves to the first face of the same feel that has them all. Faces that draw none of
204
+ those characters, such as a Latin display face, stay first for the Latin letters. Fonts Mac carries
205
+ are taken to draw them all."""
206
+ chars = set(_CJK.findall("".join(shown)))
207
+ lacks = {face: chars & set(role["missing"].get(face, "")) for face in role["chain"]}
208
+ if not chars or not lacks[role["chain"][0]]:
209
+ return None
210
+ for index, face in enumerate(role["chain"]):
211
+ if not lacks[face]:
212
+ kept = [f for f in role["chain"][:index] if lacks[f] == chars]
213
+ return _stack(kept + role["chain"][index:])
214
+ return None
116
215
 
117
216
 
118
217
  def look_css(look):
@@ -142,6 +241,8 @@ def _key(profile, timeline, duration):
142
241
  duration,
143
242
  _edits(profile),
144
243
  look_css(profile.get("look")),
244
+ # Bumped when the way a role picks one face changes, so old frames are drawn again.
245
+ "one-face-1",
145
246
  ],
146
247
  ensure_ascii=False,
147
248
  sort_keys=True,
@@ -182,6 +283,7 @@ def frames(timeline, item, profile, wanted, cancel=None):
182
283
  "frame_timeout": FRAME_TIMEOUT_SECONDS,
183
284
  "edits": _edits(profile),
184
285
  "look": look_css(profile.get("look")),
286
+ "faces": face_plan(profile),
185
287
  }
186
288
  _run(job, timeout=30 + FRAME_TIMEOUT_SECONDS + len(missing) * 1.5, cancel=cancel)
187
289
  return paths
@@ -103,6 +103,44 @@ _FIELDS = """
103
103
  }
104
104
  """
105
105
 
106
+ # The words each typeface is asked to draw right now, keyed by the face asked for first.
107
+ _SHOWN = """
108
+ () => {
109
+ const shown = {};
110
+ document.querySelectorAll('body *').forEach((el) => {
111
+ const own = Array.from(el.childNodes).filter((n) => n.nodeType === 3).map((n) => n.textContent).join('').trim();
112
+ if (!own) return;
113
+ const first = getComputedStyle(el).fontFamily.split(',')[0].trim().replace(/^["']|["']$/g, '');
114
+ shown[first] = (shown[first] || '') + own;
115
+ });
116
+ return shown;
117
+ }
118
+ """
119
+
120
+
121
+ def one_face_per_role(page, plan, duration, fps):
122
+ """Give each look role one face for the Chinese and Japanese it shows anywhere in the graphic, before drawing.
123
+
124
+ Text a page writes over time is read at a few fixed moments, so every run of the same graphic decides alike."""
125
+ from clipen.rendering.custom_components import one_face
126
+
127
+ if not plan:
128
+ return
129
+ shown = {}
130
+ for frame in sorted({0, duration // 4, duration // 2, duration * 3 // 4, duration - 1}):
131
+ page.evaluate(_SEEK, [frame, fps])
132
+ for family, words in page.evaluate(_SHOWN).items():
133
+ shown.setdefault(family, []).append(words)
134
+ stacks = {role["key"]: one_face(role, shown.get(role["chain"][0], [])) for role in plan}
135
+ stacks = {key: stack for key, stack in stacks.items() if stack}
136
+ if stacks:
137
+ page.evaluate(
138
+ "(stacks) => Object.entries(stacks).forEach(([key, stack]) =>"
139
+ " document.documentElement.style.setProperty('--look-font-' + key, stack))",
140
+ stacks,
141
+ )
142
+
143
+
106
144
  _SEEK = """
107
145
  async ([frame, fps]) => {
108
146
  const ms = frame / fps * 1000;
@@ -189,6 +227,13 @@ def render(job):
189
227
  (out / "fields.json").write_text(
190
228
  json.dumps(page.evaluate(_FIELDS), ensure_ascii=False), encoding="utf-8"
191
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))
192
237
  for frame in job["frames"]:
193
238
  try:
194
239
  page.evaluate(_SEEK, [int(frame), fps])
@@ -52,6 +52,8 @@ class FfmpegPreviewRenderer:
52
52
  if isinstance(i, MediaClip)
53
53
  for e in i.effects
54
54
  )
55
+ from .stage import set_stage
56
+
55
57
  if not layers:
56
58
  return self._render_base(project_id, timeline, output, cancel, progress)
57
59
  from clipen.editing.production_media import mix_audio_layers
@@ -60,6 +62,7 @@ class FfmpegPreviewRenderer:
60
62
  with tempfile.TemporaryDirectory(prefix=".agent-mix-", dir=output.parent) as temp:
61
63
  base = Path(temp) / "camera.mp4"
62
64
  self._render_base(project_id, timeline, base, cancel, lambda p: progress(p * 0.85))
65
+ set_stage("混合配樂與原音")
63
66
  mix_audio_layers(self.media, project_id, timeline, base, output, cancel)
64
67
  progress(1.0)
65
68
 
@@ -167,6 +170,9 @@ class FfmpegPreviewRenderer:
167
170
  return output
168
171
 
169
172
  def _render_media(self, project_id, timeline, output, cancel, progress, *, preserve_audio_gain=False):
173
+ from .stage import set_stage
174
+
175
+ set_stage("剪接畫面與聲音")
170
176
  try:
171
177
  return self._render_media_once(
172
178
  project_id, timeline, output, cancel, progress, preserve_audio_gain=preserve_audio_gain
@@ -0,0 +1,33 @@
1
+ """What a render is doing right now, in words a person reads next to its progress bar.
2
+
3
+ Renders report progress as a number through many nested callbacks; the step
4
+ they are on is set here by the step itself, per thread, so a render running
5
+ in one thread never reads another's.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import threading
11
+ from pathlib import Path
12
+
13
+ _local = threading.local()
14
+
15
+
16
+ def set_stage(text: str | None) -> None:
17
+ _local.stage = text
18
+
19
+
20
+ def current_stage() -> str | None:
21
+ return getattr(_local, "stage", None)
22
+
23
+
24
+ def stage_path(film: Path) -> Path:
25
+ """The hidden file beside a film being rendered that names its current step."""
26
+ return film.with_name(f".{film.stem}.stage")
27
+
28
+
29
+ def read_stage(film: Path) -> str | None:
30
+ try:
31
+ return stage_path(film).read_text(encoding="utf-8").strip()[:80] or None
32
+ except OSError:
33
+ return None
@@ -356,12 +356,16 @@ def compose_dense_titles(
356
356
  # every frame of every graphic, so it reports progress and stops when cancelled.
357
357
  components = [i for i in items if (custom_styles or {}).get(i.style_id, {}).get("kind") == "program_component"]
358
358
  boundaries = set(boundaries)
359
+ from .stage import set_stage
360
+
359
361
  for count, item in enumerate(components):
360
362
  if cancel.is_set():
361
363
  raise TitleRenderError("cancelled")
364
+ set_stage(f"畫自由設計元件 {count + 1}/{len(components)}")
362
365
  report(0.2 * count / len(components))
363
366
  boundaries |= component_boundaries(item, custom_styles[item.style_id], timeline, cancel)
364
367
  boundaries = sorted(boundaries)
368
+ set_stage("繪製字幕與元件")
365
369
  lines = ["ffconcat version 1.0"]
366
370
  events = max(1, len(boundaries) - 1)
367
371
  for index, (start, end) in enumerate(zip(boundaries, boundaries[1:])):
@@ -391,6 +395,7 @@ def compose_dense_titles(
391
395
  )
392
396
  manifest = directory / "text-events.ffconcat"
393
397
  manifest.write_text("\n".join(lines) + "\n")
398
+ set_stage("把字幕與元件疊上影片")
394
399
  report(0.4)
395
400
  seconds = timeline.duration_frames / fps
396
401
  progress_file = directory / "overlay-progress.txt"
@@ -40,7 +40,7 @@
40
40
  - 頁面就是整個畫面(window.clipen.width × height,例如 1920×1080)。只畫元件本身,其餘保持透明,讓素材透出來。用 vw/vh 或依 window.clipen 計算尺寸,不同解析度才會一致。
41
41
  - 時間由 Clipen 控制:CSS 動畫與 Web Animations 會逐格精準播放;用程式畫的話,定義 `window.clipenFrame = (frame, seconds) => {...}`,在裡面畫出那一格。requestAnimationFrame 迴圈、計時器與真實時鐘不會前進。第 0 格是元件出現的第一格,window.clipen 也提供 fps 與 durationFrames。
42
42
  - 沒有網路:圖片與圖形請內嵌(data: URL、inline SVG)。
43
- - 字型只能用元件外觀裡的:寫成 `font-family: var(--look-font-鍵名)`,外觀的顏色是 `var(--look-鍵名)`。用了外觀以外的字型(包括沒指定字型時的瀏覽器預設字)會被擋下。可選的字型列在 list_program_components 的 font_choices:系統字體,加上 Clipen 內附、任何電腦都能用的字型(中文手寫 Clipen Chenyu、楷書筆意 Clipen Iansui;日文手寫 Yusei Magic、Yomogi、Zen Kurenaido、Hachi Maru Pop;日文標題 Dela Gothic One、RocknRoll One、Zen Maru Gothic;英文 Bebas Neue、Anton、Caveat、Playfair Display)。字型缺字時,Clipen 會自動用同樣感覺的字型補上(例如辰宇缺日文假名時用 Yomogi),中日混排也維持同一種風格;日文為主的元件優先選日文字型。想換字或加一套字,就改外觀;用這個外觀的元件會一起換。改外觀時不要拿掉元件還在用的字型鍵名。
43
+ - 字型只能用元件外觀裡的:寫成 `font-family: var(--look-font-鍵名)`,外觀的顏色是 `var(--look-鍵名)`。用了外觀以外的字型(包括沒指定字型時的瀏覽器預設字)會被擋下。可選的字型列在 list_program_components 的 font_choices:系統字體,加上 Clipen 內附、任何電腦都能用的字型(中文手寫 Clipen Chenyu、楷書筆意 Clipen Iansui;日文手寫 Yusei Magic、Yomogi、Zen Kurenaido、Hachi Maru Pop;日文標題 Dela Gothic One、RocknRoll One、Zen Maru Gothic;英文 Bebas Neue、Anton、Caveat、Playfair Display)。字型缺了元件要顯示的中日文字時,這個字型鍵名的中日文會整組換成同樣感覺、而且字都齊全的下一套字型(例如辰宇遇到日文假名就整組改用 Yomogi),一個詞裡不會混兩種字。想保留自己選的字型,就選字都齊全的那一套;日文為主的元件優先選日文字型。想換字或加一套字,就改外觀;用這個外觀的元件會一起換。改外觀時不要拿掉元件還在用的字型鍵名。
44
44
  - 標出使用者可以自己改的地方:主要文字放在加了 `data-clipen-text="鍵名"` 的元素裡(可加 `data-clipen-label="主標"` 當顯示名稱),元素內只放純文字;主要顏色寫成 `:root` 上的 `--clipen-名稱` 變數(例如 `--clipen-主色`、`--clipen-字色`),再用 `var(--clipen-主色)` 套用。使用者在審片頁改的字與顏色會在頁面腳本執行前套上;要逐字拆開做動畫時,在 DOMContentLoaded 之後依元素目前的文字拆。沒有標出時,使用者只能請你重做;每個元件都要標。
45
45
  - 除了字型要來自外觀,只有技術檢查:頁面要能載入、程式不出錯、每格 10 秒內畫完、確實畫出東西、200 KB 以內。
46
46
  - 工具會回傳兩張圖:元件停在畫面上的樣子,以及從進場到退場的多格對照(每格標了第幾格)。兩張都要看:字是否清楚、有沒有擋到臉或字幕、是否服務這一刻;動畫是否看得出順序、節奏是否合適、退場是否乾淨。不滿意就用 update_custom_component 改,只需要給要變的欄位。