Taste Distillation Skill
- Installs
- 3.9k
- Repo stars
- 313k
- Security scans passed
- 3/3
- Repo updated
- Nov 23, 2026
TL;DR
Measures reference videos into a reusable look pack with a colour grade LUT, cut rhythm, hero stills and overlay plates for later edits.
npx skills add https://github.com/affaan-m/ECC --skill taste-distillationTry it first through the Skillselion MCP - nothing to install, nothing on disk.
1. Add the remote connector:
claude mcp add --transport http skillselion https://mcp.skillselion.com/mcp2. Ask your agent:
Use Skillselion load_skill to load skill:affaan-m/ecc#taste-distillation (Taste Distillation) and follow it.Try it first through the Skillselion MCP - nothing to install, nothing on disk.
1. Add this URL as a custom connector (Claude.ai, ChatGPT or Cursor):
https://mcp.skillselion.com/mcp2. Ask your agent:
Use Skillselion load_skill to load skill:affaan-m/ecc#taste-distillation (Taste Distillation) and follow it.What taste-distillation covers
- Colour grade measured as a 3D LUT
- Shot-length distribution captures cut rhythm
- Separate style packs per genre, with no cross-use of measurements
taste-distillation by the numbers
| All-time installs | 3,912 | skills.sh registry |
|---|---|---|
| Repo stars | ★ 313k | GitHub |
| Security audit | 3 / 3 scanners passed | skills.sh audit |
| Repo last updated | November 23, 2026 | GitHub |
| Repository | affaan-m/ECC ↗ | |
Data as of Nov 29, 2026 (Skillselion catalog sync)
What files ship with taste-distillation?
Taste Distillation
This standalone skill ships its implementation in scripts/; use taste-application for the subsequent generated or local-take edit. Keep each named genre in its own pack. Measurements from Flash Ethereal must not be silently reused for Fluid Sketch or 3D Cyber Glitch. A measured zero is valid data; distinguish it from an absent field.
Local dependencies are in scripts/requirements.txt. Separately authorized provider work also needs scripts/requirements-live.txt, credentials and explicit TASTE_FORGE_ALLOW_LIVE=1. --dry-run does not read credentials or submit jobs. Never infer that a workflow was saved from a local endpoint name; use the actual provider-side workflow or request evidence.
Turn reference videos into a style pack: a folder of measurements and assets that later stages consume deterministically.
When to Activate
- "capture the look of these clips" / "distill the vibe" / "make this repeatable"
- User has reference footage and wants a LUT, a grade, or matching pacing
- Building a library of looks partitioned by genre
- Any request where the answer would otherwise be "describe the style in a prompt"
The Core Finding
Prompting cannot deliver a grade. Measurement can.
Measured on real footage: three paid generations with escalating colour direction moved midtone a\ from +1.9 → +2.8 → +0.3 against a +24.9 target, and contrast never left ~19 against a 34.7 target. Applying a measured pack to the same footage hit chroma MAE 1.88 and contrast 33.7* in one deterministic pass, for free.
So the split is: the model supplies content, motion and lighting structure; the pack supplies the look. Colour words in a generation prompt are worse than useless — they cost money and push the render away from the neutral base the LUT wants. Say so explicitly in the prompt: "Colour: none. Render neutral. Grading is applied afterwards."
What a Pack Contains
stylepacks/<genre>/
grade.json measured colour statistics (see below)
cadence.json every detected shot boundary + the derived distribution
look.cube 33^3 LUT, drag straight into Resolve as a node LUT
spec.json VLM description, grounded in the measurements
grounding.txt the measured facts fed to the VLM
stills/ full-res frames from the longest shots (conditioning images)
plates/ screen-blend overlay elements lifted onto black
props/ minted GLB meshes
pack.json manifestRunning It
python mint.py --genre <name> --refs a.mov b.mov c.mov # offline, no API key
python distill.py --genre <name> # one VLM callmint.py is pure numeric analysis — no network, no key, deterministic, so a pack can be regenerated rather than backed up.
The Measurements That Matter
Chroma by luminance zone, not globally
Colour identity usually lives in one luminance band. A global a\/b\ offset mathematically cannot represent split-toning. Measure chroma inside zones (L* edges [0,15,35,55,75,100]).
A real signature: violet at L\25 (a\ +24.9, b\ −17.5), near-neutral at both ends. Reporting only the darkest and lightest zones calls that "uniform cast" — always print the whole curve.*
Median + MAD, never mean + std
Chroma in real reference sets is strongly right-skewed. On one measured reel the mean midtone chroma was 36.9 against a median of 17.5, so a mean-based LUT pushed colour ~3x harder than the material warranted.
Contrast is std(L\*), not white minus black
The white−black range is ~100 on almost any real footage and discriminates nothing.
Background share is a first-class statistic
Record the share of pixels below L\*10. No moment of the distribution can see it: a clip can hold the right mean, std and chroma while its blacks have been lifted into grey. This is exactly how a grade once scored MAE 1.88 / contrast 33.7 while the actual frame was a muddy purple mess.
Mask the interface before measuring
Screen-recorded references carry static furniture — letterbox bars, a status bar, a like icon, caption text. All of it lands in the statistics as if it were the look: black bars inflate shadow weight, a red heart skews a\ toward magenta. Temporal variance separates them cleanly* — the footage moves, the interface does not — so no hand-tuned crop is needed. On real material this keeps ~65% of pixels.
Cadence needs an adaptive threshold
The right content-detector threshold is material-dependent: a high-contrast action reference cuts hard enough for 30, a moody one hides its cuts under it. Sweep descending thresholds and take the highest one that still recovers ≥90% of the shots the most sensitive setting finds — that biases toward real cuts over noise. Reject thresholds implying an absurd cut rate (>100/min); continuous camera moves trip the detector every frame.
Run the whole sweep in one decode pass with a shared StatsManager. The naive version re-decodes per threshold, which on 60fps source is the difference between seconds and minutes.
Overlay Plates: Assets, Not Screenshots
A still is a whole frame — compositing one just puts a second picture on top. A plate is the reference's graphic vocabulary (flares, streaks, glitch fragments) lifted onto black so it screen-blends with no keying.
Two traps, both hit on real material:
- Absolute thresholds fail. On a bright reference an
L>55 AND chroma>12selection takes ~90% of frame, and the "plate" is the picture — including a recognisable face. Select by percentile (~top 3%) and reject any plate covering more than ~22% of frame. - Rank by separation, not by brightness. "Share of bright saturated pixels" ranks a washed-out frame top and a black frame with one intense flare — the actual signature — near the bottom. Score
p99.5(energy) / median(energy).
Also mask before scoring: burnt-in typography is bright, saturated and high-contrast, so an unmasked run yields a perfect plate of someone else's title card.
Grounding the VLM
Feed the measurements into the system prompt before asking for a description. Ungrounded, a VLM will report "no apparent colour grading, neutral" on footage with a +24.9 a\* cast. Grounded, it describes the cast correctly and infers the secondary accent independently.
Ban hedging words (varied, mixed, dynamic, some, often, neutral, or) — a model cannot render "varied lighting". Enforce the ban in code, not just in the prompt: it was violated in roughly one run in three. Re-ask per-field, keep the least-hedged answer after N attempts rather than failing.
Caveat worth stating to the user: once the spec is grounded in the measurements it is no longer an independent check on them.
LUT Baking Gotchas
- A LUT can only encode a per-pixel RGB function. Anything distribution-dependent (histogram matching, percentile anchors) must be reduced to a constant before baking, or it silently measures the uniform LUT grid instead of the footage.
cv2.cvtColor(LAB2RGB)clamps internally, so an out-of-gamut test using it reports 0%. Convert Lab→linear sRGB by hand; a real measurement was 83.3% OOG.- Offset chroma transfer, not affine. Affine divides by the source σ and overshoots — on real footage it flipped b\* to +11.6 against a −17.5 target. Offset took MAE from 6.23 to 2.13.
- Gamut compression cost 3.8x runtime for identical MAE. Make it opt-in.
Anti-Patterns
| Don't | Why |
|---|---|
| Tune against synthetic test footage | Cost four separate wrong conclusions on one project; real footage overturned every one |
| Trust MAE alone | 1.88 MAE looked like success on a visibly broken frame |
| Use mean/std for chroma | Right-skewed; pushes ~3x too hard |
| Compare only endpoint zones | Both ends are near-neutral by construction |
| Describe the look and stop | The spec is for content and structure; the pack is for colour |
Handoff
The pack is the interface. Once it exists, use the taste-application skill to generate and assemble against it, or hand look.cube to a colourist directly.
Bundled Code
scripts/ in this skill is a working implementation, not pseudocode. It has no project-specific assumptions: point it at any reference videos and it produces a pack.
pip install -r scripts/requirements.txt
export FAL_KEY=... # only needed for the stages that call falEvery network call is stubbed under TASTE_FORGE_DRY_RUN=1 or --dry-run, so the plan, prompts, track layout and manifest can be inspected without spending.
#!/usr/bin/env python3
"""Mint a style pack from reference videos. Stage 1 of taste-forge.
This stage is deliberately offline: no API keys, no model calls, no network.
Everything here is numeric analysis of the reference footage, which means it
is cheap, deterministic, and re-runnable. The expensive generative work
happens later, against the pack this produces.
python mint.py --genre flashethereal --refs a.mp4 b.mp4 c.mp4
Re-running with the same references reproduces the same pack byte-for-byte
apart from timestamps, so a pack can be regenerated rather than backed up.
"""
from __future__ import annotations
import argparse
import sys
from pathlib import Path
import numpy as np
from taste import cadence as cad_mod
from taste import frames as frame_mod
from taste import grade as grade_mod
from taste import pack as pack_mod
from taste import plates as plate_mod
def mint(
genre: str,
refs: list[str],
root: str = "stylepacks",
lut_size: int = 33,
strength: float = 1.0,
frames_per_ref: int = 48,
max_stills: int = 12,
mask_ui: bool = True,
) -> pack_mod.StylePack:
sp = pack_mod.create(genre, root=root)
print(f"minting '{genre}' from {len(refs)} reference(s) -> {sp.dir}")
pooled_pixels: list[np.ndarray] = []
pooled_frames: list[list[np.ndarray]] = []
noise_frames: list[np.ndarray] = []
cadences: list[cad_mod.Cadence] = []
mask_report: list[str] = []
for i, ref in enumerate(refs):
ref_path = Path(ref)
if not ref_path.exists():
print(f" !! missing reference, skipping: {ref}", file=sys.stderr)
continue
ref_id = f"genre1_{i + 1}" if i else "genre1"
print(f" [{ref_id}] {ref_path.name}")
fr = frame_mod.sample_frames(ref_path, n=frames_per_ref)
if mask_ui:
m = frame_mod.content_mask(fr)
y0, y1, x0, x1 = frame_mod.mask_bbox(m)
pooled_pixels.append(frame_mod.apply_mask(fr, m))
noise_frames.extend(f[y0:y1, x0:x1] for f in fr[:8])
mask_report.append(f"{100 * m.mean():.0f}%")
print(f" masked to {100 * m.mean():.0f}% moving pixels "
f"(dropped static UI / letterbox)")
else:
pooled_pixels.append(np.concatenate([f.reshape(-1, 3) for f in fr]))
noise_frames.extend(fr[:8])
pooled_frames.append(fr)
c = cad_mod.detect(ref_path)
cadences.append(c)
print(f" {c.n_shots} shots, mean {c.mean_shot:.2f}s, {c.cuts_per_min:.0f} cuts/min")
# Stills come from the longest shots of each reference, spread across
# the whole set rather than taken from whichever ref happens to be first.
ts = cad_mod.keyframe_timestamps(c, limit=max(1, max_stills // max(1, len(refs))))
wrote = frame_mod.export_stills(ref_path, sp.stills_dir, ts, prefix=ref_id)
print(f" {len(wrote)} stills")
sp.add_ref(ref_id, str(ref_path), c.total_duration, c.n_shots)
if not pooled_pixels:
raise SystemExit("no readable references - nothing to mint")
print(" analyzing grade across pooled frames ...")
stacked = np.concatenate(pooled_pixels, axis=0)
g = grade_mod.analyze_pixels(stacked, noise_frames=noise_frames)
merged = cad_mod.merge(cadences)
print(f" baking {lut_size}^3 LUT ...")
cube = grade_mod.bake_cube(g, size=lut_size, strength=strength, title=genre)
grade_mod.write_cube(sp.lut_path, cube)
# Overlay plates - the composable assets, as distinct from the stills,
# which only ever condition the generator.
plate_frames = []
for pix in pooled_frames[:3]:
plate_frames.extend(pix)
plate_dir = sp.dir / "plates"
made = plate_mod.mint_plates(plate_frames, plate_dir, noise_sigma=g.noise_sigma)
print(f" minted {len(made)} overlay plate(s) -> {plate_dir}")
sp.write_json(sp.grade_path, g.to_dict())
cad_mod.save(merged, sp.cadence_path)
sp.manifest["mint"] = {
"lut_size": lut_size,
"strength": strength,
"pixels_analyzed": int(stacked.shape[0]),
"ui_masked": mask_ui,
}
sp.save()
_report(g, merged, sp)
return sp
_HUE_WHEEL = [
(0, "magenta"), (30, "warm pink"), (60, "amber"), (90, "yellow-green"),
(120, "green"), (150, "teal-green"), (180, "cyan"), (210, "steel blue"),
(240, "blue"), (270, "violet"), (300, "periwinkle violet"), (330, "orchid"),
]
def _hue_name(a: float, b: float) -> str:
"""Rough perceptual name for a Lab a*/b* direction."""
import math
if (a * a + b * b) ** 0.5 < 3.0:
return "near-neutral"
ang = math.degrees(math.atan2(b, a)) % 360.0
return min(_HUE_WHEEL, key=lambda h: min(abs(ang - h[0]), 360 - abs(ang - h[0])))[1]
def _report(g: grade_mod.GradeStats, c: cad_mod.Cadence, sp: pack_mod.StylePack) -> None:
print(f"\n === {sp.name} ===")
print(f" black/white pt : {g.black_point:.1f} / {g.white_point:.1f} (L*)")
print(f" contrast : {g.contrast:.1f}")
print(f" saturation : {g.saturation:.1f}")
print(f" cast : warmth {g.warmth:+.1f} tint {g.tint:+.1f}")
print(f" grain sigma : {g.noise_sigma:.4f}")
print(f" palette : {', '.join(h for h, _ in g.palette[:5])}")
if g.zones:
# Report the whole curve, not just the endpoints. Comparing only the
# darkest and lightest zones is actively misleading: both ends tend
# toward neutral (there is little room for chroma near black or near
# white), so a look whose entire color identity lives in the midtones
# reads as "uniform cast" when it is anything but.
print(" chroma by zone :")
peak_i, peak_c = 0, 0.0
for i, (zl, z) in enumerate(zip(grade_mod.ZONE_CENTERS, g.zones)):
chroma = (z[0] ** 2 + z[2] ** 2) ** 0.5
if chroma > peak_c:
peak_i, peak_c = i, chroma
bar = "#" * min(40, int(chroma / 1.5))
print(f" L~{zl:5.1f} a*{z[0]:+7.2f} b*{z[2]:+7.2f} {bar}")
pz = g.zones[peak_i]
tail = (
", neutral at both ends"
if peak_i not in (0, len(g.zones) - 1)
else ""
)
print(
f" signature : {_hue_name(pz[0], pz[2])} at "
f"L~{grade_mod.ZONE_CENTERS[peak_i]:.0f}{tail}"
)
print(f" cadence : {c.n_shots} shots, mean {c.mean_shot:.2f}s, "
f"{c.cuts_per_min:.0f} cuts/min, variance {c.rhythm_variance:.2f}")
print(f" stills / props : {len(sp.stills())} / {len(sp.props())}")
plates = sorted((sp.dir / "plates").glob("*.png")) if (sp.dir / "plates").exists() else []
print(f" overlay plates : {len(plates)} ({', '.join(p.stem for p in plates[:4])}"
f"{' ...' if len(plates) > 4 else ''})")
print(f"\n pack -> {sp.dir}")
print(f" LUT -> {sp.lut_path} (drag into Resolve as a node LUT)")
def main() -> None:
ap = argparse.ArgumentParser(description="Mint a style pack from reference videos.")
ap.add_argument("--genre", required=True, help="pack name, e.g. flashethereal")
ap.add_argument("--refs", required=True, nargs="+", help="reference video paths")
ap.add_argument("--root", default="stylepacks")
ap.add_argument("--lut-size", type=int, default=33, choices=[17, 25, 33, 65])
ap.add_argument("--strength", type=float, default=1.0,
help="0-1; how hard to push toward the reference look")
ap.add_argument("--frames-per-ref", type=int, default=48)
ap.add_argument("--max-stills", type=int, default=12)
ap.add_argument("--no-mask-ui", action="store_true",
help="disable temporal-variance masking of static screen-recording UI")
a = ap.parse_args()
mint(a.genre, a.refs, a.root, a.lut_size, a.strength, a.frames_per_ref,
a.max_stills, mask_ui=not a.no_mask_ui)
if __name__ == "__main__":
main()
# Install only for separately authorized provider execution.
-r requirements.txt
fal-client
numpy
opencv-python-headless
scenedetect[opencv]
requests
"""Final edit: takes in, finished video out.
This is the last stage of the original design - distil taste, mint assets,
generate against them, then *cut the thing together*. Everything upstream
produces material; this produces the deliverable.
Three inputs the earlier stages did not handle:
* **overlay images** composited over the cut, so minted stills, grain plates
and graphic elements can ride on top;
* **a base video to supplement**, where the point is not to generate a new
piece but to push an existing one toward the distilled look and intercut
new material into it;
* **the cut itself**, at the reference's measured cadence rather than at
whatever length the generator happened to emit.
"""
from __future__ import annotations
import json
import subprocess
from pathlib import Path
from . import cadence as cad_mod
from . import frames as frame_mod
def _run(cmd: list[str]) -> None:
proc = subprocess.run(cmd, capture_output=True, text=True)
if proc.returncode != 0:
raise RuntimeError(f"ffmpeg failed: {' '.join(cmd[:6])}...\n{proc.stderr[-400:]}")
def cut_take(
src: str | Path,
shots: list[dict],
dest_dir: str | Path,
prefix: str = "shot",
fps: float | None = None,
) -> list[Path]:
"""Slice one generated take into its planned sub-shots.
Re-encodes rather than stream-copying. Stream copy can only cut on
keyframes, and at a mean shot length of 0.78s that rounds every boundary
to the nearest GOP - which is precisely the rhythm this whole pipeline
exists to preserve.
"""
src, dest_dir = Path(src), Path(dest_dir)
dest_dir.mkdir(parents=True, exist_ok=True)
info = frame_mod.probe(src)
r = fps or info.fps or 24.0
out: list[Path] = []
for i, sh in enumerate(shots):
start, dur = float(sh["start"]), float(sh["duration"])
if start >= info.duration - 0.02:
break
dur = min(dur, max(0.04, info.duration - start))
dst = dest_dir / f"{prefix}_{i:03d}.mp4"
_run([
"ffmpeg", "-nostdin", "-loglevel", "error", "-y",
"-ss", f"{start:.4f}", "-i", str(src), "-t", f"{dur:.4f}",
"-vf", f"fps={r:.6f},setpts=PTS-STARTPTS",
"-an", "-c:v", "libx264", "-crf", "14", "-preset", "veryfast",
"-pix_fmt", "yuv420p", str(dst),
])
out.append(dst)
return out
def overlay(
clip: str | Path,
image: str | Path,
dst: str | Path,
opacity: float = 0.35,
scale: float = 0.55,
position: str | tuple[float, float] = "center",
blend: str = "screen",
width: int | None = None,
height: int | None = None,
rotate: float = 0.0,
) -> Path:
"""Composite a plate over a clip as a placed ELEMENT, not a full-frame wash.
The earlier version stretched every plate to fill the frame with
``scale2ref``. That is right for a diffuse wash and wrong for everything
else: a tightened flare stretched edge to edge reads as a smear, and an
untightened one - 97% empty by construction - reads as a coloured dot
parked in the middle of the shot. Both showed up in a delivered cut.
So the element is scaled to a fraction of frame width, optionally rotated,
placed at a point, and only then blended. ``position`` is either a named
anchor or an ``(x, y)`` pair in frame fractions of the element's top-left
corner, which lets a caller vary placement per shot instead of stamping
the same mark in the same place every time.
``screen`` is the default because plates are premultiplied against black,
so screen drops their blacks for free and no matte is needed.
"""
clip, image, dst = Path(clip), Path(image), Path(dst)
if width is None or height is None:
from . import frames as _fm
info = _fm.probe(clip)
width, height = info.width, info.height
# Resolve the element's pixel size here rather than in ffmpeg expressions.
# pad() rejects a negative offset and cannot pad to a size smaller than its
# input, so an element that lands oversized or off-frame kills the whole
# filtergraph - which it did on the first attempt.
import cv2 as _cv2
_im = _cv2.imread(str(image), _cv2.IMREAD_UNCHANGED)
if _im is None:
raise ValueError(f"cannot read overlay image: {image}")
ih0, iw0 = _im.shape[:2]
ew = max(2, int(width * max(0.02, min(1.0, scale))))
eh = max(2, int(ew * ih0 / max(1, iw0)))
if eh > height: # fit tall elements to the frame instead of overflowing
eh = height
ew = max(2, int(eh * iw0 / max(1, ih0)))
ew, eh = min(ew, width), min(eh, height)
if isinstance(position, tuple):
px = int(width * position[0])
py = int(height * position[1])
else:
anchors = {
"center": (0.5, 0.5), "top": (0.5, 0.12), "bottom": (0.5, 0.88),
"left": (0.14, 0.5), "right": (0.86, 0.5),
"topleft": (0.16, 0.16), "topright": (0.84, 0.16),
"bottomleft": (0.16, 0.84), "bottomright": (0.84, 0.84),
}
ax, ay = anchors.get(position, (0.5, 0.5))
px, py = int(width * ax), int(height * ay)
# Rotation grows the bounding box, so bake it in before computing offsets.
if rotate:
import math as _math
c, sn = abs(_math.cos(rotate)), abs(_math.sin(rotate))
rw, rh = int(ew * c + eh * sn), int(ew * sn + eh * c)
if rw > width or rh > height:
k = min(width / max(1, rw), height / max(1, rh))
ew, eh = max(2, int(ew * k)), max(2, int(eh * k))
rw, rh = int(ew * c + eh * sn), int(ew * sn + eh * c)
ew_f, eh_f = rw, rh
else:
ew_f, eh_f = ew, eh
ox = max(0, min(width - ew_f, px - ew_f // 2))
oy = max(0, min(height - eh_f, py - eh_f // 2))
a = max(0.0, min(1.0, opacity))
rot = (f"rotate={rotate:.4f}:fillcolor=black@0:"
f"ow=rotw({rotate:.4f}):oh=roth({rotate:.4f}),") if rotate else ""
# Scale, rotate, fade, then pad out to full frame on transparent black so a
# full-frame blend only lights up where the element actually sits.
fc = (
f"[1:v]format=rgba,scale={ew}:{eh},{rot}"
f"colorchannelmixer=aa={a:.3f},"
f"pad={width}:{height}:{ox}:{oy}:black@0,"
# Blend RGB planes explicitly: screening neutral YUV chroma produces
# a magenta cast even where the overlay is transparent. Premultiply
# alpha after applying opacity so transparent RGB stays invisible.
f"format=gbrap,premultiply=inplace=1,format=gbrp[ov];"
f"[0:v]format=gbrp[base];"
f"[base][ov]blend=all_mode={blend or 'screen'}:shortest=1,format=yuv420p"
)
_run([
"ffmpeg", "-nostdin", "-loglevel", "error", "-y",
# Keep the still alive until the video ends; shortest=1 otherwise
# terminates every shot after the image's single decoded frame.
"-i", str(clip), "-loop", "1", "-i", str(image), "-filter_complex", fc,
"-c:v", "libx264", "-crf", "14", "-preset", "veryfast",
"-pix_fmt", "yuv420p", "-an", str(dst),
])
return Path(dst)
def concat(clips: list[str | Path], dst: str | Path, fps: float = 24.0) -> Path:
"""Join clips into one file. Assumes they already share codec and size."""
clips = [Path(c) for c in clips]
if not clips:
raise ValueError("nothing to concatenate")
dst = Path(dst)
dst.parent.mkdir(parents=True, exist_ok=True)
listing = dst.parent / f"{dst.stem}_concat.txt"
listing.write_text("".join(f"file '{c.resolve().as_posix()}'\n" for c in clips))
_run([
"ffmpeg", "-nostdin", "-loglevel", "error", "-y",
"-f", "concat", "-safe", "0", "-i", str(listing),
"-vf", f"fps={fps:.6f}",
"-c:v", "libx264", "-crf", "16", "-pix_fmt", "yuv420p", str(dst),
])
listing.unlink(missing_ok=True)
return dst
def normalize(
src: str | Path,
dst: str | Path,
width: int,
height: int,
fps: float,
crop: tuple[float, float, float, float] | None = None,
fit: str = "pad",
) -> Path:
"""Force a clip to one size and rate so it can be concatenated with others.
Generated takes and a supplied base video rarely agree on resolution or
frame rate. Scaling with letterbox padding rather than cropping keeps the
supplied footage intact, since the caller chose it deliberately.
"""
dst = Path(dst)
dst.parent.mkdir(parents=True, exist_ok=True)
pre = ""
if crop:
# Crop BEFORE scaling, in fractions of the source frame.
#
# Screen-recorded references carry the capturing app's interface baked
# into the pixels - a like button, a view counter, a comment bubble.
# Borrowing a shot from that footage without cropping ships someone
# else's UI in the finished piece, which is exactly what happened in an
# earlier cut. Fractions rather than pixels because the crop is measured
# on downscaled analysis frames and applied to full-resolution video.
fy0, fy1, fx0, fx1 = crop
pre = (f"crop=w=iw*{max(0.0, fx1 - fx0):.6f}:h=ih*{max(0.0, fy1 - fy0):.6f}"
f":x=iw*{fx0:.6f}:y=ih*{fy0:.6f},")
if fit == "cover":
# Scale up until the frame is covered, then centre-crop the excess.
#
# Padding is the safe default and the wrong one for portrait source in
# a landscape cut. Screen-recorded reference is 9:16; after the UI crop
# it is narrower still, and padding that into 16:9 left roughly 60% of
# frame as black bars - one delivered shot was very nearly an empty
# rectangle. It also poisoned the background measurement, since bars
# are pure black and count as unlit background.
#
# Covering loses the sides of the source, which is the correct trade:
# the subject is centre-framed in this material, and a full frame of
# real picture beats a letterboxed thumbnail of all of it.
geom = (f"scale={width}:{height}:force_original_aspect_ratio=increase,"
f"crop={width}:{height}")
else:
geom = (f"scale={width}:{height}:force_original_aspect_ratio=decrease,"
f"pad={width}:{height}:(ow-iw)/2:(oh-ih)/2:black")
vf = pre + geom + f",setsar=1,fps={fps:.6f}"
_run([
"ffmpeg", "-nostdin", "-loglevel", "error", "-y", "-i", str(src),
"-vf", vf, "-an", "-c:v", "libx264", "-crf", "14", "-preset", "veryfast",
"-pix_fmt", "yuv420p", str(dst),
])
return dst
def weave(generated: list[Path], base: list[Path], ratio: float = 0.5) -> list[Path]:
"""Interleave generated shots with shots cut from a supplied base video.
``ratio`` is the share of the finished cut that should come from the base
footage. Shots alternate on a running quota rather than strictly A/B, so
a 0.25 ratio yields occasional base shots scattered through generated
material instead of a rigid every-fourth pattern.
"""
if not base:
return list(generated)
if not generated:
return list(base)
out: list[Path] = []
gi = bi = 0
debt = 0.0
while gi < len(generated) or bi < len(base):
take_base = debt >= 1.0 and bi < len(base)
if not take_base and gi >= len(generated):
take_base = bi < len(base)
if take_base:
out.append(base[bi]); bi += 1; debt -= 1.0
else:
if gi >= len(generated):
break
out.append(generated[gi]); gi += 1; debt += ratio / max(1e-6, 1.0 - ratio)
return out
def write_manifest(path: str | Path, payload: dict) -> Path:
path = Path(path)
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(payload, indent=2), encoding="utf-8")
return path
"""Edit-rhythm distillation: where a reference cuts, and how often.
Cut rhythm is the half of "taste" that never survives a text prompt. A VLM
asked to describe a reference will happily say "fast-paced editing", which is
useless downstream. Actual shot boundaries give a distribution you can
generate against: how long shots run, how much that varies, where cuts land.
The output drives two things:
* how many shots ``apply.py`` asks the video model for, and how long each
one should be;
* the timeline emitted for Resolve, so the finished cut inherits the
reference's pacing instead of a default 5-seconds-per-clip layout.
"""
from __future__ import annotations
import json
from dataclasses import dataclass, asdict, field
from pathlib import Path
import numpy as np
from .frames import probe
@dataclass
class Shot:
index: int
start: float
end: float
@property
def duration(self) -> float:
return self.end - self.start
def to_dict(self) -> dict:
return {
"index": self.index,
"start": round(self.start, 4),
"end": round(self.end, 4),
"duration": round(self.duration, 4),
}
@dataclass
class Cadence:
"""Distilled pacing of a reference set."""
shots: list[dict] = field(default_factory=list)
mean_shot: float = 0.0
median_shot: float = 0.0
p25_shot: float = 0.0
p75_shot: float = 0.0
min_shot: float = 0.0
max_shot: float = 0.0
cuts_per_min: float = 0.0
rhythm_variance: float = 0.0 # std/mean; low = metronomic, high = jazzy
total_duration: float = 0.0
fps: float = 24.0
n_shots: int = 0
def to_dict(self) -> dict:
return asdict(self)
@classmethod
def from_dict(cls, d: dict) -> "Cadence":
known = {k: v for k, v in d.items() if k in cls.__dataclass_fields__}
return cls(**known)
def plan_shots(self, target_duration: float) -> list[float]:
"""Propose shot durations filling ``target_duration`` at this cadence.
Samples from the reference's own shot-length distribution rather than
using the mean, so the result inherits its rhythm variance instead of
flattening into evenly spaced clips.
"""
durations = [s["duration"] for s in self.shots if s.get("duration", 0) > 0.05]
if not durations:
durations = [max(self.mean_shot, 1.0)]
rng = np.random.default_rng(7)
pool = np.asarray(durations, dtype=float)
out: list[float] = []
acc = 0.0
while acc < target_duration:
d = float(rng.choice(pool))
remaining = target_duration - acc
if remaining < d * 0.5:
break
d = min(d, remaining)
out.append(round(d, 3))
acc += d
if not out:
out = [round(target_duration, 3)]
return out
_SWEEP = (30.0, 24.0, 19.0, 15.0, 12.0, 9.0)
_MAX_CUTS_PER_MIN = 100.0
def _sweep_detector(path: str | Path, thresholds, min_len_frames: int) -> dict:
"""Run the whole threshold sweep with a single decode pass.
The naive version calls scenedetect once per threshold, which re-decodes
the file every time - on 60fps source that is the difference between
seconds and minutes. A shared StatsManager caches the per-frame content
metric, so only the first pass computes it and the rest just re-threshold
the cached values. Frames are also downscaled before analysis: shot
boundaries are a global-content signal and survive it intact.
"""
from scenedetect import open_video, SceneManager, StatsManager, ContentDetector
stats = StatsManager()
out: dict[float, list] = {}
for t in thresholds:
video = open_video(str(path))
# Cap the long edge around 480px for the detector; large frames cost
# decode time without improving boundary detection.
try:
video.set_downscale_factor() # auto
except Exception:
pass
sm = SceneManager(stats_manager=stats)
sm.auto_downscale = True
sm.add_detector(
ContentDetector(threshold=t, min_scene_len=min_len_frames)
)
sm.detect_scenes(video, show_progress=False)
out[t] = sm.get_scene_list()
return out
def _run_detector(path: str | Path, threshold: float, min_len_frames: int) -> list[tuple]:
return _sweep_detector(path, [threshold], min_len_frames)[threshold]
def detect(
path: str | Path,
threshold: float | None = None,
min_scene_len: float = 0.25,
) -> Cadence:
"""Detect shot boundaries with PySceneDetect's content detector.
``threshold`` is HSV content delta. Passing ``None`` (the default) runs an
adaptive sweep instead of trusting one fixed number, because the right
value is material-dependent: a high-contrast action reference cuts hard
enough for 30 to work, while a moody low-contrast one hides its cuts under
it entirely. On a six-cut test reference, the library default of 27 found
only five; the sweep finds all six.
The sweep picks the *highest* (most conservative) threshold that still
recovers at least 90% of the shots the most sensitive setting finds. That
biases toward real cuts over noise-triggered false positives.
"""
info = probe(path)
fps = info.fps or 24.0
min_len_frames = max(1, int(min_scene_len * fps))
if threshold is not None:
scenes = _run_detector(path, threshold, min_len_frames)
else:
counts = _sweep_detector(path, _SWEEP, min_len_frames)
dur = max(info.duration, 1e-3)
def rate(t: float) -> float:
return 60.0 * len(counts[t]) / dur
# Continuous camera moves (a slow push-in, a morph, a whip pan) can
# trip the content detector on every frame. Thresholds implying an
# absurd cut rate are treated as noise rather than as ground truth.
plausible = [t for t in _SWEEP if rate(t) <= _MAX_CUTS_PER_MIN]
pool = plausible or [_SWEEP[0]]
best_n = max(len(counts[t]) for t in pool)
chosen = pool[-1]
for t in pool: # descending sensitivity order
if len(counts[t]) >= 0.9 * best_n:
chosen = t
break
scenes = counts[chosen]
shots: list[Shot] = []
for i, (start, end) in enumerate(scenes):
shots.append(Shot(index=i, start=start.get_seconds(), end=end.get_seconds()))
# A single-shot reference (or a detector miss) still deserves valid output.
if not shots:
shots = [Shot(index=0, start=0.0, end=info.duration)]
return _summarize(shots, fps=fps, total=info.duration)
def _summarize(shots: list[Shot], fps: float, total: float) -> Cadence:
durs = np.asarray([s.duration for s in shots], dtype=float)
durs = durs[durs > 0]
if len(durs) == 0:
durs = np.asarray([total or 1.0])
mean = float(durs.mean())
return Cadence(
shots=[s.to_dict() for s in shots],
mean_shot=round(mean, 4),
median_shot=round(float(np.median(durs)), 4),
p25_shot=round(float(np.percentile(durs, 25)), 4),
p75_shot=round(float(np.percentile(durs, 75)), 4),
min_shot=round(float(durs.min()), 4),
max_shot=round(float(durs.max()), 4),
cuts_per_min=round(60.0 * len(shots) / total, 3) if total > 0 else 0.0,
rhythm_variance=round(float(durs.std() / mean), 4) if mean > 0 else 0.0,
total_duration=round(total, 3),
fps=round(fps, 4),
n_shots=len(shots),
)
def merge(cadences: list[Cadence]) -> Cadence:
"""Pool several references into one cadence profile.
Shot lists are concatenated with times offset so the pooled *distribution*
is meaningful; absolute timings across different references are not.
"""
if not cadences:
return Cadence()
if len(cadences) == 1:
return cadences[0]
shots: list[Shot] = []
offset = 0.0
for c in cadences:
for s in c.shots:
shots.append(
Shot(index=len(shots), start=s["start"] + offset, end=s["end"] + offset)
)
offset += c.total_duration
fps = float(np.median([c.fps for c in cadences]))
return _summarize(shots, fps=fps, total=offset)
def keyframe_timestamps(cadence: Cadence, per_shot: float = 0.5, limit: int = 12) -> list[float]:
"""Representative timestamps: a point ``per_shot`` of the way through each shot.
Longest shots first, because those establish the look, whereas short ones
are often motion-blurred transition frames.
"""
ranked = sorted(cadence.shots, key=lambda s: -s.get("duration", 0.0))
out = [round(s["start"] + s.get("duration", 0.0) * per_shot, 3) for s in ranked[:limit]]
return sorted(out)
def save(cadence: Cadence, path: str | Path) -> Path:
path = Path(path)
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(cadence.to_dict(), indent=2), encoding="utf-8")
return path
def load(path: str | Path) -> Cadence:
return Cadence.from_dict(json.loads(Path(path).read_text(encoding="utf-8")))
# Durations the video model will actually accept, read off the endpoint UI.
# Seedance rejects anything below 4s; earlier code sent 3 and would have
# failed every call.
GEN_DURATIONS = (4, 5, 6, 7, 8, 9, 10, 11, 12)
def quantize_gen_duration(seconds: float) -> int:
"""Round up to the shortest generation length the model will accept."""
for d in GEN_DURATIONS:
if d >= seconds - 1e-6:
return d
return GEN_DURATIONS[-1]
def plan_takes(cadence: "Cadence", target_duration: float, take_len: float = 5.0) -> list[dict]:
"""Group the shot plan into generated TAKES, then cut within each take.
Asking a video model for one clip per shot is the obvious approach and the
wrong one. This cadence averages 0.78s per shot while the model refuses to
generate anything under 4s, so a shot-per-clip plan generates 36 seconds to
use 10 - 28% efficiency, twelve API calls, and twelve unrelated clips
stitched into what should read as a continuous piece.
Editors do not work that way: they roll a longer take and cut inside it.
Grouping shots into ~5s takes recovers close to full efficiency, cuts the
call count by roughly six, and gives consecutive shots real visual
continuity because they come from the same generation.
Returns one dict per take::
{"index": 0, "gen_duration": 5, "used": 4.8,
"shots": [{"start": 0.0, "duration": 0.78}, ...]}
"""
plan = cadence.plan_shots(target_duration)
takes: list[dict] = []
cur: list[float] = []
acc = 0.0
for d in plan:
if cur and acc + d > take_len:
takes.append(cur)
cur, acc = [], 0.0
cur.append(d)
acc += d
if cur:
takes.append(cur)
out = []
for i, group in enumerate(takes):
used = float(sum(group))
cursor = 0.0
shots = []
for d in group:
shots.append({"start": round(cursor, 3), "duration": round(d, 3)})
cursor += d
out.append(
{
"index": i,
"gen_duration": quantize_gen_duration(used),
"used": round(used, 3),
"shots": shots,
}
)
return out
"""Frame sampling and lightweight video probing."""
from __future__ import annotations
import json
import subprocess
from dataclasses import dataclass
from pathlib import Path
import cv2
import numpy as np
@dataclass
class VideoInfo:
path: Path
width: int
height: int
fps: float
frame_count: int
@property
def duration(self) -> float:
return self.frame_count / self.fps if self.fps else 0.0
def probe(path: str | Path) -> VideoInfo:
path = Path(path)
cap = cv2.VideoCapture(str(path))
if not cap.isOpened():
raise RuntimeError(f"cannot open video: {path}")
info = VideoInfo(
path=path,
width=int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)),
height=int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)),
fps=float(cap.get(cv2.CAP_PROP_FPS)) or 24.0,
frame_count=int(cap.get(cv2.CAP_PROP_FRAME_COUNT)),
)
cap.release()
return info
def sample_frames(
path: str | Path,
n: int = 48,
max_edge: int = 512,
skip_edges: float = 0.02,
) -> list[np.ndarray]:
"""Evenly sample ``n`` frames as float32 RGB in [0, 1].
``skip_edges`` trims the head/tail fraction, which is usually slate,
fade-in, or credits and would poison the grade statistics.
"""
path = Path(path)
cap = cv2.VideoCapture(str(path))
if not cap.isOpened():
raise RuntimeError(f"cannot open video: {path}")
total = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
if total <= 0:
# Some containers lie about frame count; fall back to full decode.
frames = _sequential_sample(cap, n, max_edge)
cap.release()
return frames
lo = int(total * skip_edges)
hi = int(total * (1.0 - skip_edges))
idxs = np.linspace(lo, max(lo + 1, hi - 1), num=min(n, max(1, hi - lo)))
idxs = np.unique(idxs.astype(int))
out: list[np.ndarray] = []
for i in idxs:
cap.set(cv2.CAP_PROP_POS_FRAMES, int(i))
ok, bgr = cap.read()
if not ok:
continue
out.append(_prep(bgr, max_edge))
cap.release()
if not out:
raise RuntimeError(f"decoded zero frames from {path}")
return out
def _sequential_sample(cap, n: int, max_edge: int) -> list[np.ndarray]:
frames = []
while True:
ok, bgr = cap.read()
if not ok:
break
frames.append(bgr)
if not frames:
return []
idxs = np.unique(np.linspace(0, len(frames) - 1, num=min(n, len(frames))).astype(int))
return [_prep(frames[i], max_edge) for i in idxs]
def _prep(bgr: np.ndarray, max_edge: int) -> np.ndarray:
h, w = bgr.shape[:2]
scale = max_edge / max(h, w)
if scale < 1.0:
bgr = cv2.resize(bgr, (int(w * scale), int(h * scale)), interpolation=cv2.INTER_AREA)
rgb = cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB)
return rgb.astype(np.float32) / 255.0
def export_stills(
path: str | Path,
dest: str | Path,
timestamps: list[float],
prefix: str = "still",
) -> list[Path]:
"""Write full-resolution stills at the given timestamps (seconds).
These frames are what actually carry the look into image-to-video
models, so they are exported at native resolution rather than at the
downscaled analysis size.
"""
dest = Path(dest)
dest.mkdir(parents=True, exist_ok=True)
written: list[Path] = []
for i, ts in enumerate(timestamps):
outfile = dest / f"{prefix}_{i:03d}.png"
cmd = [
"ffmpeg", "-nostdin", "-loglevel", "error", "-y",
"-ss", f"{ts:.3f}", "-i", str(path),
"-frames:v", "1", str(outfile),
]
proc = subprocess.run(cmd, capture_output=True)
if proc.returncode == 0 and outfile.exists():
written.append(outfile)
return written
def ffprobe_json(path: str | Path) -> dict:
cmd = [
"ffprobe", "-v", "quiet", "-print_format", "json",
"-show_format", "-show_streams", str(path),
]
proc = subprocess.run(cmd, capture_output=True, text=True)
if proc.returncode != 0:
return {}
return json.loads(proc.stdout or "{}")
# --------------------------------------------------------------------------
# content masking
# --------------------------------------------------------------------------
def content_mask(
frames_list: list[np.ndarray],
var_percentile: float = 35.0,
min_keep: float = 0.15,
) -> np.ndarray:
"""Boolean mask of pixels that actually change over time.
Screen-recorded references carry baked-in furniture: letterbox bars, a
phone status bar, like/comment icons, caption text. All of it is static
across the whole clip, and all of it lands in the grade statistics as if
it were part of the look. Black bars inflate the shadow weight and pull
the whole tone curve down; a red heart icon skews a* toward magenta.
Temporal variance separates them cleanly - the video content moves, the
interface does not - so no hand-tuned crop rectangle is needed and the
same code works regardless of which app the capture came from.
``min_keep`` guards the degenerate case: a genuinely static reference
(a locked-off shot) would otherwise mask itself out entirely.
"""
if len(frames_list) < 4:
return np.ones(frames_list[0].shape[:2], dtype=bool)
stack = np.stack([f.mean(axis=2) for f in frames_list], axis=0)
var = stack.std(axis=0)
thresh = np.percentile(var, var_percentile)
mask = var > max(thresh, 1e-4)
if mask.mean() < min_keep:
# Too aggressive for this material; fall back to keeping everything.
return np.ones_like(mask, dtype=bool)
return mask
def apply_mask(frames_list: list[np.ndarray], mask: np.ndarray) -> np.ndarray:
"""Flatten frames to only the masked pixels: (n_frames * n_kept, 3)."""
return np.concatenate([f[mask] for f in frames_list], axis=0)
def mask_bbox(mask: np.ndarray) -> tuple[int, int, int, int]:
"""Tight bounding box (y0, y1, x0, x1) of the moving region."""
rows = np.where(mask.any(axis=1))[0]
cols = np.where(mask.any(axis=0))[0]
if len(rows) == 0 or len(cols) == 0:
return 0, mask.shape[0], 0, mask.shape[1]
return int(rows[0]), int(rows[-1]) + 1, int(cols[0]), int(cols[-1]) + 1
def reject_outliers(
frames_list: list[np.ndarray],
z: float = 3.5,
max_drop: float = 0.25,
) -> tuple[list[np.ndarray], list[int]]:
"""Drop frames whose color statistics are alien to the rest of the set.
Screen-recorded reference reels pick up material that is not reference
material: a Control Center panel pulled down mid-capture, a home screen,
an app-switcher card, a white flash between clips. These frames are not a
style signal, but they are weighted equally with everything else, and a
single bright neutral frame drags the pooled grade toward grey.
Robust statistics are what make this safe. Each frame is reduced to its
mean L*, a*, b*, then scored by median absolute deviation rather than
standard deviation - MAD does not get inflated by the very outliers it is
meant to detect, so one extreme frame cannot hide behind the variance it
creates. ``max_drop`` caps how much can be discarded, so a genuinely
diverse reel degrades to keeping everything rather than eating itself.
Returns ``(kept_frames, dropped_indices)``.
"""
if len(frames_list) < 8:
return frames_list, []
feats = []
for f in frames_list:
lab = cv2.cvtColor(np.ascontiguousarray(f, np.float32), cv2.COLOR_RGB2LAB)
feats.append(lab.reshape(-1, 3).mean(axis=0))
feats = np.asarray(feats, dtype=np.float64)
med = np.median(feats, axis=0)
mad = np.median(np.abs(feats - med), axis=0)
mad = np.maximum(mad, 1e-3)
# 1.4826 rescales MAD into a consistent estimator of sigma for normal data.
score = np.max(np.abs(feats - med) / (1.4826 * mad), axis=1)
order = np.argsort(-score)
cap = int(len(frames_list) * max_drop)
dropped = [int(i) for i in order if score[i] > z][:cap]
dset = set(dropped)
kept = [f for i, f in enumerate(frames_list) if i not in dset]
return kept, sorted(dropped)
def ui_safe_crop(
frames_list: list[np.ndarray],
strength: float = 1.6,
max_trim: float = 0.22,
pad: int = 2,
) -> tuple[int, int, int, int]:
"""Crop rectangle (y0, y1, x0, x1) that excludes baked-in interface chrome.
``content_mask`` is the wrong tool for this and its bounding box is worse.
Temporal variance keeps a like button, because the button *animates* - the
heart pulses, the view counter ticks over - so the mask marks it as moving
content and its bbox spans nearly the whole frame. Measured on real
material, the bbox kept 100% of the width on all three references while the
interface sat plainly in the right-hand margin.
The separating signal is the temporal MEDIAN, not the variance. Real
footage moves, so the median of many frames averages into mush with almost
no edge energy. Interface chrome sits at fixed pixel coordinates, so its
edges survive the median intact. Sobel energy on the median frame therefore
lights up on chrome and goes quiet on content: on one reference the
right-hand column measured 0.23 against an interior background of 0.03,
and on another 0.31 against 0.15.
Trimming walks inward from each edge while that row or column is an outlier
against the interior median, so it removes letterbox and chrome without
touching a frame that has neither. ``max_trim`` caps each side, because a
reference that is genuinely brighter at its edges should degrade to keeping
everything rather than eating itself.
"""
if len(frames_list) < 8:
h, w = frames_list[0].shape[:2]
return 0, h, 0, w
stack = np.stack([f.mean(axis=2) for f in frames_list], axis=0)
med = np.median(stack, axis=0).astype(np.float32)
gx = cv2.Sobel(med, cv2.CV_32F, 1, 0, ksize=3)
gy = cv2.Sobel(med, cv2.CV_32F, 0, 1, ksize=3)
energy = cv2.GaussianBlur(np.sqrt(gx * gx + gy * gy), (15, 15), 0)
h, w = energy.shape
rows = energy.mean(axis=1)
cols = energy.mean(axis=0)
def _trim(profile: np.ndarray, limit: int) -> tuple[int, int]:
"""Trim past the INNERMOST outlier in each outer band, not from the edge in.
Walking inward while the current line is hot stops immediately here,
because the outermost lines are letterbox - flat black, so zero edge
energy - and the interface sits *inside* that, around 90-95% of the
width. The first version of this did exactly that and trimmed 1% of
frame while the like button stayed in shot.
"""
n = len(profile)
core = profile[n // 4: 3 * n // 4]
base = float(np.median(core)) + 1e-6
thresh = base * strength
lo = 0
head = np.where(profile[:limit] > thresh)[0]
if len(head):
lo = int(head[-1]) + 1 # just inside the innermost hot line
hi = n
tail_off = n - limit
tail = np.where(profile[tail_off:] > thresh)[0]
if len(tail):
hi = tail_off + int(tail[0])
return lo, min(hi, n)
y0, y1 = _trim(rows, int(h * max_trim))
x0, x1 = _trim(cols, int(w * max_trim))
y0 = min(y0 + pad, h - 1)
x0 = min(x0 + pad, w - 1)
y1 = max(y1 - pad, y0 + 1)
x1 = max(x1 - pad, x0 + 1)
return int(y0), int(y1), int(x0), int(x1)
def crop_fractions(frames_list: list[np.ndarray], **kw) -> tuple[float, float, float, float]:
"""``ui_safe_crop`` as fractions of frame, so it transfers across resolutions.
The detector runs on downscaled analysis frames; the crop has to be applied
to full-resolution video. Fractions survive that, absolute pixels do not.
"""
y0, y1, x0, x1 = ui_safe_crop(frames_list, **kw)
h, w = frames_list[0].shape[:2]
return y0 / h, y1 / h, x0 / w, x1 / w
"""Style pack: the durable artifact that makes taste reusable.
A pack is a directory, not a database row, so it can be copied, versioned in
git, zipped, and handed to someone else. Genres partition the library:
``stylepacks/flashethereal/``, ``stylepacks/<next-genre>/``, and so on.
Layout::
stylepacks/flashethereal/
pack.json manifest: refs, artifact inventory, version
grade.json GradeStats - color statistics incl. per-zone chroma
cadence.json Cadence - shot-length distribution
spec.json VLM style spec (written by distill.py)
look.cube 33^3 LUT baked against canonical neutral
stills/ full-res keyframes - the primary style carrier
props/ GLB meshes minted from hero frames
plates/ grain / overlay plates
"""
from __future__ import annotations
import json
import shutil
from dataclasses import dataclass, field
from datetime import datetime, timezone
from pathlib import Path
DEFAULT_ROOT = Path("stylepacks")
PACK_VERSION = 1
def _utc_now() -> str:
return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
@dataclass
class StylePack:
name: str
root: Path = DEFAULT_ROOT
manifest: dict = field(default_factory=dict)
# ---- paths -----------------------------------------------------------
@property
def dir(self) -> Path:
return Path(self.root) / self.name
@property
def manifest_path(self) -> Path:
return self.dir / "pack.json"
@property
def grade_path(self) -> Path:
return self.dir / "grade.json"
@property
def cadence_path(self) -> Path:
return self.dir / "cadence.json"
@property
def spec_path(self) -> Path:
return self.dir / "spec.json"
@property
def lut_path(self) -> Path:
return self.dir / "look.cube"
@property
def stills_dir(self) -> Path:
return self.dir / "stills"
@property
def props_dir(self) -> Path:
return self.dir / "props"
@property
def plates_dir(self) -> Path:
return self.dir / "plates"
# ---- lifecycle -------------------------------------------------------
def ensure(self) -> "StylePack":
for d in (self.dir, self.stills_dir, self.props_dir, self.plates_dir):
d.mkdir(parents=True, exist_ok=True)
if not self.manifest:
self.manifest = {
"name": self.name,
"version": PACK_VERSION,
"created": _utc_now(),
"updated": _utc_now(),
"refs": [],
"artifacts": {},
}
return self
def add_ref(self, ref_id: str, src: str, duration: float, n_shots: int) -> None:
self.manifest.setdefault("refs", []).append(
{
"id": ref_id,
"src": str(src),
"duration": round(float(duration), 3),
"n_shots": int(n_shots),
}
)
def stills(self) -> list[Path]:
return sorted(self.stills_dir.glob("*.png")) if self.stills_dir.exists() else []
def props(self) -> list[Path]:
return sorted(self.props_dir.glob("*.glb")) if self.props_dir.exists() else []
def refresh_inventory(self) -> None:
self.manifest["artifacts"] = {
"lut": self.lut_path.name if self.lut_path.exists() else None,
"grade": self.grade_path.exists(),
"cadence": self.cadence_path.exists(),
"spec": self.spec_path.exists(),
"stills": len(self.stills()),
"props": len(self.props()),
"plates": len(list(self.plates_dir.glob("*"))) if self.plates_dir.exists() else 0,
}
self.manifest["updated"] = _utc_now()
def save(self) -> Path:
self.ensure()
self.refresh_inventory()
self.manifest_path.write_text(json.dumps(self.manifest, indent=2), encoding="utf-8")
return self.manifest_path
def write_json(self, path: Path, payload: dict) -> Path:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(payload, indent=2), encoding="utf-8")
return path
def read_json(self, path: Path) -> dict:
if not path.exists():
return {}
return json.loads(path.read_text(encoding="utf-8"))
def archive(self, dest_dir: str | Path = "out") -> Path:
"""Zip the pack so a whole taste can be handed off as one file."""
dest_dir = Path(dest_dir)
dest_dir.mkdir(parents=True, exist_ok=True)
base = dest_dir / f"{self.name}-stylepack"
return Path(shutil.make_archive(str(base), "zip", root_dir=self.dir))
def load(name: str, root: str | Path = DEFAULT_ROOT) -> StylePack:
p = StylePack(name=name, root=Path(root))
if not p.manifest_path.exists():
raise FileNotFoundError(
f"no style pack '{name}' under {root} - run mint.py first"
)
p.manifest = json.loads(p.manifest_path.read_text(encoding="utf-8"))
return p
def create(name: str, root: str | Path = DEFAULT_ROOT) -> StylePack:
return StylePack(name=name, root=Path(root)).ensure()
def list_packs(root: str | Path = DEFAULT_ROOT) -> list[str]:
root = Path(root)
if not root.exists():
return []
return sorted(d.name for d in root.iterdir() if (d / "pack.json").exists())
Which skills are related to taste-distillation?
Taste Distillation skill FAQ
Is Taste Distillation safe to install?
skills.sh reports 3 of 3 security scanners passed. Review the Security Audits panel on this page before installing in production.
Add a taste-distillation badge
Show developers this skill is listed on Skillselion. Paste this into your README.