diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index 448436238..fff4e5b14 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -9,7 +9,7 @@ { "name": "dw", "source": "./plugins/dw", - "description": "Compose MiniMax H3 video, MiniMax Music 3, LTX-2.5, Kandinsky 6.0 and FLUX 3 Klein workflows over a dw MCP server, cut a multi-episode series from them, direct camera and look in each family's caption format, storyboard a scene before it is filmed, and plan a piece longer than one clip from measured levers: which template fits which shape, the hard rules, cost, and how to judge the output. Prompt format comes from the vendors' own guides." + "description": "Compose MiniMax H3 video, MiniMax Music 3, LTX-2.5, Kandinsky 6.0, FLUX 3 Klein and MiniMax-H3-Image workflows over a dw MCP server, cut a multi-episode series from them, direct camera and look in each family's caption format, storyboard a scene before it is filmed, and plan a piece longer than one clip from measured levers: which template fits which shape, the hard rules, cost, and how to judge the output. Prompt format comes from the vendors' own guides." } ] } diff --git a/.gitignore b/.gitignore index bce1b6d51..de440a303 100644 --- a/.gitignore +++ b/.gitignore @@ -169,3 +169,6 @@ workflows/*/assets/ # Claude Code worktrees .claude/worktrees/ + +# test caches written when vitest is run from the repo root +/node_modules/ diff --git a/CLAUDE.md b/CLAUDE.md index 6fcdeeacd..723eaeb7b 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -70,15 +70,13 @@ The guides in `docs/`, by topic: ### Claude Code plugin -`.claude-plugin/marketplace.json` publishes the `dw` plugin in `plugins/dw/`: one -composition skill per model family (`minimax-h3`, `minimax-music3`, `ltx-2.5`, -`kandinsky-6`, `flux3-klein`) that chooses a template for a request's shape and states the -family's hard rules, plus cross-cutting composition skills (`script-to-video`, -`series-episodes`, `cinematography`, `storyboard`, `long-form`) - shapes above the -families that orchestrate the decision trees, cast consistency across multiple -generations, one camera-and-look vocabulary compiled per family, boards and a timed -animatic before video, and the measured playbook for pieces longer than one clip. Every skill the directory holds is named in `plugins/dw/README.md` and here, pinned -by `tests/test_plugin_skills.py`; that README says how the rest is pinned and versioned. +`.claude-plugin/marketplace.json` publishes the `dw` plugin in `plugins/dw/`: one composition skill per model family (`minimax-h3`, +`minimax-music3`, `ltx-2.5`, `kandinsky-6`, `flux3-klein`, `minimax-h3-image`) that chooses a template for a request's shape and +states the family's hard rules, plus cross-cutting composition skills (`script-to-video`, `series-episodes`, `cinematography`, +`storyboard`, `long-form`) - shapes above the families that orchestrate the decision trees, cast consistency across multiple +generations, one camera-and-look vocabulary compiled per family, boards and a timed animatic before video, and the measured playbook +for pieces longer than one clip. Every skill the directory holds is named in `plugins/dw/README.md` and here, pinned by +`tests/test_plugin_skills.py`; that README says how the rest is pinned and versioned. ## Security Rules @@ -98,8 +96,9 @@ noise. `validate_path(path, base)` is a barrier only when `base` is not `None`; ## Before you edit -- **Model knowledge lives in `plugins/dw/` and the catalog, never in engine code.** A - model's rule about a value is declared in the workflow (`dw/variable_constraints.py`). +- **Model knowledge lives in `plugins/dw/` and the catalog, never in engine code.** A model's rule about a + value is declared in the workflow (`dw/variable_constraints.py`), or read off the diffusers class that + enforces it (`dw/reference_limits.py`, `dw/pipeline_limits.py`); the engine names the class, never the number. - **Compare backends with `get_device_type()`, not `== "cuda"`** - a device like `cuda:1` fails the string compare (`dw/__init__.py`). - **`{}` keeps a value a string**: under a `*_type`/`*_dtype`/`dtype` key `"{nf4}"` stays diff --git a/README.md b/README.md index 257175a74..12caaa181 100644 --- a/README.md +++ b/README.md @@ -40,7 +40,7 @@ taking over in the browser where that is quicker. | | Ready-made templates | |---|---| -| **Images** | FLUX 3 Klein (text, edits, multi-reference, layout boxes), FLUX.1 / FLUX.2 / Krea, Qwen Image (and edit), Z-Image, SDXL and SD 1.5; ControlNet, IP-Adapter, LoRA, inpaint and outpaint | +| **Images** | FLUX 3 Klein (text, edits, multi-reference, layout boxes), MiniMax-H3-Image (text, multi-reference edits at up to ~16 MP), FLUX.1 / FLUX.2 / Krea, Qwen Image (and edit), Z-Image, SDXL and SD 1.5; ControlNet, IP-Adapter, LoRA, inpaint and outpaint | | **Video with sound** | MiniMax H3 (dialogue, multi-shot cuts, music videos, reference subjects and voices), LTX-2.5 (image-to-video, keyframes, 2x upscale, restore and colourise, alpha mattes), Kandinsky 6 | | **Music, speech, sound** | MiniMax Music 3 (sung lyrics or instrumental), Audio8 TTS voice cloning and MMS TTS, MMAudio sound effects from text or under a clip, Whisper transcription | | **Longer than one clip** | chained segments that hold the look and audio level across seams, repair of one bad segment in place, music and narration of any length, storyboards and timed animatics, cut-and-score assembly, and an OpenTimelineIO export that DaVinci Resolve opens as one clip per shot | @@ -111,7 +111,7 @@ model cache and workspace with a native install on the same box. See ## Ask the agent -Describe what you want. The agent has 65 tools covering the workflow catalog, the +Describe what you want. The agent has 68 tools covering the workflow catalog, the real diffusers pipeline signatures, the job queue, the gallery and the model cache, and it stays with a long render until it finishes: @@ -149,6 +149,22 @@ One server holds several **workspaces**, each with its own workflows, assets and outputs. Two agents, or an agent and you in the browser, can share one GPU without saving over each other's work. +An ask of more than a couple of jobs gets a **request**: the agent writes its plan +into the workspace's ledger - the goal and the items it will make - links each job +to its item, and records which take it kept. The plan outlives the session. The +Requests page says where each request stands and what needs you, and shows each +item's result, takes and minutes spent; the notes you leave on an item, or on the +request, are read by the agent before it writes the plan again. A note can point at a +take or a file, and you can write it from the request page, a job page or the gallery. See [Requests](docs/WORKSPACES.md#requests). + +With the **notes channel**, a note reaches the agent as you save it. `dw-mcp +--notes-channel` runs beside an open Claude Code session and tells it "the user +left this note on Shot 3, take 2, this file": the agent reads the plan, acts - a retake, then the cut +again - and the page shows what it did. Review on the page, direct in notes, and +the session does the rest. It rides on Claude Code's channels research preview, so +it needs an interactive session started with the development-channels flag, and +its contract may change. Setup: [the notes channel](docs/MCP.md#the-notes-channel). + The tool reference, setup for other MCP hosts and the troubleshooting table are in [MCP Server](docs/MCP.md). @@ -167,7 +183,9 @@ LoRA scale and press **Run**. graph of how data flows between steps. Click a step to see what it produced. The run's warnings sit above the graph, so a problem the agent missed, such as an audible level jump at a cut, is in front of you with the argument that fixes it. -**Run again** repeats the job, and **New seed** gives you another take. Progress +**Run again** repeats the job, **New seed** gives you another take, and **Run +again with changes…** or a preset button (`tier: standard`) queues it with only +the variables you change - the rerun page says `changed: …`. Progress streams live for each denoising step, and a cancel stops the job cleanly at the next step. diff --git a/bench/README.md b/bench/README.md index b0f3703d1..6aa269558 100644 --- a/bench/README.md +++ b/bench/README.md @@ -34,3 +34,26 @@ They share no step cache either: an arms file goes to one server (`bench/driver. ## Reaching it from the Mac lem's firewall passes 8765 but not 8766 (a rule needs sudo: `sudo ufw allow 8766/tcp`, if ufw is the filter). Until then, tunnel: `ssh -f -N -L 18766:127.0.0.1:8766 lem`, then use `http://127.0.0.1:18766`. + +## Measures + +`python bench/driver.py measure ` re-measures a record's succeeded runs; `report` prints them as a table. Each run's `measures`: + +| Key | From | Meaning | +|---|---|---| +| `seam_jump_mean`, `seam_jump_max` | `analyze_seams` `seams[].jump_ratio` | Picture jump at each seam | +| `seam_look_mean`, `seam_look_max` | `seams[].look_ratio` | Look change at each seam | +| `seam_level_step_db_mean`, `seam_level_step_db_max` | `seams[].level_step_db` | Audio level step at each seam, absolute | +| `texture__seg_last` | compare's `texture_bands` on the scene crop | `\|ln(last/first)\|` of the band's luma energy, first moment to last (fine, mid, coarse) | +| `split__total` | `analyze_seams` `segment_looks` | End-to-end change of look measure `` (saturation, lightness, contrast, detail): the last segment's last second minus the first segment's first second | +| `split__seams` | `segment_looks` | Sum over seams of the next segment's first second minus this one's last second | +| `split__segments` | `segment_looks` | Sum over segments of their last second minus their first second | +| `split__seam_share` | | `seams / (\|seams\| + \|segments\|)`; left out when both are 0 | +| `split__seam_sign` | | Fraction of seams whose step has the sign of `split__seams`: how consistent the seam half is | +| `wall_minutes` | the job | Run time | + +`total = seams + segments` exactly, because both halves use the same endpoint windows. A segment missing a measure is skipped and the seam step bridges it. A take with no `segment_looks` (one shot, no picture, or a server before #1324) gets no `split_*` keys. + +The split says *where* a measure changes, not whether a viewer sees the change: it informs a viewing verdict and doesn't replace one (#1324: the "progressively glossy" levelled carry was missed by the measures). The concept is from [ComfyUI-Continuity](https://github.com/roadmaus/ComfyUI-Continuity) (MIT; no code adapted). + +**Face scores:** a face-score margin must clear the encode floor in `records/face-encode-floor.md` (0.016 on the median, 0.030 on the min, a lower bound; a first-encode H3 clip has shown 0.045 on a minimum, #1400, so 0.030 is not enough margin for H3 output), and an in-job score (frames in memory) is compared only with other in-job scores, never with a score of the saved file (#1420). diff --git a/bench/arms/keystone-attention.json b/bench/arms/keystone-attention.json new file mode 100644 index 000000000..9050bffc7 --- /dev/null +++ b/bench/arms/keystone-attention.json @@ -0,0 +1,38 @@ +[ + { + "name": "keystone-control-early", + "scene": "s6-narration", + "workflow": "keystone-attention-control-early.json", + "arguments": { + "seed": 1 + }, + "seed": 1 + }, + { + "name": "keystone-attention-early", + "scene": "s6-narration", + "workflow": "keystone-attention-early.json", + "arguments": { + "seed": 1 + }, + "seed": 1 + }, + { + "name": "keystone-control", + "scene": "s6-narration", + "workflow": "keystone-attention-control.json", + "arguments": { + "seed": 1 + }, + "seed": 1 + }, + { + "name": "keystone-attention", + "scene": "s6-narration", + "workflow": "keystone-attention.json", + "arguments": { + "seed": 1 + }, + "seed": 1 + } +] diff --git a/bench/arms/ks2v-pro-4bit.json b/bench/arms/ks2v-pro-4bit.json new file mode 100644 index 000000000..df9dd4c83 --- /dev/null +++ b/bench/arms/ks2v-pro-4bit.json @@ -0,0 +1,11 @@ +[ + { + "name": "ks2v-pro-4bit-s1", + "scene": "s3-dialogue-walk", + "workflow": "ks2v-pro-4bit.json", + "arguments": { + "seed": 1 + }, + "seed": 1 + } +] diff --git a/bench/arms/narration-reference-ab.json b/bench/arms/narration-reference-ab.json new file mode 100644 index 000000000..4f389b0a3 --- /dev/null +++ b/bench/arms/narration-reference-ab.json @@ -0,0 +1,37 @@ +[ + { + "name": "ref-ab-synthetic-s1166", + "scene": "s6-narration", + "workflow": "narration-reference-ab.json", + "arguments": { + "reference_audio": "asset:bench/narrator.wav", + "reference_text": "The tide comes in twice a day, and the lamp has to be ready for both.", + "generate_kwargs": {} + }, + "seed": 1166 + }, + { + "name": "ref-ab-human-s1166", + "scene": "s6-narration", + "workflow": "narration-reference-ab.json", + "arguments": { + "reference_audio": "asset:bench/narrator-human.wav", + "reference_text": "The brave men, living and dead, who struggled here have consecrated it, far above our poor power to add or detract.", + "generate_kwargs": {} + }, + "seed": 1166 + }, + { + "name": "ref-ab-sampling-t1.0-s1166", + "scene": "s6-narration", + "workflow": "narration-reference-ab.json", + "arguments": { + "reference_audio": "asset:bench/narrator.wav", + "reference_text": "The tide comes in twice a day, and the lamp has to be ready for both.", + "generate_kwargs": { + "temperature": 1.0 + } + }, + "seed": 1166 + } +] diff --git a/bench/arms/probe-1438.json b/bench/arms/probe-1438.json new file mode 100644 index 000000000..bb0c57a86 --- /dev/null +++ b/bench/arms/probe-1438.json @@ -0,0 +1,119 @@ +[ + { + "name": "1438-V0-flag-off", + "scene": "s1-static", + "workflow": "probe-1438-video-with-audio.json", + "arguments": { + "stochastic_sampling": false + }, + "seed": 42, + "moments": [ + "frame:0", + "frame:62", + "frame:123" + ] + }, + { + "name": "1438-V1-flag-on", + "scene": "s1-static", + "workflow": "probe-1438-video-with-audio.json", + "arguments": { + "stochastic_sampling": true + }, + "seed": 42, + "moments": [ + "frame:0", + "frame:62", + "frame:123" + ] + }, + { + "name": "1438-V1b-flag-on-again", + "scene": "s1-static", + "workflow": "probe-1438-video-with-audio.json", + "arguments": { + "stochastic_sampling": true + }, + "seed": 42, + "workflow_id_suffix": "-b", + "moments": [ + "frame:0", + "frame:62", + "frame:123" + ] + }, + { + "name": "1438-FF-flag-with-velocity", + "scene": "s1-static", + "workflow": "probe-1438-video-with-audio.json", + "arguments": { + "stochastic_sampling": true, + "euler_update_form": "velocity" + }, + "seed": 42 + }, + { + "name": "1438-C0-chain-flag-off", + "scene": "s1-static", + "workflow": "probe-1438-chained-segments.json", + "arguments": { + "stochastic_sampling": false + }, + "seed": 42 + }, + { + "name": "1438-C1-chain-flag-on", + "scene": "s1-static", + "workflow": "probe-1438-chained-segments.json", + "arguments": { + "stochastic_sampling": true + }, + "seed": 42 + }, + { + "name": "1438-I0-as-is", + "scene": "s1-static", + "workflow": "probe-1438-h3-image.json", + "arguments": {}, + "seed": 1317 + }, + { + "name": "1438-I0-16-as-is-16mp", + "scene": "s1-static", + "workflow": "probe-1438-h3-image.json", + "arguments": { + "size": "1:1" + }, + "seed": 1317 + }, + { + "name": "1438-I1-blend", + "scene": "s1-static", + "workflow": "probe-1438-h3-image.json", + "arguments": { + "euler_update_form": "blend" + }, + "seed": 1317 + }, + { + "name": "1438-I2-blend-flag", + "scene": "s1-static", + "workflow": "probe-1438-h3-image.json", + "arguments": { + "euler_update_form": "blend", + "stochastic_sampling": true + }, + "seed": 1317 + }, + { + "name": "1438-I2b-blend-flag-again", + "scene": "s1-static", + "workflow": "probe-1438-h3-image.json", + "arguments": { + "euler_update_form": "blend", + "stochastic_sampling": true + }, + "seed": 1317, + "workflow_id_suffix": "-b" + } +] diff --git a/bench/arms/t16-performer-replacement.json b/bench/arms/t16-performer-replacement.json index ca3393159..8cc0de607 100644 --- a/bench/arms/t16-performer-replacement.json +++ b/bench/arms/t16-performer-replacement.json @@ -31,5 +31,45 @@ "refine_strength": null }, "seed": 1194 + }, + { + "name": "t16-swap-g0-s1194", + "scene": "s4-montage", + "workflow": "t16-performer-swap.json", + "arguments": { + "mask_grow": 0 + }, + "seed": 1194 + }, + { + "name": "t16-swap-g0-s2002", + "scene": "s4-montage", + "workflow": "t16-performer-swap.json", + "arguments": { + "mask_grow": 0 + }, + "seed": 2002 + }, + { + "name": "t16-swap-e16-s1194", + "scene": "s4-montage", + "workflow": "t16-performer-swap.json", + "arguments": { + "mask_grow": 0, + "source_video": "asset:bench/t16/deflect-cut.mp4", + "mask_video": "asset:bench/t16/deflect-mask-e16.mp4" + }, + "seed": 1194 + }, + { + "name": "t16-swap-e16-s2002", + "scene": "s4-montage", + "workflow": "t16-performer-swap.json", + "arguments": { + "mask_grow": 0, + "source_video": "asset:bench/t16/deflect-cut.mp4", + "mask_video": "asset:bench/t16/deflect-mask-e16.mp4" + }, + "seed": 2002 } ] diff --git a/bench/arms/t16-recast-shot.json b/bench/arms/t16-recast-shot.json new file mode 100644 index 000000000..822ee41a8 --- /dev/null +++ b/bench/arms/t16-recast-shot.json @@ -0,0 +1,16 @@ +[ + { + "name": "t16-recast-arm1-replace-performer-s1194", + "scene": "s4-montage", + "workflow": "t16-recast-replace-performer.json", + "arguments": {}, + "seed": 1194 + }, + { + "name": "t16-recast-arm3-headswap-guide-s1194", + "scene": "s4-montage", + "workflow": "t16-recast-shot.json", + "arguments": {}, + "seed": 1194 + } +] diff --git a/bench/arms/track-people-backend-ab.json b/bench/arms/track-people-backend-ab.json new file mode 100644 index 000000000..0c255f8ed --- /dev/null +++ b/bench/arms/track-people-backend-ab.json @@ -0,0 +1,68 @@ +[ + { + "name": "dino-ep65-dissolve", + "scene": "s4-montage", + "workflow": "track-people-backend-ab.json", + "arguments": { + "video": "asset:qa-cast/ep65-shot-kf-priya-hal.mp4", + "backend": "grounding-dino", + "threshold": 0.3 + }, + "seed": 0 + }, + { + "name": "sam3-ep65-dissolve", + "scene": "s4-montage", + "workflow": "track-people-backend-ab.json", + "arguments": { + "video": "asset:qa-cast/ep65-shot-kf-priya-hal.mp4", + "backend": "sam3", + "threshold": 0.5 + }, + "seed": 0 + }, + { + "name": "dino-ep62-pair", + "scene": "s4-montage", + "workflow": "track-people-backend-ab.json", + "arguments": { + "video": "asset:qa-cast/ep62-episode.mp4", + "backend": "grounding-dino", + "threshold": 0.3 + }, + "seed": 0 + }, + { + "name": "sam3-ep62-pair", + "scene": "s4-montage", + "workflow": "track-people-backend-ab.json", + "arguments": { + "video": "asset:qa-cast/ep62-episode.mp4", + "backend": "sam3", + "threshold": 0.5 + }, + "seed": 0 + }, + { + "name": "dino-ep49", + "scene": "s4-montage", + "workflow": "track-people-backend-ab.json", + "arguments": { + "video": "asset:qa-cast/ep49-episode.mp4", + "backend": "grounding-dino", + "threshold": 0.3 + }, + "seed": 0 + }, + { + "name": "sam3-ep49", + "scene": "s4-montage", + "workflow": "track-people-backend-ab.json", + "arguments": { + "video": "asset:qa-cast/ep49-episode.mp4", + "backend": "sam3", + "threshold": 0.5 + }, + "seed": 0 + } +] diff --git a/bench/blur_outside_mask.py b/bench/blur_outside_mask.py new file mode 100644 index 000000000..1ef544def --- /dev/null +++ b/bench/blur_outside_mask.py @@ -0,0 +1,90 @@ +"""Blur a reference picture's backdrop outside a person mask (#1439, stage #1460). + +Arm 3 of bench/records/ref-prep-blur.md: the square crop on the person (arm 2) +with everything outside them blurred, so an H3 reference keeps the subject +sharp and gives the model no legible backdrop to carry into the clip. The mask +is a still `segment` result (prompt "person", white = subject), binarized at +128 like the masks dw writes; it must be the picture's own size, so segment +the crop that is blurred, not the uncropped picture. + +The mask is grown by --grow px (a (2N+1)-square maximum filter, so hair and +shoulder edges the segmenter clipped stay sharp), feathered by a gaussian of +--feather sigma into a 0..1 alpha, and the picture is composited as +alpha * sharp + (1 - alpha) * gaussian(picture, --blur sigma). A grow of 0 and +a feather of 0 are the hard mask itself. + +usage: python bench/blur_outside_mask.py IMAGE MASK OUT + [--grow 12] [--feather 6] [--blur 20] +""" + +import argparse + +import numpy as np +from PIL import Image +from scipy import ndimage + +MASK_THRESHOLD = 128 # white at or above, as dw's own masks are binarized + + +def read_mask(path, size): + """(H, W) bool, white = subject; `size` is the picture's (width, height).""" + mask = Image.open(path).convert("L") + if mask.size != size: + raise SystemExit(f"mask is {mask.size}, picture is {size}: segment the crop") + return np.asarray(mask) >= MASK_THRESHOLD + + +def grow(mask, px): + """`mask` dilated by `px` with a (2px+1) square; 0 is the identity.""" + if px <= 0: + return mask.copy() + return ndimage.maximum_filter(mask.astype(np.uint8), size=2 * px + 1) > 0 + + +def feather(mask, sigma): + """(H, W) float alpha in 0..1, the mask's edge softened by a gaussian.""" + alpha = mask.astype(np.float32) + if sigma > 0: + alpha = ndimage.gaussian_filter(alpha, sigma=sigma) + return np.clip(alpha, 0.0, 1.0) + + +def blur(picture, sigma): + """(H, W, 3) float picture blurred per channel by a gaussian of `sigma`.""" + return np.stack( + [ndimage.gaussian_filter(picture[..., c], sigma=sigma) for c in range(3)], + axis=-1, + ) + + +def composite(picture, blurred, alpha): + """Sharp over blurred through `alpha`, as (H, W, 3) uint8.""" + a = alpha[..., None] + out = a * picture + (1.0 - a) * blurred + return np.clip(np.rint(out), 0, 255).astype(np.uint8) + + +def main(): + p = argparse.ArgumentParser(description=__doc__.split("\n")[0]) + p.add_argument("image") + p.add_argument("mask") + p.add_argument("out") + p.add_argument("--grow", type=int, default=12, help="mask growth in px") + p.add_argument("--feather", type=float, default=6.0, help="edge gaussian sigma") + p.add_argument("--blur", type=float, default=20.0, help="backdrop gaussian sigma") + a = p.parse_args() + if a.grow < 0 or a.feather < 0 or a.blur <= 0: + raise SystemExit("--grow and --feather are 0 or more, --blur above 0") + image = Image.open(a.image).convert("RGB") + picture = np.asarray(image).astype(np.float32) + mask = read_mask(a.mask, image.size) + alpha = feather(grow(mask, a.grow), a.feather) + Image.fromarray(composite(picture, blur(picture, a.blur), alpha)).save(a.out) + print( + f"{image.size[0]}x{image.size[1]}; mask {mask.mean():.4f} of the picture, " + f"grown {a.grow} px, feather sigma {a.feather:g}, blur sigma {a.blur:g}" + ) + + +if __name__ == "__main__": + main() diff --git a/bench/cut_windows.py b/bench/cut_windows.py new file mode 100644 index 000000000..e1f1a0062 --- /dev/null +++ b/bench/cut_windows.py @@ -0,0 +1,132 @@ +"""Face-crop sharpness in 1 s windows around a cut, and identity across it. + +The measure is bench/face_windows.py's (YuNet's largest face, Laplacian variance +of the gray crop, SFace cosine), in 1 s windows sampled every 0.25 s. + +usage: + python -I bench/cut_windows.py pair + A's per-second sharpness, B's, the step from A's last 1 s to B's first 1 s, + when B first reaches A's end level, and SFace across the cut. + python -I bench/cut_windows.py clip + per-second sharpness of one clip, the step at cut_s, SFace across it. + python -I bench/cut_windows.py still ... + face sharpness of each still. +""" + +import sys + +import cv2 +import numpy as np + +STEP = 0.25 + + +def face(det, frame): + h, w = frame.shape[:2] + det.setInputSize((w, h)) + _, faces = det.detect(frame) + if faces is None or len(faces) == 0: + return None + return max(faces, key=lambda f: f[2] * f[3]) + + +def sharpness(frame, f): + x, y, w, h = [int(v) for v in f[:4]] + crop = frame[max(y, 0) : y + h, max(x, 0) : x + w] + return cv2.Laplacian(cv2.cvtColor(crop, cv2.COLOR_BGR2GRAY), cv2.CV_64F).var() + + +def samples(det, rec, path): + """(t, sharpness, feature) every STEP seconds, frames with a face only.""" + cap = cv2.VideoCapture(path) + fps = cap.get(cv2.CAP_PROP_FPS) + n = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) + every = max(int(round(STEP * fps)), 1) + out, i = [], 0 + while True: + ok, fr = cap.read() + if not ok: + break + if i % every == 0: + f = face(det, fr) + if f is not None: + out.append( + (i / fps, sharpness(fr, f), rec.feature(rec.alignCrop(fr, f))) + ) + i += 1 + return out, n / fps + + +def window(s, a, b): + v = [x[1] for x in s if a <= x[0] < b] + return float(np.median(v)) if v else float("nan") + + +def mean_feat(s, a, b): + v = [x[2] for x in s if a <= x[0] < b] + return np.mean(v, axis=0).astype(np.float32) if v else None + + +def per_second(label, s, dur): + print(f"{label} ({dur:.2f} s, {len(s)} face samples)") + for a in range(int(np.ceil(dur))): + print(f" {a:>3}-{a + 1:<3} s: sharp {window(s, a, a + 1):.0f}") + + +def across(rec, fa, fb): + if fa is None or fb is None: + return float("nan") + return rec.match(fa, fb, cv2.FaceRecognizerSF_FR_COSINE) + + +def main(): + yunet, sface, mode = sys.argv[1:4] + det = cv2.FaceDetectorYN.create(yunet, "", (320, 320), 0.6) + rec = cv2.FaceRecognizerSF.create(sface, "") + args = sys.argv[4:] + if mode == "still": + for p in args: + fr = cv2.imread(p) + f = face(det, fr) + print( + f"{p}: sharp {sharpness(fr, f):.0f}" + if f is not None + else f"{p}: no face" + ) + return + if mode == "pair": + sa, da = samples(det, rec, args[0]) + sb, db = samples(det, rec, args[1]) + per_second("A", sa, da) + per_second("B", sb, db) + end_a = window(sa, da - 1, da) + head_b = window(sb, 0, 1) + reach = next( + (a for a in range(int(np.ceil(db))) if window(sb, a, a + 1) >= end_a), None + ) + sim = across(rec, mean_feat(sa, da - 1, da), mean_feat(sb, 0, 1)) + else: + s, d = samples(det, rec, args[0]) + cut = float(args[1]) + per_second("clip", s, d) + end_a = window(s, cut - 1, cut) + head_b = window(s, cut, cut + 1) + reach = next( + (a - cut for a in np.arange(cut, d, 1.0) if window(s, a, a + 1) >= end_a), + None, + ) + sim = across(rec, mean_feat(s, cut - 1, cut), mean_feat(s, cut, cut + 1)) + print(f"last 1 s before cut: {end_a:.0f} first 1 s after: {head_b:.0f}") + print(f"step: {head_b / end_a:.2f}x ({(head_b - end_a) / end_a * 100:+.0f}%)") + print( + "after side first reaches the before level: " + + ( + f"window starting {reach:g} s after the cut" + if reach is not None + else "never" + ) + ) + print(f"SFace across the cut (mean feature, 1 s each side): {sim:.3f}") + + +main() diff --git a/bench/driver.py b/bench/driver.py index 8b8168836..3e7fb2b20 100644 --- a/bench/driver.py +++ b/bench/driver.py @@ -171,22 +171,66 @@ def _stats(out, values, name_mean, name_max): out[name_max] = max(values) +SPLIT_MEASURES = ("saturation", "lightness", "contrast", "detail") + + +def _number(value): + return ( + float(value) + if isinstance(value, (int, float)) and not isinstance(value, bool) + else None + ) + + +def _split(out, segment_looks): + """Seam/segment split of each look measure (#1324), from analyze_seams' + `segment_looks`. With endpoint windows the parts sum exactly: + total = seams + segments, where seams is the sum of each next segment's + first window minus this one's last, and segments the sum of each + segment's last window minus its first. A segment without the measure is + skipped and the seam bridges it, so the sum still telescopes. + + The split says where a measure changes, not whether a viewer sees the + change: it informs a viewing verdict and doesn't replace one.""" + for m in SPLIT_MEASURES: + spans = [] + for entry in segment_looks or []: + first = _number(((entry or {}).get("first") or {}).get(m)) + last = _number(((entry or {}).get("last") or {}).get(m)) + if first is not None and last is not None: + spans.append((first, last)) + if not spans: + continue + steps = [b[0] - a[1] for a, b in zip(spans, spans[1:])] + seams = sum(steps) + segments = sum(last - first for first, last in spans) + out[f"split_{m}_total"] = spans[-1][1] - spans[0][0] + out[f"split_{m}_segments"] = segments + if not steps: + continue # one segment: no seam to split by + out[f"split_{m}_seams"] = seams + if abs(seams) + abs(segments) > 0: + out[f"split_{m}_seam_share"] = seams / (abs(seams) + abs(segments)) + if seams != 0: + agree = sum(1 for s in steps if s * seams > 0) + out[f"split_{m}_seam_sign"] = agree / len(steps) + + def measure(job, scene, server, token, workspace=None, moments=None): name = output_name(job) params = {"probe": "analyze_seams"} if workspace: params["workspace"] = workspace - seams = ( - http( - "GET", - f"/api/gallery/{urllib.parse.quote(name, safe='/')}/assess", - server, - token, - params=params, - ).get("seams") - or [] + answer = http( + "GET", + f"/api/gallery/{urllib.parse.quote(name, safe='/')}/assess", + server, + token, + params=params, ) + seams = answer.get("seams") or [] out = {} + _split(out, answer.get("segment_looks")) _stats(out, [s.get("jump_ratio") for s in seams], "seam_jump_mean", "seam_jump_max") _stats(out, [s.get("look_ratio") for s in seams], "seam_look_mean", "seam_look_max") _stats( diff --git a/bench/erode_mask.py b/bench/erode_mask.py new file mode 100644 index 000000000..e283f6ab2 --- /dev/null +++ b/bench/erode_mask.py @@ -0,0 +1,99 @@ +"""Erode a person-mask video by N px, before H3 pools it onto patch cells (#1382). + +The eroded-mask arm of bench/records/performer-replacement.md ("The seam: an +eroded mask"). Each frame is binarized the way `h3_mask_cells.binarized` does +it - Pillow's L conversion, white at or above 128 (`h3_rules.MASK_THRESHOLD`) - +then eroded by N px with a (2N+1)-square minimum filter, so a filled square +shrinks by N on every side. The frame border does not erode (mode "nearest"): +a person cut off by the frame edge stays masked up to that edge. The output is +a 0/255 mask with the input's size, frame count and fps, written by the +diffusers `export_to_video` dw writes its own masks with. + +usage: python bench/erode_mask.py MASK.mp4 OUT.mp4 --px N +""" + +import argparse + +import cv2 +import numpy as np +from PIL import Image +from scipy import ndimage + +MASK_THRESHOLD = 128 # dw.pipeline_processors.h3_rules.MASK_THRESHOLD + + +def read_mask(path): + """(frames as a (T, H, W, 3) uint8 RGB array, fps).""" + cap = cv2.VideoCapture(path) + fps = cap.get(cv2.CAP_PROP_FPS) + frames = [] + while True: + ok, frame = cap.read() + if not ok: + break + frames.append(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)) + cap.release() + if not frames: + raise SystemExit(f"no frames in {path}") + return np.stack(frames), fps + + +def binarize(frames): + """(T, H, W[, C]) uint8 -> (T, H, W) bool, by h3_mask_cells.binarized's rule.""" + luma = np.stack( + [np.asarray(Image.fromarray(frame).convert("L")) for frame in frames] + ) + return luma >= MASK_THRESHOLD + + +def erode(mask, px): + """(T, H, W) bool eroded by `px` per frame with a (2px+1) square; 0 is the identity.""" + if px <= 0: + return mask.copy() + size = 2 * px + 1 + return np.stack( + [ + ndimage.minimum_filter(frame.astype(np.uint8), size=size, mode="nearest") + > 0 + for frame in mask + ] + ) + + +def removed_fraction(before, after): + """Share of the mask's white pixels the erosion removed (0 for an empty mask).""" + white = int(before.sum()) + return 0.0 if white == 0 else (white - int(after.sum())) / white + + +def write_mask(mask, path, fps): + """Write (T, H, W) bool as a 0/255 RGB video at `fps`.""" + from diffusers.utils import export_to_video + + frames = [ + Image.fromarray(np.repeat((m * 255).astype(np.uint8)[..., None], 3, axis=-1)) + for m in mask + ] + export_to_video(frames, path, fps=fps) + + +def main(): + p = argparse.ArgumentParser(description=__doc__.split("\n")[0]) + p.add_argument("mask") + p.add_argument("out") + p.add_argument("--px", type=int, required=True, help="erosion in px, 0 or more") + a = p.parse_args() + if a.px < 0: + raise SystemExit("--px is 0 or more") + frames, fps = read_mask(a.mask) + before = binarize(frames) + after = erode(before, a.px) + write_mask(after, a.out, fps) + print( + f"{len(after)} frames, {after.shape[2]}x{after.shape[1]} @ {fps:g} fps; " + f"eroded {a.px} px, removed {removed_fraction(before, after):.4f} of the mask" + ) + + +if __name__ == "__main__": + main() diff --git a/bench/face_creep.py b/bench/face_creep.py new file mode 100644 index 000000000..8394f03ad --- /dev/null +++ b/bench/face_creep.py @@ -0,0 +1,83 @@ +"""Face sharpness creep and identity hold over one clip (#1399). + +The measure is bench/cut_windows.py's (YuNet's largest face, Laplacian variance +of the gray crop, SFace cosine), sampled every 0.25 s. Prints the median +sharpness of each 1 s window, the total creep (last full 1 s window over the +first), and SFace between the mean feature of the first 1 s and of the last 1 s. + +usage: python -I bench/face_creep.py