Setting the file. One moment. Measure Layout · Embedded Captions · heygen-com/hyperframes · Skills Docs14.42
Hershey Script1
(opens in a new tab)
scripts/measure-layout.cjs
JavaScript·293 lines·10 KB
* If no times given, samples groups['in', 'out'] midpoints.
16 */
17const path = require("path");
18const fs = require("fs");
19const os = require("os");
20
21// Locate hyperframes' bundled puppeteer. render-and-composite.sh exports
22// HYPERFRAMES_ROOT; standalone we also try the in-repo path + ~/Downloads, and
23// accept ANY puppeteer@* the bun store holds (not a pinned version).
24const HF_ROOTS = [
25 process.env.HYPERFRAMES_ROOT,
26 path.resolve(__dirname, "../../.."), // skills/embedded-captions/scripts → repo root if in-repo
27 path.join(os.homedir(), "Downloads", "hyperframes"),
28].filter(Boolean);
29let puppeteer = null;
30for (const root of HF_ROOTS) {
31 const cands = [path.join(root, "node_modules", "puppeteer")];
32 const bunDir = path.join(root, "node_modules", ".bun");
33 try {
34 if (fs.existsSync(bunDir)) {
35 for (const d of fs.readdirSync(bunDir)) {
36 if (d.startsWith("puppeteer@"))
37 cands.push(path.join(bunDir, d, "node_modules", "puppeteer"));
38 }
39 }
40 } catch {
41 /* ignore */
42 }
43 for (const p of cands) {
44 try {
45 if (fs.existsSync(p)) {
46 puppeteer = require(p);
47 break;
48 }
49 } catch {
50 /* try next */
51 }
52 }
53 if (puppeteer) break;
54}
55if (!puppeteer) {
56 console.error(
57 "[measure] could not locate puppeteer — set HYPERFRAMES_ROOT to a built hyperframes checkout",
58 );
59 process.exit(3);
60}
61
62// Resolve hyperframes' bundled GSAP. The templates load GSAP from a CDN
63// (cdn.jsdelivr.net), but in headless Chromium that request can be slow or
64// blocked — the page's inline `gsap.timeline()` then throws "gsap is not
65// defined" and the occlusion gate hard-fails. We inject this local copy on
66// every new document (before any page script runs) so window.gsap always
67// exists, and abort the CDN request so the parser never stalls on it. The
68// render path is unaffected — this is measurement-only.
69let gsapSource = null;
70for (const root of HF_ROOTS) {
71 const cands = [path.join(root, "node_modules", "gsap", "dist", "gsap.min.js")];
72 const bunDir = path.join(root, "node_modules", ".bun");
73 try {
74 if (fs.existsSync(bunDir)) {
75 for (const d of fs.readdirSync(bunDir)) {
76 if (d.startsWith("gsap@"))
77 cands.push(path.join(bunDir, d, "node_modules", "gsap", "dist", "gsap.min.js"));
78 }
79 }
80 } catch {
81 /* ignore */
82 }
83 for (const p of cands) {
84 try {
85 if (fs.existsSync(p)) {
86 gsapSource = fs.readFileSync(p, "utf8");
87 break;
88 }
89 } catch {
90 /* try next */
91 }
92 }
93 if (gsapSource) break;
94}
95
96async function main() {
97 const projectDir = process.argv[2];
98 if (!projectDir) {
99 console.error("usage: measure-layout.cjs <project-dir> [t1 t2 ...]");
100 process.exit(1);
101 }
102 const indexPath = path.resolve(projectDir, "index.html");
103 if (!fs.existsSync(indexPath)) {
104 console.error(`[measure] missing ${indexPath} — run make-composition.cjs first`);
105 process.exit(2);
106 }
107
108 // Load plan to get groups + sample times
109 const planPath = path.join(projectDir, "plan.json");
110 let plan = null;
111 if (fs.existsSync(planPath)) plan = JSON.parse(fs.readFileSync(planPath, "utf8"));
112
113 // Determine sample times: per group, sample multiple points across [in, out]
114 // (catches subject motion within block, multi-frame validation).
115 const explicitTimes = process.argv.slice(3).map(Number).filter(Number.isFinite);
116 let sampleTimes = explicitTimes;
117 if (sampleTimes.length === 0 && plan?.groups) {
118 const allTimes = new Set();
119 for (const g of plan.groups) {
120 const dur = g.out - g.in;
121 // 4 samples per group: 15%, 40%, 65%, 90% through window — covers entry/peak/exit
122 [0.15, 0.4, 0.65, 0.9].forEach((p) => allTimes.add(+(g.in + dur * p).toFixed(3)));
123 }
124 sampleTimes = [...allTimes].sort((a, b) => a - b);
125 }
126
127 // Match render-and-composite's Chrome detection
128 const exe =
129 process.platform === "darwin"
130 ? "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
131 : "/usr/bin/google-chrome";
132
133 const W = plan?.width || 720;
134 const H = plan?.height || 1290;
135 const FPS = plan?.fps || 24;
136
137 const browser = await puppeteer.launch({
138 headless: "new",
139 executablePath: fs.existsSync(exe) ? exe : undefined,
140 args: [
141 "--disable-web-security",
142 "--allow-file-access-from-files",
143 `--window-size=${W},${H}`,
144 "--disable-dev-shm-usage",
145 ],
146 });
147 try {
148 const page = await browser.newPage();
149 await page.setViewport({ width: W, height: H, deviceScaleFactor: 1 });
150 page.on("pageerror", (err) => console.error(`[browser-error] ${err.message}`));
151
152 // Inject local GSAP before any page script + abort the CDN <script> so the
153 // page never depends on network for GSAP (see resolver note above). Falls
154 // back to the page's own CDN load if no local copy was found.
155 if (gsapSource) {
156 await page.evaluateOnNewDocument(gsapSource);
157 await page.setRequestInterception(true);
158 page.on("request", (req) => {
159 const u = req.url();
160 if (req.resourceType() === "script" && /gsap/i.test(u) && /^https?:/i.test(u)) req.abort();
161 else req.continue();
162 });
163 }
164
165 await page.goto(`file://${indexPath}`, { waitUntil: "load", timeout: 15000 });
166 // GSAP is injected locally above; poll for the page's timeline registration.
167 const start = Date.now();
168 let ready = false;
169 while (Date.now() - start < 15000) {
170 const r = await page.evaluate(() => !!(window.__timelines && window.__timelines.main));
171 if (r) {
172 ready = true;
173 break;
174 }
175 await new Promise((res) => setTimeout(res, 200));
176 }
177 if (!ready) {
178 console.error("[measure] GSAP timeline never registered");
179 process.exit(4);
180 }
181 // Inject the skill's bundled @font-face set so headless Chromium measures the SAME
182 // glyph metrics the renderer will use. Without this, Inter/etc fall back to system
183 // fonts here while the real render uses the true (often wider) face → wrapped line
184 // counts differ → slot layout / occlusion verdicts are measured on the wrong text.
185 try {
186 const fontsCss = path.join(__dirname, "..", "modes", "standard", "fonts", "fonts.css");
187 if (fs.existsSync(fontsCss))
188 await page.addStyleTag({ content: fs.readFileSync(fontsCss, "utf8") });
189 } catch {
190 /* best-effort — fonts.css missing just reverts to old behavior */
191 }
192 // let webfonts settle so measured glyph metrics match the render
193 await page.evaluate(async () => {
194 try {
195 await document.fonts.ready;
196 } catch {}
197 });
198
199 const samples = [];
200 for (const t of sampleTimes) {
201 // Seek timeline
202 await page.evaluate((t) => {
203 const tl = window.__timelines.main;
204 tl.seek(t);
205 // Force layout flush
206 void document.body.offsetHeight;
207 }, t);
208 // Tiny settle for animations / fonts
209 await new Promise((r) => setTimeout(r, 30));
210
211 // Measure every .cap and its .w children
212 const measurements = await page.evaluate(() => {
213 const caps = [...document.querySelectorAll(".cap")];
214 const out = [];
215 for (const cap of caps) {
216 const cs = getComputedStyle(cap);
217 if (cs.opacity === "0" || cs.display === "none") continue;
218 const cb = cap.getBoundingClientRect();
219 if (cb.width === 0 || cb.height === 0) continue;
220 const id = cap.id || "";
221 const layer = cap.dataset.layer || "";
222 // Per-line via Range over all word spans
223 const ws = [...cap.querySelectorAll(".w")];
224 const words = [];
225 for (const w of ws) {
226 const wcs = getComputedStyle(w);
227 if (wcs.opacity === "0") continue; // not yet animated in
228 const wb = w.getBoundingClientRect();
229 if (wb.width === 0) continue;
230 words.push({
231 text: w.textContent,
232 x: +wb.x.toFixed(1),
233 y: +wb.y.toFixed(1),
234 w: +wb.width.toFixed(1),
235 h: +wb.height.toFixed(1),
236 opacity: +wcs.opacity,
237 });
238 }
239 // Group by line (same y ± 2px)
240 const lines = [];
241 for (const w of words) {
242 const line = lines.find((l) => Math.abs(l.y - w.y) < 3);
243 if (line) {
244 line.words.push(w);
245 line.x = Math.min(line.x, w.x);
246 line.w = Math.max(line.x + line.w, w.x + w.w) - line.x;
247 line.h = Math.max(line.h, w.h);
248 } else {
249 lines.push({ x: w.x, y: w.y, w: w.w, h: w.h, words: [w] });
250 }
251 }
252 out.push({
253 id,
254 layer,
255 cap_bbox: {
256 x: +cb.x.toFixed(1),
257 y: +cb.y.toFixed(1),
258 w: +cb.width.toFixed(1),
259 h: +cb.height.toFixed(1),
260 },
261 opacity: +cs.opacity,
262 lines,
263 words, // also keep flat list
264 });
265 }
266 return out;
267 });
268 const frame_idx = Math.max(1, Math.round(t * FPS));
269 samples.push({ t, frame_idx, caps: measurements });
270 }
271
272 const layout = { width: W, height: H, fps: FPS, samples };
273 const outPath = path.join(projectDir, "_layout.json");
274 fs.writeFileSync(outPath, JSON.stringify(layout, null, 2));
275 console.log(
276 `[measure] wrote ${outPath} (${sampleTimes.length} sample frames, ${samples.reduce((a, s) => a + s.caps.length, 0)} cap measurements)`,
277 );
278 } finally {
279 // Chromium occasionally hangs on shutdown. This script runs synchronously
280 // inside check-occlusion.cjs, which the render gate blocks on — a hung close
281 // would wedge the whole render. Cap the close, then force-exit below.
282 await Promise.race([browser.close().catch(() => {}), new Promise((r) => setTimeout(r, 8000))]);
283 }
284}
285
286// Force a hard exit so a lingering Chromium/libuv handle can't keep the process
287// (and the render gate that spawned it) alive indefinitely.
288main()
289 .then(() => process.exit(0))
290 .catch((e) => {
291 console.error(e);
292 process.exit(1);
293 });