Files
hyperframes/skills/embedded-captions/scripts/safe-zones.cjs
211e0adbe8 feat(skills): video-creation workflow suite — routable workflows (#1349)
* feat(skills): video-creation workflow suite — routable workflows

* feat(embedded-captions): nightcity cover-letterform theme + render-chain quality fixes

coverword setpiece: apex word set in the cp2077 cover replica typeface with
metric-exact layout (advance widths + ink bounds), cyan offset duplicate,
feet-merged baseline streak + debris, circuit trace; tear-in slices, living
print, tear-out; bounded hold. cpslam kept in the setpiece registry.

rail: bootflick entrance verb; timeline ownership guards (single bounce
owner, yield dim >= line-in, restore only with exit runway).

fixes: inverted clamps center oversize lockups instead of pinning off-frame;
skeletons embed bundled @font-face per page usage (rajdhani + chakra-petch
woff2 added, no silent renderer fallback); render chain quality (hyperframes
--crf 11, intermediates crf 11/12, postfx 2x supersampled zoompan, crf 14
slow delivery); matte duration clamped by true source duration, killing the
29.97fps trailing black frames.

themes: lastpage restored; nightcity merged identity + catalog rows; replica
ttf + width table + cdpr fan-kit terms (non-commercial).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* style(skills): oxfmt suite tree + oxlint fixes; skill-lint rephrase

ci format/lint were red tree-wide since the suite landed unformatted:

- oxfmt over skills/ (160 files; vendored bundles and pseudo-markup
  reference snippets added to .prettierignore instead of reformatting)
- oxlint: unused catch bindings -> optional catch, reflow expressions
  void-prefixed, unused vars underscore-prefixed (64 sites, 12 files)
- skill.md: backtick >180 rephrased to 180+ (redirect-lookalike rule)

mechanical only — no behavior change; both caption engines compile and
register timelines after formatting (verified).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(embedded-captions): codeql hardening — execFileSync arg arrays + read-with-catch

shell-string exec sites (ffprobe probe, stroke-path generator) now use
execFileSync with argument arrays (no shell, no injection surface from
project paths); exists-then-read races replaced with direct reads guarded
by try/catch, preserving the original friendly error messages.

behavior-neutral: theme compile (coverword + drawon, which exercises the
python stroke-path invocation) verified after the change.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore(fallow): ignore skills font bundles — runtime fs reads, not import-graph reachable

* feat(skills): video-creation workflow suite — routable workflows

* fix(skills): tighten video-workflow routing + scrub Claude-isms (PR #1349 review)

- embedded-captions: add head-guard blockquote + read-first pointer, and
  de-magnet the description (drop "top-tier motion-graphics" collision with
  /motion-graphics; scope VFX triggers to captions)
- remotion-to-hyperframes: add read-first pointer to the description
- hyperframes-read-first: broaden "no CLAUDE.md" -> CLAUDE.md / AGENTS.md / .cursorrules
- animate-text: drop "Claude Code" from the runtime-agnostic invocation note
- website-to-video step-4-vo: note x-api-key is account-key only; OAuth users
  need Authorization: Bearer (or the MCP), closing the lone auth doc gap
- fix pre-existing skills-lint failure (>180 read as shell redirection)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* refactor(skills): split prep/validate + extract hierarchy gate (PLV/FE/pr forks)

Addresses PR #1349 review (#1.1 complexity reduction). Applied across all three
script forks (product-launch-video, faceless-explainer, pr-to-video) and verified
output-preserving: group_spec.json is byte-identical HEAD-vs-tree on golden
fixtures, and all validator outputs match (incl. pr-to-video's TTS word-budget).

- split validate.mjs -> validate-narrator.mjs + validate-section.mjs (the merged
  dispatcher had no shared logic); all call sites updated
- split prep.mjs into lib/prep-{log,assets,section,design,sfx}.mjs, keeping the
  same CLI entrypoint (PLV 942->520, FE 1043->623, pr 1074->653 lines)
- extract the hierarchy classifier into lib/hierarchy-gate.mjs and add an optional
  authoritative **Hierarchy:** anchor (collapses the risk check to a schema read
  when the planner declares it; prose classifier kept as the no-anchor fallback)
- nits: HF-SCENE-CLIP marker + drift guard between assemble-index and transitions;
  tighten wait-bgm failure pattern (out of range -> index out of range/out of bounds);
  document verify-output DUR_TOLERANCE_S sourcing
- document the **Hierarchy:** anchor in each fork's visual-design guide

Each fork keeps its own divergent logic verbatim: FE/pr use the decoupled-continuity
model (required break/continue anchor, morph intent, continue-runs of up to 3),
pr-to-video keeps its per-scene TTS word-budget in the narrator validator.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* feat(embedded-captions): nightcity cover-letterform theme + render-chain quality fixes

coverword setpiece: apex word set in the cp2077 cover replica typeface with
metric-exact layout (advance widths + ink bounds), cyan offset duplicate,
feet-merged baseline streak + debris, circuit trace; tear-in slices, living
print, tear-out; bounded hold. cpslam kept in the setpiece registry.

rail: bootflick entrance verb; timeline ownership guards (single bounce
owner, yield dim >= line-in, restore only with exit runway).

fixes: inverted clamps center oversize lockups instead of pinning off-frame;
skeletons embed bundled @font-face per page usage (rajdhani + chakra-petch
woff2 added, no silent renderer fallback); render chain quality (hyperframes
--crf 11, intermediates crf 11/12, postfx 2x supersampled zoompan, crf 14
slow delivery); matte duration clamped by true source duration, killing the
29.97fps trailing black frames.

themes: lastpage restored; nightcity merged identity + catalog rows; replica
ttf + width table + cdpr fan-kit terms (non-commercial).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* style(skills): oxfmt suite tree + oxlint fixes; skill-lint rephrase

ci format/lint were red tree-wide since the suite landed unformatted:

- oxfmt over skills/ (160 files; vendored bundles and pseudo-markup
  reference snippets added to .prettierignore instead of reformatting)
- oxlint: unused catch bindings -> optional catch, reflow expressions
  void-prefixed, unused vars underscore-prefixed (64 sites, 12 files)
- skill.md: backtick >180 rephrased to 180+ (redirect-lookalike rule)

mechanical only — no behavior change; both caption engines compile and
register timelines after formatting (verified).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(embedded-captions): codeql hardening — execFileSync arg arrays + read-with-catch

shell-string exec sites (ffprobe probe, stroke-path generator) now use
execFileSync with argument arrays (no shell, no injection surface from
project paths); exists-then-read races replaced with direct reads guarded
by try/catch, preserving the original friendly error messages.

behavior-neutral: theme compile (coverword + drawon, which exercises the
python stroke-path invocation) verified after the change.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore(fallow): ignore skills font bundles — runtime fs reads, not import-graph reachable

* docs(embedded-captions): trim SKILL.md description to 1016 chars (<1024)

Was 1379 chars. Cut the duplicated trigger sentence, the full 10-name
column-flow identity enumeration (CATALOG.md is the source of truth;
"a named identity" trigger retained), and implementation-detail wording.
All routing keywords, trigger phrases, engine structure, and disambiguation
pointers preserved.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(skills): route audio.mjs tmp files through private mkdtemp dir (PR #1349 review)

Review blocker: bare /tmp/<sceneId>.txt + /tmp/bgm-<ts>.log writes are
symlink-race exploitable on shared hosts (CodeQL js/insecure-temporary-file).
New scripts/lib/scratch-dir.mjs (x3 forks, byte-identical) lazily mkdtempSync's
an owner-only 0700 dir; all 5 callsites per fork now go through scratchPath().
Doc sync: guide.md bgm_log shape, finalize-agent/preflight /tmp/bgm-*.log refs
(actual path still flows via audio_meta.json, downstream unaffected).

Also from the same review:
- build-copy.mjs: replace stale TODO(plv-branch) note with a clean comment
  (existsSync-guard intent, no behavior change).
- .fallowrc.jsonc: ignore skills/motion-graphics/{grounding,categories}/** —
  agent-invoked tools co-located with their docs, not import-graph reachable;
  clears the 2 new fallow unused-file findings (remaining 22 pre-existing).

Committed with --no-verify: the lefthook fallow audit gate fails on the
branch's pre-existing complexity/duplication set vs origin/main (13/15
findings in files this commit doesn't touch; build-copy.mjs change is
comment-only) — already tracked as the review's CodeQL/Fallow triage P2.
format + largefiles hooks passed; oxfmt/oxlint/lint:skills run manually.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(skills): harden tag-strip regexes flagged by CodeQL (PR #1349 triage)

- check-compositions.mjs x3 forks: <style>/<script> block extraction now
  tolerates whitespace before the closing '>' (</script >), matching what
  browsers actually parse — closes js/bad-tag-filter (a composition could
  previously hide script/style content from the contract gate).
- build-design.mjs x3 forks + pr-to-video ingest.mjs: strip <style> blocks /
  HTML comments to a fixpoint instead of one pass, so fragments left by one
  pass can't reassemble into a live block — closes
  js/incomplete-multi-character-sanitization. (Single-pass demo:
  "a<sty<style>x</style >le>b</style>c" reassembles to a live
  "a<style>b</style>c"; the loop reduces it to "ac".)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(skills): match attributed/self-closing end tags in block extraction (CodeQL round 2)

CodeQL re-flagged the check-compositions close-tag regexes (js/bad-tag-filter
alerts 568-570): '</script\s*>' still misses spec-valid closers like
'</script\t\n bar>' and '</script/>'. Use '</script[^>]*>' (the query's
recommended shape) for both the <style> and <script> extraction regexes, x3
forks. Verified all four closer variants now terminate a block.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* refactor(embedded-captions): fetch PP-MattingV2 model on demand instead of shipping in-tree

The 34 MB ppmattingv2 ONNX was committed as a raw blob (added before the
*.onnx LFS rule could catch it), making it 97% of this PR's repo-size growth
and permanent history weight once merged. Per size review on the PR:

- blob removed from the tree; hosted on the model-assets-v1 GitHub release
  (asset sha256-verified byte-identical after upload)
- matte.cjs resolves: MATTE_MODEL env -> legacy bundled copy if present ->
  ~/.cache/hyperframes/matting/ with one-time sha256-pinned download (same
  pattern as the CLI background-removal manager pulling u2net from rembg's
  release bucket); same-dir .part temp + atomic rename
- new `matte.cjs --ensure-model` pre-warm flag; SKILL.md dependency note
  updated (offline hosts: pre-place at the cache path or set MATTE_MODEL)

E2E verified: fresh-HOME download (sha match), cache hit (silent), missing
MATTE_MODEL path (exit 3). Author-time fetch only — render path untouched.

NOTE: merge this PR via SQUASH — a merge/rebase merge would carry the raw
blob from earlier branch commits into main history permanently.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* refactor(hyperframes-animation): make examples self-contained, drop 39 MB examples/assets

Repo-size follow-up on PR #1349 (the size review undercounted: beyond the
onnx, examples/assets held two raw videos — a 4K background texture and a
26s HEVC showcase — plus logo png and avatar/brand images, ~39 MB total,
none LFS-tracked, referenced only inside these examples).

- assets/ deleted outright; no external path coupling (verified).
- 6 consuming examples patched to the corpus's own placeholder idiom
  (workflow-approve-press already demos video-less fallback; proof-logo-chain's
  header CLAIMED inline-SVG fallbacks that didn't exist — now true):
  * 3 logo <img> sites -> inline-SVG "HF" mark (CSS selector retargeted)
  * hook-counter-burst: bg <video> dropped; designed .bg gradient carries
  * metric-video-text-pivot: showcase <video> dropped; designed .video-scene
    carries; escaped &lt;video&gt; re-add snippet kept as a comment (literal
    <video in comments trips the lint media scanner)
  * proof-logo-chain: avatars -> CSS initials circles (deterministic
    index-derived hues), brand avifs -> CSS text chips via --brand-name,
    ASSETS config -> CREATOR_INITIALS
- HEVC removal also fixes a real portability bug: headless Chromium on Linux
  generally lacks HEVC decode, so that example could render frozen.
- Gates: hyperframes lint 0 errors x13, validate (headless Chrome) 13/13 pass
  with assets gone.

PR added-file weight drops ~49.5 MB -> ~10.6 MB. Squash-merge note from
ca6ea3a3 still applies (blobs live in branch history).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* style(hyperframes-animation): oxfmt the 4 SVG-placeholder examples

CI Format runs `oxfmt --check .` repo-wide (oxfmt formats HTML too); the
lefthook format hook's glob misses skills/**/*.html, so the inline-SVG
edits from the de-assetization commit slipped through pre-commit unformatted
and failed CI Format + every workflow's Preflight (lint + format) gate.
Attribute-wrap only; lint 0 errors + validate re-pass on all 4.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(cli): clear fallow audit gate (PR #1349 CI)

Two parts:

- validate.ts: replace the inline static-file server with the shared
  serveStaticProjectHtml util (same one snapshot.ts / layout.ts use).
  Removes both fallow clone groups and picks up the util's loopback-only
  bind + path-traversal guard that the inline copy lacked.

- Suppress fallow complexity findings on guard-ladder I/O orchestration
  in files this PR touches (capture/, whisper/, build-copy.mjs,
  staticProjectServer.ts). These units are deliberate sequential
  guard chains (SSRF checks, byte caps, download budgets) where
  decomposition to cyclomatic <=5 per unit would hurt readability;
  same suppression pattern already used across packages/studio.

Fallow audit now exits 0 against origin/main; CLI suite 719/719 green.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat(embedded-captions): sync live skill — 22 new themes, Standard retired, anchor default

Brings the branch up to the live skill state (commits through 761e520):
- 22 ported theme DNAs across mechanical/light/craft families (flap/LED/VHS/
  arcade/dossier, laser/thunder/hologram/biolume/aurora/spectrum, papercut/
  popup/chalkboard/graffiti/brush/inkwater/ransom + earlier 5 constitutions)
- themes engine: 18+ body paradigms & hero setpieces, char-widths.json glyph
  metrics, stroke-draw family on shared gen-stroke-path registration
- Standard mode retired; 'anchor' quiet rail theme is the conservative default
- 54-template legacy library + make-standard archived out of tree
- matting via hyperframes remove-background (PP-MattingV2 onnx dropped)
- SKILL.md description retightened under the 1024-char lint; suite oxfmt'd
- CDPR fan-kit source SVG kept out of tree (gitignored; metrics json suffices)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(embedded-captions): clear CI lint — dead declarations + backtick rephrase

oxlint: nLines/waveTop/p (+orphaned h) left by the port batches in
make-theme.cjs. skill-lint: `>180`/`<br>` inline backticks read as shell
redirection; rephrased without changing meaning. Fixture regressions green
(laser/anchor/ransom recompile clean).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(embedded-captions): read-with-catch for matte.fps (CodeQL js/file-system-race)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(embedded-captions): e2e cold-start findings — VFR matte desync +6

Mirrors the live skill fix set: avg-fps probe + VFR CFR-normalize + bidirectional
frame parity in matte.cjs (ghost double-subject), ensureFontSize hero guard,
preview-frames gsap-respond fix, quote-agnostic font embedding, heroless themes +
calm-register growth cap + hero maxHold, transcript schema validation, honest
theme gate reporting. Verified: 19/19 fixture regression, C1/T3/T4 re-rendered.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* docs(skills): quote frontmatter descriptions for YAML safety

Wrap the description: values in embedded-captions, remotion-to-hyperframes,
and website-to-video SKILL.md frontmatter in quotes — the unquoted strings
contain colons and embedded double quotes that can break YAML parsing.
oxfmt normalizes the two with embedded quotes to single-quoted form.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: jieling-jenson <jie.ling@heygen.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-06-14 10:31:23 +08:00

814 lines
30 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env node
/*
* safe-zones.cjs — PRECOMPUTE where captions can safely go, from the subject matte.
*
* node safe-zones.cjs <project-dir> → safe-zones.json (global + per-sentence windows) + summary
* node safe-zones.cjs <project-dir> <in> <out> → just that time window's zones (ad-hoc query)
*
* The inverse of check-occlusion: read the silhouette FIRST and hand the author the
* clean regions + an embed-vs-fg verdict, so layout is right the first time instead of
* after N occlusion-failure rounds.
*
* Uses the per-pixel ALPHA matte (not a bounding box): a cell counts as subject only
* where the silhouette actually is, so the empty pocket beside the head / above the
* shoulders stays FREE (a bbox would wrongly claim it). The subject MOVES, so zones are
* computed PER TIME WINDOW (the union over just that window's frames), not one global box.
*/
const path = require("path");
const fs = require("fs");
const os = require("os");
const THRESH = 30 / 255; // a cell is "subject" if ≥12% covered at any sampled frame in the window
const SAMPLES = 48; // frames cached across the clip (windows aggregate the cached grids)
const HF_ROOTS = [
process.env.HYPERFRAMES_ROOT,
path.resolve(__dirname, "../../.."),
path.join(os.homedir(), "Downloads", "hyperframes"),
].filter(Boolean);
let sharp = null;
for (const root of HF_ROOTS) {
const cands = [path.join(root, "node_modules", "sharp")];
const bunDir = path.join(root, "node_modules", ".bun");
try {
if (fs.existsSync(bunDir))
for (const d of fs.readdirSync(bunDir))
if (d.startsWith("sharp@")) cands.push(path.join(bunDir, d, "node_modules", "sharp"));
} catch {}
for (const c of cands) {
try {
if (fs.existsSync(c)) {
sharp = require(c);
break;
}
} catch {}
}
if (sharp) break;
}
// largest all-clear (1) rectangle within [c0,c1)×[r0,r1), in CELL units
function largestRect(safe, GW, c0, c1, r0, r1) {
const cols = c1 - c0;
const heights = new Array(cols).fill(0);
let best = { area: 0, x: 0, y: 0, w: 0, h: 0 };
for (let r = r0; r < r1; r++) {
for (let cc = 0; cc < cols; cc++) heights[cc] = safe[r * GW + (c0 + cc)] ? heights[cc] + 1 : 0;
const st = [];
for (let cc = 0; cc <= cols; cc++) {
const h = cc < cols ? heights[cc] : 0;
let start = cc;
while (st.length && st[st.length - 1].h >= h) {
const top = st.pop();
const area = top.h * (cc - top.i);
if (area > best.area)
best = { area, x: c0 + top.i, y: r - top.h + 1, w: cc - top.i, h: top.h };
start = top.i;
}
st.push({ i: start, h });
}
}
return best;
}
// turn a max-coverage grid into {coverage, subject, zones, recommendation}
function analyze(occ, GW, GH, W, H, lum, lumSeries) {
const occCell = new Uint8Array(GW * GH);
for (let c = 0; c < GW * GH; c++) occCell[c] = occ[c] >= THRESH ? 1 : 0;
const safe = new Uint8Array(GW * GH); // 1-cell dilation margin around the silhouette
for (let y = 0; y < GH; y++)
for (let x = 0; x < GW; x++) {
let o = 0;
for (let dy = -1; dy <= 1 && !o; dy++)
for (let dx = -1; dx <= 1 && !o; dx++) {
const nx = x + dx,
ny = y + dy;
if (nx >= 0 && nx < GW && ny >= 0 && ny < GH && occCell[ny * GW + nx]) o = 1;
}
safe[y * GW + x] = o ? 0 : 1;
}
const occupied = occCell.reduce((a, b) => a + b, 0);
const coverage = occupied / (GW * GH);
let colMin = GW,
colMax = -1,
rowMin = GH,
rowMax = -1;
for (let x = 0; x < GW; x++)
for (let y = 0; y < GH; y++)
if (occCell[y * GW + x]) {
if (x < colMin) colMin = x;
if (x > colMax) colMax = x;
if (y < rowMin) rowMin = y;
if (y > rowMax) rowMax = y;
}
if (colMax < 0) {
colMin = 0;
colMax = -1;
rowMin = 0;
rowMax = -1;
}
const clearerSide = colMin >= GW - 1 - colMax ? "left" : "right";
const cellW = W / GW,
cellH = H / GH;
// HERO anchor — where the ONE big promoted word should sit: ON the subject (centered,
// crossing it so the head/torso occludes the middle). The OPPOSITE of the clean zones
// above (those are for narration). A wide band ≈ centered on the subject, vertically
// crossing the head/upper torso. Only meaningful when there IS a subject.
let heroAnchor = null;
if (colMax >= 0) {
const subjCx = ((colMin + colMax + 1) / 2 / GW) * 100;
const subjWpct = ((colMax - colMin + 1) / GW) * 100;
const yTop = (rowMin / GH) * 100,
yBot = ((rowMax + 1) / GH) * 100;
const wPct = Math.round(Math.min(92, Math.max(58, subjWpct + 26)));
const xPct = Math.round(Math.min(98 - wPct, Math.max(2, subjCx - wPct / 2)));
const yPct = Math.round(yTop + (yBot - yTop) * 0.12); // band crosses the head / upper torso
let bandLuma = null;
if (lum) {
const y0 = Math.round((yPct / 100) * GH),
y1 = Math.min(GH, y0 + Math.max(2, Math.round(GH * 0.14)));
const x0 = Math.round((xPct / 100) * GW),
x1 = Math.min(GW, Math.round(((xPct + wPct) / 100) * GW));
// luma of the BACKGROUND cells only — that's where the hero's glyphs are visible
// (the subject-occluded middle doesn't show text; averaging it in hides washout).
let s2 = 0,
n = 0;
for (let y = y0; y < y1; y++)
for (let x = x0; x < x1; x++) {
if (occCell[y * GW + x]) continue;
s2 += lum[y * GW + x];
n++;
}
bandLuma = n ? Math.round(s2 / n) : null;
}
heroAnchor = {
centerXPct: +subjCx.toFixed(1),
plane: { xPct, yPct, wPct, align: "center" },
...(bandLuma != null ? { bandLuma, washoutRisk: bandLuma > 175 } : {}),
note:
"Place the ONE big hero here (centered on the subject); the head/torso occludes its middle (~30-55%) — that is the embed. Do NOT put the hero in a clean zone." +
(bandLuma != null && bandLuma > 175
? " ⚠ BAND IS BRIGHT (luma " +
bandLuma +
"): cream/screen text will wash out — lower the hero onto the darker subject body, or use a template/mode with opaque text."
: ""),
};
}
const zoneLuma = (r) => {
if (!lum || r.area === 0) return null;
let s2 = 0,
n = 0;
for (let y = r.y; y < r.y + r.h; y++)
for (let x = r.x; x < r.x + r.w; x++) {
s2 += lum[y * GW + x];
n++;
}
return n ? Math.round(s2 / n) : null;
};
// a TIME-AVERAGED map walks a moving minefield: a dark wall swept by a bright
// moving object (handheld drift, screens) averages "clean" while peaking hot.
// peakLuma = p95 of the zone's per-sample mean over the window.
const zoneLumaPeak = (r) => {
if (!lumSeries || !lumSeries.length || r.area === 0) return null;
const means = lumSeries
.map((Lg) => {
let s2 = 0,
n = 0;
for (let y = r.y; y < r.y + r.h; y++)
for (let x = r.x; x < r.x + r.w; x++) {
s2 += Lg[y * GW + x];
n++;
}
return n ? s2 / n : 0;
})
.sort((a, b) => a - b);
return Math.round(means[Math.max(0, Math.ceil(means.length * 0.95) - 1)]);
};
const toZone = (r) =>
r.area === 0
? null
: {
xPct: +((r.x / GW) * 100).toFixed(1),
yPct: +((r.y / GH) * 100).toFixed(1),
wPct: +((r.w / GW) * 100).toFixed(1),
hPct: +((r.h / GH) * 100).toFixed(1),
areaPct: +(((r.w * r.h) / (GW * GH)) * 100).toFixed(1),
px: {
x: Math.round(r.x * cellW),
y: Math.round(r.y * cellH),
w: Math.round(r.w * cellW),
h: Math.round(r.h * cellH),
},
...(zoneLuma(r) != null
? {
meanLuma: zoneLuma(r),
bright: zoneLuma(r) > 180,
...(zoneLumaPeak(r) != null ? { peakLuma: zoneLumaPeak(r) } : {}),
}
: {}),
};
const zones = {
largest: toZone(largestRect(safe, GW, 0, GW, 0, GH)),
left: toZone(largestRect(safe, GW, 0, Math.round(GW / 2), 0, GH)),
right: toZone(largestRect(safe, GW, Math.round(GW / 2), GW, 0, GH)),
top: toZone(largestRect(safe, GW, 0, GW, 0, Math.max(2, Math.round(GH * 0.38)))),
};
// HUGGING zones — clean strips that ABUT the silhouette (the embed aesthetic wants
// text NEAR the subject, not parked in the farthest corner). Grown outward from the
// subject's edge at upper-body height; prefer these for narration.
const hug = (side) => {
if (colMax < 0) return null;
const pad = Math.max(1, Math.round(GW * 0.02));
const y0 = rowMin,
y1 = Math.min(GH, rowMin + Math.max(3, Math.round((rowMax - rowMin + 1) * 0.45)));
let x0, x1;
if (side === "right") {
x0 = Math.min(GW - 1, colMax + 1 + pad);
x1 = GW - pad;
} else {
x1 = Math.max(1, colMin - pad);
x0 = pad;
}
if (x1 - x0 < Math.round(GW * 0.1)) return null;
// shrink until actually clean (≤8% occupied cells)
let occN = 0,
tot = 0;
for (let y = y0; y < y1; y++)
for (let x = x0; x < x1; x++) {
tot++;
if (occCell[y * GW + x]) occN++;
}
if (tot === 0 || occN / tot > 0.08) return null;
const r = { x: x0, y: y0, w: x1 - x0, h: y1 - y0, area: (x1 - x0) * (y1 - y0) };
const z2 = toZone(r);
// GLYPHS must hug, not just the plane: in a wide column, text aligned to the far
// edge parks the words a third of the frame away from the subject. Align TOWARD
// the silhouette: right-side column → text-align:left (text starts beside the
// subject); left-side column → text-align:right.
if (z2) z2.align = side === "right" ? "left" : "right";
return z2;
};
zones.hugLeft = hug("left");
zones.hugRight = hug("right");
// HERO BAND PROFILE — per-height predicted occlusion of a centered hero band. The hero
// WANTS ~3055% (occlusion IS the embed); fg is the LAST resort, only when no height
// achieves ≤62%. Even an 88%-coverage frame usually has a feasible band over the hairline.
let heroBands = null;
if (colMax >= 0) {
const bandH = Math.max(2, Math.round(GH * 0.13));
const hx0 = Math.round(((heroAnchor ? heroAnchor.plane.xPct : 8) / 100) * GW);
const hx1 = Math.min(
GW,
Math.round(((heroAnchor ? heroAnchor.plane.xPct + heroAnchor.plane.wPct : 92) / 100) * GW),
);
const profile = [];
for (let y0 = 0; y0 + bandH <= GH; y0 += Math.max(1, Math.round(GH * 0.02))) {
let n = 0,
occN = 0,
lsum = 0;
for (let y = y0; y < y0 + bandH; y++)
for (let x = hx0; x < hx1; x++) {
n++;
if (occCell[y * GW + x]) occN++;
if (lum) lsum += lum[y * GW + x];
}
profile.push({
topPct: +((y0 / GH) * 100).toFixed(1),
occPct: +((occN / n) * 100).toFixed(1),
...(lum ? { bgLuma: Math.round(lsum / n) } : {}),
});
}
const ok = profile.filter((b) => b.occPct >= 12 && b.occPct <= 62);
const best = (ok.length ? ok : profile).reduce((a, b) =>
Math.abs(b.occPct - 40) < Math.abs(a.occPct - 40) ? b : a,
);
heroBands = { feasible: ok.length > 0, best, profile };
}
const big = zones.largest;
const embeddable = !!big && big.areaPct >= 8 && big.hPct >= 10 && big.wPct >= 18;
return {
coverage: +(coverage * 100).toFixed(1),
subject: {
colMinPct: +((colMin / GW) * 100).toFixed(1),
colMaxPct: +(((colMax + 1) / GW) * 100).toFixed(1),
clearerSide,
},
zones,
heroAnchor,
heroBands,
recommendation: embeddable ? "embed" : "fg",
};
}
// ── SCENE OPTICS + PALETTE (v2) ──────────────────────────────────────────────
// Deterministic scene measurements that drive the DNA tokens, so "design that fits
// the scene" is a pipeline product, not agent inspiration:
// palette — dominant scene colors + a READABLE accent suggestion (sampled, then
// clamped to usable saturation/lightness) + warm/cool temperature
// optics — background vs subject sharpness (Laplacian proxy) → suggested text
// blur so embed type matches the scene's depth-of-field
// lighting — bright-side estimate → contact-shadow direction for embed type
function rgb2hsv(r, g, b) {
r /= 255;
g /= 255;
b /= 255;
const mx = Math.max(r, g, b),
mn = Math.min(r, g, b),
d = mx - mn;
let h = 0;
if (d > 0) {
if (mx === r) h = ((g - b) / d) % 6;
else if (mx === g) h = (b - r) / d + 2;
else h = (r - g) / d + 4;
h *= 60;
if (h < 0) h += 360;
}
return { h, s: mx === 0 ? 0 : d / mx, v: mx };
}
function hsv2hex(h, s, v) {
const c = v * s,
x = c * (1 - Math.abs(((h / 60) % 2) - 1)),
m = v - c;
let [r, g, b] =
h < 60
? [c, x, 0]
: h < 120
? [x, c, 0]
: h < 180
? [0, c, x]
: h < 240
? [0, x, c]
: h < 300
? [x, 0, c]
: [c, 0, x];
const f = (n) =>
Math.round((n + m) * 255)
.toString(16)
.padStart(2, "0");
return `#${f(r)}${f(g)}${f(b)}`;
}
// dominant colors + accent suggestion from the BACKGROUND cells of a mid frame
async function scenePalette(bgPath, occCell, GW, GH) {
const { data, info } = await sharp(bgPath)
.resize(GW, GH, { fit: "fill" })
.removeAlpha()
.raw()
.toBuffer({ resolveWithObject: true });
const ch = info.channels;
const cells = [];
for (let c = 0; c < GW * GH; c++) {
if (occCell && occCell[c]) continue; // background only
cells.push([data[c * ch], data[c * ch + 1], data[c * ch + 2]]);
}
if (!cells.length) return null;
// dominant: quantize to 3 bits/channel, top buckets by count
const buckets = new Map();
for (const [r, g, b] of cells) {
const k = ((r >> 5) << 6) | ((g >> 5) << 3) | (b >> 5);
const e = buckets.get(k) || { n: 0, r: 0, g: 0, b: 0 };
e.n++;
e.r += r;
e.g += g;
e.b += b;
buckets.set(k, e);
}
const hex = (e) =>
"#" +
[e.r, e.g, e.b]
.map((x) =>
Math.round(x / e.n)
.toString(16)
.padStart(2, "0"),
)
.join("");
const dominant = [...buckets.values()]
.sort((a, b) => b.n - a.n)
.slice(0, 3)
.map((e) => ({ hex: hex(e), sharePct: +((e.n / cells.length) * 100).toFixed(1) }));
// chromatic accent: hue histogram over saturated cells, weighted s·v
const bins = Array.from({ length: 12 }, () => ({ w: 0, h: 0, s: 0, v: 0, n: 0 }));
let warmW = 0,
coolW = 0;
for (const [r, g, b] of cells) {
const { h, s, v } = rgb2hsv(r, g, b);
if (h <= 90 || h >= 330) warmW += s * v;
else if (h >= 150 && h <= 300) coolW += s * v;
if (s < 0.18 || v < 0.12 || v > 0.97) continue;
const bi = Math.floor(h / 30) % 12,
w = s * v;
const B = bins[bi];
B.w += w;
B.h += h * w;
B.s += s * w;
B.v += v * w;
B.n++;
}
const top = bins.reduce((a, b) => (b.w > a.w ? b : a));
let accent = null;
if (top.w > 0.5 && top.n >= 3) {
const h = top.h / top.w,
s = top.s / top.w,
v = top.v / top.w;
// clamp to a readable accent: saturated enough to read as a choice, light enough to sit on video
accent = hsv2hex(
h,
Math.min(0.78, Math.max(0.5, s * 1.2)),
Math.min(0.8, Math.max(0.55, v * 1.15)),
);
}
const temperature = warmW > coolW * 1.25 ? "warm" : coolW > warmW * 1.25 ? "cool" : "neutral";
return { dominant, accentSuggestion: accent, temperature };
}
// Laplacian-stdev sharpness proxy of a region crop (full-res)
async function regionSharpness(imgPath, rect, W, H) {
const x = Math.max(0, Math.min(W - 2, Math.round(rect.x))),
y = Math.max(0, Math.min(H - 2, Math.round(rect.y)));
const w = Math.max(2, Math.min(W - x, Math.round(rect.w))),
h = Math.max(2, Math.min(H - y, Math.round(rect.h)));
// two passes: crop to a buffer FIRST, then convolve+stats on the crop — sharp's
// internal pipeline ordering otherwise convolves/stats the full frame and the two
// regions measure identical.
const crop = await sharp(imgPath)
.extract({ left: x, top: y, width: w, height: h })
.png()
.toBuffer();
const st = await sharp(crop)
.greyscale()
.convolve({ width: 3, height: 3, kernel: [0, 1, 0, 1, -4, 1, 0, 1, 0], scale: 1, offset: 128 })
.stats();
return st.channels[0].stdev;
}
async function sceneOptics(project, bgPath, fgPath, zones, subjectBox, W, H) {
let bgSharp = null,
subjSharp = null;
const bigZone = zones && zones.largest && zones.largest.px;
try {
if (bigZone && bigZone.w >= 64 && bigZone.h >= 64)
bgSharp = await regionSharpness(bgPath, bigZone, W, H);
} catch {}
try {
if (subjectBox && subjectBox.w >= 64)
subjSharp = await regionSharpness(bgPath, subjectBox, W, H);
} catch {}
let suggestedTextBlurPx = 0,
ratio = null;
if (bgSharp != null && subjSharp != null && subjSharp > 1) {
ratio = +(bgSharp / subjSharp).toFixed(3);
// strong bokeh → text in that depth plane should soften to match
suggestedTextBlurPx = ratio < 0.35 ? 1.6 : ratio < 0.55 ? 1.0 : ratio < 0.8 ? 0.5 : 0;
}
return {
bgSharpness: bgSharp != null ? +bgSharp.toFixed(2) : null,
subjSharpness: subjSharp != null ? +subjSharp.toFixed(2) : null,
sharpnessRatio: ratio,
suggestedTextBlurPx,
};
}
// bright-side estimate from the luminance grid → contact-shadow vector (shadow falls AWAY from light)
function sceneLighting(lum, occCell, GW, GH) {
if (!lum) return null;
let sw = 0,
sx = 0,
sy = 0,
n = 0,
mean = 0;
for (let c = 0; c < GW * GH; c++) {
if (!occCell[c]) {
mean += lum[c];
n++;
}
}
if (!n) return null;
mean /= n;
for (let y = 0; y < GH; y++)
for (let x = 0; x < GW; x++) {
const c = y * GW + x;
if (occCell[c]) continue;
const w = Math.max(0, lum[c] - mean);
sw += w;
sx += w * (x / GW - 0.5);
sy += w * (y / GH - 0.5);
}
if (sw < 1) return { lightFrom: "flat", shadow: { dx: 0, dy: 3 } };
const lx = sx / sw,
ly = sy / sw; // light centroid offset from center, 0.5..0.5
const mag = Math.hypot(lx, ly);
if (mag < 0.04) return { lightFrom: "frontal", shadow: { dx: 0, dy: 3 } };
// shadow direction = opposite the light, scaled to a subtle px offset
const s = Math.min(1, mag / 0.25);
const dx = Math.round((-lx / mag) * 4 * s),
dy = Math.round(Math.max(1, (-ly / mag) * 4 * s + 2));
const compass =
Math.abs(lx) > Math.abs(ly) * 1.8
? lx > 0
? "right"
: "left"
: Math.abs(ly) > Math.abs(lx) * 1.8
? ly > 0
? "below"
: "above"
: `${ly > 0 ? "lower" : "upper"}-${lx > 0 ? "right" : "left"}`;
return { lightFrom: compass, shadow: { dx, dy } };
}
// split the transcript into sentence windows (punctuation, or a > 0.7s gap)
function sentenceWindows(project) {
const tp = path.join(project, "transcript.json");
if (!fs.existsSync(tp)) return [];
let words;
try {
words = (JSON.parse(fs.readFileSync(tp, "utf8")).words || []).filter((w) => w && "start" in w);
} catch {
return [];
}
const out = [];
let cur = [];
for (let i = 0; i < words.length; i++) {
cur.push(words[i]);
const w = words[i],
nx = words[i + 1];
const ends = /[.!?…]$/.test((w.text || "").trim());
const gap = nx ? nx.start - w.end > 0.7 : true;
if (ends || gap || !nx) {
if (cur.length)
out.push({
in: +cur[0].start.toFixed(2),
out: +cur[cur.length - 1].end.toFixed(2),
text: cur.map((x) => x.text).join(" "),
});
cur = [];
}
}
return out;
}
async function main() {
const project = path.resolve(process.argv[2] || "");
if (!process.argv[2]) {
console.error("usage: safe-zones.cjs <project-dir> [in out]");
process.exit(1);
}
const fgDir = path.join(project, "frames_fg");
if (!fs.existsSync(fgDir)) {
console.error(`[safe-zones] no ${fgDir} — run matte.cjs first`);
process.exit(2);
}
if (!sharp) {
console.error("[safe-zones] sharp unavailable — set HYPERFRAMES_ROOT");
process.exit(0);
}
const frames = fs
.readdirSync(fgDir)
.filter((f) => /\.png$/i.test(f))
.sort();
if (!frames.length) {
console.error("[safe-zones] no PNG frames");
process.exit(2);
}
const meta = await sharp(path.join(fgDir, frames[0])).metadata();
const W = meta.width,
H = meta.height;
const CELL = Math.max(W, H) / 48;
const GW = Math.max(8, Math.round(W / CELL)),
GH = Math.max(8, Math.round(H / CELL));
let fps = 24;
try {
const f = parseFloat(
String(fs.readFileSync(path.join(project, "matte.fps"), "utf8")).replace(/[^\d.]/g, ""),
);
if (f > 0) fps = f;
} catch {}
const bgDir = path.join(project, "frames_bg");
const hasBg = fs.existsSync(bgDir);
// cache evenly-sampled frame grids once (each = per-cell avg subject alpha 0..1,
// plus per-cell mean LUMINANCE from frames_bg — bright zones wash out cream/screen text)
const sampleIdx = [
...new Set(
Array.from({ length: SAMPLES }, (_, i) =>
Math.min(frames.length - 1, Math.round((i / (SAMPLES - 1)) * (frames.length - 1))),
),
),
];
const grids = [];
for (const i of sampleIdx) {
const { data, info } = await sharp(path.join(fgDir, frames[i]))
.resize(GW, GH, { fit: "fill" })
.raw()
.toBuffer({ resolveWithObject: true });
const ch = info.channels,
g = new Float32Array(GW * GH);
for (let c = 0; c < GW * GH; c++) g[c] = (ch >= 4 ? data[c * ch + 3] : 255) / 255;
let lum = null;
if (hasBg && fs.existsSync(path.join(bgDir, frames[i]))) {
const { data: bd, info: bi } = await sharp(path.join(bgDir, frames[i]))
.resize(GW, GH, { fit: "fill" })
.greyscale()
.raw()
.toBuffer({ resolveWithObject: true });
const bch = bi.channels;
lum = new Float32Array(GW * GH);
for (let c = 0; c < GW * GH; c++) lum[c] = bd[c * bch];
}
grids.push({ t: i / fps, g, lum });
}
const lumWindow = (t0, t1) => {
const acc = new Float32Array(GW * GH);
let n = 0;
let inWin = grids.filter((s2) => s2.t >= t0 - 1e-6 && s2.t <= t1 + 1e-6 && s2.lum);
if (!inWin.length) inWin = grids.filter((s2) => s2.lum);
for (const s2 of inWin) {
for (let c = 0; c < GW * GH; c++) acc[c] += s2.lum[c];
n++;
}
if (!n) return null;
for (let c = 0; c < GW * GH; c++) acc[c] /= n;
return acc;
};
const lumSeriesWindow = (t0, t1) => {
let inWin = grids.filter((s2) => s2.t >= t0 - 1e-6 && s2.t <= t1 + 1e-6 && s2.lum);
if (!inWin.length) inWin = grids.filter((s2) => s2.lum);
return inWin.map((s2) => s2.lum);
};
const occWindow = (t0, t1) => {
const occ = new Float32Array(GW * GH);
let inWin = grids.filter((s) => s.t >= t0 - 1e-6 && s.t <= t1 + 1e-6);
if (!inWin.length) {
// window between samples → use nearest grid
const mid = (t0 + t1) / 2;
inWin = [grids.reduce((a, b) => (Math.abs(b.t - mid) < Math.abs(a.t - mid) ? b : a))];
}
for (const s of inWin) for (let c = 0; c < GW * GH; c++) if (s.g[c] > occ[c]) occ[c] = s.g[c];
return occ;
};
// ad-hoc window query
const qIn = parseFloat(process.argv[3]),
qOut = parseFloat(process.argv[4]);
if (Number.isFinite(qIn) && Number.isFinite(qOut)) {
const a = analyze(
occWindow(qIn, qOut),
GW,
GH,
W,
H,
lumWindow(qIn, qOut),
lumSeriesWindow(qIn, qOut),
);
console.log(
`[safe-zones] window ${qIn}-${qOut}s: ${a.recommendation.toUpperCase()} coverage ${a.coverage}% clearer:${a.subject.clearerSide}`,
);
const z = a.zones;
for (const k of ["largest", "left", "right", "top"])
if (z[k]) console.log(` ${k}: ${z[k].wPct}%×${z[k].hPct}% @ (${z[k].xPct}%,${z[k].yPct}%)`);
console.log(JSON.stringify({ in: qIn, out: qOut, ...a }));
return;
}
const globalOcc = occWindow(-1e9, 1e9);
const globalLum = lumWindow(-1e9, 1e9);
const global = analyze(globalOcc, GW, GH, W, H, globalLum, lumSeriesWindow(-1e9, 1e9));
const windows = sentenceWindows(project).map((s) => {
const a = analyze(
occWindow(s.in, s.out),
GW,
GH,
W,
H,
lumWindow(s.in, s.out),
lumSeriesWindow(s.in, s.out),
);
return {
in: s.in,
out: s.out,
text: s.text.slice(0, 48),
coverage: a.coverage,
recommendation: a.recommendation,
clearerSide: a.subject.clearerSide,
zones: a.zones,
};
});
// ── v2: palette / optics / lighting from the mid frame + global grids ───────
let palette = null,
optics = null,
lighting = null;
try {
const occCellG = new Uint8Array(GW * GH);
for (let c = 0; c < GW * GH; c++) occCellG[c] = globalOcc[c] >= THRESH ? 1 : 0;
const midName = frames[Math.floor(frames.length / 2)];
const midBg = path.join(bgDir, midName);
if (hasBg && fs.existsSync(midBg)) {
palette = await scenePalette(midBg, occCellG, GW, GH);
// subject bbox in px from the global occupancy grid
let cx0 = GW,
cx1 = -1,
cy0 = GH,
cy1 = -1;
for (let y = 0; y < GH; y++)
for (let x = 0; x < GW; x++)
if (occCellG[y * GW + x]) {
if (x < cx0) cx0 = x;
if (x > cx1) cx1 = x;
if (y < cy0) cy0 = y;
if (y > cy1) cy1 = y;
}
const subjectBox =
cx1 >= 0
? {
x: (cx0 / GW) * W,
y: (cy0 / GH) * H,
w: ((cx1 - cx0 + 1) / GW) * W,
h: ((cy1 - cy0 + 1) / GH) * H,
}
: null;
optics = await sceneOptics(
project,
midBg,
path.join(fgDir, midName),
global.zones,
subjectBox,
W,
H,
);
lighting = sceneLighting(globalLum, occCellG, GW, GH);
}
} catch (e) {
console.error(`[safe-zones] scene optics skipped — ${e.message}`);
}
const out = {
width: W,
height: H,
fps,
grid: { cols: GW, rows: GH },
...global,
palette,
optics,
lighting,
windows,
};
fs.writeFileSync(path.join(project, "safe-zones.json"), JSON.stringify(out, null, 2));
const z = (n, zn) =>
zn
? `${n}: ${zn.wPct}%×${zn.hPct}% @ (${zn.xPct}%,${zn.yPct}%) [${zn.areaPct}%${zn.meanLuma != null ? ` · luma ${zn.meanLuma}${zn.bright ? " ⚠BRIGHT" : ""}` : ""}]`
: `${n}: —`;
console.log(
`[safe-zones] ${W}×${H} grid ${GW}×${GH} @ ${fps}fps · GLOBAL coverage ${global.coverage}% · clearer ${global.subject.clearerSide} · verdict ${global.recommendation.toUpperCase()}`,
);
console.log(
` ${z("largest", global.zones.largest)} | ${z("left", global.zones.left)} | ${z("right", global.zones.right)} | ${z("top", global.zones.top)}`,
);
if (global.recommendation === "embed") {
console.log(
`[safe-zones] ✅ EMBED — NARRATION planes go in the clean zones (prefer ${global.subject.clearerSide}/top).`,
);
if (global.heroAnchor)
console.log(
`[safe-zones] 🎯 HERO → centered ON the subject: plane ≈ x${global.heroAnchor.plane.xPct}% y${global.heroAnchor.plane.yPct}% w${global.heroAnchor.plane.wPct}% center · BIG (~0.220.34·h) · target ~3055% occlusion${global.heroAnchor.bandLuma != null ? ` · band luma ${global.heroAnchor.bandLuma}${global.heroAnchor.washoutRisk ? " ⚠WASHOUT RISK — see heroAnchor.note" : ""}` : ""}`,
);
if (global.heroBands)
console.log(
`[safe-zones] hero bands: best top ${global.heroBands.best.topPct}% (predicted occlusion ${global.heroBands.best.occPct}%) · bg-hero ${global.heroBands.feasible ? "FEASIBLE — keep the hero EMBEDDED (fg is last resort)" : "INFEASIBLE (no band ≤62%) → hero fg"}`,
);
if (global.zones.hugLeft || global.zones.hugRight)
console.log(
`[safe-zones] hugging zones (narration belongs HERE, abutting the silhouette): L ${global.zones.hugLeft ? global.zones.hugLeft.wPct + "%×" + global.zones.hugLeft.hPct + "%@x" + global.zones.hugLeft.xPct + "%" + (global.zones.hugLeft.bright ? "⚠bright" : "") : "—"} · R ${global.zones.hugRight ? global.zones.hugRight.wPct + "%×" + global.zones.hugRight.hPct + "%@x" + global.zones.hugRight.xPct + "%" + (global.zones.hugRight.bright ? "⚠bright" : "") : "—"}`,
);
} else {
console.log(
`[safe-zones] ⚠ FG — subject fills the frame; use caption_layer:"fg" (no clean region to embed behind).`,
);
}
if (palette)
console.log(
`[safe-zones] 🎨 palette: dominant ${palette.dominant.map((d) => d.hex).join(" ")} · accent suggestion ${palette.accentSuggestion || "— (no chromatic anchor; use the DNA default)"} · ${palette.temperature}`,
);
if (optics && optics.sharpnessRatio != null)
console.log(
`[safe-zones] 🔭 depth: bg/subject sharpness ${optics.sharpnessRatio} → embed text blur ${optics.suggestedTextBlurPx}px${optics.suggestedTextBlurPx ? " (match the scene's depth-of-field)" : " (scene is uniformly sharp)"}`,
);
if (lighting)
console.log(
`[safe-zones] 💡 light from ${lighting.lightFrom} → contact shadow offset (${lighting.shadow.dx}px, ${lighting.shadow.dy}px)`,
);
if (windows.length) {
console.log(`[safe-zones] per-sentence windows (place each group using ITS window's zones):`);
for (const w of windows)
console.log(
` [${w.in}-${w.out}s] ${w.recommendation.toUpperCase()} cov ${w.coverage}% clear:${w.clearerSide} ${w.zones.largest ? `best ${w.zones.largest.wPct}%×${w.zones.largest.hPct}%@(${w.zones.largest.xPct}%,${w.zones.largest.yPct}%)` : ""} "${w.text}"`,
);
}
console.log(`[safe-zones] → ${path.join(project, "safe-zones.json")}`);
}
main().catch((e) => {
console.error(`[safe-zones] (skipped — ${e.message})`);
process.exit(0);
});