Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
77a3fe1ff8 | ||
|
|
95ab5f6e0e | ||
|
|
aadfcb88ec | ||
|
|
e8da2a52a2 | ||
|
|
5fec58ace9 | ||
|
|
f91c8e48d5 | ||
|
|
c5ad611bee | ||
|
|
f71088b958 | ||
|
|
fec84b928c | ||
|
|
4b1ef024b8 | ||
|
|
71c1ec2071 | ||
|
|
0991ef27bb | ||
|
|
170885cb73 | ||
|
|
a4354a47dd | ||
|
|
cb612c777f | ||
|
|
c0e348bedd | ||
|
|
722878d0c1 | ||
|
|
0f4a156c6b | ||
|
|
78e696ad8b | ||
|
|
6effc61e2d | ||
|
|
2b03710023 | ||
|
|
df5ee8bb08 | ||
|
|
da10e98b43 | ||
|
|
6308a7257f | ||
|
|
14298c6d7e | ||
|
|
9a7b8ee5b1 | ||
|
|
acbbb032ef | ||
|
|
a8321bccad | ||
|
|
a0b3c2ea95 | ||
|
|
d6a7c630b2 | ||
|
|
03ddbc9ef7 | ||
|
|
060c40a195 | ||
|
|
9f3ac5a498 | ||
|
|
c7fe70dde9 | ||
|
|
d28ce0ebb6 | ||
|
|
72f8830ebd | ||
|
|
2477b758a0 | ||
|
|
84515ebd97 | ||
|
|
d19e6661b2 | ||
|
|
2e8a10ec10 | ||
|
|
f0f5134c7e | ||
|
|
174d4a81b1 | ||
|
|
c30b124178 | ||
|
|
37e13da2ae | ||
|
|
8520951187 | ||
|
|
7f13daead7 | ||
|
|
1fca384aff | ||
|
|
f39396c5d4 | ||
|
|
98dced9d2f | ||
|
|
369702d22a | ||
|
|
f453bacf5e | ||
|
|
48c0bc0000 | ||
|
|
e76d475eb3 | ||
|
|
b33ea15575 | ||
|
|
2f080686f9 | ||
|
|
62413eef53 | ||
|
|
5cdb560c0c | ||
|
|
af923711a2 | ||
|
|
4f54298cac | ||
|
|
538698d2b2 | ||
|
|
be9db84962 | ||
|
|
c47b4bd36e | ||
|
|
41260de5b3 | ||
|
|
e82fdddfb9 |
@@ -16,6 +16,8 @@ name: ComfyUI updates
|
||||
# and nothing throws. A third run acts like a privacy browser that
|
||||
# blanks canvas pixel reads: a node that loads a picture must still
|
||||
# draw it.
|
||||
# scripts/dev/h3_sockets_check.mjs then checks that H3 Prompt Writer
|
||||
# still draws only the sockets in use, in both views.
|
||||
#
|
||||
# A failure on the release opens an issue (or adds to the open one) and fails
|
||||
# the run. The development head breaks and mends itself often, so that job
|
||||
@@ -33,6 +35,7 @@ on:
|
||||
- "tests/test_comfy_core_contract.py"
|
||||
- "scripts/compat_boot.py"
|
||||
- "scripts/dev/face_smoke.mjs"
|
||||
- "scripts/dev/h3_sockets_check.mjs"
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
@@ -128,6 +131,8 @@ jobs:
|
||||
node ComfyUI-AusBoss/scripts/dev/face_smoke.mjs 9333 || status=1
|
||||
node ComfyUI-AusBoss/scripts/dev/face_smoke.mjs 9333 --vue || status=1
|
||||
node ComfyUI-AusBoss/scripts/dev/face_smoke.mjs 9333 --blocked-reads || status=1
|
||||
node ComfyUI-AusBoss/scripts/dev/h3_sockets_check.mjs 9333 || status=1
|
||||
node ComfyUI-AusBoss/scripts/dev/h3_sockets_check.mjs 9333 --vue || status=1
|
||||
exit "$status"
|
||||
- name: ComfyUI's log
|
||||
if: ${{ always() }}
|
||||
|
||||
+125
@@ -2,6 +2,131 @@
|
||||
|
||||
All notable changes to ComfyUI-AusBoss are documented here.
|
||||
|
||||
## 2.30.0 - 2026-11-28
|
||||
|
||||
- **H3 Prompt Writer 🆎 has a gear menu.** The gear at the top right of the
|
||||
node holds two things. Sockets picks whether the node shows only the
|
||||
sockets in use or all of them. Under it are the four things the model on
|
||||
clip is asked: describe a new person, fill in the next moments, hear the
|
||||
place, and tidy up my lines. Each can be edited, and the edit is saved in
|
||||
the node, so a shared workflow asks the same. Back to built-in undoes it,
|
||||
and Reset puts the sockets and all four back. The editor checks with you
|
||||
before Esc throws away your typing, and before Save keeps a wording that
|
||||
lost a name the node fills in, such as {lines}.
|
||||
- **Mask by Touch 🆎 can use RMBG-3.0 for soft edges.** With Bria's
|
||||
RMBG-3.0 files in place, Fine edges offers RMBG-3.0 next to BiRefNet, and
|
||||
Subject and Background use it too. It keeps loose hair, fur and lace that
|
||||
BiRefNet cuts hard, at about 14 GB of files and about 2 seconds a picture
|
||||
once loaded. Its licence is non-commercial. Fine edges still starts at off,
|
||||
and Subject and Background then use BiRefNet. The ? page says where to get
|
||||
the files.
|
||||
- **H3 Prompt Writer 🆎 shows how it read a swap.** A small "Read as" line
|
||||
under the script says who each new person replaces, as you type. Click it
|
||||
to open the full reading: the Ref2VA tab lists the cast lines the writer
|
||||
sends to H3, and the Plain tab says the same in everyday words. Words a
|
||||
swap can't use, such as "make the camera spin", show in amber as not
|
||||
used, and a line the writer would refuse says why before you run it. The
|
||||
writer also reads more ways of saying it: a description right after the
|
||||
picture ("replaced by @1, a game character with orange hair"), names
|
||||
("Elon is @1"), clothes after "and wears", and one line per person when
|
||||
two people swap. Before, some of those words were dropped or the wrong
|
||||
person was replaced.
|
||||
- **Undo takes back a drag on a node's face as its own step.** Moving a
|
||||
moment on H3 Prompt Writer's timeline, picking a picture's job from its
|
||||
chip, dragging Strength Curve's points, and picking the crop side or the
|
||||
next file on Load Image's strip were never kept as steps of their own.
|
||||
One Ctrl+Z took back the change before them too, and the drag could not
|
||||
be brought back. Each one is its own step now.
|
||||
- **H3 Prompt Writer 🆎 shows the script's problems when the clip sets the
|
||||
length.** With copy its moves, swap the person, new voice or change
|
||||
something, a mistake such as `@5` now shows under the script, as it does
|
||||
for the other jobs. Before, the node said nothing and the run stopped.
|
||||
- **H3 Prompt Writer 🆎 speaks a line whose closing quote is missing.**
|
||||
`He says "Wait for me` is spoken to the end of the line, the way the
|
||||
script box already colours it. Before, the words went in as plain action.
|
||||
- **H3 Prompt Writer 🆎 asks you to change a second start or end picture.**
|
||||
Two pictures set to start on it, or two set to end on it, now say which
|
||||
one to change. Before, the second one was left out of the prompt without
|
||||
a word.
|
||||
- **H3 Prompt Writer 🆎's picture chips stay on one line.** With four
|
||||
pictures and a video plugged in, the video chip dropped onto the Length
|
||||
row, where it was hard to click. The chips now share their row: on a
|
||||
narrow node the longest jobs are cut short first, and pointing at a chip
|
||||
shows its whole job.
|
||||
- **H3 Prompt Writer 🆎 says when a style picture is used like a thing.** A
|
||||
line such as "@1 wears @3" with Picture 3 set to style now shows a note
|
||||
under the timeline: a style is a look, so write "in the style of @3" or
|
||||
give the picture another job. The run still goes ahead.
|
||||
- **H3 Prompt Writer 🆎 gives each person named in words their own line.**
|
||||
With `A barista … says "…"` and `The customer … says "…"`, both lines
|
||||
went to the person in the picture. Each one now says their own line.
|
||||
- **H3 Prompt Writer 🆎 says a shout typed without quotes.** `he yells wait`
|
||||
is spoken now. Before, it was read as something that happens, and nothing
|
||||
was said.
|
||||
- **H3 Prompt Writer 🆎 keeps how a line is said.** `@1 whispers "Stay
|
||||
quiet."`, `shouts`, `sings`, `yells`, `mutters` and `asks` all reached
|
||||
the model as "says". The word you typed is kept now, and so are words
|
||||
between it and the line, as in `says quietly "Hello."`.
|
||||
- **H3 Prompt Writer 🆎 reads "Close-up of her boots" as a framing.** After
|
||||
a blank line, a framing typed without "a" in front ("Close-up of...",
|
||||
"Wide shot of...", "POV from...") was sent to H3 as a cut to a new place,
|
||||
and the person could come back in other clothes. It is now a cut to that
|
||||
framing in the same place, as "a close-up of..." already was.
|
||||
- **H3 Prompt Writer 🆎 ignores chat talk from its small model.** When the
|
||||
model on clip answered "Sure! Here are the next moments:" or "I'm sorry,
|
||||
but I can't help with that", those words became a moment in the clip or
|
||||
its sound. They are left out now, and so are labels such as "Moment 2:"
|
||||
in front of a line.
|
||||
- **H3 Prompt Writer 🆎 keeps what someone does after they speak.** A line
|
||||
such as `@1 says "Hi" and waves.` went to H3 as "and waves." with nobody
|
||||
doing it. The writer now puts the person back and keeps the order: the
|
||||
line is said, then @1 waves. Words about how a line is said, like
|
||||
"slowly" or "to the camera", stay with the speaker too. A sign's words
|
||||
("a sign reading "CLOSED"") end their sentence, and bold or italic marks
|
||||
pasted with a script (`**@1**`) no longer reach the prompt.
|
||||
- **H3 Prompt Writer 🆎 hears a line in single quotes with an apostrophe.**
|
||||
"She says 'I don't know.'" was written as plain text, so nobody spoke it.
|
||||
The words are now a spoken line, as they are in double quotes.
|
||||
- **H3 Prompt Writer 🆎: "none" in Sound turns the sound off.** Typing none,
|
||||
off, silent or no sound in Sound wrote the word "None." as the clip's
|
||||
sound. It now means no sound of the place, and the music you typed stays.
|
||||
The same words in Music mean no music.
|
||||
- **H3 Prompt Writer 🆎: clearer timeline and messages.** A 4 s clip shows a
|
||||
4 s bar. The note under a clip that H3 shortens says how much is left
|
||||
out. `@5` says there are four pictures, and a line that names a missing
|
||||
picture says to connect it or turn it on.
|
||||
- **Long text boxes scroll with the mouse wheel in Nodes 2.0.** In the new
|
||||
node view, turning the wheel over a text box with more lines than fit
|
||||
zoomed the graph and the text stayed put, even while typing in it. The
|
||||
box now scrolls first, and the graph zooms once the text is at its top or
|
||||
bottom, as in the classic view. This covers Text 🆎, Text Lines 🆎,
|
||||
Prompt Variations 🆎, Krea 2 Encode 🆎 and H3 Prompt Writer 🆎.
|
||||
- **Mask Refine 🆎's guided and matting edges follow the picture.** Both
|
||||
edge modes now look further from the mask's edge and snap to the real
|
||||
edge in the guide image, so hair and thin parts a rough mask missed come
|
||||
back. Two new settings under More, Detail range and Fix threshold, tune
|
||||
them. Workflows that use guided or matting will give a cleaner, different
|
||||
edge after updating. The node can also run on its own now, to check a
|
||||
mask before the rest of the graph. Thanks to kajan988.
|
||||
- **LoRA Loader 🆎 leaves out a skipped LoRA's trigger words on a flat
|
||||
curve too.** With Stop on missing LoRA off, a row whose file is missing is
|
||||
skipped and its trigger words stay out of `triggers`. That broke when the
|
||||
row followed a Strength Curve that holds one value the whole run: the LoRA
|
||||
was skipped, but its words still reached the prompt. They stay out now,
|
||||
as they already did with no curve or a curve that moves.
|
||||
- **H3 Prompt Writer 🆎 shows only the sockets you use.** A new node has
|
||||
five inputs and four outputs, where it had nine and fourteen. Connect a
|
||||
picture and the next picture socket appears, and an output appears once
|
||||
its input is connected. The picture chips under the words do the same: a
|
||||
chip shows for each picture or video you plugged in. Saved workflows are
|
||||
unchanged: every wire stays where it was and the node sends the same
|
||||
things. To see every socket and chip all the time, turn on **Settings →
|
||||
🆎 AusBoss → H3 Prompt Writer → Show every socket**.
|
||||
- **H3 Prompt Writer 🆎: the grey hints in Sound and Music read as examples.**
|
||||
They now say `(e.g. rain on a window)` and `(e.g. slow piano)` in
|
||||
italics, so an empty box no longer looks filled in. Every one-line text
|
||||
box in the pack shows its hint in italics.
|
||||
|
||||
## 2.29.0 - 2026-11-27
|
||||
|
||||
- **H3 Prompt Writer 🆎 can tidy up your lines.** Turn on **More → Tidy up
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="105" height="20" role="img" aria-label="release: v2.29.0">
|
||||
<title>release: v2.29.0</title>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="105" height="20" role="img" aria-label="release: v2.30.0">
|
||||
<title>release: v2.30.0</title>
|
||||
<path fill="#555" d="M0 0h48v20H0z"/>
|
||||
<path fill="#00b4aa" d="M48 0h57v20H48z"/>
|
||||
<g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" font-size="11">
|
||||
<text x="24" y="14">release</text>
|
||||
<text x="76.5" y="14">v2.29.0</text>
|
||||
<text x="76.5" y="14">v2.30.0</text>
|
||||
</g>
|
||||
</svg>
|
||||
|
||||
|
Before Width: | Height: | Size: 425 B After Width: | Height: | Size: 425 B |
@@ -43,6 +43,7 @@ recipe.
|
||||
| `audit_workflows.mjs <port> <output-dir> [workflow.json ...]` | loads every example (or selected files), exports API and loaded graphs, captures screenshots, and fails on overlaps, missing nodes, browser exceptions, or exposed AusBoss number widgets |
|
||||
| `wheel_sweep.mjs <port> [--vue] [--only=Type,Type] [--workflow=file.json] [--shots=dir]` | turns the mouse wheel at every point of every node of the pack (or of the nodes in one workflow) and fails on any spot where the graph does not zoom, naming the element that took the wheel; `--real` sends real wheel turns, slower and on a coarser grid |
|
||||
| `face_smoke.mjs <port> [--vue] [--blocked-reads] [--only=Type,Type]` | puts one of each node of the pack on an empty graph and fails when a face does not come up: no node, a panel that is not on the page or has no size, an error thrown, a file of the pack that did not load. `--blocked-reads` acts like a privacy browser that blanks canvas pixel reads, gives every node that loads a picture a sample picture, and fails when its face then draws no picture. Needs no model, so it also runs in the nightly ComfyUI check |
|
||||
| `h3_sockets_check.mjs <port> [--vue]` | puts H3 Prompt Writer on a graph and reads the screen: which socket rows are drawn fresh, wired, unwired, after undo, a paste, a collapse and a switch of renderer, what a run would send, and what a save would write. Fails when a row shows or hides against the rule in `js/shared/h3_sockets.mjs`. `H3_LIVE_WORKFLOWS` adds saved workflows to open. Needs no model, so it also runs in the nightly ComfyUI check |
|
||||
| `cdp_nav_debug.mjs <port>` | navigates the tab in place and logs every CDP event, for when a tab stops answering |
|
||||
| `cdp_hang.mjs <port>` | pre-arms the debugger on a fresh tab, loads ComfyUI, and pauses to print the stack if the page stops answering |
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
// under the pointer.
|
||||
import { app } from "../../../scripts/app.js";
|
||||
import {
|
||||
dragCarriesFiles, graphDragStarts, panelHost, panelKeepsWheel, panelNeedsDropHelp, panelRoot,
|
||||
dragCarriesFiles, graphDragStarts, panelHost, panelKeepsWheel, panelNeedsDropHelp, panelRoot, vueBoxKeepsWheel,
|
||||
} from "../shared/canvas_passthrough.mjs";
|
||||
import { showToast } from "../shared/index.mjs";
|
||||
|
||||
@@ -26,6 +26,14 @@ function canvas() {
|
||||
return app.canvas ?? null;
|
||||
}
|
||||
|
||||
// Nodes 2.0 hands every wheel turn over a node to the graph before the node
|
||||
// sees it. This runs first, on the way down: a box of the pack's that can
|
||||
// still scroll keeps the wheel, the event stops here, and the browser
|
||||
// scrolls the box.
|
||||
function onWheelFirst(event) {
|
||||
if (vueBoxKeepsWheel(event.target, event, { styleOf: (el) => getComputedStyle(el) })) event.stopPropagation();
|
||||
}
|
||||
|
||||
function onWheel(event) {
|
||||
const target = event.target;
|
||||
const root = panelRoot(target);
|
||||
@@ -128,6 +136,7 @@ app.registerExtension({
|
||||
// The wheel listener sits in the bubble phase so a panel's own handler
|
||||
// (stopPropagation / preventDefault) always gets the first say.
|
||||
window.addEventListener("wheel", onWheel, { passive: false });
|
||||
window.addEventListener("wheel", onWheelFirst, { capture: true, passive: true });
|
||||
window.addEventListener("pointerdown", onPointerDown, true);
|
||||
window.addEventListener("pointermove", onPointerMove, true);
|
||||
window.addEventListener("pointerup", onPointerEnd, true);
|
||||
|
||||
@@ -7,6 +7,28 @@ Use it with MiniMax H3 or Pika H3 Flex. Connect up to four pictures and give eac
|
||||
one a job. Copy the moves from a video, keep a clip going, or add a voice or a
|
||||
song.
|
||||
|
||||
## Sockets appear as you use them
|
||||
|
||||
The node shows only the sockets you are using, so its face stays small.
|
||||
|
||||
- A new node has one picture socket. Connect a picture and the next one
|
||||
appears, up to four.
|
||||
- **video_sound** appears once a video is connected.
|
||||
- An output appears once its input is connected: connect two pictures and
|
||||
two picture outputs show. **song_under** needs a voice and a song, and
|
||||
**keeps_clip_sound** a video. **prompt**, **frames**, **width** and
|
||||
**height** are always there.
|
||||
- A socket with a wire on it always shows.
|
||||
- The picture chips under the words work the same way: a chip shows for each
|
||||
picture or video you plugged in. If its loader is turned off, the chip
|
||||
turns faint and says **off**.
|
||||
|
||||
Nothing changes in a workflow you already saved: every wire stays where it
|
||||
was and the node sends the same things. To see every socket and chip all the
|
||||
time, pick **all** under **Sockets** in the gear menu (the gear at the top
|
||||
right of the node), or turn on **Settings → 🆎 AusBoss → H3 Prompt Writer →
|
||||
Show every socket**. Both are the same setting.
|
||||
|
||||
## How to write it
|
||||
|
||||
Every line is a moment, and the lines play in order in one shot. The bar under
|
||||
@@ -114,7 +136,8 @@ Connect a video, then pick what it is for:
|
||||
This keeps the person in the clip, so a person picture is not allowed here;
|
||||
use **swap the person** to change who is in it.
|
||||
|
||||
If your swap keeps the video's audio, connect it to **video_sound** and turn on
|
||||
If your swap keeps the video's audio, connect it to **video_sound** (it shows
|
||||
once a video is connected) and turn on
|
||||
**More → Clip's own sound**. The writer uses the clip to estimate when each
|
||||
line is spoken and keeps only the incoming people's words in the swap prompt.
|
||||
Type a time such as `3.2s:` to set it yourself. This switch starts off.
|
||||
@@ -234,7 +257,7 @@ as not plugged in.
|
||||
the clip. Clay and 3D don't work from words, so change your picture first with
|
||||
an edit model.
|
||||
- **Picture 1** to **Picture 4** (`job_1` to `job_4`): what each picture is
|
||||
for, on the picture chips under the bar. An empty slot shows as a faint `+ @3`.
|
||||
for, on the picture chips under the bar. A chip shows once its picture is plugged in.
|
||||
- **Video** (`video_job`): what the video is for, on the video chip.
|
||||
- **Song starts at** (`song_start`, under **More**): the second of the song to
|
||||
start from, so the clip gets the good part.
|
||||
@@ -253,6 +276,20 @@ as not plugged in.
|
||||
**clip** it does nothing, so a workflow can leave it on. Starts off.
|
||||
- **Full prompt** (`full_prompt`, on the Full prompt tab): your own edit of the
|
||||
finished prompt. Empty means the node's own prompt is sent.
|
||||
- **What the model is asked** (`model_asks`, in the gear menu): the four things
|
||||
the model on **clip** is asked, each with an **Edit** button. **Describe a new
|
||||
person** writes how a new person in a swap looks from their picture. **Fill in
|
||||
the next moments** writes what happens after a single typed line. **Hear the
|
||||
place** writes the steady sound of the place. **Tidy up my lines** holds the
|
||||
instructions for Tidy up. Change the words to steer the model; `{seconds}`,
|
||||
`{first}`, `{count}` and `{lines}` are filled in by the node. Your wording is
|
||||
saved in this node, so a shared workflow asks the same. **Back to built-in**
|
||||
puts the node's own wording back. They only matter with a text model plugged
|
||||
into **clip**. If your wording loses `{lines}` or another filled-in name,
|
||||
**Save** first says what the model will miss; press it again to keep it.
|
||||
**Esc** over typing you have not saved asks once before it closes.
|
||||
**Reset** at the bottom of the menu puts the sockets and all four wordings
|
||||
back at once; Ctrl+Z brings yours back.
|
||||
|
||||
## Tips
|
||||
|
||||
|
||||
@@ -195,6 +195,35 @@ used ComfyUI's Remove Background template, you already have it.
|
||||
A workflow that already has Fine edges on tells ComfyUI which file it needs,
|
||||
so ComfyUI lists it under **Missing Models** with a download button.
|
||||
|
||||
### RMBG-3.0: softer hair, bigger and slower
|
||||
|
||||
Bria's RMBG-3.0 keeps loose strands, fur and lace that BiRefNet cuts into a
|
||||
hard edge. Once its files are in place, **Fine edges** offers **RMBG-3.0**
|
||||
next to **BiRefNet**, and **Subject** and **Background** use the one you pick.
|
||||
Fine edges still starts at **off**, and while it is off, Subject and
|
||||
Background use BiRefNet.
|
||||
|
||||
It costs more: about 14 GB of files, up to about 17 GB of graphics memory (a
|
||||
24 GB card), and
|
||||
about 2 seconds a picture once it is loaded, where BiRefNet takes under one.
|
||||
The first picture also waits while it loads. Its licence
|
||||
is non-commercial (CC BY-NC 4.0): for paid work, Bria sells a licence. Keep
|
||||
BiRefNet for that.
|
||||
|
||||
From the Hugging Face page `briaai/RMBG-3.0-Comfy`:
|
||||
|
||||
1. `diffusion_models/rmbg3_int8_convrot.safetensors` into
|
||||
`ComfyUI/models/diffusion_models`.
|
||||
2. `text_encoders/qwen3vl_4b_int8_convrot.safetensors` into
|
||||
`ComfyUI/models/text_encoders`.
|
||||
3. `vae/flux2-vae.safetensors` into `ComfyUI/models/vae`.
|
||||
4. Press **R**, then set **Fine edges** to **RMBG-3.0**.
|
||||
|
||||
It needs ComfyUI 0.43 or newer. Keep the model's file name starting with
|
||||
`rmbg3`: that is how the node knows it. After moving a file into a
|
||||
subfolder, pick it again under Fine edges. With both of Bria's copies (int8
|
||||
and bf16), Fine edges says which is which.
|
||||
|
||||
Good to know:
|
||||
|
||||
- Fine edges works on the outline of the main subject: a person's hair
|
||||
@@ -425,6 +454,15 @@ no browser:
|
||||
node, the plain edge is shown instead, with the same line.
|
||||
- **Free VRAM** unloads this model as well.
|
||||
|
||||
With RMBG-3.0 the subject comes from ComfyUI's own nodes, run the way Comfy's
|
||||
RMBG-3.0 template runs them: its fixed matting instruction, 4 steps, cfg 1,
|
||||
euler, simple, seed 42. The picture is stretched (never cropped) to about one
|
||||
megapixel in steps of 16 pixels, and the red channel of what it paints is
|
||||
scaled back to the picture's size, so the matte lines up pixel for pixel. Its
|
||||
model, text reader and VAE are loaded once and kept, and Free VRAM unloads all
|
||||
three. One copy is held at a time, and it is unloaded before BiRefNet runs.
|
||||
Each picture of a batch is worked out once per run, however long the batch.
|
||||
|
||||
### The things that light up
|
||||
|
||||
- The node asks SAM 3 about a picture in this order: the place under the
|
||||
|
||||
@@ -6,6 +6,9 @@ quick brush before the mask goes to an inpainter. It can also snap the edge
|
||||
to a guide image and adjust the mask's levels. Both the refined mask and its
|
||||
inverse are returned, so no separate invert node is needed.
|
||||
|
||||
You can run it on its own, with nothing wired after it, to check the mask
|
||||
before the rest of the graph runs.
|
||||
|
||||
The panel shows the refined mask itself once the node has run, so the effect
|
||||
of a setting is visible without wiring a preview node beside it. With a batch
|
||||
or a video it shows the first mask. The small
|
||||
@@ -58,12 +61,19 @@ run the workflow again. The switch is the node's optional `preview` input.
|
||||
- **Edge** (`edge_refine`): `off`, **guided** (`guided filter`), or
|
||||
`matting`. Both refinements snap the mask edge to the connected
|
||||
**guide_image** and run per frame, so video batches stay interruptible:
|
||||
- `guided filter` — fast edge-aware filtering of the soft mask against the
|
||||
guide image. The filter radius scales with **Expand**.
|
||||
- `matting` — closed-form alpha matting: the binarized mask eroded by the
|
||||
edge radius counts as definite foreground, the dilation marks where
|
||||
definite background begins, and the band between is solved against the
|
||||
guide image. Pair it with the levels remap to tidy the solved alpha.
|
||||
- `guided filter` — fast. Pulls the mask's edge onto the edges in the
|
||||
guide image, which picks up thin parts and loose strands a rough mask
|
||||
missed. **Detail range** sets how far it looks.
|
||||
- `matting` — slower and finer. Softens the mask's edge over a wide band
|
||||
and works out the real edge inside it from the guide image. Pair it
|
||||
with the levels remap to tidy the result.
|
||||
- **Detail range** (`detail_range`): How far from the mask's edge to look
|
||||
for the real edge, `12` by default. Raise it for hair or a loose mask,
|
||||
lower it for a small subject. Used only while **Edge** is on.
|
||||
- **Fix threshold** (`fix_threshold`): How much of the softened edge
|
||||
matting may rework. The default, `0.01`, lets it fix the whole edge;
|
||||
higher values trim the mask inward. Used only while **Edge** is
|
||||
`matting`.
|
||||
- **guide_image** (optional input): RGB frames the mask belongs to, matching
|
||||
the mask's size; one frame is broadcast across a mask batch. Required when
|
||||
`edge_refine` is not `off`.
|
||||
|
||||
@@ -0,0 +1,177 @@
|
||||
// H3 Prompt Writer 🆎 draws only the sockets in use.
|
||||
//
|
||||
// The node keeps every socket in its lists: a wire is saved by its socket's
|
||||
// number, so taking one out would send the wrong output. A socket that is
|
||||
// not in use is only left out of the drawing. The rule is in
|
||||
// js/shared/h3_sockets.mjs.
|
||||
//
|
||||
// classic a hidden socket gets a position of its own, which takes it
|
||||
// out of the stacked rows, and draws nothing.
|
||||
// Nodes 2.0 one style rule hides the socket's row by its data-slot-key.
|
||||
//
|
||||
// If either lever is missing in the running frontend, every socket shows,
|
||||
// as it always did.
|
||||
import { app } from "../../../scripts/app.js";
|
||||
import { chainCallback } from "../shared/index.mjs";
|
||||
import { lookupLink } from "../shared/graph_links.mjs";
|
||||
import { SHOW_ALL, dropTarget, hiddenRowsRule, setSocketHidden, socketsToShow } from "../shared/h3_sockets.mjs";
|
||||
|
||||
const NODE_CLASS = "AUSBOSS_NODES_H3PromptWriter";
|
||||
const STYLE_ID = "ausboss-h3-sockets";
|
||||
|
||||
const showAll = () => Boolean(app.extensionManager?.setting?.get?.(SHOW_ALL));
|
||||
|
||||
let warned = false;
|
||||
// Nothing here may stop a node from loading: on a throw the sockets show.
|
||||
function safely(run) {
|
||||
return function (...args) {
|
||||
try { return run.apply(this, args); } catch (error) {
|
||||
if (!warned) console.warn("[AusBoss] H3 Prompt Writer shows every socket:", error);
|
||||
warned = true;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
const plainInputs = (node) => (node.inputs ?? []).filter((slot) => !slot.widget);
|
||||
const outputWired = (slot) => (slot.links?.length ?? 0) > 0;
|
||||
const shownRows = (node) => Math.max(
|
||||
plainInputs(node).filter((slot) => !slot._ausbossHidden).length,
|
||||
(node.outputs ?? []).filter((slot) => !slot._ausbossHidden).length,
|
||||
1,
|
||||
);
|
||||
const hiddenRows = (node) => Math.max(plainInputs(node).length, (node.outputs ?? []).length, 1) - shownRows(node);
|
||||
const rowHeight = () => globalThis.LiteGraph?.NODE_SLOT_HEIGHT ?? 20;
|
||||
|
||||
function writerNodes(graph = app.graph, found = []) {
|
||||
for (const node of graph?._nodes ?? []) {
|
||||
if (node.type === NODE_CLASS) found.push(node);
|
||||
if (node.subgraph) writerNodes(node.subgraph, found);
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
// Nodes 2.0 draws a row for every socket of the list. One style sheet for
|
||||
// the page holds each node's hidden rows.
|
||||
function writeStyleRules() {
|
||||
const rules = writerNodes().map((node) => node._ausbossSocketRule ?? "").filter(Boolean).join("\n");
|
||||
let sheet = document.getElementById(STYLE_ID);
|
||||
if (!sheet && !rules) return;
|
||||
sheet ??= document.head.appendChild(Object.assign(document.createElement("style"), { id: STYLE_ID }));
|
||||
if (sheet.textContent !== rules) sheet.textContent = rules;
|
||||
}
|
||||
|
||||
export function applySockets(node) {
|
||||
if (!node?.inputs || !node?.outputs) return;
|
||||
// The rows as this node last had them. Not counted from the sockets: a
|
||||
// paste or a copy gives the node new socket objects, with no marks.
|
||||
const rowsBefore = node._ausbossSocketRows;
|
||||
const show = socketsToShow({
|
||||
wiredInputs: plainInputs(node).filter((slot) => slot.link != null).map((slot) => slot.name),
|
||||
wiredOutputs: node.outputs.filter(outputWired).map((slot) => slot.name),
|
||||
showAll: showAll(),
|
||||
inputNames: plainInputs(node).map((slot) => slot.name),
|
||||
outputNames: node.outputs.map((slot) => slot.name),
|
||||
});
|
||||
const hiddenKeys = [];
|
||||
node.inputs.forEach((slot, index) => {
|
||||
if (slot.widget) return;
|
||||
const hide = !show.inputs.has(slot.name);
|
||||
if (setSocketHidden(slot, hide) && hide) hiddenKeys.push(`in-${index}`);
|
||||
});
|
||||
node.outputs.forEach((slot, index) => {
|
||||
const hide = !show.outputs.has(slot.name);
|
||||
if (setSocketHidden(slot, hide) && hide) hiddenKeys.push(`out-${index}`);
|
||||
});
|
||||
// When the hidden rows change, the nudge flips, so Nodes 2.0 measures the
|
||||
// sockets again and every wire ends on its dot.
|
||||
const hiddenNow = hiddenKeys.join(",");
|
||||
if (node._ausbossHiddenRows !== undefined && node._ausbossHiddenRows !== hiddenNow) node._ausbossNudge = !node._ausbossNudge;
|
||||
node._ausbossHiddenRows = hiddenNow;
|
||||
node._ausbossSocketRule = hiddenRowsRule(node.id, hiddenKeys, Boolean(node._ausbossNudge));
|
||||
writeStyleRules();
|
||||
|
||||
// The node gets a row taller or shorter with its sockets, so the panel
|
||||
// keeps its size. A workflow that is loading keeps the size it was saved at.
|
||||
const rows = shownRows(node);
|
||||
if (rowsBefore != null && rows !== rowsBefore && !app.configuringGraph && node.size) {
|
||||
node.setSize([node.size[0], node.size[1] + (rows - rowsBefore) * rowHeight()]);
|
||||
}
|
||||
node._ausbossSocketRows = rows;
|
||||
node.setDirtyCanvas?.(true, true);
|
||||
}
|
||||
|
||||
// A wire dropped on the node's body goes to the socket the frontend finds
|
||||
// for its kind, and the first free one can be one nobody can see (an audio
|
||||
// wire finds video_sound before voice). Nodes 2.0 then makes no wire at
|
||||
// all, as a hidden row has no place to snap to. So the node answers with
|
||||
// the first shown socket of that kind that can take the wire. The same goes
|
||||
// for a wire pulled from another node's input, which lands on an output.
|
||||
function shownSocketFor(node, found, outputs) {
|
||||
if (!found?.slot?._ausbossHidden) return found;
|
||||
const slots = outputs ? node.outputs : node.inputs;
|
||||
const target = dropTarget(slots.map((slot) => ({
|
||||
name: slot.name,
|
||||
type: slot.type,
|
||||
// A wire that is being dragged away leaves its socket free.
|
||||
wired: outputs ? outputWired(slot) : slot.link != null && !lookupLink(node.graph, slot.link)?._dragging,
|
||||
shown: !slot.widget && !slot._ausbossHidden,
|
||||
})), found.index, { shared: outputs });
|
||||
return target === found.index ? found : { index: target, slot: slots[target] };
|
||||
}
|
||||
|
||||
app.registerExtension({
|
||||
name: "AusBoss.H3Sockets",
|
||||
settings: [
|
||||
{
|
||||
id: SHOW_ALL,
|
||||
name: "Show every socket on H3 Prompt Writer",
|
||||
type: "boolean",
|
||||
defaultValue: false,
|
||||
category: ["🆎 AusBoss", "H3 Prompt Writer", "Show every socket"],
|
||||
tooltip:
|
||||
"H3 Prompt Writer shows only the sockets and picture chips you are using. "
|
||||
+ "Turn this on to see all of them all the time.",
|
||||
// The card redraws too: its row of picture chips follows the setting.
|
||||
onChange: safely(() => writerNodes().forEach((node) => { applySockets(node); node.__ausbossCard?.refresh?.(); })),
|
||||
},
|
||||
],
|
||||
beforeRegisterNodeDef(nodeType, nodeData) {
|
||||
if (nodeData.name !== NODE_CLASS) return;
|
||||
const proto = nodeType.prototype;
|
||||
|
||||
// The least height counts only the rows that are drawn.
|
||||
const computeSize = proto.computeSize;
|
||||
proto.computeSize = function (...args) {
|
||||
const size = computeSize.apply(this, args);
|
||||
try { size[1] -= hiddenRows(this) * rowHeight(); } catch { /* the full height is a safe answer */ }
|
||||
return size;
|
||||
};
|
||||
|
||||
for (const [name, outputs] of [["findInputByType", false], ["findOutputByType", true]]) {
|
||||
const find = proto[name];
|
||||
if (typeof find !== "function") continue;
|
||||
proto[name] = function (...args) {
|
||||
const found = find.apply(this, args);
|
||||
try { return shownSocketFor(this, found, outputs); } catch { return found; }
|
||||
};
|
||||
}
|
||||
|
||||
const apply = safely(function () { applySockets(this); });
|
||||
chainCallback(proto, "onNodeCreated", apply);
|
||||
chainCallback(proto, "onAdded", apply);
|
||||
// A node that takes a saved state (a load, a paste, a copy) keeps the
|
||||
// size that came with it.
|
||||
chainCallback(proto, "onConfigure", safely(function () { this._ausbossSocketRows = null; applySockets(this); }));
|
||||
chainCallback(proto, "onConnectionsChange", apply);
|
||||
chainCallback(proto, "onRemoved", safely(function () {
|
||||
this._ausbossSocketRule = "";
|
||||
// The node is still in the graph's list while it is being removed.
|
||||
queueMicrotask(safely(writeStyleRules));
|
||||
}));
|
||||
// The saved node is what it always was: no parked position in it.
|
||||
chainCallback(proto, "onSerialize", safely(function (saved) {
|
||||
(saved.inputs ?? []).forEach((slot, index) => { if (this.inputs?.[index]?._ausbossHidden) delete slot.pos; });
|
||||
(saved.outputs ?? []).forEach((slot, index) => { if (this.outputs?.[index]?._ausbossHidden) delete slot.pos; });
|
||||
}));
|
||||
},
|
||||
});
|
||||
@@ -41,6 +41,18 @@ export function panelKeepsWheel(target, event, { root, host, styleOf }) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Nodes 2.0 hands every wheel turn over a node to the graph on its way down
|
||||
// to the node, before any part of the node sees it (only a focused core text
|
||||
// box is spared). A box of the pack's that can still scroll the way the wheel
|
||||
// turns has to claim the wheel before that. The classic renderer lets the box
|
||||
// see the wheel first, so there it needs no claim.
|
||||
export function vueBoxKeepsWheel(target, event, { styleOf }) {
|
||||
if (!target?.closest?.(".lg-node-widgets")) return false;
|
||||
const root = panelRoot(target);
|
||||
if (!root) return false;
|
||||
return panelKeepsWheel(target, event, { root, host: panelHost(target), styleOf });
|
||||
}
|
||||
|
||||
// Gestures that start over a panel and still mean "move the graph": the
|
||||
// middle button (pan), and Ctrl + Shift + left button (drag-zoom) when the
|
||||
// user has that shortcut switched on.
|
||||
|
||||
+52
-21
@@ -1,10 +1,15 @@
|
||||
// The row of chips on H3 Prompt Writer: each picture plugged in, with its @
|
||||
// name, a small copy of it and its job, then the video and its job. A slot with nothing plugged in is a faint
|
||||
// dashed chip, so it reads as optional. The widgets underneath stay the
|
||||
// source of truth: a chip only changes their value.
|
||||
// name, a small copy of it and its job, then the video and its job. A slot
|
||||
// with nothing plugged in has no chip (js/shared/h3_sockets.mjs holds the
|
||||
// rule). A picture whose loader is turned off keeps a faint dashed chip that
|
||||
// says so. The widgets underneath stay the source of truth: a chip only
|
||||
// changes their value. The chips share one line. On a narrow node the widest
|
||||
// chips give way first, their job cut short, so a short job such as "place"
|
||||
// stays whole for as long as it can.
|
||||
import { app } from "../../../scripts/app.js";
|
||||
import { BRAND, chainCallback } from "./index.mjs";
|
||||
import { BRAND, chainCallback, notifyAusbossChange } from "./index.mjs";
|
||||
import { THEME as T, FONT_UI } from "./theme.mjs";
|
||||
import { SHOW_ALL, chipsToShow } from "./h3_sockets.mjs";
|
||||
import { liftSocket } from "./widget_card.mjs";
|
||||
import { commitWidgetValue, comboValues } from "./widget_card_math.mjs";
|
||||
|
||||
@@ -16,13 +21,13 @@ function ensureCss() {
|
||||
const style = document.createElement("style");
|
||||
style.id = CSS_ID;
|
||||
style.textContent = `
|
||||
.ausboss-chips{display:flex;flex-wrap:wrap;align-content:flex-start;gap:5px;height:100%;min-width:0;font:600 10.5px/1 -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif}
|
||||
.ausboss-chip{position:relative;display:flex;align-items:center;gap:4px;height:24px;max-width:100%;padding:0 8px;box-sizing:border-box;border:1px solid #2a3437;border-radius:12px;background:#0b0f10;color:#d8ecea;white-space:nowrap}
|
||||
.ausboss-chips{display:grid;grid-auto-flow:column;grid-auto-columns:minmax(0,max-content);justify-content:start;align-items:start;gap:5px;height:100%;min-width:0;font:600 10.5px/1 -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif}
|
||||
.ausboss-chip{position:relative;display:flex;align-items:center;gap:4px;height:24px;min-width:0;max-width:100%;padding:0 8px;box-sizing:border-box;border:1px solid #2a3437;border-radius:12px;background:#0b0f10;color:#d8ecea;white-space:nowrap}
|
||||
.ausboss-chip:hover{border-color:${BRAND}}
|
||||
.ausboss-chip img{flex:none;width:18px;height:18px;margin-left:-5px;border-radius:9px;object-fit:cover}
|
||||
.ausboss-chip b{flex:none;color:${BRAND};font:700 10px ui-monospace,SFMono-Regular,Menlo,monospace}
|
||||
.ausboss-chip em{flex:none;color:#6f8886;font-style:normal;font-weight:500}
|
||||
.ausboss-chip-pick{min-width:0;max-width:120px;height:22px;padding:0 12px 0 0;border:none;background:transparent url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='8' height='5' viewBox='0 0 8 5'%3E%3Cpath d='M1 1l3 3 3-3' fill='none' stroke='%236f8886' stroke-width='1.4'/%3E%3C/svg%3E") no-repeat right 1px center;color:#d8ecea;font:inherit;cursor:pointer;overflow:hidden;white-space:nowrap;text-overflow:ellipsis;text-align:left}
|
||||
.ausboss-chip-pick{flex:0 1 auto;min-width:0;max-width:120px;height:22px;padding:0 12px 0 0;border:none;background:transparent url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='8' height='5' viewBox='0 0 8 5'%3E%3Cpath d='M1 1l3 3 3-3' fill='none' stroke='%236f8886' stroke-width='1.4'/%3E%3C/svg%3E") no-repeat right 1px center;color:#d8ecea;font:inherit;cursor:pointer;overflow:hidden;white-space:nowrap;text-overflow:ellipsis;text-align:left}
|
||||
.ausboss-chip-pick:focus-visible{outline:2px solid ${BRAND};outline-offset:2px;border-radius:3px}
|
||||
.ausboss-chip.open{border-color:${BRAND}}
|
||||
.ausboss-chip-menu{position:fixed;z-index:10000;box-sizing:border-box;padding:.33em;border:1px solid ${T.rule};border-radius:.66em;background:${T.card};box-shadow:0 10px 32px rgba(0,0,0,.55);font:500 12px/1.25 ${FONT_UI};color:${T.inkSoft}}
|
||||
@@ -31,6 +36,7 @@ function ensureCss() {
|
||||
.ausboss-chip-item.current::before{content:"\\2713"}
|
||||
.ausboss-chip-item.current{color:${T.brandInk}}
|
||||
.ausboss-chip-item.hot{background:${T.fill};color:${T.ink}}
|
||||
.ausboss-chip span{min-width:0;overflow:hidden;text-overflow:ellipsis}
|
||||
.ausboss-chip.off{border-style:dashed;background:transparent;color:#56706d}
|
||||
.ausboss-chip.off:hover{border-color:#2a3437}
|
||||
.ausboss-chip.wired{color:#8ba3a1}
|
||||
@@ -47,6 +53,19 @@ function linkSource(node, name) {
|
||||
return (source?.mode ?? 0) === 0 ? source ?? {} : null;
|
||||
}
|
||||
|
||||
const hasWire = (node, name) => {
|
||||
const slot = node.inputs?.find((input) => !input?.widget && input?.name === name);
|
||||
return slot?.link !== null && slot?.link !== undefined;
|
||||
};
|
||||
|
||||
// The names of the chips this node draws now: picture_1 to picture_4, video.
|
||||
export function castChipNames(node) {
|
||||
return chipsToShow({
|
||||
wiredInputs: ["picture_1", "picture_2", "picture_3", "picture_4", "video"].filter((name) => hasWire(node, name)),
|
||||
showAll: Boolean(app.extensionManager?.setting?.get?.(SHOW_ALL)),
|
||||
});
|
||||
}
|
||||
|
||||
const widgetOf = (node, name) => node.widgets?.find((widget) => widget.name === name) ?? null;
|
||||
|
||||
function chip(className = "") {
|
||||
@@ -150,12 +169,19 @@ function choice(node, name, into) {
|
||||
const button = add(into, "button", undefined, "ausboss-chip-pick");
|
||||
button.type = "button";
|
||||
button.setAttribute("aria-haspopup", "listbox");
|
||||
button.title = widget?.options?.tooltip ?? "";
|
||||
const show = (value) => { button.textContent = String(value ?? ""); };
|
||||
// The job can be cut short on a narrow node, so the hint starts with it.
|
||||
const hint = widget?.options?.tooltip ?? "";
|
||||
const show = (value) => {
|
||||
button.textContent = String(value ?? "");
|
||||
button.title = [String(value ?? ""), hint].filter(Boolean).join("\n");
|
||||
};
|
||||
show(widget?.value);
|
||||
const choose = (value) => {
|
||||
show(value);
|
||||
if (widget && value !== widget.value) commitWidgetValue(node, widget, value, app.canvas);
|
||||
if (widget && value !== widget.value) {
|
||||
commitWidgetValue(node, widget, value, app.canvas);
|
||||
notifyAusbossChange();
|
||||
}
|
||||
node.setDirtyCanvas?.(true, true);
|
||||
};
|
||||
button.addEventListener("pointerdown", (event) => event.stopPropagation());
|
||||
@@ -192,13 +218,21 @@ export function castChips(node) {
|
||||
if (openMenu && element.contains(openMenu.owner)) openMenu.close();
|
||||
element.textContent = "";
|
||||
syncs = [];
|
||||
const names = castChipNames(node);
|
||||
// A faint chip: a socket with nothing in it (only with every socket
|
||||
// shown), or a picture whose loader is turned off.
|
||||
const faint = (name, label, plugIn) => {
|
||||
const empty = chip("off");
|
||||
const off = hasWire(node, name);
|
||||
empty.textContent = off ? `${label} off` : `+ ${label}`;
|
||||
empty.title = off ? `The loader on ${name} is turned off, so it is not used.` : plugIn;
|
||||
element.append(empty);
|
||||
};
|
||||
for (const number of [1, 2, 3, 4]) {
|
||||
if (!names.includes(`picture_${number}`)) continue;
|
||||
const source = linkSource(node, `picture_${number}`);
|
||||
if (!source) {
|
||||
const empty = chip("off");
|
||||
empty.textContent = `+ @${number}`;
|
||||
empty.title = `Plug a picture into picture_${number} to name it @${number} in your lines.`;
|
||||
element.append(empty);
|
||||
faint(`picture_${number}`, `@${number}`, `Plug a picture into picture_${number} to name it @${number} in your lines.`);
|
||||
continue;
|
||||
}
|
||||
const item = chip();
|
||||
@@ -215,20 +249,17 @@ export function castChips(node) {
|
||||
if (linkSource(node, "video_job")) add(item, "span", "job from its wire");
|
||||
else syncs.push(choice(node, "video_job", item));
|
||||
element.append(item);
|
||||
} else {
|
||||
const empty = chip("off");
|
||||
empty.textContent = "+ video";
|
||||
empty.title = "Plug a video into video to copy its moves, swap the person, keep it going or give it a new voice.";
|
||||
element.append(empty);
|
||||
} else if (names.includes("video")) {
|
||||
faint("video", "video", "Plug a video into video to copy its moves, swap the person, keep it going or give it a new voice.");
|
||||
}
|
||||
|
||||
for (const run of syncs) run(values);
|
||||
};
|
||||
|
||||
const shapeOf = () => JSON.stringify(["picture_1", "picture_2", "picture_3", "picture_4", "video", ...JOBS].map((name) => {
|
||||
const shapeOf = () => JSON.stringify([castChipNames(node), ...["picture_1", "picture_2", "picture_3", "picture_4", "video", ...JOBS].map((name) => {
|
||||
const source = linkSource(node, name);
|
||||
return source ? [source.id ?? 1, source.imgs?.[0]?.src ?? ""] : 0;
|
||||
}));
|
||||
})]);
|
||||
const sync = (values) => {
|
||||
latest = values;
|
||||
const now = shapeOf();
|
||||
|
||||
@@ -40,7 +40,7 @@ export function clipLengthWords(timing) {
|
||||
const stops = timing.startSeconds + made / H3_FPS;
|
||||
return {
|
||||
title: `H3 makes ${made} of the clip's ${timing.frames} frames · ${seconds(made)} s`,
|
||||
note: `Stops at ${String(Number(stops.toFixed(2)))} s in the video. To use all of it, set the clip's Duration to ${seconds(made)} s${up <= Math.min(room, 15 * H3_FPS) ? ` or ${seconds(up)} s` : ""}.`,
|
||||
note: `H3 leaves out the last ${seconds(timing.frames - made)} s, so it stops at ${String(Number(stops.toFixed(2)))} s in the video. To lose nothing, set the clip's Duration to ${seconds(made)} s${up <= Math.min(room, 15 * H3_FPS) ? ` or ${seconds(up)} s` : ""}.`,
|
||||
warn: true,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
// Which sockets H3 Prompt Writer 🆎 shows. The node keeps every socket in
|
||||
// its lists, so a saved workflow and what is sent are unchanged; the ones
|
||||
// not in use are only left out of the drawing (js/h3_sockets/index.js).
|
||||
//
|
||||
// Kept free of /scripts/app.js imports so node:test can cover it
|
||||
// (tests/h3_sockets.test.mjs).
|
||||
|
||||
const PICTURES = ["picture_1", "picture_2", "picture_3", "picture_4"];
|
||||
|
||||
export const INPUT_NAMES = ["clip", ...PICTURES, "video", "video_sound", "voice", "song"];
|
||||
export const OUTPUT_NAMES = [
|
||||
"prompt", ...PICTURES, "video", "video_sound", "voice", "song", "song_under",
|
||||
"frames", "width", "height", "keeps_clip_sound",
|
||||
];
|
||||
|
||||
// The setting that shows every socket, and every picture chip, all the time.
|
||||
export const SHOW_ALL = "AusBoss.H3PromptWriter.ShowEverySocket";
|
||||
|
||||
// The sockets that come and go. Every other socket always shows, and so
|
||||
// does one this rule does not know (a later release may add some).
|
||||
const PICTURE = /^picture_(\d+)$/;
|
||||
const inOrder = (names) => names.filter((name) => PICTURE.test(name))
|
||||
.sort((a, b) => Number(a.match(PICTURE)[1]) - Number(b.match(PICTURE)[1]));
|
||||
const COMES_AND_GOES_OUT = ["video", "video_sound", "voice", "song", "song_under", "keeps_clip_sound"];
|
||||
// An output that shows once the input of the same name has a wire.
|
||||
const FOLLOWS_ITS_INPUT = ["video", "video_sound", "voice", "song"];
|
||||
|
||||
// The names of the sockets to draw. A socket with a wire on it always shows.
|
||||
// `inputNames` and `outputNames` are the node's own sockets: a node with more
|
||||
// pictures than four follows the same rule.
|
||||
export function socketsToShow({
|
||||
wiredInputs = [], wiredOutputs = [], showAll = false, inputNames = INPUT_NAMES, outputNames = OUTPUT_NAMES,
|
||||
} = {}) {
|
||||
if (showAll) return { inputs: new Set(inputNames), outputs: new Set(outputNames) };
|
||||
const wired = new Set(wiredInputs);
|
||||
const inputs = new Set([...inputNames.filter((name) => !PICTURE.test(name) && name !== "video_sound"), ...wired]);
|
||||
const outputs = new Set([...outputNames.filter((name) => !PICTURE.test(name) && !COMES_AND_GOES_OUT.includes(name)), ...wiredOutputs]);
|
||||
|
||||
// Every picture up to the last wired one, and the next free one after it.
|
||||
const pictures = inOrder(inputNames);
|
||||
const lastWired = pictures.reduce((last, name, index) => (wired.has(name) ? index : last), -1);
|
||||
pictures.slice(0, lastWired + 2).forEach((name) => inputs.add(name));
|
||||
// The pictures come out in order, so two wired pictures are outputs 1 and
|
||||
// 2 whichever inputs they are on.
|
||||
const count = pictures.filter((name) => wired.has(name)).length;
|
||||
inOrder(outputNames).slice(0, count).forEach((name) => outputs.add(name));
|
||||
|
||||
if (wired.has("video")) inputs.add("video_sound");
|
||||
FOLLOWS_ITS_INPUT.filter((name) => wired.has(name)).forEach((name) => outputs.add(name));
|
||||
if (wired.has("voice") && wired.has("song")) outputs.add("song_under");
|
||||
if (wired.has("video")) outputs.add("keeps_clip_sound");
|
||||
return { inputs, outputs };
|
||||
}
|
||||
|
||||
// The chips to draw under "Pictures and settings": one for each picture and
|
||||
// for the video that has a wire, in the node's order.
|
||||
export function chipsToShow({ wiredInputs = [], showAll = false } = {}) {
|
||||
const wired = new Set(wiredInputs);
|
||||
return [...PICTURES, "video"].filter((name) => showAll || wired.has(name));
|
||||
}
|
||||
|
||||
// Where a wire dropped on the node's body should go. `slots` is the node's
|
||||
// input or output list as { name, type, wired, shown }, and `landed` the
|
||||
// index the frontend picked. A wire never stays on a socket nobody can see
|
||||
// while a shown one of the same kind can take it. An input takes one wire;
|
||||
// an output takes many (`shared`), so a wired one will do when none is free.
|
||||
export function dropTarget(slots, landed, { shared = false } = {}) {
|
||||
const slot = slots[landed];
|
||||
if (!slot || slot.shown) return landed;
|
||||
const fits = (other, index) => index !== landed && other.shown && other.type === slot.type;
|
||||
const free = slots.findIndex((other, index) => fits(other, index) && !other.wired);
|
||||
if (free !== -1) return free;
|
||||
const any = shared ? slots.findIndex(fits) : -1;
|
||||
return any === -1 ? landed : any;
|
||||
}
|
||||
|
||||
// A node's id comes from the workflow file and can be any text, so it goes
|
||||
// into a style rule escaped: it can name a row and nothing else.
|
||||
const cssText = (value) => String(value).replace(/[^A-Za-z0-9_-]/g, (char) => `\\${char.codePointAt(0).toString(16)} `);
|
||||
|
||||
// The style rule for one node in Nodes 2.0: it hides the row of each hidden
|
||||
// socket. `keys` are "in-<index>" and "out-<index>". Nodes 2.0 measures
|
||||
// where the sockets are only when the node or its widget grid changes size,
|
||||
// and a row that comes or goes in the shorter column changes neither, which
|
||||
// left wires ending beside their dots. `nudge` makes the grid a tenth of a
|
||||
// pixel narrower; flipping it makes the frontend measure again.
|
||||
export function hiddenRowsRule(nodeId, keys, nudge = false) {
|
||||
const id = cssText(nodeId);
|
||||
const rows = keys.length ? `${keys.map((key) => `.lg-slot:has([data-slot-key="${id}-${key}"])`).join(",")}{display:none}` : "";
|
||||
return nudge ? `${rows}[data-widgets-grid-node-id="${id}"]{padding-left:0.1px}` : rows;
|
||||
}
|
||||
|
||||
// A socket with a position of its own gets no row: the frontend only stacks
|
||||
// the ones without (and writes the position into the saved file, which
|
||||
// js/h3_sockets/index.js takes out again).
|
||||
const PARKED = [0, -4000];
|
||||
const noDraw = () => {};
|
||||
|
||||
// Hide or show one socket of a live node. Returns false, and changes
|
||||
// nothing, when it cannot be done here: a frontend whose sockets do not draw
|
||||
// themselves, or a socket that was placed by someone else.
|
||||
export function setSocketHidden(slot, hidden) {
|
||||
if (!slot || typeof slot.draw !== "function") return false;
|
||||
if (!slot._ausbossHidden && slot.pos) return false;
|
||||
if (hidden === Boolean(slot._ausbossHidden)) return true;
|
||||
slot._ausbossHidden = hidden;
|
||||
if (hidden) {
|
||||
slot.pos = PARKED;
|
||||
slot.draw = noDraw;
|
||||
slot.drawCollapsed = noDraw;
|
||||
} else {
|
||||
delete slot.pos;
|
||||
delete slot.draw;
|
||||
delete slot.drawCollapsed;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,233 @@
|
||||
// H3 Prompt Writer 🆎: the gear in the card's corner.
|
||||
//
|
||||
// Sockets in use | all. The same choice as the ComfyUI setting "Show
|
||||
// every socket on H3 Prompt Writer" (js/h3_sockets), so it
|
||||
// holds for every writer on this browser.
|
||||
// The model what the small model on clip is asked, four wordings. Each
|
||||
// opens in an editor; an edited one is saved in this node's
|
||||
// hidden model_asks input, so a shared workflow asks the same.
|
||||
// Empty means the built-in wording.
|
||||
import { api } from "../../../scripts/api.js";
|
||||
import { app } from "../../../scripts/app.js";
|
||||
import { SHOW_ALL } from "./h3_sockets.mjs";
|
||||
import { LONGEST_ASK, editedAsks, readAsks, wordingWarning, writeAsks } from "./h3_writer_gear_math.mjs";
|
||||
import { showToast } from "./index.mjs";
|
||||
import { gearIconSvg, openSettingsMenu, closeSettingsMenu } from "./settings_menu.mjs";
|
||||
import { FONT_UI, THEME } from "./theme.mjs";
|
||||
|
||||
const CSS_ID = "ausboss-h3-gear-css";
|
||||
const TITLE = "H3 Prompt Writer settings";
|
||||
// The gear's width and the gap beside it, kept free at the end of the tabs.
|
||||
const CORNER_RESERVE = 30;
|
||||
|
||||
export const ASKS = [
|
||||
{ key: "describe", label: "Describe a new person", hint: "In a swap, writes how a new person looks from their picture." },
|
||||
{ key: "next", label: "Fill in the next moments", hint: "After one typed line, writes what happens next. {seconds}, {first} and {count} are filled in." },
|
||||
{ key: "heard", label: "Hear the place", hint: "Writes the steady sound of the place. {lines} is filled in." },
|
||||
{ key: "tidy", label: "Tidy up my lines", hint: "Instructions for Tidy up my lines, under More." },
|
||||
];
|
||||
|
||||
let builtIn = null;
|
||||
async function builtInAsks() {
|
||||
if (builtIn) return builtIn;
|
||||
const response = await api.fetchApi("/ausboss/h3_writer/asks");
|
||||
if (!response.ok) throw new Error("no built-in wording");
|
||||
builtIn = await response.json();
|
||||
return builtIn;
|
||||
}
|
||||
|
||||
function ensureCss() {
|
||||
if (document.getElementById(CSS_ID)) return;
|
||||
const style = document.createElement("style");
|
||||
style.id = CSS_ID;
|
||||
style.textContent = `
|
||||
.ausboss-card.has-corner .ausboss-prompt-tabs{width:calc(100% - ${CORNER_RESERVE}px)}
|
||||
.ausboss-ask-back{position:fixed;inset:0;z-index:10000;display:grid;place-items:center;background:rgba(0,0,0,.45)}
|
||||
.ausboss-ask{width:min(560px,calc(100vw - 32px));max-height:calc(100vh - 48px);display:flex;flex-direction:column;gap:8px;padding:12px;box-sizing:border-box;border:1px solid ${THEME.rule};border-radius:10px;background:#1f2326;color:${THEME.inkSoft};font:13px/1.4 ${FONT_UI};box-shadow:0 12px 36px rgba(0,0,0,.55)}
|
||||
.ausboss-ask h3{margin:0;font-size:14px;color:${THEME.ink}}
|
||||
.ausboss-ask p{margin:0;font-size:11px;color:${THEME.faint}}
|
||||
.ausboss-ask textarea{min-height:240px;flex:1 1 auto;resize:vertical;padding:8px;box-sizing:border-box;border:1px solid ${THEME.brand};border-radius:6px;outline:none;background:#0b0f10;color:${THEME.ink};font:12px/1.45 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace}
|
||||
.ausboss-ask-row{display:flex;gap:6px;align-items:center}
|
||||
.ausboss-ask-row .gap{flex:1}
|
||||
.ausboss-ask button{all:unset;flex:none;white-space:nowrap;padding:5px 11px;border-radius:6px;background:${THEME.fill};color:${THEME.inkSoft};font-weight:600;font-size:12px;cursor:pointer}
|
||||
.ausboss-ask button:hover{background:${THEME.fillHover}}
|
||||
.ausboss-ask button.save{background:${THEME.brand};color:${THEME.onBrand}}
|
||||
.ausboss-ask .state{font-size:11px;color:${THEME.faint}}
|
||||
.ausboss-ask .state.warn{color:${THEME.warn}}
|
||||
`;
|
||||
document.head.append(style);
|
||||
}
|
||||
|
||||
// The editor for one wording: the node's own, or the built-in one to start
|
||||
// from. Save keeps it on the node; Back to built-in empties it.
|
||||
function openEditor(node, card, ask, built) {
|
||||
ensureCss();
|
||||
const back = document.createElement("div");
|
||||
back.className = "ausboss-ask-back";
|
||||
const box = document.createElement("div");
|
||||
box.className = "ausboss-ask";
|
||||
const title = document.createElement("h3");
|
||||
title.textContent = ask.label;
|
||||
const hint = document.createElement("p");
|
||||
hint.textContent = `${ask.hint} Only used when a text model is plugged into clip. Saved in this node.`;
|
||||
const area = document.createElement("textarea");
|
||||
const own = readAsks(card.values().model_asks)[ask.key];
|
||||
area.maxLength = LONGEST_ASK;
|
||||
area.value = (own ?? built).slice(0, LONGEST_ASK);
|
||||
area.spellcheck = false;
|
||||
const opened = area.value;
|
||||
const state = document.createElement("span");
|
||||
state.className = "state";
|
||||
const button = (label, className, run) => {
|
||||
const element = document.createElement("button");
|
||||
element.type = "button";
|
||||
element.textContent = label;
|
||||
if (className) element.className = className;
|
||||
element.addEventListener("click", run);
|
||||
return element;
|
||||
};
|
||||
const saveButton = button("Save", "save", () => save(area.value));
|
||||
// Escape or a click outside over typing that is not saved, and Save over a
|
||||
// wording that drops a name the writer fills in, each say so once; the
|
||||
// second press goes ahead.
|
||||
let leaving = false;
|
||||
let saving = false;
|
||||
const warn = (words) => {
|
||||
state.textContent = words;
|
||||
state.classList.toggle("warn", true);
|
||||
};
|
||||
const showState = () => {
|
||||
leaving = false;
|
||||
saving = false;
|
||||
saveButton.textContent = "Save";
|
||||
state.classList.toggle("warn", false);
|
||||
const words = area.value.trim() === built.trim() || !area.value.trim() ? "Built-in wording" : "Your wording";
|
||||
state.textContent = area.value.length >= LONGEST_ASK ? `${words}, at the ${LONGEST_ASK.toLocaleString()} letter limit` : words;
|
||||
};
|
||||
showState();
|
||||
area.addEventListener("input", showState);
|
||||
const close = () => back.remove();
|
||||
const leave = () => {
|
||||
if (leaving || area.value === opened) return close();
|
||||
showState();
|
||||
leaving = true;
|
||||
warn("Not saved yet. Press Esc again to close without saving.");
|
||||
};
|
||||
const save = (words) => {
|
||||
// The built-in wording, or nothing, is stored as nothing, so a later
|
||||
// release's better wording reaches this node.
|
||||
const kept = words.trim() && words.trim() !== built.trim() ? words : "";
|
||||
const problem = kept ? wordingWarning(ask.key, kept, built) : "";
|
||||
if (problem && !saving) {
|
||||
showState();
|
||||
saving = true;
|
||||
saveButton.textContent = "Save anyway";
|
||||
warn(problem);
|
||||
return;
|
||||
}
|
||||
card.setWidget("model_asks", writeAsks(card.values().model_asks, ask.key, kept));
|
||||
card.refresh();
|
||||
close();
|
||||
};
|
||||
// The editor is a window of its own: no key reaches ComfyUI while it is
|
||||
// open (Ctrl+Enter would queue the old wording; here it saves), Tab stays
|
||||
// inside it, and Escape closes it from any of its controls.
|
||||
back.addEventListener("keydown", (event) => {
|
||||
event.stopPropagation();
|
||||
if (event.key === "Escape") {
|
||||
event.preventDefault();
|
||||
leave();
|
||||
} else if (event.key === "Enter" && (event.ctrlKey || event.metaKey)) {
|
||||
event.preventDefault();
|
||||
save(area.value);
|
||||
} else if (event.key === "Tab") {
|
||||
const stops = [...box.querySelectorAll("textarea, button")];
|
||||
const at = stops.indexOf(document.activeElement);
|
||||
const next = (at + (event.shiftKey ? -1 : 1) + stops.length) % stops.length;
|
||||
event.preventDefault();
|
||||
stops[next].focus();
|
||||
}
|
||||
});
|
||||
const row = document.createElement("div");
|
||||
row.className = "ausboss-ask-row";
|
||||
const gap = document.createElement("span");
|
||||
gap.className = "gap";
|
||||
row.append(
|
||||
button("Back to built-in", "", () => { area.value = built; showState(); }),
|
||||
state, gap,
|
||||
button("Cancel", "", close),
|
||||
saveButton,
|
||||
);
|
||||
box.append(title, hint, area, row);
|
||||
back.append(box);
|
||||
back.addEventListener("pointerdown", (event) => { if (event.target === back) leave(); });
|
||||
document.body.append(back);
|
||||
area.focus();
|
||||
}
|
||||
|
||||
// The card's corner: { element, sync } for mountWidgetCard's corner option.
|
||||
export function writerGear(node, card) {
|
||||
ensureCss();
|
||||
const gear = document.createElement("button");
|
||||
gear.type = "button";
|
||||
gear.className = "ausboss-card-gear";
|
||||
gear.title = TITLE;
|
||||
gear.innerHTML = gearIconSvg();
|
||||
const open = async () => {
|
||||
let built;
|
||||
try {
|
||||
built = await builtInAsks();
|
||||
} catch {
|
||||
built = null;
|
||||
}
|
||||
const edited = editedAsks(card.values().model_asks);
|
||||
const schema = [
|
||||
{ section: "Display (this browser)" },
|
||||
{
|
||||
key: "sockets", label: "Sockets", type: "choice", options: ["in use", "all"], default: "in use", persist: false,
|
||||
hint: "In use shows the sockets you use and the next free picture.",
|
||||
},
|
||||
{ section: "What the model on clip is asked (saved in this node)" },
|
||||
...ASKS.map((ask) => ({
|
||||
key: `ask_${ask.key}`, label: ask.label, type: "action", button: "Edit",
|
||||
hint: built ? (edited.has(ask.key) ? "Your wording." : "Built-in wording.") : "Restart ComfyUI to edit this.",
|
||||
onAction: () => {
|
||||
if (!built) return;
|
||||
closeSettingsMenu();
|
||||
openEditor(node, card, ask, built[ask.key] ?? "");
|
||||
},
|
||||
})),
|
||||
];
|
||||
openSettingsMenu({
|
||||
scope: "h3_writer",
|
||||
schema,
|
||||
anchor: gear.getBoundingClientRect(),
|
||||
title: TITLE,
|
||||
initial: { sockets: app.extensionManager?.setting?.get?.(SHOW_ALL) ? "all" : "in use" },
|
||||
onChange: (values, key) => {
|
||||
if (key === "sockets") app.extensionManager?.setting?.set?.(SHOW_ALL, values.sockets === "all");
|
||||
else if (key === null) reset();
|
||||
},
|
||||
});
|
||||
};
|
||||
// The menu's Reset: the sockets back to "in use" and every wording back
|
||||
// to built-in, as one undo step, then the menu again to show it.
|
||||
const reset = async () => {
|
||||
try {
|
||||
await app.extensionManager?.setting?.set?.(SHOW_ALL, false);
|
||||
} catch {
|
||||
// The menu shows what the setting holds.
|
||||
}
|
||||
if (editedAsks(card.values().model_asks).size) {
|
||||
card.setWidget("model_asks", "");
|
||||
card.refresh();
|
||||
showToast({ summary: "H3 Prompt Writer", detail: "The model's wordings are back to built-in. Ctrl+Z brings yours back." });
|
||||
}
|
||||
closeSettingsMenu();
|
||||
await open();
|
||||
};
|
||||
gear.addEventListener("click", open);
|
||||
// Only the tabs make room for the gear (the style above); the rows under
|
||||
// them keep the card's full width.
|
||||
return { element: gear, sync: () => 0 };
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
// H3 Prompt Writer's model_asks: the node's own wording for each thing the
|
||||
// small model is asked, as JSON in one hidden text input. Empty means the
|
||||
// built-in wording. Kept free of app imports so node:test covers it.
|
||||
|
||||
const KEYS = ["describe", "next", "heard", "tidy"];
|
||||
// The longest wording the writer reads (LONGEST_ASK in nodes/_h3_model_asks.py).
|
||||
export const LONGEST_ASK = 8000;
|
||||
|
||||
export function readAsks(value) {
|
||||
let found;
|
||||
try {
|
||||
found = value ? JSON.parse(value) : {};
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
if (!found || typeof found !== "object" || Array.isArray(found)) return {};
|
||||
const asks = {};
|
||||
for (const key of KEYS) {
|
||||
if (typeof found[key] === "string" && found[key].trim()) asks[key] = found[key];
|
||||
}
|
||||
return asks;
|
||||
}
|
||||
|
||||
// The input's new text with one wording set, or taken out when empty.
|
||||
export function writeAsks(value, key, words) {
|
||||
const asks = readAsks(value);
|
||||
if (String(words ?? "").trim()) asks[key] = String(words);
|
||||
else delete asks[key];
|
||||
return Object.keys(asks).length ? JSON.stringify(asks) : "";
|
||||
}
|
||||
|
||||
export function editedAsks(value) {
|
||||
return new Set(Object.keys(readAsks(value)));
|
||||
}
|
||||
|
||||
// The names the writer fills into each wording (fill_words in
|
||||
// nodes/_h3_script_helpers.py), and what each one tells the model.
|
||||
const FILLS = {
|
||||
next: { seconds: "how long the clip is", first: "what happens first", count: "how many lines to write" },
|
||||
heard: { lines: "what happens in the clip" },
|
||||
};
|
||||
const NAME = /\{(\w+)\}/g;
|
||||
const listed = (items) => (items.length < 2 ? items.join("") : `${items.slice(0, -1).join(", ")} and ${items.at(-1)}`);
|
||||
const namesIn = (text) => [...new Set([...String(text ?? "").matchAll(NAME)].map((match) => match[1]))];
|
||||
|
||||
// What a node's own wording would lose, or send as typed, in plain words:
|
||||
// a name the built-in wording fills in that it no longer has, and a name
|
||||
// the writer does not fill in. Empty when it has neither.
|
||||
export function wordingWarning(key, words, built) {
|
||||
const fills = FILLS[key] ?? {};
|
||||
const fillsIn = (name) => Object.hasOwn(fills, name);
|
||||
const typed = namesIn(words);
|
||||
const missing = namesIn(built).filter((name) => fillsIn(name) && !typed.includes(name));
|
||||
const unknown = typed.filter((name) => !fillsIn(name));
|
||||
const said = [];
|
||||
if (missing.length) {
|
||||
said.push(`Without ${listed(missing.map((name) => `{${name}}`))}, the model is not told ${listed(missing.map((name) => fills[name]))}.`);
|
||||
}
|
||||
if (unknown.length) {
|
||||
const many = unknown.length > 1;
|
||||
said.push(`${listed(unknown.map((name) => `{${name}}`))} ${many ? "are" : "is"} not filled in: the model reads ${many ? "them" : "it"} as typed.`);
|
||||
}
|
||||
return said.join(" ");
|
||||
}
|
||||
@@ -21,6 +21,7 @@ export const ZH = {
|
||||
"Target size, extend": "目标尺寸与外扩", "Extra context": "额外上下文", "Target width": "目标宽度", "Target height": "目标高度",
|
||||
"Rescale": "重新缩放", "Extend left": "向左外扩", "Extend right": "向右外扩", "Extend up": "向上外扩", "Extend down": "向下外扩",
|
||||
"Expand": "扩张", "Fill holes": "填补孔洞", "Max hole size": "最大孔洞", "Smooth": "平滑", "Black point": "黑场", "White point": "白场",
|
||||
"Detail range": "细节范围", "Fix threshold": "修正阈值",
|
||||
"From": "来源", "Folder": "文件夹", "Subfolders": "子文件夹", "Order": "排序", "Run": "运行", "Picture": "图片",
|
||||
"After a run": "运行之后", "At the end": "到末尾时", "Soften": "柔化", "Fine edges": "精细边缘", "Fill small holes": "填补小孔",
|
||||
"Invert": "反转", "If nothing": "没选中时", "New picture": "换新图时", "Free VRAM": "释放显存", "Canvas": "画布",
|
||||
@@ -178,7 +179,7 @@ export const ZH = {
|
||||
"What happens, one line for each moment. A blank line cuts to a new place. @1 is Picture 1. Start a line with 3s: to put it on that second.": "发生了什么,每个时刻写一行。空行表示切到新的地点。@1 是图片 1。行首写 3s: 可把它放在第 3 秒。",
|
||||
"Type what happens, one line for each thing. Picture 1 is @1. A blank line cuts to a new place.\n\nSwap: leave empty, or name who goes. Optional new look on its own line: @1 looks like a woman with blonde hair and a black hoodie.": "输入发生了什么,每件事一行。图片 1 是 @1。空行表示切到新的地点。\n\n换人:留空,或写明换掉谁。新造型可单独写一行:@1 是一位金发、穿黑色连帽衫的女士。",
|
||||
"Your lines, the pictures and the menus. The node writes the full prompt from them.": "你写的文字、图片和各个菜单。节点会据此写出完整提示词。",
|
||||
"What you can type in the words": "文字里可以怎么写", "rain on a window": "窗上的雨声", "slow piano: music makes it louder": "舒缓钢琴:加了音乐会更响",
|
||||
"What you can type in the words": "文字里可以怎么写", "rain on a window": "窗上的雨声", "slow piano: music makes it louder": "舒缓钢琴:加了音乐会更响", "(e.g. rain on a window)": "(例如:窗上的雨声)", "(e.g. slow piano)": "(例如:舒缓钢琴)",
|
||||
"upscale, face": "放大, 人脸",
|
||||
"Switching a row on switches the other rows off - for alternatives such as two upscalers.": "打开一行会关掉其他行,适合在两个放大器这类互斥方案之间切换。",
|
||||
"Rows gives each switch a row with its own off | on. One pill makes the switches choices in a single pill, where one is always picked.": "“逐行”让每个开关各占一行,各自有关 | 开。“单选”把这些开关合成一个选项条,始终选中其中一个。",
|
||||
@@ -215,6 +216,8 @@ export const ZH = {
|
||||
// ---- card tooltips and placeholders
|
||||
"Size of the finished picture. 0 keeps the picture's own size.": "成品图片的大小。0 表示保持图片原有大小。",
|
||||
"Used only while Fill holes is on.": "仅在“填补孔洞”开启时使用。",
|
||||
"Used only while Edge is on.": "仅在“边缘”开启时使用。",
|
||||
"Used only while Edge is matting.": "仅在“边缘”为抠图(matting)时使用。",
|
||||
"the folder itself": "文件夹本身",
|
||||
"Choose a folder inside ComfyUI's input or output folder.": "选择 ComfyUI 的 input 或 output 文件夹里的一个文件夹。",
|
||||
"Prompt, caption, or shared text": "提示词、字幕或共用文字",
|
||||
|
||||
+1
-1
@@ -9,7 +9,7 @@ import { app } from "../../../scripts/app.js";
|
||||
// Must match `version` in pyproject.toml — scripts/release_preflight.py
|
||||
// enforces it. The backend serves its copy at /ausboss/pack_version; a
|
||||
// mismatch means the browser cached JavaScript from an older install.
|
||||
export const AUSBOSS_JS_VERSION = "2.29.0";
|
||||
export const AUSBOSS_JS_VERSION = "2.30.0";
|
||||
|
||||
export const BRAND = "#00b4aa"; // AusBoss teal — keep node accents consistent.
|
||||
export const BRAND_DARK = "#007f78";
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
// on the first picture picks the part to keep.
|
||||
import { api } from "../../../scripts/api.js";
|
||||
import { app } from "../../../scripts/app.js";
|
||||
import { notifyAusbossChange } from "./index.mjs";
|
||||
import { CROP_MODES, changeText, cropSideAt, keptPart, placeText, planLoadSize, shapeText, sizeText, stepFile, thumbSizes } from "./load_size.mjs";
|
||||
import { mediaViewQuery } from "./media_list.mjs";
|
||||
import { FONT_UI, RADIUS_CONTROL, THEME as T } from "./theme.mjs";
|
||||
@@ -93,6 +94,7 @@ export function loadImagePreview(node) {
|
||||
const next = cropSideAt((event.clientX - box.left) / box.width, (event.clientY - box.top) / box.height);
|
||||
if (next === widget.value) return;
|
||||
commitWidgetValue(node, widget, next, app.canvas);
|
||||
notifyAusbossChange();
|
||||
node.setDirtyCanvas?.(true, true);
|
||||
});
|
||||
|
||||
@@ -163,6 +165,7 @@ export function loadImageStrip(node) {
|
||||
const next = stepFile(comboValues(image), image.value, delta);
|
||||
if (next === null || next === image.value) return;
|
||||
commitWidgetValue(node, image, next, app.canvas);
|
||||
notifyAusbossChange();
|
||||
node.setDirtyCanvas?.(true, true);
|
||||
});
|
||||
root.append(button);
|
||||
|
||||
+36
-11
@@ -2,10 +2,10 @@
|
||||
// bar as long as the clip, with the cuts as marks. The server reads the script with the same code a run uses,
|
||||
// so the bar shows what will happen. It also colours the script box, so the
|
||||
// words the node reads as instructions (@1, 3s:, a cut) stand out.
|
||||
import { clipLengthWords, clipSetsDuration, clipTimingFor, linkSource } from "./h3_duration.mjs";
|
||||
import { H3_FPS, clipLengthWords, clipSetsDuration, clipTimingFor, h3VideoFrames, linkSource } from "./h3_duration.mjs";
|
||||
import { api } from "../../../scripts/api.js";
|
||||
import { app } from "../../../scripts/app.js";
|
||||
import { BRAND, chainCallback } from "./index.mjs";
|
||||
import { BRAND, chainCallback, notifyAusbossChange } from "./index.mjs";
|
||||
import { dragRange, moveMoment, retime, rulerSeconds, stripCaption, stripRows, toggleCut, wiredJobs } from "./moment_strip_math.mjs";
|
||||
import { attachScriptAssist } from "./script_assist.mjs";
|
||||
import { attachScriptColours } from "./script_colours.mjs";
|
||||
@@ -98,6 +98,7 @@ export function momentStrip(node) {
|
||||
const next = change(String(widget.value ?? ""));
|
||||
if (next === widget.value) return;
|
||||
commitWidgetValue(node, widget, next, app.canvas);
|
||||
notifyAusbossChange();
|
||||
sync({ ...lastValues, script: widget.value });
|
||||
};
|
||||
// The left edge of a moment that opens a typed line: drag it to set when
|
||||
@@ -264,6 +265,16 @@ export function momentStrip(node) {
|
||||
let shown = null;
|
||||
let timer = null;
|
||||
let asked = 0;
|
||||
// A problem in the script while the clip sets the length: the run would
|
||||
// stop on it, so it is shown in place of the clip's note.
|
||||
let clipWarning = "";
|
||||
const showClipWarning = (warning) => {
|
||||
clipWarning = String(warning ?? "");
|
||||
if (!clipWarning) return;
|
||||
note.textContent = clipWarning;
|
||||
note.title = clipWarning;
|
||||
note.classList.toggle("warn", true);
|
||||
};
|
||||
const ask = async (script, seconds, jobs, video) => {
|
||||
const turn = ++asked;
|
||||
try {
|
||||
@@ -273,7 +284,9 @@ export function momentStrip(node) {
|
||||
body: JSON.stringify({ script, seconds, jobs, video }),
|
||||
});
|
||||
const report = response.ok ? await response.json() : null;
|
||||
if (turn === asked && !clipSetsDuration(node, lastValues)) show(report);
|
||||
if (turn !== asked) return;
|
||||
if (clipSetsDuration(node, lastValues)) showClipWarning(report?.warning);
|
||||
else show(report);
|
||||
} catch {
|
||||
if (turn === asked && !clipSetsDuration(node, lastValues)) show(null);
|
||||
}
|
||||
@@ -292,20 +305,30 @@ export function momentStrip(node) {
|
||||
}
|
||||
colours.sync(values, [1, 2, 3, 4].filter((number) => wired(node, `picture_${number}`)));
|
||||
if (fromClip) {
|
||||
shown = null;
|
||||
clearTimeout(timer);
|
||||
asked += 1;
|
||||
ruler.textContent = "";
|
||||
track.textContent = "";
|
||||
// Say what H3 will make of the clip's frames, when the clip node knows
|
||||
// its count; it rounds down to 5 + 17n, so a 48-frame clip gives 39.
|
||||
const words = clipLengthWords(clipTimingFor(node));
|
||||
const timing = clipTimingFor(node);
|
||||
const words = clipLengthWords(timing);
|
||||
const message = el("ausboss-strip-words", words?.title ?? "Length comes from the clip");
|
||||
message.style.cssText = "display:flex;align-items:center;height:100%";
|
||||
track.append(message);
|
||||
note.textContent = words?.note ?? "Set the clip's length on the clip node. H3 makes 5 + 17n frames (22, 39, 56 ...), rounding the clip down.";
|
||||
// The typed script is still read once for its problems.
|
||||
const script = wired(node, "script") ? null : String(values.script ?? "");
|
||||
const jobs = wiredJobs(values, (name) => wired(node, name));
|
||||
const key = script === null ? null : JSON.stringify(["clip", script, jobs, values.video_job]);
|
||||
if (key !== shown) {
|
||||
shown = key;
|
||||
clipWarning = "";
|
||||
clearTimeout(timer);
|
||||
asked += 1;
|
||||
const seconds = timing ? h3VideoFrames(timing.frames) / H3_FPS : lastSeconds;
|
||||
if (key !== null) timer = setTimeout(() => ask(script, seconds, jobs, values.video_job), WAIT);
|
||||
}
|
||||
note.textContent = clipWarning || (words?.note ?? "Set the clip's length on the clip node. H3 makes 5 + 17n frames (22, 39, 56 ...), rounding the clip down.");
|
||||
note.title = note.textContent;
|
||||
note.classList.toggle("warn", Boolean(words?.warn));
|
||||
note.classList.toggle("warn", Boolean(clipWarning || words?.warn));
|
||||
return;
|
||||
}
|
||||
if (wired(node, "script")) {
|
||||
@@ -320,7 +343,7 @@ export function momentStrip(node) {
|
||||
// A length wired from a number box shows that box's value.
|
||||
const source = linkSource(node, "seconds");
|
||||
const fromWire = Number(source?.widgets?.find?.((widget) => widget.name === "value")?.value);
|
||||
const seconds = Math.min(15, Math.max(5, Math.round(fromWire || Number(values.seconds) || 8)));
|
||||
const seconds = Math.min(15, Math.max(4, Math.round(fromWire || Number(values.seconds) || 8)));
|
||||
lastSeconds = seconds;
|
||||
const jobs = wiredJobs(values, (name) => wired(node, name));
|
||||
const video = wired(node, "video") ? values.video_job : "";
|
||||
@@ -330,7 +353,9 @@ export function momentStrip(node) {
|
||||
clearTimeout(timer);
|
||||
timer = setTimeout(() => ask(script, seconds, jobs, video), WAIT);
|
||||
};
|
||||
const watch = setInterval(() => latest && sync(latest), WATCH);
|
||||
// Only while the strip is on screen: a hidden row is not handed new values,
|
||||
// and syncing old ones would put old words back in the script box.
|
||||
const watch = setInterval(() => latest && element.offsetParent !== null && sync(latest), WATCH);
|
||||
chainCallback(node, "onRemoved", () => { clearInterval(watch); colours.dispose(); assist.dispose(); });
|
||||
return { element, sync };
|
||||
}
|
||||
|
||||
@@ -72,6 +72,69 @@ export function stripCaption(report) {
|
||||
return { text: `${even ? `${count}, ${each[0]} s each` : count}, one take. Click between two moments to cut there.`, warn: false };
|
||||
}
|
||||
|
||||
// What each other picture does in a swap, in plain words.
|
||||
const PICTURE_WORDS = {
|
||||
place: (slot) => `@${slot} is the place.`,
|
||||
outfit: (slot, wearer) => `@${slot} is the outfit${wearer ? ` @${wearer} wears` : ""}.`,
|
||||
thing: (slot) => `@${slot} is a thing in the shot.`,
|
||||
style: (slot) => `@${slot} sets the style.`,
|
||||
};
|
||||
|
||||
// What a swap's lines were read as, in plain words: who each new person
|
||||
// replaces and how they look, the other pictures, who says what, then any
|
||||
// words a swap leaves out.
|
||||
export function readLines(read) {
|
||||
if (!read) return [];
|
||||
if (read.problem) return [{ text: read.problem, warn: true }];
|
||||
const lines = (read.people ?? []).map((person) => {
|
||||
let text = `@${person.slot} replaces ${person.goes}${person.named ? "" : " (no one named)"}.`;
|
||||
if (person.looks) text += ` Looks like ${person.looks}.`;
|
||||
else if (read.keeps_clip_clothes) text += " Keeps the clip's clothes.";
|
||||
return { text, warn: false };
|
||||
});
|
||||
for (const picture of read.pictures ?? []) {
|
||||
const words = PICTURE_WORDS[picture.job];
|
||||
lines.push({ text: words ? words(picture.slot, picture.worn_by) : `@${picture.slot} is used as ${picture.job}.`, warn: false });
|
||||
}
|
||||
for (const line of read.says ?? []) {
|
||||
lines.push({ text: `${line.slot ? `@${line.slot}` : "Someone in the clip"} says \u201c${line.words}\u201d`, warn: false });
|
||||
}
|
||||
const words = unusedWords(read);
|
||||
if (words) lines.push({ text: `Not used: ${words}. A swap keeps the clip's camera and moves; only spoken lines in quotes change.`, warn: true });
|
||||
return lines;
|
||||
}
|
||||
|
||||
// The same reading as the Ref2VA prompt names it: the cast lines the writer
|
||||
// sends to H3, then any words it leaves out.
|
||||
export function castLines(read) {
|
||||
if (!read) return [];
|
||||
if (read.problem) return [{ text: read.problem, warn: true }];
|
||||
const lines = (read.cast ?? []).map((text) => ({ text, warn: false }));
|
||||
const words = unusedWords(read);
|
||||
if (words) lines.push({ text: `Not sent: ${words} (a swap keeps the clip's camera and moves)`, warn: true });
|
||||
return lines;
|
||||
}
|
||||
|
||||
function unusedWords(read) {
|
||||
return (read.unused ?? []).map((clause) => `\u201c${clause}\u201d`).join(", ");
|
||||
}
|
||||
|
||||
// A cast line in pieces, so the tags can be coloured: subject, video,
|
||||
// picture, removed, speech marks, and plain words.
|
||||
export function castPieces(text) {
|
||||
const pieces = [];
|
||||
const pattern = /(<Subject \d+>)|(<Video \d+>)|(<Picture \d+>)|(\u2192 removed)|(<\/?d>)/g;
|
||||
let at = 0;
|
||||
for (const match of text.matchAll(pattern)) {
|
||||
if (match.index > at) pieces.push({ kind: "", text: text.slice(at, match.index) });
|
||||
const kind = match[1] ? "subject" : match[2] ? "video" : match[3] ? "picture" : match[4] ? "removed" : "speech";
|
||||
pieces.push({ kind, text: match[0] });
|
||||
at = match.index + match[0].length;
|
||||
}
|
||||
if (at < text.length) pieces.push({ kind: "", text: text.slice(at) });
|
||||
return pieces;
|
||||
}
|
||||
|
||||
// The seconds the bar under the script marks: every second up to 10 s,
|
||||
// every other one after, always with the end.
|
||||
export function rulerSeconds(seconds) {
|
||||
|
||||
@@ -0,0 +1,207 @@
|
||||
// H3 Prompt Writer, swap job: the box under the script that shows how the
|
||||
// writer read the swap lines, as you type. Two views: Ref2VA, the cast lines
|
||||
// the writer sends to H3, and Plain, the same reading in everyday words. The
|
||||
// clip's frame count sits along the bottom, as the moment strip shows it for
|
||||
// other clip jobs.
|
||||
|
||||
import { clipLengthWords, clipSetsDuration, clipTimingFor, linkSource } from "./h3_duration.mjs";
|
||||
import { api } from "../../../scripts/api.js";
|
||||
import { chainCallback } from "./index.mjs";
|
||||
import { castLines, castPieces, readLines, wiredJobs } from "./moment_strip_math.mjs";
|
||||
import { FONT_UI, THEME } from "./theme.mjs";
|
||||
|
||||
const CSS_ID = "ausboss-swap-reading-css";
|
||||
const SWAP_JOB = "swap the person";
|
||||
const VIEW = "ausboss_read_view"; // the picked view, kept on the node
|
||||
const OPEN = "ausboss_read_open"; // unfolded, kept on the node; folded by default
|
||||
const WAIT = 200; // Lets someone finish a word before asking.
|
||||
const WATCH = 1000; // Notices the clip unplugged or switched off.
|
||||
|
||||
// Whether the box is unfolded. Folded, it is one line, so the node stays short.
|
||||
export function swapReadingOpen(node) {
|
||||
return node.properties?.[OPEN] === true;
|
||||
}
|
||||
|
||||
// The box shows for a swap whose clip is plugged in and whose words are typed.
|
||||
export function swapReadingShows(values, node) {
|
||||
return values.video_job === SWAP_JOB && clipSetsDuration(node, values) && linkSource(node, "script") === null;
|
||||
}
|
||||
|
||||
function ensureCss() {
|
||||
if (document.getElementById(CSS_ID)) return;
|
||||
const style = document.createElement("style");
|
||||
style.id = CSS_ID;
|
||||
style.textContent = `
|
||||
.ausboss-swapread{display:flex;flex-direction:column;gap:4px;height:100%;min-width:0;padding:5px 8px 4px;box-sizing:border-box;border-left:2px solid ${THEME.brand};border-radius:6px;background:rgba(0,180,170,.1);font:500 11px/1.35 ${FONT_UI};color:${THEME.inkSoft};user-select:none}
|
||||
.ausboss-swapread-head{flex:none;display:flex;align-items:center;gap:6px;height:16px}
|
||||
.ausboss-swapread-title{flex:none;cursor:pointer;color:${THEME.faint};font-size:9px;font-weight:700;letter-spacing:.08em;text-transform:uppercase}
|
||||
.ausboss-swapread-title{display:flex;align-items:center;gap:5px}
|
||||
.ausboss-swapread-title:hover{color:${THEME.inkSoft}}
|
||||
.ausboss-swapread-chevron{flex:none;width:11px;height:7px;color:${THEME.label};transition:transform .12s}
|
||||
.ausboss-swapread.folded .ausboss-swapread-chevron{transform:rotate(-90deg)}
|
||||
.ausboss-swapread-sum{flex:1 1 auto;min-width:0;overflow:hidden;white-space:nowrap;text-overflow:ellipsis;cursor:pointer}
|
||||
.ausboss-swapread-sum.warn{color:${THEME.warn}}
|
||||
.ausboss-swapread.folded{gap:2px;padding-top:4px}
|
||||
.ausboss-swapread.folded .ausboss-swapread-body,.ausboss-swapread.folded .ausboss-swapread-tabs{display:none}
|
||||
.ausboss-swapread-tabs{flex:none;display:flex;margin-left:auto;padding:1px;border-radius:5px;background:${THEME.fill}}
|
||||
.ausboss-swapread-tabs button{all:unset;padding:0 7px;height:14px;border-radius:4px;color:${THEME.label};font-size:9px;font-weight:700;line-height:14px;cursor:pointer}
|
||||
.ausboss-swapread-tabs button.on{background:${THEME.brand};color:${THEME.onBrand}}
|
||||
.ausboss-swapread-body{flex:1 1 0;min-height:0;overflow-y:auto;overflow-x:hidden;scrollbar-width:thin}
|
||||
.ausboss-swapread-body div{margin:0 0 2px;word-break:break-word}
|
||||
.ausboss-swapread-body.ref2va{font:500 10px/1.4 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace}
|
||||
.ausboss-swapread-body .warn{color:${THEME.warn}}
|
||||
.ausboss-swapread-body .subject{color:#f5b53d}
|
||||
.ausboss-swapread-body .video{color:#7fb8ff}
|
||||
.ausboss-swapread-body .picture{color:${THEME.brandInk}}
|
||||
.ausboss-swapread-body .removed{color:${THEME.danger}}
|
||||
.ausboss-swapread-body .speech{color:${THEME.faint}}
|
||||
.ausboss-swapread-body .empty{color:${THEME.faint}}
|
||||
.ausboss-swapread-foot{flex:none;overflow:hidden;white-space:nowrap;text-overflow:ellipsis;color:${THEME.faint};font-size:10px;line-height:12px}
|
||||
.ausboss-swapread-foot.warn{color:${THEME.warn}}
|
||||
`;
|
||||
document.head.append(style);
|
||||
}
|
||||
|
||||
function el(className, text) {
|
||||
const node = document.createElement("div");
|
||||
node.className = className;
|
||||
if (text !== undefined) node.textContent = text;
|
||||
return node;
|
||||
}
|
||||
|
||||
// Card rows: the folded line, and the open box with its two views.
|
||||
export const swapReading = (node) => readingBox(node, false);
|
||||
export const swapReadingFolded = (node) => readingBox(node, true);
|
||||
|
||||
function readingBox(node, folded) {
|
||||
ensureCss();
|
||||
const element = el(folded ? "ausboss-swapread folded" : "ausboss-swapread");
|
||||
const head = el("ausboss-swapread-head");
|
||||
const title = el("ausboss-swapread-title");
|
||||
// The same chevron the cast chips use: right when folded, down when open.
|
||||
const chevron = document.createElementNS("http://www.w3.org/2000/svg", "svg");
|
||||
chevron.setAttribute("viewBox", "0 0 10 6");
|
||||
chevron.setAttribute("class", "ausboss-swapread-chevron");
|
||||
chevron.innerHTML = '<path d="M1 1l4 4 4-4" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/>';
|
||||
title.append(chevron, "Read as");
|
||||
const summary = el("ausboss-swapread-sum");
|
||||
const tabs = el("ausboss-swapread-tabs");
|
||||
const body = el("ausboss-swapread-body");
|
||||
const foot = el("ausboss-swapread-foot");
|
||||
head.append(title, ...(folded ? [summary] : []), tabs);
|
||||
element.append(head, body, foot);
|
||||
// Click the caption (or, folded, the line) to open or fold the box.
|
||||
const toggle = (event) => {
|
||||
event.stopPropagation();
|
||||
node.properties = node.properties ?? {};
|
||||
node.properties[OPEN] = folded;
|
||||
node.__ausbossCard?.refresh?.();
|
||||
};
|
||||
title.title = folded ? "Show how the writer read your lines." : "Fold this away.";
|
||||
summary.title = "Click to show all of it.";
|
||||
title.addEventListener("click", toggle);
|
||||
summary.addEventListener("click", toggle);
|
||||
|
||||
const view = () => (node.properties?.[VIEW] === "plain" ? "plain" : "ref2va");
|
||||
const buttons = {};
|
||||
for (const [key, label, hint] of [
|
||||
["ref2va", "Ref2VA", "The cast lines the writer sends to H3."],
|
||||
["plain", "Plain", "The same reading in everyday words."],
|
||||
]) {
|
||||
const button = document.createElement("button");
|
||||
button.type = "button";
|
||||
button.textContent = label;
|
||||
button.title = hint;
|
||||
button.addEventListener("click", (event) => {
|
||||
event.stopPropagation();
|
||||
node.properties = node.properties ?? {};
|
||||
node.properties[VIEW] = key;
|
||||
render();
|
||||
});
|
||||
buttons[key] = button;
|
||||
tabs.append(button);
|
||||
}
|
||||
|
||||
let read = null;
|
||||
const render = () => {
|
||||
const picked = view();
|
||||
for (const [key, button] of Object.entries(buttons)) button.classList.toggle("on", key === picked);
|
||||
body.className = `ausboss-swapread-body ${picked}`;
|
||||
body.textContent = "";
|
||||
const lines = picked === "plain" ? readLines(read) : castLines(read);
|
||||
// Folded: who goes, with a count of the words not used in front of it.
|
||||
const plain = readLines(read);
|
||||
const first = read?.problem ? plain[0] : plain.find((line) => !line.warn);
|
||||
const left = read?.problem ? 0 : (read?.unused ?? []).length;
|
||||
const words = first?.text ?? (read ? "Plug in a person's picture to swap." : "Reading the lines\u2026");
|
||||
summary.textContent = left ? `${left} part${left === 1 ? "" : "s"} not used. ${words}` : words;
|
||||
summary.classList.toggle("warn", Boolean(read?.problem || left));
|
||||
if (!lines.length) {
|
||||
body.append(el("empty", read ? "Plug in a person's picture to swap." : "Reading the lines…"));
|
||||
return;
|
||||
}
|
||||
for (const line of lines) {
|
||||
const row = el(line.warn ? "warn" : "");
|
||||
if (picked === "plain" || line.warn) row.textContent = line.text;
|
||||
else {
|
||||
for (const piece of castPieces(line.text)) {
|
||||
const span = document.createElement("span");
|
||||
if (piece.kind) span.className = piece.kind;
|
||||
span.textContent = piece.text;
|
||||
row.append(span);
|
||||
}
|
||||
}
|
||||
body.append(row);
|
||||
}
|
||||
};
|
||||
|
||||
const showLength = () => {
|
||||
const words = clipLengthWords(clipTimingFor(node));
|
||||
foot.textContent = words?.title ?? "Length comes from the clip";
|
||||
foot.title = [words?.title, words?.note].filter(Boolean).join(". ");
|
||||
foot.classList.toggle("warn", Boolean(words?.warn));
|
||||
};
|
||||
|
||||
let shown = null;
|
||||
let timer = null;
|
||||
let turn = 0;
|
||||
const ask = async (script, jobs) => {
|
||||
const mine = ++turn;
|
||||
try {
|
||||
const response = await api.fetchApi("/ausboss/h3_writer/read", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ script, seconds: 8, jobs, video: SWAP_JOB }),
|
||||
});
|
||||
const report = response.ok ? await response.json() : null;
|
||||
if (mine !== turn) return;
|
||||
read = report?.read ?? null;
|
||||
render();
|
||||
} catch {
|
||||
// The reading is a help; without it the box keeps its last reading.
|
||||
}
|
||||
};
|
||||
|
||||
let latest = null;
|
||||
let showing = null;
|
||||
const sync = (values) => {
|
||||
latest = values;
|
||||
const shows = swapReadingShows(values, node);
|
||||
if (showing !== null && shows !== showing) queueMicrotask(() => node.__ausbossCard?.refresh?.());
|
||||
showing = shows;
|
||||
if (!shows) return;
|
||||
showLength();
|
||||
const script = String(values.script ?? "");
|
||||
const jobs = wiredJobs(values, (name) => linkSource(node, name) !== null);
|
||||
const key = JSON.stringify([script, jobs]);
|
||||
if (key === shown) return;
|
||||
shown = key;
|
||||
clearTimeout(timer);
|
||||
timer = setTimeout(() => ask(script, jobs), WAIT);
|
||||
};
|
||||
render();
|
||||
// Only while on screen: a hidden row is not handed new values.
|
||||
const watch = setInterval(() => latest && element.offsetParent !== null && sync(latest), WATCH);
|
||||
chainCallback(node, "onRemoved", () => clearInterval(watch));
|
||||
return { element, sync };
|
||||
}
|
||||
@@ -1190,11 +1190,24 @@ export function fineChoice(value) {
|
||||
}
|
||||
|
||||
// The words for a Fine edges choice on the node's card: off, and on while
|
||||
// there is one model file. With more files, each goes by its own name.
|
||||
// there is one model file. With more files, each goes by its own name, and
|
||||
// the two known models by theirs (BiRefNet, RMBG-3.0). RMBG-3.0 always goes
|
||||
// by its name: it is never the model Subject uses while Fine edges is off,
|
||||
// and the help page says to pick it by name. Two copies of it (int8, bf16)
|
||||
// also show which is which.
|
||||
const fileName = (value) => String(value).split(/[\\/]/).pop().replace(/\.safetensors$/i, "");
|
||||
const isRmbg3 = (value) => /^rmbg3/i.test(fileName(value));
|
||||
export function fineEdgeLabel(value, values = []) {
|
||||
if (fineChoice(value) === "") return "off";
|
||||
const name = fileName(value);
|
||||
if (isRmbg3(value)) {
|
||||
if (values.filter(isRmbg3).length <= 1) return "RMBG-3.0";
|
||||
const variant = name.replace(/^rmbg3[-_]?/i, "").split(/[-_]/)[0];
|
||||
return variant ? `RMBG-3.0 ${variant}` : "RMBG-3.0";
|
||||
}
|
||||
if (values.filter((other) => fineChoice(other) !== "").length <= 1) return "on";
|
||||
return String(value).split(/[\\/]/).pop().replace(/\.safetensors$/i, "");
|
||||
if (/^birefnet$/i.test(name)) return "BiRefNet";
|
||||
return name;
|
||||
}
|
||||
|
||||
// The settings a fine edge was made with, as one line. The node writes the
|
||||
|
||||
@@ -712,6 +712,9 @@ function requestRun(face, ask) {
|
||||
return false;
|
||||
}
|
||||
const run = { ask, stamp: face.stamp, epoch: face.sourceEpoch, queued: false };
|
||||
// The Subject and Background picks come back from the model Fine edges
|
||||
// names at the time (BiRefNet while it is off).
|
||||
face.askedFine = settings(face).fine;
|
||||
// Runs of this node that are at a picture it no longer has. The one that
|
||||
// is running ends by itself once the next job waits; the ones that still
|
||||
// wait in the queue would each run for nothing, one after the other, so
|
||||
@@ -832,6 +835,17 @@ function wantFine(face) {
|
||||
}, FINE_WAIT_MS);
|
||||
}
|
||||
|
||||
// Subject and Background are worked out by the model Fine edges names, and
|
||||
// by BiRefNet while it is off. Turned off after RMBG-3.0, the picks on show
|
||||
// are RMBG-3.0's while the next run makes BiRefNet's, so they are asked for
|
||||
// again. (Turned to a model, the fine edge asks anyway.)
|
||||
function wantSubjectAgain(face) {
|
||||
const now = settings(face).fine;
|
||||
if (!face.alive || !face.pic || face.pic.provisional || now || face.askedFine === undefined || face.askedFine === now) return;
|
||||
if (!face.items.some((item) => item.t === "subject" || item.t === "background")) return;
|
||||
requestRun(face, "look");
|
||||
}
|
||||
|
||||
function draw(face) {
|
||||
if (face.frameRequest || !face.alive) return;
|
||||
face.frameRequest = requestAnimationFrame(() => {
|
||||
@@ -3193,6 +3207,7 @@ export function mountTouchStage(node, host) {
|
||||
paintSwatch(face);
|
||||
draw(face);
|
||||
wantFine(face);
|
||||
wantSubjectAgain(face);
|
||||
};
|
||||
// The widget's text was changed from outside (a loaded workflow, an undo).
|
||||
face.resync = () => {
|
||||
|
||||
@@ -125,7 +125,7 @@ export function ensureCardCss() {
|
||||
.ausboss-card-select:focus-visible{outline:2px solid ${T.brand};outline-offset:1px}
|
||||
.ausboss-card-text{width:100%;height:${ROW_HEIGHT}px;padding:0 8px;box-sizing:border-box;border:1px solid transparent;border-radius:${RADIUS_CONTROL}px;background:${T.fill};color:${T.ink};font:12px ${FONT};min-width:0}
|
||||
.ausboss-card-text:focus{outline:none;border-color:${T.brand}}
|
||||
.ausboss-card-text::placeholder{color:${T.faint}}
|
||||
.ausboss-card-text::placeholder{color:${T.faint};font-style:italic}
|
||||
.ausboss-card-area{display:block;width:100%;height:100%;padding:5px 8px;box-sizing:border-box;border:1px solid transparent;border-radius:${RADIUS_CONTROL}px;background:${T.fill};color:${T.ink};font:12px/1.4 ${FONT};resize:none;overflow:auto;min-width:0}
|
||||
.ausboss-card-area:focus{outline:none;border-color:${T.brand}}
|
||||
.ausboss-card-area::placeholder{color:${T.faint}}
|
||||
@@ -348,10 +348,19 @@ export function mountWidgetCard(node, { rows, minWidth = 300, first = false, hid
|
||||
button.addEventListener("click", () => setWidget(name, value));
|
||||
seg.append(button); buttons.set(value, button);
|
||||
};
|
||||
const values = comboValues(widget);
|
||||
for (const value of values) add(value, values);
|
||||
// Built again when the choices change: R (refresh model lists) can bring
|
||||
// a new model file after the card was drawn.
|
||||
let built = [];
|
||||
const build = () => {
|
||||
seg.textContent = ""; buttons.clear();
|
||||
built = comboValues(widget);
|
||||
for (const value of built) add(value, built);
|
||||
};
|
||||
build();
|
||||
into.append(seg);
|
||||
return (vals) => {
|
||||
const values = comboValues(widget);
|
||||
if (values.length !== built.length || values.some((value, index) => value !== built[index])) build();
|
||||
// A value the list does not offer (a model file this machine does not
|
||||
// have) still shows as what is chosen, as it does in a list.
|
||||
const current = vals[name];
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
// draws the same curve as nodes/_curve_helpers.py.
|
||||
|
||||
import { app } from "../../../scripts/app.js";
|
||||
import { chainCallback, keepDomWidgetWidthAuto } from "../shared/index.mjs";
|
||||
import { chainCallback, keepDomWidgetWidthAuto, notifyAusbossChange } from "../shared/index.mjs";
|
||||
import { compactAction, CAPTION_TYPE, HINT_TYPE } from "../shared/panel_controls.mjs";
|
||||
import { WIDGET_FRAME, fillNodeHeight } from "../shared/panel_layout.mjs";
|
||||
import { makeScrubInput } from "../shared/scrub_input.mjs";
|
||||
@@ -251,14 +251,17 @@ function build(node) {
|
||||
render();
|
||||
}
|
||||
let settledText = null;
|
||||
// Kept: through the widget's own callback, so the workflow is marked
|
||||
// changed and an undo takes the whole drag back.
|
||||
// Kept through the widget's own callback, then recorded as one undo
|
||||
// step, so Ctrl+Z takes the whole drag back.
|
||||
function save() {
|
||||
const widget = pointsWidget();
|
||||
const text = pointsText(face.points);
|
||||
if (widget) {
|
||||
widget.value = settledText ?? widget.value;
|
||||
if (widget.value !== text) commitWidgetValue(node, widget, text, app.canvas);
|
||||
if (widget.value !== text) {
|
||||
commitWidgetValue(node, widget, text, app.canvas);
|
||||
notifyAusbossChange();
|
||||
}
|
||||
}
|
||||
settledText = text;
|
||||
node.setDirtyCanvas?.(true, true);
|
||||
|
||||
+31
-10
@@ -10,11 +10,13 @@ import { app } from "../../../scripts/app.js";
|
||||
import { chainCallback, notifyAusbossChange } from "../shared/index.mjs";
|
||||
import { formatWidgetVisibility } from "../shared/save_video_formats.mjs";
|
||||
import { hideInputsInDef } from "../shared/widget_visibility.mjs";
|
||||
import { castChips } from "../shared/h3_cast_chips.mjs";
|
||||
import { castChipNames, castChips } from "../shared/h3_cast_chips.mjs";
|
||||
import { FULL, fullPromptBox, isEdited, promptTab, promptTabs, simpleEditedNote } from "../shared/h3_full_prompt.mjs";
|
||||
import { cameraChoiceLabel, clipSetsDuration } from "../shared/h3_duration.mjs";
|
||||
import { loadImagePreview, loadImageStrip } from "../shared/load_image_strip.mjs";
|
||||
import { momentStrip } from "../shared/moment_strip.mjs";
|
||||
import { writerGear } from "../shared/h3_writer_gear.mjs";
|
||||
import { swapReading, swapReadingFolded, swapReadingOpen, swapReadingShows } from "../shared/swap_reading.mjs";
|
||||
import { mountWidgetCard } from "../shared/widget_card.mjs";
|
||||
import { copiesGrain, grainFromLinked } from "../shared/grain_auto.mjs";
|
||||
import { FONT_UI, THEME } from "../shared/theme.mjs";
|
||||
@@ -275,8 +277,9 @@ const CARDS = {
|
||||
// A workflow saved by a 1.x release holds the preview panel's own empty
|
||||
// value where preview now sits; it loads on, the node's default. One
|
||||
// saved by 2.x before Max hole size existed holds the card's there; it
|
||||
// loads 0, no limit, as the node ran then.
|
||||
resetUnknown: { preview: true, max_hole_size: 0 },
|
||||
// loads 0, no limit, as the node ran then. detail_range and fix_threshold
|
||||
// came later still; older saves hold the card's value there.
|
||||
resetUnknown: { preview: true, max_hole_size: 0, detail_range: 12, fix_threshold: 0.01 },
|
||||
rows: [
|
||||
{ widget: "expand", label: "Expand", suffix: "px" },
|
||||
{ widget: "blur", label: "Blur" },
|
||||
@@ -288,6 +291,10 @@ const CARDS = {
|
||||
{ widget: "black_point", label: "Black point", group: "advanced" },
|
||||
{ widget: "white_point", label: "White point", group: "advanced" },
|
||||
{ widget: "edge_refine", label: "Edge", kind: "segment", labels: { "guided filter": "guided" }, group: "advanced" },
|
||||
{ widget: "detail_range", label: "Detail range", group: "advanced",
|
||||
mute: (values) => values.edge_refine === "off", muteTitle: "Used only while Edge is on." },
|
||||
{ widget: "fix_threshold", label: "Fix threshold", group: "advanced",
|
||||
mute: (values) => values.edge_refine !== "matting", muteTitle: "Used only while Edge is matting." },
|
||||
],
|
||||
},
|
||||
// The settings of Image Folder. Its gallery (js/image_folder) sits under
|
||||
@@ -445,9 +452,11 @@ const CARDS = {
|
||||
// sockets, and each picture's job sits under the words.
|
||||
AUSBOSS_NODES_H3PromptWriter: {
|
||||
minWidth: 420,
|
||||
hide: ["job_1", "job_2", "job_3", "job_4", "video_job", "full_prompt"],
|
||||
socketless: ["job_1", "job_2", "job_3", "job_4", "video_job", "full_prompt"],
|
||||
resetUnknown: { sound: "", music: "", clip_sound: false, full_prompt: "", tidy: false },
|
||||
hide: ["job_1", "job_2", "job_3", "job_4", "video_job", "full_prompt", "model_asks"],
|
||||
socketless: ["job_1", "job_2", "job_3", "job_4", "video_job", "full_prompt", "model_asks"],
|
||||
resetUnknown: { sound: "", music: "", clip_sound: false, full_prompt: "", tidy: false, model_asks: "" },
|
||||
// The gear: which sockets show, and what the model on clip is asked.
|
||||
corner: writerGear,
|
||||
rows: [
|
||||
// Simple is the card as it always was; Full prompt shows the prompt the
|
||||
// node wrote and sends an edit made there instead (js/shared/h3_full_prompt.mjs).
|
||||
@@ -461,11 +470,15 @@ const CARDS = {
|
||||
widget: "script", kind: "textarea", height: 118, grow: true,
|
||||
placeholder: "Type what happens, one line for each thing. Picture 1 is @1. A blank line cuts to a new place.\n\nSwap: leave empty, or name who goes. Optional new look on its own line: @1 looks like a woman with blonde hair and a black hoodie.",
|
||||
},
|
||||
{ panel: momentStrip, height: 76, when: (values, node) => promptTab(node) !== FULL },
|
||||
{ widget: "sound", label: "Sound", placeholder: "rain on a window", when: (values, node) => promptTab(node) !== FULL },
|
||||
{ widget: "music", label: "Music", placeholder: "slow piano: music makes it louder", when: (values, node) => promptTab(node) !== FULL },
|
||||
{ panel: momentStrip, height: 76, when: (values, node) => promptTab(node) !== FULL && !swapReadingShows(values, node) },
|
||||
// A swap shows how its lines were read instead: the cast H3 gets, or plain words.
|
||||
{ panel: swapReadingFolded, height: 44, when: (values, node) => promptTab(node) !== FULL && swapReadingShows(values, node) && !swapReadingOpen(node) },
|
||||
{ panel: swapReading, height: 150, when: (values, node) => promptTab(node) !== FULL && swapReadingShows(values, node) && swapReadingOpen(node) },
|
||||
{ widget: "sound", label: "Sound", placeholder: "(e.g. rain on a window)", when: (values, node) => promptTab(node) !== FULL },
|
||||
{ widget: "music", label: "Music", placeholder: "(e.g. slow piano)", when: (values, node) => promptTab(node) !== FULL },
|
||||
{ section: "Pictures and settings" },
|
||||
{ panel: castChips, height: 30 },
|
||||
// The row is there once a picture or a video is plugged in.
|
||||
{ panel: castChips, height: 30, when: (values, node) => castChipNames(node).length > 0 },
|
||||
{ widget: "seconds", label: "Length", suffix: "s", readOnlyText: (node, values) => clipSetsDuration(node, values) ? "From the clip" : "", readOnlyTitle: "This video job uses the incoming clip, so Length is not used." },
|
||||
{ widget: "camera", label: "Camera", kind: "select", labels: cameraChoiceLabel },
|
||||
{ widget: "look", label: "Look", kind: "select" },
|
||||
@@ -673,6 +686,14 @@ app.registerExtension({
|
||||
},
|
||||
};
|
||||
},
|
||||
// R (refresh model lists) gives a choice new options after the cards
|
||||
// were drawn: each card draws again, so a new model file gets its button.
|
||||
async refreshComboInNodes() {
|
||||
const root = app.rootGraph ?? app.graph;
|
||||
for (const graph of [root, ...(root?.subgraphs?.values?.() ?? [])]) {
|
||||
for (const node of graph?._nodes ?? []) node.__ausbossCard?.refresh?.();
|
||||
}
|
||||
},
|
||||
beforeRegisterNodeDef(nodeType, nodeData) {
|
||||
const config = CARDS[nodeData?.name];
|
||||
if (!config) return;
|
||||
|
||||
@@ -1272,6 +1272,12 @@
|
||||
},
|
||||
"max_hole_size": {
|
||||
"name": "最大空洞尺寸"
|
||||
},
|
||||
"detail_range": {
|
||||
"name": "细节范围"
|
||||
},
|
||||
"fix_threshold": {
|
||||
"name": "修正阈值"
|
||||
}
|
||||
},
|
||||
"outputs": {
|
||||
|
||||
+213
-14
@@ -68,6 +68,42 @@ NOT_A_MODEL = (
|
||||
"Use birefnet.safetensors from the Hugging Face page Comfy-Org/BiRefNet."
|
||||
)
|
||||
|
||||
# RMBG-3.0 (Bria): a picture model that paints the subject's matte in four
|
||||
# steps. Its files sit in ComfyUI's usual model folders, so it is found by
|
||||
# name: the model in diffusion_models, its text reader and its VAE beside it.
|
||||
RMBG3_FOLDER = "diffusion_models"
|
||||
RMBG3_PREFIX = "rmbg3"
|
||||
# Text readers and VAEs it works with, best first: the files Bria's ComfyUI
|
||||
# page lists, then any Qwen3-VL 4B or FLUX.2 VAE file.
|
||||
RMBG3_TEXT = ("qwen3vl_4b_int8_convrot.safetensors", "qwen3vl_4b_bf16.safetensors")
|
||||
RMBG3_VAE = ("flux2-vae.safetensors",)
|
||||
# The instruction it was trained with, as Comfy's RMBG-3.0 template sends it.
|
||||
RMBG3_ASK = (
|
||||
'{"edit_instruction": "Generate a detailed grayscale alpha matte. Map the opaque foreground '
|
||||
"to white and the background to black. Produce soft, anti-aliased grayscale gradients at the "
|
||||
'edges of the subject to represent fine details and transparency."}'
|
||||
)
|
||||
# Its sampling: four steps, no guidance, one fixed seed, as the template.
|
||||
RMBG3_STEPS = 4
|
||||
RMBG3_SEED = 42
|
||||
# It paints about one megapixel, in steps of 16 pixels.
|
||||
RMBG3_AREA = 1024 * 1024
|
||||
NEEDS_RMBG3_PARTS = (
|
||||
"Fine edges with RMBG-3.0 also needs its text reader and VAE: {missing}. "
|
||||
"Get them from the Hugging Face page briaai/RMBG-3.0-Comfy "
|
||||
"(text_encoders/qwen3vl_4b_int8_convrot.safetensors into ComfyUI/models/text_encoders, "
|
||||
"vae/flux2-vae.safetensors into ComfyUI/models/vae), press R, and try again."
|
||||
)
|
||||
RMBG3_NOT_FOUND = (
|
||||
"Fine edges: the RMBG-3.0 file '{name}' is not in ComfyUI/models/diffusion_models. "
|
||||
"Get rmbg3_int8_convrot.safetensors from the Hugging Face page briaai/RMBG-3.0-Comfy, "
|
||||
"put it there and press R, or pick another file under Fine edges."
|
||||
)
|
||||
NEEDS_FIBO2 = (
|
||||
"Fine edges with RMBG-3.0 needs ComfyUI 0.43 or newer (it runs on ComfyUI's "
|
||||
"FIBO 2.0 nodes). Update ComfyUI, or pick BiRefNet under Fine edges."
|
||||
)
|
||||
|
||||
# The band and its tests are worked out on a copy this long at most. They
|
||||
# are about areas, not about single pixels, so a big picture loses nothing.
|
||||
WORK_SIDE = 1024
|
||||
@@ -125,6 +161,15 @@ CLEAN_FOR = 1440
|
||||
|
||||
_MODELS = OrderedDict()
|
||||
_SUBJECTS = OrderedDict()
|
||||
# Raised to the batch at hand: a run asks about each picture twice (the
|
||||
# picks, then the fine edge), and RMBG-3.0 takes seconds a picture.
|
||||
_subjects_kept = SUBJECTS_KEPT
|
||||
|
||||
|
||||
def keep_subjects_for(pictures: int) -> None:
|
||||
"""Remember the subject of at least this many pictures (one batch)."""
|
||||
global _subjects_kept
|
||||
_subjects_kept = max(SUBJECTS_KEPT, int(pictures))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -140,9 +185,31 @@ def list_subject_models() -> list[str]:
|
||||
return list(folder_paths.get_filename_list(MODEL_FOLDER))
|
||||
|
||||
|
||||
def _folder_files(folder: str) -> list[str]:
|
||||
if folder_paths is None or folder not in getattr(folder_paths, "folder_names_and_paths", {}):
|
||||
return []
|
||||
return list(folder_paths.get_filename_list(folder))
|
||||
|
||||
|
||||
def _base(name: str) -> str:
|
||||
return str(name).replace("\\", "/").rsplit("/", 1)[-1].lower()
|
||||
|
||||
|
||||
def list_rmbg3_models() -> list[str]:
|
||||
"""RMBG-3.0 model files in diffusion_models (their names start with rmbg3)."""
|
||||
return [name for name in _folder_files(RMBG3_FOLDER) if _base(name).startswith(RMBG3_PREFIX)]
|
||||
|
||||
|
||||
def is_rmbg3(name) -> bool:
|
||||
"""An RMBG-3.0 choice, by its file name, whether or not this ComfyUI has
|
||||
it. A background-removal file stays one, whatever it is called."""
|
||||
return _base(name).startswith(RMBG3_PREFIX) and str(name).strip() not in list_subject_models()
|
||||
|
||||
|
||||
def fine_edge_choices() -> list[str]:
|
||||
"""What the Fine edges input offers: off, then every model file."""
|
||||
return [OFF, *list_subject_models()]
|
||||
"""What the Fine edges input offers: off, then every model file, then
|
||||
every RMBG-3.0 model."""
|
||||
return [OFF, *list_subject_models(), *list_rmbg3_models()]
|
||||
|
||||
|
||||
def wants_fine_edges(choice) -> bool:
|
||||
@@ -163,11 +230,12 @@ def subject_model_name(choice) -> str:
|
||||
raise FileNotFoundError(NEEDS_MODEL)
|
||||
|
||||
|
||||
def _core_node(key: str):
|
||||
"""One of ComfyUI's own node classes. None outside ComfyUI, or before 0.21."""
|
||||
def _core_node(key: str, method: str = "execute"):
|
||||
"""One of ComfyUI's own node classes, when it has `method`. None outside
|
||||
ComfyUI, or on a ComfyUI without that node."""
|
||||
mappings = getattr(sys.modules.get("nodes"), "NODE_CLASS_MAPPINGS", None)
|
||||
node = mappings.get(key) if isinstance(mappings, dict) else None
|
||||
return node if hasattr(node, "execute") else None
|
||||
return node if hasattr(node, method) else None
|
||||
|
||||
|
||||
def _load(name: str):
|
||||
@@ -194,9 +262,136 @@ def _load(name: str):
|
||||
return model
|
||||
|
||||
|
||||
def _pick_file(folder: str, preferred: tuple, fits) -> str | None:
|
||||
files = _folder_files(folder)
|
||||
for wanted in preferred:
|
||||
for name in files:
|
||||
if _base(name) == wanted:
|
||||
return name
|
||||
return next((name for name in files if fits(_base(name))), None)
|
||||
|
||||
|
||||
def _rmbg3_parts(name: str):
|
||||
"""RMBG-3.0's model, text reader and VAE, through ComfyUI's own loader
|
||||
nodes, as its template loads them. Kept while the files do not change."""
|
||||
unet_loader = _core_node("UNETLoader", "load_unet")
|
||||
clip_loader = _core_node("CLIPLoader", "load_clip")
|
||||
vae_loader = _core_node("VAELoader", "load_vae")
|
||||
if None in (unet_loader, clip_loader, vae_loader, _core_node("TextEncodeFibo2"),
|
||||
_core_node("KSampler", "sample"), _core_node("VAEDecode", "decode")):
|
||||
raise RuntimeError(NEEDS_FIBO2)
|
||||
if folder_paths is None or not folder_paths.get_full_path(RMBG3_FOLDER, name):
|
||||
raise FileNotFoundError(RMBG3_NOT_FOUND.format(name=name))
|
||||
text = _pick_file("text_encoders", RMBG3_TEXT, lambda base: "qwen3vl_4b" in base or "qwen3-vl-4b" in base)
|
||||
# A decoder-only or encoder-only copy of the VAE cannot do the job.
|
||||
vae = _pick_file("vae", RMBG3_VAE, lambda base: "flux2" in base and "vae" in base and "decoder" not in base and "encoder" not in base)
|
||||
# A file that is listed but cannot be opened (a broken link) counts as missing.
|
||||
if text and not folder_paths.get_full_path("text_encoders", text):
|
||||
text = None
|
||||
if vae and not folder_paths.get_full_path("vae", vae):
|
||||
vae = None
|
||||
missing = [what for what, found in (("qwen3vl_4b_int8_convrot.safetensors", text), ("flux2-vae.safetensors", vae)) if not found]
|
||||
if missing:
|
||||
raise FileNotFoundError(NEEDS_RMBG3_PARTS.format(missing=" and ".join(missing)))
|
||||
paths = [folder_paths.get_full_path(folder, file) for folder, file in ((RMBG3_FOLDER, name), ("text_encoders", text), ("vae", vae))]
|
||||
stamp = tuple((path, os.path.getmtime(path), os.path.getsize(path)) for path in paths)
|
||||
kept = _MODELS.get(name)
|
||||
if kept is not None and kept[0] == stamp:
|
||||
_MODELS.move_to_end(name)
|
||||
return kept[1]
|
||||
# One RMBG-3.0 at a time: another copy (int8 after bf16) goes first.
|
||||
_drop_rmbg3()
|
||||
parts = (
|
||||
unet_loader().load_unet(unet_name=name, weight_dtype="default")[0],
|
||||
clip_loader().load_clip(clip_name=text, type="fibo2", device="default")[0],
|
||||
vae_loader().load_vae(vae_name=vae)[0],
|
||||
)
|
||||
_MODELS[name] = (stamp, parts)
|
||||
while len(_MODELS) > MODELS_KEPT:
|
||||
_MODELS.popitem(last=False)
|
||||
return parts
|
||||
|
||||
|
||||
def rmbg3_size(width: int, height: int) -> tuple[int, int]:
|
||||
"""The size RMBG-3.0 paints a picture at: its shape, about one megapixel,
|
||||
each side a multiple of 16. The picture is stretched to it, never cut, so
|
||||
the matte lines up with every pixel once it is scaled back."""
|
||||
scale = (RMBG3_AREA / max(1, width * height)) ** 0.5
|
||||
return max(16, round(width * scale / 16) * 16), max(16, round(height * scale / 16) * 16)
|
||||
|
||||
|
||||
def _rmbg3_matte(frame: torch.Tensor, name: str) -> torch.Tensor:
|
||||
"""RMBG-3.0's matte for one picture (H x W, 0..1), made the way its
|
||||
template makes it: the fixed instruction, four steps, no guidance."""
|
||||
model, clip, vae = _rmbg3_parts(name)
|
||||
height, width = int(frame.shape[1]), int(frame.shape[2])
|
||||
paint_w, paint_h = rmbg3_size(width, height)
|
||||
picture = frame[..., :3].float().movedim(-1, 1)
|
||||
picture = F.interpolate(picture, size=(paint_h, paint_w), mode="bicubic", align_corners=False, antialias=True)
|
||||
picture = picture.clamp(0.0, 1.0).movedim(1, -1)
|
||||
raise_if_interrupted()
|
||||
positive, negative, latent = _core_node("TextEncodeFibo2").execute(
|
||||
clip=clip, prompt=RMBG3_ASK, negative_prompt="", vae=vae, images={"image_1": picture},
|
||||
width=paint_w, height=paint_h, batch_size=1,
|
||||
).result
|
||||
painted = _core_node("KSampler", "sample")().sample(
|
||||
model=model, seed=RMBG3_SEED, steps=RMBG3_STEPS, cfg=1.0, sampler_name="euler", scheduler="simple",
|
||||
positive=positive, negative=negative, latent_image=latent, denoise=1.0,
|
||||
)[0]
|
||||
raise_if_interrupted()
|
||||
decoded = _core_node("VAEDecode", "decode")().decode(vae=vae, samples=painted)[0]
|
||||
if not isinstance(decoded, torch.Tensor) or decoded.ndim != 4:
|
||||
raise ValueError("RMBG-3.0's answer is not a picture")
|
||||
matte = decoded[:1, :, :, 0].detach().float().cpu() # its red channel, as the template reads it
|
||||
matte = F.interpolate(matte[:, None], size=(height, width), mode="bilinear", align_corners=False)[0, 0]
|
||||
return matte.clamp(0.0, 1.0)
|
||||
|
||||
|
||||
def _drop_rmbg3() -> None:
|
||||
"""Take RMBG-3.0 out of memory before BiRefNet runs. ComfyUI's own
|
||||
background-removal node makes room for its model but not for the work it
|
||||
does, and RMBG-3.0 holds about 20 GB: left in, BiRefNet runs out of
|
||||
graphics memory on all but the biggest cards. Best effort, with
|
||||
ComfyUI's own unload of one model, as Free VRAM does it."""
|
||||
held = [name for name, (_, model) in _MODELS.items() if isinstance(model, tuple)]
|
||||
if not held:
|
||||
return
|
||||
management = sys.modules.get("comfy.model_management")
|
||||
unload = getattr(management, "unload_model_and_clones", None)
|
||||
for name in held:
|
||||
unet, clip, vae = _MODELS.pop(name)[1]
|
||||
for patcher in (unet, getattr(clip, "patcher", None), getattr(vae, "patcher", None)):
|
||||
if unload is None or patcher is None:
|
||||
continue
|
||||
try:
|
||||
unload(patcher)
|
||||
except Exception: # noqa: BLE001 - making room never fails a run
|
||||
pass
|
||||
empty = getattr(management, "soft_empty_cache", None)
|
||||
if empty is not None:
|
||||
try:
|
||||
empty()
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
|
||||
|
||||
class _Unloadable:
|
||||
"""Gives Free VRAM a `patcher` for a model that is its own patcher."""
|
||||
|
||||
def __init__(self, patcher):
|
||||
self.patcher = patcher
|
||||
|
||||
|
||||
def loaded_subject_models() -> list:
|
||||
"""The models this module holds, for Free VRAM."""
|
||||
return [model for _, model in _MODELS.values()]
|
||||
held = []
|
||||
for _, model in _MODELS.values():
|
||||
if isinstance(model, tuple): # RMBG-3.0: its model, text reader and VAE
|
||||
unet, clip, vae = model
|
||||
held.extend((_Unloadable(unet), clip, vae))
|
||||
else:
|
||||
held.append(model)
|
||||
return held
|
||||
|
||||
|
||||
def subject_matte(frame: torch.Tensor, choice, key: str | None = None) -> torch.Tensor:
|
||||
@@ -210,16 +405,20 @@ def subject_matte(frame: torch.Tensor, choice, key: str | None = None) -> torch.
|
||||
if key is not None and slot in _SUBJECTS:
|
||||
_SUBJECTS.move_to_end(slot)
|
||||
return _SUBJECTS[slot].float() / 255.0
|
||||
model = _load(name)
|
||||
raise_if_interrupted()
|
||||
answer = _core_node("RemoveBackground").execute(bg_removal_model=model, image=frame[..., :3]).result[0]
|
||||
height, width = int(frame.shape[1]), int(frame.shape[2])
|
||||
if not isinstance(answer, torch.Tensor) or answer.ndim != 3 or tuple(answer.shape[1:]) != (height, width):
|
||||
raise ValueError("the background-removal model's answer is not one mask the size of the picture")
|
||||
matte = answer[0].detach().float().clamp(0.0, 1.0).cpu()
|
||||
if is_rmbg3(name):
|
||||
matte = _rmbg3_matte(frame, name)
|
||||
else:
|
||||
_drop_rmbg3()
|
||||
model = _load(name)
|
||||
raise_if_interrupted()
|
||||
answer = _core_node("RemoveBackground").execute(bg_removal_model=model, image=frame[..., :3]).result[0]
|
||||
height, width = int(frame.shape[1]), int(frame.shape[2])
|
||||
if not isinstance(answer, torch.Tensor) or answer.ndim != 3 or tuple(answer.shape[1:]) != (height, width):
|
||||
raise ValueError("the background-removal model's answer is not one mask the size of the picture")
|
||||
matte = answer[0].detach().float().clamp(0.0, 1.0).cpu()
|
||||
if key is not None:
|
||||
_SUBJECTS[slot] = (matte * 255.0).round().to(torch.uint8)
|
||||
while len(_SUBJECTS) > SUBJECTS_KEPT:
|
||||
while len(_SUBJECTS) > _subjects_kept:
|
||||
_SUBJECTS.popitem(last=False)
|
||||
return matte
|
||||
|
||||
|
||||
+47
-115
@@ -10,6 +10,8 @@ from __future__ import annotations
|
||||
from dataclasses import dataclass
|
||||
import re
|
||||
|
||||
from ._h3_swap_reader import KEEP_CLOTHES_WORDS, read_swap
|
||||
|
||||
PERSON = "person"
|
||||
SHEET = "character sheet"
|
||||
PLACE = "place"
|
||||
@@ -34,6 +36,7 @@ KEEPS_ITS_LENGTH = (MOVES, SWAP, REVOICE, EDIT) # These follow a clip, so the n
|
||||
NEEDS_NO_WORDS = (SWAP, KEEP)
|
||||
|
||||
TOKEN = re.compile(r"@(\d)\b")
|
||||
ANY_NUMBER = re.compile(r"@(\d+)\b") # @10 too, which is no picture.
|
||||
# "@2 says", "@2 whispers": the person named right before what they say.
|
||||
SAYS_AFTER = re.compile(r"@(\d)\s+(?:says?|said|asks?|whispers?|shouts?|yells?|screams?|mutters?|sings?|raps?|chants?|announces?|calls?\s+out|cries|replies|answers?)\b", re.I)
|
||||
MAIN = "@0" # The main person, for lines the node writes itself.
|
||||
@@ -59,6 +62,11 @@ REVOICE_KEEPS_PERSON = (
|
||||
'Take the picture off, or pick the video job "swap the person".'
|
||||
)
|
||||
HE_SHE = re.compile(r"\b(?:he|she|they)\b", re.I)
|
||||
# Words that say a style picture is being used as a look, as in "drawn like @3".
|
||||
AS_A_LOOK = re.compile(r"\b(?:like|style[ds]?|looks? of|colou?rs?|palette|drawn|painted|shaded|rendered|art|grade[ds]?|lighting|tones?|mood|textures?|grain)\b", re.I)
|
||||
A_SENTENCE = re.compile(r"[^.!?\n]+")
|
||||
STYLE_IS_A_LOOK = ('Picture {slot} is a style: a look, not something in the shot. '
|
||||
'Write "in the style of @{slot}", or give Picture {slot} another job.')
|
||||
|
||||
# (what the label is, how it is kept). {picture} is H3's number for the picture.
|
||||
JOB_WORDS = {
|
||||
@@ -172,7 +180,7 @@ def add_looks(text, jobs, describe):
|
||||
small picture-reading model shown that person's picture. Without such a line H3 kept the original person for the
|
||||
first seconds (2026-11-07), so a connected model writes it when the user didn't."""
|
||||
text = looks_on_own_lines(text)
|
||||
typed = {int(match.group(1)) for match in map(APPEARANCE_LINE.match, text.splitlines()) if match}
|
||||
typed = set(read_swap(text, jobs).descriptions)
|
||||
for slot in sorted(jobs):
|
||||
if jobs[slot] not in (PERSON, SHEET) or slot in typed:
|
||||
continue
|
||||
@@ -187,87 +195,31 @@ def add_looks(text, jobs, describe):
|
||||
|
||||
|
||||
def swap_appearances(text, jobs, video):
|
||||
"""An optional separate @1 looks like line describes a replacement, not who goes.
|
||||
|
||||
Other jobs and scripts without that exact line keep their original text.
|
||||
The number is the visible picture slot, not its compact H3 ordinal.
|
||||
"""
|
||||
"""How each new person in a swap looks, by the visible picture slot, and the script without its looks and
|
||||
clothes lines. Other jobs keep their text."""
|
||||
if video != SWAP:
|
||||
return text, {}
|
||||
kept, descriptions, clothes = [], {}, {}
|
||||
descriptions = read_swap(text, jobs).descriptions
|
||||
if not descriptions:
|
||||
return text, {}
|
||||
kept = []
|
||||
for line in looks_on_own_lines(text).splitlines():
|
||||
worn = WEARS_LINE.fullmatch(line)
|
||||
if worn and (jobs or {}).get(int(worn.group(1))) in (PERSON, SHEET):
|
||||
clothes.setdefault(int(worn.group(1)), []).append(worn.group(2).strip().rstrip(" ."))
|
||||
continue
|
||||
match = APPEARANCE_LINE.fullmatch(line)
|
||||
if match is None:
|
||||
kept.append(line)
|
||||
continue
|
||||
slot = int(match.group(1))
|
||||
if slot not in (jobs or {}):
|
||||
raise ValueError(f"Picture {slot} is not connected. Connect the new person's picture or remove its looks like line.")
|
||||
if jobs[slot] not in (PERSON, SHEET):
|
||||
raise ValueError(f"Picture {slot} must be a person or character sheet for a swap's looks like line.")
|
||||
if slot in descriptions:
|
||||
raise ValueError(f"Describe Picture {slot} once, in one looks like line.")
|
||||
# A sentence on the looks line that names an @ again ("The trees behind @1 stay the same.") is not how
|
||||
# the person looks: it goes back to the script as its own line, or H3 reads a raw @1 in the appearance.
|
||||
sentences = re.split(r"(?<=[.!?])\s+", match.group(2).strip())
|
||||
looks = [sentence for sentence in sentences if not TOKEN.search(sentence)]
|
||||
kept.extend(sentence for sentence in sentences if TOKEN.search(sentence))
|
||||
description = " ".join(looks).strip().rstrip(" .")
|
||||
if not description:
|
||||
raise ValueError(f"Say what Picture {slot}'s person looks like, or remove its looks like line.")
|
||||
descriptions[slot] = description
|
||||
for slot, worn in clothes.items():
|
||||
# Clothes typed on their own line join the description; with none typed, the picture still gives the hair.
|
||||
descriptions[slot] = f"{descriptions.get(slot, 'the same hair')}, wearing {' and '.join(worn)}"
|
||||
return ("\n".join(kept), descriptions) if descriptions else (text, {})
|
||||
# A sentence on the looks line that names an @ again ("The trees behind @1 stay the same.") goes back.
|
||||
kept.extend(sentence for sentence in re.split(r"(?<=[.!?])\s+", match.group(2).strip()) if TOKEN.search(sentence))
|
||||
return "\n".join(kept), descriptions
|
||||
|
||||
|
||||
# Where each person stands when two or more go and the script doesn't say, from left to right like the pictures.
|
||||
SPOTS = {2: ("left", "right"), 3: ("left", "centre", "right"), 4: ("far left", "left", "right", "far right")}
|
||||
SAYS_WHO = re.compile(
|
||||
r"^(?:is|are|replaces|takes\s+the\s+place\s+of|goes\s+in\s+for|swaps?\s+(?:in\s+)?for|in\s+place\s+of|for|as)\b\s*"
|
||||
r"|^[:=\-\u2013\u2014>]+\s*",
|
||||
re.I,
|
||||
)
|
||||
# "he replaces the person at the counter": the words after one of these are who goes, wherever they stand in the line.
|
||||
REPLACES = re.compile(
|
||||
r"\b(?:replaces|replacing|takes\s+the\s+place\s+of|taking\s+the\s+place\s+of|in\s+place\s+of|instead\s+of"
|
||||
r"|swaps?\s+(?:in\s+)?for|goes\s+in\s+for|stands?\s+in\s+for)\s+",
|
||||
re.I,
|
||||
)
|
||||
# A plain sentence: "Replace the man in red with @1", "swap the guy for @1", "make the dancer look like @1",
|
||||
# "swap @1 in for the singer". The words caught are who goes.
|
||||
ASKS = re.compile(
|
||||
r"^\s*(?:please\s+)?(?:replace|swap(?:\s+out)?|switch(?:\s+out)?|change|turn|make)\s+(?!@\d)(.+?)\s+"
|
||||
r"(?:with|for|to|into|by|look\s+like|become)\s+@\d\b"
|
||||
r"|^\s*(?:please\s+)?(?:swap|put|place|drop|switch)\s+@\d\s+(?:in\s+)?(?:with|for|over|on|onto|in\s+place\s+of)\s+(.+)",
|
||||
re.I,
|
||||
)
|
||||
# "the cashier is now @1", "the man on the left becomes @1".
|
||||
BECOMES = re.compile(
|
||||
r"^\s*(.+?)\s+(?:is\s+now|becomes|turns\s+into|is\s+replaced\s+(?:by|with)|gets\s+replaced\s+(?:by|with)"
|
||||
r"|is\s+swapped\s+(?:for|with|to)|gets\s+swapped\s+(?:for|with)|->|\u2192)\s*@\d\b",
|
||||
re.I,
|
||||
)
|
||||
IN_THE_CLIP = re.compile(r"\s+(?:in|from|of)\s+the\s+(?:clip|video|original(?:\s+(?:clip|video))?)\b", re.I)
|
||||
# "Elon is @1," names the new person, not the one who goes.
|
||||
# "the man on the left, Dario is" ends where the next person's name starts.
|
||||
NAMES_NEXT = re.compile(r",?\s*(?:[A-Z][\w'.-]*\s+)+(?:is|as|plays)\s*$")
|
||||
NAMES_THE_NEW = re.compile(r"^[^@.;]*?\b(?:is|as|plays)\s+@\d\b[\s,.;]*", re.I)
|
||||
SWAPPED = "attribute_transfer - apply the defined appearance to the original performance; the background of {picture} is not transferred."
|
||||
# "keeps the outfit", "in the clip's clothes": the new person wears the clothes of the one who goes, not the picture's.
|
||||
KEEP_CLOTHES = (
|
||||
r"\bkeep(?:s|ing)?\s+(?:the\s+|his\s+|her\s+|their\s+)?(?:original\s+|same\s+)?(?:outfit|clothes|clothing)\b"
|
||||
r"(?:\s+(?:from|of|in)\s+the\s+(?:clip|video|original))?"
|
||||
r"|\b(?:in|wearing|wears)\s+the\s+(?:clip'?s|video'?s|original)\s+(?:outfit|clothes|clothing)\b"
|
||||
r"|\b(?:outfit|clothes|clothing)\s+(?:from|of)\s+the\s+(?:clip|video)\b"
|
||||
)
|
||||
KEEP_CLOTHES = KEEP_CLOTHES_WORDS
|
||||
CLIP_CLOTHES = re.compile(KEEP_CLOTHES, re.I)
|
||||
CLIP_CLOTHES_CUT = re.compile(rf",?\s*(?:\band\s+)?(?:{KEEP_CLOTHES})", re.I)
|
||||
CLOTHED_SWAP = "{subject} is the person in {picture}, with the same face and hair, wearing the clothes of {who} in <Video 1>."
|
||||
CLOTHES_STAY = (
|
||||
"attribute_transfer - apply only the face and hair to the original performance; the clothes of {who} in <Video 1> "
|
||||
@@ -299,34 +251,8 @@ REVOICE_KEPT = (
|
||||
)
|
||||
|
||||
|
||||
# A line only names who goes when it is a noun phrase like "the child in the seat", not an action or a pronoun.
|
||||
NOUN_PHRASE = re.compile(r"^(?:the|a|an|this|that|these|those|his|her|their|everyone|someone|somebody|both|each|all)\b", re.I)
|
||||
ACTION_WORD = re.compile(
|
||||
r"\b(?:dances|walks|runs|talks|says|sits|stands|smiles|waves|jumps|enters|leaves|laughs|sings|eats|drinks|waits|"
|
||||
r"is\s+\w+ing|are\s+\w+ing)\b",
|
||||
re.I,
|
||||
)
|
||||
|
||||
|
||||
def who_goes_in(text):
|
||||
"""Who a typed swap line says goes, without the rest of the line: "Elon is @1, he replaces the man at the
|
||||
counter" is the man at the counter, and so is "Replace the man at the counter with @1."."""
|
||||
replaces = REPLACES.search(text)
|
||||
plain = None if replaces else next((match for match in (ASKS.search(text), BECOMES.search(text)) if match), None)
|
||||
if replaces:
|
||||
text = text[replaces.end() :]
|
||||
elif plain:
|
||||
text = next(group for group in plain.groups() if group)
|
||||
else:
|
||||
text = NAMES_THE_NEW.sub("", text)
|
||||
text = IN_THE_CLIP.sub("", text)
|
||||
text = re.split(r"[.;!?]", text.strip(" .;!?"), maxsplit=1)[0]
|
||||
text = NAMES_NEXT.sub("", text)
|
||||
text = SAYS_WHO.sub("", TOKEN.sub("", text).strip(" .,;")).strip(" .,;")
|
||||
text = re.sub(r"\s+and$", "", text).strip(" .,;")
|
||||
if not (replaces or plain) and not (NOUN_PHRASE.match(text) and not ACTION_WORD.search(text)):
|
||||
return "" # "@1 dances" or "He dances" says what happens, not who goes.
|
||||
return text
|
||||
# Where each person stands when two or more go and the script doesn't say, from left to right like the pictures.
|
||||
SPOTS = {2: ("left", "right"), 3: ("left", "centre", "right"), 4: ("far left", "left", "right", "far right")}
|
||||
|
||||
|
||||
def lower_first(text):
|
||||
@@ -467,25 +393,13 @@ class Cast:
|
||||
new = subject_label(picture.subject)
|
||||
return next((who for _, who, coming in self.swaps if coming == new), self.who)
|
||||
|
||||
def name_who_goes(self, lines):
|
||||
"""Who each new person replaces, from the lines typed in a swap. With one, the words are who goes. With more,
|
||||
each @ names one, or else the lines go in picture order; anything else keeps left to right."""
|
||||
self.clip_clothes = any(CLIP_CLOTHES.search(line) for line in lines)
|
||||
lines = [CLIP_CLOTHES_CUT.sub("", line).strip() for line in lines]
|
||||
lines = [line for line in lines if line.strip(" .")]
|
||||
text = ". ".join(line.rstrip(" .") for line in lines) # Each line ends where its who-goes words end.
|
||||
if len(self.whos) == 1:
|
||||
self.who = lower_first(who_goes_in(text) or ONE_GOES)
|
||||
return
|
||||
slots = [picture.slot for picture in self.swappers]
|
||||
pieces = re.split(r"@(\d)\b", text)
|
||||
named = {int(slot): words for slot, words in zip(pieces[1::2], pieces[2::2]) if int(slot) in slots}
|
||||
if not named:
|
||||
named = dict(zip(slots, lines)) if len(lines) == len(slots) else {}
|
||||
for index, slot in enumerate(slots):
|
||||
words = who_goes_in(named.get(slot, ""))
|
||||
if words:
|
||||
self.whos[index] = lower_first(words)
|
||||
def name_who_goes(self, read, text):
|
||||
"""Who each new person replaces, from the reader. A new person nobody placed keeps the default: the original
|
||||
person, or left to right."""
|
||||
self.clip_clothes = bool(CLIP_CLOTHES.search(text or ""))
|
||||
for index, picture in enumerate(self.swappers):
|
||||
if picture.slot in read.goes:
|
||||
self.whos[index] = lower_first(read.goes[picture.slot])
|
||||
|
||||
@property
|
||||
def main(self):
|
||||
@@ -550,11 +464,20 @@ class Cast:
|
||||
return NEEDS_A_PERSON[self.video]
|
||||
if self.video == REVOICE and self.of(PERSON, SHEET):
|
||||
return REVOICE_KEEPS_PERSON
|
||||
for job, verb in ((START, "starts"), (END, "ends")):
|
||||
same = self.of(job)
|
||||
if len(same) > 1:
|
||||
return (f'Pictures {same[0].slot} and {same[1].slot} are both "{job}". '
|
||||
f"The clip {verb} on one picture, so pick another job for Picture {same[1].slot}.")
|
||||
for number in sorted({int(number) for number in ANY_NUMBER.findall(text)} - {0}):
|
||||
if number > 4:
|
||||
return f"There are four pictures, @1 to @4. Take @{number} out of your script."
|
||||
typed = sorted({int(number) for number in TOKEN.findall(text)} - {0})
|
||||
slots = {picture.slot: picture for picture in self.pictures}
|
||||
for slot in typed:
|
||||
if slot not in slots:
|
||||
return f"@{slot} has no picture. Turn Picture {slot} on, or take @{slot} out of your script."
|
||||
# The picture is switched off or not connected: from here the two look the same.
|
||||
return f"@{slot} has no picture: connect or turn on Picture {slot}, or take @{slot} out of your script."
|
||||
if slots[slot].job == END:
|
||||
return f"Picture {slot} is where the clip ends, so @{slot} can't be in a line. Say what happens on the way there."
|
||||
if typed:
|
||||
@@ -568,6 +491,15 @@ class Cast:
|
||||
return f"Picture {picture.slot} is on, but no line names @{picture.slot}.{hint}"
|
||||
return ""
|
||||
|
||||
def style_as_a_thing(self, text):
|
||||
"""A style picture named like something in the shot, as in "@1 wears @3"."""
|
||||
styles = {picture.slot for picture in self.of(STYLE)}
|
||||
for sentence in A_SENTENCE.findall(text):
|
||||
for slot in TOKEN.findall(sentence):
|
||||
if int(slot) in styles and not AS_A_LOOK.search(sentence):
|
||||
return STYLE_IS_A_LOOK.format(slot=slot)
|
||||
return ""
|
||||
|
||||
def wearers(self, moments):
|
||||
"""Who wears each outfit: the person named just before it, or else the main person."""
|
||||
found = {}
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
"""What H3 Prompt Writer asks its small model, and a node's own wording for each.
|
||||
|
||||
A node keeps its own wording in one hidden text input, as JSON: {"describe": ..., "next": ..., "heard": ..., "tidy": ...}.
|
||||
A missing, empty or unreadable entry means the built-in wording, so a workflow saved without it runs as before."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
from ._h3_cast_helpers import DESCRIBE_PERSON
|
||||
from ._h3_script_helpers import HEARD, NEXT
|
||||
from ._h3_tidy_helpers import TIDY_SYSTEM
|
||||
|
||||
BUILT_IN = {"describe": DESCRIBE_PERSON, "next": NEXT, "heard": HEARD, "tidy": TIDY_SYSTEM}
|
||||
LONGEST_ASK = 8000
|
||||
|
||||
|
||||
def parse_asks(value):
|
||||
"""The node's own wordings that are set, by name. Anything else in the text is left out."""
|
||||
try:
|
||||
found = json.loads(value) if value else {}
|
||||
except (TypeError, ValueError, RecursionError):
|
||||
return {}
|
||||
if not isinstance(found, dict):
|
||||
return {}
|
||||
asks = {}
|
||||
for key in BUILT_IN:
|
||||
words = found.get(key)
|
||||
if isinstance(words, str) and words.strip():
|
||||
asks[key] = words.strip()[:LONGEST_ASK]
|
||||
return asks
|
||||
@@ -12,6 +12,7 @@ import re
|
||||
|
||||
import numpy as np
|
||||
|
||||
from ._h3_swap_reader import read_swap
|
||||
from ._h3_cast_helpers import EDIT, KEEP, NEEDS_NO_WORDS, ONE_GOES, REVOICE, SWAP, Cast, number_pictures, swap_appearances
|
||||
from ._h3_cast_helpers import TOKEN, things_that_perform
|
||||
from ._h3_script_helpers import (
|
||||
@@ -25,7 +26,6 @@ from ._h3_script_helpers import (
|
||||
script_parts,
|
||||
speakers,
|
||||
voice_of,
|
||||
without_speech,
|
||||
)
|
||||
|
||||
SECTIONS = (
|
||||
@@ -96,14 +96,20 @@ def add_task(summary, task):
|
||||
return "[" + " + ".join(tasks) + "]" + summary[match.end() :]
|
||||
|
||||
|
||||
def spoken_line(speaker, words, language, voice_label, on_screen, number=1, lips="", delivery=""):
|
||||
def spoken_line(speaker, words, language, voice_label, on_screen, number=1, lips="", delivery="", verb="says"):
|
||||
"""The sentence that carries the words, with the speaker's mouth stated
|
||||
the way H3 needs it: moving and then closed on screen, closed in a
|
||||
voiceover. lips names a video whose lip movement the words land on."""
|
||||
line = f"<d>[{language}] {words}</d>"
|
||||
if speaker is None: # The typed line around it already says who speaks.
|
||||
return line
|
||||
said = f"says {delivery}" if delivery else "says"
|
||||
said = f"{verb} {delivery}" if delivery else verb # "whispers", "says quietly"
|
||||
if speaker.startswith("\x04"): # Someone on screen named in words: "the customer".
|
||||
name = speaker[1:]
|
||||
return (
|
||||
f"{name[:1].upper()}{name[1:]} ({f'S{number}'}) {said}, {line} The jaw and lips of {name} move clearly "
|
||||
f"through every word. {name[:1].upper()}{name[1:]} closes the lips."
|
||||
)
|
||||
if not speaker.startswith("<"): # A thing off screen, like a card reader.
|
||||
return f"{speaker} (S{number}) {said} from off screen, {line} Nobody on screen moves their lips to these words."
|
||||
if on_screen:
|
||||
@@ -298,7 +304,7 @@ def put_on_from_pictures(script, jobs):
|
||||
|
||||
|
||||
def write_prompt(script, seconds=15.0, camera="", look="", sound="", language="English", voice=False, song_beats=None,
|
||||
ask=None, jobs=None, video="", soundtrack=False, clip_sound=False, speech=None):
|
||||
ask=None, jobs=None, video="", soundtrack=False, clip_sound=False, speech=None, asks=None):
|
||||
"""The finished prompt.
|
||||
|
||||
A typed scene is read and laid out over seconds; H3's own six parts go
|
||||
@@ -326,6 +332,7 @@ def write_prompt(script, seconds=15.0, camera="", look="", sound="", language="E
|
||||
jobs = things_that_perform(script, jobs, video)
|
||||
cast = Cast(number_pictures(jobs, video), video)
|
||||
cast.voiced = bool(voice)
|
||||
typed = script
|
||||
script, cast.appearances = swap_appearances(script, jobs, video)
|
||||
scene = read_script(script)
|
||||
cast.notice_people(" ".join(moment.text for moment in scene.moments))
|
||||
@@ -338,7 +345,7 @@ def write_prompt(script, seconds=15.0, camera="", look="", sound="", language="E
|
||||
if not scene.moments and video not in NEEDS_NO_WORDS:
|
||||
raise ValueError(NO_SCRIPT)
|
||||
if video == SWAP and scene.moments: # Typed words in a swap say which person goes, for a clip with two.
|
||||
cast.name_who_goes([without_speech(moment) for moment in scene.moments])
|
||||
cast.name_who_goes(read_swap(typed, jobs), typed)
|
||||
if cast.appearances and cast.clip_clothes:
|
||||
raise ValueError('Remove "keep the clip\'s clothes" or the looks like line. This appearance hint replaces the whole look.')
|
||||
goes = [(who, str(picture.slot)) for who, picture in zip(cast.whos, cast.swappers) if who != ONE_GOES]
|
||||
@@ -358,8 +365,8 @@ def write_prompt(script, seconds=15.0, camera="", look="", sound="", language="E
|
||||
if voice and not any(moment.speech for moment in scene.moments):
|
||||
raise ValueError(VOICE_NO_WORDS)
|
||||
if ask is not None and video != SWAP: # A swap keeps the clip's own action; its model only writes the looks.
|
||||
add_moments(scene, seconds, ask, jobs)
|
||||
add_sound(scene, ask, jobs)
|
||||
add_moments(scene, seconds, ask, jobs, (asks or {}).get("next"))
|
||||
add_sound(scene, ask, jobs, (asks or {}).get("heard"))
|
||||
audio += soundtrack and video == KEEP
|
||||
speaker = next(iter(speakers(scene.moments, cast)), None)
|
||||
|
||||
@@ -368,10 +375,10 @@ def write_prompt(script, seconds=15.0, camera="", look="", sound="", language="E
|
||||
|
||||
if parts is None:
|
||||
|
||||
def say(words, on_screen=True, who="<Subject 1>", number=1, delivery=""):
|
||||
def say(words, on_screen=True, who="<Subject 1>", number=1, delivery="", verb="says"):
|
||||
lips = "<Video 1>" if video in (REVOICE, SWAP, EDIT) else ""
|
||||
voiced = voice_label if number == 1 else None
|
||||
return spoken_line(who, clean_words(words), language, voiced, on_screen, number, lips, delivery)
|
||||
return spoken_line(who, clean_words(words), language, voiced, on_screen, number, lips, delivery, verb)
|
||||
|
||||
parts = script_parts(scene, seconds, camera=camera, look=look, sound=sound, say=say, cast=cast, soundtrack=soundtrack)
|
||||
|
||||
|
||||
+287
-30
@@ -11,6 +11,7 @@ from __future__ import annotations
|
||||
from dataclasses import dataclass, field
|
||||
import re
|
||||
|
||||
from ._h3_swap_reader import SWAPPERS, read_swap
|
||||
from ._h3_cast_helpers import (
|
||||
SAYS_AFTER,
|
||||
EDIT,
|
||||
@@ -132,6 +133,24 @@ A_NAME = re.compile(r"^[A-Z][\w'.-]*(?:\s+[A-Z][\w'.-]*)?$")
|
||||
UNSEEN = re.compile(r"\b(?:feels?|thinks?|remembers?|reali[sz]es?|decides?|wants?|hopes?|wonders?|knows?|understands?|believes?|imagines?)\b", re.I)
|
||||
MOVING = re.compile(r"\b(?:pov|walks?|walking|runs?|running|forward|follows?|tracks?)\b", re.I)
|
||||
FRAME_WORDS = re.compile(r"^(?:(?:an?|the)\s+(?:[\w-]+\s+){0,2}?(?:close-?up|wide|medium|shot|view|angle|overhead|profile|insert|aerial)\b|black\b)", re.I)
|
||||
# The same typed with no "a" in front, as most people do: "Close-up of her boots", "Wide shot of the valley".
|
||||
# Narrower than the form above, so "Wide awake, she sits up" stays something that happens.
|
||||
BARE_FRAME = re.compile(
|
||||
r"^(?:(?:extreme|tight|big|medium|wide|long|full|low|high)[\s-]+)*(?:close-?up|(?:wide|medium|long|full|two|macro|establishing"
|
||||
r"|tracking|drone|aerial|overhead|profile|insert|pov|reaction|over-the-shoulder)[\s-]+(?:shot|view|angle)|(?:low|high)[\s-]+angle"
|
||||
r"|pov|(?:shot|view|insert)\s+of|wide\s+(?:of|on)|tight\s+on|close\s+on)\b",
|
||||
re.I,
|
||||
)
|
||||
|
||||
|
||||
def framing(words):
|
||||
"""A line that only says how the camera frames what we see, with "a" or
|
||||
"an" in front when it was typed without one. Empty for any other line."""
|
||||
if FRAME_WORDS.match(words):
|
||||
return words
|
||||
if not BARE_FRAME.match(words):
|
||||
return ""
|
||||
return ("an " if words[:1].lower() in "aeio" else "a ") + lower_first(words)
|
||||
|
||||
# What a small model is asked. It adds to a script; it never holds what was typed.
|
||||
NEXT = (
|
||||
@@ -278,6 +297,7 @@ class Moment:
|
||||
delivery: str = "" # How a swap line is said: "in a flat robot voice".
|
||||
other: bool = False # Said by someone who is in no picture, like the man at the counter.
|
||||
back: bool = False # "cut back to": a place already seen.
|
||||
named: str = "" # Who says it, named in words when two people are: "\x04the customer".
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -288,19 +308,40 @@ class Script:
|
||||
sound: str = ""
|
||||
music: str = "" # "N/A" is no music.
|
||||
silent: bool = False
|
||||
quiet: bool = False # "sound: none": no sound of the place. The music stays.
|
||||
one_take: bool = False
|
||||
|
||||
|
||||
SINGLE_QUOTED = re.compile(
|
||||
r"\b((?:says?|said|asks?|asked|whispers?|whispered|shouts?|shouted|yells?|yelled|screams?|mutters?|sings?|replies|replied"
|
||||
r"|answers?|calls?\s+out|cries)\s*[:,]?\s*)'([^'\n\x01]+?)'(?!\w)",
|
||||
# An apostrophe inside a word, as in don't, is part of the words.
|
||||
r"|answers?|calls?\s+out|cries)\s*[:,]?\s*)'((?:[^'\n\x01]|(?<=\w)'(?=\w))+?)'(?!\w)",
|
||||
re.I,
|
||||
)
|
||||
|
||||
|
||||
# The last quote on a line opens words: at the start, or after a space or ( [ : ,
|
||||
OPENS_LAST = re.compile(r'(?:^|[\s(\[:,])"[^"]*$')
|
||||
|
||||
|
||||
def close_quotes(text):
|
||||
"""A line whose words open with a quote that never closes: they run to the
|
||||
end of the line, the way they are coloured. A closing quote is easy to miss
|
||||
on a phone; a 12" record is a measure and stays as typed."""
|
||||
return "\n".join(
|
||||
line.rstrip() + '"' if line.count('"') % 2 and OPENS_LAST.search(line) else line for line in text.split("\n")
|
||||
)
|
||||
|
||||
|
||||
# Bold and italic marks pasted from a chat or a notes app: **word**, *word*, __word__, _word_.
|
||||
MARKED = re.compile(r"(?<![\w*_])(\*\*|__|\*|_)(?=\S)([^\n*_]+?)(?<=\S)\1(?![\w*_])")
|
||||
|
||||
|
||||
def clean(text):
|
||||
for old, new in QUOTES.items():
|
||||
text = text.replace(old, new)
|
||||
text = MARKED.sub(r"\2", text)
|
||||
text = close_quotes(text)
|
||||
# Words already in double quotes stay as typed, so a quote inside them can't move their ends.
|
||||
kept = []
|
||||
|
||||
@@ -342,6 +383,10 @@ def split_line(line):
|
||||
return pieces
|
||||
|
||||
|
||||
# What people type in Sound or Music to turn it off.
|
||||
NOTHING = re.compile(r"^(?:none|no(?:\s+(?:sounds?|audio|music|score))?|n/?a|off|silent|silence|nothing)$", re.I)
|
||||
|
||||
|
||||
def take_label(line, script):
|
||||
"""camera: look: sound: music: lines go to their own part."""
|
||||
match = LABEL.match(line)
|
||||
@@ -353,9 +398,12 @@ def take_label(line, script):
|
||||
elif name in ("style", "look"):
|
||||
script.look = value
|
||||
elif name in ("sound", "sounds", "audio"):
|
||||
script.sound = value
|
||||
if NOTHING.match(value.rstrip(".")):
|
||||
script.quiet = True
|
||||
else:
|
||||
script.sound = value
|
||||
else:
|
||||
script.music = "N/A" if value.lower().rstrip(".") in ("none", "no", "n/a", "off") else value
|
||||
script.music = "N/A" if NOTHING.match(value.rstrip(".")) else value
|
||||
return True
|
||||
|
||||
|
||||
@@ -415,6 +463,31 @@ def one_or_more(text, match):
|
||||
return len(rest.split()) > 1 or (bool(rest) and (match.group(0).rstrip().endswith(":") or rest.lower() in ("black", "white")))
|
||||
|
||||
|
||||
# "he yells wait": words said with no quotes, at the end of a line. Where or how
|
||||
# they are said ("yells at the dog", "says nothing", "shouts back") is not words.
|
||||
BARE_SPEECH = re.compile(
|
||||
r"\b((?:says?|yells?|shouts?|screams?|whispers?|mutters?|asks?|cries|calls\s+out)\s+)([A-Za-z'][\w' ,!?-]{0,40}?)[.!?]*$",
|
||||
re.I,
|
||||
)
|
||||
NOT_SAID = re.compile(
|
||||
r"^(?:at|to|for|from|with|into|in|on|back|out|up|down|over|across|again|nothing|something|anything|it|this|that"
|
||||
r"|the|a|an|his|her|their|its|my|our|your|him|them|me|us|so|too|and|but|while|as|\w+ly)$",
|
||||
re.I,
|
||||
)
|
||||
|
||||
|
||||
def quote_bare_speech(text):
|
||||
"""'he yells wait' as 'he yells "Wait"', so the words are said."""
|
||||
match = None if '"' in text else BARE_SPEECH.search(text)
|
||||
if not match:
|
||||
return text
|
||||
words = match.group(2).strip(" ,")
|
||||
if not 0 < len(words.split()) <= 4 or any(NOT_SAID.match(word.strip(",!?")) for word in words.split()):
|
||||
return text
|
||||
words = words.capitalize() if words.isupper() else words[:1].upper() + words[1:]
|
||||
return f'{text[: match.start(2)]}"{words}"'
|
||||
|
||||
|
||||
def read_moment(moment):
|
||||
text = moment.text
|
||||
timed = TIMED.match(text)
|
||||
@@ -441,6 +514,7 @@ def read_moment(moment):
|
||||
moment.end = True
|
||||
text = text[end.end() :]
|
||||
text = re.sub(r"\s+", " ", text).strip(" ,.")
|
||||
text = quote_bare_speech(text)
|
||||
moment.text = text[:1].upper() + text[1:] if text else ""
|
||||
quoted_words(moment)
|
||||
|
||||
@@ -560,10 +634,22 @@ def moments_for(seconds):
|
||||
return max(2, round(seconds / 2.5))
|
||||
|
||||
|
||||
# "Moment 2: She looks up" and "0:04 She lifts it": the label is not part of the line.
|
||||
LABELLED = re.compile(r"^(?:(?:moment|line|shot|scene|beat)\s*\d+\s*[:.)-]\s*|\d{1,2}:\d{2}(?:\.\d+)?\s*[-:]?\s*)", re.I)
|
||||
# What a chat model says around its answer, or in place of one.
|
||||
CHATTER = re.compile(
|
||||
r"^(?:sure\b|certainly\b|of course\b|okay\b|ok\b|here(?:'s|\s+is|\s+are)\b|i'?m\s+sorry|i\s+am\s+sorry|sorry\b|i\s+can(?:'t|not)\b"
|
||||
r"|i\s+cannot\b|as\s+an\s+ai\b|let\s+me\s+know\b|i\s+hope\b|note\s*:)|:\s*$",
|
||||
re.I,
|
||||
)
|
||||
|
||||
|
||||
def answer_lines(answer):
|
||||
"""The lines of a model's answer, without numbers or bullets."""
|
||||
lines = (NUMBER.sub("", line).strip() for line in str(answer).split("\n"))
|
||||
return [line for line in lines if line]
|
||||
"""The lines of a model's answer, without numbers, bullets, labels or the
|
||||
talk a chat model puts around them. A line that names a picture is the
|
||||
model echoing its question, so it goes too."""
|
||||
lines = (LABELLED.sub("", NUMBER.sub("", MARKED.sub(r"\2", line))).strip() for line in str(answer or "").split("\n"))
|
||||
return [line for line in lines if line and not CHATTER.search(line) and "@" not in line]
|
||||
|
||||
|
||||
def bare(line):
|
||||
@@ -575,12 +661,19 @@ def usable_line(line, kept):
|
||||
return 1 < len(words) <= LINE_WORDS and not set(line) & set('"<>[]{}') and all(bare(line) != bare(other) for other in kept)
|
||||
|
||||
|
||||
def fill_words(template, **values):
|
||||
"""The wording with {name} replaced for each value; other braces stay, so a node's own wording never breaks a run.
|
||||
|
||||
One pass, so braces inside a filled-in value (a typed line) are never filled in themselves."""
|
||||
return re.sub(r"\{(\w+)\}", lambda match: str(values[match.group(1)]) if match.group(1) in values else match.group(0), template)
|
||||
|
||||
|
||||
def plain_names(text, jobs):
|
||||
"""The line with each @ swapped for what that picture is."""
|
||||
return TOKEN.sub(lambda match: NAMED.get((jobs or {}).get(int(match.group(1))), "the person"), text)
|
||||
|
||||
|
||||
def add_moments(script, seconds, ask, jobs=None):
|
||||
def add_moments(script, seconds, ask, jobs=None, wording=None):
|
||||
"""One typed line in a clip with time to spare: a small model adds what
|
||||
happens next. The typed line stays first, and a line that fails the check
|
||||
is left out, so a bad answer costs nothing."""
|
||||
@@ -589,18 +682,18 @@ def add_moments(script, seconds, ask, jobs=None):
|
||||
wanted = moments_for(seconds) - 1
|
||||
first = plain_names(script.moments[0].text, jobs)
|
||||
kept = [first]
|
||||
for line in answer_lines(ask(NEXT.format(seconds=seconds, first=first, count=wanted), 256)):
|
||||
for line in answer_lines(ask(fill_words(wording or NEXT, seconds=seconds, first=first, count=wanted), 256)):
|
||||
if len(kept) <= wanted and usable_line(line, kept):
|
||||
kept.append(line)
|
||||
script.moments.append(Moment(line.strip(" ,.")))
|
||||
|
||||
|
||||
def add_sound(script, ask, jobs=None):
|
||||
def add_sound(script, ask, jobs=None, wording=None):
|
||||
"""What this place sounds like, unless someone said."""
|
||||
if script.sound or script.silent:
|
||||
if script.sound or script.silent or script.quiet:
|
||||
return
|
||||
lines = "\n".join(plain_names(moment.text, jobs) for moment in script.moments)
|
||||
answer = " ".join(answer_lines(ask(HEARD.format(lines=lines), 64)))
|
||||
answer = " ".join(answer_lines(ask(fill_words(wording or HEARD, lines=lines), 64)))
|
||||
if 1 < len(answer.split()) <= SOUND_WORDS and not set(answer) & set('"<>[]{}'):
|
||||
script.sound = answer
|
||||
|
||||
@@ -624,13 +717,100 @@ def script_warning(script, seconds, cast=None):
|
||||
takes = len(moment.speech.split()) / WORDS_A_SECOND
|
||||
if takes > end - start + 0.5 and index not in carried and index != cut_off:
|
||||
return f"A spoken line takes about {takes:.0f} seconds to say, and its moment has {end - start:.0f}. Give it more room."
|
||||
return ""
|
||||
# Said last, and only said: the run goes ahead with the script as typed.
|
||||
return cast.style_as_a_thing("\n".join(moment.text for moment in script.moments)) if cast else ""
|
||||
|
||||
|
||||
def swap_reading(text, jobs, parts=None):
|
||||
"""What a swap's lines were read as, for the node: who each new person replaces and how they look, from the
|
||||
same reading the prompt uses, and the words a swap does not use. With the written prompt's parts, also the
|
||||
other pictures it names and who says what, by picture."""
|
||||
jobs = things_that_perform(text, jobs, SWAP)
|
||||
read = read_swap(text, jobs)
|
||||
cast = Cast(number_pictures(jobs, SWAP), SWAP)
|
||||
cast.name_who_goes(read, text)
|
||||
descriptions = read.descriptions
|
||||
people = [
|
||||
{"slot": picture.slot, "goes": who, "looks": descriptions.get(picture.slot, ""), "named": picture.slot in read.goes}
|
||||
for picture, who in zip(cast.swappers, cast.whos)
|
||||
]
|
||||
reading = {"people": people, "unused": read.unused, "keeps_clip_clothes": cast.clip_clothes}
|
||||
if parts is not None:
|
||||
slot_of = {label: slot for slot, label in cast.subjects.items()}
|
||||
wearers = {slot_of.get(outfit): slot_of.get(wearer) for outfit, wearer in WORN.findall(parts.get("retention_analysis", ""))}
|
||||
reading["pictures"] = [
|
||||
{"slot": slot, "job": job, "worn_by": wearers.get(slot)} for slot, job in sorted(jobs.items()) if job not in SWAPPERS
|
||||
]
|
||||
reading["says"] = [{"slot": slot_of.get(who), "words": words} for who, words in SAYS.findall(parts.get("detailed_description", ""))]
|
||||
return reading
|
||||
|
||||
|
||||
GOES = re.compile(r"^(<Subject \d+>) is (.+) in <Video 1>, selected for replacement\.$")
|
||||
COMES = re.compile(r"^(<Subject \d+>) is (.*?<Picture \d>)(?:, (.+?))?\.(?: The background .*)?$")
|
||||
TAKES = re.compile(r"^(<Subject \d+>): removed - replace .+ with (<Subject \d+>) throughout\.$", re.M)
|
||||
WORN = re.compile(r"^(<Subject \d+>) \([^)]*\): attribute_transfer - put only this outfit on (<Subject \d+>)\.$", re.M)
|
||||
SAYS = re.compile(r"(<Subject \d+>)(?:(?!<Subject \d+>).)*?<d>(?:\[[^\]]*\]\s*)?(.*?)</d>")
|
||||
|
||||
|
||||
def swap_parts(text, jobs):
|
||||
"""The sections of the prompt the writer writes for this swap."""
|
||||
from ._h3_prompt_helpers import split_sections, write_prompt
|
||||
|
||||
return split_sections(write_prompt(text, jobs=jobs, video=SWAP))
|
||||
|
||||
|
||||
def sent(words, description):
|
||||
"""Whether words a swap's reading set aside reached the prompt after all, with each @N as the subject the
|
||||
prompt names in its place: "@1 wears" is sent as "<Subject 2> wears <Subject 4>"."""
|
||||
pieces = [piece.strip(".,;:!?") for piece in str(words).split()]
|
||||
pattern = r"\s+".join(r"<Subject \d+>" if re.fullmatch(r"@\d", piece) else re.escape(piece) for piece in pieces if piece)
|
||||
return bool(pattern) and re.search(pattern, description, re.I) is not None
|
||||
|
||||
|
||||
def swap_cast(text, jobs, parts=None):
|
||||
"""A swap's cast as the Ref2VA prompt names it, one short line each, taken from the prompt the writer writes:
|
||||
who leaves the clip, who takes their place and how they look, every other picture it names, and who says
|
||||
what."""
|
||||
parts = swap_parts(text, jobs) if parts is None else parts
|
||||
replaced = {new: old for old, new in TAKES.findall(parts.get("retention_analysis", ""))}
|
||||
worn = dict(WORN.findall(parts.get("retention_analysis", "")))
|
||||
lines = []
|
||||
for line in parts.get("subject_definitions", "").splitlines():
|
||||
goes = GOES.match(line)
|
||||
comes = COMES.match(line)
|
||||
if goes:
|
||||
lines.append(f"{goes.group(1)} {goes.group(2)} in <Video 1> \u2192 removed")
|
||||
elif comes:
|
||||
subject, who, rest = comes.groups()
|
||||
rest = (rest or "").removeprefix("with the same face and this appearance: ").removeprefix("with ")
|
||||
place = f", takes {replaced[subject]}'s place" if subject in replaced else ""
|
||||
lines.append(f"{subject} = {who}{place}{': ' + rest if rest else ''}")
|
||||
elif line.startswith("<Subject ") and " is " in line:
|
||||
# Every other picture the prompt names, in its first sentence: an outfit, a style.
|
||||
subject, _, words = line.partition(" is ")
|
||||
wearer = f", worn by {worn[subject]}" if subject in worn else ""
|
||||
lines.append(f"{subject} = {words.split('. ')[0].rstrip('.')}{wearer}")
|
||||
for subject, words in SAYS.findall(parts.get("detailed_description", "")):
|
||||
lines.append(f"{subject} says <d>{words}</d>")
|
||||
return lines
|
||||
|
||||
|
||||
def script_report(text, seconds, jobs=None, video=""):
|
||||
"""What a script will do, for the timeline on the node."""
|
||||
reading = None
|
||||
if video == SWAP and jobs is not None:
|
||||
try:
|
||||
parts = swap_parts(text, jobs)
|
||||
reading = swap_reading(text, jobs, parts)
|
||||
reading["cast"] = swap_cast(text, jobs, parts)
|
||||
# Only words the written prompt really leaves out are called unused.
|
||||
reading["unused"] = [words for words in reading["unused"] if not sent(words, parts.get("detailed_description", ""))]
|
||||
except ValueError as error:
|
||||
# The writer refuses these lines when it runs; say why now, on the node.
|
||||
reading = {"people": [], "unused": [], "keeps_clip_clothes": False, "problem": str(error)}
|
||||
# The optional swap description is not a second timed action.
|
||||
text, _ = swap_appearances(text, jobs, video)
|
||||
if not (reading and "problem" in reading):
|
||||
text, _ = swap_appearances(text, jobs, video)
|
||||
script = read_script(text)
|
||||
starts = timeline(script, seconds)
|
||||
ends = [*starts[1:], seconds]
|
||||
@@ -647,7 +827,10 @@ def script_report(text, seconds, jobs=None, video=""):
|
||||
]
|
||||
jobs = things_that_perform(text, jobs, video) if jobs is not None else None
|
||||
cast = Cast(number_pictures(jobs, video), video) if jobs is not None else None
|
||||
return {"moments": moments, "seconds": seconds, "warning": script_warning(script, seconds, cast)}
|
||||
report = {"moments": moments, "seconds": seconds, "warning": script_warning(script, seconds, cast)}
|
||||
if reading is not None:
|
||||
report["read"] = reading
|
||||
return report
|
||||
|
||||
|
||||
def stamp(seconds):
|
||||
@@ -664,29 +847,69 @@ def after_comma(text):
|
||||
|
||||
def sentence(text):
|
||||
text = text.strip()
|
||||
return text if text[-1:] in '.!?"' else text + "."
|
||||
# Words shown on screen end in a quote: 'a sign reading "CLOSED"' still needs its full stop.
|
||||
return text if text[-1:] in ".!?" or text[-2:] in ('."', '!"', '?"') else text + "."
|
||||
|
||||
|
||||
def capital(text):
|
||||
return sentence(text[:1].upper() + text[1:])
|
||||
|
||||
|
||||
def without_speech(moment):
|
||||
"""A moment's words with what is said taken out, and what says it."""
|
||||
# '"Hi" and waves' is what they do next. Anything else, like '"Hi" slowly', is how they say it.
|
||||
DOES_NEXT = re.compile(r"^(?:and\s+then|and|then)\s+", re.I)
|
||||
|
||||
|
||||
def around_speech(moment):
|
||||
"""(before, after): a moment's words with what is said taken out. Before
|
||||
is what happens up to the line, after is what the speaker does once it is
|
||||
said."""
|
||||
if not moment.speech:
|
||||
return moment.text
|
||||
return moment.text, ""
|
||||
before, _, after = moment.text.partition(f'"{moment.speech}"')
|
||||
spoken = SPEECH_CUE.search(before)
|
||||
name = ""
|
||||
if spoken:
|
||||
# "She looks up and says" keeps "She looks up". In "She says" the words
|
||||
# in front only name who speaks.
|
||||
action = before[: spoken.start()].rstrip()
|
||||
linked = re.search(r",?\s*\band(?:\s+\w+ly)?$", action, re.I)
|
||||
before = action[: linked.start()] if linked else action.rpartition(",")[0]
|
||||
if not linked:
|
||||
# Who speaks, when it is a short name. Longer words in front are a
|
||||
# sentence of their own ("@1 hears a voice say"), so the main person does what follows.
|
||||
name = action.rpartition(",")[2].strip()
|
||||
name = name if 0 < len(name.split()) <= 4 and not VOICEOVER.search(name) else MAIN
|
||||
if VOICEOVER.search(before):
|
||||
before = ""
|
||||
after = AFTER_VOICEOVER.sub("", after)
|
||||
return " ".join(part.strip(" ,:") for part in (before, after) if part.strip(" ,:."))
|
||||
before = before.strip(" ,:") if before.strip(" ,:.") else ""
|
||||
after = AFTER_VOICEOVER.sub("", after).strip(" ,:") if AFTER_VOICEOVER.sub("", after).strip(" ,:.") else ""
|
||||
if before or not after or not name:
|
||||
return " ".join(part for part in (before, after) if part), ""
|
||||
# The words in front only named the speaker, so what follows needs them back.
|
||||
next_thing = DOES_NEXT.sub("", after)
|
||||
if next_thing != after:
|
||||
return "", f"{name} {next_thing}"
|
||||
verb = how_said(moment)[0]
|
||||
return f"{name} {'speaks' if verb == 'says' else verb} {after}", ""
|
||||
|
||||
|
||||
def how_said(moment):
|
||||
"""(word, how): the word a line is said with, "whispers" or "shouts", and
|
||||
anything typed between it and the line, "quietly". A plain line is "says"."""
|
||||
before = moment.text.partition(f'"{moment.speech}"')[0]
|
||||
cue = SPEECH_CUE.search(before)
|
||||
verb = SPEECH_VERB.match(before, cue.start()) if cue else None
|
||||
if not verb:
|
||||
return "says", ""
|
||||
first, _, rest = verb.group().lower().partition(" ")
|
||||
first = "says" if first in ("say", "said") else first if first.endswith("s") else first + "s"
|
||||
how = before[verb.end() :].strip(" ,:")
|
||||
return " ".join(f"{first} {rest}".split()), "" if "@" in how or VOICEOVER.search(how) else how
|
||||
|
||||
|
||||
def without_speech(moment):
|
||||
"""A moment's words with what is said taken out, and what says it."""
|
||||
return " ".join(part for part in around_speech(moment) if part)
|
||||
|
||||
|
||||
def moment_words(moment, say, cast):
|
||||
@@ -700,17 +923,49 @@ def moment_words(moment, say, cast):
|
||||
typed = typed.strip()
|
||||
typed = typed if typed.endswith("\x02") else sentence(typed)
|
||||
return typed.replace("\x02", say(moment.speech, not moment.voiceover, bare=True))
|
||||
words = with_labels(without_speech(moment), cast)
|
||||
if moment.start:
|
||||
before, after = around_speech(moment)
|
||||
words = with_labels(before, cast)
|
||||
if moment.start and words:
|
||||
words = "The shot opens on " + lower_first(words)
|
||||
elif moment.end:
|
||||
elif moment.end and words:
|
||||
words = "The shot ends on " + lower_first(words)
|
||||
line = sentence(words) if words else ""
|
||||
if moment.speech:
|
||||
line = f"{line} {say(moment.speech, not moment.voiceover)}".strip()
|
||||
if after:
|
||||
line = f"{line} {sentence(with_labels(after, cast))}".strip()
|
||||
return line
|
||||
|
||||
|
||||
# "A barista slides", "The old fisherman casts": who does it, named in words.
|
||||
DESCRIBED = re.compile(r"^(?:the|a|an)\s+((?:[\w-]+\s+){0,2}?[\w-]+?)\s+(?=[a-z]+s\b)", re.I)
|
||||
IN_WORDS = "\x04" # In front of a speaker named in words, who is on screen.
|
||||
|
||||
|
||||
def described_speaker(moment):
|
||||
"""Who says a line when the words in front name them without an @ or a he
|
||||
or she: "The customer laughs and says" is the customer."""
|
||||
if not moment.speech or moment.voice or moment.voiceover:
|
||||
return ""
|
||||
before = moment.text.partition(f'"{moment.speech}"')[0]
|
||||
if TOKEN.search(before) or PRONOUN.search(before):
|
||||
return ""
|
||||
match = DESCRIBED.match(before)
|
||||
return f"the {match.group(1).lower()}" if match else ""
|
||||
|
||||
|
||||
def name_speakers(moments, cast):
|
||||
"""Two or more people named in words each say their own lines. One is the
|
||||
person in the picture, and keeps the picture's label."""
|
||||
if cast.as_typed:
|
||||
return
|
||||
found = [described_speaker(moment) for moment in moments]
|
||||
if len({who for who in found if who}) < 2:
|
||||
return
|
||||
for moment, who in zip(moments, found):
|
||||
moment.named = IN_WORDS + who if who else ""
|
||||
|
||||
|
||||
def speaker_of(moment, cast):
|
||||
"""Who says a moment's words: an off-screen voice, the person named right
|
||||
before them ("@2 says"), the first person the moment names, or the main
|
||||
@@ -718,6 +973,8 @@ def speaker_of(moment, cast):
|
||||
picked at all."""
|
||||
if moment.voice:
|
||||
return moment.voice
|
||||
if moment.named:
|
||||
return moment.named
|
||||
people = {picture.slot for picture in cast.people}
|
||||
quote = moment.text.find('"')
|
||||
before = moment.text[:quote] if quote >= 0 else moment.text
|
||||
@@ -837,8 +1094,8 @@ def cut_to(words, text, cast, back=False):
|
||||
"""How a later shot opens, and what is left of its first moment to say."""
|
||||
if back:
|
||||
return f"the camera cuts back to {lower_first(words)}", ""
|
||||
if FRAME_WORDS.match(words):
|
||||
return f"the camera cuts to {lower_first(words)}", ""
|
||||
if framing(words):
|
||||
return f"the camera cuts to {lower_first(framing(words))}", ""
|
||||
places = [subject_label(picture.subject) for picture in cast.of(PLACE)]
|
||||
named = next((place for place in places if place in text), None)
|
||||
if named:
|
||||
@@ -866,9 +1123,8 @@ def shot_lines(script, seconds, say, cast, wearers, move="", hold=""):
|
||||
if bare: # Only the speech tag: the typed line around it says who.
|
||||
return say(words, on_screen, None)
|
||||
who = speaker_of(moment, cast)
|
||||
if moment.delivery:
|
||||
return say(words, on_screen, who, talking.index(who) + 1, delivery=moment.delivery)
|
||||
return say(words, on_screen, who, talking.index(who) + 1)
|
||||
verb, how = how_said(moment)
|
||||
return say(words, on_screen, who, talking.index(who) + 1, delivery=moment.delivery or how, verb=verb)
|
||||
|
||||
words = " ".join(
|
||||
[
|
||||
@@ -914,7 +1170,7 @@ def script_sound(script, sound, places=False):
|
||||
if script.silent or sound == "none":
|
||||
return "N/A", "N/A"
|
||||
typed = capital(script.sound) if script.sound else (EACH_PLACE if places else PLACE_SOUND)
|
||||
return typed, capital(script.music) if script.music not in ("", "N/A") else "N/A"
|
||||
return "N/A" if script.quiet else typed, capital(script.music) if script.music not in ("", "N/A") else "N/A"
|
||||
|
||||
|
||||
def task_of(cast):
|
||||
@@ -968,6 +1224,7 @@ def script_parts(script, seconds, camera="", look="", sound="", say=None, cast=N
|
||||
video's own sound is connected."""
|
||||
say = say or (lambda words, on_screen=True, speaker="", number=1: words)
|
||||
cast = cast or Cast(number_pictures({1: PERSON}))
|
||||
name_speakers(script.moments, cast)
|
||||
style, redraw, hold = LOOKS.get(look, ("", "", ""))
|
||||
if script.look:
|
||||
style, redraw, hold = LOOKS.get(script.look.lower().strip(), (sentence(script.look), "", ""))
|
||||
@@ -981,7 +1238,7 @@ def script_parts(script, seconds, camera="", look="", sound="", say=None, cast=N
|
||||
lines = shot_lines(script, seconds, say, cast, wearers, move, hold)
|
||||
last = len(lines)
|
||||
cuts = [script.moments[shot[0]] for shot in shots_of(script)[1:]]
|
||||
new_view = [not moment.back and not FRAME_WORDS.match(without_speech(moment)) for moment in cuts]
|
||||
new_view = [not moment.back and not framing(without_speech(moment)) for moment in cuts]
|
||||
new_places = last > 1 and not cast.of(PLACE) and any(new_view) and all(new_view)
|
||||
# Only a place, a start frame or a person sets the look; an outfit, a thing or a style never does.
|
||||
first = next(iter(cast.of(PLACE) or cast.of(START_JOB) or cast.of(PERSON, SHEET, PERFORMER, END_JOB)), None)
|
||||
|
||||
@@ -0,0 +1,383 @@
|
||||
"""How H3 Prompt Writer reads the lines typed for a swap.
|
||||
|
||||
The text is cut into sentences (quotes and "Mr." stay whole), each sentence into one stretch of words per @, and
|
||||
each stretch is read for two things: who in the clip goes, and how the new person looks. Whatever a sentence says
|
||||
beyond that is kept as "not used", so the node can show it instead of losing it. A swap keeps the clip's action and
|
||||
camera, so only spoken lines go on to the prompt from there.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
import re
|
||||
|
||||
PERSONS = ("person", "character sheet")
|
||||
SWAPPERS = (*PERSONS, "thing that moves") # A moving thing can come in too; only people get a look.
|
||||
TOKEN = re.compile(r"@([1-4])\b")
|
||||
QUOTE_MARKS = '"“”'
|
||||
HAS_QUOTE = re.compile(r'["“”]')
|
||||
ABBREVIATION = re.compile(r"\b(?:Mr|Mrs|Ms|Dr|St|Jr|Sr|Prof|vs|etc)\.$", re.I)
|
||||
# "keeps the outfit", "in the clip's clothes": the new person wears the clothes of the one who goes.
|
||||
KEEP_CLOTHES_WORDS = (
|
||||
r"\bkeep(?:s|ing)?\s+(?:the\s+|his\s+|her\s+|their\s+)?(?:(?:clip|video)'?s\s+)?(?:original\s+|same\s+)?"
|
||||
r"(?:outfit|clothes|clothing)\b(?:\s+(?:from|of|in)\s+the\s+(?:clip|video|original))?"
|
||||
r"|\b(?:in|wearing|wears)\s+the\s+(?:clip'?s|video'?s|original)\s+(?:outfit|clothes|clothing)\b"
|
||||
r"|\b(?:outfit|clothes|clothing)\s+(?:from|of)\s+the\s+(?:clip|video)\b"
|
||||
)
|
||||
KEEP_CLOTHES = re.compile(rf",?\s*(?:\b(?:and|but)\s+)?(?:{KEEP_CLOTHES_WORDS})", re.I)
|
||||
IN_THE_CLIP = re.compile(r"\s+(?:in|from|of)\s+the\s+(?:clip|video|original(?:\s+(?:clip|video))?)\b", re.I)
|
||||
PRONOUN = re.compile(r"^(?:him|her|them|it|he|she|they|his\s+\w+|her\s+\w+|their\s+\w+|the\s+person)$", re.I)
|
||||
NAME = r"[A-Z][a-z][\w'.-]*(?:\s+[A-Z][a-z][\w'.-]*)?"
|
||||
SPOT = r"(?:far\s+left|far\s+right|left|right|middle|centre|center|front|back)"
|
||||
|
||||
# The words to the left of an @ that say who goes. Each pattern ends where the @ starts.
|
||||
ASKS = re.compile(
|
||||
r"^(?:please\s+)?(?:replace|swap|switch|exchange|substitute|change|trade)\s+(?:out\s+)?(?P<x>.+?)\s+(?:out\s+)?"
|
||||
r"(?:with|for|by|to)\s*$",
|
||||
re.I,
|
||||
)
|
||||
MAKE = re.compile(r"^(?:please\s+)?(?:make|turn)\s+(?P<x>.+?)\s+(?:into|look\s+like|become|be)\s*$", re.I)
|
||||
SHORT_ASK = re.compile(r"^(?P<x>.+?)\s+(?:with|for|by)\s*$", re.I) # "and the girl in blue with @2", after a replace.
|
||||
REPLACED = re.compile(
|
||||
r"^(?P<x>.+?)\s+(?:is|gets|will\s+be)\s+(?:replaced|swapped(?:\s+out)?)\s+(?:by|with|for)\s*$"
|
||||
r"|^(?P<y>.+?)\s+(?:becomes|turns\s+into|is\s+now|is|->|→|=>|=)\s*$",
|
||||
re.I,
|
||||
)
|
||||
IN_BRACKETS = re.compile(r"^(?P<x>.+?)\s*\(\s*$")
|
||||
PUTS = re.compile(r"^(?:please\s+)?(?:put|place|drop|swap|switch|insert)\s*$", re.I)
|
||||
LEFT_SIDE = (ASKS, MAKE, REPLACED, IN_BRACKETS)
|
||||
|
||||
# The words to the right of an @, read one piece at a time.
|
||||
POSSESSIVE = re.compile(r"^'s\s+(?:face|head|body|look)\b", re.I)
|
||||
BRACKET = re.compile(r"^\s*\((?P<p>[^)]*)\)")
|
||||
COMMA_LOOKS = re.compile(
|
||||
r"^\s*,\s*(?P<looks>(?:a|an)\s+.+?)\s*(?=,\s*(?:and\s+)?(?:he|she|they|who|replaces|replacing|takes)\b|,\s*and\b|;|$)", re.I
|
||||
)
|
||||
WEARS = re.compile(
|
||||
r"^\s*,?\s*(?:and\s+(?=(?:is\s+)?(?:wears|wearing|dressed)\b))?(?:who\s+(?:is\s+)?(?:wears|wearing)|wearing|wears|is\s+wearing|dressed\s+in|in)\s+"
|
||||
r"(?P<wear>(?:a|an|some)\s+.+?)\s*(?=,|\s+and\s+|;|$)",
|
||||
re.I,
|
||||
)
|
||||
HAS = re.compile(r"^\s*,?\s*(?:who\s+has|who\s+is|with)\s+(?P<looks>.+?)\s*(?=,\s*and\b|\s+and\s+(?:is\s+)?(?:wears|wearing|dressed)\b|\s+and\s+(?:he|she|says|replaces)\b|;|$)", re.I)
|
||||
LOOKS_LIKE = re.compile(r"^\s+(?:looks\s+like|is|has)\s+(?P<looks>(?:a|an|long|short|\w+\s+hair).+?)\s*(?=,\s*and\b|\s+and\s+(?:is\s+)?(?:wears|wearing|dressed)\b|;|$)", re.I)
|
||||
IS_WHO = re.compile(r"^\s*(?:,|\s+is)\s+(?P<x>the\s+.+?)\s*(?=,\s*(?:and|then|while|but)\b|\s+and\s+|;|$)", re.I)
|
||||
IS_NAME = re.compile(rf"^\s+is\s+{NAME}\s*(?=,|$|\s+and\b)")
|
||||
IS_NEW = re.compile(r"^\s+is\s+the\s+new\s+\w+", re.I)
|
||||
GOES_FOR = re.compile(
|
||||
r"^\s*,?\s*(?:and\s+)?(?:(?:he|she|they)\s+)?(?:replaces|is\s+replacing|replacing|takes\s+(?:over\s+)?(?:the\s+)?(?:place|role|spot)\s+of"
|
||||
r"|swaps?\s+(?:in\s+)?(?:for|with)|in\s+for|goes\s+in\s+for|stands?\s+in\s+for|in\s+place\s+of|instead\s+of|for|as|plays)\s+"
|
||||
r"(?P<x>.+?)\s*(?=,\s*(?:and|then|while|but)\b|\s+and\s+(?:the|says|then|make|add|keep|have)\b|;|$)",
|
||||
re.I,
|
||||
)
|
||||
ON_SPOT = re.compile(rf"^\s+(?:on|at|in)\s+the\s+(?P<spot>{SPOT})\b", re.I)
|
||||
NOUN = re.compile(r"^\s+(?P<x>(?:the|a|an|his|her|their)\s+.+?)\s*(?=,\s*(?:and|then|while|but)\b|\s+and\s+|;|$)", re.I)
|
||||
ARROW = re.compile(r"^\s*(?:->|→|=>|=|:)\s*(?P<x>.+?)\s*$")
|
||||
# Lines with no @ that still say something about the one new person: "she has red hair", "he replaces the man".
|
||||
SAYS_LOOKS = re.compile(
|
||||
r"^(?:and\s+)?(?:she|he|they)\s+(?:(?P<wear>wears|is\s+wearing|is\s+dressed\s+in)|has|have|looks\s+like|is\s+(?=a\b|an\b))\s+(?P<looks>.+)$",
|
||||
re.I,
|
||||
)
|
||||
SAYS_GOES = re.compile(
|
||||
r"^(?:and\s+)?(?:she|he|they)\s+(?:replaces|takes\s+the\s+place\s+of|goes\s+in\s+for|stands\s+in\s+for)\s+(?P<x>.+)$", re.I
|
||||
)
|
||||
LOOKS_LINE = re.compile(r"^\s*@([1-4])\s+looks\s+like(?:\s+(?P<looks>.+?))?\s*$", re.I)
|
||||
BARE_WHO = re.compile(r"^(?:the|a|an|this|that|everyone|both)\b", re.I)
|
||||
ACTION = re.compile(
|
||||
r"\b(?:dances|walks|runs|talks|says|sits|stands|smiles|waves|jumps|enters|leaves|laughs|sings|eats|drinks|waits|"
|
||||
r"zooms|pans|is\s+\w+ing|are\s+\w+ing)\b",
|
||||
re.I,
|
||||
)
|
||||
BOUNDARY = re.compile(r";\s*|,\s*and\s+|\s+and\s+|,\s*then\s+|\s+then\s+|,\s*but\s+|,\s+")
|
||||
FILLER = re.compile(
|
||||
r"^(?:(?:both|all|the)\s+(?:two\s+|three\s+|four\s+)?(?:people|persons|of\s+them)\s+(?:are|get)\s+(?:replaced|swapped)|and|then|but|so|please|also|he|she|they|it|him|her|them|ok|okay|thanks|says?|said|@\d|\d+(?:\.\d+)?\s*s(?:ec(?:onds?)?)?:?"
|
||||
r"|at\s+\d+(?:\.\d+)?\s*s(?:ec(?:onds?)?)?|[\W_]+)$",
|
||||
re.I,
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class SwapRead:
|
||||
"""What a swap's typed lines say: who goes (by picture number), how each new person looks, and the words that
|
||||
went nowhere."""
|
||||
|
||||
goes: dict = field(default_factory=dict)
|
||||
looks: dict = field(default_factory=dict)
|
||||
wears: dict = field(default_factory=dict)
|
||||
unused: list = field(default_factory=list)
|
||||
names: dict = field(default_factory=dict)
|
||||
|
||||
@property
|
||||
def descriptions(self):
|
||||
"""How each new person looks, as one phrase. Clothes alone keep the picture's hair."""
|
||||
out = {}
|
||||
for slot in sorted({*self.looks, *self.wears}):
|
||||
looks = ", ".join(self.looks.get(slot, []))
|
||||
worn = " and ".join(self.wears.get(slot, []))
|
||||
out[slot] = f"{looks or 'the same hair'}, wearing {worn}" if worn else looks
|
||||
return out
|
||||
|
||||
|
||||
def sentences(text):
|
||||
"""The text cut into sentences: at each line end, at . ! ? outside quotes that are not part of "Mr.", and after a
|
||||
quote that ends with one."""
|
||||
out = []
|
||||
for line in str(text or "").splitlines():
|
||||
start, quoted, index = 0, False, 0
|
||||
while index < len(line):
|
||||
char = line[index]
|
||||
if char in QUOTE_MARKS:
|
||||
quoted = not quoted
|
||||
# A quote that ends its own sentence ("Hi." Then ...) ends the sentence with it.
|
||||
at_end = index + 1 == len(line) or line[index + 1].isspace()
|
||||
if not quoted and index and line[index - 1] in ".!?" and at_end:
|
||||
out.append(line[start : index + 1])
|
||||
start = index + 1
|
||||
elif char in ".!?" and not quoted:
|
||||
while index + 1 < len(line) and line[index + 1] in ".!?":
|
||||
index += 1
|
||||
at_end = index + 1 == len(line) or line[index + 1].isspace()
|
||||
if at_end and not ABBREVIATION.search(line[start : index + 1]):
|
||||
out.append(line[start : index + 1])
|
||||
start = index + 1
|
||||
index += 1
|
||||
out.append(line[start:])
|
||||
return [piece.strip() for piece in out if piece.strip(" .!?\t")]
|
||||
|
||||
|
||||
def clean_who(words):
|
||||
words = IN_THE_CLIP.sub("", words.strip()).strip(" ,.;:")
|
||||
words = re.sub(r"^(?:out\s+)", "", words, flags=re.I)
|
||||
return "" if not words or PRONOUN.match(words) else words
|
||||
|
||||
|
||||
def tidy(words):
|
||||
return re.sub(r"\s+", " ", words).strip(" ,.;:")
|
||||
|
||||
|
||||
class Reader:
|
||||
def __init__(self, jobs):
|
||||
self.jobs = dict(jobs or {})
|
||||
self.swappers = [slot for slot in sorted(self.jobs) if self.jobs[slot] in SWAPPERS]
|
||||
self.explicit = set() # Pictures with an "@N looks like" line, which wins over any other description.
|
||||
self.read = SwapRead()
|
||||
self.last = self.swappers[0] if len(self.swappers) == 1 else None
|
||||
self.bare = [] # Lines that only name someone, for line-order matching.
|
||||
|
||||
# ---- the parts of one sentence
|
||||
|
||||
def name_aliases(self, text):
|
||||
""" "Elon is @1", "@1 is Elon", "Elon (@1)", "with Elon, @1": the name stands for the picture from here on."""
|
||||
for pattern in (
|
||||
rf"(?P<name>{NAME})\s+is\s+@(?P<slot>[1-4])\b",
|
||||
rf"@(?P<slot>[1-4])\s+is\s+(?P<name>{NAME})\b(?!\s+(?:of|on|in)\b)",
|
||||
rf"(?P<name>{NAME})\s*\(\s*@(?P<slot>[1-4])\s*\)",
|
||||
rf"(?<=\bwith\s)(?P<name>{NAME}),\s*@(?P<slot>[1-4])\b",
|
||||
):
|
||||
for match in re.finditer(pattern, text):
|
||||
name = match.group("name")
|
||||
if not re.match(r"(?:The|A|An|This|That|Left|Right)\b", name):
|
||||
self.read.names[name] = int(match.group("slot"))
|
||||
|
||||
def with_names_as_pictures(self, text):
|
||||
for name, slot in self.read.names.items():
|
||||
text = re.sub(rf"{re.escape(name)}\s+is\s+@{slot}\b", f"@{slot}", text)
|
||||
text = re.sub(rf"@{slot}\s+is\s+{re.escape(name)}\b", f"@{slot}", text)
|
||||
text = re.sub(rf"{re.escape(name)}\s*\(\s*@{slot}\s*\)", f"@{slot}", text)
|
||||
text = re.sub(rf"{re.escape(name)},\s*@{slot}\b", f"@{slot}", text)
|
||||
text = re.sub(rf"\b{re.escape(name)}\b(?!\s*[,(]?\s*@)", f"@{slot}", text)
|
||||
return text
|
||||
|
||||
def goes(self, slot, words):
|
||||
words = clean_who(words)
|
||||
if words and slot in self.swappers and slot not in self.read.goes:
|
||||
self.read.goes[slot] = words
|
||||
|
||||
def looks(self, slot, words, explicit=False):
|
||||
words = tidy(words or "")
|
||||
if not words:
|
||||
if explicit:
|
||||
raise ValueError(f"Say what Picture {slot}'s person looks like, or remove its looks like line.")
|
||||
return
|
||||
if explicit:
|
||||
if slot not in self.jobs:
|
||||
raise ValueError(f"Picture {slot} is not connected. Connect the new person's picture or remove its looks like line.")
|
||||
if self.jobs[slot] not in PERSONS:
|
||||
raise ValueError(f"Picture {slot} must be a person or character sheet for a swap's looks like line.")
|
||||
if slot in self.explicit:
|
||||
raise ValueError(f"Describe Picture {slot} once, in one looks like line.")
|
||||
self.explicit.add(slot)
|
||||
self.read.unused.extend(self.read.looks.pop(slot, []))
|
||||
elif slot in self.explicit:
|
||||
self.read.unused.append(words)
|
||||
return
|
||||
if slot in self.swappers and self.jobs.get(slot) in PERSONS:
|
||||
self.read.looks.setdefault(slot, []).append(words)
|
||||
|
||||
def wears(self, slot, words):
|
||||
words = tidy(words)
|
||||
if words and slot in self.swappers and self.jobs.get(slot) in PERSONS:
|
||||
self.read.wears.setdefault(slot, []).append(words)
|
||||
|
||||
def left_of(self, slot, left, verb_before):
|
||||
"""Reads the words before an @. Returns whether they were used."""
|
||||
left = re.sub(r"^\s*(?:,|and\b|;)\s*", "", left).strip()
|
||||
if not left:
|
||||
return True
|
||||
for pattern in LEFT_SIDE + ((SHORT_ASK,) if verb_before else ()):
|
||||
match = pattern.match(left)
|
||||
if match:
|
||||
who = next(group for group in match.groups() if group)
|
||||
if pattern is REPLACED and re.fullmatch(NAME, who.strip()):
|
||||
return True # "Elon is @1" names the new person.
|
||||
self.goes(slot, who)
|
||||
return True
|
||||
return bool(PUTS.match(left))
|
||||
|
||||
def right_of(self, slot, right, verb_before, first=True):
|
||||
"""Reads the words after an @, piece by piece. Returns what is left over."""
|
||||
right = re.sub(r"^\s*\)", "", right)
|
||||
first = first # "@1 the man on the left": a plain who-goes right after an @ that starts its words.
|
||||
while right.strip(" ,.;:"):
|
||||
for pattern, use in (
|
||||
(POSSESSIVE, None),
|
||||
(KEEP_CLOTHES_AT_START, None),
|
||||
(COMMA_LOOKS, "looks"),
|
||||
(IS_NEW, None),
|
||||
(IS_WHO, "goes"),
|
||||
(BRACKET, "bracket"),
|
||||
(GOES_FOR, "goes"),
|
||||
(WEARS, "wear"),
|
||||
(HAS, "looks"),
|
||||
(LOOKS_LIKE, "looks"),
|
||||
(IS_NAME, None),
|
||||
(IS_NEW, None),
|
||||
(ON_SPOT, "spot"),
|
||||
(ARROW, "goes"),
|
||||
(NOUN, "goes"),
|
||||
):
|
||||
if pattern is NOUN and not (verb_before or first):
|
||||
continue
|
||||
match = pattern.match(right)
|
||||
if not match:
|
||||
continue
|
||||
if use == "looks":
|
||||
self.looks(slot, match.group("looks"))
|
||||
elif use == "wear":
|
||||
self.wears(slot, match.group("wear"))
|
||||
elif use == "goes":
|
||||
self.goes(slot, match.group("x"))
|
||||
elif use == "spot":
|
||||
self.goes(slot, f"the person on the {match.group('spot').lower()}")
|
||||
elif use == "bracket":
|
||||
words = match.group("p").strip()
|
||||
if not re.fullmatch(NAME, words):
|
||||
self.looks(slot, words)
|
||||
right = right[match.end() :]
|
||||
first = False
|
||||
break
|
||||
else:
|
||||
return right
|
||||
return ""
|
||||
|
||||
def sentence(self, text):
|
||||
"""Reads one sentence. Returns the words it did not use."""
|
||||
if HAS_QUOTE.search(text):
|
||||
# Spoken words go on to the prompt; only the words before the line are read here.
|
||||
quote = HAS_QUOTE.search(text).start()
|
||||
cuts = [match.start() for match in BOUNDARY.finditer(text[:quote])]
|
||||
text = text[: cuts[-1]] if cuts else ""
|
||||
spoken = True
|
||||
else:
|
||||
spoken = False
|
||||
text = KEEP_CLOTHES.sub("", text).strip()
|
||||
if not text.strip(" .!?"):
|
||||
return []
|
||||
line = LOOKS_LINE.match(text.rstrip(" .!?"))
|
||||
if line:
|
||||
self.looks(int(line.group(1)), line.group("looks"), explicit=True)
|
||||
self.last = int(line.group(1))
|
||||
return []
|
||||
tokens = list(TOKEN.finditer(text))
|
||||
if not tokens:
|
||||
return self.no_picture(text.rstrip(" .!?"), spoken)
|
||||
leftover = []
|
||||
verb_before = False
|
||||
start = 0
|
||||
for index, token in enumerate(tokens):
|
||||
slot = int(token.group(1))
|
||||
self.last = slot
|
||||
end = len(text)
|
||||
if index + 1 < len(tokens):
|
||||
end = self.cut(text[token.end() : tokens[index + 1].start()], verb_before or self.asks(text[start : token.start()]))
|
||||
end += token.end()
|
||||
left = text[start : token.start()]
|
||||
used_left = self.left_of(slot, left, verb_before)
|
||||
verb_before = verb_before or bool(ASKS.match(left.strip()) or re.search(r"\breplaces?\b|\bswap\b", left + text[token.end() : end], re.I))
|
||||
if not used_left:
|
||||
leftover.append(left)
|
||||
right = text[token.end() : end]
|
||||
rest = self.right_of(slot, right, verb_before, first=not left.strip())
|
||||
if rest.strip(" ,.;:!?"):
|
||||
leftover.append(f"@{slot}{rest}" if rest == right and not left.strip() else rest)
|
||||
start = end
|
||||
return [] if spoken else leftover
|
||||
|
||||
@staticmethod
|
||||
def asks(left):
|
||||
return bool(ASKS.match(re.sub(r"^\s*(?:,|and\b)\s*", "", left).strip()))
|
||||
|
||||
@staticmethod
|
||||
def cut(between, verb_before):
|
||||
"""Where the words between two @s stop being about the first one: at the earliest break after which the
|
||||
rest reads as the second one's start, or at the end."""
|
||||
for match in BOUNDARY.finditer(between):
|
||||
after = between[match.end() :].strip()
|
||||
if not after:
|
||||
return match.start()
|
||||
for pattern in LEFT_SIDE + ((SHORT_ASK,) if verb_before else ()):
|
||||
if pattern.match(after):
|
||||
return match.start()
|
||||
return len(between)
|
||||
|
||||
def no_picture(self, text, spoken):
|
||||
"""A sentence with no @: about the one new person ("she has red hair"), only who goes ("the man in the hat"),
|
||||
or something a swap does not use."""
|
||||
who = self.last if self.last in self.swappers else (self.swappers[0] if len(self.swappers) == 1 else None)
|
||||
looks = SAYS_LOOKS.match(text)
|
||||
if looks and who:
|
||||
(self.wears if looks.group("wear") else self.looks)(who, looks.group("looks"))
|
||||
return []
|
||||
goes = SAYS_GOES.match(text)
|
||||
if goes and who:
|
||||
self.goes(who, re.split(r",\s*(?:and|then)\b|\s+and\s+(?:the|then)\b", goes.group("x"))[0])
|
||||
return []
|
||||
if spoken:
|
||||
return []
|
||||
if BARE_WHO.match(text) and not ACTION.search(text) and not re.match(r"^(?:make|add|keep|turn)\b", text, re.I):
|
||||
self.bare.append(text)
|
||||
return []
|
||||
return [text]
|
||||
|
||||
def run(self, text):
|
||||
self.name_aliases(text)
|
||||
text = self.with_names_as_pictures(text)
|
||||
for piece in sentences(text):
|
||||
for words in self.sentence(piece):
|
||||
for part in BOUNDARY.split(words):
|
||||
part = tidy(part)
|
||||
if part and not FILLER.match(part) and re.search(r"[A-Za-z]{3,}", part):
|
||||
self.read.unused.append(part)
|
||||
missing = [slot for slot in self.swappers if slot not in self.read.goes]
|
||||
if self.bare and len(self.bare) == len(missing) or (self.bare and len(missing) == 1):
|
||||
for slot, who in zip(missing, self.bare):
|
||||
self.goes(slot, who)
|
||||
elif self.bare:
|
||||
self.read.unused.extend(self.bare)
|
||||
return self.read
|
||||
|
||||
|
||||
KEEP_CLOTHES_AT_START = re.compile(r"^" + KEEP_CLOTHES.pattern, re.I)
|
||||
|
||||
|
||||
def read_swap(text, jobs):
|
||||
"""What a swap's typed lines say, read once. jobs is {picture number: job}."""
|
||||
return Reader(jobs).run(text)
|
||||
@@ -181,17 +181,17 @@ def same_reading(typed, tidied):
|
||||
return not any(words in [line[2] for line in now] for words in shown) and (cuts, times) == (now_cuts, now_times)
|
||||
|
||||
|
||||
def tidy_line(line, ask):
|
||||
def tidy_line(line, ask, system=TIDY_SYSTEM):
|
||||
"""One typed line tidied by the model, or as typed when its answer breaks a rule."""
|
||||
held, marks, quotes = hold(line)
|
||||
longest = min(800, 64 + 3 * len(held.split()))
|
||||
answer = LABEL.sub("", str(ask(TIDY_SYSTEM, f"Line: {held}\nCleaned:", longest) or "").strip()).strip()
|
||||
answer = LABEL.sub("", str(ask(system, f"Line: {held}\nCleaned:", longest) or "").strip()).strip()
|
||||
if "\n" in answer or not answer_ok(held, answer, marks) or not same_roles(held, answer):
|
||||
return line
|
||||
return put_back(answer, marks, quotes)
|
||||
|
||||
|
||||
def tidy_script(script, ask):
|
||||
def tidy_script(script, ask, system=TIDY_SYSTEM):
|
||||
"""The script tidied by ask(system, user, longest) one line at a time. Returns (script, tidied). Each
|
||||
line's answer is kept only when the whole script still reads the same with it."""
|
||||
if not clean(script):
|
||||
@@ -204,7 +204,7 @@ def tidy_script(script, ask):
|
||||
for index, line in enumerate(lines):
|
||||
if not line.strip() or SETTING_LINE.match(clean(line)):
|
||||
continue
|
||||
tidy = tidy_line(line, ask)
|
||||
tidy = tidy_line(line, ask, system)
|
||||
trial = out[:index] + [tidy] + out[index + 1 :]
|
||||
if tidy != line and same_reading(script, "\n".join(trial)):
|
||||
out = trial
|
||||
|
||||
@@ -574,18 +574,21 @@ def apply_lora_stack(
|
||||
import comfy.sd
|
||||
|
||||
follower = None
|
||||
effective = rows
|
||||
if curve is not None and any(row.get("curve") and row["enabled"] for row in rows):
|
||||
from ._curve_helpers import keyframe_plan
|
||||
|
||||
plan = keyframe_plan(curve)
|
||||
if len(plan) == 1:
|
||||
# A flat curve is a plain strength: nothing to schedule.
|
||||
rows = [{**row, "strength": clamp_strength(row["strength"] * plan[0][1])}
|
||||
if row.get("curve") else row for row in rows]
|
||||
# Scaled copies; ``missing`` still gets the caller's own rows, which
|
||||
# the node matches by identity to keep a skipped row's words out.
|
||||
effective = [{**row, "strength": clamp_strength(row["strength"] * plan[0][1])}
|
||||
if row.get("curve") else row for row in rows]
|
||||
else:
|
||||
follower = LoraCurve(curve)
|
||||
|
||||
for row in rows:
|
||||
for given, row in zip(rows, effective):
|
||||
if not row["enabled"]:
|
||||
continue
|
||||
strength_clip = row["strength_clip"] if clip is not None else 0.0
|
||||
@@ -607,7 +610,7 @@ def apply_lora_stack(
|
||||
)
|
||||
_warn_missing(row["name"], str(exc))
|
||||
if missing is not None:
|
||||
missing.append(row)
|
||||
missing.append(given)
|
||||
continue
|
||||
try:
|
||||
lora_sd = _load_lora_file(path)
|
||||
|
||||
+75
-41
@@ -334,14 +334,10 @@ def _load_alpha_matting():
|
||||
except ImportError as exc:
|
||||
raise RuntimeError(_MATTING_HINT) from exc
|
||||
estimate = getattr(pymatting, "estimate_alpha_cf", None)
|
||||
if estimate is None:
|
||||
fix_trimap = getattr(pymatting, "fix_trimap", None)
|
||||
if estimate is None or fix_trimap is None:
|
||||
raise RuntimeError(_MATTING_HINT)
|
||||
return estimate
|
||||
|
||||
|
||||
def _edge_radius(expand: int) -> int:
|
||||
"""Working radius at the edge, scaled with how far the mask was moved."""
|
||||
return max(4, 2 * abs(int(expand)))
|
||||
return estimate, fix_trimap
|
||||
|
||||
|
||||
def _guide_frames(
|
||||
@@ -372,68 +368,101 @@ def _guide_frames(
|
||||
return frames
|
||||
|
||||
|
||||
def _odd(value: int) -> int:
|
||||
"""Force a positive odd kernel size, the way cv2 and pymatting expect."""
|
||||
value = int(value)
|
||||
if value < 1:
|
||||
value = 1
|
||||
return value if value % 2 else value + 1
|
||||
|
||||
|
||||
def guided_filter_refine(
|
||||
mask: torch.Tensor, guide_image: torch.Tensor, expand: int
|
||||
mask: torch.Tensor, guide_image: torch.Tensor, detail_range: int
|
||||
) -> torch.Tensor:
|
||||
"""Snap soft mask edges to guide-image edges with an edge-aware filter."""
|
||||
"""Snap soft mask edges to guide-image edges with an edge-aware filter.
|
||||
|
||||
A window of detail_range + 1 pixels with a firm eps (0.015) pulls a
|
||||
feathered mask onto the picture's edge; the old tiny eps (1e-4) left the
|
||||
gray ramp in place.
|
||||
"""
|
||||
guided_filter = _load_guided_filter()
|
||||
count, height, width = mask.shape
|
||||
guides = _guide_frames(guide_image, count, height, width)
|
||||
radius = _edge_radius(expand)
|
||||
radius = _odd(detail_range + 1)
|
||||
frames = []
|
||||
for index in range(count):
|
||||
raise_if_interrupted()
|
||||
guide = guides[index].detach().float().clamp(0.0, 1.0).contiguous().cpu().numpy()
|
||||
source = mask[index].detach().float().contiguous().cpu().numpy()
|
||||
frames.append(torch.from_numpy(guided_filter(guide, source, radius, 1e-4)))
|
||||
frames.append(torch.from_numpy(guided_filter(guide, source, radius, 0.015)))
|
||||
return torch.stack(frames).to(device=mask.device, dtype=mask.dtype).clamp(0.0, 1.0)
|
||||
|
||||
|
||||
def matting_refine(
|
||||
mask: torch.Tensor, guide_image: torch.Tensor, expand: int
|
||||
mask: torch.Tensor,
|
||||
guide_image: torch.Tensor,
|
||||
detail_range: int,
|
||||
fix_threshold: float,
|
||||
) -> torch.Tensor:
|
||||
"""Closed-form alpha matting around the mask edge.
|
||||
|
||||
The binarized mask eroded by the edge radius is definite foreground, the
|
||||
dilation marks where definite background begins, and the band between is
|
||||
solved by pymatting's estimate_alpha_cf against the guide image.
|
||||
The mask alpha is blurred with a wide kernel (detail_range*5+1) to open a
|
||||
broad unknown band, fix_trimap carves that band into definite foreground,
|
||||
definite background and unknown, and pymatting's estimate_alpha_cf solves
|
||||
the unknown against the guide image. The wide blur is what lets the solve
|
||||
reach the edge; a narrow morphological band left the result ragged.
|
||||
"""
|
||||
estimate_alpha_cf = _load_alpha_matting()
|
||||
estimate_alpha_cf, fix_trimap = _load_alpha_matting()
|
||||
cv2 = _optional_import("cv2")
|
||||
count, height, width = mask.shape
|
||||
guides = _guide_frames(guide_image, count, height, width)
|
||||
band = _edge_radius(expand)
|
||||
# Morphology once for the whole batch, not per frame: pooling is
|
||||
# per-sample, so the batched call is bit-identical, and rebuilding the
|
||||
# trimap inside the loop was paying the erode/dilate `count` times over.
|
||||
kernel = _odd(detail_range * 5 + 1)
|
||||
alpha_all = mask.detach().float().cpu()
|
||||
solid_all = (alpha_all >= 0.5).float()
|
||||
eroded_all = grow_shrink_mask(solid_all, -band) >= 0.5
|
||||
dilated_all = grow_shrink_mask(solid_all, band) >= 0.5
|
||||
frames = []
|
||||
for index in range(count):
|
||||
raise_if_interrupted()
|
||||
alpha_in = alpha_all[index]
|
||||
# Definite foreground has to be opaque in the mask we were handed, and
|
||||
# anything carrying any alpha at all is at least possible foreground.
|
||||
# On a binary mask those reduce to exactly the eroded and dilated
|
||||
# shapes; on a feathered one the soft ramp widens the unknown band,
|
||||
# which is what lets the blur control reach the solve instead of being
|
||||
# thresholded straight back out of it.
|
||||
sure_fg = eroded_all[index] & (alpha_in >= 1.0 - _SOFT_EPSILON)
|
||||
possible = dilated_all[index] | (alpha_in > _SOFT_EPSILON)
|
||||
unknown = possible & ~sure_fg
|
||||
if not bool(unknown.any()) or not bool(sure_fg.any()) or bool(possible.all()):
|
||||
# Degenerate trimap (empty mask, mask everywhere, or a shape the
|
||||
# band swallows whole): keep this frame's mask as it arrived.
|
||||
# Nothing to solve on an empty or fully solid frame.
|
||||
if not bool((alpha_in > _SOFT_EPSILON).any()) or bool(
|
||||
(alpha_in >= 1.0 - _SOFT_EPSILON).all()
|
||||
):
|
||||
frames.append(alpha_in)
|
||||
continue
|
||||
# Below fix_threshold is definite background, above 0.99 definite
|
||||
# foreground, the rest is solved. The upper bound is fixed: a blurred
|
||||
# alpha never reaches exactly 1, and white_point stays a levels
|
||||
# control rather than also moving the solve. A high fix_threshold
|
||||
# marks the blurred rim as background and shrinks the mask, so the
|
||||
# default is the lowest value.
|
||||
lower = min(max(float(fix_threshold), 0.01), 0.98)
|
||||
upper = 0.99
|
||||
source = alpha_in.numpy().astype("float64")
|
||||
size = kernel
|
||||
while True:
|
||||
blurred = cv2.GaussianBlur(source, (size, size), 0)
|
||||
trimap = fix_trimap(blurred, lower, upper)
|
||||
# A blur wider than the subject never lets its core reach the
|
||||
# upper bound, which leaves no foreground and nothing solved.
|
||||
# Narrow the blur until the subject keeps a solid core.
|
||||
if bool((trimap >= 0.9).any()) or size <= 3:
|
||||
break
|
||||
size = _odd(size // 2)
|
||||
if not (
|
||||
bool((trimap >= 0.9).any())
|
||||
and bool((trimap <= 0.1).any())
|
||||
and bool((trimap == 0.5).any())
|
||||
):
|
||||
# Thresholds left no usable foreground/background/unknown band
|
||||
# (e.g. a soft mask whose core never nears 1); keep the mask as it
|
||||
# arrived instead of letting pymatting raise.
|
||||
frames.append(alpha_in)
|
||||
continue
|
||||
trimap = torch.full((height, width), 0.5, dtype=torch.float64)
|
||||
trimap[~possible] = 0.0
|
||||
trimap[sure_fg] = 1.0
|
||||
guide = (
|
||||
guides[index].detach().float().clamp(0.0, 1.0).contiguous().cpu().numpy().astype("float64")
|
||||
)
|
||||
alpha = estimate_alpha_cf(guide, trimap.numpy())
|
||||
alpha = estimate_alpha_cf(
|
||||
guide, trimap, laplacian_kwargs={"epsilon": 1e-6}, cg_kwargs={"maxiter": 500}
|
||||
)
|
||||
frames.append(torch.from_numpy(alpha).float())
|
||||
return torch.stack(frames).to(device=mask.device, dtype=mask.dtype).clamp(0.0, 1.0)
|
||||
|
||||
@@ -463,11 +492,16 @@ def refine_mask(
|
||||
edge_refine: str = "off",
|
||||
guide_image: torch.Tensor | None = None,
|
||||
max_hole_size: float = 0.0,
|
||||
detail_range: int = 12,
|
||||
fix_threshold: float = 0.01,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
"""Expand, fill holes, smooth, feather, edge-refine, then remap levels.
|
||||
|
||||
max_hole_size limits fill holes to holes up to that percent of the
|
||||
frame's area; 0 (the default) fills every hole, as before it existed.
|
||||
detail_range and fix_threshold tune the edge_refine pass: detail_range sets
|
||||
the guided-filter window and the matting unknown-band width, fix_threshold
|
||||
is the lower trimap threshold for matting (higher trims the mask inward).
|
||||
"""
|
||||
if edge_refine not in EDGE_REFINE_MODES:
|
||||
raise ValueError(
|
||||
@@ -494,9 +528,9 @@ def refine_mask(
|
||||
refined = smooth_mask(refined, int(smooth))
|
||||
refined = blur_mask(refined, blur).clamp(0.0, 1.0)
|
||||
if edge_refine == "guided filter":
|
||||
refined = guided_filter_refine(refined, guide_image, expand)
|
||||
refined = guided_filter_refine(refined, guide_image, detail_range)
|
||||
elif edge_refine == "matting":
|
||||
refined = matting_refine(refined, guide_image, expand)
|
||||
refined = matting_refine(refined, guide_image, detail_range, fix_threshold)
|
||||
refined = remap_mask(refined, black_point, white_point)
|
||||
return refined, 1.0 - refined
|
||||
|
||||
|
||||
@@ -8,7 +8,8 @@ import sys
|
||||
from ._h3_cast_helpers import DESCRIBE_PERSON, add_looks, EDIT, JOBS, KEEP, KEEPS_ITS_LENGTH, PERSON, PLACE, START, SWAP, THING, VIDEO_JOBS
|
||||
from ._h3_prompt_helpers import find_beats, find_speech, split_sections, write_prompt
|
||||
from ._h3_script_helpers import CAMERAS, LOOKS, script_report
|
||||
from ._h3_tidy_helpers import tidy_script
|
||||
from ._h3_model_asks import BUILT_IN as BUILT_IN_ASKS, parse_asks
|
||||
from ._h3_tidy_helpers import TIDY_SYSTEM, tidy_script
|
||||
from ._route_errors import safe_route_error
|
||||
|
||||
|
||||
@@ -90,7 +91,7 @@ def model_tidier(clip):
|
||||
return ask
|
||||
|
||||
|
||||
def tidied(script, clip):
|
||||
def tidied(script, clip, system=None):
|
||||
"""The typed script in plain, ordered sentences, from the model on clip.
|
||||
|
||||
H3's own six parts go through as they are, and so does everything when nothing is on clip:
|
||||
@@ -98,7 +99,7 @@ def tidied(script, clip):
|
||||
if clip is None or not str(script or "").strip() or split_sections(script) is not None:
|
||||
return script
|
||||
ask = model_tidier(clip)
|
||||
return script if ask is None else tidy_script(script, ask)[0]
|
||||
return script if ask is None else tidy_script(script, ask, system or TIDY_SYSTEM)[0]
|
||||
|
||||
|
||||
def fill_picture(pictures, jobs):
|
||||
@@ -342,6 +343,18 @@ class AusBossH3PromptWriter:
|
||||
),
|
||||
},
|
||||
),
|
||||
"model_asks": (
|
||||
"STRING",
|
||||
{
|
||||
"default": "",
|
||||
"multiline": True,
|
||||
"dynamicPrompts": False,
|
||||
"tooltip": (
|
||||
"Your own wording for what the model on clip is asked, set in the gear menu. Empty "
|
||||
"means the built-in wording."
|
||||
),
|
||||
},
|
||||
),
|
||||
},
|
||||
}
|
||||
|
||||
@@ -383,11 +396,12 @@ class AusBossH3PromptWriter:
|
||||
def write(self, script, seconds, clip=None, picture_1=None, picture_2=None, picture_3=None, picture_4=None, video=None,
|
||||
video_sound=None, voice=None, song=None, camera=AS_TYPED, look=FROM_PICTURE, song_start=0.0, cut_on_beat=True,
|
||||
language="English", job_1=PERSON, job_2=PERSON, job_3=PERSON, job_4=THING, video_job=VIDEO_JOBS[0],
|
||||
sound="", music="", clip_sound=False, tidy=False):
|
||||
sound="", music="", clip_sound=False, tidy=False, model_asks=""):
|
||||
inputs = dict(locals())
|
||||
del inputs["self"], inputs["script"], inputs["tidy"]
|
||||
del inputs["self"], inputs["script"], inputs["tidy"], inputs["model_asks"]
|
||||
inputs["asks"] = asks = parse_asks(model_asks)
|
||||
if tidy:
|
||||
tidy_text = tidied(script, clip)
|
||||
tidy_text = tidied(script, clip, asks.get("tidy"))
|
||||
if tidy_text != script:
|
||||
try:
|
||||
return self._write(tidy_text, **inputs)
|
||||
@@ -398,7 +412,8 @@ class AusBossH3PromptWriter:
|
||||
def _write(self, script, seconds, clip=None, picture_1=None, picture_2=None, picture_3=None, picture_4=None, video=None,
|
||||
video_sound=None, voice=None, song=None, camera=AS_TYPED, look=FROM_PICTURE, song_start=0.0, cut_on_beat=True,
|
||||
language="English", job_1=PERSON, job_2=PERSON, job_3=PERSON, job_4=THING, video_job=VIDEO_JOBS[0],
|
||||
sound="", music="", clip_sound=False):
|
||||
sound="", music="", clip_sound=False, asks=None):
|
||||
asks = asks or {}
|
||||
# A clip that keeps its own sound has no room for a score: the finished clip plays the video's sound.
|
||||
if video is not None and (video_job == EDIT or (video_job == SWAP and clip_sound)):
|
||||
music = ""
|
||||
@@ -410,7 +425,7 @@ class AusBossH3PromptWriter:
|
||||
video_job = "" if video is None else video_job
|
||||
if clip is not None and video_job == SWAP:
|
||||
# The model on clip writes each new person's @N looks like line from their picture, when none is typed.
|
||||
script = add_looks(script, jobs, lambda slot: model_asker(clip, given[slot])(DESCRIBE_PERSON, 60))
|
||||
script = add_looks(script, jobs, lambda slot: model_asker(clip, given[slot])(asks.get("describe", DESCRIBE_PERSON), 60))
|
||||
frames = clip_frames(seconds)
|
||||
if video_job in KEEPS_ITS_LENGTH:
|
||||
frames = video_frames(video.shape[0])
|
||||
@@ -446,6 +461,7 @@ class AusBossH3PromptWriter:
|
||||
soundtrack=video_sound is not None,
|
||||
clip_sound=clip_sound,
|
||||
speech=speech,
|
||||
asks=asks,
|
||||
)
|
||||
ordered = [*given.values(), None, None, None, None][: len(PICTURES)]
|
||||
return (text, *ordered, video, video_sound, voice, song, song_under, frames, *clip_shape(video, ordered[0]), keeps_clip_sound)
|
||||
@@ -472,6 +488,11 @@ def _register_routes():
|
||||
return
|
||||
PromptServer.instance._ausboss_h3_writer_routes = True
|
||||
|
||||
@PromptServer.instance.routes.get("/ausboss/h3_writer/asks")
|
||||
async def asks(request):
|
||||
"""The built-in wording of each thing the small model is asked, for the gear menu's editor."""
|
||||
return web.json_response(BUILT_IN_ASKS)
|
||||
|
||||
@PromptServer.instance.routes.post("/ausboss/h3_writer/read")
|
||||
async def read(request):
|
||||
try:
|
||||
|
||||
@@ -22,6 +22,7 @@ from ._fine_edge_helpers import (
|
||||
fine_edge_choices,
|
||||
fine_edges as find_fine_edges,
|
||||
grow_fine,
|
||||
keep_subjects_for,
|
||||
loaded_subject_models,
|
||||
shown_colours,
|
||||
subject_matte,
|
||||
@@ -790,8 +791,9 @@ class AusBossMaskByTouch:
|
||||
"at the outline of the picture's main subject, that outline "
|
||||
"is taken from ComfyUI's background-removal model. The "
|
||||
"cut-out also loses the colour of the old background. Off "
|
||||
"keeps the edge as found. The ? page says where to get the "
|
||||
"model file."
|
||||
"keeps the edge as found. RMBG-3.0, when you have it, keeps "
|
||||
"the softest hair but is bigger and slower. The ? page says "
|
||||
"where to get the model files."
|
||||
),
|
||||
},
|
||||
),
|
||||
@@ -1264,6 +1266,7 @@ class AusBossMaskByTouch:
|
||||
# Each picked thing's own area on the first picture, for the face.
|
||||
things = []
|
||||
self._edge_choice = fine_edges
|
||||
keep_subjects_for(int(image.shape[0]))
|
||||
subject_trouble = None
|
||||
# Per word, which of its matches are picked on the first picture. A
|
||||
# word is in while it has any, in the order the words were picked.
|
||||
|
||||
@@ -15,7 +15,9 @@ class AusBossRefineMask:
|
||||
"without feathering), feather with a gaussian blur, edge-refine "
|
||||
"against the optional guide_image (guided filter or alpha matting), "
|
||||
"then remap levels with black_point/white_point to clear gray haze. "
|
||||
"Returns the refined mask and its inverse."
|
||||
"detail_range and fix_threshold (under More) tune the edge-refine pass. "
|
||||
"Returns the refined mask and its inverse. An output node, so it can run "
|
||||
"on its own to check the mask before anything downstream."
|
||||
)
|
||||
# "refine mask" first: the node shipped under that display name, so the
|
||||
# phrase people already know has to keep finding it. The name itself now
|
||||
@@ -27,6 +29,8 @@ class AusBossRefineMask:
|
||||
"fill holes", "smooth", "levels", "guided filter", "alpha matting",
|
||||
"mask blur", "mask fix", "ausboss",
|
||||
]
|
||||
# An output node, so the node can run on its own.
|
||||
OUTPUT_NODE = True
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
@@ -139,6 +143,30 @@ class AusBossRefineMask:
|
||||
),
|
||||
},
|
||||
),
|
||||
"detail_range": (
|
||||
"INT",
|
||||
{
|
||||
"default": 12,
|
||||
"min": 1,
|
||||
"max": 256,
|
||||
"step": 1,
|
||||
"tooltip": "How far from the mask's edge to look for the real "
|
||||
"edge in the guide picture. Raise it for hair or a loose mask, "
|
||||
"lower it for a small subject. Used only while Edge is on.",
|
||||
},
|
||||
),
|
||||
"fix_threshold": (
|
||||
"FLOAT",
|
||||
{
|
||||
"default": 0.01,
|
||||
"min": 0.01,
|
||||
"max": 0.99,
|
||||
"step": 0.01,
|
||||
"tooltip": "How much of the softened edge matting may rework. "
|
||||
"Low (the default) lets it fix the whole edge; higher trims "
|
||||
"the mask inward. Used only while Edge is matting.",
|
||||
},
|
||||
),
|
||||
},
|
||||
}
|
||||
|
||||
@@ -168,6 +196,8 @@ class AusBossRefineMask:
|
||||
guide_image=None,
|
||||
preview=True,
|
||||
max_hole_size=0.0,
|
||||
detail_range=12,
|
||||
fix_threshold=0.01,
|
||||
):
|
||||
refined, inverted = refine_mask(
|
||||
mask,
|
||||
@@ -180,6 +210,8 @@ class AusBossRefineMask:
|
||||
edge_refine=str(edge_refine),
|
||||
guide_image=guide_image,
|
||||
max_hole_size=float(max_hole_size),
|
||||
detail_range=int(detail_range),
|
||||
fix_threshold=float(fix_threshold),
|
||||
)
|
||||
# The refined mask itself is the preview. Before this the panel showed
|
||||
# whatever fed the mask input, and a segmentation node upstream has no
|
||||
|
||||
+1
-1
@@ -3,7 +3,7 @@ name = "ausboss-nodes"
|
||||
# Manager/registry search matches against this text, so it names the actual
|
||||
# nodes instead of describing the collection abstractly.
|
||||
description = "ComfyUI-AusBoss (AusBoss nodes): image and video nodes: Image and Video Crop + Rotate + Pad, Load Image, Load Image + Pad, Image Folder, Image Resize, Align Image, Image Size, Color Match, Image Compare A/B, Image Toolbox, Realign to Source (experimental), Save Image (PNG, WebP/JXL, captions), Load Video, Load Audio, Save Video, Select Frame, Frame Interpolate, Mask Refine, Mask by Name and Mask by Touch, LaMa Inpaint, Crop For Inpaint, Stitch Inpaint, Tiled Upscale and Tiled Upscale Stitch, FlashVSR Upscale, Edit Lock and Edit Lock Restore, LoRA Loader, Krea 2 Encode and Outpaint Model Patch, Latent Size, Layout Boxes, Seed, Select Every Nth, Split Batch, Merge Batches, Text, Text Lines, Prompt Variations, H3 Prompt Writer, Integer, Float, Math Expression, Show Text, Free Memory, Workflow Note, Workflow Note Tile, Callout, Callout Tile, Workflow Switches, Run Timer, Step Preview, Pause for Shot, and Photo Camera. Examples for Qwen Image 2.1, Krea 2, Klein 9B and LTX 2.3."
|
||||
version = "2.29.0"
|
||||
version = "2.30.0"
|
||||
# comfy-cli serializes this to JSON verbatim, so `file` publishes the literal
|
||||
# string {"file": "LICENSE"} to the registry listing. `text` puts a readable
|
||||
# name there instead. Both forms are supported; the LICENSE file is unchanged.
|
||||
|
||||
@@ -0,0 +1,501 @@
|
||||
// h3_sockets_check.mjs <port> [--vue]
|
||||
//
|
||||
// H3 Prompt Writer draws only the sockets in use. This puts the node on a
|
||||
// real canvas and reads what is on the screen: which socket rows are drawn,
|
||||
// what a run would send, and what a save would write. It fails when a row
|
||||
// shows or hides against the rule (js/shared/h3_sockets.mjs), when a wire
|
||||
// would be sent from the wrong output, or when the saved node changes.
|
||||
//
|
||||
// <port> the debugging port of a headless Chrome (docs/live_testing.md)
|
||||
// --vue Nodes 2.0 instead of the classic renderer
|
||||
//
|
||||
// COMFY_URL points at the ComfyUI to test (default http://127.0.0.1:8188/).
|
||||
// H3_LIVE_WORKFLOWS, a list of workflow files split by the path delimiter,
|
||||
// adds a check that every wired output of the node in them still shows.
|
||||
import { readFileSync } from "node:fs";
|
||||
import { delimiter } from "node:path";
|
||||
import { INPUT_NAMES, OUTPUT_NAMES, socketsToShow } from "../../js/shared/h3_sockets.mjs";
|
||||
|
||||
const args = process.argv.slice(2);
|
||||
const port = args.find((arg) => !arg.startsWith("--"));
|
||||
const vue = args.includes("--vue");
|
||||
if (!port) { console.error("usage: h3_sockets_check.mjs <port> [--vue]"); process.exit(2); }
|
||||
|
||||
const NODE = "AUSBOSS_NODES_H3PromptWriter";
|
||||
const COMFY = new URL(process.env.COMFY_URL || "http://127.0.0.1:8188/").href;
|
||||
const page = await (await fetch(`http://127.0.0.1:${port}/json/new?about:blank`, { method: "PUT" })).json();
|
||||
const ws = new WebSocket(page.webSocketDebuggerUrl);
|
||||
await new Promise((resolve) => (ws.onopen = resolve));
|
||||
let id = 0;
|
||||
const pending = new Map();
|
||||
const thrown = [];
|
||||
ws.onmessage = (message) => {
|
||||
const data = JSON.parse(message.data);
|
||||
if (data.id && pending.has(data.id)) { pending.get(data.id)(data); pending.delete(data.id); return; }
|
||||
if (data.method === "Page.javascriptDialogOpening") ws.send(JSON.stringify({ id: ++id, method: "Page.handleJavaScriptDialog", params: { accept: true } }));
|
||||
else if (data.method === "Runtime.exceptionThrown") {
|
||||
const details = data.params.exceptionDetails;
|
||||
const text = String(details.exception?.description ?? details.text ?? "");
|
||||
if (/ausboss|h3_sockets/i.test(`${text} ${details.url ?? ""}`)) thrown.push(text.slice(0, 400));
|
||||
}
|
||||
};
|
||||
const send = (method, params = {}) => new Promise((resolve, reject) => {
|
||||
const call = ++id;
|
||||
pending.set(call, resolve);
|
||||
ws.send(JSON.stringify({ id: call, method, params }));
|
||||
const timer = setTimeout(() => { if (pending.has(call)) { pending.delete(call); reject(new Error(`CDP timeout: ${method}`)); } }, 25000);
|
||||
timer.unref?.();
|
||||
});
|
||||
const evalJs = async (expression) => {
|
||||
const reply = await send("Runtime.evaluate", { expression, awaitPromise: true, returnByValue: true });
|
||||
if (reply.result?.exceptionDetails) throw new Error(JSON.stringify(reply.result.exceptionDetails.exception?.description ?? reply.result.exceptionDetails));
|
||||
return reply.result?.result?.value;
|
||||
};
|
||||
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
|
||||
await send("Page.enable"); await send("Runtime.enable");
|
||||
await send("Emulation.setDeviceMetricsOverride", { width: 1800, height: 1100, deviceScaleFactor: 1, mobile: false });
|
||||
await send("Network.enable"); await send("Network.setCacheDisabled", { cacheDisabled: true });
|
||||
await send("Page.navigate", { url: COMFY });
|
||||
let ready = false;
|
||||
for (let i = 0; i < 240 && !ready; i++) { await sleep(500); ready = await evalJs("Boolean(window.app?.graph && window.app?.canvas && window.LiteGraph?.registered_node_types)").catch(() => false); }
|
||||
if (!ready) { console.error(`ComfyUI did not come up at ${COMFY}`); ws.close(); process.exit(2); }
|
||||
await sleep(2500);
|
||||
|
||||
const setLook = async (on) => { await evalJs(`(async () => { await window.app.extensionManager.setting.set("Comfy.VueNodes.Enabled", ${on}); return true; })()`); await sleep(on ? 1500 : 500); };
|
||||
const lookBefore = await evalJs(`window.app.extensionManager.setting.get("Comfy.VueNodes.Enabled")`);
|
||||
await setLook(vue);
|
||||
|
||||
// Helpers that live in the page for the whole run.
|
||||
await evalJs(`(() => {
|
||||
const { app } = window;
|
||||
const LG = window.LiteGraph;
|
||||
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
const vueOn = () => Boolean(app.extensionManager.setting.get("Comfy.VueNodes.Enabled"));
|
||||
const everyNode = () => { const all = []; const walk = (graph) => { for (const node of graph._nodes) { all.push(node); if (node.subgraph) walk(node.subgraph); } }; walk(app.graph); return all; };
|
||||
const writers = () => everyNode().filter((node) => node.type === ${JSON.stringify(NODE)});
|
||||
const sockets = (node) => ({
|
||||
inputs: node.inputs.map((slot, index) => ({ slot, index })).filter(({ slot }) => !slot.widget),
|
||||
outputs: node.outputs.map((slot, index) => ({ slot, index })),
|
||||
});
|
||||
// Which sockets are on the screen. Classic: the socket's dot is inside the
|
||||
// node. Nodes 2.0: the socket's row has a height.
|
||||
const shown = (node) => {
|
||||
const { inputs, outputs } = sockets(node);
|
||||
const problems = [];
|
||||
if (vueOn()) {
|
||||
const row = (side, index) => document.querySelector('[data-slot-key="' + node.id + '-' + side + '-' + index + '"]')?.closest(".lg-slot");
|
||||
const tall = (side) => ({ slot, index }) => { const element = row(side, index); if (!element) problems.push("no row for " + side + " " + slot.name); return Boolean(element && element.getBoundingClientRect().height > 0); };
|
||||
const seenIn = inputs.filter(tall("in")), seenOut = outputs.filter(tall("out"));
|
||||
// A wire ends where the frontend last measured the socket: that must
|
||||
// be the dot on the screen now.
|
||||
const rect = app.canvas.canvas.getBoundingClientRect(); const ds = app.canvas.ds;
|
||||
for (const [side, list, at] of [["in", seenIn, (i) => node.getInputPos(i)], ["out", seenOut, (i) => node.getOutputPos(i)]]) {
|
||||
for (const { slot, index } of list) {
|
||||
const dot = document.querySelector('[data-slot-key="' + node.id + '-' + side + '-' + index + '"]').getBoundingClientRect();
|
||||
const y = (dot.top + dot.height / 2 - rect.top) / ds.scale - ds.offset[1];
|
||||
const off = Math.round(at(index)[1] - y);
|
||||
if (Math.abs(off) > 2) problems.push("a wire on " + (side === "in" ? "input " : "output ") + slot.name + " ends " + Math.abs(off) + " px " + (off > 0 ? "under" : "over") + " its dot");
|
||||
}
|
||||
}
|
||||
return { inputs: seenIn.map(({ slot }) => slot.name), outputs: seenOut.map(({ slot }) => slot.name), problems };
|
||||
}
|
||||
const [x, y] = node.pos; const [w, h] = node.size;
|
||||
const inside = (pos) => pos[0] >= x - 2 && pos[0] <= x + w + 2 && pos[1] >= y && pos[1] <= y + h;
|
||||
const seenIn = inputs.filter(({ index }) => inside(node.getInputPos(index)));
|
||||
const seenOut = outputs.filter(({ index }) => inside(node.getOutputPos(index)));
|
||||
// Shown rows are stacked with no blank row between them.
|
||||
for (const [side, list, at] of [["input", seenIn, (i) => node.getInputPos(i)], ["output", seenOut, (i) => node.getOutputPos(i)]]) {
|
||||
list.forEach(({ slot, index }, order) => {
|
||||
const expected = y + (order + 0.7) * LG.NODE_SLOT_HEIGHT;
|
||||
if (Math.abs(at(index)[1] - expected) > 1) problems.push(side + " " + slot.name + " is at row y " + Math.round(at(index)[1] - y) + ", expected " + Math.round(expected - y));
|
||||
});
|
||||
}
|
||||
return { inputs: seenIn.map(({ slot }) => slot.name), outputs: seenOut.map(({ slot }) => slot.name), problems };
|
||||
};
|
||||
const wired = (node) => ({
|
||||
inputs: node.inputs.filter((slot) => !slot.widget && slot.link != null).map((slot) => slot.name),
|
||||
outputs: node.outputs.filter((slot) => (slot.links?.length ?? 0) > 0).map((slot) => slot.name),
|
||||
});
|
||||
const read = async (node, ms = 500) => { await wait(ms); app.canvas.setDirty(true, true); await wait(80); return { id: node.id, size: [...node.size], shown: shown(node), wired: wired(node) }; };
|
||||
const fresh = async () => {
|
||||
app.canvas.linkConnector?.reset?.();
|
||||
const next = app.graph.last_node_id + 50;
|
||||
app.graph.clear(); app.graph.last_node_id = next;
|
||||
const node = LG.createNode(${JSON.stringify(NODE)});
|
||||
node.pos = [0, 0]; app.graph.add(node);
|
||||
app.canvas.ds.scale = 1; app.canvas.ds.offset = [520, 160];
|
||||
window.__h3.node = node;
|
||||
return node;
|
||||
};
|
||||
const add = (type, x, y) => { const node = LG.createNode(type); node.pos = [x, y]; app.graph.add(node); return node; };
|
||||
const input = (node, name) => node.inputs.findIndex((slot) => slot.name === name);
|
||||
const output = (node, name) => node.outputs.findIndex((slot) => slot.name === name);
|
||||
window.__h3 = { wait, vueOn, everyNode, writers, shown, wired, read, fresh, add, input, output, node: null, sources: {} };
|
||||
return true;
|
||||
})()`);
|
||||
|
||||
let failed = 0;
|
||||
const sorted = (names) => [...names].sort();
|
||||
const same = (a, b) => JSON.stringify(sorted(a)) === JSON.stringify(sorted(b));
|
||||
const pass = (name) => console.log(`ok ${name}`);
|
||||
const fail = (name, why) => { failed += 1; console.log(`FAIL ${name}: ${why}`); };
|
||||
const skip = (name, why) => console.log(`skip ${name}: ${why}`);
|
||||
// The screen against the rule, for a state read in the page.
|
||||
const againstRule = (state) => {
|
||||
const rule = socketsToShow({ wiredInputs: state.wired.inputs, wiredOutputs: state.wired.outputs });
|
||||
const problems = [...state.shown.problems];
|
||||
if (!same(state.shown.inputs, rule.inputs)) problems.push(`inputs shown ${sorted(state.shown.inputs).join(", ")}; the rule says ${sorted(rule.inputs).join(", ")}`);
|
||||
if (!same(state.shown.outputs, rule.outputs)) problems.push(`outputs shown ${sorted(state.shown.outputs).join(", ")}; the rule says ${sorted(rule.outputs).join(", ")}`);
|
||||
return problems;
|
||||
};
|
||||
const check = async (name, run) => {
|
||||
try {
|
||||
const problems = (await run()) ?? [];
|
||||
if (problems === "skip") return;
|
||||
if (problems.length) fail(name, problems.join(" | ")); else pass(name);
|
||||
} catch (error) { fail(name, String(error.message ?? error).slice(0, 400)); }
|
||||
};
|
||||
const WIRE = `(async () => {
|
||||
const h = window.__h3; const node = h.node;
|
||||
const one = h.add("LoadImage", -420, -60), two = h.add("LoadImage", -420, 320), clip = h.add("LoadImage", -420, 700);
|
||||
one.connect(0, node, h.input(node, "picture_1"));
|
||||
two.connect(0, node, h.input(node, "picture_2"));
|
||||
clip.connect(0, node, h.input(node, "video"));
|
||||
const text = h.add("PreviewAny", 480, 0), picture = h.add("PreviewImage", 480, 160), count = h.add("PreviewAny", 480, 460);
|
||||
node.connect(h.output(node, "prompt"), text, 0);
|
||||
node.connect(h.output(node, "picture_2"), picture, 0);
|
||||
node.connect(h.output(node, "frames"), count, 0);
|
||||
h.sources = { two: two.id, picture: picture.id, text: text.id, count: count.id };
|
||||
return h.read(node);
|
||||
})()`;
|
||||
|
||||
await check("fresh", async () => {
|
||||
const state = await evalJs(`(async () => window.__h3.read(await window.__h3.fresh(), 900))()`);
|
||||
const problems = againstRule(state);
|
||||
if (!same(state.shown.inputs, ["clip", "picture_1", "video", "voice", "song"])) problems.push(`a fresh node shows inputs ${state.shown.inputs.join(", ")}`);
|
||||
if (!same(state.shown.outputs, ["prompt", "frames", "width", "height"])) problems.push(`a fresh node shows outputs ${state.shown.outputs.join(", ")}`);
|
||||
return problems;
|
||||
});
|
||||
|
||||
await check("wire", async () => {
|
||||
const state = await evalJs(WIRE);
|
||||
const problems = againstRule(state);
|
||||
const sent = await evalJs(`(async () => {
|
||||
const h = window.__h3; const prompt = (await window.app.graphToPrompt()).output;
|
||||
const from = (id) => Object.values(prompt[id].inputs).find((value) => Array.isArray(value) && String(value[0]) === String(h.node.id))?.[1];
|
||||
return { text: from(h.sources.text), picture: from(h.sources.picture), count: from(h.sources.count) };
|
||||
})()`);
|
||||
if (sent.text !== 0 || sent.picture !== 2 || sent.count !== 10) problems.push(`a run would read outputs ${JSON.stringify(sent)}; expected prompt 0, picture_2 2, frames 10`);
|
||||
return problems;
|
||||
});
|
||||
|
||||
await check("saved file", async () => {
|
||||
const saved = await evalJs(`(() => {
|
||||
const saved = window.__h3.node.serialize();
|
||||
return { inputs: saved.inputs.map((slot) => slot.name), outputs: saved.outputs.map((slot) => slot.name), placed: [...saved.inputs, ...saved.outputs].filter((slot) => !slot.widget && slot.pos).map((slot) => slot.name), keys: Object.keys(saved.properties ?? {}) };
|
||||
})()`);
|
||||
const problems = [];
|
||||
if (!same(saved.inputs.filter((name) => INPUT_NAMES.includes(name)), INPUT_NAMES)) problems.push(`the saved node lists inputs ${saved.inputs.join(", ")}`);
|
||||
if (JSON.stringify(saved.outputs) !== JSON.stringify(OUTPUT_NAMES)) problems.push(`the saved node lists outputs ${saved.outputs.join(", ")}`);
|
||||
if (saved.placed.length) problems.push(`the saved node carries a position for ${saved.placed.join(", ")}`);
|
||||
if (saved.keys.some((key) => /socket/i.test(key))) problems.push(`the saved node carries a new property: ${saved.keys.join(", ")}`);
|
||||
return problems;
|
||||
});
|
||||
|
||||
await check("unwire", async () => {
|
||||
const state = await evalJs(`(async () => {
|
||||
const h = window.__h3; const node = h.node;
|
||||
node.disconnectOutput(h.output(node, "picture_2"));
|
||||
node.disconnectInput(h.input(node, "picture_2"));
|
||||
return h.read(node);
|
||||
})()`);
|
||||
const problems = againstRule(state);
|
||||
if (state.shown.inputs.includes("picture_3")) problems.push("picture_3 still shows after picture_2 lost its wire");
|
||||
if (state.shown.outputs.includes("picture_2")) problems.push("the picture_2 output still shows after its picture lost its wire");
|
||||
return problems;
|
||||
});
|
||||
|
||||
await check("undo", async () => {
|
||||
const result = await evalJs(`(async () => {
|
||||
const h = window.__h3; const node = await h.fresh(); await h.wait(400);
|
||||
const tracker = window.app.extensionManager.workflow?.activeWorkflow?.changeTracker;
|
||||
const commands = window.app.extensionManager.command;
|
||||
if (!tracker?.checkState || !commands?.execute) return { skip: "this frontend gives no handle on undo" };
|
||||
tracker.checkState();
|
||||
const source = h.add("LoadImage", -420, 0);
|
||||
source.connect(0, node, h.input(node, "picture_1"));
|
||||
tracker.checkState();
|
||||
const after = await h.read(h.writers()[0]);
|
||||
await commands.execute("Comfy.Undo");
|
||||
await h.wait(700);
|
||||
const writer = h.writers()[0];
|
||||
if (!writer) return { skip: "undo removed the node itself" };
|
||||
h.node = writer;
|
||||
return { after, undone: await h.read(writer) };
|
||||
})()`);
|
||||
if (result.skip) { skip("undo", result.skip); return "skip"; }
|
||||
const problems = [...againstRule(result.after).map((p) => `after wiring: ${p}`), ...againstRule(result.undone).map((p) => `after undo: ${p}`)];
|
||||
if (!result.after.shown.inputs.includes("picture_2")) problems.push("picture_2 did not appear with picture_1 wired");
|
||||
if (result.undone.wired.inputs.length === 0 && result.undone.shown.inputs.includes("picture_2")) problems.push("picture_2 still shows after the wire was undone");
|
||||
return problems;
|
||||
});
|
||||
|
||||
await check("switch look", async () => {
|
||||
await evalJs(`(async () => { await window.__h3.fresh(); return true; })()`);
|
||||
await evalJs(WIRE);
|
||||
await setLook(!vue);
|
||||
const other = await evalJs(`window.__h3.read(window.__h3.node, 900)`);
|
||||
await setLook(vue);
|
||||
const back = await evalJs(`window.__h3.read(window.__h3.node, 900)`);
|
||||
return [...againstRule(other).map((p) => `in the other look: ${p}`), ...againstRule(back).map((p) => `back in this look: ${p}`)];
|
||||
});
|
||||
|
||||
await check("paste and delete", async () => {
|
||||
const result = await evalJs(`(async () => {
|
||||
const h = window.__h3; const { app } = window; const original = h.node;
|
||||
const before = new Set(h.writers().map((node) => node.id));
|
||||
// A node the person made taller: its copy keeps that height.
|
||||
original.setSize([original.size[0], original.size[1] + 150]);
|
||||
await h.wait(300);
|
||||
app.canvas.selectItems?.([original]) ?? app.canvas.selectNode?.(original);
|
||||
app.canvas.copyToClipboard(); app.canvas.pasteFromClipboard();
|
||||
await h.wait(700);
|
||||
const copy = h.writers().find((node) => !before.has(node.id));
|
||||
if (!copy) return { skip: "this frontend did not paste from a script" };
|
||||
const states = { copy: await h.read(copy), original: await h.read(original, 100) };
|
||||
const originalId = original.id;
|
||||
app.graph.remove(original);
|
||||
await h.wait(400);
|
||||
h.node = copy;
|
||||
return { ...states, rule: document.getElementById("ausboss-h3-sockets")?.textContent ?? "", originalId, afterDelete: await h.read(copy, 100) };
|
||||
})()`);
|
||||
if (result.skip) { skip("paste and delete", result.skip); return "skip"; }
|
||||
const problems = [...againstRule(result.copy).map((p) => `the copy: ${p}`), ...againstRule(result.original).map((p) => `the original: ${p}`), ...againstRule(result.afterDelete).map((p) => `the copy after the delete: ${p}`)];
|
||||
if (result.rule.includes(`"${result.originalId}-in-`) || result.rule.includes(`"${result.originalId}-out-`)) problems.push("the deleted node's style rule is still on the page");
|
||||
const rows = (state) => Math.max(state.shown.inputs.length, state.shown.outputs.length);
|
||||
const least = result.original.size[1] - Math.max(0, rows(result.original) - rows(result.copy)) * 20 - 2;
|
||||
if (result.copy.size[1] < least) problems.push(`the copy is ${Math.round(result.copy.size[1])} px tall; the original is ${Math.round(result.original.size[1])} with ${rows(result.original)} rows against the copy's ${rows(result.copy)}, so at least ${Math.round(least)}`);
|
||||
return problems;
|
||||
});
|
||||
|
||||
await check("collapse", async () => {
|
||||
await evalJs(`(async () => { await window.__h3.fresh(); return true; })()`);
|
||||
const before = await evalJs(WIRE);
|
||||
const after = await evalJs(`(async () => {
|
||||
const h = window.__h3; const node = h.node;
|
||||
node.collapse(); await h.wait(400); node.collapse();
|
||||
return h.read(node, 700);
|
||||
})()`);
|
||||
const problems = againstRule(after);
|
||||
if (!same(before.wired.inputs, after.wired.inputs) || !same(before.wired.outputs, after.wired.outputs)) problems.push("a wire was lost by collapsing the node");
|
||||
return problems;
|
||||
});
|
||||
|
||||
await check("floor", async () => {
|
||||
const sizes = await evalJs(`(async () => {
|
||||
const h = window.__h3; const measure = (node) => {
|
||||
const panel = node.widgets?.find((widget) => widget.element)?.element;
|
||||
const scale = window.app.canvas.ds.scale || 1;
|
||||
return { height: node.size[1], least: node.computeSize()[1], panel: panel ? panel.getBoundingClientRect().height / scale : null, panelLeast: panel ? parseFloat(getComputedStyle(panel).minHeight) || 0 : null };
|
||||
};
|
||||
const wired = measure(h.node);
|
||||
const node = await h.fresh(); await h.wait(900);
|
||||
return { wired, fresh: measure(node), vue: h.vueOn() };
|
||||
})()`);
|
||||
const problems = [];
|
||||
for (const [name, size] of [["wired", sizes.wired], ["fresh", sizes.fresh]]) {
|
||||
if (!sizes.vue && size.height + 0.5 < size.least) problems.push(`the ${name} node is ${Math.round(size.height)} px tall, under its ${Math.round(size.least)} px least`);
|
||||
if (size.panel != null && size.panel + 0.5 < size.panelLeast) problems.push(`the ${name} node's panel is ${Math.round(size.panel)} px tall, under its ${Math.round(size.panelLeast)} px least`);
|
||||
}
|
||||
return problems;
|
||||
});
|
||||
|
||||
// A real mouse drag, as a person makes it.
|
||||
const mouse = (type, x, y, extra = {}) => send("Input.dispatchMouseEvent", { type, x, y, button: "left", buttons: type === "mouseReleased" ? 0 : 1, pointerType: "mouse", ...extra });
|
||||
const drag = async (from, to) => {
|
||||
await mouse("mouseMoved", from.x, from.y, { buttons: 0 }); await sleep(80);
|
||||
await mouse("mousePressed", from.x, from.y, { clickCount: 1 }); await sleep(120);
|
||||
for (let step = 1; step <= 12; step++) { await mouse("mouseMoved", from.x + ((to.x - from.x) * step) / 12, from.y + ((to.y - from.y) * step) / 12); await sleep(25); }
|
||||
await sleep(150);
|
||||
await mouse("mouseReleased", to.x, to.y, { clickCount: 1 }); await sleep(500);
|
||||
};
|
||||
// Where a person would grab an audio source's output, and a blank spot of
|
||||
// the writer's body between its socket names.
|
||||
const DRAG_POINTS = `(async () => {
|
||||
const h = window.__h3; const { app } = window; const node = h.node;
|
||||
const source = h.add("LoadAudio", -420, 40 + 260 * (h.audioSources = (h.audioSources ?? 0) + 1));
|
||||
await h.wait(700); app.canvas.setDirty(true, true); await h.wait(100);
|
||||
const rect = app.canvas.canvas.getBoundingClientRect(); const ds = app.canvas.ds;
|
||||
const client = (pos) => ({ x: rect.left + (pos[0] + ds.offset[0]) * ds.scale, y: rect.top + (pos[1] + ds.offset[1]) * ds.scale });
|
||||
const dot = document.querySelector('[data-slot-key="' + source.id + '-out-0"]')?.getBoundingClientRect();
|
||||
const from = h.vueOn() && dot ? { x: dot.left + dot.width / 2, y: dot.top + dot.height / 2 } : client(source.getOutputPos(0));
|
||||
const to = client([node.pos[0] + node.size[0] / 2, node.pos[1] + 30]);
|
||||
return { from, to };
|
||||
})()`;
|
||||
|
||||
await check("body drop", async () => {
|
||||
await evalJs(`(async () => { await window.__h3.fresh(); await window.__h3.wait(600); return true; })()`);
|
||||
const problems = [];
|
||||
await drag(...Object.values(await evalJs(DRAG_POINTS)));
|
||||
const first = await evalJs(`window.__h3.read(window.__h3.node)`);
|
||||
if (!same(first.wired.inputs, ["voice"])) problems.push(`the first audio wire dropped on the node is on ${first.wired.inputs.join(", ") || "nothing"}; expected voice`);
|
||||
problems.push(...againstRule(first).map((p) => `after the first drop: ${p}`));
|
||||
await drag(...Object.values(await evalJs(DRAG_POINTS)));
|
||||
const second = await evalJs(`window.__h3.read(window.__h3.node)`);
|
||||
if (!same(second.wired.inputs, ["voice", "song"])) problems.push(`after a second audio wire the node has ${second.wired.inputs.join(", ") || "nothing"} wired; expected voice and song`);
|
||||
// A script that wires a hidden socket on purpose is left alone.
|
||||
const scripted = await evalJs(`(async () => {
|
||||
const h = window.__h3; const node = await h.fresh(); await h.wait(400);
|
||||
const source = h.add("LoadAudio", -420, 0);
|
||||
source.connect(0, node, h.input(node, "video_sound"));
|
||||
return h.read(node);
|
||||
})()`);
|
||||
if (!same(scripted.wired.inputs, ["video_sound"])) problems.push(`a scripted wire to video_sound ended on ${scripted.wired.inputs.join(", ") || "nothing"}`);
|
||||
if (!scripted.shown.inputs.includes("video_sound")) problems.push("video_sound has a wire and does not show");
|
||||
problems.push(...againstRule(scripted).map((p) => `after the scripted wire: ${p}`));
|
||||
return problems;
|
||||
});
|
||||
|
||||
// A wire pulled from another node's input and dropped on the writer takes a
|
||||
// shown output, never one nobody can see.
|
||||
await check("body drop, backwards", async () => {
|
||||
const points = await evalJs(`(async () => {
|
||||
const h = window.__h3; const { app } = window; const node = await h.fresh();
|
||||
const source = h.add("LoadAudio", -420, 40);
|
||||
source.connect(0, node, h.input(node, "voice"));
|
||||
const player = h.add("PreviewAudio", 520, 300);
|
||||
h.player = player.id;
|
||||
await h.wait(900); app.canvas.setDirty(true, true); await h.wait(100);
|
||||
const rect = app.canvas.canvas.getBoundingClientRect(); const ds = app.canvas.ds;
|
||||
const client = (pos) => ({ x: rect.left + (pos[0] + ds.offset[0]) * ds.scale, y: rect.top + (pos[1] + ds.offset[1]) * ds.scale });
|
||||
const dot = document.querySelector('[data-slot-key="' + player.id + '-in-0"]')?.getBoundingClientRect();
|
||||
const from = h.vueOn() && dot ? { x: dot.left + dot.width / 2, y: dot.top + dot.height / 2 } : client(player.getInputPos(0));
|
||||
const to = client([node.pos[0] + node.size[0] / 2, node.pos[1] + 30]);
|
||||
return { from, to };
|
||||
})()`);
|
||||
await drag(points.from, points.to);
|
||||
const state = await evalJs(`window.__h3.read(window.__h3.node)`);
|
||||
const problems = [];
|
||||
if (!same(state.wired.outputs, ["voice"])) problems.push(`an audio wire pulled from a player and dropped on the node is on output ${state.wired.outputs.join(", ") || "nothing"}; expected voice`);
|
||||
problems.push(...againstRule(state));
|
||||
return problems;
|
||||
});
|
||||
|
||||
await check("setting", async () => {
|
||||
const SETTING = "AusBoss.H3PromptWriter.ShowEverySocket";
|
||||
const result = await evalJs(`(async () => {
|
||||
const h = window.__h3; const settings = window.app.extensionManager.setting;
|
||||
const node = await h.fresh(); await h.wait(500);
|
||||
const before = JSON.stringify(node.serialize());
|
||||
await settings.set(${JSON.stringify(SETTING)}, true);
|
||||
const all = await h.read(node, 900);
|
||||
const during = JSON.stringify(node.serialize());
|
||||
await settings.set(${JSON.stringify(SETTING)}, false);
|
||||
const back = await h.read(node, 900);
|
||||
const sizeKept = (text) => text.replace(/"size":\\[[^\\]]*\\]/, "");
|
||||
return { known: settings.get(${JSON.stringify(SETTING)}) === false, all, back, sameFile: sizeKept(before) === sizeKept(during) };
|
||||
})()`);
|
||||
const problems = [];
|
||||
if (!result.known) problems.push("the setting is not registered");
|
||||
if (!same(result.all.shown.inputs, INPUT_NAMES)) problems.push(`with the setting on the inputs shown are ${result.all.shown.inputs.join(", ")}`);
|
||||
if (!same(result.all.shown.outputs, OUTPUT_NAMES)) problems.push(`with the setting on the outputs shown are ${result.all.shown.outputs.join(", ")}`);
|
||||
problems.push(...result.all.shown.problems, ...againstRule(result.back).map((p) => `with the setting off again: ${p}`));
|
||||
if (!result.sameFile) problems.push("the saved node differs with the setting on");
|
||||
return problems;
|
||||
});
|
||||
|
||||
// The row of picture chips under "Pictures and settings": a chip only for a
|
||||
// picture or a video that is plugged in.
|
||||
await check("chips", async () => {
|
||||
const SETTING = "AusBoss.H3PromptWriter.ShowEverySocket";
|
||||
const result = await evalJs(`(async () => {
|
||||
const h = window.__h3; const settings = window.app.extensionManager.setting;
|
||||
const chips = async (node, ms = 1400) => {
|
||||
await h.wait(ms);
|
||||
const row = node.__ausbossCard?.root?.querySelector(".ausboss-chips");
|
||||
const list = [...(row?.querySelectorAll(".ausboss-chip") ?? [])];
|
||||
return {
|
||||
row: Boolean(row),
|
||||
height: Math.round(row?.getBoundingClientRect().height ?? 0),
|
||||
on: list.filter((chip) => !chip.classList.contains("off")).map((chip) => chip.querySelector("b")?.textContent ?? ""),
|
||||
off: list.filter((chip) => chip.classList.contains("off")).map((chip) => chip.textContent.trim()),
|
||||
};
|
||||
};
|
||||
const node = await h.fresh();
|
||||
const empty = await chips(node);
|
||||
const one = h.add("LoadImage", -420, -60), two = h.add("LoadImage", -420, 320), clip = h.add("LoadImage", -420, 700);
|
||||
one.connect(0, node, h.input(node, "picture_1"));
|
||||
const first = await chips(node);
|
||||
two.connect(0, node, h.input(node, "picture_2"));
|
||||
clip.connect(0, node, h.input(node, "video"));
|
||||
const three = await chips(node);
|
||||
two.mode = 4;
|
||||
const off = await chips(node);
|
||||
two.mode = 0;
|
||||
node.disconnectInput(h.input(node, "picture_2"));
|
||||
node.disconnectInput(h.input(node, "video"));
|
||||
node.disconnectInput(h.input(node, "picture_1"));
|
||||
const gone = await chips(node);
|
||||
await settings.set(${JSON.stringify(SETTING)}, true);
|
||||
const all = await chips(node);
|
||||
await settings.set(${JSON.stringify(SETTING)}, false);
|
||||
const back = await chips(node);
|
||||
return { empty, first, three, off, gone, all, back };
|
||||
})()`);
|
||||
const problems = [];
|
||||
const said = (state) => `${state.on.join(", ") || "no chip"}${state.off.length ? ` and faint ${state.off.join(", ")}` : ""}${state.height ? "" : " (row not on the screen)"}`;
|
||||
const expectChips = (label, state, on, off, rowShown) => {
|
||||
if (!state.row) { problems.push(`${label}: the card has no chip row`); return; }
|
||||
if (JSON.stringify(state.on) !== JSON.stringify(on) || JSON.stringify(state.off) !== JSON.stringify(off)) problems.push(`${label}: shows ${said(state)}; expected ${on.join(", ") || "no chip"}${off.length ? ` and faint ${off.join(", ")}` : ""}`);
|
||||
if (Boolean(state.height) !== rowShown) problems.push(`${label}: the chip row is ${state.height ? "on the screen" : "not on the screen"}`);
|
||||
};
|
||||
expectChips("a new node", result.empty, [], [], false);
|
||||
expectChips("one picture", result.first, ["@1"], [], true);
|
||||
expectChips("two pictures and a video", result.three, ["@1", "@2", "video"], [], true);
|
||||
expectChips("the second picture's loader turned off", result.off, ["@1", "video"], ["@2 off"], true);
|
||||
expectChips("every wire pulled off", result.gone, [], [], false);
|
||||
expectChips("with the setting on", result.all, [], ["+ @1", "+ @2", "+ @3", "+ @4", "+ video"], true);
|
||||
expectChips("with the setting off again", result.back, [], [], false);
|
||||
return problems;
|
||||
});
|
||||
|
||||
const live = (process.env.H3_LIVE_WORKFLOWS ?? "").split(delimiter).filter(Boolean);
|
||||
if (!live.length) skip("live workflows", "set H3_LIVE_WORKFLOWS to check saved workflows");
|
||||
for (const file of live) {
|
||||
await check(`live workflow ${file.split("/").pop()}`, async () => {
|
||||
const workflow = readFileSync(file, "utf-8");
|
||||
await evalJs(`(async () => { await window.app.loadGraphData(${workflow}, true, true, null, { showMissingNodesDialog: false, showMissingModelsDialog: false }); return true; })()`);
|
||||
await sleep(2500);
|
||||
const states = await evalJs(`(async () => { const h = window.__h3; const out = []; for (const node of h.writers()) { if (node.graph === window.app.canvas.graph) out.push({ ...(await h.read(node, 300)), saved: node.serialize().outputs.length }); else out.push({ id: node.id, elsewhere: true, hidden: node.outputs.filter((slot) => slot._ausbossHidden && (slot.links?.length ?? 0) > 0).map((slot) => slot.name), saved: node.serialize().outputs.length }); } return out; })()`);
|
||||
if (!states.length) return ["the workflow has no H3 Prompt Writer"];
|
||||
const problems = [];
|
||||
for (const state of states) {
|
||||
if (state.saved !== OUTPUT_NAMES.length) problems.push(`node ${state.id} would save ${state.saved} outputs`);
|
||||
if (state.elsewhere) { if (state.hidden.length) problems.push(`node ${state.id} hides wired outputs ${state.hidden.join(", ")}`); continue; }
|
||||
problems.push(...againstRule(state).map((p) => `node ${state.id}: ${p}`));
|
||||
const lost = state.wired.outputs.filter((name) => !state.shown.outputs.includes(name));
|
||||
if (lost.length) problems.push(`node ${state.id} does not show its wired outputs ${lost.join(", ")}`);
|
||||
}
|
||||
// One more picture plugged in: a row comes in the shorter column, and
|
||||
// every wire still ends on its dot.
|
||||
const more = await evalJs(`(async () => {
|
||||
const h = window.__h3; const node = h.writers().find((item) => item.graph === window.app.canvas.graph);
|
||||
if (!node) return null;
|
||||
const free = ["picture_1", "picture_2", "picture_3", "picture_4"].find((name) => node.inputs[h.input(node, name)].link == null);
|
||||
if (!free) return null;
|
||||
const picture = h.add("LoadImage", node.pos[0] - 420, node.pos[1] - 420);
|
||||
picture.connect(0, node, h.input(node, free));
|
||||
return { free, state: await h.read(node, 900) };
|
||||
})()`);
|
||||
if (more) problems.push(...againstRule(more.state).map((p) => `with a picture on ${more.free}: ${p}`));
|
||||
return problems;
|
||||
});
|
||||
}
|
||||
|
||||
for (const text of thrown) fail("no error thrown", text);
|
||||
await evalJs(`(async () => { window.app.graph.clear(); await window.app.extensionManager.setting.set("Comfy.VueNodes.Enabled", ${JSON.stringify(lookBefore ?? false)}); return true; })()`).catch(() => {});
|
||||
await fetch(`http://127.0.0.1:${port}/json/close/${page.id}`).catch(() => {});
|
||||
console.log(`\n${vue ? "Nodes 2.0" : "classic"}: ${failed} failed`);
|
||||
ws.close();
|
||||
process.exit(failed ? 1 : 0);
|
||||
@@ -7,7 +7,7 @@ import { fileURLToPath } from "node:url";
|
||||
|
||||
import {
|
||||
canScrollFurther, dragCarriesFiles, graphDragStarts, isAppShortcut, isWeightShortcut, keepKeyInField, panelKeepsWheel,
|
||||
panelNeedsDropHelp, panelRoot,
|
||||
panelNeedsDropHelp, panelRoot, vueBoxKeepsWheel,
|
||||
} from "../js/shared/canvas_passthrough.mjs";
|
||||
|
||||
const box = (over = {}) => ({ scrollHeight: 300, clientHeight: 100, scrollTop: 0, ...over });
|
||||
@@ -121,6 +121,39 @@ test("a pointer on the classic wrapper is over the panel inside it", () => {
|
||||
assert.equal(panelKeepsWheel(classic, { deltaY: 100 }, ctx), false);
|
||||
});
|
||||
|
||||
test("in Nodes 2.0 a box of the pack's that can still scroll claims the wheel before the graph does", () => {
|
||||
// Nodes 2.0 hands every wheel turn over a node to the graph on its way down
|
||||
// to the node, before any part of the node sees it, so a long script box
|
||||
// zoomed the graph instead of scrolling. The box claims the wheel first.
|
||||
const inHost = (className, ...children) => {
|
||||
const host = { className, parentElement: null };
|
||||
const answers = (sel) => sel.split(",").some((part) => className.split(" ").includes(part.trim().slice(1)));
|
||||
let parent = host;
|
||||
return children.map((child) => (parent = { ...child, parentElement: parent, closest: (sel) => (answers(sel) ? host : null) }));
|
||||
};
|
||||
const styleOf = (el) => ({ overflowY: el.tagName === "TEXTAREA" ? "auto" : "visible" });
|
||||
const [, vueScript] = inHost("lg-node-widgets grid", { className: "ausboss-card" }, { tagName: "TEXTAREA", className: "ausboss-card-area", ...box() });
|
||||
assert.equal(vueBoxKeepsWheel(vueScript, { deltaY: 100 }, { styleOf }), true, "long script, room below");
|
||||
assert.equal(vueBoxKeepsWheel(vueScript, { deltaY: -100 }, { styleOf }), false, "at its top, wheel up zooms");
|
||||
assert.equal(vueBoxKeepsWheel(vueScript, { deltaY: 100, ctrlKey: true }, { styleOf }), false, "Ctrl + wheel zooms");
|
||||
const [, shortScript] = inHost("lg-node-widgets grid", { className: "ausboss-card" }, { tagName: "TEXTAREA", className: "ausboss-card-area", ...box({ scrollHeight: 100 }) });
|
||||
assert.equal(vueBoxKeepsWheel(shortScript, { deltaY: 100 }, { styleOf }), false, "nothing to scroll zooms");
|
||||
const [, classicScript] = inHost("dom-widget", { className: "ausboss-card" }, { tagName: "TEXTAREA", className: "ausboss-card-area", ...box() });
|
||||
assert.equal(vueBoxKeepsWheel(classicScript, { deltaY: 100 }, { styleOf }), false, "the classic renderer lets the box see the wheel itself");
|
||||
const [coreBox] = inHost("lg-node-widgets grid", { tagName: "TEXTAREA", className: "comfy-multiline-input", ...box() });
|
||||
assert.equal(vueBoxKeepsWheel(coreBox, { deltaY: 100 }, { styleOf }), false, "core's own boxes are core's");
|
||||
assert.equal(vueBoxKeepsWheel(null, { deltaY: 100 }, { styleOf }), false);
|
||||
});
|
||||
|
||||
test("the claim runs on the way down and only stops the event, so the browser still scrolls the box", () => {
|
||||
const source = readFileSync(join(dirname(fileURLToPath(import.meta.url)), "..", "js", "canvas_passthrough", "index.js"), "utf-8");
|
||||
assert.match(source, /window\.addEventListener\("wheel", onWheelFirst, \{ capture: true, passive: true \}\)/);
|
||||
const first = source.slice(source.indexOf("function onWheelFirst"), source.indexOf("function onWheel("));
|
||||
assert.match(first, /vueBoxKeepsWheel\(/);
|
||||
assert.match(first, /event\.stopPropagation\(\)/);
|
||||
assert.doesNotMatch(first, /preventDefault/);
|
||||
});
|
||||
|
||||
// Each place under js/ that listens for the wheel, as "file target".
|
||||
function wheelListeners(js) {
|
||||
const files = readdirSync(js, { recursive: true }).map(String).filter((file) => /\.m?js$/.test(file)).map((file) => file.replaceAll("\\", "/"));
|
||||
@@ -139,6 +172,7 @@ test("only the listed parts of the pack listen for the wheel", () => {
|
||||
const js = join(dirname(fileURLToPath(import.meta.url)), "..", "js");
|
||||
const listed = [
|
||||
"canvas_passthrough/index.js window", // hands the wheel to the graph
|
||||
"canvas_passthrough/index.js window", // Nodes 2.0: a box that can still scroll keeps it
|
||||
"image_folder/index.js root", // the copy question, a window over the page
|
||||
"image_folder/index.js root", // the folder list, a window over the page
|
||||
"shared/discard_prompt.mjs backdrop", // the keep or discard question
|
||||
@@ -317,6 +351,7 @@ test("no keydown handler stops every key, outside dialogs that own the keyboard"
|
||||
const ownTheKeyboard = [
|
||||
"callout/index.js dialog", // the tile editor: Ctrl + Enter saves the text
|
||||
"shared/discard_prompt.mjs backdrop", // the keep or discard question
|
||||
"shared/h3_writer_gear.mjs back", // the wording editor: Ctrl + Enter saves the wording
|
||||
"workflow_note/index.js overlay", // the note editor: Ctrl + Enter saves the note
|
||||
];
|
||||
const files = readdirSync(js, { recursive: true }).map(String).filter((file) => /\.m?js$/.test(file)).map((file) => file.replaceAll("\\", "/"));
|
||||
|
||||
Vendored
+5
-2
@@ -305,7 +305,8 @@
|
||||
"music",
|
||||
"clip_sound",
|
||||
"full_prompt",
|
||||
"tidy"
|
||||
"tidy",
|
||||
"model_asks"
|
||||
],
|
||||
"outputs": [
|
||||
[
|
||||
@@ -1083,7 +1084,9 @@
|
||||
"optional": [
|
||||
"preview",
|
||||
"guide_image",
|
||||
"max_hole_size"
|
||||
"max_hole_size",
|
||||
"detail_range",
|
||||
"fix_threshold"
|
||||
],
|
||||
"outputs": [
|
||||
[
|
||||
|
||||
@@ -12,3 +12,24 @@ test("a chip's job list stays open while an item is pressed", () => {
|
||||
assert.doesNotMatch(blur, /\bon\)/, "the blur listener is not the capturing set");
|
||||
assert.match(source, /menu\.addEventListener\("mousedown", \(event\) => event\.preventDefault\(\)\)/, "a press keeps focus on the button");
|
||||
});
|
||||
|
||||
// One CSS rule's declarations, by its selector as written in the module.
|
||||
const rule = (selector) => source.split("\n").find((line) => line.startsWith(`${selector}{`))?.slice(selector.length + 1, -1) ?? "";
|
||||
|
||||
test("the chips stay on their one row and never drop onto the row below", () => {
|
||||
// The row is 30 px tall. Five chips with their pictures need more width
|
||||
// than the node opens with, and chips that wrapped drew the video chip over
|
||||
// the Length row, where a click could land on Length instead. They share
|
||||
// the one line: columns that take what their words need while there is
|
||||
// room, and give way widest first when there is not.
|
||||
assert.match(rule(".ausboss-chips"), /display:grid;grid-auto-flow:column;grid-auto-columns:minmax\(0,max-content\)/);
|
||||
assert.doesNotMatch(rule(".ausboss-chips"), /wrap/);
|
||||
assert.match(rule(".ausboss-chip"), /(^|;)min-width:0(;|$)/, "a chip may get narrower than its words");
|
||||
assert.match(rule(".ausboss-chip-pick"), /text-overflow:ellipsis/);
|
||||
assert.match(rule(".ausboss-chip-pick"), /(^|;)min-width:0(;|$)/);
|
||||
});
|
||||
|
||||
test("a job cut short can still be read: the chip's hint starts with it", () => {
|
||||
const choice = source.slice(source.indexOf("function choice("), source.indexOf("// The jobs have no socket"));
|
||||
assert.match(choice, /button\.title = \[String\(value \?\? ""\), hint\]\.filter\(Boolean\)\.join\("\\n"\)/);
|
||||
});
|
||||
|
||||
@@ -63,13 +63,13 @@ class Element {
|
||||
get textContent(){return this._text+this.children.map(c=>c.textContent??'').join('');}
|
||||
addEventListener(){}
|
||||
}
|
||||
test('timeline omits guessed duration/retiming and rejects an old async report; old timeline returns on Video OFF', async()=>{
|
||||
test('timeline omits guessed duration/retiming, still shows the script\'s problems for a clip, and returns on Video OFF', async()=>{
|
||||
const realDocument=globalThis.document;
|
||||
globalThis.document={getElementById:()=>true,createElement:()=>new Element()};
|
||||
const timers=[];const intervals=[];const requests=[];const pending=[];
|
||||
globalThis.__h3DurationTest={
|
||||
api:{fetchApi:async(_url,opts)=>{requests.push(JSON.parse(opts.body));return await new Promise(resolve=>pending.push(resolve));}},
|
||||
app:{},chainCallback(){},
|
||||
app:{},chainCallback(){},notifyAusbossChange(){},
|
||||
attachScriptColours:()=>({area:null,layer:null,sync(){},dispose(){}}),
|
||||
attachScriptAssist:()=>({dispose(){}}),
|
||||
setTimeout:fn=>{timers.push(fn);return fn;},clearTimeout:fn=>{const i=timers.indexOf(fn);if(i>=0)timers.splice(i,1);},
|
||||
@@ -82,7 +82,7 @@ test('timeline omits guessed duration/retiming and rejects an old async report;
|
||||
return line.replace(/"\.\/(.*?)"/,(_m,file)=>JSON.stringify(new URL('../js/shared/'+file,import.meta.url).href));
|
||||
if(line.includes('api.js'))return 'const {api}=globalThis.__h3DurationTest;';
|
||||
if(line.includes('app.js'))return 'const {app}=globalThis.__h3DurationTest;';
|
||||
if(line.includes('index.mjs'))return 'const BRAND="#0ba", {chainCallback}=globalThis.__h3DurationTest;';
|
||||
if(line.includes('index.mjs'))return 'const BRAND="#0ba", {chainCallback,notifyAusbossChange}=globalThis.__h3DurationTest;';
|
||||
if(line.includes('script_assist.mjs'))return 'const {attachScriptAssist}=globalThis.__h3DurationTest;';
|
||||
if(line.includes('script_colours.mjs'))return 'const {attachScriptColours}=globalThis.__h3DurationTest;';
|
||||
throw new Error('Unmocked host import '+line);
|
||||
@@ -96,16 +96,28 @@ test('timeline omits guessed duration/retiming and rejects an old async report;
|
||||
assert.equal(requests[0].seconds,12);
|
||||
panel.sync({...values,video_job:'swap the person'});
|
||||
assert.equal(ruler.children.length,0);assert.equal(track.textContent,'Length comes from the clip');
|
||||
assert.doesNotMatch(panel.element.textContent,/12|one take/);assert.equal(timers.length,0);
|
||||
assert.doesNotMatch(panel.element.textContent,/12|one take/);
|
||||
// The clip sets the length, but the script is still read once for its
|
||||
// problems: the run would stop on them.
|
||||
assert.equal(timers.length,1);
|
||||
pending.shift()({ok:true,json:async()=>({seconds:12,moments:[{start:0,end:12,text:'She walks',line:0}]})});
|
||||
await new Promise(resolve=>setImmediate(resolve));
|
||||
assert.equal(track.textContent,'Length comes from the clip');assert.ok(refreshes>0);
|
||||
timers.shift()();await Promise.resolve();
|
||||
assert.equal(requests.at(-1).video,'swap the person');
|
||||
pending.shift()({ok:true,json:async()=>({seconds:12,moments:[{start:0,end:12,text:'She walks',line:0}],warning:'@5 has no picture.'})});
|
||||
await new Promise(resolve=>setImmediate(resolve));
|
||||
assert.equal(note.textContent,'@5 has no picture.');assert.equal(track.textContent,'Length comes from the clip');
|
||||
intervals[0]();assert.equal(timers.length,0);assert.equal(note.textContent,'@5 has no picture.');
|
||||
video.mode=4;intervals[0]();assert.equal(timers.length,1);
|
||||
timers.shift()();await Promise.resolve();assert.equal(requests.at(-1).seconds,12);
|
||||
assert.equal(requests.at(-1).video,'');
|
||||
pending.shift()({ok:true,json:async()=>({seconds:12,moments:[{start:0,end:12,text:'She walks',line:0}]})});
|
||||
await new Promise(resolve=>setImmediate(resolve));
|
||||
assert.match(note.textContent,/12 s/);assert.ok(ruler.children.length>0);
|
||||
// 4 s is the shortest length the node takes, and the bar marks 4 s.
|
||||
panel.sync({...values,seconds:4});timers.shift()();await Promise.resolve();
|
||||
assert.equal(requests.at(-1).seconds,4);
|
||||
} finally {globalThis.document=realDocument;delete globalThis.__h3DurationTest;}
|
||||
});
|
||||
|
||||
@@ -142,7 +154,7 @@ test('H3 makes 5 + 17n frames, rounding a clip down (Python video_frames)', asyn
|
||||
assert.equal(h3VideoFrames(1000), 360 - ((360 - 5) % 17));
|
||||
const words = clipLengthWords({ frames: 48, startSeconds: 1, endSeconds: 3, roomFrames: 74 });
|
||||
assert.equal(words.title, "H3 makes 39 of the clip's 48 frames · 1.63 s");
|
||||
assert.match(words.note, /Stops at 2\.63 s.*1\.63 s or 2\.33 s/);
|
||||
assert.equal(words.note, "H3 leaves out the last 0.38 s, so it stops at 2.63 s in the video. To lose nothing, set the clip's Duration to 1.63 s or 2.33 s.");
|
||||
assert.equal(clipLengthWords({ frames: 39, startSeconds: 0, endSeconds: 1.625 }).warn, false);
|
||||
assert.equal(clipLengthWords(null), null);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,196 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { INPUT_NAMES, OUTPUT_NAMES, SHOW_ALL, chipsToShow, dropTarget, hiddenRowsRule, setSocketHidden, socketsToShow } from '../js/shared/h3_sockets.mjs';
|
||||
|
||||
const BASE_IN = ['clip', 'picture_1', 'video', 'voice', 'song'];
|
||||
const BASE_OUT = ['prompt', 'frames', 'width', 'height'];
|
||||
const sorted = (names) => [...new Set(names)].sort();
|
||||
const shows = (wiredInputs, wiredOutputs = [], showAll = false) => {
|
||||
const { inputs, outputs } = socketsToShow({ wiredInputs, wiredOutputs, showAll });
|
||||
return { inputs: sorted(inputs), outputs: sorted(outputs) };
|
||||
};
|
||||
const expectShown = (wiredInputs, moreInputs, moreOutputs) => {
|
||||
const got = shows(wiredInputs);
|
||||
assert.deepEqual(got.inputs, sorted([...BASE_IN, ...moreInputs]), `inputs with ${wiredInputs.join(', ') || 'nothing'} wired`);
|
||||
assert.deepEqual(got.outputs, sorted([...BASE_OUT, ...moreOutputs]), `outputs with ${wiredInputs.join(', ') || 'nothing'} wired`);
|
||||
};
|
||||
|
||||
test('the socket names are the node\'s own, in its order', () => {
|
||||
assert.deepEqual(INPUT_NAMES, ['clip', 'picture_1', 'picture_2', 'picture_3', 'picture_4', 'video', 'video_sound', 'voice', 'song']);
|
||||
assert.deepEqual(OUTPUT_NAMES, ['prompt', 'picture_1', 'picture_2', 'picture_3', 'picture_4', 'video', 'video_sound', 'voice', 'song', 'song_under', 'frames', 'width', 'height', 'keeps_clip_sound']);
|
||||
});
|
||||
|
||||
test('a fresh node shows five inputs and four outputs', () => expectShown([], [], []));
|
||||
test('one picture shows the next picture input and its own output', () => expectShown(['picture_1'], ['picture_2'], ['picture_1']));
|
||||
test('two pictures show a third input and two outputs', () => expectShown(['picture_1', 'picture_2'], ['picture_2', 'picture_3'], ['picture_1', 'picture_2']));
|
||||
test('a picture on the third input shows every picture input and one packed output', () => expectShown(['picture_3'], ['picture_2', 'picture_3', 'picture_4'], ['picture_1']));
|
||||
test('four pictures show four inputs and four outputs', () => {
|
||||
const all = ['picture_1', 'picture_2', 'picture_3', 'picture_4'];
|
||||
expectShown(all, all, all);
|
||||
});
|
||||
test('a video shows its sound input, its output and the keeps-sound flag', () => expectShown(['video'], ['video_sound'], ['video', 'keeps_clip_sound']));
|
||||
test('a video with its sound shows both outputs', () => expectShown(['video', 'video_sound'], ['video_sound'], ['video', 'video_sound', 'keeps_clip_sound']));
|
||||
test('a video sound alone shows its own row but no keeps-sound flag', () => expectShown(['video_sound'], ['video_sound'], ['video_sound']));
|
||||
test('a voice shows the voice output', () => expectShown(['voice'], [], ['voice']));
|
||||
test('a song shows the song output', () => expectShown(['song'], [], ['song']));
|
||||
test('a voice and a song show the song to mix under', () => expectShown(['voice', 'song'], [], ['voice', 'song', 'song_under']));
|
||||
|
||||
test('an output with a wire on it always shows', () => {
|
||||
assert.deepEqual(shows([], ['song_under']).outputs, sorted([...BASE_OUT, 'song_under']));
|
||||
});
|
||||
|
||||
test('show all returns every socket', () => {
|
||||
const got = shows([], [], true);
|
||||
assert.deepEqual(got.inputs, sorted(INPUT_NAMES));
|
||||
assert.deepEqual(got.outputs, sorted(OUTPUT_NAMES));
|
||||
});
|
||||
|
||||
test('pulling the second picture\'s wire drops its output again', () => {
|
||||
assert.ok(shows(['picture_1', 'picture_2']).outputs.includes('picture_2'));
|
||||
const after = shows(['picture_1']);
|
||||
assert.equal(after.outputs.includes('picture_2'), false);
|
||||
assert.equal(after.inputs.includes('picture_3'), false);
|
||||
});
|
||||
|
||||
const audioInputs = ({ voice = false, song = false, videoSoundShown = false } = {}) => [
|
||||
{ name: 'video', type: 'IMAGE', wired: false, shown: true },
|
||||
{ name: 'video_sound', type: 'AUDIO', wired: true, shown: videoSoundShown },
|
||||
{ name: 'voice', type: 'AUDIO', wired: voice, shown: true },
|
||||
{ name: 'song', type: 'AUDIO', wired: song, shown: true },
|
||||
];
|
||||
|
||||
test('a wire that lands on a hidden socket moves to the first shown free one of its kind', () => {
|
||||
assert.equal(dropTarget(audioInputs(), 1), 2);
|
||||
assert.equal(dropTarget(audioInputs({ voice: true }), 1), 3);
|
||||
});
|
||||
|
||||
test('a dropped wire stays put when nothing shown is free, or when it landed on a shown socket', () => {
|
||||
assert.equal(dropTarget(audioInputs({ voice: true, song: true }), 1), 1);
|
||||
assert.equal(dropTarget(audioInputs({ videoSoundShown: true }), 1), 1);
|
||||
assert.equal(dropTarget(audioInputs(), 9), 9);
|
||||
});
|
||||
|
||||
// A socket as the frontend makes it: draw and drawCollapsed live on its class.
|
||||
class Socket {
|
||||
constructor(name) { this.name = name; }
|
||||
draw() { return 'drawn'; }
|
||||
drawCollapsed() { return 'drawn collapsed'; }
|
||||
}
|
||||
const own = (slot, key) => Object.prototype.hasOwnProperty.call(slot, key);
|
||||
|
||||
test('hiding a socket parks it and silences its drawing', () => {
|
||||
const slot = new Socket('picture_2');
|
||||
assert.equal(setSocketHidden(slot, true), true);
|
||||
assert.equal(slot._ausbossHidden, true);
|
||||
assert.ok(Array.isArray(slot.pos), 'a position takes the socket out of the stacked rows');
|
||||
assert.equal(slot.draw(), undefined);
|
||||
assert.equal(slot.drawCollapsed(), undefined);
|
||||
});
|
||||
|
||||
test('showing a socket again leaves it exactly as the frontend made it', () => {
|
||||
const slot = new Socket('picture_2');
|
||||
setSocketHidden(slot, true);
|
||||
assert.equal(setSocketHidden(slot, false), true);
|
||||
assert.equal(slot._ausbossHidden, false);
|
||||
for (const key of ['pos', 'draw', 'drawCollapsed']) assert.equal(own(slot, key), false, key);
|
||||
assert.equal(slot.draw(), 'drawn');
|
||||
});
|
||||
|
||||
test('a socket with no draw of its own kind is left alone and stays visible', () => {
|
||||
const slot = { name: 'x' };
|
||||
assert.equal(setSocketHidden(slot, true), false);
|
||||
assert.equal(own(slot, 'pos'), false);
|
||||
assert.equal(Boolean(slot._ausbossHidden), false);
|
||||
});
|
||||
|
||||
test('a socket that came with its own position is never hidden and keeps it', () => {
|
||||
const slot = new Socket('placed');
|
||||
slot.pos = [10, 20];
|
||||
assert.equal(setSocketHidden(slot, true), false);
|
||||
assert.deepEqual(slot.pos, [10, 20]);
|
||||
setSocketHidden(slot, false);
|
||||
assert.deepEqual(slot.pos, [10, 20]);
|
||||
});
|
||||
|
||||
test('a new node has no picture chip', () => {
|
||||
assert.deepEqual(chipsToShow({ wiredInputs: [] }), []);
|
||||
assert.deepEqual(chipsToShow(), []);
|
||||
});
|
||||
|
||||
test('a chip shows for each picture and video with a wire, in the node\'s order', () => {
|
||||
assert.deepEqual(chipsToShow({ wiredInputs: ['picture_1'] }), ['picture_1']);
|
||||
assert.deepEqual(chipsToShow({ wiredInputs: ['video', 'picture_3', 'picture_1'] }), ['picture_1', 'picture_3', 'video']);
|
||||
});
|
||||
|
||||
test('a voice, a song or a text model gets no chip', () => {
|
||||
assert.deepEqual(chipsToShow({ wiredInputs: ['clip', 'voice', 'song', 'video_sound'] }), []);
|
||||
});
|
||||
|
||||
test('show all gives every picture chip and the video chip', () => {
|
||||
assert.deepEqual(chipsToShow({ wiredInputs: ['picture_2'], showAll: true }), ['picture_1', 'picture_2', 'picture_3', 'picture_4', 'video']);
|
||||
});
|
||||
|
||||
test('the setting has the id the settings page lists it under', () => {
|
||||
assert.equal(SHOW_ALL, 'AusBoss.H3PromptWriter.ShowEverySocket');
|
||||
});
|
||||
|
||||
test('the style rule hides one row for each hidden socket of a node', () => {
|
||||
assert.equal(
|
||||
hiddenRowsRule(7, ['in-2', 'out-1']),
|
||||
'.lg-slot:has([data-slot-key="7-in-2"]),.lg-slot:has([data-slot-key="7-out-1"]){display:none}',
|
||||
);
|
||||
assert.equal(hiddenRowsRule(7, []), '');
|
||||
});
|
||||
|
||||
test('a node id from a workflow file cannot add style rules of its own', () => {
|
||||
const hostile = 'a"]){}body{background:url(https://example.com/x)}.x:has([q="';
|
||||
const rule = hiddenRowsRule(hostile, ['in-2'], true);
|
||||
assert.equal(rule.split('{').length - 1, 2, 'one block for the rows and one for the nudge, no more');
|
||||
assert.equal(rule.split('}').length - 1, 2);
|
||||
assert.equal(rule.split('"').length - 1, 4, 'only the quotes around the two attribute values');
|
||||
assert.doesNotMatch(rule, /url\(/);
|
||||
});
|
||||
|
||||
test('the nudge adds a rule for the node\'s widget grid, so the frontend measures the rows again', () => {
|
||||
const plain = hiddenRowsRule(7, ['in-2']);
|
||||
const nudged = hiddenRowsRule(7, ['in-2'], true);
|
||||
assert.notEqual(nudged, plain);
|
||||
assert.ok(nudged.startsWith(plain));
|
||||
assert.match(nudged, /\[data-widgets-grid-node-id="7"\]\{padding-left:0\.1px\}$/);
|
||||
assert.match(hiddenRowsRule(7, [], true), /^\[data-widgets-grid-node-id="7"\]/, 'a node with nothing hidden can still be measured again');
|
||||
});
|
||||
|
||||
const outputs = ({ voiceWired = true } = {}) => [
|
||||
{ name: 'prompt', type: 'STRING', wired: false, shown: true },
|
||||
{ name: 'picture_1', type: 'IMAGE', wired: false, shown: false },
|
||||
{ name: 'video_sound', type: 'AUDIO', wired: false, shown: false },
|
||||
{ name: 'voice', type: 'AUDIO', wired: voiceWired, shown: true },
|
||||
];
|
||||
|
||||
test('an output can take more than one wire, so a shown one of the kind is the target even when wired', () => {
|
||||
assert.equal(dropTarget(outputs(), 2, { shared: true }), 3);
|
||||
assert.equal(dropTarget(outputs({ voiceWired: false }), 2, { shared: true }), 3);
|
||||
assert.equal(dropTarget(outputs(), 2), 2, 'an input takes one wire only');
|
||||
assert.equal(dropTarget(outputs(), 1, { shared: true }), 1, 'no picture output shows: the wire stays where it landed');
|
||||
});
|
||||
|
||||
// A later release may give the node more pictures, added at the end of its lists.
|
||||
const EIGHT_IN = [...INPUT_NAMES, 'picture_5', 'picture_6', 'picture_7', 'picture_8'];
|
||||
const EIGHT_OUT = [...OUTPUT_NAMES, 'picture_5', 'picture_6', 'picture_7', 'picture_8'];
|
||||
const eight = (wiredInputs) => {
|
||||
const { inputs, outputs } = socketsToShow({ wiredInputs, inputNames: EIGHT_IN, outputNames: EIGHT_OUT });
|
||||
return { inputs: sorted(inputs), outputs: sorted(outputs) };
|
||||
};
|
||||
|
||||
test('a node with more picture sockets grows them one at a time too', () => {
|
||||
assert.deepEqual(eight([]).inputs, sorted(BASE_IN));
|
||||
const four = ['picture_1', 'picture_2', 'picture_3', 'picture_4'];
|
||||
assert.deepEqual(eight(four).inputs, sorted([...BASE_IN, ...four, 'picture_5']));
|
||||
assert.deepEqual(eight([...four, 'picture_5']).outputs, sorted([...BASE_OUT, ...four, 'picture_5']));
|
||||
});
|
||||
|
||||
test('a socket the rule does not know is always shown', () => {
|
||||
const { inputs, outputs } = socketsToShow({ inputNames: [...INPUT_NAMES, 'new_input'], outputNames: [...OUTPUT_NAMES, 'new_output'] });
|
||||
assert.ok(inputs.has('new_input'));
|
||||
assert.ok(outputs.has('new_output'));
|
||||
});
|
||||
@@ -0,0 +1,249 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { readFileSync } from "node:fs";
|
||||
|
||||
import { LONGEST_ASK, editedAsks, readAsks, writeAsks } from "../js/shared/h3_writer_gear_math.mjs";
|
||||
|
||||
test("an empty or broken model_asks reads as no wording of the node's own", () => {
|
||||
for (const value of ["", undefined, "nope", "[1]", '{"next": 3}']) assert.deepEqual(readAsks(value), {});
|
||||
assert.deepEqual(readAsks('{"next": "Write {count}.", "other": "x", "heard": " "}'), { next: "Write {count}." });
|
||||
});
|
||||
|
||||
test("saving a wording keeps the others, and an empty one goes back to built-in", () => {
|
||||
const one = writeAsks("", "next", "Write {count}.");
|
||||
assert.equal(one, '{"next":"Write {count}."}');
|
||||
const two = writeAsks(one, "tidy", "Be brief.");
|
||||
assert.deepEqual(JSON.parse(two), { next: "Write {count}.", tidy: "Be brief." });
|
||||
assert.deepEqual(JSON.parse(writeAsks(two, "next", " ")), { tidy: "Be brief." });
|
||||
assert.equal(writeAsks(writeAsks(two, "next", ""), "tidy", ""), "");
|
||||
});
|
||||
|
||||
test("the menu marks the wordings the node has changed", () => {
|
||||
assert.deepEqual([...editedAsks('{"describe": "x", "tidy": "y"}')].sort(), ["describe", "tidy"]);
|
||||
assert.equal(editedAsks("").size, 0);
|
||||
});
|
||||
|
||||
test("the editor's longest wording is the one the writer reads", async () => {
|
||||
const { readFileSync } = await import("node:fs");
|
||||
const python = readFileSync(new URL("../nodes/_h3_model_asks.py", import.meta.url), "utf8");
|
||||
assert.equal(LONGEST_ASK, Number(python.match(/LONGEST_ASK = (\d+)/)[1]));
|
||||
});
|
||||
|
||||
test("a wording that drops a name the writer fills in, or adds one it does not, is called out", async () => {
|
||||
const { wordingWarning } = await import("../js/shared/h3_writer_gear_math.mjs");
|
||||
const heard = "This happens in a video:\n{lines}\n\nList the sounds.";
|
||||
const next = "This is a {seconds} second video.\nFirst this happens: {first}\n\nWrite {count} short lines.";
|
||||
assert.equal(wordingWarning("heard", "Where is this?\n{lines}\nName the steady sounds.", heard), "");
|
||||
assert.equal(wordingWarning("heard", "Name the steady sounds.", heard), "Without {lines}, the model is not told what happens in the clip.");
|
||||
assert.equal(
|
||||
wordingWarning("next", "A {seconds} second video. Write {count} lines.", next),
|
||||
"Without {first}, the model is not told what happens first.",
|
||||
);
|
||||
assert.equal(
|
||||
wordingWarning("heard", "In the clip: {line}. Name the sounds.", heard),
|
||||
"Without {lines}, the model is not told what happens in the clip. {line} is not filled in: the model reads it as typed.",
|
||||
);
|
||||
assert.equal(wordingWarning("describe", "Describe {who}.", "Describe the person."), "{who} is not filled in: the model reads it as typed.");
|
||||
assert.equal(wordingWarning("tidy", "Keep it short.", "Tidy the lines."), "");
|
||||
});
|
||||
|
||||
// The gear itself, with only ComfyUI and the page replaced: the menu's Reset,
|
||||
// and the editor's Escape and Save.
|
||||
class Element {
|
||||
constructor(tag) {
|
||||
Object.assign(this, { tag, children: [], parent: null, listeners: {}, removed: false, value: "", title: "", className: "", textContent: "" });
|
||||
const names = new Set();
|
||||
this.classList = { toggle: (name, on) => (on ? names.add(name) : names.delete(name)), contains: (name) => names.has(name) };
|
||||
this.style = {};
|
||||
}
|
||||
append(...children) {
|
||||
for (const child of children) {
|
||||
child.parent = this;
|
||||
this.children.push(child);
|
||||
}
|
||||
}
|
||||
addEventListener(type, listener) {
|
||||
(this.listeners[type] ??= []).push(listener);
|
||||
}
|
||||
remove() {
|
||||
this.removed = true;
|
||||
if (this.parent) this.parent.children = this.parent.children.filter((child) => child !== this);
|
||||
}
|
||||
focus() {
|
||||
globalThis.document.activeElement = this;
|
||||
}
|
||||
set innerHTML(_html) {}
|
||||
all() {
|
||||
return [this, ...this.children.flatMap((child) => child.all())];
|
||||
}
|
||||
querySelectorAll(selector) {
|
||||
const tags = selector.split(",").map((part) => part.trim());
|
||||
return this.all().filter((element) => element !== this && tags.includes(element.tag));
|
||||
}
|
||||
getBoundingClientRect() {
|
||||
return { left: 0, top: 0, right: 20, bottom: 20, width: 20, height: 20 };
|
||||
}
|
||||
}
|
||||
|
||||
async function fire(element, type, extra = {}) {
|
||||
const event = { type, target: element, preventDefault() {}, stopPropagation() {}, ...extra };
|
||||
const waits = [];
|
||||
for (let at = element; at; at = at.parent) for (const listener of at.listeners[type] ?? []) waits.push(listener(event));
|
||||
await Promise.all(waits);
|
||||
}
|
||||
|
||||
// Each load is a module of its own, so one test's stand-ins never leak into the next.
|
||||
let loads = 0;
|
||||
async function loadGear({ asks = "", showAll = false } = {}) {
|
||||
const realDocument = globalThis.document;
|
||||
const body = new Element("body");
|
||||
globalThis.document = { body, head: new Element("head"), activeElement: null, getElementById: () => null, createElement: (tag) => new Element(tag) };
|
||||
const settings = { "AusBoss.H3PromptWriter.ShowEverySocket": showAll };
|
||||
const menus = [];
|
||||
const toasts = [];
|
||||
const written = [];
|
||||
let closed = 0;
|
||||
globalThis.__gearTest = {
|
||||
api: { fetchApi: async () => ({ ok: true, json: async () => ({ describe: "Describe the person.", next: "Write {count} lines after {first}, in {seconds} s.", heard: "In the clip:\n{lines}\nName the sounds.", tidy: "Tidy the lines." }) }) },
|
||||
app: { extensionManager: { setting: { get: (key) => settings[key], set: (key, value) => { settings[key] = value; } } } },
|
||||
openSettingsMenu: (options) => menus.push(options),
|
||||
closeSettingsMenu: () => { closed += 1; },
|
||||
showToast: (toast) => toasts.push(toast),
|
||||
};
|
||||
let source = readFileSync(new URL("../js/shared/h3_writer_gear.mjs", import.meta.url), "utf8");
|
||||
source = source.replace(/^import .*;$/gm, (line) => {
|
||||
if (/h3_writer_gear_math|h3_sockets|theme/.test(line)) {
|
||||
return line.replace(/"\.\/(.*?)"/, (_match, file) => JSON.stringify(new URL(`../js/shared/${file}`, import.meta.url).href));
|
||||
}
|
||||
if (line.includes("api.js")) return "const { api } = globalThis.__gearTest;";
|
||||
if (line.includes("app.js")) return "const { app } = globalThis.__gearTest;";
|
||||
if (line.includes("settings_menu.mjs")) return "const { openSettingsMenu, closeSettingsMenu } = globalThis.__gearTest; const gearIconSvg = () => '';";
|
||||
if (line.includes("index.mjs")) return "const { showToast } = globalThis.__gearTest;";
|
||||
throw new Error(`Unmocked import ${line}`);
|
||||
});
|
||||
source += `\n// load ${(loads += 1)}`;
|
||||
const { writerGear } = await import(`data:text/javascript;base64,${Buffer.from(source).toString("base64")}`);
|
||||
const values = { model_asks: asks };
|
||||
const card = {
|
||||
values: () => ({ ...values }),
|
||||
setWidget: (name, value) => { values[name] = value; written.push([name, value]); },
|
||||
refresh() {},
|
||||
};
|
||||
const gear = writerGear({ id: 1 }, card).element;
|
||||
const open = async () => { await fire(gear, "click"); return menus.at(-1); };
|
||||
const editor = async (key) => {
|
||||
const menu = await open();
|
||||
await menu.schema.find((entry) => entry.key === `ask_${key}`).onAction();
|
||||
const back = body.children.at(-1);
|
||||
const find = (tag, text) => back.all().find((element) => element.tag === tag && (text === undefined || element.textContent === text));
|
||||
return { back, area: find("textarea"), state: back.all().find((element) => element.className.startsWith("state")), find };
|
||||
};
|
||||
const restore = () => {
|
||||
globalThis.document = realDocument;
|
||||
delete globalThis.__gearTest;
|
||||
};
|
||||
return { settings, menus, toasts, written, values, open, editor, restore, closed: () => closed };
|
||||
}
|
||||
|
||||
test("Reset in the gear puts the sockets and every wording back, and says how to undo it", async () => {
|
||||
const gear = await loadGear({ asks: '{"heard": "Mine: {lines}"}', showAll: true });
|
||||
try {
|
||||
const menu = await gear.open();
|
||||
assert.equal(menu.initial.sockets, "all");
|
||||
menu.onChange({ sockets: "all" }, null);
|
||||
await new Promise((resolve) => setImmediate(resolve));
|
||||
assert.equal(gear.settings["AusBoss.H3PromptWriter.ShowEverySocket"], false);
|
||||
assert.deepEqual(gear.written, [["model_asks", ""]]);
|
||||
assert.match(gear.toasts[0]?.detail ?? "", /built-in/);
|
||||
assert.match(gear.toasts[0]?.detail ?? "", /Ctrl\+Z/);
|
||||
const shown = gear.menus.at(-1);
|
||||
assert.notEqual(shown, menu);
|
||||
assert.equal(shown.initial.sockets, "in use");
|
||||
assert.equal(shown.schema.find((entry) => entry.key === "ask_heard").hint, "Built-in wording.");
|
||||
} finally {
|
||||
gear.restore();
|
||||
}
|
||||
});
|
||||
|
||||
test("Reset with nothing edited changes no wording and says nothing", async () => {
|
||||
const gear = await loadGear();
|
||||
try {
|
||||
(await gear.open()).onChange({ sockets: "in use" }, null);
|
||||
await new Promise((resolve) => setImmediate(resolve));
|
||||
assert.deepEqual(gear.written, []);
|
||||
assert.deepEqual(gear.toasts, []);
|
||||
} finally {
|
||||
gear.restore();
|
||||
}
|
||||
});
|
||||
|
||||
test("Escape over typing that is not saved asks once before it closes the editor", async () => {
|
||||
const gear = await loadGear();
|
||||
try {
|
||||
const { back, area, state } = await gear.editor("heard");
|
||||
await fire(area, "keydown", { key: "Escape" });
|
||||
assert.equal(back.removed, true, "nothing typed: Escape closes at once");
|
||||
const again = await gear.editor("heard");
|
||||
again.area.value = "Mine: {lines}";
|
||||
await fire(again.area, "input");
|
||||
await fire(again.area, "keydown", { key: "Escape" });
|
||||
assert.equal(again.back.removed, false);
|
||||
assert.match(again.state.textContent, /Esc again/);
|
||||
await fire(again.area, "keydown", { key: "Escape" });
|
||||
assert.equal(again.back.removed, true);
|
||||
assert.deepEqual(gear.written, []);
|
||||
void state;
|
||||
} finally {
|
||||
gear.restore();
|
||||
}
|
||||
});
|
||||
|
||||
test("a click outside the editor over unsaved typing asks first too", async () => {
|
||||
const gear = await loadGear();
|
||||
try {
|
||||
const { back, area } = await gear.editor("tidy");
|
||||
area.value = "Keep it short.";
|
||||
await fire(area, "input");
|
||||
await fire(back, "pointerdown");
|
||||
assert.equal(back.removed, false);
|
||||
await fire(back, "pointerdown");
|
||||
assert.equal(back.removed, true);
|
||||
assert.deepEqual(gear.written, []);
|
||||
} finally {
|
||||
gear.restore();
|
||||
}
|
||||
});
|
||||
|
||||
test("Save over a wording that drops {lines} says so first, and saves on the second press", async () => {
|
||||
const gear = await loadGear();
|
||||
try {
|
||||
const { back, area, state, find } = await gear.editor("heard");
|
||||
area.value = "Name the steady sounds.";
|
||||
await fire(area, "input");
|
||||
const save = find("button", "Save");
|
||||
await fire(save, "click");
|
||||
assert.deepEqual(gear.written, []);
|
||||
assert.equal(back.removed, false);
|
||||
assert.match(state.textContent, /Without \{lines\}/);
|
||||
assert.equal(save.textContent, "Save anyway");
|
||||
await fire(save, "click");
|
||||
assert.deepEqual(gear.written, [["model_asks", '{"heard":"Name the steady sounds."}']]);
|
||||
assert.equal(back.removed, true);
|
||||
} finally {
|
||||
gear.restore();
|
||||
}
|
||||
});
|
||||
|
||||
test("Save over an empty wording goes back to built-in without asking", async () => {
|
||||
const gear = await loadGear({ asks: '{"heard": "Mine: {lines}"}' });
|
||||
try {
|
||||
const { back, area, find } = await gear.editor("heard");
|
||||
area.value = " ";
|
||||
await fire(area, "input");
|
||||
await fire(find("button", "Save"), "click");
|
||||
assert.deepEqual(gear.written, [["model_asks", ""]]);
|
||||
assert.equal(back.removed, true);
|
||||
} finally {
|
||||
gear.restore();
|
||||
}
|
||||
});
|
||||
@@ -1,7 +1,7 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
|
||||
import { stripCaption, stripRows, wiredJobs } from "../js/shared/moment_strip_math.mjs";
|
||||
import { castLines, castPieces, readLines, stripCaption, stripRows, wiredJobs } from "../js/shared/moment_strip_math.mjs";
|
||||
|
||||
const row = (start, end, extra = {}) => ({ start, end, text: "She runs", cut: false, speech: false, ...extra });
|
||||
|
||||
@@ -43,3 +43,70 @@ test("only connected pictures send their job", () => {
|
||||
test("a warning goes first", () => {
|
||||
assert.deepEqual(stripCaption({ warning: "Too many.", moments: [row(0, 5)] }), { text: "Too many.", warn: true });
|
||||
});
|
||||
test("a swap's plain reading says who each new person replaces, in sentences, and the words it leaves out", () => {
|
||||
const lines = readLines({
|
||||
people: [
|
||||
{ slot: 1, goes: "the man in front", looks: "a game character with a blue suit", named: true },
|
||||
{ slot: 2, goes: "the person on the right", looks: "", named: false },
|
||||
],
|
||||
unused: ["make her smile"],
|
||||
keeps_clip_clothes: false,
|
||||
});
|
||||
assert.deepEqual(lines, [
|
||||
{ text: "@1 replaces the man in front. Looks like a game character with a blue suit.", warn: false },
|
||||
{ text: "@2 replaces the person on the right (no one named).", warn: false },
|
||||
{ text: "Not used: “make her smile”. A swap keeps the clip's camera and moves; only spoken lines in quotes change.", warn: true },
|
||||
]);
|
||||
});
|
||||
|
||||
test("a swap's plain reading says when the clip keeps its clothes, and shows a refused line's reason", () => {
|
||||
assert.deepEqual(readLines({ people: [{ slot: 1, goes: "the woman", looks: "", named: true }], unused: [], keeps_clip_clothes: true }), [
|
||||
{ text: "@1 replaces the woman. Keeps the clip's clothes.", warn: false },
|
||||
]);
|
||||
assert.deepEqual(readLines({ people: [], unused: [], keeps_clip_clothes: false, problem: "Picture 3 is not connected." }), [
|
||||
{ text: "Picture 3 is not connected.", warn: true },
|
||||
]);
|
||||
assert.deepEqual(readLines(undefined), []);
|
||||
});
|
||||
|
||||
test("the Ref2VA view lists the cast lines the writer sends, then words it leaves out", () => {
|
||||
const read = { people: [], cast: ["<Subject 1> the man in <Video 1> → removed"], unused: ["make her smile"], keeps_clip_clothes: false };
|
||||
assert.deepEqual(castLines(read), [
|
||||
{ text: "<Subject 1> the man in <Video 1> → removed", warn: false },
|
||||
{ text: "Not sent: “make her smile” (a swap keeps the clip's camera and moves)", warn: true },
|
||||
]);
|
||||
assert.deepEqual(castLines({ problem: "Picture 2 is not connected." }), [{ text: "Picture 2 is not connected.", warn: true }]);
|
||||
});
|
||||
|
||||
test("a cast line splits into coloured tags and plain words", () => {
|
||||
assert.deepEqual(castPieces("<Subject 2> = the person in <Picture 1>, takes <Subject 1>'s place"), [
|
||||
{ kind: "subject", text: "<Subject 2>" },
|
||||
{ kind: "", text: " = the person in " },
|
||||
{ kind: "picture", text: "<Picture 1>" },
|
||||
{ kind: "", text: ", takes " },
|
||||
{ kind: "subject", text: "<Subject 1>" },
|
||||
{ kind: "", text: "'s place" },
|
||||
]);
|
||||
assert.deepEqual(castPieces("<Subject 1> the man in <Video 1> → removed").map((piece) => piece.kind), ["subject", "", "video", "", "removed"]);
|
||||
assert.deepEqual(castPieces("<Subject 4> says <d>Hi.</d>").map((piece) => piece.kind), ["subject", "", "speech", "", "speech"]);
|
||||
});
|
||||
|
||||
test("plain words name every other picture and who speaks", () => {
|
||||
const lines = readLines({
|
||||
people: [{ slot: 1, goes: "the man", looks: "", named: true }], unused: [], keeps_clip_clothes: false,
|
||||
pictures: [
|
||||
{ slot: 2, job: "place", worn_by: null }, { slot: 3, job: "outfit", worn_by: 1 },
|
||||
{ slot: 4, job: "thing", worn_by: null }, { slot: 2, job: "style", worn_by: null },
|
||||
],
|
||||
says: [{ slot: 1, words: "Hello there." }, { slot: null, words: "Hi." }],
|
||||
});
|
||||
assert.deepEqual(lines.map((line) => line.text), [
|
||||
"@1 replaces the man.",
|
||||
"@2 is the place.",
|
||||
"@3 is the outfit @1 wears.",
|
||||
"@4 is a thing in the shot.",
|
||||
"@2 sets the style.",
|
||||
"@1 says \u201cHello there.\u201d",
|
||||
"Someone in the clip says \u201cHi.\u201d",
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -170,7 +170,7 @@ const APPENDED_SINCE = {
|
||||
AUSBOSS_NODES_LaMaInpaint: { preview: "toggle" },
|
||||
// Film Grain's Auto, appended after its preview switch.
|
||||
AUSBOSS_NODES_FilmGrain: { auto: "toggle", auto_amount: "number", auto_size: "number", grain_from: "socket", auto_color: "number" },
|
||||
AUSBOSS_NODES_RefineMask: { preview: "toggle", max_hole_size: "number" },
|
||||
AUSBOSS_NODES_RefineMask: { preview: "toggle", max_hole_size: "number", detail_range: "number", fix_threshold: "number" },
|
||||
AUSBOSS_NODES_SelectFrame: { preview: "toggle" },
|
||||
AUSBOSS_NODES_LoraLoader: { on_missing: "combo", curve: "socket" },
|
||||
// Sockets, which hold no saved value.
|
||||
|
||||
@@ -48,6 +48,12 @@ CORE_NODES = {
|
||||
"RemoveBackground": ("execute", ["bg_removal_model", "image"]),
|
||||
"ImageUpscaleWithModel": ("execute", ["upscale_model", "image"]),
|
||||
"TextGenerate": ("execute", ["clip", "prompt", "max_length", "sampling_mode", "image", "system_prompt"]),
|
||||
"UNETLoader": ("load_unet", ["unet_name", "weight_dtype"]),
|
||||
"CLIPLoader": ("load_clip", ["clip_name", "type", "device"]),
|
||||
"VAELoader": ("load_vae", ["vae_name"]),
|
||||
"TextEncodeFibo2": ("execute", ["clip", "prompt", "negative_prompt", "vae", "images", "width", "height", "batch_size"]),
|
||||
"KSampler": ("sample", ["model", "seed", "steps", "cfg", "sampler_name", "scheduler", "positive", "negative", "latent_image", "denoise"]),
|
||||
"VAEDecode": ("decode", ["samples", "vae"]),
|
||||
}
|
||||
# Read with a fallback while a workflow runs: (module, name, what leans on it).
|
||||
INTERNALS = [
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
"""Each test file runs as a script (scripts/run_python_tests.py), so the
|
||||
unittest.main() at its foot runs only the tests defined above it. A test
|
||||
class written after that guard would never run, and the file would still
|
||||
pass."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
import re
|
||||
import unittest
|
||||
|
||||
TESTS = Path(__file__).resolve().parent
|
||||
GUARD = re.compile(r'^if __name__ == "__main__":', re.M)
|
||||
|
||||
|
||||
class EveryTestRuns(unittest.TestCase):
|
||||
def test_no_test_is_defined_after_the_main_guard(self):
|
||||
late = []
|
||||
for path in sorted(TESTS.glob("test_*.py")):
|
||||
text = path.read_text(encoding="utf-8")
|
||||
guard = GUARD.search(text)
|
||||
if guard and re.search(r"^(?:class|def) ", text[guard.end():], re.M):
|
||||
late.append(path.name)
|
||||
self.assertEqual(late, [])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -506,5 +506,232 @@ class ColourTests(unittest.TestCase):
|
||||
self.assertTrue(bool(torch.isfinite(solid).all()))
|
||||
|
||||
|
||||
class Shelves:
|
||||
"""A stand-in for ComfyUI's folder_paths with several model folders."""
|
||||
|
||||
def __init__(self, root: Path, names=("background_removal", "diffusion_models", "text_encoders", "vae")):
|
||||
self.root = root
|
||||
self.folder_names_and_paths = {}
|
||||
for name in names:
|
||||
(root / name).mkdir(exist_ok=True)
|
||||
self.folder_names_and_paths[name] = ([str(root / name)], {".safetensors"})
|
||||
|
||||
def get_filename_list(self, name):
|
||||
return sorted(path.name for path in (self.root / name).iterdir())
|
||||
|
||||
def get_full_path(self, name, file):
|
||||
path = self.root / name / file
|
||||
return str(path) if path.is_file() else None
|
||||
|
||||
|
||||
class Painter:
|
||||
"""Stand-ins for the ComfyUI nodes RMBG-3.0 runs on, recording their calls."""
|
||||
|
||||
calls = []
|
||||
|
||||
class UNETLoader:
|
||||
def load_unet(self, unet_name, weight_dtype):
|
||||
Painter.calls.append(("unet", unet_name, weight_dtype))
|
||||
return ({"unet": unet_name},)
|
||||
|
||||
class CLIPLoader:
|
||||
def load_clip(self, clip_name, type, device): # noqa: A002 - ComfyUI's own input name
|
||||
Painter.calls.append(("clip", clip_name, type))
|
||||
return (types.SimpleNamespace(patcher="clip patcher", name=clip_name),)
|
||||
|
||||
class VAELoader:
|
||||
def load_vae(self, vae_name):
|
||||
Painter.calls.append(("vae", vae_name))
|
||||
return (types.SimpleNamespace(patcher="vae patcher", name=vae_name),)
|
||||
|
||||
class TextEncodeFibo2:
|
||||
@classmethod
|
||||
def execute(cls, clip, prompt, negative_prompt, vae, images, width, height, batch_size):
|
||||
Painter.calls.append(("encode", prompt, tuple(images["image_1"].shape), width, height))
|
||||
return Output("positive", "negative", {"samples": torch.zeros(1, 128, height // 16, width // 16)})
|
||||
|
||||
class KSampler:
|
||||
def sample(self, model, seed, steps, cfg, sampler_name, scheduler, positive, negative, latent_image, denoise):
|
||||
Painter.calls.append(("sample", seed, steps, cfg, sampler_name, scheduler, denoise))
|
||||
return (latent_image,)
|
||||
|
||||
class VAEDecode:
|
||||
def decode(self, vae, samples):
|
||||
height, width = samples["samples"].shape[2] * 16, samples["samples"].shape[3] * 16
|
||||
red = torch.linspace(0, 1, width).expand(height, width)
|
||||
Painter.calls.append(("decode", height, width))
|
||||
return (torch.stack([red, torch.zeros_like(red), torch.ones_like(red)], dim=-1)[None],)
|
||||
|
||||
|
||||
class Rmbg3Tests(unittest.TestCase):
|
||||
MODEL = "rmbg3_int8_convrot.safetensors"
|
||||
|
||||
def setUp(self):
|
||||
self.root = Path(tempfile.mkdtemp(prefix="ausboss_rmbg3_test_"))
|
||||
self.addCleanup(__import__("shutil").rmtree, self.root, True)
|
||||
self.addCleanup(setattr, fine, "folder_paths", fine.folder_paths)
|
||||
fine.folder_paths = Shelves(self.root)
|
||||
Painter.calls = []
|
||||
nodes = types.ModuleType("nodes")
|
||||
nodes.NODE_CLASS_MAPPINGS = {
|
||||
"LoadBackgroundRemovalModel": Loader, "RemoveBackground": Remover,
|
||||
**{key: getattr(Painter, key) for key in ("UNETLoader", "CLIPLoader", "VAELoader", "TextEncodeFibo2", "KSampler", "VAEDecode")},
|
||||
}
|
||||
self.addCleanup(sys.modules.__setitem__, "nodes", sys.modules.get("nodes")) if "nodes" in sys.modules else self.addCleanup(sys.modules.pop, "nodes", None)
|
||||
sys.modules["nodes"] = nodes
|
||||
self.nodes = nodes
|
||||
fine.forget_subjects()
|
||||
self.addCleanup(fine.forget_subjects)
|
||||
|
||||
def put(self, folder, name):
|
||||
(self.root / folder / name).write_text("weights")
|
||||
|
||||
def all_parts(self):
|
||||
self.put("diffusion_models", self.MODEL)
|
||||
self.put("text_encoders", "qwen3vl_4b_int8_convrot.safetensors")
|
||||
self.put("vae", "flux2-vae.safetensors")
|
||||
|
||||
def test_an_rmbg3_model_joins_the_choices_after_comfyuis_own_folder(self):
|
||||
self.put("background_removal", "birefnet.safetensors")
|
||||
self.put("diffusion_models", "some_other_model.safetensors")
|
||||
self.assertEqual(fine_edge_choices(), [OFF, "birefnet.safetensors"])
|
||||
self.put("diffusion_models", self.MODEL)
|
||||
self.assertEqual(fine_edge_choices(), [OFF, "birefnet.safetensors", self.MODEL])
|
||||
|
||||
def test_off_never_picks_rmbg3_for_the_subject(self):
|
||||
self.put("background_removal", "birefnet.safetensors")
|
||||
self.all_parts()
|
||||
self.assertEqual(subject_model_name(OFF), "birefnet.safetensors")
|
||||
|
||||
def test_it_paints_at_about_one_megapixel_in_steps_of_16_keeping_the_shape(self):
|
||||
for width, height in ((1024, 1024), (912, 1152), (1920, 1080), (300, 200), (4000, 3000)):
|
||||
paint_w, paint_h = fine.rmbg3_size(width, height)
|
||||
self.assertEqual((paint_w % 16, paint_h % 16), (0, 0))
|
||||
self.assertLess(abs(paint_w * paint_h / fine.RMBG3_AREA - 1), 0.05, (width, height))
|
||||
self.assertLess(abs(paint_w / paint_h / (width / height) - 1), 0.02, (width, height))
|
||||
|
||||
def test_the_matte_is_made_the_way_its_template_makes_it_and_fits_the_picture(self):
|
||||
self.all_parts()
|
||||
frame = torch.rand(1, 90, 160, 4)
|
||||
matte = subject_matte(frame, self.MODEL)
|
||||
self.assertEqual((tuple(matte.shape), matte.dtype), ((90, 160), torch.float32))
|
||||
# The stand-in decodes red rising 0 -> 1, green 0, blue 1: only the red
|
||||
# channel runs from black on the left to white on the right.
|
||||
self.assertLess(float(matte[:, :3].mean()), 0.1, "the red channel, scaled back")
|
||||
self.assertGreater(float(matte[:, -3:].mean()), 0.9, "the red channel, scaled back")
|
||||
paint_w, paint_h = fine.rmbg3_size(160, 90)
|
||||
kinds = [call[0] for call in Painter.calls]
|
||||
self.assertEqual(kinds, ["unet", "clip", "vae", "encode", "sample", "decode"])
|
||||
self.assertEqual(Painter.calls[1], ("clip", "qwen3vl_4b_int8_convrot.safetensors", "fibo2"))
|
||||
encode = Painter.calls[3]
|
||||
# Word for word the instruction in Bria's ComfyUI template.
|
||||
self.assertEqual(encode[1], '{"edit_instruction": "Generate a detailed grayscale alpha matte. Map the opaque '
|
||||
'foreground to white and the background to black. Produce soft, anti-aliased grayscale '
|
||||
'gradients at the edges of the subject to represent fine details and transparency."}')
|
||||
self.assertEqual(encode[2:], ((1, paint_h, paint_w, 3), paint_w, paint_h), "stretched to the painted size, never cut")
|
||||
self.assertEqual(Painter.calls[4], ("sample", 42, 4, 1.0, "euler", "simple", 1.0))
|
||||
|
||||
def test_its_parts_are_loaded_once_and_a_picture_asked_once(self):
|
||||
self.all_parts()
|
||||
frame = torch.rand(1, 64, 64, 3)
|
||||
subject_matte(frame, self.MODEL, key="one")
|
||||
subject_matte(frame, self.MODEL, key="one")
|
||||
subject_matte(frame, self.MODEL, key="two")
|
||||
kinds = [call[0] for call in Painter.calls]
|
||||
self.assertEqual((kinds.count("unet"), kinds.count("sample")), (1, 2))
|
||||
|
||||
def test_free_vram_can_unload_all_three_parts(self):
|
||||
self.all_parts()
|
||||
subject_matte(torch.rand(1, 32, 32, 3), self.MODEL)
|
||||
patchers = [getattr(model, "patcher", None) for model in fine.loaded_subject_models()]
|
||||
self.assertEqual(patchers, [{"unet": self.MODEL}, "clip patcher", "vae patcher"])
|
||||
|
||||
def test_birefnet_after_rmbg3_first_takes_rmbg3_out_of_memory(self):
|
||||
self.all_parts()
|
||||
self.put("background_removal", "birefnet.safetensors")
|
||||
unloaded = []
|
||||
management = types.ModuleType("comfy.model_management")
|
||||
management.unload_model_and_clones = unloaded.append
|
||||
management.soft_empty_cache = lambda: unloaded.append("emptied")
|
||||
self.addCleanup(sys.modules.__setitem__, "comfy.model_management", sys.modules.get("comfy.model_management")) if "comfy.model_management" in sys.modules else self.addCleanup(sys.modules.pop, "comfy.model_management", None)
|
||||
sys.modules["comfy.model_management"] = management
|
||||
frame = torch.rand(1, 32, 32, 3)
|
||||
subject_matte(frame, self.MODEL)
|
||||
self.assertEqual(unloaded, [], "RMBG-3.0 on its own unloads nothing")
|
||||
subject_matte(frame, "birefnet.safetensors")
|
||||
self.assertEqual(unloaded, [{"unet": self.MODEL}, "clip patcher", "vae patcher", "emptied"])
|
||||
self.assertEqual(len(fine.loaded_subject_models()), 1, "only BiRefNet is held now")
|
||||
subject_matte(frame, "birefnet.safetensors")
|
||||
self.assertEqual(len(unloaded), 4, "nothing more to drop")
|
||||
|
||||
def watch_unloads(self):
|
||||
unloaded = []
|
||||
management = types.ModuleType("comfy.model_management")
|
||||
management.unload_model_and_clones = unloaded.append
|
||||
management.soft_empty_cache = lambda: unloaded.append("emptied")
|
||||
self.addCleanup(sys.modules.__setitem__, "comfy.model_management", sys.modules.get("comfy.model_management")) if "comfy.model_management" in sys.modules else self.addCleanup(sys.modules.pop, "comfy.model_management", None)
|
||||
sys.modules["comfy.model_management"] = management
|
||||
return unloaded
|
||||
|
||||
def test_a_second_copy_of_rmbg3_takes_the_first_out_of_memory(self):
|
||||
self.all_parts()
|
||||
self.put("diffusion_models", "rmbg3_bf16.safetensors")
|
||||
unloaded = self.watch_unloads()
|
||||
frame = torch.rand(1, 32, 32, 3)
|
||||
subject_matte(frame, self.MODEL)
|
||||
subject_matte(frame, "rmbg3_bf16.safetensors")
|
||||
self.assertEqual(unloaded, [{"unet": self.MODEL}, "clip patcher", "vae patcher", "emptied"])
|
||||
self.assertEqual(len(fine.loaded_subject_models()), 3, "one copy's three parts")
|
||||
|
||||
def test_a_whole_batch_is_asked_about_once_however_long(self):
|
||||
self.all_parts()
|
||||
frames = [torch.rand(1, 24, 24, 3) for _ in range(12)]
|
||||
fine.keep_subjects_for(len(frames))
|
||||
self.addCleanup(fine.keep_subjects_for, 0)
|
||||
for _ in range(2): # the picks, then the fine edge
|
||||
for index, frame in enumerate(frames):
|
||||
subject_matte(frame, self.MODEL, key=f"frame {index}")
|
||||
self.assertEqual([call[0] for call in Painter.calls].count("sample"), 12)
|
||||
|
||||
def test_a_background_removal_file_named_rmbg3_stays_one(self):
|
||||
self.put("background_removal", "rmbg3-backup.safetensors")
|
||||
self.assertFalse(fine.is_rmbg3("rmbg3-backup.safetensors"))
|
||||
self.assertTrue(fine.is_rmbg3(self.MODEL), "a diffusion file, or a workflow's name for one")
|
||||
matte = subject_matte(torch.rand(1, 16, 16, 3), "rmbg3-backup.safetensors")
|
||||
self.assertEqual(tuple(matte.shape), (16, 16))
|
||||
self.assertNotIn("unet", [call[0] for call in Painter.calls])
|
||||
|
||||
def test_a_broken_link_or_a_decoder_only_vae_counts_as_missing(self):
|
||||
self.put("diffusion_models", self.MODEL)
|
||||
self.put("text_encoders", "qwen3vl_4b_int8_convrot.safetensors")
|
||||
self.put("vae", "flux2-vae-decoder.safetensors")
|
||||
(self.root / "vae" / "flux2-vae.safetensors").symlink_to(self.root / "vae" / "gone.safetensors")
|
||||
with self.assertRaises(FileNotFoundError) as raised:
|
||||
subject_matte(torch.rand(1, 32, 32, 3), self.MODEL)
|
||||
message = str(raised.exception)
|
||||
self.assertIn("flux2-vae.safetensors", message)
|
||||
self.assertNotIn("diffusion_models", message, "the model file is there; the VAE is what is missing")
|
||||
|
||||
def test_a_missing_text_reader_or_vae_is_named_with_where_to_get_it(self):
|
||||
self.put("diffusion_models", self.MODEL)
|
||||
with self.assertRaises(FileNotFoundError) as raised:
|
||||
subject_matte(torch.rand(1, 32, 32, 3), self.MODEL)
|
||||
message = str(raised.exception)
|
||||
for part in ("qwen3vl_4b_int8_convrot.safetensors", "flux2-vae.safetensors", "briaai/RMBG-3.0-Comfy"):
|
||||
self.assertIn(part, message)
|
||||
|
||||
def test_a_workflow_naming_an_rmbg3_file_this_machine_lacks_says_where_it_goes(self):
|
||||
with self.assertRaises(FileNotFoundError) as raised:
|
||||
subject_matte(torch.rand(1, 32, 32, 3), self.MODEL)
|
||||
self.assertIn("diffusion_models", str(raised.exception))
|
||||
|
||||
def test_a_comfyui_without_fibo2_gets_a_plain_message(self):
|
||||
self.all_parts()
|
||||
del self.nodes.NODE_CLASS_MAPPINGS["TextEncodeFibo2"]
|
||||
with self.assertRaises(RuntimeError) as raised:
|
||||
subject_matte(torch.rand(1, 32, 32, 3), self.MODEL)
|
||||
self.assertEqual(str(raised.exception), fine.NEEDS_FIBO2)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
"""H3 Prompt Writer: the words its small model is asked, and a node's own wording for each."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
|
||||
from nodes._h3_model_asks import BUILT_IN, parse_asks
|
||||
from nodes._h3_script_helpers import fill_words as fill
|
||||
from nodes._h3_prompt_helpers import write_prompt
|
||||
from nodes._h3_script_helpers import HEARD, NEXT
|
||||
from nodes._h3_tidy_helpers import TIDY_SYSTEM, tidy_script
|
||||
|
||||
|
||||
class ParseTests(unittest.TestCase):
|
||||
def test_empty_or_broken_text_means_the_built_in_wording(self):
|
||||
for value in ("", None, "not json", "[1, 2]", '{"next": 5}', '{"next": " "}'):
|
||||
with self.subTest(value=value):
|
||||
self.assertEqual(parse_asks(value), {})
|
||||
|
||||
def test_only_the_four_known_asks_are_kept(self):
|
||||
asks = parse_asks(json.dumps({"next": " Write {count} lines. ", "elsewhere": "x", "tidy": "Be brief."}))
|
||||
self.assertEqual(asks, {"next": "Write {count} lines.", "tidy": "Be brief."})
|
||||
|
||||
def test_json_nested_too_deep_means_the_built_in_wording(self):
|
||||
self.assertEqual(parse_asks("[" * 100000 + "]" * 100000), {})
|
||||
|
||||
def test_a_very_long_wording_is_cut(self):
|
||||
self.assertEqual(len(parse_asks(json.dumps({"heard": "a" * 50000}))["heard"]), 8000)
|
||||
|
||||
def test_the_built_in_wordings_are_the_ones_the_writer_uses(self):
|
||||
self.assertEqual(BUILT_IN["next"], NEXT)
|
||||
self.assertEqual(BUILT_IN["heard"], HEARD)
|
||||
self.assertEqual(BUILT_IN["tidy"], TIDY_SYSTEM)
|
||||
|
||||
|
||||
class FillTests(unittest.TestCase):
|
||||
def test_fill_matches_format_for_the_built_in_wording(self):
|
||||
self.assertEqual(fill(NEXT, seconds=8, first="she waves", count=3), NEXT.format(seconds=8, first="she waves", count=3))
|
||||
|
||||
def test_braces_in_the_filled_in_words_stay_as_typed(self):
|
||||
line = "A worker pins a sign reading {count} to the wall."
|
||||
self.assertIn(line, fill(NEXT, seconds=8, first=line, count=2))
|
||||
|
||||
def test_other_braces_in_a_users_wording_stay_as_typed(self):
|
||||
self.assertEqual(fill("Make {count} lines {like this} {seconds}", count=2), "Make 2 lines {like this} {seconds}")
|
||||
|
||||
|
||||
class UseTests(unittest.TestCase):
|
||||
def test_the_next_moments_and_the_sound_use_the_nodes_wording(self):
|
||||
asked = []
|
||||
|
||||
def ask(question, longest):
|
||||
asked.append(question)
|
||||
return ""
|
||||
|
||||
write_prompt("A woman walks into the kitchen.", seconds=8.0, ask=ask, asks={"next": "NEXT {count} after {first}", "heard": "HEAR {lines}"})
|
||||
self.assertTrue(asked[0].startswith("NEXT "), asked)
|
||||
self.assertIn("after A woman walks into the kitchen", asked[0])
|
||||
self.assertTrue(asked[1].startswith("HEAR A woman walks"), asked)
|
||||
|
||||
def test_without_its_own_wording_the_writer_asks_as_before(self):
|
||||
asked = []
|
||||
write_prompt("A woman walks into the kitchen.", seconds=8.0, ask=lambda question, longest: asked.append(question) or "")
|
||||
self.assertTrue(asked[0].startswith("This is a 8.0 second video."), asked)
|
||||
|
||||
def test_tidy_up_uses_the_nodes_instructions(self):
|
||||
systems = []
|
||||
|
||||
def ask(system, line, longest):
|
||||
systems.append(system)
|
||||
return ""
|
||||
|
||||
tidy_script("@1 waves\n@2 says \"hi\"", ask, system="MY RULES")
|
||||
self.assertEqual(set(systems), {"MY RULES"})
|
||||
|
||||
|
||||
class NodeTests(unittest.TestCase):
|
||||
def test_the_wording_is_one_optional_input_after_the_others(self):
|
||||
from nodes.node_h3_prompt_writer import AusBossH3PromptWriter
|
||||
optional = list(AusBossH3PromptWriter.INPUT_TYPES()["optional"])
|
||||
self.assertEqual(optional[-1], "model_asks")
|
||||
|
||||
def test_a_run_with_the_nodes_wording_and_no_model_still_writes(self):
|
||||
from nodes.node_h3_prompt_writer import AusBossH3PromptWriter
|
||||
import torch
|
||||
result = AusBossH3PromptWriter().run(
|
||||
"@1 waves.", 8, picture_1=torch.zeros(1, 64, 64, 3), model_asks=json.dumps({"next": "x"}), tidy=True)
|
||||
self.assertIn("waves", result["result"][0])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -125,6 +125,14 @@ class ReadingTests(unittest.TestCase):
|
||||
self.assertEqual((script.camera, script.look, script.sound, script.music), ("handheld", "anime", "rain", "N/A"))
|
||||
self.assertEqual(len(script.moments), 1)
|
||||
|
||||
def test_none_in_sound_is_no_sound_and_keeps_the_music(self):
|
||||
for typed in ("none", "None.", "no sound", "silent", "n/a", "off"):
|
||||
parts = parts_of(f"sound: {typed}\nmusic: a slow piano\n" + LINES, jobs={1: "start on it"})
|
||||
self.assertEqual((parts["overall_soundscape"], parts["non_diegetic_music"]), ("N/A", "A slow piano."), typed)
|
||||
for typed in ("none", "No music.", "silent"):
|
||||
parts = parts_of(f"sound: rain\nmusic: {typed}\n" + LINES, jobs={1: "start on it"})
|
||||
self.assertEqual((parts["overall_soundscape"], parts["non_diegetic_music"]), ("Rain.", "N/A"), typed)
|
||||
|
||||
def test_camera_and_sound_lines_belong_to_their_shot(self):
|
||||
script = read_script("she runs\ncamera: orbit\n\nshe stops\nsound: rain on glass\n\nmusic: a slow piano")
|
||||
self.assertEqual((script.moments[0].camera, script.moments[1].sound), ("orbit", "rain on glass"))
|
||||
@@ -293,6 +301,21 @@ class ScriptPartsTests(unittest.TestCase):
|
||||
self.assertEqual(lines[1], "[Shot 2] At 00:03.000, the camera cuts to a close-up of her hand.")
|
||||
self.assertEqual(lines[2], "[Shot 3] At 00:06.000, the camera cuts to a new place. The door opens.")
|
||||
|
||||
def test_a_framing_typed_without_a_or_the_is_still_a_framing(self):
|
||||
for typed, cut in (
|
||||
("Close-up of her muddy boots on the rocks.", "a close-up of her muddy boots on the rocks."),
|
||||
("Extreme close-up on her eyes.", "an extreme close-up on her eyes."),
|
||||
("Wide shot of the whole valley.", "a wide shot of the whole valley."),
|
||||
("Overhead view of the table.", "an overhead view of the table."),
|
||||
("POV from the driver's seat.", "a POV from the driver's seat."),
|
||||
):
|
||||
lines = shots("she walks\n\n" + typed, seconds=8)
|
||||
self.assertEqual(lines[1], "[Shot 2] At 00:04.000, the camera cuts to " + cut, typed)
|
||||
self.assertNotIn("new place", write_prompt("she walks\n\n" + typed, seconds=8), typed)
|
||||
# A line that only starts like one is still something that happens.
|
||||
for typed in ("Wide awake, she sits up.", "Shot glasses line the bar.", "Medium rare steaks sizzle."):
|
||||
self.assertIn("the camera cuts to a new place.", shots("she walks\n\n" + typed, seconds=8)[1], typed)
|
||||
|
||||
def test_one_take_overrides_a_blank_line(self):
|
||||
self.assertNotIn("cuts to", " ".join(shots("one take\nshe walks\n\nshe stops")))
|
||||
|
||||
@@ -437,14 +460,46 @@ class PictureJobTests(unittest.TestCase):
|
||||
self.assertIn("<Subject 1> sits down in <Subject 2>.", parts["detailed_description"])
|
||||
|
||||
def test_a_number_with_no_picture_says_what_to_do(self):
|
||||
with self.assertRaisesRegex(ValueError, "@2 has no picture. Turn Picture 2 on"):
|
||||
# Off and not connected look the same here, so the advice covers both.
|
||||
with self.assertRaisesRegex(ValueError, "^@2 has no picture: connect or turn on Picture 2, or take @2 out of your script.$"):
|
||||
write_prompt("@2 runs", jobs={1: "person"})
|
||||
|
||||
def test_a_number_past_four_is_not_a_picture(self):
|
||||
for typed in ("@5 jumps into the lake.", "@10 waves."):
|
||||
with self.assertRaisesRegex(ValueError, r"^There are four pictures, @1 to @4\. Take @(5|10) out of your script\.$"):
|
||||
write_prompt(typed, jobs={1: "person"})
|
||||
|
||||
def test_only_one_picture_starts_the_clip(self):
|
||||
with self.assertRaisesRegex(ValueError, '^Pictures 1 and 2 are both "start on it". The clip starts on one picture, so pick another job for Picture 2.$'):
|
||||
write_prompt("She walks.", jobs={1: "start on it", 2: "start on it"})
|
||||
|
||||
def test_only_one_picture_ends_the_clip(self):
|
||||
with self.assertRaisesRegex(ValueError, '^Pictures 2 and 3 are both "end on it". The clip ends on one picture, so pick another job for Picture 3.$'):
|
||||
write_prompt("She walks.", jobs={1: "person", 2: "end on it", 3: "end on it"})
|
||||
|
||||
def test_a_line_with_no_closing_quote_is_still_spoken(self):
|
||||
# A closing quote is easy to miss on a phone; the words run to the end of the line.
|
||||
self.assertIn("<d>[English] Wait for me", write_prompt('He says "Wait for me', jobs={1: "start on it"}))
|
||||
both = write_prompt('He shouts "Stop!" and she says "Why', jobs={1: "start on it"})
|
||||
self.assertIn("<d>[English] Stop!</d>", both)
|
||||
self.assertIn("<d>[English] Why", both)
|
||||
# A quote that only measures something is left alone.
|
||||
self.assertNotIn("<d>", write_prompt('A 12" record spins on the turntable.', jobs={1: "start on it"}))
|
||||
|
||||
def test_the_timeline_warns_before_the_run(self):
|
||||
self.assertIn("@2 has no picture", script_report("@2 runs", 8, {1: "person"})["warning"])
|
||||
self.assertIn("no line names @2", script_report("@1 runs", 8, {1: "person", 2: "person"})["warning"])
|
||||
self.assertEqual(script_report("@1 runs", 8, {1: "person"})["warning"], "")
|
||||
|
||||
def test_a_style_picture_named_as_a_thing_gets_a_warning(self):
|
||||
jobs = {1: "person", 3: "style"}
|
||||
for line in ("@1 wears @3.", "@1 picks up @3.", "@1 walks in. Then @1 stands in @3."):
|
||||
self.assertIn("Picture 3 is a style", script_report(line, 8, jobs)["warning"], line)
|
||||
for line in ("@1 walks in. In the style of @3.", "@1 walks in, drawn like @3.", "@1 walks in. Use the look of @3.", "@1 walks in."):
|
||||
self.assertEqual(script_report(line, 8, jobs)["warning"], "", line)
|
||||
# It only warns: the run still goes ahead.
|
||||
self.assertIn("visual style of <Picture 2>", write_prompt("@1 wears @3.", jobs=jobs))
|
||||
|
||||
def test_lines_with_no_numbers_still_work_with_two_people(self):
|
||||
parts = parts_of("They sit down on a bench.", jobs={1: "person", 2: "person"})
|
||||
self.assertIn("<Subject 1> and <Subject 2> are in the shot. They sit down on a bench.", parts["detailed_description"])
|
||||
@@ -682,11 +737,94 @@ class EverydayLineTests(unittest.TestCase):
|
||||
self.assertEqual([moment.cut for moment in script.moments], [False, True])
|
||||
self.assertEqual(read_script("camera: handheld").camera, "handheld")
|
||||
|
||||
def test_words_shown_on_screen_end_their_sentence(self):
|
||||
shot = parts_of('@1 holds a sign reading "CLOSED" and says "Sorry, folks."', seconds=5, jobs={1: "person"})["detailed_description"]
|
||||
self.assertIn('holds a sign reading "CLOSED". <Subject 1> stays silent', shot)
|
||||
self.assertTrue(parts_of('@1 holds a sign reading "OPEN!"', seconds=5, jobs={1: "person"})["detailed_description"].endswith('reading "OPEN!"'))
|
||||
|
||||
def test_bold_and_italic_marks_are_not_part_of_the_words(self):
|
||||
for typed in ("**@1** walks in.", "*@1 walks in.*", "_@1_ walks in.", "__@1 walks in__."):
|
||||
shot = parts_of(typed, seconds=5, jobs={1: "person"})["detailed_description"]
|
||||
self.assertTrue(shot.endswith("[Shot 1] <Subject 1> walks in."), (typed, shot))
|
||||
# A name with an underscore in it, and a star rating, stay as typed.
|
||||
self.assertIn("my_new_file", moments("She opens my_new_file on the laptop.")[0])
|
||||
self.assertIn("5*", moments("He gives it 5* and nods.")[0])
|
||||
|
||||
def test_what_follows_a_spoken_line_keeps_who_does_it(self):
|
||||
def shot(line, jobs={1: "person"}):
|
||||
return parts_of(line, seconds=5, jobs=jobs)["detailed_description"]
|
||||
|
||||
# What they do next comes after the line, with who does it.
|
||||
waves = shot('@1 says "Hi" and waves.')
|
||||
self.assertIn("closes the lips. <Subject 1> waves.", waves)
|
||||
self.assertNotIn("and waves", waves)
|
||||
self.assertIn("closes the lips. <Subject 1> sprints away.", shot('She shouts "Run!" and sprints away.'))
|
||||
# How they say it comes before the line.
|
||||
self.assertIn("[Shot 1] <Subject 1> speaks slowly. <Subject 1> (S1) says,", shot('@1 says "Hi" slowly.'))
|
||||
self.assertIn("<Subject 1> speaks to the camera. <Subject 1> (S1) says,", shot('She says "Hi" to the camera.'))
|
||||
# A voice nobody sees: the person on screen still does what follows.
|
||||
self.assertTrue(shot('@1 hears a voice off screen say "Dinner!" and looks up.').endswith("<Subject 1> looks up."))
|
||||
# Something that speaks and is in no picture keeps its own name.
|
||||
self.assertIn("The card reader beeps.", shot('The card reader says "Declined" and beeps.', {1: "start on it"}))
|
||||
# Words in front of the line stay as they were.
|
||||
self.assertIn("[Shot 1] <Subject 1> looks up and waves.", shot('@1 looks up and says "Hi" and waves.'))
|
||||
|
||||
def test_a_shout_typed_without_quotes_is_still_said(self):
|
||||
def said(line):
|
||||
return [moment.speech for moment in read_script(line).moments]
|
||||
|
||||
self.assertEqual(said("he yells wait"), ["Wait"])
|
||||
self.assertEqual(said("He yells WAIT."), ["Wait"])
|
||||
self.assertEqual(said("she whispers come here"), ["Come here"])
|
||||
self.assertEqual(said("@1 says hi"), ["Hi"])
|
||||
# Where or how they shout is not something said.
|
||||
for line in ("he yells at the dog", "she shouts for help", "he says nothing", "she whispers to @2",
|
||||
"he yells loudly", "she says it again", "the crowd shouts back"):
|
||||
self.assertEqual(said(line), [""], line)
|
||||
shot = parts_of("guy runs to bus misses it\nhe yells wait", seconds=5, jobs={1: "start on it"})["detailed_description"]
|
||||
self.assertIn("<d>[English] Wait.</d>", shot)
|
||||
self.assertNotIn("WAIT", shot)
|
||||
|
||||
def test_two_people_named_in_words_each_say_their_own_line(self):
|
||||
typed = 'A barista slides a cup across the counter and says "One oat latte, extra hot."\nThe customer laughs and says "You remembered!"'
|
||||
shot = parts_of(typed, seconds=8, jobs={1: "start on it"})["detailed_description"]
|
||||
self.assertIn('The barista (S1) says, <d>[English] One oat latte, extra hot.</d>', shot)
|
||||
self.assertIn('The customer (S2) says, <d>[English] You remembered!</d>', shot)
|
||||
self.assertIn("The jaw and lips of the customer move", shot)
|
||||
self.assertNotIn("<Subject 1> (S1)", shot)
|
||||
# One person named in words is still the person in the picture.
|
||||
one = parts_of('A street vendor holds up an orange and says "Fresh!"', seconds=5, jobs={1: "start on it"})["detailed_description"]
|
||||
self.assertIn("<Subject 1> (S1) says, <d>[English] Fresh!</d>", one)
|
||||
|
||||
def test_how_a_line_is_said_stays_in_the_prompt(self):
|
||||
def shot(line, **more):
|
||||
return parts_of(line, seconds=5, jobs={1: "person"}, **more)["detailed_description"]
|
||||
|
||||
# Whispered, shouted and sung lines keep their word.
|
||||
self.assertIn("<Subject 1> (S1) whispers, <d>[English] Stay quiet.</d>", shot('@1 whispers "Stay quiet."'))
|
||||
self.assertIn("<Subject 1> leans in. <Subject 1> (S1) shouts, <d>[English] Run!</d>", shot('@1 leans in and shouts "Run!"'))
|
||||
self.assertIn("(S1) sings, <d>", shot('She sings "La la la"'))
|
||||
self.assertIn("(S1) calls out, <d>", shot('He call out "Over here!"'))
|
||||
self.assertIn("<Subject 1> sings softly. <Subject 1> (S1) sings, <d>", shot('She sings "La la la" softly.'))
|
||||
# So do the words typed between "says" and the line.
|
||||
self.assertIn("(S1) says quietly, <d>[English] Hello.</d>", shot('@1 says quietly "Hello."'))
|
||||
self.assertIn("(S1) mutters under his breath, <d>", shot('@1 mutters under his breath "Not again."'))
|
||||
# A plain line is still "says", and so is one with no such word.
|
||||
self.assertIn("(S1) says, <d>", shot('@1 says "Hello."'))
|
||||
self.assertIn("(S1) says, <d>", shot('@1 tells him "Hello."'))
|
||||
self.assertIn("(S1) says, <d>", shot('@1: "Hello."'))
|
||||
# A voiceover keeps the one phrase H3 knows it by.
|
||||
self.assertIn("(S1) says in an off-screen voiceover, <d>", shot('@1 whispers in voiceover "Stay quiet."'))
|
||||
|
||||
def test_every_quote_is_said_by_who_says_it(self):
|
||||
script = read_script('Maya says "Hi" while Ben replies "Bye".')
|
||||
self.assertEqual([moment.speech for moment in script.moments], ["Hi", "Bye"])
|
||||
self.assertEqual(read_script("She says 'come here' and waves.").moments[0].speech, "come here")
|
||||
self.assertEqual(read_script("She can't wait, it's 'late'.").moments[0].speech, "")
|
||||
# An apostrophe inside the words does not end them.
|
||||
self.assertEqual(read_script("She says 'I don't know.'").moments[0].speech, "I don't know.")
|
||||
self.assertEqual(read_script("She says ‘It’s fine, don’t worry.’ and leaves.").moments[0].speech, "It's fine, don't worry.")
|
||||
self.assertIn("<d>[English] I don't know.</d>", write_prompt("She says 'I don't know.'", jobs={1: "start on it"}))
|
||||
for line in ('She says "Wait" in voiceover.', 'VO: "Come back."'):
|
||||
moment = read_script(line).moments[0]
|
||||
self.assertTrue(moment.voiceover, line)
|
||||
@@ -1197,6 +1335,23 @@ class AskTests(unittest.TestCase):
|
||||
lines = shots("she flies away", seconds=10, ask=self.ask(moments='She rises.\nShe says "bye."\nShe vanishes from sight.'))
|
||||
self.assertEqual(count_moments(lines[0]), 3)
|
||||
|
||||
def test_what_a_chat_model_says_around_its_answer_is_left_out(self):
|
||||
chatty = "Sure! Here are the next moments:\n**Moment 2:** She looks at the cup.\n0:04 She lifts it.\nLet me know if you want more!"
|
||||
line = shots("she sits at a cafe table", seconds=10, ask=self.ask(chatty))[0]
|
||||
self.assertIn("<Subject 1> looks at the cup. At 00:06.667, <Subject 1> lifts it.", line)
|
||||
for word in ("Sure", "Moment", "0:04", "Let me know", "*"):
|
||||
self.assertNotIn(word, line)
|
||||
|
||||
def test_a_refusal_is_not_a_moment_or_a_sound(self):
|
||||
sorry = "I'm sorry, but I can't help with that request."
|
||||
parts = parts_of("she sits at a cafe table", seconds=10, ask=self.ask(sorry, sorry), jobs={1: "start on it"})
|
||||
self.assertNotIn("sorry", parts["detailed_description"])
|
||||
self.assertEqual(parts["overall_soundscape"], "The steady sound of the place continues throughout.")
|
||||
# An answer that names a picture is the model echoing the question.
|
||||
echoed = parts_of("she sits at a cafe table", seconds=10, ask=self.ask("@1 looks at @7.", "@1 hums, @2 enters."), jobs={1: "start on it"})
|
||||
self.assertNotIn("looks at", echoed["detailed_description"])
|
||||
self.assertNotIn("@", echoed["overall_soundscape"])
|
||||
|
||||
def test_the_small_model_reads_each_picture_by_its_job(self):
|
||||
asked = []
|
||||
|
||||
@@ -1560,7 +1715,7 @@ class SoundAndMusicBoxTests(unittest.TestCase):
|
||||
|
||||
def test_the_boxes_are_appended_after_every_older_input(self):
|
||||
names = list(AusBossH3PromptWriter.INPUT_TYPES()["optional"])
|
||||
self.assertEqual(names[-5:], ["sound", "music", "clip_sound", "full_prompt", "tidy"])
|
||||
self.assertEqual(names[-6:], ["sound", "music", "clip_sound", "full_prompt", "tidy", "model_asks"])
|
||||
|
||||
|
||||
def spoken(stretches, seconds, rate=16000, noise=0.002, seed=3):
|
||||
@@ -1737,6 +1892,26 @@ class ClipSoundTests(unittest.TestCase):
|
||||
|
||||
|
||||
class PromptBugBatchTests(unittest.TestCase):
|
||||
def test_two_swaps_each_name_who_goes_on_their_own_line(self):
|
||||
script = (
|
||||
"The young man in the grey cardigan with headphones on the left is replaced by @1, a cartoon 3D wooden log character with big eyes.\n"
|
||||
"The young woman with dark bangs in the white blouse on the right is replaced by @2, a young woman with long red hair."
|
||||
)
|
||||
parts = parts_of(script, seconds=6, jobs={1: "person", 2: "person"}, video="swap the person")
|
||||
self.assertIn("<Subject 1> is the young man in the grey cardigan with headphones on the left in <Video 1>", parts["subject_definitions"])
|
||||
self.assertIn("<Subject 2> is the young woman with dark bangs in the white blouse on the right in <Video 1>", parts["subject_definitions"])
|
||||
self.assertNotIn("Do not show a cartoon", parts["detailed_description"])
|
||||
|
||||
def test_a_description_after_the_picture_is_how_the_new_person_looks(self):
|
||||
script = "The man in front is replaced by @1, a 3D animated game character with long orange-red hair and a blue dress."
|
||||
parts = parts_of(script, seconds=6, jobs={1: "person"}, video="swap the person")
|
||||
self.assertIn("<Subject 1> is the man in front in <Video 1>", parts["subject_definitions"])
|
||||
self.assertIn("this appearance: a 3D animated game character with long orange-red hair and a blue dress", parts["subject_definitions"])
|
||||
typed = "The man in front is replaced by @1, a man in a hat.\n@1 looks like a woman with red hair"
|
||||
kept = parts_of(typed, seconds=6, jobs={1: "person"}, video="swap the person")["subject_definitions"]
|
||||
self.assertIn("this appearance: a woman with red hair", kept)
|
||||
self.assertNotIn("a man in a hat", kept)
|
||||
|
||||
def test_a_swap_action_line_does_not_name_who_goes(self):
|
||||
for script in ("@1 dances.", "He dances."):
|
||||
text = write_prompt(script, seconds=6, jobs={1: "person"}, video="swap the person")
|
||||
|
||||
@@ -64,9 +64,10 @@ class SwapAppearanceTests(unittest.TestCase):
|
||||
with self.assertRaises(ValueError):
|
||||
self.parts(text)
|
||||
|
||||
def test_anchored_line_only_and_other_jobs_are_untouched(self):
|
||||
for text in ['Put @1 looks like a friend here.', '@1 looks like a woman and says "Hello".']:
|
||||
self.assertEqual(swap_appearances(text, {1: 'person'}, 'swap the person'), (text, {}))
|
||||
def test_a_looks_in_a_spoken_line_is_read_and_other_jobs_are_untouched(self):
|
||||
# The look is read; the line stays in the script for what is said.
|
||||
text = '@1 looks like a woman and says "Hello".'
|
||||
self.assertEqual(swap_appearances(text, {1: 'person'}, 'swap the person'), (text, {1: 'a woman'}))
|
||||
for job in ['', 'copy its moves', 'change something', 'keep going']:
|
||||
self.assertEqual(swap_appearances(SCRIPT, {1: 'person'}, job), (SCRIPT, {}))
|
||||
legacy = '\r\n @1 replaces the man in the hat.\r\n'
|
||||
|
||||
@@ -0,0 +1,227 @@
|
||||
"""How H3 Prompt Writer reads a swap's typed lines: who goes, how each new person looks, and what it did not use.
|
||||
|
||||
Each row is a way people really type a swap. Before the reader, about a third of these lost words without a word
|
||||
to the user, or put the new person's description where the person who goes belongs.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
|
||||
from nodes._h3_swap_reader import read_swap, sentences
|
||||
|
||||
ONE = {1: "person"}
|
||||
TWO = {1: "person", 2: "person"}
|
||||
THREE = {1: "person", 2: "person", 3: "person"}
|
||||
|
||||
# (typed, jobs, who goes by slot, words each slot's look must hold, words the not-used list must hold)
|
||||
ROWS = [
|
||||
("Replace the man in red with @1", ONE, {1: "the man in red"}, {}, []),
|
||||
("swap the guy on the left for @1", ONE, {1: "the guy on the left"}, {}, []),
|
||||
("the guy on the left (@1)", ONE, {1: "the guy on the left"}, {}, []),
|
||||
("@1 replaces the guy on the left", ONE, {1: "the guy on the left"}, {}, []),
|
||||
("@1 is the new guy, replacing the old bartender", ONE, {1: "the old bartender"}, {}, []),
|
||||
("Elon is @1, he replaces the man at the counter", ONE, {1: "the man at the counter"}, {}, []),
|
||||
("Elon is @1 and he replaces the man at the counter", ONE, {1: "the man at the counter"}, {}, []),
|
||||
("put @1 in place of the dancer in the back", ONE, {1: "the dancer in the back"}, {}, []),
|
||||
("Replace the man in red with @1, a guy with a beard and glasses", ONE, {1: "the man in red"}, {1: "a guy with a beard and glasses"}, []),
|
||||
("Replace the man in red with @1 who has a beard", ONE, {1: "the man in red"}, {1: "a beard"}, []),
|
||||
("replace the man in red with @1 (bearded, glasses)", ONE, {1: "the man in red"}, {1: "bearded, glasses"}, []),
|
||||
("replace the singer with @1. @1 is a tall woman with red hair.", ONE, {1: "the singer"}, {1: "a tall woman with red hair"}, []),
|
||||
("replace the singer with @1. she has red hair", ONE, {1: "the singer"}, {1: "red hair"}, []),
|
||||
("replace the singer with @1\nshe has red hair", ONE, {1: "the singer"}, {1: "red hair"}, []),
|
||||
("replace the singer with @1, wearing a black suit", ONE, {1: "the singer"}, {1: "a black suit"}, []),
|
||||
("replace the singer with @1 in a black suit", ONE, {1: "the singer"}, {1: "a black suit"}, []),
|
||||
("replace the singer with @1\n@1 wears a black suit", ONE, {1: "the singer"}, {1: "a black suit"}, []),
|
||||
("replace the man in the clip with @1's face", ONE, {1: "the man"}, {}, []),
|
||||
("the barista is replaced by @1, a woman in her 40s with short grey hair", ONE, {1: "the barista"}, {1: "short grey hair"}, []),
|
||||
("Replace the man on the left, who is wearing a hat, with @1", ONE, {1: "the man on the left, who is wearing a hat"}, {}, []),
|
||||
("replace the woman who is walking with @1", ONE, {1: "the woman who is walking"}, {}, []),
|
||||
("@1 replaces the man, and the camera zooms in", ONE, {1: "the man"}, {}, ["the camera zooms in"]),
|
||||
("@1 replaces the man; the camera zooms in at 3s", ONE, {1: "the man"}, {}, ["the camera zooms in"]),
|
||||
('replace the man with @1, a guy with a beard. he says "hi there"', ONE, {1: "the man"}, {1: "a guy with a beard"}, []),
|
||||
('Replace the man with @1, a guy with a beard, and he says "hi there"', ONE, {1: "the man"}, {1: "a guy with a beard"}, []),
|
||||
('replace the man at the counter with @1 and have him say "i\'ll take two"', ONE, {1: "the man at the counter"}, {}, []),
|
||||
("replace the man with @1 (a tall woman)", ONE, {1: "the man"}, {1: "a tall woman"}, []),
|
||||
("@1 is Elon, a man with a beard, and he replaces the man at the counter", ONE, {1: "the man at the counter"}, {1: "a man with a beard"}, []),
|
||||
("Elon (@1) replaces the man at the counter", ONE, {1: "the man at the counter"}, {}, []),
|
||||
("replace the man at the counter with Elon (@1)", ONE, {1: "the man at the counter"}, {}, []),
|
||||
("replace the man at the counter with Elon, @1", ONE, {1: "the man at the counter"}, {}, []),
|
||||
("REPLACE THE MAN WITH @1. @1 LOOKS LIKE A TALL WOMAN", ONE, {1: "THE MAN"}, {1: "A TALL WOMAN"}, []),
|
||||
("replace the man with @1. make the background a beach", ONE, {1: "the man"}, {}, ["make the background a beach"]),
|
||||
("replace the man with @1 and make her smile", ONE, {1: "the man"}, {}, ["make her smile"]),
|
||||
("replace the man with @1 and add a hat", ONE, {1: "the man"}, {}, ["add a hat"]),
|
||||
("replace the man with @1. she is happy", ONE, {1: "the man"}, {}, ["she is happy"]),
|
||||
("replace Mr. Smith with @1", ONE, {1: "Mr. Smith"}, {}, []),
|
||||
("@1 dances", ONE, {}, {}, ["@1 dances"]),
|
||||
("Swap him out for @1", ONE, {}, {}, []),
|
||||
("The man in front is replaced by @1, a 3D animated game character with a blue body suit, brown hair tied in buns.", ONE,
|
||||
{1: "the man in front"}, {1: "a 3D animated game character with a blue body suit, brown hair tied in buns"}, []),
|
||||
("replace the singer with @1. keep the clip's clothes", ONE, {1: "the singer"}, {}, []),
|
||||
("the man in the hat", ONE, {1: "the man in the hat"}, {}, []),
|
||||
# Two or three people.
|
||||
("@1 replaces the man on the left, @2 replaces the woman on the right", TWO, {1: "the man on the left", 2: "the woman on the right"}, {}, []),
|
||||
("@1 the man on the left. @2 the woman in red.", TWO, {1: "the man on the left", 2: "the woman in red"}, {}, []),
|
||||
("replace the man with @1 and the woman with @2", TWO, {1: "the man", 2: "the woman"}, {}, []),
|
||||
("replace the man with @1 and replace the woman with @2", TWO, {1: "the man", 2: "the woman"}, {}, []),
|
||||
("Replace the man in red with @1 and the girl in blue with @2", TWO, {1: "the man in red", 2: "the girl in blue"}, {}, []),
|
||||
("swap @1 for the guy on the left and @2 for the girl on the right", TWO, {1: "the guy on the left", 2: "the girl on the right"}, {}, []),
|
||||
("@1 is Elon, he replaces the man on the left. @2 is Dario, he replaces the woman on the right", TWO,
|
||||
{1: "the man on the left", 2: "the woman on the right"}, {}, []),
|
||||
("the guy on the left (@1) and the guy on the right (@2)", TWO, {1: "the guy on the left", 2: "the guy on the right"}, {}, []),
|
||||
("the guy on the left is @1, the guy on the right is @2", TWO, {1: "the guy on the left", 2: "the guy on the right"}, {}, []),
|
||||
("left guy -> @1, right guy -> @2", TWO, {1: "left guy", 2: "right guy"}, {}, []),
|
||||
("@1: the man on the left\n@2: the woman on the right", TWO, {1: "the man on the left", 2: "the woman on the right"}, {}, []),
|
||||
("replace the man on the left with @1, a bearded man. replace the woman on the right with @2, a girl with pigtails", TWO,
|
||||
{1: "the man on the left", 2: "the woman on the right"}, {1: "a bearded man", 2: "a girl with pigtails"}, []),
|
||||
("@1, a bearded man, replaces the one on the left. @2, a girl with pigtails, replaces the one on the right.", TWO,
|
||||
{1: "the one on the left", 2: "the one on the right"}, {1: "a bearded man", 2: "a girl with pigtails"}, []),
|
||||
("@1 looks like a bearded man\n@2 looks like a girl with pigtails\nswap the left person for @1 and the right person for @2", TWO,
|
||||
{1: "the left person", 2: "the right person"}, {1: "a bearded man", 2: "a girl with pigtails"}, []),
|
||||
("both people are replaced, @1 on the left and @2 on the right", TWO, {1: "the person on the left", 2: "the person on the right"}, {}, []),
|
||||
('@1 replaces the man on the left and says "hello". @2 replaces the woman on the right and says "hi"', TWO,
|
||||
{1: "the man on the left", 2: "the woman on the right"}, {}, []),
|
||||
("the woman on the right is replaced by @2 and the man on the left is replaced by @1", TWO,
|
||||
{1: "the man on the left", 2: "the woman on the right"}, {}, []),
|
||||
("replace the man with @2 and the woman with @1", TWO, {1: "the woman", 2: "the man"}, {}, []),
|
||||
("@2 replaces the man and @1 replaces the woman", TWO, {1: "the woman", 2: "the man"}, {}, []),
|
||||
("@1 replaces the man on the left and @2 the woman on the right", TWO, {1: "the man on the left", 2: "the woman on the right"}, {}, []),
|
||||
("@1 (bearded man) replaces the man on the left, @2 (girl with pigtails) replaces the woman on the right", TWO,
|
||||
{1: "the man on the left", 2: "the woman on the right"}, {1: "bearded man", 2: "girl with pigtails"}, []),
|
||||
("Elon is @1, Dario is @2. Elon replaces the man on the left and Dario the woman on the right.", TWO,
|
||||
{1: "the man on the left", 2: "the woman on the right"}, {}, []),
|
||||
("the man on the left becomes @1 and the woman on the right becomes @2", TWO, {1: "the man on the left", 2: "the woman on the right"}, {}, []),
|
||||
("@1 replaces Mr. Smith. @2 replaces Dr. Jones.", TWO, {1: "Mr. Smith", 2: "Dr. Jones"}, {}, []),
|
||||
("The young man in the grey cardigan with headphones on the left is replaced by @1, a cartoon 3D wooden log character with big eyes.\n"
|
||||
"The young woman with dark bangs in the white blouse on the right is replaced by @2, a young woman with long red hair.", TWO,
|
||||
{1: "the young man in the grey cardigan with headphones on the left", 2: "the young woman with dark bangs in the white blouse on the right"},
|
||||
{1: "a cartoon 3D wooden log character with big eyes", 2: "a young woman with long red hair"}, []),
|
||||
("the man on the left\nthe woman on the right", TWO, {1: "the man on the left", 2: "the woman on the right"}, {}, []),
|
||||
("@1 replaces the man at the bar, @2 replaces the woman, and @3 replaces the kid", THREE,
|
||||
{1: "the man at the bar", 2: "the woman", 3: "the kid"}, {}, []),
|
||||
]
|
||||
|
||||
|
||||
class SwapReaderTests(unittest.TestCase):
|
||||
def test_each_way_people_type_a_swap(self):
|
||||
for typed, jobs, goes, looks, unused in ROWS:
|
||||
with self.subTest(typed=typed):
|
||||
read = read_swap(typed, jobs)
|
||||
self.assertEqual({slot: who.lower() for slot, who in read.goes.items()},
|
||||
{slot: who.lower() for slot, who in goes.items()}, "who goes")
|
||||
for slot, words in looks.items():
|
||||
self.assertIn(words.lower(), read.descriptions.get(slot, "").lower(), f"how @{slot} looks")
|
||||
self.assertEqual(set(read.descriptions) - set(looks), set(), "a look nobody typed")
|
||||
said = " | ".join(read.unused).lower()
|
||||
for words in unused:
|
||||
self.assertIn(words.lower(), said, "not used")
|
||||
if not unused:
|
||||
self.assertEqual(read.unused, [], "words left over")
|
||||
|
||||
def test_clothes_after_and_are_worn_not_part_of_the_look(self):
|
||||
for typed in ("@1 has short red hair and wears a leather jacket.", "@1 is a man with short red hair and is wearing a leather jacket."):
|
||||
with self.subTest(typed=typed):
|
||||
read = read_swap("Replace the man with @1. " + typed, ONE)
|
||||
self.assertEqual(read.wears.get(1), ["a leather jacket"])
|
||||
self.assertNotIn("wear", " ".join(read.looks.get(1, [])))
|
||||
self.assertEqual(read.unused, [])
|
||||
|
||||
def test_an_ask_after_a_quoted_line_is_its_own_sentence(self):
|
||||
read = read_swap('Replace the man with @1. @1 says "Thank you, Mario!" Make the camera spin around her.', ONE)
|
||||
self.assertEqual(read.unused, ["Make the camera spin around her"])
|
||||
self.assertEqual(sentences('@1 says "Hi." Then she waves.'), ['@1 says "Hi."', "Then she waves."])
|
||||
|
||||
def test_a_looks_line_for_a_picture_that_is_not_connected_is_an_error(self):
|
||||
with self.assertRaisesRegex(ValueError, "Picture 2 is not connected"):
|
||||
read_swap("@2 looks like a pilot", ONE)
|
||||
|
||||
def test_a_picture_described_twice_is_an_error(self):
|
||||
with self.assertRaisesRegex(ValueError, "once"):
|
||||
read_swap("@1 looks like a pilot\n@1 looks like a chef", ONE)
|
||||
|
||||
def test_spoken_words_are_never_listed_as_not_used(self):
|
||||
read = read_swap('replace the barista with @1. 2s: "coffee is ready"', ONE)
|
||||
self.assertEqual(read.unused, [])
|
||||
self.assertEqual(read.goes, {1: "the barista"})
|
||||
|
||||
|
||||
|
||||
|
||||
class ReportTests(unittest.TestCase):
|
||||
"""The node's report shows what was read, from the same reading the prompt uses."""
|
||||
|
||||
def report(self, text, jobs):
|
||||
from nodes._h3_script_helpers import script_report
|
||||
return script_report(text, 6.0, jobs, "swap the person")["read"]
|
||||
|
||||
def test_the_report_says_who_goes_and_how_they_look(self):
|
||||
read = self.report("The man in front is replaced by @1, a game character with a blue suit.", ONE)
|
||||
self.assertEqual(read["people"], [{"slot": 1, "goes": "the man in front", "looks": "a game character with a blue suit", "named": True}])
|
||||
self.assertEqual(read["unused"], [])
|
||||
|
||||
def test_the_report_says_when_nobody_was_named(self):
|
||||
read = self.report("", TWO)
|
||||
self.assertEqual([person["goes"] for person in read["people"]], ["the person on the left", "the person on the right"])
|
||||
self.assertEqual([person["named"] for person in read["people"]], [False, False])
|
||||
self.assertEqual(read["people"][0]["looks"], "")
|
||||
|
||||
def test_the_report_lists_words_a_swap_does_not_use(self):
|
||||
read = self.report("replace the man with @1 and make her smile", ONE)
|
||||
self.assertEqual(read["unused"], ["make her smile"])
|
||||
|
||||
def test_a_line_the_writer_would_refuse_shows_its_reason(self):
|
||||
read = self.report("@3 looks like a man in red.", ONE)
|
||||
self.assertEqual(read["people"], [])
|
||||
self.assertIn("Picture 3 is not connected", read["problem"])
|
||||
|
||||
def test_the_report_gives_the_ref2va_cast_from_the_written_prompt(self):
|
||||
read = self.report(
|
||||
'Swap the woman on the left for @1 and the man on the right for @2. @1 is a knight in silver armor, '
|
||||
'and @2 has short red hair and wears a leather jacket. @2 says "We made it."', TWO)
|
||||
self.assertEqual(read["cast"], [
|
||||
"<Subject 1> the woman on the left in <Video 1> \u2192 removed",
|
||||
"<Subject 2> the man on the right in <Video 1> \u2192 removed",
|
||||
"<Subject 3> = the person in <Picture 1>, takes <Subject 1>'s place: a knight in silver armor",
|
||||
"<Subject 4> = the person in <Picture 2>, takes <Subject 2>'s place: short red hair, wearing a leather jacket",
|
||||
"<Subject 4> says <d>We made it.</d>",
|
||||
])
|
||||
|
||||
def test_the_cast_says_what_is_kept_when_nothing_is_described(self):
|
||||
read = self.report("", ONE)
|
||||
self.assertEqual(read["cast"][1], "<Subject 2> = the person in <Picture 1>, takes <Subject 1>'s place: the same face, hair and clothes")
|
||||
|
||||
def test_other_jobs_have_no_reading(self):
|
||||
from nodes._h3_script_helpers import script_report
|
||||
self.assertNotIn("read", script_report("@1 waves", 6.0, ONE, ""))
|
||||
|
||||
def test_the_cast_shows_every_subject_the_prompt_defines(self):
|
||||
import re
|
||||
from nodes._h3_prompt_helpers import split_sections, write_prompt
|
||||
for jobs, text in (
|
||||
({1: "person", 2: "place", 3: "outfit", 4: "thing"}, "Replace the man with @1.\n@1 wears @3.\n@1 holds @4."),
|
||||
({1: "person", 2: "style"}, "Replace the man with @1."),
|
||||
):
|
||||
parts = split_sections(write_prompt(text, jobs=jobs, video="swap the person"))
|
||||
defined = re.findall(r"^(<Subject \d+>) is ", parts["subject_definitions"], re.M)
|
||||
shown = [re.match(r"<Subject \d+>", line).group(0) for line in self.report(text, jobs)["cast"] if "<d>" not in line]
|
||||
self.assertEqual(shown, defined, jobs)
|
||||
|
||||
def test_the_cast_says_who_wears_an_outfit(self):
|
||||
cast = self.report("Replace the man with @1. @1 wears @2.", {1: "person", 2: "outfit"})["cast"]
|
||||
self.assertIn("<Subject 3> = the outfit in <Picture 2>, worn by <Subject 2>", cast)
|
||||
|
||||
def test_a_line_the_prompt_uses_is_never_called_unused(self):
|
||||
read = self.report("Replace the man with @1.\n@1 wears @3.\n@1 holds @4.", {1: "person", 2: "place", 3: "outfit", 4: "thing"})
|
||||
self.assertEqual(read["unused"], ["@1 holds"])
|
||||
|
||||
def test_the_reading_names_the_other_pictures_and_who_speaks(self):
|
||||
read = self.report('Replace the man with @1. @1 wears @3. @1 says "Hello there."', {1: "person", 2: "place", 3: "outfit"})
|
||||
self.assertEqual(read["pictures"], [{"slot": 2, "job": "place", "worn_by": None}, {"slot": 3, "job": "outfit", "worn_by": 1}])
|
||||
self.assertEqual(read["says"], [{"slot": 1, "words": "Hello there."}])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -509,9 +509,6 @@ class SaveImageLocalModeTests(SaveImageNodeTests):
|
||||
self.assertIs(node.VALIDATE_INPUTS(filename_prefix="a/b"), True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
|
||||
class SaveImageLightPreviewTests(unittest.TestCase):
|
||||
"""The small copy the node shows on its face instead of the full file."""
|
||||
@@ -588,3 +585,7 @@ class SaveImageLightPreviewTests(unittest.TestCase):
|
||||
result = self.run_node(out, blocked)
|
||||
self.assertEqual(result["ui"]["ausboss_preview"], [])
|
||||
self.assertTrue(Path(result["result"][0]).is_file())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
@@ -438,6 +438,70 @@ class MissingRowPolicyTests(unittest.TestCase):
|
||||
)
|
||||
self.assertEqual(triggers, "kept word, parked word")
|
||||
|
||||
def test_a_missing_row_on_a_flat_curve_adds_no_trigger_words(self):
|
||||
# A LoRA that never loaded must not put its words in the prompt. A
|
||||
# row parked at strength 0 keeps its words, as the node docs promise,
|
||||
# so comparing with and without it changes only the weights.
|
||||
try:
|
||||
from nodes.node_lora_loader import AusBossLoraLoader
|
||||
except Exception as exc: # pragma: no cover - needs the package importable
|
||||
self.skipTest(f"node module not importable offline: {exc}")
|
||||
|
||||
def resolve(name):
|
||||
if name == "gone.safetensors":
|
||||
raise ValueError("LoRA file not found in models/loras: gone.safetensors")
|
||||
return Path(name)
|
||||
|
||||
rows = [
|
||||
{**self.ROW, "name": "kept.safetensors", "triggers": "kept word"},
|
||||
{**self.ROW, "triggers": "ghost word", "curve": True},
|
||||
{**self.ROW, "name": "parked.safetensors", "strength": 0, "strength_clip": 0,
|
||||
"triggers": "parked word"},
|
||||
{**self.ROW, "name": "off.safetensors", "enabled": False, "triggers": "off word"},
|
||||
]
|
||||
sys.modules["comfy.sd"].load_lora_for_models = lambda model, clip, *_args: (model, clip)
|
||||
with (
|
||||
patch.object(_lora_helpers, "resolve_lora_path", side_effect=resolve),
|
||||
patch.object(_lora_helpers, "_load_lora_file", return_value={}),
|
||||
contextlib.redirect_stdout(io.StringIO()),
|
||||
):
|
||||
_model, _clip, triggers = AusBossLoraLoader().load_loras(
|
||||
"model", json.dumps(rows), on_missing="skip", curve=[0.5, 0.5, 0.5]
|
||||
)
|
||||
self.assertEqual(triggers, "kept word, parked word")
|
||||
|
||||
def test_a_missing_row_on_a_moving_curve_adds_no_trigger_words(self):
|
||||
# A LoRA that never loaded must not put its words in the prompt. A
|
||||
# row parked at strength 0 keeps its words, as the node docs promise,
|
||||
# so comparing with and without it changes only the weights.
|
||||
try:
|
||||
from nodes.node_lora_loader import AusBossLoraLoader
|
||||
except Exception as exc: # pragma: no cover - needs the package importable
|
||||
self.skipTest(f"node module not importable offline: {exc}")
|
||||
|
||||
def resolve(name):
|
||||
if name == "gone.safetensors":
|
||||
raise ValueError("LoRA file not found in models/loras: gone.safetensors")
|
||||
return Path(name)
|
||||
|
||||
rows = [
|
||||
{**self.ROW, "name": "kept.safetensors", "triggers": "kept word"},
|
||||
{**self.ROW, "triggers": "ghost word", "curve": True},
|
||||
{**self.ROW, "name": "parked.safetensors", "strength": 0, "strength_clip": 0,
|
||||
"triggers": "parked word"},
|
||||
{**self.ROW, "name": "off.safetensors", "enabled": False, "triggers": "off word"},
|
||||
]
|
||||
sys.modules["comfy.sd"].load_lora_for_models = lambda model, clip, *_args: (model, clip)
|
||||
with (
|
||||
patch.object(_lora_helpers, "resolve_lora_path", side_effect=resolve),
|
||||
patch.object(_lora_helpers, "_load_lora_file", return_value={}),
|
||||
contextlib.redirect_stdout(io.StringIO()),
|
||||
):
|
||||
_model, _clip, triggers = AusBossLoraLoader().load_loras(
|
||||
"model", json.dumps(rows), on_missing="skip", curve=[1.0, 0.5, 0.0]
|
||||
)
|
||||
self.assertEqual(triggers, "kept word, parked word")
|
||||
|
||||
def test_the_on_missing_choices_come_from_the_helper(self):
|
||||
try:
|
||||
from nodes.node_lora_loader import AusBossLoraLoader
|
||||
|
||||
@@ -186,6 +186,9 @@ class FillHolesLimitTests(unittest.TestCase):
|
||||
everything, _ = node.refine(kept_subject_mask(), **settings)
|
||||
self.assertTrue(torch.all(everything == 1.0))
|
||||
|
||||
def test_mask_refine_is_an_output_node_so_it_can_run_on_its_own(self):
|
||||
self.assertIs(node_refine_mask.AusBossRefineMask.OUTPUT_NODE, True)
|
||||
|
||||
|
||||
class SmoothTests(unittest.TestCase):
|
||||
def test_zero_smooth_is_identity(self):
|
||||
@@ -467,14 +470,6 @@ class MattingSeesTheFeatherTests(unittest.TestCase):
|
||||
self.mask, 0, blur, False, guide_image=self.guide, edge_refine="matting"
|
||||
)[0]
|
||||
|
||||
def test_a_wider_feather_produces_a_richer_matte(self):
|
||||
# Distinct alpha levels separate the two behaviours cleanly: seeding
|
||||
# from the threshold moved this barely at all, seeding from the soft
|
||||
# values multiplies it.
|
||||
base = int(torch.unique(self.matted(0.0)).numel())
|
||||
feathered = int(torch.unique(self.matted(8.0)).numel())
|
||||
self.assertGreater(feathered, base * 2)
|
||||
|
||||
def test_the_matte_changes_materially_with_the_feather(self):
|
||||
self.assertGreater(float((self.matted(8.0) - self.matted(0.0)).abs().max()), 0.25)
|
||||
|
||||
@@ -485,6 +480,25 @@ class MattingSeesTheFeatherTests(unittest.TestCase):
|
||||
self.assertLessEqual(float(out.max()), 1.0)
|
||||
self.assertGreater(int(torch.unique(out).numel()), 2)
|
||||
|
||||
def test_matting_keeps_the_subject_its_own_size(self):
|
||||
# A high lower threshold marked the blurred rim as background and the
|
||||
# matte came back at about two thirds of the subject.
|
||||
mask = torch.zeros((1, 256, 256))
|
||||
mask[:, 64:192, 64:192] = 1.0
|
||||
guide = torch.rand((1, 256, 256, 3)) * 0.2
|
||||
guide[:, 64:192, 64:192] += 0.6
|
||||
out = refine_mask(mask, 0, 0.0, False, guide_image=guide, edge_refine="matting")[0]
|
||||
self.assertGreater(float(out.sum() / mask.sum()), 0.9)
|
||||
|
||||
def test_matting_still_solves_a_subject_smaller_than_its_blur(self):
|
||||
mask = torch.zeros((1, 256, 256))
|
||||
mask[:, 113:143, 113:143] = 1.0
|
||||
guide = torch.full((1, 256, 256, 3), 0.8)
|
||||
guide[:, 113:143, 113:143] = 0.1
|
||||
out = refine_mask(mask, 0, 0.0, False, guide_image=guide, edge_refine="matting")[0]
|
||||
self.assertGreater(int(torch.unique(out).numel()), 2)
|
||||
self.assertGreater(float(out.sum() / mask.sum()), 0.8)
|
||||
|
||||
|
||||
class SeparableMorphologyTests(unittest.TestCase):
|
||||
"""grow_shrink_mask runs as one separable pass; the result must stay
|
||||
|
||||
@@ -84,7 +84,7 @@ class SavedFallbackTests(unittest.TestCase):
|
||||
def test_the_known_fallbacks_are_read(self):
|
||||
self.assertEqual(self.fallbacks["AUSBOSS_NODES_StitchInpaint"], {"seam": "classic", "paste_onto": "crop", "follow_changes": False})
|
||||
self.assertEqual(self.fallbacks["AUSBOSS_NODES_CropForInpaint"], {"keep_inside": True})
|
||||
self.assertEqual(self.fallbacks["AUSBOSS_NODES_RefineMask"], {"preview": True, "max_hole_size": 0})
|
||||
self.assertEqual(self.fallbacks["AUSBOSS_NODES_RefineMask"], {"preview": True, "max_hole_size": 0, "detail_range": 12, "fix_threshold": 0.01})
|
||||
for node_id in ("AUSBOSS_NODES_LaMaInpaint", "AUSBOSS_NODES_SelectFrame"):
|
||||
self.assertEqual(self.fallbacks[node_id], {"preview": True})
|
||||
self.assertEqual(self.fallbacks["AUSBOSS_NODES_LoraLoader"], {"on_missing": "error"})
|
||||
|
||||
@@ -875,6 +875,17 @@ test("the Fine edges choices read off and on, and by name only when there are se
|
||||
assert.equal(fineEdgeLabel("small/model.safetensors", several), "model");
|
||||
assert.equal(fineEdgeLabel("vitmatte_base.safetensors", several), "vitmatte_base");
|
||||
assert.equal(fineEdgeLabel("off", several), "off");
|
||||
// The two known models go by their own names once there is a choice.
|
||||
const known = ["off", "birefnet.safetensors", "rmbg3_int8_convrot.safetensors"];
|
||||
assert.equal(fineEdgeLabel("birefnet.safetensors", known), "BiRefNet");
|
||||
assert.equal(fineEdgeLabel("rmbg3_int8_convrot.safetensors", known), "RMBG-3.0");
|
||||
// RMBG-3.0 alone still reads RMBG-3.0: the help page says to pick it by that name.
|
||||
assert.equal(fineEdgeLabel("rmbg3_int8_convrot.safetensors", ["off", "rmbg3_int8_convrot.safetensors"]), "RMBG-3.0");
|
||||
// Both of Bria's copies: each says which it is.
|
||||
const both = ["off", "birefnet.safetensors", "rmbg3_bf16.safetensors", "rmbg3_int8_convrot.safetensors"];
|
||||
assert.equal(fineEdgeLabel("rmbg3_bf16.safetensors", both), "RMBG-3.0 bf16");
|
||||
assert.equal(fineEdgeLabel("rmbg3_int8_convrot.safetensors", both), "RMBG-3.0 int8");
|
||||
assert.equal(fineEdgeLabel("birefnet.safetensors", both), "BiRefNet");
|
||||
});
|
||||
|
||||
test("the line of settings a fine edge was made with is the one the node writes", () => {
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
// A value written from a click or a drag on a node face is one undo step.
|
||||
// ComfyUI records a step when the canvas sees the mouse go up, but a face
|
||||
// that keeps its own pointer events never lets the canvas see it. A file that
|
||||
// writes widgets through commitWidgetValue therefore also records the step
|
||||
// itself, with notifyAusbossChange once the gesture is over. Without it, the
|
||||
// next Ctrl+Z jumps back past the change and it is gone for good.
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { readdirSync, readFileSync } from "node:fs";
|
||||
import { join, relative } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const JS = fileURLToPath(new URL("../js/", import.meta.url));
|
||||
|
||||
function sources(folder) {
|
||||
return readdirSync(folder, { withFileTypes: true }).flatMap((entry) => {
|
||||
const path = join(folder, entry.name);
|
||||
if (entry.isDirectory()) return entry.name === "docs" ? [] : sources(path);
|
||||
return /\.m?js$/.test(entry.name) ? [path] : [];
|
||||
});
|
||||
}
|
||||
|
||||
test("every face that commits a widget value also records the undo step", () => {
|
||||
const missing = sources(JS)
|
||||
.filter((path) => !path.endsWith("widget_card_math.mjs"))
|
||||
.filter((path) => {
|
||||
const source = readFileSync(path, "utf8");
|
||||
return /\bcommitWidgetValue\(/.test(source) && !/\bnotifyAusbossChange\(|changeTracker\?\.checkState\?\.\(/.test(source);
|
||||
})
|
||||
.map((path) => relative(JS, path));
|
||||
assert.deepEqual(missing, []);
|
||||
});
|
||||
|
||||
test("the moment strip records a step for each drag or click it writes", () => {
|
||||
const source = readFileSync(join(JS, "shared/moment_strip.mjs"), "utf8");
|
||||
const commit = source.slice(source.indexOf("const commitScript"), source.indexOf("const addHandle"));
|
||||
assert.match(commit, /commitWidgetValue\([^)]*\);\s*notifyAusbossChange\(\);/);
|
||||
});
|
||||
|
||||
test("a job picked from a picture chip is its own step", () => {
|
||||
const source = readFileSync(join(JS, "shared/h3_cast_chips.mjs"), "utf8");
|
||||
const choose = source.slice(source.indexOf("const choose ="), source.indexOf("button.addEventListener"));
|
||||
assert.match(choose, /notifyAusbossChange\(\)/);
|
||||
});
|
||||
@@ -281,12 +281,16 @@ test("Mask Refine saved before Max hole size opens with no limit, as an API prom
|
||||
const maxHole = widgets.find((widget) => widget.name === "max_hole_size");
|
||||
assert.equal(maxHole.value, "", "the old save hands max_hole_size the card's empty value");
|
||||
|
||||
assert.deepEqual(resetUnknownValues(widgets, cardFallbacks("AUSBOSS_NODES_RefineMask")), ["max_hole_size"]);
|
||||
// Detail range and Fix threshold came later still, so the old save resets them too.
|
||||
assert.deepEqual(resetUnknownValues(widgets, cardFallbacks("AUSBOSS_NODES_RefineMask")), ["max_hole_size", "detail_range", "fix_threshold"]);
|
||||
assert.equal(widgets.find((widget) => widget.name === "detail_range").value, 12);
|
||||
assert.equal(widgets.find((widget) => widget.name === "fix_threshold").value, 0.01);
|
||||
const defaults = maxHoleSizeDefaults();
|
||||
assert.equal(maxHole.value, 0);
|
||||
assert.equal(maxHole.value, defaults.widget, "a new node's default");
|
||||
assert.equal(maxHole.value, defaults.argument, "what an API prompt without max_hole_size runs with");
|
||||
const others = widgets.filter((widget) => widget.name !== "max_hole_size" && widget.name !== "ausboss_widget_card");
|
||||
const appended = ["max_hole_size", "detail_range", "fix_threshold", "ausboss_widget_card"];
|
||||
const others = widgets.filter((widget) => !appended.includes(widget.name));
|
||||
assert.deepEqual(others.map((widget) => widget.value), REFINE_BEFORE_MAX_HOLE.slice(0, 8));
|
||||
});
|
||||
|
||||
@@ -296,7 +300,7 @@ test("Mask Refine saved since keeps its Max hole size", () => {
|
||||
for (const size of [0, 2, 0.5]) {
|
||||
const widgets = restoreByPosition(names, [...REFINE_BEFORE_MAX_HOLE.slice(0, 8), size], REFINE_TYPES);
|
||||
widgets.find((widget) => widget.name === "edge_refine").options = { values: ["off", "guided filter", "matting"] };
|
||||
assert.deepEqual(resetUnknownValues(widgets, fallbacks), []);
|
||||
assert.deepEqual(resetUnknownValues(widgets, fallbacks), ["detail_range", "fix_threshold"]);
|
||||
assert.equal(widgets.find((widget) => widget.name === "max_hole_size").value, size);
|
||||
}
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user