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 | ||
|
|
c020e53435 | ||
|
|
0632c104ff | ||
|
|
62413eef53 | ||
|
|
9943a60e63 | ||
|
|
050723f245 | ||
|
|
c5bfdcfe93 | ||
|
|
5cdb560c0c | ||
|
|
6640478428 | ||
|
|
067e5e946a | ||
|
|
af923711a2 | ||
|
|
7766dad425 | ||
|
|
4f54298cac | ||
|
|
e2cef8e75c | ||
|
|
ce672777c5 | ||
|
|
b9abadc011 | ||
|
|
7315c9bd30 | ||
|
|
cf5e5a832b | ||
|
|
4c1d25d81f | ||
|
|
3f248d1b98 | ||
|
|
839e00bbac | ||
|
|
2a367a90cc | ||
|
|
9c2fa1e454 | ||
|
|
57672d9058 | ||
|
|
365050aa8c | ||
|
|
b9c5898285 | ||
|
|
b90ee3bf14 | ||
|
|
f3fd30e965 | ||
|
|
4186db0a26 | ||
|
|
1749792457 | ||
|
|
0ba8b5664b | ||
|
|
9136fe88d3 | ||
|
|
9cd87d4778 | ||
|
|
f0ef22c01c | ||
|
|
98e4ddf1ff | ||
|
|
c478c86e73 | ||
|
|
bbd1841e42 | ||
|
|
50897144bd | ||
|
|
84115ca26e | ||
|
|
699c435955 | ||
|
|
017788a2d9 | ||
|
|
6bfbfcbf29 | ||
|
|
7a34c917ae | ||
|
|
e3871d624c | ||
|
|
538698d2b2 | ||
|
|
be9db84962 | ||
|
|
ad7bf01cbc | ||
|
|
254be062ba | ||
|
|
1d4d619649 | ||
|
|
d9a143b98e | ||
|
|
f6d01458a8 | ||
|
|
60dca17f4a | ||
|
|
94b1ab1def | ||
|
|
f7fe1ceac8 | ||
|
|
e21c06591d | ||
|
|
39af045ecd | ||
|
|
043025107d | ||
|
|
32b42832fc | ||
|
|
7ab5b333a0 | ||
|
|
62e5d26e14 | ||
|
|
36d5ee3604 | ||
|
|
6ec510f5e0 | ||
|
|
95350d1d77 | ||
|
|
f6f9fb4525 | ||
|
|
3399f6c4f2 | ||
|
|
e9864c02cb | ||
|
|
ccce4073a6 | ||
|
|
5389db5ce5 | ||
|
|
e8be47102e | ||
|
|
ac9817945e | ||
|
|
1068b3fb75 | ||
|
|
1bf9f0bbb8 | ||
|
|
201cd54508 | ||
|
|
4ce99c7254 | ||
|
|
be078c7da3 | ||
|
|
533fede3b9 | ||
|
|
f8ce7c03b7 | ||
|
|
6e9651613a | ||
|
|
e382402bea | ||
|
|
676c810538 | ||
|
|
780177f118 | ||
|
|
1f11996210 | ||
|
|
b5481a6bbd | ||
|
|
c47b4bd36e | ||
|
|
41260de5b3 | ||
|
|
e82fdddfb9 | ||
|
|
2b5d5de853 | ||
|
|
1276d95708 |
@@ -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() }}
|
||||
|
||||
+224
@@ -2,6 +2,230 @@
|
||||
|
||||
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
|
||||
my lines** with a small text model such as Qwen3-VL 8B on `clip`, and it
|
||||
fixes spelling, writes short sentences, and puts each spoken line right
|
||||
after whoever says it before the node reads them. Your quoted words are
|
||||
never rewritten: they stay exactly as typed. Off by default.
|
||||
- **Load Audio 🆎: Clean up.** Turn on **Clean up** for a voice recording
|
||||
and it comes out as one channel, with the quiet bits at the start and end
|
||||
cut, less hum and hiss, and an even volume that never clips. A video model
|
||||
that copies the sound it is given copies its noise too, so this helps a
|
||||
phone recording. It is off by default, so saved workflows are unchanged.
|
||||
- **H3 Prompt Writer 🆎 keeps to what you wrote.** It lays your notes out
|
||||
for H3 and adds no sounds or settings you didn't type. Notes are read more
|
||||
carefully too: "muted colours" no longer turns the sound off, "First
|
||||
person view" keeps its first word, a shirt or sign that says something
|
||||
stays written on it, and a "no music" said inside quotes stays part of
|
||||
the line.
|
||||
- **H3 Prompt Writer 🆎 follows your layout more closely.** A `camera:` or
|
||||
`sound:` line belongs to the shot it is typed under, `Shot 2:` on its own
|
||||
line starts the next shot, and two people quoted in one sentence each get
|
||||
their line. Single quotes after "says" count as speech, "in voiceover"
|
||||
after a quote keeps the lips closed, `Cut back to` returns to a place,
|
||||
and `Start on black.` works. A number such as "7 seconds remain" stays
|
||||
part of the action, and two people are no longer placed left and right
|
||||
unless the script says where they stand. With two or more people, a
|
||||
spoken line reaches H3 as you typed it.
|
||||
- **New node: Strength Curve 🆎.** Draw how strong something should be
|
||||
from the start of a run to the end, and wire it into a node that follows
|
||||
it step by step. Drag the points or start from a preset (flat, fade out,
|
||||
fade in, ease out, ease in); Top and Bottom set the strength range.
|
||||
- **LoRA Loader 🆎 rows can follow a strength curve.** A new `curve` input
|
||||
takes a Strength Curve, and each row gets a curve mark: rows you mark run
|
||||
at their strength times the curve at every step, so a style LoRA can fade
|
||||
out before the last steps. It works with every model file, fp8 and int8
|
||||
included.
|
||||
- **Krea 2 Encode 🆎 can change the reference's strength over the run.** A
|
||||
new `reference_curve` input takes a Strength Curve: 1 follows the
|
||||
reference as before, 0 ignores it. It also works with Krea 2 Outpaint
|
||||
Model Patch 🆎.
|
||||
- **New node: Film Grain 🆎.** Adds film grain to a picture or a video.
|
||||
The grain is strongest in the midtones and gentler in deep shadows and
|
||||
highlights, as on film. Size, roughness and colour set its look, it moves
|
||||
from frame to frame on a video (or stays put), an optional mask limits
|
||||
where, and the same seed gives the same grain.
|
||||
- **Film Grain has an Auto switch.** With Auto on, the node picks the grain
|
||||
for the picture: the same look on a small or a big one (the size follows the
|
||||
picture's size), and an amount that matches the grain the picture already
|
||||
has. A clean render starts at the normal 0.25. Amount and Size then count as
|
||||
multipliers ("1 × = Auto's pick"), with the real value in small type beside
|
||||
each box. Auto on and Auto off keep their own numbers, and Auto starts off,
|
||||
so saved workflows behave as before.
|
||||
- **Film Grain can copy another picture's grain.** Wire a picture whose grain
|
||||
you like into `grain_from` and switch Auto on (it reads "match"). The node
|
||||
reads that picture's grain, how strong, how big and how colourful, and adds
|
||||
grain like it; Amount, Size and Color then count from the match ("1 × = the
|
||||
match"), with the real value beside each box. The picture to copy from is
|
||||
scaled to your picture's size first, so the grain matches at the same
|
||||
viewing size, and only its plainest patches are read. Roughness stays yours.
|
||||
- **Film Grain, Keep Detail and Cut Out show a live preview.** After one run,
|
||||
the picture on the node redraws while you drag a value, with a "not run yet"
|
||||
tag until you queue. A Fit | 100% switch left of Preview shows the whole
|
||||
picture or real pixels; at 100% dragging the picture moves around it.
|
||||
- **New node: Cut Out 🆎.** Turns a picture and a mask into a cut-out with a
|
||||
see-through background, ready to save as a PNG. Clean edges takes the old
|
||||
background's colour out of hair and soft edges so there is no halo, and
|
||||
fully kept pixels stay exactly as they were. Grow, feather, haze and
|
||||
solid-core levels, and smoothing over video frames, are on the card.
|
||||
- **New node: Keep Detail 🆎.** Puts the original picture's fine detail
|
||||
back on an edit that came out too smooth. The edit keeps its shapes,
|
||||
light and colour; Light only never shifts a colour. The two pictures must
|
||||
line up.
|
||||
- **Check layout 🆎 shows what makes a workflow hard to read.** Right-click
|
||||
the canvas or use the command palette. It lists overlapping nodes and
|
||||
groups, wires that run backwards or hide behind a node, nodes just under a
|
||||
preview that grows when it runs, nodes outside every group, a saved zoom
|
||||
too small to read and a missing Workflow Note, inside subgraphs too. Click
|
||||
an entry to jump to it. Nothing is moved.
|
||||
- **The example workflows are tidied so Check layout finds nothing.** Only
|
||||
node and group positions and sizes, and reroute spots, changed. What each
|
||||
workflow does is the same.
|
||||
- **Frame Interpolate 🆎 holds cuts between two shots of the same place.**
|
||||
It used to count a cut only when the frame changed more than **Scene
|
||||
cut**, and two shots of one place in the same light can change less
|
||||
than fast movement inside one shot, so it mixed those shots together
|
||||
for a frame or two. A change that jumps out from the frames around it
|
||||
now counts as a cut too. **Scene cut** still works as before, and `0`
|
||||
still turns cut finding off.
|
||||
- **Latent Size 🆎: pick which ratio chips show.** The gear's Ratio chips
|
||||
row opens a list of every ratio with its size. Switch each on or off,
|
||||
remove one, add your own such as 21:9, or reset to the shipped list.
|
||||
5:4 and 21:9 now come in the list, switched off. A chip keeps the name
|
||||
it was given, so 21:9 no longer reads 7:3.
|
||||
- **Edit Lock 🆎 says what is wrong when the VAE and model don't match.**
|
||||
The readout used to blame the VAE alone. It now says either file can be
|
||||
the wrong one, gives the two channel counts it compared, and points to
|
||||
the model and VAE in the workflow's notes. A GGUF or other converted
|
||||
model is a common cause.
|
||||
|
||||
## 2.28.1 - 2026-11-25
|
||||
|
||||
- **Image Resize 🆎 shows Fit only when it is used.** Fit, and Fill under
|
||||
|
||||
@@ -144,6 +144,18 @@ Small picture jobs in one node, picked from a list. **split sheet at gaps** cuts
|
||||
|
||||
Matches a picture's colors to a reference, with LAB, RGB, MKL or histogram transfer. Strength sets how much, and an optional mask (with invert) limits where. With `reference_mode` set to first frame, every frame of a batch matches the batch's first frame. That can cut down color drift in a clip, but it does not steady motion.
|
||||
|
||||
### Film Grain
|
||||
|
||||
Adds film grain to a picture or a video. The grain is strongest in the midtones and gentler in deep shadows and bright highlights, as on film. **Size** is the grain's size in pixels, **Roughness** mixes in finer grain that bunches up unevenly, and **Color** goes from black-and-white grain to colour film's. On a video the grain moves from frame to frame, or stays put with **Video grain** on *still*. An optional mask adds grain only where it is white, and the same seed always gives the same grain. **Auto** picks the grain for the picture's size, or copies the grain of a picture wired into `grain_from`. The preview shows the result.
|
||||
|
||||
### Cut Out
|
||||
|
||||
Turns a picture and a mask into a cut-out with a see-through background, ready to save as a PNG (Save Image keeps the transparency) or lay on a new background. Keep the white or the black part of the mask, grow or shrink it and soften its edge. **Clean edges** takes the old background's colour out of hair and soft edges, so the cut-out has no halo; fully kept pixels stay exactly as they were. It also returns the final mask, and works on video. The preview shows the cut-out on a checkerboard.
|
||||
|
||||
### Keep Detail
|
||||
|
||||
Puts the original picture's fine detail (skin, fabric, grain) back on an edited version that came out too smooth. Wire the edit and the original, which must line up (Realign to Source fixes an edit that drifted). The edit keeps its shapes, light and colour, and only detail smaller than **Detail size** comes from the original. **Light only** never shifts the edit's colours; **color + light** brings the detail's colour too. An optional mask limits where.
|
||||
|
||||
### Realign to Source (EXPERIMENTAL 🧪)
|
||||
|
||||
Lines an edited picture back up with the original. Qwen Image 2.1 often draws an edit, especially a style change, a little bigger or shifted: up to about 12% taller, by a different amount every seed. Wire in the edit and the picture it was made from. The node measures how far the edit moved and moves it back, at the original's size. It fixes the zoom and shift of the whole picture, not shapes the edit redrew in a new place, so the result lines up closely rather than pixel for pixel.
|
||||
@@ -228,7 +240,7 @@ Picks one frame from a batch, unchanged: `1` is the first, `-1` the last and `-2
|
||||
|
||||
### Frame Interpolate
|
||||
|
||||
Changes a clip's frame rate by making in-between frames. You set the source and target fps, so 24 to 30 works as well as doubling. The blend method crossfades frames, and optical flow uses RAFT weights you put in place yourself. At a hard cut it holds the frame instead of blending two unrelated shots. It works in chunks to keep memory down.
|
||||
Changes a clip's frame rate by making in-between frames. You set the source and target fps, so 24 to 30 works as well as doubling. The blend method crossfades frames, and optical flow uses RAFT weights you put in place yourself. At a hard cut it holds the frame instead of blending two shots together, even when both shots show the same place. It works in chunks to keep memory down.
|
||||
|
||||
It returns the new frames and their fps. It doesn't touch audio, so carry the source audio to Save Video separately. The [help page](js/docs/AUSBOSS_NODES_FrameInterpolate.md) covers the weights and timing.
|
||||
|
||||
@@ -320,12 +332,16 @@ In the **+ LoRA** list, tick several files to add them at once. Rows can be gath
|
||||
|
||||
When a file has moved, the node finds it by name if only one file matches. A missing LoRA that is switched on stops the run by default. Turn off **Stop on missing LoRA** to warn and skip it instead. A LoRA that changes nothing in the model gets a warning with its file name.
|
||||
|
||||
Wire a [Strength Curve](#strength-curve) into the `curve` input and click the curve mark on a row, and that row's strength changes over the run: fade a style LoRA out so the last steps come out clean. It works with every model file, fp8 and int8 included.
|
||||
|
||||
### Krea 2 Encode
|
||||
|
||||
Krea 2's positive and negative prompts in one card. Connect a VAE and reference pictures, and it adds them as references too, resized for the model first. **VLM reference** sets whether the text encoder also looks at them. Leave the references empty for plain text to image. For an outpaint, connect the pad node's mask too: the model then sees the new area in your picture's own colour instead of gray, so it paints it rather than keeping a gray frame.
|
||||
|
||||
The prompt box takes several lines and a linked text. The [help page](js/docs/AUSBOSS_NODES_Krea2Encode.md) covers preparing references. With an outpaint LoRA, copy the wiring from the matching example.
|
||||
|
||||
Wire a [Strength Curve](#strength-curve) into `reference_curve` and the picture follows the references as strongly as the curve says at each step, from 1 (as today) to 0 (ignored): hold the layout early and let go late.
|
||||
|
||||
### Krea 2 Outpaint Model Patch
|
||||
|
||||
Tells Krea 2 where a reference picture sits on the canvas. It's made for Krea 2 outpaint LoRAs, and the two that exist want different placements. Put it after the LoRAs and before the sampler, and connect a stitcher and the reference conditioning from Krea 2 Encode.
|
||||
@@ -341,6 +357,10 @@ Here Krea 2 Outpaint takes a 16:9 photo to 4:5 in one pass. [Open the Krea 2 Out
|
||||
|
||||
The patch relies on ComfyUI's internal attention code. Its [help page](js/docs/AUSBOSS_NODES_Krea2OutpaintModelPatch.md) explains both setups and what happens without reference conditioning.
|
||||
|
||||
### Strength Curve
|
||||
|
||||
Draw how strong something should be from the first step of a run to the last: drag the points, or start from flat, fade out, fade in, ease out or ease in. **Top** and **Bottom** set the strength at the top and bottom of the curve box. Wire the curve into LoRA Loader's `curve` (rows you mark follow it) or Krea 2 Encode's `reference_curve`. The output is ComfyUI's list of numbers (`FLOATS`), so it also feeds ComfyUI's own hook keyframe nodes.
|
||||
|
||||
## 3D viewer
|
||||
|
||||
### Pause for Shot
|
||||
@@ -495,6 +515,7 @@ If you share workflows, a few of these nodes help the people who download them:
|
||||
|
||||
- **Workflow Note** puts a setup card on the canvas with each model's download link, folder and size, the node packs it needs and your links, and checks them against the reader's install.
|
||||
- **Callout** is a note with big readable text and teal arrows you type with an emoji.
|
||||
- **Check layout 🆎** lists overlaps, hidden and backwards wires and nodes outside the groups before you share.
|
||||
- **Image Compare A/B** shows the result against its source with a slider.
|
||||
- **Seed** keeps runs repeatable, and **Use last run** brings back the seed the last run used.
|
||||
- **Run Timer** shows how long the whole run took, so a speed note is measured.
|
||||
@@ -509,6 +530,7 @@ People who download your workflow get the nodes through ComfyUI-Manager's missin
|
||||
- **Help cards:** the **?** in a classic node's title bar opens its description, inputs and outputs. Nodes 2.0 and titleless nodes such as Run Timer have **About this node** in their right-click menu.
|
||||
- **Recreate node 🆎** (right-click an AusBoss node) rebuilds a node saved by an older version from the current definition. It keeps the values, links, position and colors.
|
||||
- **Replace with AusBoss nodes 🆎** (canvas right-click or the command palette) finds third-party nodes this pack can stand in for, such as VideoHelperSuite's Load Video and Video Combine or KJNodes' Color Match. It previews each swap and replaces the ones you leave ticked.
|
||||
- **Check layout 🆎** (canvas right-click or the command palette) lists what makes a workflow hard to read: overlapping nodes and groups (title bars included), wires that run backwards or hide behind a node, a node just under one that grows when it shows a picture, nodes outside every group, a saved zoom too small for the text to draw, and a missing Workflow Note. It checks inside every subgraph too. Click an entry to jump to it and select it. It moves nothing.
|
||||
- **Snap into line:** a node, group or selection you drag lines up with the nodes and groups around it, edge to edge or middle to middle, and a teal line shows what it lines up with. Pulling a corner to resize lines up the same way. Hold Shift while you drag to skip it, or turn it off in Settings → 🆎 AusBoss → Canvas.
|
||||
- **Line up:** select two or more nodes or groups and the selection toolbar gets a Line up button: line up edges or middles, match widths or heights, or space them evenly. With two or more nodes selected, pulling the edge or corner of one resizes them all: a column gets one width, a row one height, a grid both (turn it off in Settings → 🆎 AusBoss → Canvas → Resize together).
|
||||
- **Node colors:** Settings → 🆎 AusBoss → Appearance sets the scheme for every AusBoss node (AusBoss, Graphite, Slate, Teal, Moss, Plum, Rust, Navy, Custom or Theme default). A node's right-click **AusBoss color** menu recolors just that node, and nodes you colored by hand keep their colors.
|
||||
|
||||
@@ -21,7 +21,9 @@ NODE_MODULES = [
|
||||
"node_callout",
|
||||
"node_color_match",
|
||||
"node_compare",
|
||||
"node_cut_out",
|
||||
"node_edit_lock",
|
||||
"node_film_grain",
|
||||
"node_flashvsr_upscale",
|
||||
"node_frame_interpolate",
|
||||
"node_free_memory",
|
||||
@@ -32,6 +34,7 @@ NODE_MODULES = [
|
||||
"node_image_size",
|
||||
"node_image_toolbox",
|
||||
"node_inpaint_crop_stitch",
|
||||
"node_keep_detail",
|
||||
"node_krea2_encode",
|
||||
"node_krea2_model_patch",
|
||||
"node_lama_inpaint",
|
||||
@@ -58,6 +61,7 @@ NODE_MODULES = [
|
||||
"node_select_frame",
|
||||
"node_show_text",
|
||||
"node_step_preview",
|
||||
"node_strength_curve",
|
||||
"node_text_lines",
|
||||
"node_tiled_upscale",
|
||||
"node_video_crop_rotate_pad",
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="105" height="20" role="img" aria-label="release: v2.28.1">
|
||||
<title>release: v2.28.1</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.28.1</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 |
|
||||
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 206 KiB |
@@ -0,0 +1,993 @@
|
||||
{
|
||||
"id": "aba7bd0c-8de6-4044-a89e-cada288c8911",
|
||||
"revision": 0,
|
||||
"last_node_id": 15,
|
||||
"last_link_id": 11,
|
||||
"nodes": [
|
||||
{
|
||||
"id": 1,
|
||||
"type": "AUSBOSS_NODES_WorkflowNote",
|
||||
"pos": [
|
||||
0,
|
||||
30
|
||||
],
|
||||
"size": [
|
||||
440,
|
||||
640
|
||||
],
|
||||
"flags": {},
|
||||
"order": 0,
|
||||
"mode": 0,
|
||||
"inputs": [],
|
||||
"outputs": [],
|
||||
"properties": {
|
||||
"Node name for S&R": "AUSBOSS_NODES_WorkflowNote"
|
||||
},
|
||||
"widgets_values": [
|
||||
"{\"v\":1,\"title\":\"Film Grain, Cut Out and Keep Detail\",\"subtitle\":\"Finish a picture: add film grain, cut it out, or put back detail an edit smoothed away.\",\"author\":\"AusBoss\",\"layout\":\"card\",\"accent\":\"\",\"body\":\"[▶ AusBoss on YouTube](https://www.youtube.com/@ausbossdev) · videos on these nodes and workflows\\n\\n---\\n\\n1. Load your picture.\\n2. Press **Run**. Each node shows its result, and Save Image keeps it.\\n\\n### Good to know\\n\\n- **Film Grain** works on video too: new grain on every frame, or the same grain with **Video grain** on *still*.\\n- **Cut Out** gets its mask from two core nodes, Convert Image to Mask and Threshold Mask, so it needs no model. Wire Mask by Name or Mask by Touch for a real subject. The PNG keeps the transparency.\\n- **Keep Detail** needs the two pictures to line up. Image Blur here stands in for an edit; wire your own edit and the original.\\n\\nRuns on the CPU, with nothing to download. Needs AusBoss nodes newer than 2.28.1.\",\"models\":[],\"packs\":[{\"name\":\"ComfyUI-AusBoss\",\"url\":\"https://github.com/ausboss/ComfyUI-AusBoss\",\"node\":\"AUSBOSS_NODES_KeepDetail\"}],\"links\":[{\"label\":\"YouTube · ausbossdev\",\"url\":\"https://www.youtube.com/@ausbossdev\"},{\"label\":\"GitHub · ausboss\",\"url\":\"https://github.com/ausboss\"},{\"label\":\"Civitai · AusBoss\",\"url\":\"https://civitai.com/user/AusBoss\"},{\"label\":\"X · Zanzibased\",\"url\":\"https://x.com/Zanzibased\"}]}"
|
||||
],
|
||||
"widgets_values_named": {
|
||||
"note": "{\"v\":1,\"title\":\"Film Grain, Cut Out and Keep Detail\",\"subtitle\":\"Finish a picture: add film grain, cut it out, or put back detail an edit smoothed away.\",\"author\":\"AusBoss\",\"layout\":\"card\",\"accent\":\"\",\"body\":\"[▶ AusBoss on YouTube](https://www.youtube.com/@ausbossdev) · videos on these nodes and workflows\\n\\n---\\n\\n1. Load your picture.\\n2. Press **Run**. Each node shows its result, and Save Image keeps it.\\n\\n### Good to know\\n\\n- **Film Grain** works on video too: new grain on every frame, or the same grain with **Video grain** on *still*.\\n- **Cut Out** gets its mask from two core nodes, Convert Image to Mask and Threshold Mask, so it needs no model. Wire Mask by Name or Mask by Touch for a real subject. The PNG keeps the transparency.\\n- **Keep Detail** needs the two pictures to line up. Image Blur here stands in for an edit; wire your own edit and the original.\\n\\nRuns on the CPU, with nothing to download. Needs AusBoss nodes newer than 2.28.1.\",\"models\":[],\"packs\":[{\"name\":\"ComfyUI-AusBoss\",\"url\":\"https://github.com/ausboss/ComfyUI-AusBoss\",\"node\":\"AUSBOSS_NODES_KeepDetail\"}],\"links\":[{\"label\":\"YouTube · ausbossdev\",\"url\":\"https://www.youtube.com/@ausbossdev\"},{\"label\":\"GitHub · ausboss\",\"url\":\"https://github.com/ausboss\"},{\"label\":\"Civitai · AusBoss\",\"url\":\"https://civitai.com/user/AusBoss\"},{\"label\":\"X · Zanzibased\",\"url\":\"https://x.com/Zanzibased\"}]}"
|
||||
},
|
||||
"color": "#14424d",
|
||||
"bgcolor": "#161f21"
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"type": "LoadImage",
|
||||
"pos": [
|
||||
500,
|
||||
272
|
||||
],
|
||||
"size": [
|
||||
424,
|
||||
760
|
||||
],
|
||||
"flags": {},
|
||||
"order": 1,
|
||||
"mode": 0,
|
||||
"inputs": [],
|
||||
"outputs": [
|
||||
{
|
||||
"name": "IMAGE",
|
||||
"type": "IMAGE",
|
||||
"links": [
|
||||
1,
|
||||
3,
|
||||
5,
|
||||
8,
|
||||
10
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "MASK",
|
||||
"type": "MASK",
|
||||
"links": null
|
||||
}
|
||||
],
|
||||
"title": "Your picture",
|
||||
"properties": {
|
||||
"Node name for S&R": "LoadImage"
|
||||
},
|
||||
"widgets_values": [
|
||||
"",
|
||||
"image"
|
||||
],
|
||||
"widgets_values_named": {
|
||||
"image": "",
|
||||
"upload": "image"
|
||||
},
|
||||
"color": "#14424d",
|
||||
"bgcolor": "#161f21"
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"type": "AUSBOSS_NODES_Callout",
|
||||
"pos": [
|
||||
500,
|
||||
80
|
||||
],
|
||||
"size": [
|
||||
424,
|
||||
122
|
||||
],
|
||||
"flags": {},
|
||||
"order": 2,
|
||||
"mode": 0,
|
||||
"inputs": [],
|
||||
"outputs": [],
|
||||
"title": "Callout",
|
||||
"properties": {
|
||||
"Node name for S&R": "AUSBOSS_NODES_Callout"
|
||||
},
|
||||
"widgets_values": [
|
||||
"⬇️#2 Load your **picture** here."
|
||||
],
|
||||
"widgets_values_named": {
|
||||
"text": "⬇️#2 Load your **picture** here."
|
||||
},
|
||||
"color": "#07090a",
|
||||
"bgcolor": "#07090a"
|
||||
},
|
||||
{
|
||||
"id": 4,
|
||||
"type": "AUSBOSS_NODES_FilmGrain",
|
||||
"pos": [
|
||||
984,
|
||||
272
|
||||
],
|
||||
"size": [
|
||||
424,
|
||||
449
|
||||
],
|
||||
"flags": {},
|
||||
"order": 6,
|
||||
"mode": 0,
|
||||
"inputs": [
|
||||
{
|
||||
"name": "image",
|
||||
"type": "IMAGE",
|
||||
"link": 1
|
||||
},
|
||||
{
|
||||
"name": "mask",
|
||||
"shape": 7,
|
||||
"type": "MASK",
|
||||
"link": null
|
||||
}
|
||||
],
|
||||
"outputs": [
|
||||
{
|
||||
"name": "image",
|
||||
"type": "IMAGE",
|
||||
"links": [
|
||||
2
|
||||
]
|
||||
}
|
||||
],
|
||||
"properties": {
|
||||
"Node name for S&R": "AUSBOSS_NODES_FilmGrain"
|
||||
},
|
||||
"widgets_values": [
|
||||
0.3,
|
||||
1.2,
|
||||
0.5,
|
||||
0.2,
|
||||
true,
|
||||
0,
|
||||
true
|
||||
],
|
||||
"widgets_values_named": {
|
||||
"amount": 0.3,
|
||||
"size": 1.2,
|
||||
"roughness": 0.5,
|
||||
"color": 0.2,
|
||||
"moving": true,
|
||||
"seed": 0,
|
||||
"preview": true
|
||||
},
|
||||
"color": "#14424d",
|
||||
"bgcolor": "#161f21"
|
||||
},
|
||||
{
|
||||
"id": 5,
|
||||
"type": "AUSBOSS_NODES_Callout",
|
||||
"pos": [
|
||||
984,
|
||||
80
|
||||
],
|
||||
"size": [
|
||||
424,
|
||||
122
|
||||
],
|
||||
"flags": {},
|
||||
"order": 3,
|
||||
"mode": 0,
|
||||
"inputs": [],
|
||||
"outputs": [],
|
||||
"title": "Callout",
|
||||
"properties": {
|
||||
"Node name for S&R": "AUSBOSS_NODES_Callout"
|
||||
},
|
||||
"widgets_values": [
|
||||
"⬇️#4 Set the **grain**.\n###### Amount is how strong, Size how big each grain is in pixels. Color 0 is black-and-white grain."
|
||||
],
|
||||
"widgets_values_named": {
|
||||
"text": "⬇️#4 Set the **grain**.\n###### Amount is how strong, Size how big each grain is in pixels. Color 0 is black-and-white grain."
|
||||
},
|
||||
"color": "#07090a",
|
||||
"bgcolor": "#07090a"
|
||||
},
|
||||
{
|
||||
"id": 6,
|
||||
"type": "AUSBOSS_NODES_SaveImage",
|
||||
"pos": [
|
||||
984,
|
||||
791
|
||||
],
|
||||
"size": [
|
||||
424,
|
||||
422
|
||||
],
|
||||
"flags": {},
|
||||
"order": 9,
|
||||
"mode": 0,
|
||||
"inputs": [
|
||||
{
|
||||
"name": "images",
|
||||
"type": "IMAGE",
|
||||
"link": 2
|
||||
},
|
||||
{
|
||||
"name": "filename",
|
||||
"shape": 7,
|
||||
"type": "STRING",
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"name": "caption_text",
|
||||
"shape": 7,
|
||||
"type": "STRING",
|
||||
"link": null
|
||||
}
|
||||
],
|
||||
"outputs": [
|
||||
{
|
||||
"name": "file_path",
|
||||
"type": "STRING",
|
||||
"links": null
|
||||
},
|
||||
{
|
||||
"name": "images",
|
||||
"type": "IMAGE",
|
||||
"links": null
|
||||
}
|
||||
],
|
||||
"title": "Save Image - With grain",
|
||||
"properties": {
|
||||
"Node name for S&R": "AUSBOSS_NODES_SaveImage"
|
||||
},
|
||||
"widgets_values": {
|
||||
"filename_prefix": "film_grain",
|
||||
"format": "png",
|
||||
"save_metadata": true,
|
||||
"exact_name": "",
|
||||
"on_existing": "overwrite",
|
||||
"output_dir": "",
|
||||
"caption": "",
|
||||
"name_counter": true,
|
||||
"name_date": false,
|
||||
"name_time": false,
|
||||
"name_size": false,
|
||||
"name_batch": false,
|
||||
"preview": false,
|
||||
"step_preview": false,
|
||||
"autosave": true,
|
||||
"civitai_info": false
|
||||
},
|
||||
"widgets_values_named": {
|
||||
"filename_prefix": "film_grain",
|
||||
"format": "png",
|
||||
"save_metadata": true,
|
||||
"exact_name": "",
|
||||
"on_existing": "overwrite",
|
||||
"output_dir": "",
|
||||
"caption": "",
|
||||
"name_counter": true,
|
||||
"name_date": false,
|
||||
"name_time": false,
|
||||
"name_size": false,
|
||||
"name_batch": false,
|
||||
"preview": false,
|
||||
"step_preview": false,
|
||||
"autosave": true,
|
||||
"civitai_info": false
|
||||
},
|
||||
"color": "#14424d",
|
||||
"bgcolor": "#161f21"
|
||||
},
|
||||
{
|
||||
"id": 7,
|
||||
"type": "AUSBOSS_NODES_Callout",
|
||||
"pos": [
|
||||
1468,
|
||||
80
|
||||
],
|
||||
"size": [
|
||||
424,
|
||||
122
|
||||
],
|
||||
"flags": {},
|
||||
"order": 4,
|
||||
"mode": 0,
|
||||
"inputs": [],
|
||||
"outputs": [],
|
||||
"title": "Callout",
|
||||
"properties": {
|
||||
"Node name for S&R": "AUSBOSS_NODES_Callout"
|
||||
},
|
||||
"widgets_values": [
|
||||
"The mask is the picture's blue channel, with no model.\n###### Wire your own mask here, such as one from Mask by Name."
|
||||
],
|
||||
"widgets_values_named": {
|
||||
"text": "The mask is the picture's blue channel, with no model.\n###### Wire your own mask here, such as one from Mask by Name."
|
||||
},
|
||||
"color": "#07090a",
|
||||
"bgcolor": "#07090a"
|
||||
},
|
||||
{
|
||||
"id": 8,
|
||||
"type": "ImageToMask",
|
||||
"pos": [
|
||||
1468,
|
||||
272
|
||||
],
|
||||
"size": [
|
||||
424,
|
||||
58
|
||||
],
|
||||
"flags": {},
|
||||
"order": 7,
|
||||
"mode": 0,
|
||||
"inputs": [
|
||||
{
|
||||
"name": "image",
|
||||
"type": "IMAGE",
|
||||
"link": 3
|
||||
}
|
||||
],
|
||||
"outputs": [
|
||||
{
|
||||
"name": "MASK",
|
||||
"type": "MASK",
|
||||
"links": [
|
||||
4
|
||||
]
|
||||
}
|
||||
],
|
||||
"title": "Convert Image to Mask - Blue channel",
|
||||
"properties": {
|
||||
"Node name for S&R": "ImageToMask"
|
||||
},
|
||||
"widgets_values": [
|
||||
"blue"
|
||||
],
|
||||
"widgets_values_named": {
|
||||
"channel": "blue"
|
||||
},
|
||||
"color": "#14424d",
|
||||
"bgcolor": "#161f21"
|
||||
},
|
||||
{
|
||||
"id": 9,
|
||||
"type": "ThresholdMask",
|
||||
"pos": [
|
||||
1468,
|
||||
400
|
||||
],
|
||||
"size": [
|
||||
424,
|
||||
58
|
||||
],
|
||||
"flags": {},
|
||||
"order": 10,
|
||||
"mode": 0,
|
||||
"inputs": [
|
||||
{
|
||||
"name": "mask",
|
||||
"type": "MASK",
|
||||
"link": 4
|
||||
}
|
||||
],
|
||||
"outputs": [
|
||||
{
|
||||
"name": "MASK",
|
||||
"type": "MASK",
|
||||
"links": [
|
||||
6
|
||||
]
|
||||
}
|
||||
],
|
||||
"title": "Threshold Mask - Sky and mist",
|
||||
"properties": {
|
||||
"Node name for S&R": "ThresholdMask"
|
||||
},
|
||||
"widgets_values": [
|
||||
0.55
|
||||
],
|
||||
"widgets_values_named": {
|
||||
"value": 0.55
|
||||
},
|
||||
"color": "#14424d",
|
||||
"bgcolor": "#161f21"
|
||||
},
|
||||
{
|
||||
"id": 10,
|
||||
"type": "AUSBOSS_NODES_CutOut",
|
||||
"pos": [
|
||||
1468,
|
||||
528
|
||||
],
|
||||
"size": [
|
||||
424,
|
||||
418
|
||||
],
|
||||
"flags": {},
|
||||
"order": 12,
|
||||
"mode": 0,
|
||||
"inputs": [
|
||||
{
|
||||
"name": "image",
|
||||
"type": "IMAGE",
|
||||
"link": 5
|
||||
},
|
||||
{
|
||||
"name": "mask",
|
||||
"type": "MASK",
|
||||
"link": 6
|
||||
}
|
||||
],
|
||||
"outputs": [
|
||||
{
|
||||
"name": "image",
|
||||
"type": "IMAGE",
|
||||
"links": [
|
||||
7
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "alpha",
|
||||
"type": "MASK",
|
||||
"links": null
|
||||
}
|
||||
],
|
||||
"properties": {
|
||||
"Node name for S&R": "AUSBOSS_NODES_CutOut"
|
||||
},
|
||||
"widgets_values": [
|
||||
"black",
|
||||
0,
|
||||
1,
|
||||
true,
|
||||
0,
|
||||
1,
|
||||
0,
|
||||
true
|
||||
],
|
||||
"widgets_values_named": {
|
||||
"keep": "black",
|
||||
"grow": 0,
|
||||
"feather": 1,
|
||||
"clean_edges": true,
|
||||
"clear_haze": 0,
|
||||
"solid_above": 1,
|
||||
"smooth_frames": 0,
|
||||
"preview": true
|
||||
},
|
||||
"color": "#14424d",
|
||||
"bgcolor": "#161f21"
|
||||
},
|
||||
{
|
||||
"id": 11,
|
||||
"type": "AUSBOSS_NODES_SaveImage",
|
||||
"pos": [
|
||||
1468,
|
||||
1016
|
||||
],
|
||||
"size": [
|
||||
424,
|
||||
422
|
||||
],
|
||||
"flags": {},
|
||||
"order": 14,
|
||||
"mode": 0,
|
||||
"inputs": [
|
||||
{
|
||||
"name": "images",
|
||||
"type": "IMAGE",
|
||||
"link": 7
|
||||
},
|
||||
{
|
||||
"name": "filename",
|
||||
"shape": 7,
|
||||
"type": "STRING",
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"name": "caption_text",
|
||||
"shape": 7,
|
||||
"type": "STRING",
|
||||
"link": null
|
||||
}
|
||||
],
|
||||
"outputs": [
|
||||
{
|
||||
"name": "file_path",
|
||||
"type": "STRING",
|
||||
"links": null
|
||||
},
|
||||
{
|
||||
"name": "images",
|
||||
"type": "IMAGE",
|
||||
"links": null
|
||||
}
|
||||
],
|
||||
"title": "Save Image - The cut-out",
|
||||
"properties": {
|
||||
"Node name for S&R": "AUSBOSS_NODES_SaveImage"
|
||||
},
|
||||
"widgets_values": {
|
||||
"filename_prefix": "cut_out",
|
||||
"format": "png",
|
||||
"save_metadata": true,
|
||||
"exact_name": "",
|
||||
"on_existing": "overwrite",
|
||||
"output_dir": "",
|
||||
"caption": "",
|
||||
"name_counter": true,
|
||||
"name_date": false,
|
||||
"name_time": false,
|
||||
"name_size": false,
|
||||
"name_batch": false,
|
||||
"preview": false,
|
||||
"step_preview": false,
|
||||
"autosave": true,
|
||||
"civitai_info": false
|
||||
},
|
||||
"widgets_values_named": {
|
||||
"filename_prefix": "cut_out",
|
||||
"format": "png",
|
||||
"save_metadata": true,
|
||||
"exact_name": "",
|
||||
"on_existing": "overwrite",
|
||||
"output_dir": "",
|
||||
"caption": "",
|
||||
"name_counter": true,
|
||||
"name_date": false,
|
||||
"name_time": false,
|
||||
"name_size": false,
|
||||
"name_batch": false,
|
||||
"preview": false,
|
||||
"step_preview": false,
|
||||
"autosave": true,
|
||||
"civitai_info": false
|
||||
},
|
||||
"color": "#14424d",
|
||||
"bgcolor": "#161f21"
|
||||
},
|
||||
{
|
||||
"id": 12,
|
||||
"type": "AUSBOSS_NODES_Callout",
|
||||
"pos": [
|
||||
1952,
|
||||
80
|
||||
],
|
||||
"size": [
|
||||
424,
|
||||
122
|
||||
],
|
||||
"flags": {},
|
||||
"order": 5,
|
||||
"mode": 0,
|
||||
"inputs": [],
|
||||
"outputs": [],
|
||||
"title": "Callout",
|
||||
"properties": {
|
||||
"Node name for S&R": "AUSBOSS_NODES_Callout"
|
||||
},
|
||||
"widgets_values": [
|
||||
"Image Blur stands in for an edit that came out too smooth.\n###### Edge safe is off under More, because a blur softens strong edges too. Wire your own edit to image and the original to detail_from."
|
||||
],
|
||||
"widgets_values_named": {
|
||||
"text": "Image Blur stands in for an edit that came out too smooth.\n###### Edge safe is off under More, because a blur softens strong edges too. Wire your own edit to image and the original to detail_from."
|
||||
},
|
||||
"color": "#07090a",
|
||||
"bgcolor": "#07090a"
|
||||
},
|
||||
{
|
||||
"id": 13,
|
||||
"type": "ImageBlur",
|
||||
"pos": [
|
||||
1952,
|
||||
272
|
||||
],
|
||||
"size": [
|
||||
424,
|
||||
82
|
||||
],
|
||||
"flags": {},
|
||||
"order": 8,
|
||||
"mode": 0,
|
||||
"inputs": [
|
||||
{
|
||||
"name": "image",
|
||||
"type": "IMAGE",
|
||||
"link": 8
|
||||
}
|
||||
],
|
||||
"outputs": [
|
||||
{
|
||||
"name": "IMAGE",
|
||||
"type": "IMAGE",
|
||||
"links": [
|
||||
9
|
||||
]
|
||||
}
|
||||
],
|
||||
"title": "Image Blur - Stands in for a smooth edit",
|
||||
"properties": {
|
||||
"Node name for S&R": "ImageBlur"
|
||||
},
|
||||
"widgets_values": [
|
||||
4,
|
||||
2
|
||||
],
|
||||
"widgets_values_named": {
|
||||
"blur_radius": 4,
|
||||
"sigma": 2
|
||||
},
|
||||
"color": "#14424d",
|
||||
"bgcolor": "#161f21"
|
||||
},
|
||||
{
|
||||
"id": 14,
|
||||
"type": "AUSBOSS_NODES_KeepDetail",
|
||||
"pos": [
|
||||
1952,
|
||||
424
|
||||
],
|
||||
"size": [
|
||||
424,
|
||||
407
|
||||
],
|
||||
"flags": {},
|
||||
"order": 11,
|
||||
"mode": 0,
|
||||
"inputs": [
|
||||
{
|
||||
"name": "image",
|
||||
"type": "IMAGE",
|
||||
"link": 9
|
||||
},
|
||||
{
|
||||
"name": "detail_from",
|
||||
"type": "IMAGE",
|
||||
"link": 10
|
||||
},
|
||||
{
|
||||
"name": "mask",
|
||||
"shape": 7,
|
||||
"type": "MASK",
|
||||
"link": null
|
||||
}
|
||||
],
|
||||
"outputs": [
|
||||
{
|
||||
"name": "image",
|
||||
"type": "IMAGE",
|
||||
"links": [
|
||||
11
|
||||
]
|
||||
}
|
||||
],
|
||||
"properties": {
|
||||
"Node name for S&R": "AUSBOSS_NODES_KeepDetail"
|
||||
},
|
||||
"widgets_values": [
|
||||
4,
|
||||
1,
|
||||
false,
|
||||
false,
|
||||
true
|
||||
],
|
||||
"widgets_values_named": {
|
||||
"detail_size": 4,
|
||||
"strength": 1,
|
||||
"color_detail": false,
|
||||
"edge_safe": false,
|
||||
"preview": true
|
||||
},
|
||||
"color": "#14424d",
|
||||
"bgcolor": "#161f21"
|
||||
},
|
||||
{
|
||||
"id": 15,
|
||||
"type": "AUSBOSS_NODES_SaveImage",
|
||||
"pos": [
|
||||
1952,
|
||||
901
|
||||
],
|
||||
"size": [
|
||||
424,
|
||||
422
|
||||
],
|
||||
"flags": {},
|
||||
"order": 13,
|
||||
"mode": 0,
|
||||
"inputs": [
|
||||
{
|
||||
"name": "images",
|
||||
"type": "IMAGE",
|
||||
"link": 11
|
||||
},
|
||||
{
|
||||
"name": "filename",
|
||||
"shape": 7,
|
||||
"type": "STRING",
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"name": "caption_text",
|
||||
"shape": 7,
|
||||
"type": "STRING",
|
||||
"link": null
|
||||
}
|
||||
],
|
||||
"outputs": [
|
||||
{
|
||||
"name": "file_path",
|
||||
"type": "STRING",
|
||||
"links": null
|
||||
},
|
||||
{
|
||||
"name": "images",
|
||||
"type": "IMAGE",
|
||||
"links": null
|
||||
}
|
||||
],
|
||||
"title": "Save Image - With the detail back",
|
||||
"properties": {
|
||||
"Node name for S&R": "AUSBOSS_NODES_SaveImage"
|
||||
},
|
||||
"widgets_values": {
|
||||
"filename_prefix": "keep_detail",
|
||||
"format": "png",
|
||||
"save_metadata": true,
|
||||
"exact_name": "",
|
||||
"on_existing": "overwrite",
|
||||
"output_dir": "",
|
||||
"caption": "",
|
||||
"name_counter": true,
|
||||
"name_date": false,
|
||||
"name_time": false,
|
||||
"name_size": false,
|
||||
"name_batch": false,
|
||||
"preview": false,
|
||||
"step_preview": false,
|
||||
"autosave": true,
|
||||
"civitai_info": false
|
||||
},
|
||||
"widgets_values_named": {
|
||||
"filename_prefix": "keep_detail",
|
||||
"format": "png",
|
||||
"save_metadata": true,
|
||||
"exact_name": "",
|
||||
"on_existing": "overwrite",
|
||||
"output_dir": "",
|
||||
"caption": "",
|
||||
"name_counter": true,
|
||||
"name_date": false,
|
||||
"name_time": false,
|
||||
"name_size": false,
|
||||
"name_batch": false,
|
||||
"preview": false,
|
||||
"step_preview": false,
|
||||
"autosave": true,
|
||||
"civitai_info": false
|
||||
},
|
||||
"color": "#14424d",
|
||||
"bgcolor": "#161f21"
|
||||
}
|
||||
],
|
||||
"links": [
|
||||
[
|
||||
1,
|
||||
2,
|
||||
0,
|
||||
4,
|
||||
0,
|
||||
"IMAGE"
|
||||
],
|
||||
[
|
||||
2,
|
||||
4,
|
||||
0,
|
||||
6,
|
||||
0,
|
||||
"IMAGE"
|
||||
],
|
||||
[
|
||||
3,
|
||||
2,
|
||||
0,
|
||||
8,
|
||||
0,
|
||||
"IMAGE"
|
||||
],
|
||||
[
|
||||
4,
|
||||
8,
|
||||
0,
|
||||
9,
|
||||
0,
|
||||
"MASK"
|
||||
],
|
||||
[
|
||||
5,
|
||||
2,
|
||||
0,
|
||||
10,
|
||||
0,
|
||||
"IMAGE"
|
||||
],
|
||||
[
|
||||
6,
|
||||
9,
|
||||
0,
|
||||
10,
|
||||
1,
|
||||
"MASK"
|
||||
],
|
||||
[
|
||||
7,
|
||||
10,
|
||||
0,
|
||||
11,
|
||||
0,
|
||||
"IMAGE"
|
||||
],
|
||||
[
|
||||
8,
|
||||
2,
|
||||
0,
|
||||
13,
|
||||
0,
|
||||
"IMAGE"
|
||||
],
|
||||
[
|
||||
9,
|
||||
13,
|
||||
0,
|
||||
14,
|
||||
0,
|
||||
"IMAGE"
|
||||
],
|
||||
[
|
||||
10,
|
||||
2,
|
||||
0,
|
||||
14,
|
||||
1,
|
||||
"IMAGE"
|
||||
],
|
||||
[
|
||||
11,
|
||||
14,
|
||||
0,
|
||||
15,
|
||||
0,
|
||||
"IMAGE"
|
||||
]
|
||||
],
|
||||
"groups": [
|
||||
{
|
||||
"id": 1,
|
||||
"title": "1 · Your picture",
|
||||
"bounding": [
|
||||
480,
|
||||
0,
|
||||
464,
|
||||
1458
|
||||
],
|
||||
"color": "#1d5560",
|
||||
"flags": {}
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"title": "2 · Film Grain",
|
||||
"bounding": [
|
||||
964,
|
||||
0,
|
||||
464,
|
||||
1458
|
||||
],
|
||||
"color": "#1d5560",
|
||||
"flags": {}
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"title": "3 · Cut Out",
|
||||
"bounding": [
|
||||
1448,
|
||||
0,
|
||||
464,
|
||||
1458
|
||||
],
|
||||
"color": "#1d5560",
|
||||
"flags": {}
|
||||
},
|
||||
{
|
||||
"id": 4,
|
||||
"title": "4 · Keep Detail",
|
||||
"bounding": [
|
||||
1932,
|
||||
0,
|
||||
464,
|
||||
1458
|
||||
],
|
||||
"color": "#1d5560",
|
||||
"flags": {}
|
||||
}
|
||||
],
|
||||
"config": {},
|
||||
"extra": {
|
||||
"ds": {
|
||||
"scale": 0.6,
|
||||
"offset": [
|
||||
20,
|
||||
60
|
||||
]
|
||||
},
|
||||
"frontendVersion": "1.58.5",
|
||||
"reroutes": [
|
||||
{
|
||||
"id": 1,
|
||||
"pos": [
|
||||
954,
|
||||
222
|
||||
],
|
||||
"linkIds": [
|
||||
3,
|
||||
5,
|
||||
8,
|
||||
10
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"parentId": 1,
|
||||
"pos": [
|
||||
1438,
|
||||
222
|
||||
],
|
||||
"linkIds": [
|
||||
3,
|
||||
5,
|
||||
8,
|
||||
10
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"parentId": 2,
|
||||
"pos": [
|
||||
1922,
|
||||
222
|
||||
],
|
||||
"linkIds": [
|
||||
8,
|
||||
10
|
||||
]
|
||||
}
|
||||
],
|
||||
"linkExtensions": [
|
||||
{
|
||||
"id": 3,
|
||||
"parentId": 2
|
||||
},
|
||||
{
|
||||
"id": 5,
|
||||
"parentId": 2
|
||||
},
|
||||
{
|
||||
"id": 8,
|
||||
"parentId": 3
|
||||
},
|
||||
{
|
||||
"id": 10,
|
||||
"parentId": 3
|
||||
}
|
||||
]
|
||||
},
|
||||
"version": 0.4
|
||||
}
|
||||
@@ -520,7 +520,42 @@
|
||||
137,
|
||||
20
|
||||
]
|
||||
}
|
||||
},
|
||||
"reroutes": [
|
||||
{
|
||||
"id": 1,
|
||||
"pos": [
|
||||
950,
|
||||
310
|
||||
],
|
||||
"linkIds": [
|
||||
3,
|
||||
4
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"parentId": 1,
|
||||
"pos": [
|
||||
1370,
|
||||
310
|
||||
],
|
||||
"linkIds": [
|
||||
3,
|
||||
4
|
||||
]
|
||||
}
|
||||
],
|
||||
"linkExtensions": [
|
||||
{
|
||||
"id": 3,
|
||||
"parentId": 2
|
||||
},
|
||||
{
|
||||
"id": 4,
|
||||
"parentId": 2
|
||||
}
|
||||
]
|
||||
},
|
||||
"version": 0.4
|
||||
}
|
||||
@@ -1706,7 +1706,7 @@
|
||||
"type": "SetLatentNoiseMask",
|
||||
"pos": [
|
||||
20,
|
||||
354
|
||||
398
|
||||
],
|
||||
"size": [
|
||||
460,
|
||||
@@ -1947,7 +1947,7 @@
|
||||
"type": "KSampler",
|
||||
"pos": [
|
||||
1100,
|
||||
304
|
||||
338
|
||||
],
|
||||
"size": [
|
||||
460,
|
||||
@@ -2325,7 +2325,7 @@
|
||||
0,
|
||||
0,
|
||||
500,
|
||||
428
|
||||
470
|
||||
],
|
||||
"color": "#1d5560",
|
||||
"flags": {}
|
||||
@@ -2349,7 +2349,7 @@
|
||||
1080,
|
||||
0,
|
||||
500,
|
||||
586
|
||||
620
|
||||
],
|
||||
"color": "#1d5560",
|
||||
"flags": {}
|
||||
@@ -2361,7 +2361,7 @@
|
||||
1620,
|
||||
0,
|
||||
500,
|
||||
529
|
||||
620
|
||||
],
|
||||
"color": "#1d5560",
|
||||
"flags": {}
|
||||
@@ -2446,7 +2446,8 @@
|
||||
"origin_slot": 0,
|
||||
"target_id": 11,
|
||||
"target_slot": 0,
|
||||
"type": "CONDITIONING"
|
||||
"type": "CONDITIONING",
|
||||
"parentId": 1
|
||||
},
|
||||
{
|
||||
"id": 34,
|
||||
@@ -2553,7 +2554,19 @@
|
||||
"type": "IMAGE"
|
||||
}
|
||||
],
|
||||
"extra": {}
|
||||
"extra": {},
|
||||
"reroutes": [
|
||||
{
|
||||
"id": 1,
|
||||
"pos": [
|
||||
1060,
|
||||
540
|
||||
],
|
||||
"linkIds": [
|
||||
33
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -2566,7 +2579,92 @@
|
||||
20
|
||||
]
|
||||
},
|
||||
"frontendVersion": "1.53.6"
|
||||
"frontendVersion": "1.53.6",
|
||||
"reroutes": [
|
||||
{
|
||||
"id": 1,
|
||||
"pos": [
|
||||
1040,
|
||||
188
|
||||
],
|
||||
"linkIds": [
|
||||
14
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"parentId": 1,
|
||||
"pos": [
|
||||
1580,
|
||||
188
|
||||
],
|
||||
"linkIds": [
|
||||
14
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"pos": [
|
||||
1580,
|
||||
325
|
||||
],
|
||||
"linkIds": [
|
||||
4
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 4,
|
||||
"pos": [
|
||||
1562,
|
||||
450
|
||||
],
|
||||
"linkIds": [
|
||||
10
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 5,
|
||||
"pos": [
|
||||
1580,
|
||||
425
|
||||
],
|
||||
"linkIds": [
|
||||
11
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 6,
|
||||
"pos": [
|
||||
1604,
|
||||
400
|
||||
],
|
||||
"linkIds": [
|
||||
12
|
||||
]
|
||||
}
|
||||
],
|
||||
"linkExtensions": [
|
||||
{
|
||||
"id": 14,
|
||||
"parentId": 2
|
||||
},
|
||||
{
|
||||
"id": 4,
|
||||
"parentId": 3
|
||||
},
|
||||
{
|
||||
"id": 10,
|
||||
"parentId": 4
|
||||
},
|
||||
{
|
||||
"id": 11,
|
||||
"parentId": 5
|
||||
},
|
||||
{
|
||||
"id": 12,
|
||||
"parentId": 6
|
||||
}
|
||||
]
|
||||
},
|
||||
"version": 0.4
|
||||
}
|
||||
|
||||
@@ -2769,7 +2769,7 @@
|
||||
"type": "KSampler",
|
||||
"pos": [
|
||||
1100,
|
||||
546
|
||||
646
|
||||
],
|
||||
"size": [
|
||||
460,
|
||||
@@ -3088,8 +3088,8 @@
|
||||
"id": 37,
|
||||
"type": "Reroute",
|
||||
"pos": [
|
||||
1100,
|
||||
450
|
||||
1082,
|
||||
510
|
||||
],
|
||||
"size": [
|
||||
75,
|
||||
@@ -3150,7 +3150,7 @@
|
||||
"id": 47,
|
||||
"type": "Reroute",
|
||||
"pos": [
|
||||
1200,
|
||||
1118,
|
||||
450
|
||||
],
|
||||
"size": [
|
||||
@@ -3214,7 +3214,7 @@
|
||||
1080,
|
||||
0,
|
||||
500,
|
||||
828
|
||||
928
|
||||
],
|
||||
"color": "#1d5560",
|
||||
"flags": {}
|
||||
@@ -3226,7 +3226,7 @@
|
||||
1620,
|
||||
0,
|
||||
500,
|
||||
529
|
||||
600
|
||||
],
|
||||
"color": "#1d5560",
|
||||
"flags": {}
|
||||
@@ -3466,7 +3466,8 @@
|
||||
"type": "FLOAT"
|
||||
}
|
||||
],
|
||||
"extra": {}
|
||||
"extra": {},
|
||||
"reroutes": []
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -3479,7 +3480,117 @@
|
||||
96
|
||||
]
|
||||
},
|
||||
"frontendVersion": "1.53.6"
|
||||
"frontendVersion": "1.53.6",
|
||||
"reroutes": [
|
||||
{
|
||||
"id": 1,
|
||||
"pos": [
|
||||
964,
|
||||
350
|
||||
],
|
||||
"linkIds": [
|
||||
70
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"pos": [
|
||||
976,
|
||||
410
|
||||
],
|
||||
"linkIds": [
|
||||
79
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"pos": [
|
||||
952,
|
||||
860
|
||||
],
|
||||
"linkIds": [
|
||||
71
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 4,
|
||||
"parentId": 3,
|
||||
"pos": [
|
||||
964,
|
||||
430
|
||||
],
|
||||
"linkIds": [
|
||||
71
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 5,
|
||||
"pos": [
|
||||
1556,
|
||||
420
|
||||
],
|
||||
"linkIds": [
|
||||
73
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 6,
|
||||
"pos": [
|
||||
1576,
|
||||
450
|
||||
],
|
||||
"linkIds": [
|
||||
74
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 7,
|
||||
"pos": [
|
||||
955,
|
||||
188
|
||||
],
|
||||
"linkIds": [
|
||||
42
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 8,
|
||||
"parentId": 7,
|
||||
"pos": [
|
||||
1564,
|
||||
188
|
||||
],
|
||||
"linkIds": [
|
||||
42
|
||||
]
|
||||
}
|
||||
],
|
||||
"linkExtensions": [
|
||||
{
|
||||
"id": 70,
|
||||
"parentId": 1
|
||||
},
|
||||
{
|
||||
"id": 79,
|
||||
"parentId": 2
|
||||
},
|
||||
{
|
||||
"id": 71,
|
||||
"parentId": 4
|
||||
},
|
||||
{
|
||||
"id": 73,
|
||||
"parentId": 5
|
||||
},
|
||||
{
|
||||
"id": 74,
|
||||
"parentId": 6
|
||||
},
|
||||
{
|
||||
"id": 42,
|
||||
"parentId": 8
|
||||
}
|
||||
]
|
||||
},
|
||||
"version": 0.4
|
||||
}
|
||||
|
||||
@@ -2183,7 +2183,7 @@
|
||||
1080,
|
||||
0,
|
||||
500,
|
||||
529
|
||||
600
|
||||
],
|
||||
"color": "#1d5560",
|
||||
"flags": {}
|
||||
@@ -2375,7 +2375,8 @@
|
||||
"type": "MASK"
|
||||
}
|
||||
],
|
||||
"extra": {}
|
||||
"extra": {},
|
||||
"reroutes": []
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -2388,7 +2389,78 @@
|
||||
20
|
||||
]
|
||||
},
|
||||
"frontendVersion": "1.53.6"
|
||||
"frontendVersion": "1.53.6",
|
||||
"reroutes": [
|
||||
{
|
||||
"id": 1,
|
||||
"pos": [
|
||||
950,
|
||||
188
|
||||
],
|
||||
"linkIds": [
|
||||
31
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"parentId": 1,
|
||||
"pos": [
|
||||
1462,
|
||||
188
|
||||
],
|
||||
"linkIds": [
|
||||
31
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"pos": [
|
||||
1468,
|
||||
325
|
||||
],
|
||||
"linkIds": [
|
||||
43
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 4,
|
||||
"pos": [
|
||||
1444,
|
||||
475
|
||||
],
|
||||
"linkIds": [
|
||||
50
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 5,
|
||||
"pos": [
|
||||
1468,
|
||||
450
|
||||
],
|
||||
"linkIds": [
|
||||
51
|
||||
]
|
||||
}
|
||||
],
|
||||
"linkExtensions": [
|
||||
{
|
||||
"id": 31,
|
||||
"parentId": 2
|
||||
},
|
||||
{
|
||||
"id": 43,
|
||||
"parentId": 3
|
||||
},
|
||||
{
|
||||
"id": 50,
|
||||
"parentId": 4
|
||||
},
|
||||
{
|
||||
"id": 51,
|
||||
"parentId": 5
|
||||
}
|
||||
]
|
||||
},
|
||||
"version": 0.4
|
||||
}
|
||||
@@ -612,7 +612,7 @@
|
||||
"type": "2f8cb72f-ebab-4ed9-bb0c-328a4e6493d9",
|
||||
"pos": [
|
||||
1020,
|
||||
238
|
||||
380
|
||||
],
|
||||
"size": [
|
||||
240,
|
||||
@@ -2180,7 +2180,7 @@
|
||||
1080,
|
||||
0,
|
||||
500,
|
||||
529
|
||||
600
|
||||
],
|
||||
"color": "#1d5560",
|
||||
"flags": {}
|
||||
@@ -2372,7 +2372,8 @@
|
||||
"type": "MASK"
|
||||
}
|
||||
],
|
||||
"extra": {}
|
||||
"extra": {},
|
||||
"reroutes": []
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -2385,7 +2386,131 @@
|
||||
20
|
||||
]
|
||||
},
|
||||
"frontendVersion": "1.53.6"
|
||||
"frontendVersion": "1.53.6",
|
||||
"reroutes": [
|
||||
{
|
||||
"id": 1,
|
||||
"pos": [
|
||||
950,
|
||||
188
|
||||
],
|
||||
"linkIds": [
|
||||
31
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"parentId": 1,
|
||||
"pos": [
|
||||
1580,
|
||||
188
|
||||
],
|
||||
"linkIds": [
|
||||
31
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"pos": [
|
||||
968,
|
||||
900
|
||||
],
|
||||
"linkIds": [
|
||||
48
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 4,
|
||||
"parentId": 3,
|
||||
"pos": [
|
||||
984,
|
||||
350
|
||||
],
|
||||
"linkIds": [
|
||||
48
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 5,
|
||||
"pos": [
|
||||
1564,
|
||||
450
|
||||
],
|
||||
"linkIds": [
|
||||
50
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 6,
|
||||
"pos": [
|
||||
1596,
|
||||
400
|
||||
],
|
||||
"linkIds": [
|
||||
51
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 7,
|
||||
"pos": [
|
||||
955,
|
||||
182
|
||||
],
|
||||
"linkIds": [
|
||||
44
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 8,
|
||||
"pos": [
|
||||
955,
|
||||
194
|
||||
],
|
||||
"linkIds": [
|
||||
45
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 9,
|
||||
"pos": [
|
||||
955,
|
||||
206
|
||||
],
|
||||
"linkIds": [
|
||||
46
|
||||
]
|
||||
}
|
||||
],
|
||||
"linkExtensions": [
|
||||
{
|
||||
"id": 31,
|
||||
"parentId": 2
|
||||
},
|
||||
{
|
||||
"id": 48,
|
||||
"parentId": 4
|
||||
},
|
||||
{
|
||||
"id": 50,
|
||||
"parentId": 5
|
||||
},
|
||||
{
|
||||
"id": 51,
|
||||
"parentId": 6
|
||||
},
|
||||
{
|
||||
"id": 44,
|
||||
"parentId": 7
|
||||
},
|
||||
{
|
||||
"id": 45,
|
||||
"parentId": 8
|
||||
},
|
||||
{
|
||||
"id": 46,
|
||||
"parentId": 9
|
||||
}
|
||||
]
|
||||
},
|
||||
"version": 0.4
|
||||
}
|
||||
@@ -2785,7 +2785,7 @@
|
||||
1080,
|
||||
0,
|
||||
500,
|
||||
719
|
||||
780
|
||||
],
|
||||
"color": "#1d5560",
|
||||
"flags": {}
|
||||
@@ -2990,7 +2990,8 @@
|
||||
"origin_slot": 0,
|
||||
"target_id": 19,
|
||||
"target_slot": 0,
|
||||
"type": "CONDITIONING"
|
||||
"type": "CONDITIONING",
|
||||
"parentId": 1
|
||||
},
|
||||
{
|
||||
"id": 147,
|
||||
@@ -2998,7 +2999,8 @@
|
||||
"origin_slot": 1,
|
||||
"target_id": 19,
|
||||
"target_slot": 1,
|
||||
"type": "CONDITIONING"
|
||||
"type": "CONDITIONING",
|
||||
"parentId": 2
|
||||
},
|
||||
{
|
||||
"id": 148,
|
||||
@@ -3065,7 +3067,29 @@
|
||||
"type": "FLOAT"
|
||||
}
|
||||
],
|
||||
"extra": {}
|
||||
"extra": {},
|
||||
"reroutes": [
|
||||
{
|
||||
"id": 1,
|
||||
"pos": [
|
||||
1080,
|
||||
900
|
||||
],
|
||||
"linkIds": [
|
||||
146
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"pos": [
|
||||
1090,
|
||||
900
|
||||
],
|
||||
"linkIds": [
|
||||
147
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -3078,7 +3102,53 @@
|
||||
25
|
||||
]
|
||||
},
|
||||
"frontendVersion": "1.53.6"
|
||||
"frontendVersion": "1.53.6",
|
||||
"reroutes": [
|
||||
{
|
||||
"id": 1,
|
||||
"pos": [
|
||||
1508,
|
||||
325
|
||||
],
|
||||
"linkIds": [
|
||||
63
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"pos": [
|
||||
1476,
|
||||
475
|
||||
],
|
||||
"linkIds": [
|
||||
59
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"pos": [
|
||||
1508,
|
||||
400
|
||||
],
|
||||
"linkIds": [
|
||||
60
|
||||
]
|
||||
}
|
||||
],
|
||||
"linkExtensions": [
|
||||
{
|
||||
"id": 63,
|
||||
"parentId": 1
|
||||
},
|
||||
{
|
||||
"id": 59,
|
||||
"parentId": 2
|
||||
},
|
||||
{
|
||||
"id": 60,
|
||||
"parentId": 3
|
||||
}
|
||||
]
|
||||
},
|
||||
"version": 0.4
|
||||
}
|
||||
@@ -1280,7 +1280,36 @@
|
||||
60
|
||||
]
|
||||
},
|
||||
"frontendVersion": "1.53.6"
|
||||
"frontendVersion": "1.53.6",
|
||||
"reroutes": [
|
||||
{
|
||||
"id": 1,
|
||||
"pos": [
|
||||
1464,
|
||||
205
|
||||
],
|
||||
"linkIds": [
|
||||
5
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"parentId": 1,
|
||||
"pos": [
|
||||
1924,
|
||||
205
|
||||
],
|
||||
"linkIds": [
|
||||
5
|
||||
]
|
||||
}
|
||||
],
|
||||
"linkExtensions": [
|
||||
{
|
||||
"id": 5,
|
||||
"parentId": 2
|
||||
}
|
||||
]
|
||||
},
|
||||
"version": 0.4
|
||||
}
|
||||
|
||||
@@ -1135,7 +1135,64 @@
|
||||
60
|
||||
]
|
||||
},
|
||||
"frontendVersion": "1.53.6"
|
||||
"frontendVersion": "1.53.6",
|
||||
"reroutes": [
|
||||
{
|
||||
"id": 1,
|
||||
"pos": [
|
||||
1504,
|
||||
205
|
||||
],
|
||||
"linkIds": [
|
||||
5
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"parentId": 1,
|
||||
"pos": [
|
||||
1964,
|
||||
205
|
||||
],
|
||||
"linkIds": [
|
||||
5
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"pos": [
|
||||
1508,
|
||||
441
|
||||
],
|
||||
"linkIds": [
|
||||
2
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 4,
|
||||
"pos": [
|
||||
1516,
|
||||
451
|
||||
],
|
||||
"linkIds": [
|
||||
3
|
||||
]
|
||||
}
|
||||
],
|
||||
"linkExtensions": [
|
||||
{
|
||||
"id": 5,
|
||||
"parentId": 2
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"parentId": 3
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"parentId": 4
|
||||
}
|
||||
]
|
||||
},
|
||||
"version": 0.4
|
||||
}
|
||||
@@ -1679,7 +1679,8 @@
|
||||
"origin_slot": 0,
|
||||
"target_id": 72,
|
||||
"target_slot": 1,
|
||||
"type": "IMAGE"
|
||||
"type": "IMAGE",
|
||||
"parentId": 1
|
||||
},
|
||||
{
|
||||
"id": 5,
|
||||
@@ -1706,7 +1707,19 @@
|
||||
"type": "STRING"
|
||||
}
|
||||
],
|
||||
"extra": {}
|
||||
"extra": {},
|
||||
"reroutes": [
|
||||
{
|
||||
"id": 1,
|
||||
"pos": [
|
||||
1048,
|
||||
676
|
||||
],
|
||||
"linkIds": [
|
||||
6
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "fe7eddff-ee33-40d2-98aa-e25b894fc34e",
|
||||
@@ -2713,7 +2726,8 @@
|
||||
"origin_slot": 4,
|
||||
"target_id": 66,
|
||||
"target_slot": 2,
|
||||
"type": "AUSBOSS_STITCHER"
|
||||
"type": "AUSBOSS_STITCHER",
|
||||
"parentId": 4
|
||||
},
|
||||
{
|
||||
"id": 28,
|
||||
@@ -2729,7 +2743,8 @@
|
||||
"origin_slot": 0,
|
||||
"target_id": 68,
|
||||
"target_slot": 1,
|
||||
"type": "IMAGE"
|
||||
"type": "IMAGE",
|
||||
"parentId": 2
|
||||
},
|
||||
{
|
||||
"id": 30,
|
||||
@@ -2780,7 +2795,51 @@
|
||||
"type": "STRING"
|
||||
}
|
||||
],
|
||||
"extra": {}
|
||||
"extra": {},
|
||||
"reroutes": [
|
||||
{
|
||||
"id": 1,
|
||||
"pos": [
|
||||
522,
|
||||
248
|
||||
],
|
||||
"linkIds": [
|
||||
29
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"parentId": 1,
|
||||
"pos": [
|
||||
1600,
|
||||
248
|
||||
],
|
||||
"linkIds": [
|
||||
29
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"pos": [
|
||||
522,
|
||||
262
|
||||
],
|
||||
"linkIds": [
|
||||
27
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 4,
|
||||
"parentId": 3,
|
||||
"pos": [
|
||||
1600,
|
||||
262
|
||||
],
|
||||
"linkIds": [
|
||||
27
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -2793,7 +2852,53 @@
|
||||
27
|
||||
]
|
||||
},
|
||||
"frontendVersion": "1.53.6"
|
||||
"frontendVersion": "1.53.6",
|
||||
"reroutes": [
|
||||
{
|
||||
"id": 1,
|
||||
"pos": [
|
||||
1460,
|
||||
360
|
||||
],
|
||||
"linkIds": [
|
||||
35
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"pos": [
|
||||
1444,
|
||||
500
|
||||
],
|
||||
"linkIds": [
|
||||
40
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"pos": [
|
||||
1476,
|
||||
450
|
||||
],
|
||||
"linkIds": [
|
||||
41
|
||||
]
|
||||
}
|
||||
],
|
||||
"linkExtensions": [
|
||||
{
|
||||
"id": 35,
|
||||
"parentId": 1
|
||||
},
|
||||
{
|
||||
"id": 40,
|
||||
"parentId": 2
|
||||
},
|
||||
{
|
||||
"id": 41,
|
||||
"parentId": 3
|
||||
}
|
||||
]
|
||||
},
|
||||
"version": 0.4
|
||||
}
|
||||
@@ -1025,7 +1025,7 @@
|
||||
"type": "AUSBOSS_NODES_LoraLoader",
|
||||
"pos": [
|
||||
2288,
|
||||
1040.0
|
||||
1290
|
||||
],
|
||||
"size": [
|
||||
440,
|
||||
@@ -2005,9 +2005,9 @@
|
||||
"title": "3 · Models",
|
||||
"bounding": [
|
||||
1968,
|
||||
960.0,
|
||||
960,
|
||||
780,
|
||||
500.0
|
||||
540
|
||||
],
|
||||
"color": "#1d5560",
|
||||
"flags": {
|
||||
@@ -2550,7 +2550,7 @@
|
||||
"type": "Reroute",
|
||||
"pos": [
|
||||
560,
|
||||
676.0
|
||||
640
|
||||
],
|
||||
"size": [
|
||||
75,
|
||||
@@ -2587,8 +2587,8 @@
|
||||
"id": 25,
|
||||
"type": "Reroute",
|
||||
"pos": [
|
||||
560,
|
||||
772.0
|
||||
580,
|
||||
784
|
||||
],
|
||||
"size": [
|
||||
75,
|
||||
@@ -3094,7 +3094,8 @@
|
||||
"origin_slot": 0,
|
||||
"target_id": 26,
|
||||
"target_slot": 3,
|
||||
"type": "LATENT"
|
||||
"type": "LATENT",
|
||||
"parentId": 1
|
||||
},
|
||||
{
|
||||
"id": 20,
|
||||
@@ -3241,7 +3242,19 @@
|
||||
"type": "IMAGE"
|
||||
}
|
||||
],
|
||||
"extra": {}
|
||||
"extra": {},
|
||||
"reroutes": [
|
||||
{
|
||||
"id": 1,
|
||||
"pos": [
|
||||
1060,
|
||||
640
|
||||
],
|
||||
"linkIds": [
|
||||
25
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "f03669a3-61c2-44c8-ad63-bad928a695fa",
|
||||
@@ -3828,7 +3841,8 @@
|
||||
"type": "MASK"
|
||||
}
|
||||
],
|
||||
"extra": {}
|
||||
"extra": {},
|
||||
"reroutes": []
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -3841,7 +3855,106 @@
|
||||
60
|
||||
]
|
||||
},
|
||||
"frontendVersion": "1.53.6"
|
||||
"frontendVersion": "1.53.6",
|
||||
"reroutes": [
|
||||
{
|
||||
"id": 1,
|
||||
"pos": [
|
||||
954,
|
||||
36
|
||||
],
|
||||
"linkIds": [
|
||||
46,
|
||||
31
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"parentId": 1,
|
||||
"pos": [
|
||||
1945,
|
||||
36
|
||||
],
|
||||
"linkIds": [
|
||||
46,
|
||||
31
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"parentId": 2,
|
||||
"pos": [
|
||||
2768,
|
||||
36
|
||||
],
|
||||
"linkIds": [
|
||||
31
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 4,
|
||||
"pos": [
|
||||
2768,
|
||||
300
|
||||
],
|
||||
"linkIds": [
|
||||
45
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 5,
|
||||
"parentId": 4,
|
||||
"pos": [
|
||||
3208,
|
||||
300
|
||||
],
|
||||
"linkIds": [
|
||||
45
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 6,
|
||||
"pos": [
|
||||
956,
|
||||
1030
|
||||
],
|
||||
"linkIds": [
|
||||
2
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 7,
|
||||
"pos": [
|
||||
962,
|
||||
980
|
||||
],
|
||||
"linkIds": [
|
||||
3
|
||||
]
|
||||
}
|
||||
],
|
||||
"linkExtensions": [
|
||||
{
|
||||
"id": 46,
|
||||
"parentId": 2
|
||||
},
|
||||
{
|
||||
"id": 31,
|
||||
"parentId": 3
|
||||
},
|
||||
{
|
||||
"id": 45,
|
||||
"parentId": 5
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"parentId": 6
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"parentId": 7
|
||||
}
|
||||
]
|
||||
},
|
||||
"version": 0.4
|
||||
}
|
||||
@@ -921,8 +921,8 @@
|
||||
"id": 11,
|
||||
"type": "AUSBOSS_NODES_LoraLoader",
|
||||
"pos": [
|
||||
1808,
|
||||
608
|
||||
1468,
|
||||
1072
|
||||
],
|
||||
"size": [
|
||||
400,
|
||||
@@ -2021,7 +2021,7 @@
|
||||
"type": "Reroute",
|
||||
"pos": [
|
||||
560,
|
||||
394
|
||||
430
|
||||
],
|
||||
"size": [
|
||||
75,
|
||||
@@ -2059,7 +2059,7 @@
|
||||
"type": "Reroute",
|
||||
"pos": [
|
||||
560,
|
||||
460
|
||||
360
|
||||
],
|
||||
"size": [
|
||||
75,
|
||||
@@ -2096,11 +2096,11 @@
|
||||
"id": 20,
|
||||
"type": "KSampler",
|
||||
"pos": [
|
||||
560,
|
||||
640,
|
||||
546
|
||||
],
|
||||
"size": [
|
||||
460,
|
||||
380,
|
||||
262
|
||||
],
|
||||
"flags": {},
|
||||
@@ -2607,7 +2607,8 @@
|
||||
"type": "IMAGE"
|
||||
}
|
||||
],
|
||||
"extra": {}
|
||||
"extra": {},
|
||||
"reroutes": []
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -2620,7 +2621,64 @@
|
||||
60
|
||||
]
|
||||
},
|
||||
"frontendVersion": "1.53.6"
|
||||
"frontendVersion": "1.53.6",
|
||||
"reroutes": [
|
||||
{
|
||||
"id": 1,
|
||||
"pos": [
|
||||
1428,
|
||||
210
|
||||
],
|
||||
"linkIds": [
|
||||
21
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"parentId": 1,
|
||||
"pos": [
|
||||
2248,
|
||||
210
|
||||
],
|
||||
"linkIds": [
|
||||
21
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"pos": [
|
||||
1820,
|
||||
400
|
||||
],
|
||||
"linkIds": [
|
||||
27
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 4,
|
||||
"pos": [
|
||||
1860,
|
||||
450
|
||||
],
|
||||
"linkIds": [
|
||||
28
|
||||
]
|
||||
}
|
||||
],
|
||||
"linkExtensions": [
|
||||
{
|
||||
"id": 21,
|
||||
"parentId": 2
|
||||
},
|
||||
{
|
||||
"id": 27,
|
||||
"parentId": 3
|
||||
},
|
||||
{
|
||||
"id": 28,
|
||||
"parentId": 4
|
||||
}
|
||||
]
|
||||
},
|
||||
"version": 0.4
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1816,7 +1816,8 @@
|
||||
"type": "IMAGE"
|
||||
}
|
||||
],
|
||||
"extra": {}
|
||||
"extra": {},
|
||||
"reroutes": []
|
||||
},
|
||||
{
|
||||
"id": "a988ba93-208b-4af3-b721-61365d1292ac",
|
||||
@@ -2612,7 +2613,8 @@
|
||||
"type": "IMAGE"
|
||||
}
|
||||
],
|
||||
"extra": {}
|
||||
"extra": {},
|
||||
"reroutes": []
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -2624,7 +2626,111 @@
|
||||
137,
|
||||
20
|
||||
]
|
||||
}
|
||||
},
|
||||
"reroutes": [
|
||||
{
|
||||
"id": 1,
|
||||
"pos": [
|
||||
940,
|
||||
34
|
||||
],
|
||||
"linkIds": [
|
||||
1
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"parentId": 1,
|
||||
"pos": [
|
||||
1420,
|
||||
34
|
||||
],
|
||||
"linkIds": [
|
||||
1
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"pos": [
|
||||
940,
|
||||
38
|
||||
],
|
||||
"linkIds": [
|
||||
13
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 4,
|
||||
"parentId": 3,
|
||||
"pos": [
|
||||
1780,
|
||||
38
|
||||
],
|
||||
"linkIds": [
|
||||
13
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 5,
|
||||
"pos": [
|
||||
940,
|
||||
42
|
||||
],
|
||||
"linkIds": [
|
||||
14
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 6,
|
||||
"parentId": 5,
|
||||
"pos": [
|
||||
1780,
|
||||
42
|
||||
],
|
||||
"linkIds": [
|
||||
14
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 7,
|
||||
"pos": [
|
||||
934,
|
||||
450
|
||||
],
|
||||
"linkIds": [
|
||||
15
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 8,
|
||||
"parentId": 7,
|
||||
"pos": [
|
||||
942,
|
||||
700
|
||||
],
|
||||
"linkIds": [
|
||||
15
|
||||
]
|
||||
}
|
||||
],
|
||||
"linkExtensions": [
|
||||
{
|
||||
"id": 1,
|
||||
"parentId": 2
|
||||
},
|
||||
{
|
||||
"id": 13,
|
||||
"parentId": 4
|
||||
},
|
||||
{
|
||||
"id": 14,
|
||||
"parentId": 6
|
||||
},
|
||||
{
|
||||
"id": 15,
|
||||
"parentId": 8
|
||||
}
|
||||
]
|
||||
},
|
||||
"version": 0.4
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
# Cut Out
|
||||
|
||||
Turns a picture and a mask into a cut-out with a see-through background.
|
||||
Use it to save a subject as a transparent PNG, or to lay it on a new
|
||||
background. It goes after the node that makes the mask, such as Mask by
|
||||
Name or Mask by Touch. In a Qwen Image cut-out workflow, where SAM 3 finds a
|
||||
thing and Qwen paints it out of the picture, Cut Out turns the same mask and
|
||||
the original picture into the transparent PNG.
|
||||
|
||||
**Clean edges** fixes the rim of old background colour that a cut-out
|
||||
usually carries in hair and soft edges, so it sits cleanly on any new
|
||||
background. Parts of the picture that are fully kept stay exactly as they
|
||||
were.
|
||||
|
||||
Save Image keeps the transparency when it saves a PNG (or WebP). JPEG has no
|
||||
transparency, so a JPEG shows the clear parts black.
|
||||
|
||||
The panel under the card shows the cut-out over a checkerboard once the
|
||||
node has run (the first frame for a video). The small **preview** switch at
|
||||
the right of the bar turns it off.
|
||||
|
||||
## Live preview
|
||||
|
||||
Once the node has a picture, the picture on the node redraws while you drag a
|
||||
value, before you queue anything. Run the graph once to give the node its
|
||||
picture (run once to get the picture and the mask); after that it changes as you drag. A small "not run yet" tag
|
||||
shows while the picture is a preview and not a real result.
|
||||
|
||||
The **Fit | 100%** switch sits on the bar above the picture, left of Preview.
|
||||
Fit shows the whole picture. 100% shows real pixels, and dragging on the
|
||||
picture moves around it instead of moving the node. The cut-out shows over a checker, so see-through parts read as see-through.
|
||||
|
||||
|
||||
## Controls
|
||||
|
||||
- **Keep** (`keep`): **white part** keeps what is under the white of the
|
||||
mask, **black part** keeps what is under the black. Pick black part when
|
||||
your mask covers the background rather than the subject.
|
||||
- **Grow** (`grow`): grows the kept part by this many pixels, or shrinks it
|
||||
with a negative number. Shrink by 1 or 2 when a thin line of old
|
||||
background shows around the edge.
|
||||
- **Feather** (`feather`): how soft the edge is, in pixels. `0` keeps the
|
||||
mask's own edge. `1` takes the jagged steps off a hard mask.
|
||||
- **Clean edges** (`clean_edges`): on by default. Works out the subject's
|
||||
own colour where the edge is see-through (hair, fur, motion blur) and
|
||||
puts it back, so the old background does not show as a halo. Turn it off
|
||||
to keep the picture's colours everywhere.
|
||||
|
||||
### Behind **More**
|
||||
|
||||
- **Clear haze** (`clear_haze`): parts this see-through or more become fully
|
||||
clear. Raise it a little (`0.05`) when a faint haze surrounds the cut-out.
|
||||
- **Solid above** (`solid_above`): parts at least this solid become fully
|
||||
solid. Lower it a little (`0.95`) to fill thin see-through spots inside
|
||||
the subject.
|
||||
- **Smooth video** (`smooth_frames`): for a video, blends each frame's edge
|
||||
with this many frames before and after it, which calms an edge that
|
||||
flickers from frame to frame. `0` is off. Keep it low (`1` or `2`) on
|
||||
fast motion, or the edge lags behind the subject.
|
||||
|
||||
### Inputs and outputs
|
||||
|
||||
- **image**: the picture or video frames.
|
||||
- **mask**: what to keep. One mask can cover every frame, or give one per
|
||||
frame. A mask of another size is stretched to the picture.
|
||||
- **image** (output): the cut-out as an RGBA picture with straight (not
|
||||
premultiplied) alpha. If the input already had a transparent background,
|
||||
both are kept.
|
||||
- **alpha** (output): how solid each pixel is, as a mask: white is kept,
|
||||
black is clear. Wire it to any node that wants the final mask.
|
||||
|
||||
## Technical details
|
||||
|
||||
- The alpha is made in a fixed order: pick the white or black part, grow or
|
||||
shrink (whole pixels), feather (a Gaussian blur of that many pixels),
|
||||
average over neighbouring frames, then the levels (Clear haze and Solid
|
||||
above). Values within 0.0001 of solid or clear are made exactly solid or
|
||||
clear.
|
||||
- Clean edges uses blur-fusion foreground estimation (Forte and Pitie,
|
||||
"Approximate Fast Foreground Colour Estimation", ICIP 2021), written in
|
||||
torch for this pack and shared with Mask by Touch's fine edges: around
|
||||
each pixel it averages the subject's colour and the background's from the
|
||||
pixels nearby, corrects the subject's by what the pixel shows, and does
|
||||
this once wide and once narrow. The widths follow the picture's size. It
|
||||
needs no extra package. Pixels with an alpha of exactly 1 keep their
|
||||
original colours to the bit.
|
||||
- Frames are worked on eight at a time.
|
||||
|
||||
### Live preview
|
||||
|
||||
The preview runs the node's own maths in the browser: on a copy shrunk to the
|
||||
size it is shown at in Fit, and on a real-pixel crop of the picture in 100%.
|
||||
It is checked against the Python node on recorded values (`tests/test_live_parity.py`);
|
||||
results agree to within 5e-5 on a 0 to 1 scale. The picture is the one the
|
||||
last run kept, or a Load Image read through ComfyUI's own view route. When
|
||||
the values match the last run, the real result is drawn instead.
|
||||
@@ -0,0 +1,171 @@
|
||||
# Film Grain
|
||||
|
||||
Adds film grain to a picture or a video. Use it at the end of a workflow to
|
||||
give a clean render the texture of a photo shot on film, or to make a fake
|
||||
look less smooth and plastic.
|
||||
|
||||
The grain is strongest in the midtones and gentler in deep shadows and bright
|
||||
highlights, the way it is on film. On a video it moves from frame to frame
|
||||
like real film grain, or stays put if you want a still texture. An optional
|
||||
mask puts grain only where it is white.
|
||||
|
||||
The panel under the card shows the result once the node has run (the first
|
||||
frame for a video). The small **preview** switch at the right of the bar
|
||||
turns it off, which also skips writing the preview file.
|
||||
|
||||
## Auto
|
||||
|
||||
Switch **Auto** on and the node picks the grain for the picture. The grain
|
||||
looks the same on a small picture and on a big one, and it matches the grain
|
||||
the picture already has. A clean render, with no grain of its own, starts at
|
||||
the normal amount of `0.25`.
|
||||
|
||||
With Auto on, **Amount** and **Size** become multipliers. `1 ×` is Auto's
|
||||
pick, `1.5 ×` is half as much again, `2 ×` is twice as big. The small number
|
||||
beside each box is what you get ("= 0.27", "= 1.0 px"). It shows once the
|
||||
node knows the picture: right away from a Load Image, or after one run when
|
||||
the picture comes from another node. Until then it shows a dash.
|
||||
|
||||
Auto on and Auto off each keep their own numbers, so switching back loses
|
||||
nothing. Auto starts off, so workflows saved before it behave as they did.
|
||||
|
||||
## Copy the grain of another picture
|
||||
|
||||
Wire a picture whose grain you like into **grain_from** and switch Auto on.
|
||||
Its switch now reads **match**: the node reads how strong, how big and how
|
||||
colourful that picture's grain is, and adds grain like it. A film scan, a
|
||||
still from a film or a photo you like all work.
|
||||
|
||||
- **Amount**, **Size** and **Color** count from the match, the same way as
|
||||
Auto's pick: `1 ×` is the match, and the small number beside each box is
|
||||
what you get. **Roughness** stays yours; the match does not read it.
|
||||
- Grain is matched at the same viewing size. The picture to copy from is
|
||||
scaled to your picture's size first, so grain from a big photo comes out
|
||||
finer on a small picture, as it would look side by side on screen.
|
||||
- Only the plainest patches are read: a sky, a wall, skin. A picture that is
|
||||
all busy texture (gravel, leaves, a tiled floor) reads stronger grain than
|
||||
it has; turn **Amount** down, or copy from a plainer picture.
|
||||
- Grain your picture already has counts. A grainy picture gets only the
|
||||
grain it is missing, and a reference with less grain than yours adds none.
|
||||
- The match is worked out when the node runs. Until the first run the
|
||||
numbers show a dash and the picture asks for a run; after it, the live
|
||||
preview uses the match while you drag. A video is read from its first
|
||||
frame, and so is a video wired in to copy from.
|
||||
- The node remembers the match for each pair of pictures it ran, and saves
|
||||
it with the workflow. A reopened workflow shows it at once, and so does a
|
||||
run ComfyUI skips because nothing changed.
|
||||
- Without a picture on grain_from, Auto picks the grain as above. Auto off
|
||||
ignores grain_from.
|
||||
|
||||
## Live preview
|
||||
|
||||
Once the node has a picture, the picture on the node redraws while you drag a
|
||||
value, before you queue anything. Run the graph once to give the node its
|
||||
picture (an image connected is enough once it has run; a Load Image shows at once); after that it changes as you drag. A small "not run yet" tag
|
||||
shows while the picture is a preview and not a real result.
|
||||
|
||||
The **Fit | 100%** switch sits on the bar above the picture, left of Preview.
|
||||
Fit shows the whole picture. 100% shows real pixels, and dragging on the
|
||||
picture moves around it instead of moving the node. At 100% you see the grain at the size it will have in the saved picture.
|
||||
|
||||
|
||||
## Controls
|
||||
|
||||
- **Auto** (`auto`): off uses the Amount and Size you set. On, the node
|
||||
picks them for the picture, or reads **match** and copies the grain of the
|
||||
picture on grain_from.
|
||||
- **Amount** (`amount`): how strong the grain is. `0` adds none, `0.25` is a
|
||||
clearly visible film look, `1` is very heavy.
|
||||
- **Size** (`size`): how big each grain is, in pixels of this picture. `1` is
|
||||
fine 35 mm grain on a picture of about 1 megapixel. Raise it on a big
|
||||
picture, or for a coarse, fast-film look. Below `1` the grain is smaller
|
||||
than a pixel, so it also gets quieter.
|
||||
- **Roughness** (`roughness`): `0` is soft, even grain. Higher mixes in finer
|
||||
grain that bunches up in some places and thins out in others, like real
|
||||
film.
|
||||
- **Color** while matching (`auto_color`): a multiplier of the matched
|
||||
colour. `0` turns the copied grain black-and-white.
|
||||
- **Color** (`color`): `0` is black-and-white grain, the same in red, green
|
||||
and blue. Higher gives each colour its own grain, like the dye clouds of
|
||||
colour film. A little (`0.2` to `0.4`) looks most natural on colour
|
||||
pictures.
|
||||
- **Video grain** (`moving`): **moving** gives every frame of a video new
|
||||
grain, so it moves like film. **still** puts the same grain on every
|
||||
frame, which looks like a texture on the lens. A single picture looks the
|
||||
same either way.
|
||||
|
||||
### Behind **More**
|
||||
|
||||
- **Seed** (`seed`): picks the grain pattern. The same seed always gives
|
||||
the same grain, so a re-run gives the same picture. Change it for another
|
||||
pattern.
|
||||
|
||||
### Inputs and output
|
||||
|
||||
- **image**: the picture or video frames.
|
||||
- **grain_from** (optional): a picture whose grain to copy while Auto is
|
||||
on. It can be any size and shape.
|
||||
- **mask** (optional): grain goes only where the mask is white, and fades
|
||||
in with a soft mask. One mask can cover every frame, or give one per
|
||||
frame. A mask of another size is stretched to the picture.
|
||||
- **image** (output): the picture or frames with grain, at the same size. A
|
||||
picture with a transparent background keeps its transparency.
|
||||
|
||||
## Technical details
|
||||
|
||||
- Auto's size is `1` pixel at 1 megapixel and follows the square root of the
|
||||
picture's megapixels, so a 4 MP picture gets `2` px (kept between 0.5 and
|
||||
16 px). Its amount is `0.25` plus the picture's own grain divided by
|
||||
`0.15`, kept between `0.05` and `1`.
|
||||
- The picture's own grain is measured in its flat areas: a Laplacian-
|
||||
difference filter (Immerkaer, 1996) removes shapes and leaves fine noise,
|
||||
and the median of what is left, read from a histogram, gives the noise as
|
||||
one standard deviation. Edges and texture are a small part of a picture, so
|
||||
the median ignores them. Below `0.0015` (what 8-bit rounding alone
|
||||
measures) counts as no grain. A clip is measured on up to four frames.
|
||||
The browser measures a Load Image's picture with the same filter, so the
|
||||
note beside the boxes agrees with the node's result.
|
||||
- `auto_amount` and `auto_size` are separate inputs from `amount` and
|
||||
`size`, which is why each mode keeps its own numbers.
|
||||
- The grain match (`nodes/_grain_match_helpers.py`) scales the picture to
|
||||
copy from to the target's megapixels, its shape kept, and reads both
|
||||
pictures' first frames. Each is shrunk by 1 to 12 times; at each size the
|
||||
fine detail (mean absolute Laplacian, as a standard deviation) of the
|
||||
plainest fifth of the mid-tone 16 px blocks gives the brightness grain, and
|
||||
the same blocks of two colour-difference channels give the colour grain.
|
||||
The target's own grain at each size is taken off (in quadrature). How the
|
||||
grain falls off over the sizes is fitted, in log space, to a stored table
|
||||
of Film Grain's own grain at sizes 1 to 16 px and colours 0 to 1
|
||||
(`nodes/_grain_match_table.py`), with a mild pull toward size 1; grain
|
||||
smaller than a pixel reads as size 1 and a lower amount, which looks the
|
||||
same. The colour comes from the colour grain against the brightness grain,
|
||||
and the amount is checked twice by adding the grain to the target and
|
||||
correcting it. On Film Grain's own grain the match reads back its settings
|
||||
(0.40 / 2.0 px / 0.3 reads 0.41 / 2.0 px / 0.3); a 1 MP pair takes about
|
||||
a third of a second on the CPU.
|
||||
|
||||
- Grain is random noise drawn on a grid `size` pixels apart and smoothed up
|
||||
to the picture with a bicubic filter, then scaled back to the same
|
||||
strength. Below 1 pixel it is drawn finer and averaged down to the
|
||||
picture, so its strength falls with its size.
|
||||
- Roughness adds a second layer at half the size whose strength is varied by
|
||||
a slow noise four grains wide, mixed so the total strength stays the same.
|
||||
Extreme values are rounded off softly at three standard deviations, so no
|
||||
lone white or black speck appears.
|
||||
- At **Amount** `1` one standard deviation of the grain is `0.15` (on a
|
||||
`0` to `1` scale) at mid grey, falling to a fifth of that at black and
|
||||
white. The weight follows the picture's own brightness, `4 L (1 - L)`.
|
||||
- Every frame's grain has its own seed, worked out from the node's seed and
|
||||
the frame number, so a frame's grain does not depend on how long the clip
|
||||
is. Frames are worked on eight at a time: 81 frames at 1920 x 1080 take
|
||||
about 12 seconds on a desktop CPU, with only a few frames' worth of extra
|
||||
memory.
|
||||
|
||||
### Live preview
|
||||
|
||||
The preview runs the node's own maths in the browser: on a copy shrunk to the
|
||||
size it is shown at in Fit, and on a real-pixel crop of the picture in 100%.
|
||||
It is checked against the Python node on recorded values (`tests/test_live_parity.py`);
|
||||
results agree to within 5e-5 on a 0 to 1 scale. The picture is the one the
|
||||
last run kept, or a Load Image read through ComfyUI's own view route. When
|
||||
the values match the last run, the real result is drawn instead.
|
||||
@@ -24,12 +24,16 @@ frame are copied untouched, and only the true in-betweens are synthesized.
|
||||
|
||||
## Scene cuts
|
||||
|
||||
Interpolating across a hard cut produces morph artifacts: two unrelated
|
||||
shots smeared into each other for a frame or two. When the mean absolute
|
||||
difference between adjacent source frames rises above **Scene cut**
|
||||
(`scene_cut_threshold`), the node treats that pair as a cut and holds the
|
||||
last frame before it instead of morphing. Set the threshold to `0` to
|
||||
disable detection and interpolate everything.
|
||||
Making in-betweens across a hard cut mixes two shots into each other for a
|
||||
frame or two. The node finds each cut and holds the last frame before it
|
||||
instead.
|
||||
|
||||
A cut is a change between two frames that jumps out from the frames around
|
||||
it. That works even when both shots show the same place in the same light,
|
||||
where the change at a cut can be smaller than fast movement inside one
|
||||
shot. Any change above **Scene cut** (`scene_cut_threshold`) also counts as
|
||||
a cut, as it always has. Set it to `0` to turn cut finding off and make
|
||||
in-betweens everywhere.
|
||||
|
||||
## Controls
|
||||
|
||||
@@ -40,8 +44,10 @@ disable detection and interpolate everything.
|
||||
source rate passes the batch through unchanged. A new node starts at
|
||||
24 → 30.
|
||||
- **Method** (`method`): `blend` or **optical flow (RAFT)**, as described above.
|
||||
- **Scene cut** (`scene_cut_threshold`): Cut sensitivity from 0 to 1; `0.35`
|
||||
suits most footage, `0` disables.
|
||||
- **Scene cut** (`scene_cut_threshold`): A change above this always counts
|
||||
as a cut; `0.35` suits most footage, and `0` turns cut finding off. Cuts
|
||||
that jump out from the frames around them are found at any setting above
|
||||
`0`.
|
||||
- **Batch** (`batch_size`, starts at `8`): In-between frames computed per batch. Higher is
|
||||
faster but uses more VRAM; results land in system memory as each batch
|
||||
finishes.
|
||||
@@ -55,3 +61,33 @@ disable detection and interpolate everything.
|
||||
|
||||
Neither method performs network requests or writes files. The optical-flow
|
||||
method reads an existing checkpoint from the local torch hub cache.
|
||||
|
||||
## Technical details
|
||||
|
||||
### How cuts are found
|
||||
|
||||
The node makes a small copy of every frame, 64 px on its long side. Each
|
||||
4 px block of a frame looks for its best match in the frame before it,
|
||||
moved up to 3 px each way. Movement inside a shot finds its match, so what
|
||||
is left is small; after a cut the picture is new and the change stays
|
||||
large, even with the same colors on both sides.
|
||||
|
||||
That leftover change is compared with the median of the 4 frame pairs on
|
||||
each side. A pair is a cut when it is at least 3 times that median and
|
||||
above 0.02 (on a 0 to 1 scale), so grain in a still shot never counts.
|
||||
Repeated frames, as in footage drawn on twos or threes, are left out of the
|
||||
median. A pair is also a cut when its plain mean difference over the full
|
||||
frame is above **Scene cut**, the rule earlier versions used on its own, so
|
||||
no cut those versions found is lost.
|
||||
|
||||
Measured on seven MiniMax H3 clips with 29 cuts, among them a rooftop clip
|
||||
whose three cuts scored 0.14 to 0.17 on the plain difference and a street
|
||||
clip that moved 0.15 inside one shot: every cut stood out at least 4.1
|
||||
times from its neighbours, and movement inside a shot at most 1.9 times.
|
||||
All 29 were held and nothing inside a shot was. The plain rule alone,
|
||||
at `0.35`, held 2 of them.
|
||||
|
||||
A cut straight into very fast movement, more than about a twentieth of the
|
||||
frame from one frame to the next, can stand out less from the shot after
|
||||
it. A clip of two frames has nothing to compare with; there only the
|
||||
plain rule applies.
|
||||
|
||||
@@ -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
|
||||
@@ -23,10 +45,11 @@ the box shows the second each one starts, before you spend a run.
|
||||
That is two shots in two places. `@1` is Picture 1. With one person you can
|
||||
write `She` or `He` instead.
|
||||
|
||||
The node also fills in two things H3 misses by itself. A moment gets its own
|
||||
sound when it names something that makes one, like rain, footsteps or thunder.
|
||||
And what changes stays changed: when the lights go out, the next moments in that
|
||||
place say they are still out.
|
||||
Your words go into the prompt as you typed them. To hear something at a
|
||||
moment, say it in that line: `Thunder cracks overhead.` For a sound under the
|
||||
whole clip, add a `sound:` line, such as `sound: rain on the windows`. When
|
||||
something should stay the way it changed, say so in the later lines too:
|
||||
`The lights are still off.`
|
||||
|
||||
## The words box and the bar
|
||||
|
||||
@@ -113,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.
|
||||
@@ -143,11 +167,14 @@ workflows and scripts keep their previous behavior when it is absent.
|
||||
- **A cut in the same place**: start the line with a kind of shot, like
|
||||
`a close-up of her hand`. Any other line after a blank line goes to a new
|
||||
place.
|
||||
- **A cut back**: `Cut back to the hallway.` returns to a place you have
|
||||
already shown.
|
||||
- **One long take**: type `no cuts` and blank lines stop being cuts.
|
||||
- **An ending**: start a line with `ends on`, wherever it sits:
|
||||
`ends on her sitting by the window`.
|
||||
- **Speech**: put the words in quotes: `@1 says "we are late."` Each person
|
||||
keeps their own voice.
|
||||
- **Speech**: put the words in quotes: `She says "we are late."` With two or
|
||||
more people, your sentence goes to H3 as you typed it, so write it the way
|
||||
you would tell a person: `@1 listens as @2 says "we are late."`
|
||||
- **Talking over a cut**: end the words with `...` and the line keeps going
|
||||
into the next shot, said once. On the last line, `...` means the clip ends
|
||||
mid-sentence.
|
||||
@@ -183,14 +210,16 @@ text is sent instead.
|
||||
speech timing when **Clip's own sound** is on. To keep source audio in a swap
|
||||
or **change something**, route the original loader's audio to the save node.
|
||||
- **voice**: a clip of someone talking, about 10 seconds, plus words in quotes
|
||||
in your script. It goes to whoever speaks first. It works with your own voice,
|
||||
in your script. It goes to whoever speaks first. With two or more people,
|
||||
put the speaker right before the words: `@2 says "hello."` It works with your own voice,
|
||||
or one you have permission to use. Put the spoken line last: with time left
|
||||
after it, H3 tends to keep talking.
|
||||
- **song**: your music. It is cut to the length of the clip and plays as it is,
|
||||
and each moment moves onto its beat.
|
||||
- **clip**: a small text model such as Qwen3-VL 8B. Type one line and it adds
|
||||
what happens next, and it names the sound of the place. Your line always stays
|
||||
first.
|
||||
first. Turn on **More → Tidy up my lines** and it also cleans up what you
|
||||
typed before the node reads it (see the controls below).
|
||||
|
||||
A voice and a song work together. H3 can't keep a song while someone speaks, so
|
||||
the node keeps the song out of H3's way and hands it on as **song_under**, turned
|
||||
@@ -228,15 +257,39 @@ 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.
|
||||
- **Moments on the beat** (`cut_on_beat`, under **More**): moves each moment onto
|
||||
the nearest beat of the song. Off keeps your own seconds.
|
||||
- **Language** (`language`, under **More**): the language of the words in quotes.
|
||||
- **Tidy up my lines** (`tidy`, under **More**): the model on **clip** rewrites
|
||||
your lines first. It fixes spelling, breaks long lines into short sentences,
|
||||
and puts each spoken line right after whoever says it, so
|
||||
`@1 stares at @2 who goes "No way."` becomes `@1 stares at @2. @2 says "No way."`
|
||||
Your words in quotes are never rewritten: they are held out while it tidies
|
||||
and come back exactly as typed. Each line is tidied on its own, so blank
|
||||
lines and timed lines stay where you put them, and `camera:`, `sound:` and
|
||||
`music:` lines are left alone. If a tidied line would change who says what,
|
||||
that line is used as typed. A one-line idea is left as it is, for the model to fill out. With nothing on
|
||||
**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
|
||||
|
||||
@@ -258,7 +311,7 @@ as not plugged in.
|
||||
| --- | --- | --- | --- |
|
||||
| `script` | input | STRING | What happens, one line for each moment. |
|
||||
| `seconds` | input | INT | How long the clip is. |
|
||||
| `clip` | input, optional | CLIP | A small text model that fills in a one-line idea. |
|
||||
| `clip` | input, optional | CLIP | A small text model that fills in a one-line idea, and tidies your lines when Tidy up is on. |
|
||||
| `picture_1` to `picture_4` | input, optional | IMAGE | Your pictures. |
|
||||
| `video` | input, optional | IMAGE | The frames of a video. |
|
||||
| `video_sound` | input, optional | AUDIO | The video's own sound. |
|
||||
@@ -293,6 +346,24 @@ that sentence the picture's street came back halfway through on 2 of 2. With no
|
||||
place in your lines H3 has nothing else to use, so it stayed in the picture's
|
||||
place on 2 of 2.
|
||||
|
||||
Tidy up sends the model one call per typed line, with its own instructions, no
|
||||
picture, and no randomness, so the same lines tidy the same way every run. Blank
|
||||
lines, `camera:`/`sound:`/`music:`/`look:` lines and the order of lines never pass
|
||||
through the model. Each quote is swapped for a marker (`SPOKEN`, or `SPOKEN1`,
|
||||
`SPOKEN2`) before anything else touches the line, so the model never sees the
|
||||
quoted words. A line's answer is used only when it is one line, every marker comes
|
||||
back once, the same `@` numbers are in it, it is not much longer than what you
|
||||
typed, each typed `@N says "..."` keeps the same person, a quote on a sign or a
|
||||
shirt stays on it, and the writer reads the whole script the same way with the
|
||||
tidied line in it: the same words said in the same order, shot and second, and the
|
||||
same cuts and timed seconds.
|
||||
Any other line is used as typed. If the writer still turns the tidied lines down,
|
||||
it uses your lines as typed. On Qwen3-VL 8B the instructions put the right speaker
|
||||
before the words on 38 of 38 lines they were not written for, took about 0.3
|
||||
seconds a call once the model was loaded, and passed every check on 77 of 79
|
||||
lines. What it still changes: "as" and "while" can become two sentences, and a
|
||||
leading `Voiceover:` label is left as typed.
|
||||
|
||||
The Full prompt tab is filled from the node's run, so it shows nothing until
|
||||
the workflow has run once. The node still writes its own prompt on every run, a
|
||||
model on `clip` included, so the tab can show it next to your edit and Reset can
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
# Keep Detail
|
||||
|
||||
Puts the fine detail of your original picture back on an edited version of
|
||||
it. Use it when an edit, a relight or an upscale made skin, fabric or wood
|
||||
look too smooth: the edit keeps its shapes, light and colour, and the pores,
|
||||
weave and grain come from the original.
|
||||
|
||||
The two pictures must line up, pixel for pixel. Wire the edit to **image**
|
||||
and the original to **detail_from**. If an edit drifted (Qwen Image often
|
||||
draws an edit a little bigger or shifted), run it through Realign to Source
|
||||
first, or the detail lands in the wrong place and doubles up.
|
||||
|
||||
If **detail_from** is a different size from the edit, it is resized to the
|
||||
edit's size first. That only helps when it is the same picture at another
|
||||
size; the pictures still have to line up.
|
||||
|
||||
The panel under the card shows the result once the node has run. The small
|
||||
**preview** switch at the right of the bar turns it off.
|
||||
|
||||
## Live preview
|
||||
|
||||
Once the node has a picture, the picture on the node redraws while you drag a
|
||||
value, before you queue anything. Run the graph once to give the node its
|
||||
picture (run once to get the picture); after that it changes as you drag. A small "not run yet" tag
|
||||
shows while the picture is a preview and not a real result.
|
||||
|
||||
The **Fit | 100%** switch sits on the bar above the picture, left of Preview.
|
||||
Fit shows the whole picture. 100% shows real pixels, and dragging on the
|
||||
picture moves around it instead of moving the node. Fine detail is easiest to judge at 100%.
|
||||
|
||||
|
||||
## Controls
|
||||
|
||||
- **Detail size** (`detail_size`): detail smaller than this many pixels
|
||||
comes from the original; anything bigger stays the edit's. `2` to `6` suits
|
||||
skin and fabric. Larger brings back more of the original, until it starts
|
||||
to bring back the old picture's light and shapes too.
|
||||
- **Strength** (`strength`): `0` leaves the edit as it is, `1` puts the
|
||||
original's detail on it in place of the edit's own, above `1` makes the
|
||||
original's detail stronger.
|
||||
- **Detail** (`color_detail`): **light only** brings back only how bright
|
||||
or dark the detail is, so the edit's colours never shift. **color +
|
||||
light** brings back the detail's colour too, such as freckles, stains or
|
||||
a coloured weave. Use it when the edit kept the original's colours.
|
||||
|
||||
### Behind **More**
|
||||
|
||||
- **Edge safe** (`edge_safe`): on by default. Strong edges, such as a
|
||||
jaw against a bright wall, are left as the edit has them, so no light or
|
||||
dark rim appears along them. Turn it off when the edit also blurred
|
||||
strong edges and you want those back from the original as well.
|
||||
|
||||
### Inputs and output
|
||||
|
||||
- **image**: the edited picture.
|
||||
- **detail_from**: the original picture, lined up with the edit.
|
||||
- **mask** (optional): detail goes back only where the mask is white, such
|
||||
as on skin alone.
|
||||
- **image** (output): the edit with the original's detail, at the edit's
|
||||
size.
|
||||
|
||||
Both pictures can be videos. One picture on either side goes with every
|
||||
frame of the other.
|
||||
|
||||
## Technical details
|
||||
|
||||
- Each picture is split into a base and detail. The base is the picture
|
||||
smoothed over `detail_size` pixels; the detail is what the smoothing took
|
||||
away. The result is the edit's base with the original's detail.
|
||||
- The split is a ratio in linear light, not a difference. Detail is how much
|
||||
brighter or darker each pixel is than its base, as a factor: pores that
|
||||
are 8 % darker than the skin around them stay 8 % darker on a darker,
|
||||
relit face. A difference would carry a bright original's texture too
|
||||
strong into a dark edit and too weak into a bright one. Linear light is
|
||||
the picture with the sRGB curve taken off, where light adds up
|
||||
physically, so a factor means the same in shadows and highlights.
|
||||
- With **light only** the factor comes from the luminance (Rec. 709 weights)
|
||||
and multiplies red, green and blue alike, so the colour of every pixel
|
||||
stays the edit's. With **color + light** each channel has its own factor.
|
||||
- The base is a Gaussian blur with a radius of `detail_size`, or with
|
||||
**Edge safe** a guided filter (He, Sun and Tang, 2010) of the picture by
|
||||
itself over a box of the same spread: it smooths texture but follows a
|
||||
strong edge, so the detail at that edge stays near nothing. A step that
|
||||
varies the values around it by more than about `0.15` counts as an edge;
|
||||
skin, fabric and wood grain vary them less. The smoothing runs on the
|
||||
sRGB-curved values, where an edge's size matches how strong it looks.
|
||||
- Strength `s` mixes the two details: the edit's own to the power `1 - s`
|
||||
(for `s` up to `1`) times the original's to the power `s`. At `0` the
|
||||
result is the edit, unchanged.
|
||||
- Frames are worked on four at a time.
|
||||
|
||||
### Live preview
|
||||
|
||||
The preview runs the node's own maths in the browser: on a copy shrunk to the
|
||||
size it is shown at in Fit, and on a real-pixel crop of the picture in 100%.
|
||||
It is checked against the Python node on recorded values (`tests/test_live_parity.py`);
|
||||
results agree to within 5e-5 on a 0 to 1 scale. The picture is the one the
|
||||
last run kept, or a Load Image read through ComfyUI's own view route. When
|
||||
the values match the last run, the real result is drawn instead.
|
||||
@@ -39,6 +39,11 @@ come back with the new area still gray, like a gray frame or a gray corner.
|
||||
Pad 🆎 or Load Image + Pad 🆎, or the painted mask of an inpaint. Wire it
|
||||
for AnyPaint. The reference then shows that area in your picture's own
|
||||
colour instead of the gray fill, and the model paints it.
|
||||
- **reference_curve**: How strongly the picture follows the references over
|
||||
the run, from Strength Curve 🆎. 1 is the normal strength and 0 ignores
|
||||
them. Hold the layout early and let go late (a fade out), or let the
|
||||
model find its own shapes first and pull the reference in for the details
|
||||
(a fade in). Leave it unwired for today's behaviour.
|
||||
|
||||
## Outputs
|
||||
|
||||
@@ -69,3 +74,23 @@ above 0.5) is refilled with the median colour of everything else before the
|
||||
reference goes to the VAE and to the vision tower. The canvas the rest of
|
||||
the graph uses keeps its gray, so the prompt writer and the stitch are
|
||||
unchanged. Only `reference` is refilled; `extra_image` is left as it is.
|
||||
|
||||
## Technical details: the reference curve
|
||||
|
||||
The references reach Krea 2 as extra tokens that the prompt and the canvas
|
||||
attend to. At each step the curve's value `s` is added as `log(s)` to
|
||||
the attention scores of the reference keys, which multiplies the attention
|
||||
weight they get by `s` before the weights are shared out again. At 1
|
||||
nothing changes, at 0 the reference gets no attention at all and the result
|
||||
is the same as without a reference, and values in between fade it. The
|
||||
reference's own tokens see the same scale. It works the same with Krea 2
|
||||
Outpaint Model Patch 🆎, which scales its cached reference keys.
|
||||
|
||||
The curve travels on the positive output as a ComfyUI hook, read at each
|
||||
step by ComfyUI's own hook keyframes (see Strength Curve 🆎 for how "where
|
||||
in the run" is measured). Two costs come with ComfyUI's hooks: a run with a
|
||||
hooked prompt turns dynamic VRAM loading off (the first one loads the model
|
||||
a second time), and at a CFG above 1 the positive and negative are run one
|
||||
after the other instead of together. While the strength is not 1, attention
|
||||
also runs with a mask, which some fast attention kernels hand to PyTorch's
|
||||
own.
|
||||
|
||||
@@ -20,6 +20,22 @@ the video you are making. An empty Duration runs to the end of the file.
|
||||
A box set by another node, such as Float 🆎, shows a **linked** button that
|
||||
jumps to that node, and the wave shows the part that number picks.
|
||||
|
||||
## Clean up
|
||||
|
||||
Turn **Clean up** on for a voice recording you want a video model to say,
|
||||
such as a line recorded on a phone. The sound that comes out:
|
||||
|
||||
- is one channel,
|
||||
- has the quiet bits at the start and end cut off, so the voice starts right
|
||||
away,
|
||||
- has less hum, rumble and hiss,
|
||||
- is at an even volume, never so loud that it clips.
|
||||
|
||||
A model that copies the sound it is given copies its noise too, so a clean
|
||||
recording gives a cleaner result. Clean up works on the part you picked, so
|
||||
the sound can come out a little shorter than the length shown under the wave;
|
||||
`seconds` always gives the real length. Leave it off for music.
|
||||
|
||||
## Controls
|
||||
|
||||
- **Source** (`audio`): a sound file in ComfyUI's input folder. **Upload**
|
||||
@@ -30,6 +46,8 @@ jumps to that node, and the wave shows the part that number picks.
|
||||
- **Ends at**: where the sound stops. Typing it sets the Duration.
|
||||
A workflow saved with an end time (`end_seconds`) keeps it and runs the
|
||||
same.
|
||||
- **Clean up** (`clean_up`): on cleans up a voice recording, as above. Off
|
||||
hands on the sound as it is.
|
||||
|
||||
## Outputs
|
||||
|
||||
@@ -44,3 +62,10 @@ jumps to that node, and the wave shows the part that number picks.
|
||||
- A start past the end of the file stops the run with a message that says so.
|
||||
- The wave is drawn in the browser from the file itself; nothing extra is
|
||||
stored with the workflow besides the node's own values.
|
||||
- Clean up runs in this order: the channels are averaged into one; a
|
||||
high-pass at 80 Hz takes out rumble and mains hum; a noise print is
|
||||
taken from the quietest moments and whatever sits close to it is turned
|
||||
down by up to 12 dB (hiss, fans, room tone); quiet ends are cut, keeping
|
||||
0.1 s before the first sound and 0.2 s after the last; then the volume is
|
||||
set to -18 LUFS (the loudness broadcast meters read) with a limiter that
|
||||
keeps every peak under -1 dBFS. The sample rate stays the file's own.
|
||||
|
||||
@@ -158,6 +158,40 @@ while something is linked to that row. It takes FLOAT or INT. In an API
|
||||
prompt, give a row's input the row's `id` from the `loras` text, for example
|
||||
`"strength_ra1": 0.6`. A name that matches no row is ignored.
|
||||
|
||||
## Strength over the run
|
||||
|
||||
A row can change strength while the picture is made: strong at the start
|
||||
and gone by the end, say, so a style LoRA sets the look and the fine detail
|
||||
at the end comes out clean.
|
||||
|
||||
1. Wire a Strength Curve 🆎 into the loader's `curve` input.
|
||||
2. Each row now shows a small curve mark beside its strength. The first
|
||||
curve you wire marks every row (teal). Click a mark, or right-click the
|
||||
row and pick **Keep a steady strength**, for a row that should stay as
|
||||
it is; its mark turns gray. **Follow the strength curve** in the same
|
||||
menu turns it back on.
|
||||
|
||||
A row that follows the curve runs at its own strength times the curve: a row
|
||||
at 0.8 with a fade out goes from 0.8 down to 0. It works with every model
|
||||
file: full size, fp8, fp8 scaled and int8.
|
||||
|
||||
### Technical details
|
||||
|
||||
The CLIP half of a row is applied as always, since a prompt is encoded once.
|
||||
The model half is loaded in ComfyUI's bypass mode: the LoRA is added to each
|
||||
layer's result as the layer runs, and the model's weights are never
|
||||
rewritten. Before every step the loader sets each following row to its
|
||||
strength times the curve at that step. "Where in the run" is read by the
|
||||
step's noise level, the way ComfyUI reads hook keyframes, so it lines up
|
||||
with Krea 2 Encode's `reference_curve`. In the `loras` text a following row
|
||||
has `"curve": true`; in an API prompt, link `curve` and set that on the rows.
|
||||
|
||||
A moving curve costs a little speed and no memory: on Krea 2 each step ran
|
||||
3 to 8% slower, the same on every model file we tried. A flat curve
|
||||
skips all of this: the rows just run at their strength times its value. The
|
||||
rare parts of a LoRA that are not low-rank (a plain weight or bias
|
||||
difference) cannot change from step to step and stay at the row's strength.
|
||||
|
||||
## Strength bars
|
||||
|
||||
Every named row paints a center-zero bar behind its name: teal grows right
|
||||
|
||||
@@ -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`.
|
||||
|
||||
@@ -5,7 +5,8 @@ Pick a picture size by shape and megapixels, or by dragging. Use it in place of
|
||||
- **Shape:** the left button selects landscape or portrait. Ratio chips follow that choice; square retains it for the next selection. Clicking a chip changes the shape and keeps your current megapixels. To have a chip jump to its size near one megapixel instead, turn off **Chips keep current budget** in the gear.
|
||||
- **Canvas:** drag a side to change one dimension; drag the corner to scale both. Shift frees the corner ratio, Alt removes snapping, and Escape cancels the drag. The bright readout shows the size, megapixels and ratio; an amber dot means the size is off the snap grid, which a typed size can be. Arrow keys nudge the focused canvas by the snap step, or by 8 px with Shift.
|
||||
- **Size & budget:** scrub or type W, H, or MP. Typed dimensions are preserved exactly. The swap button exchanges dimensions. The **Sizes** chips are ready-made sizes for the current ratio, small to large. They show while the shape is one of the ratio chips; any other shape shows one greyed-out "custom" chip.
|
||||
- **Gear:** set the **Snap step**, edit the **Ratio rail**, choose the **Latent family** (`latent`) and **Batch size** (`batch_size`), and hide the **Dot grid** or **MP cost curves**. **Snap step** (8, 16, 32 or 64; starts at 32) is the grid that drags, arrow keys and chips land on. The **Ratio rail** is the list of ratio chips, typed as `1:1, 21:9`. The display options apply to every Latent Size node in this browser; latent family and batch size (1 to 64) belong to this node.
|
||||
- **Gear:** set the **Snap step**, edit the **Ratio chips**, choose the **Latent family** (`latent`) and **Batch size** (`batch_size`), and hide the **Dot grid** or **MP cost curves**. **Snap step** (8, 16, 32 or 64; starts at 32) is the grid that drags, arrow keys and chips land on. The display options apply to every Latent Size node in this browser; latent family and batch size (1 to 64) belong to this node.
|
||||
- **Ratio chips:** in the gear, **Ratio chips → Edit list** shows every ratio with its size near one megapixel. Tick a ratio to show it as a chip, untick it to hide it, × removes it, and the box at the bottom adds your own, such as `21:9`. 5:4 and 21:9 come in the list switched off. **Reset to defaults** brings back the shipped list. Add a ratio once: the flip button turns it portrait.
|
||||
- **Node size:** drag the node's corner to make it wider or taller, so it lines up with the nodes around it. The controls stretch with it, and the canvas preview takes any extra height. It can be as narrow as 320 pixels.
|
||||
|
||||
## Workflow resolutions
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
# Strength Curve
|
||||
|
||||
Draw how strong something should be over a run, from the first step to the
|
||||
last, and wire the curve into a node that follows it step by step.
|
||||
|
||||
- **LoRA Loader 🆎**: wire the curve into its `curve` input and click the
|
||||
curve mark on each row that should follow it. Fade a style LoRA out so
|
||||
the fine detail at the end comes out clean, or bring a detail LoRA in
|
||||
late.
|
||||
- **Krea 2 Encode 🆎**: wire the curve into `reference_curve`. The picture
|
||||
follows your reference as strongly as the curve says: hold the layout
|
||||
early and let go late, or the other way round.
|
||||
|
||||
## Using it
|
||||
|
||||
1. Pick a preset (flat, fade out, fade in, ease out, ease in) or drag the
|
||||
points. Double-click the curve box to add a point, right-click a point to
|
||||
remove it.
|
||||
2. Click a point to pick it, then type or scrub **Point at** (where in the
|
||||
run, in %) and **value** for exact numbers.
|
||||
3. Set **Top** (`high`) and **Bottom** (`low`): the strength at the top and
|
||||
the bottom of the curve box. A fade from 1 to 0.3 is a fade out with
|
||||
Bottom at 0.3.
|
||||
|
||||
Left is the start of the run, where the picture is still noise; right is
|
||||
the end, where only fine detail changes. Hover the curve to read the value at
|
||||
any point.
|
||||
|
||||
## Outputs
|
||||
|
||||
- **curve**: the strength over the run, as a list of numbers from start to
|
||||
end (ComfyUI's `FLOATS` type).
|
||||
|
||||
## Tips
|
||||
|
||||
- On a LoRA row, the curve multiplies the row's own strength. A row at 0.8
|
||||
with a fade out goes from 0.8 to 0.
|
||||
- It works with every model file: full size, fp8, fp8 scaled and int8.
|
||||
- A curve that moves makes each step a little slower (about 5% on Krea 2)
|
||||
and needs no extra memory. A flat line costs nothing.
|
||||
|
||||
## Technical details
|
||||
|
||||
- The points are saved in the hidden `points` input as `[where, value]`
|
||||
pairs from 0 to 1, so a workflow run through the API gives the same
|
||||
curve with no editor open. The line between points is a monotone cubic
|
||||
(Fritsch and Carlson), so it never swings past a point.
|
||||
- The output is 101 values spread evenly from start to end, Bottom to Top.
|
||||
It is the same reading ComfyUI's own **Create Hook Keyframes From
|
||||
Floats** gives a list, so the curve also feeds ComfyUI's hook nodes, and a
|
||||
list of numbers from another node feeds our inputs.
|
||||
- Both nodes read "where in the run" the way ComfyUI's hook keyframes do:
|
||||
ComfyUI's percent of the run, measured by noise level. With
|
||||
the `simple` and `normal` schedulers that matches the step count; other
|
||||
schedulers spend more steps at some noise levels. A second sampler that
|
||||
carries on from the first (a refiner pass, a denoise below 1) reads only
|
||||
the part of the curve it covers.
|
||||
- LoRA Loader adds a following row to each layer's result as the layer
|
||||
runs (ComfyUI's bypass mode), so the model's weights are never rewritten
|
||||
and no second copy of them is kept. Krea 2 Encode scales the reference
|
||||
inside attention.
|
||||
@@ -28,11 +28,15 @@ help panel.
|
||||
| Keep the untouched parts of a picture exactly as they were while an edit model edits it | Edit Lock (`AUSBOSS_NODES_EditLock`) then Edit Lock Restore (`AUSBOSS_NODES_EditLockRestore`) |
|
||||
| Line an edited picture back up with the original | Realign to Source (`AUSBOSS_NODES_RealignToSource`, experimental) |
|
||||
| Match one picture's colors to another | Color Match (`AUSBOSS_NODES_ColorMatch`) |
|
||||
| Add film grain to a picture or a video, or copy another picture's grain | Film Grain (`AUSBOSS_NODES_FilmGrain`) |
|
||||
| Turn a picture and a mask into a transparent cut-out with clean edges | Cut Out (`AUSBOSS_NODES_CutOut`) |
|
||||
| Put the original's fine detail back on a smoothed edit | Keep Detail (`AUSBOSS_NODES_KeepDetail`) |
|
||||
| Upscale big pictures in tiles | Tiled Upscale (`AUSBOSS_NODES_TiledUpscale`) then Tiled Upscale Stitch (`AUSBOSS_NODES_TiledUpscaleStitch`) |
|
||||
| Compare two pictures | Image Compare A/B (`AUSBOSS_NODES_Compare`) |
|
||||
| Save pictures (PNG, lossless WebP or JPEG XL) | Save Image (`AUSBOSS_NODES_SaveImage`) |
|
||||
| Run a workflow on each picture in a folder | Image Folder (`AUSBOSS_NODES_ImageFolder`) |
|
||||
| Apply a stack of LoRAs | LoRA Loader (`AUSBOSS_NODES_LoraLoader`) |
|
||||
| Change a LoRA row's or a Krea 2 reference's strength over the steps of a run | Strength Curve (`AUSBOSS_NODES_StrengthCurve`) into LoRA Loader's `curve` or Krea 2 Encode's `reference_curve` |
|
||||
| Write a MiniMax H3 or Pika H3 Flex prompt from plain words | H3 Prompt Writer (`AUSBOSS_NODES_H3PromptWriter`): [node help](../AUSBOSS_NODES_H3PromptWriter.md) |
|
||||
| Krea 2 prompt, and Krea 2 outpainting | Krea 2 Encode (`AUSBOSS_NODES_Krea2Encode`), Krea 2 Outpaint Model Patch (`AUSBOSS_NODES_Krea2OutpaintModelPatch`) |
|
||||
| Load or save a video | Load Video (`AUSBOSS_NODES_LoadVideo`), Save Video (`AUSBOSS_NODES_SaveVideo`) |
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
// Film Grain's Auto, on the node's face: keeps what Auto picks for the
|
||||
// picture on hand up to date for the card's "= 0.27" notes
|
||||
// (js/shared/grain_auto.mjs).
|
||||
import { api } from "../../../scripts/api.js";
|
||||
import { app } from "../../../scripts/app.js";
|
||||
import { chainCallback } from "../shared/index.mjs";
|
||||
import { isForeignRun } from "../shared/prompt_scope.mjs";
|
||||
import { keepMatch, matchFromRun, refreshAuto } from "../shared/grain_auto.mjs";
|
||||
import { outputLocatorId, sourceFileWidget, upstreamNode } from "../shared/input_preview.mjs";
|
||||
|
||||
const NODE_CLASS = "AUSBOSS_NODES_FilmGrain";
|
||||
const viewUrl = (query) => api.apiURL(`/view?${query}`);
|
||||
|
||||
// One hook on a Load Image's file box, with every Film Grain it feeds listed
|
||||
// under it, so a picked file refreshes them all and a removed node leaves.
|
||||
// Both pictures are watched: the one getting grain, and grain_from's.
|
||||
const watched = new WeakMap();
|
||||
const WATCHED_INPUTS = ["image", "grain_from"];
|
||||
function unwatch(node) {
|
||||
for (const entry of node.__ausbossGrainWatch ?? []) entry.nodes.delete(node);
|
||||
node.__ausbossGrainWatch = [];
|
||||
}
|
||||
function watchFile(node) {
|
||||
const widgets = WATCHED_INPUTS.map((name) => sourceFileWidget(upstreamNode(node, name))).filter(Boolean);
|
||||
const now = node.__ausbossGrainWatch ?? [];
|
||||
if (now.length === widgets.length && now.every((entry, i) => entry.widget === widgets[i])) return;
|
||||
unwatch(node);
|
||||
for (const widget of widgets) {
|
||||
let entry = watched.get(widget);
|
||||
if (!entry) {
|
||||
const nodes = new Set();
|
||||
entry = { widget, nodes };
|
||||
chainCallback(widget, "callback", () => { for (const item of nodes) update(item); });
|
||||
watched.set(widget, entry);
|
||||
}
|
||||
entry.nodes.add(node);
|
||||
node.__ausbossGrainWatch.push(entry);
|
||||
}
|
||||
}
|
||||
|
||||
function update(node) {
|
||||
if (!node?.graph) return;
|
||||
watchFile(node);
|
||||
const record = app.nodeOutputs?.[outputLocatorId(node)] ?? null;
|
||||
refreshAuto(node, { viewUrl, record });
|
||||
}
|
||||
|
||||
const later = (node) => queueMicrotask(() => update(node));
|
||||
|
||||
app.registerExtension({
|
||||
name: "ausboss.film_grain",
|
||||
beforeRegisterNodeDef(nodeType, nodeData) {
|
||||
if (nodeData?.name !== NODE_CLASS) return;
|
||||
chainCallback(nodeType.prototype, "onNodeCreated", function () { later(this); });
|
||||
chainCallback(nodeType.prototype, "onConfigure", function () { later(this); });
|
||||
chainCallback(nodeType.prototype, "onConnectionsChange", function () { later(this); });
|
||||
chainCallback(nodeType.prototype, "onExecuted", function (output) {
|
||||
if (isForeignRun()) return;
|
||||
keepMatch(this, matchFromRun(output));
|
||||
later(this);
|
||||
});
|
||||
chainCallback(nodeType.prototype, "onRemoved", function () { unwatch(this); });
|
||||
},
|
||||
// A reopened workflow restores every node's last output at once.
|
||||
onNodeOutputsUpdated() {
|
||||
for (const node of app.graph?._nodes ?? []) if (node.type === NODE_CLASS) later(node);
|
||||
},
|
||||
});
|
||||
@@ -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; });
|
||||
}));
|
||||
},
|
||||
});
|
||||
@@ -1,5 +1,5 @@
|
||||
// The in-node preview panel for LaMa Inpaint, Mask Refine, Mask by Name,
|
||||
// Select Frame and Save Image.
|
||||
// Select Frame, Save Image, Film Grain, Cut Out and Keep Detail.
|
||||
//
|
||||
// It shows this node's own result once it has one, and falls back to a
|
||||
// thumbnail of whatever feeds its IMAGE/MASK input before the graph has run.
|
||||
@@ -24,9 +24,11 @@ import { chainCallback, keepDomWidgetWidthAuto, notifyAusbossChange } from "../s
|
||||
import { ensureNodeMinHeight, fillNodeHeight, growToNodeFloor } from "../shared/panel_layout.mjs";
|
||||
import { suppressCoreImagePreview } from "../shared/core_preview.mjs";
|
||||
import { autoMaskValues } from "../shared/mask_auto.mjs";
|
||||
import { CHECKER } from "../shared/compare_erase.mjs";
|
||||
import { hideInputsInDef, hideWidget, setWidgetVisible } from "../shared/widget_visibility.mjs";
|
||||
import { makePictureStepper } from "../shared/picture_stepper.mjs";
|
||||
import { ALL, allLabel, gridShape, heldPlaces, keepIndex, keepWords, stepIndex, stepWithAll } from "../shared/picture_steps.mjs";
|
||||
import { mountLive, takeStage } from "../shared/live_stage.mjs";
|
||||
import { addStepConsumer, mountStepOverlay, showsStepsOn, stepRun, stopStepRun, watchSteps } from "../shared/step_preview.mjs";
|
||||
import {
|
||||
describeNodePreview,
|
||||
@@ -123,6 +125,11 @@ const NODE_CONFIG = {
|
||||
: null),
|
||||
},
|
||||
AUSBOSS_NODES_SelectFrame: { inputName: "frames", noun: "frames" },
|
||||
// These three redraw their picture while a value is dragged, before any
|
||||
// run (shared/live_stage.mjs), with a Fit | 100% switch on the bar.
|
||||
AUSBOSS_NODES_FilmGrain: { inputName: "image", noun: "an image", live: "grain" },
|
||||
AUSBOSS_NODES_CutOut: { inputName: "image", noun: "an image", checker: true, live: "cutout" },
|
||||
AUSBOSS_NODES_KeepDetail: { inputName: "image", noun: "an image", live: "detail" },
|
||||
// Its result is the file it just saved; the card sits above the panel.
|
||||
// SAVE shows only for a run made with Auto save off, which holds its
|
||||
// pictures until this button keeps them.
|
||||
@@ -157,6 +164,7 @@ function ensureCss() {
|
||||
.ausboss-input-preview.preview-off .ausboss-stepper{display:none;}
|
||||
.ausboss-input-preview-stage img,.ausboss-input-preview-stage video{display:none;position:absolute;inset:0;margin:auto;max-width:100%;max-height:100%;object-fit:contain;}
|
||||
.ausboss-input-preview-stage.show-image img{display:block;}
|
||||
.ausboss-input-preview-stage.checker img{background-image:repeating-conic-gradient(${CHECKER.light} 0 25%,${CHECKER.dark} 0 50%);background-size:${CHECKER.side * 2}px ${CHECKER.side * 2}px;}
|
||||
.ausboss-input-preview-stage.loading-image img{opacity:.4;transition:opacity .3s ease 1.2s;}
|
||||
.ausboss-input-preview-stage.show-video video{display:block;}
|
||||
.ausboss-input-preview-grid{display:none;position:absolute;inset:0;box-sizing:border-box;gap:${GRID_GAP}px;padding:${GRID_GAP}px;justify-content:center;align-content:center;}
|
||||
@@ -848,6 +856,9 @@ function refresh(state) {
|
||||
}
|
||||
const source = upstreamNode(state.node, state.inputName);
|
||||
rewatchSource(state, source);
|
||||
// Film Grain, Keep Detail and Cut Out draw their own picture while a value
|
||||
// is dragged; the stage is theirs for as long as they can.
|
||||
if (state.live && takeStage(state)) return;
|
||||
const count = resultCount(state);
|
||||
const hidden = state.stepper.root.hidden;
|
||||
state.index = keepIndex(state.index, count);
|
||||
@@ -964,6 +975,8 @@ function buildPanel(node, config) {
|
||||
root.className = "ausboss-input-preview";
|
||||
const stage = document.createElement("div");
|
||||
stage.className = "ausboss-input-preview-stage";
|
||||
// A cut-out's see-through parts show over a checkerboard.
|
||||
if (config.checker) stage.classList.add("checker");
|
||||
const img = document.createElement("img");
|
||||
const video = document.createElement("video");
|
||||
video.muted = true;
|
||||
@@ -1047,6 +1060,16 @@ function buildPanel(node, config) {
|
||||
syncAdvanced(state);
|
||||
installPreviewSwitch(state, abort.signal);
|
||||
if (config.steps) installStepsSwitch(state, abort.signal);
|
||||
if (config.live) {
|
||||
state.live = mountLive(state, config.live, {
|
||||
refresh: () => refresh(state),
|
||||
// A run that came while the preview was off left an older picture.
|
||||
record: () => (state.stale ? null : outputRecord(node) ?? null),
|
||||
hasResult: () => resultCount(state) > 0,
|
||||
resultUrl: () => storedResultUrl(node),
|
||||
viewUrl: (query) => api.apiURL(`/view?${query}`),
|
||||
});
|
||||
}
|
||||
|
||||
// The grid is laid out for the stage's shape, so a resized node lays it out again.
|
||||
if (typeof ResizeObserver === "function") {
|
||||
@@ -1162,6 +1185,7 @@ app.registerExtension({
|
||||
clearTimeout(state.toastTimer);
|
||||
state.timer = 0;
|
||||
state.abort?.abort();
|
||||
state.live?.dispose();
|
||||
unwatchSource(state);
|
||||
clearMedia(state);
|
||||
for (const forget of state.forgetSteps ?? []) forget();
|
||||
|
||||
@@ -0,0 +1,329 @@
|
||||
// Check layout 🆎 (canvas right-click menu and command palette): lists what
|
||||
// makes a workflow hard to read and moves nothing. Overlapping nodes and
|
||||
// groups, wires that run backwards or hide behind a node, a node close under
|
||||
// one that grows when it runs, nodes outside every group, a saved zoom too
|
||||
// small to read and a missing Workflow Note, on the top level and inside
|
||||
// every subgraph. Click an entry to jump to it. The decisions live in
|
||||
// js/shared/layout_check_math.mjs under node:test.
|
||||
|
||||
import { app } from "../../../scripts/app.js";
|
||||
import { t } from "../shared/i18n.mjs";
|
||||
import { THEME as T, FONT_UI } from "../shared/theme.mjs";
|
||||
import { compactAction } from "../shared/panel_controls.mjs";
|
||||
import { CALLOUT_TYPES, NOTE_TYPES } from "../shared/note_identity.mjs";
|
||||
import { normalizeNote } from "../shared/workflow_note.mjs";
|
||||
import { frameBounds } from "../shared/workflow_switches.mjs";
|
||||
import { KINDS, MIN_ZOOM, checkLayout, countByKind, jumpViewport } from "../shared/layout_check_math.mjs";
|
||||
|
||||
const CSS_ID = "ausboss-layout-check-css";
|
||||
const LABEL = "Check layout";
|
||||
const FRAME_FILL = 0.8;
|
||||
// Core nodes that get taller once a run shows its picture or text in them.
|
||||
// The pack's own preview nodes keep their size (js/input_preview/).
|
||||
const GROWS = new Set(["PreviewImage", "SaveImage", "SaveAnimatedWEBP", "SaveAnimatedPNG", "SaveWEBM", "SaveVideo", "PreviewAny"]);
|
||||
const KIND_LABEL = {
|
||||
"overlap": "Overlapping",
|
||||
"group-overlap": "Groups overlapping",
|
||||
"under-grower": "Under a node that grows",
|
||||
"hidden-wire": "Wire behind a node",
|
||||
"backward-wire": "Wire runs backwards",
|
||||
"outside-group": "Outside every group",
|
||||
"no-groups": "No groups",
|
||||
"zoom": "Zoomed out too far",
|
||||
"no-note": "No Workflow Note",
|
||||
};
|
||||
|
||||
function ensureCss() {
|
||||
if (document.getElementById(CSS_ID)) return;
|
||||
const style = document.createElement("style");
|
||||
style.id = CSS_ID;
|
||||
style.textContent = `
|
||||
.ausboss-layout-check{position:fixed;z-index:1000;display:flex;flex-direction:column;box-sizing:border-box;width:360px;max-height:70vh;overflow:hidden;border:1px solid ${T.rule};border-radius:10px;background:${T.card};box-shadow:0 12px 40px #0009;color:${T.inkSoft};font:12px/1.4 ${FONT_UI}}
|
||||
.ausboss-layout-check header{display:flex;align-items:center;gap:6px;padding:10px 10px 8px 14px;border-bottom:1px solid ${T.rule}}
|
||||
.ausboss-layout-check header b{color:${T.ink};font-size:13px;font-weight:650}
|
||||
.ausboss-layout-check header span{margin-right:auto;color:${T.faint}}
|
||||
.ausboss-layout-check-list{overflow:auto;padding:4px 0 6px}
|
||||
.ausboss-layout-check h4{display:flex;align-items:center;gap:6px;margin:10px 14px 4px;color:${T.label};font:600 11px/1.25 ${FONT_UI}}
|
||||
.ausboss-layout-check h4 i{color:${T.faint};font-style:normal}
|
||||
.ausboss-layout-check-row{display:block;box-sizing:border-box;width:100%;padding:5px 12px 5px 11px;border:0;border-left:3px solid transparent;background:transparent;color:${T.inkSoft};font:12px/1.35 ${FONT_UI};text-align:left;cursor:pointer}
|
||||
.ausboss-layout-check-row:hover{background:${T.fill}}
|
||||
.ausboss-layout-check-row.is-picked{border-left-color:${T.brand};background:${T.brandSoft}}
|
||||
.ausboss-layout-check-row:focus-visible{outline:2px solid ${T.brand};outline-offset:-2px}
|
||||
.ausboss-layout-check-row small{display:block;color:${T.faint};font-size:11px}
|
||||
.ausboss-layout-check-row.is-info{cursor:default}
|
||||
.ausboss-layout-check-row.is-info:hover{background:transparent}
|
||||
.ausboss-layout-check-clean{padding:12px 14px;color:${T.inkSoft}}
|
||||
.ausboss-layout-check-clean small{display:block;margin-top:2px;color:${T.faint};font-size:11px}
|
||||
.ausboss-layout-check footer{padding:7px 14px 9px;border-top:1px solid ${T.rule};color:${T.faint};font-size:11px}
|
||||
`;
|
||||
document.head.append(style);
|
||||
}
|
||||
|
||||
const el = (tag, className, text) => {
|
||||
const node = document.createElement(tag);
|
||||
if (className) node.className = className;
|
||||
if (text !== undefined && text !== null) node.textContent = text;
|
||||
return node;
|
||||
};
|
||||
|
||||
// A name from the graph: never translated, whatever it says.
|
||||
const nameSpan = (text) => {
|
||||
const span = el("span", "", text);
|
||||
span.dataset.noI18n = "";
|
||||
return span;
|
||||
};
|
||||
|
||||
const LINK_MODES = { 0: "straight", 1: "linear", 2: "spline" };
|
||||
|
||||
function titleHeight(node) {
|
||||
const LG = globalThis.LiteGraph;
|
||||
const none = LG?.NO_TITLE;
|
||||
if (none !== undefined && (node.title_mode === none || node.constructor?.title_mode === none)) return 0;
|
||||
return LG?.NODE_TITLE_HEIGHT ?? 30;
|
||||
}
|
||||
|
||||
// A graph as plain numbers for checkLayout.
|
||||
function readGraph(graph, top) {
|
||||
const LG = globalThis.LiteGraph;
|
||||
const nodes = (graph._nodes ?? graph.nodes ?? []).map((node) => {
|
||||
const collapsed = Boolean(node.flags?.collapsed);
|
||||
const kind = NOTE_TYPES.has(node.type) ? "note" : CALLOUT_TYPES.has(node.type) ? "callout" : null;
|
||||
return {
|
||||
id: node.id,
|
||||
x: node.pos[0],
|
||||
y: node.pos[1],
|
||||
w: collapsed ? (node._collapsed_width ?? LG?.NODE_COLLAPSED_WIDTH ?? 80) : node.size[0],
|
||||
h: collapsed ? 0 : node.size[1],
|
||||
titleHeight: titleHeight(node),
|
||||
grows: GROWS.has(node.type),
|
||||
kind,
|
||||
};
|
||||
});
|
||||
const mode = app.canvas?.links_render_mode;
|
||||
const links = [];
|
||||
if (mode !== LG?.HIDDEN_LINK) {
|
||||
const all = graph.links instanceof Map ? [...graph.links.values()] : Object.values(graph.links ?? {});
|
||||
for (const link of all) {
|
||||
const from = link && graph.getNodeById?.(link.origin_id);
|
||||
const to = link && graph.getNodeById?.(link.target_id);
|
||||
if (!from || !to) continue;
|
||||
const start = from.getConnectionPos?.(false, link.origin_slot);
|
||||
const end = to.getConnectionPos?.(true, link.target_slot);
|
||||
if (!start || !end) continue;
|
||||
const via = [];
|
||||
for (let id = link.parentId, guard = 0; id !== undefined && id !== null && guard < 64; guard++) {
|
||||
const reroute = graph.reroutes?.get?.(id);
|
||||
if (!reroute) break;
|
||||
via.unshift([reroute.pos[0], reroute.pos[1]]);
|
||||
id = reroute.parentId;
|
||||
}
|
||||
links.push({ id: link.id, from: from.id, to: to.id, points: [[start[0], start[1]], ...via, [end[0], end[1]]] });
|
||||
}
|
||||
}
|
||||
const groups = (graph.groups ?? graph._groups ?? []).map((group) => {
|
||||
const [x, y, w, h] = group._bounding ?? [group.pos[0], group.pos[1], group.size[0], group.size[1]];
|
||||
return { id: group.id, x, y, w, h };
|
||||
});
|
||||
const shape = { nodes, links, groups, linkMode: LINK_MODES[mode] ?? "spline", topLevel: top };
|
||||
if (top) {
|
||||
const notes = (graph._nodes ?? []).filter((node) => NOTE_TYPES.has(node.type));
|
||||
shape.noteFilled = notes.some((node) => {
|
||||
const note = normalizeNote(node.widgets?.find((widget) => widget.name === "note")?.value);
|
||||
return Boolean(note.title && note.body.trim());
|
||||
});
|
||||
if (app.canvas?.graph === graph) shape.scale = app.canvas.ds?.scale;
|
||||
}
|
||||
return shape;
|
||||
}
|
||||
|
||||
// Every issue of the workflow, each with the graph it is in and the names of
|
||||
// the boxes that lead there.
|
||||
function findIssues() {
|
||||
const root = app.rootGraph ?? app.graph;
|
||||
if (!root) return [];
|
||||
const graphs = [{ graph: root, path: [] }];
|
||||
for (const sub of root.subgraphs?.values?.() ?? []) graphs.push({ graph: sub, path: [sub.name || "Subgraph"] });
|
||||
const out = [];
|
||||
for (const { graph, path } of graphs) {
|
||||
for (const issue of checkLayout(readGraph(graph, path.length === 0))) out.push({ ...issue, graph, path });
|
||||
}
|
||||
return out.sort((a, b) => KINDS.indexOf(a.kind) - KINDS.indexOf(b.kind));
|
||||
}
|
||||
|
||||
const nodeName = (graph, id) => {
|
||||
const node = graph.getNodeById?.(id);
|
||||
return node?.getTitle?.() ?? node?.title ?? String(id);
|
||||
};
|
||||
const groupName = (graph, id) => (graph.groups ?? []).find((group) => group.id === id)?.title || "Group";
|
||||
|
||||
// The two lines of an entry: what, and why or where.
|
||||
function describe(issue) {
|
||||
const { graph } = issue;
|
||||
const names = (ids) => ids.map((id) => nodeName(graph, id));
|
||||
const main = [];
|
||||
const small = [];
|
||||
const wires = issue.wires > 1 ? [" · ", el("span", "", `${issue.wires} wires`)] : [];
|
||||
switch (issue.kind) {
|
||||
case "overlap":
|
||||
main.push(nameSpan(names(issue.nodes).join(" × ")));
|
||||
small.push("Title bars count too");
|
||||
break;
|
||||
case "group-overlap":
|
||||
main.push(nameSpan(issue.groups.map((id) => groupName(graph, id)).join(" × ")));
|
||||
small.push("One group crosses the other");
|
||||
break;
|
||||
case "under-grower":
|
||||
main.push(nameSpan(nodeName(graph, issue.nodes[0])));
|
||||
small.push(el("span", "", "Under:"), " ", nameSpan(nodeName(graph, issue.nodes[1])));
|
||||
break;
|
||||
case "hidden-wire":
|
||||
main.push(nameSpan(names(issue.nodes.slice(0, 2)).join(" → ")));
|
||||
small.push(el("span", "", "Behind:"), " ", nameSpan(names(issue.behind).join(", ")), ...wires);
|
||||
break;
|
||||
case "backward-wire":
|
||||
main.push(nameSpan(names(issue.nodes).join(" → ")));
|
||||
small.push(el("span", "", "Ends left of where it starts"), ...wires);
|
||||
break;
|
||||
case "outside-group":
|
||||
main.push(nameSpan(nodeName(graph, issue.nodes[0])));
|
||||
small.push("Move it into a group");
|
||||
break;
|
||||
case "no-groups":
|
||||
main.push("Nothing here is in a group");
|
||||
small.push("Put each step in a numbered group");
|
||||
break;
|
||||
case "zoom":
|
||||
main.push(el("span", "", "Saved zoom:"), " ", nameSpan(issue.scale.toFixed(2)));
|
||||
small.push(el("span", "", `Below ${MIN_ZOOM.toFixed(2)} the text on nodes stops drawing`));
|
||||
break;
|
||||
case "no-note":
|
||||
main.push(issue.empty ? "The Workflow Note has no title or steps" : "Add a Workflow Note");
|
||||
small.push("It tells people what the workflow does and how to run it");
|
||||
break;
|
||||
default:
|
||||
main.push(issue.kind);
|
||||
}
|
||||
if (issue.path.length) small.push(small.length ? " · " : "", el("span", "", "Inside:"), " ", nameSpan(issue.path.join(" › ")));
|
||||
return { main, small };
|
||||
}
|
||||
|
||||
// Open the graph the issue is in, select what it names and bring it into view.
|
||||
function jump(issue) {
|
||||
const canvas = app.canvas;
|
||||
if (!canvas) return;
|
||||
const { graph } = issue;
|
||||
if (canvas.graph !== graph) {
|
||||
const root = app.rootGraph ?? app.graph;
|
||||
if (graph !== root && typeof canvas.openSubgraph === "function") canvas.openSubgraph(graph);
|
||||
else canvas.setGraph?.(graph);
|
||||
}
|
||||
canvas.deselectAll?.();
|
||||
for (const id of issue.nodes ?? []) {
|
||||
const node = graph.getNodeById?.(id);
|
||||
if (node) canvas.select?.(node);
|
||||
}
|
||||
for (const id of issue.groups ?? []) {
|
||||
const group = (graph.groups ?? []).find((item) => item.id === id);
|
||||
if (group) canvas.select?.(group);
|
||||
}
|
||||
const focus = issue.focus;
|
||||
if (focus) {
|
||||
const view = canvas.canvas?.getBoundingClientRect?.();
|
||||
// Frame it in the part of the canvas left of the panel, so what the
|
||||
// panel names is never under it.
|
||||
const viewport = jumpViewport(view, panel?.getBoundingClientRect?.());
|
||||
const size = viewport ? [viewport[2], viewport[3]] : [view?.width, view?.height];
|
||||
const rect = frameBounds([focus[0], focus[1], focus[2] - focus[0], focus[3] - focus[1]], size, FRAME_FILL);
|
||||
const options = viewport ? { zoom: FRAME_FILL, viewport } : { zoom: FRAME_FILL };
|
||||
if (typeof canvas.animateToBounds === "function") canvas.animateToBounds(rect, options);
|
||||
else canvas.ds?.fitToBounds?.(rect, options);
|
||||
}
|
||||
canvas.setDirty?.(true, true);
|
||||
}
|
||||
|
||||
let panel = null;
|
||||
|
||||
function onKey(event) {
|
||||
if (event.key !== "Escape" || !panel || event.target?.closest?.("input,textarea,select,[contenteditable]")) return;
|
||||
closePanel();
|
||||
}
|
||||
|
||||
function closePanel() {
|
||||
if (!panel) return;
|
||||
panel.remove();
|
||||
panel = null;
|
||||
window.removeEventListener("keydown", onKey, true);
|
||||
}
|
||||
|
||||
function fill(list, count) {
|
||||
const issues = findIssues();
|
||||
list.replaceChildren();
|
||||
count.textContent = issues.length === 0 ? "Nothing to fix" : issues.length === 1 ? "1 thing to look at" : `${issues.length} things to look at`;
|
||||
if (!issues.length) {
|
||||
const clean = el("div", "ausboss-layout-check-clean", "Nothing to fix.");
|
||||
clean.append(el("small", "", "No overlaps, no hidden or backwards wires, and every node sits in a group."));
|
||||
list.append(clean);
|
||||
return;
|
||||
}
|
||||
for (const [kind, total] of countByKind(issues)) {
|
||||
const heading = el("h4", "", KIND_LABEL[kind] ?? kind);
|
||||
heading.append(el("i", "", String(total)));
|
||||
list.append(heading);
|
||||
for (const issue of issues.filter((item) => item.kind === kind)) {
|
||||
const { main, small } = describe(issue);
|
||||
const canJump = Boolean(issue.focus || issue.nodes?.length || issue.groups?.length);
|
||||
const row = el(canJump ? "button" : "div", `ausboss-layout-check-row${canJump ? "" : " is-info"}`);
|
||||
if (canJump) row.type = "button";
|
||||
row.append(...main);
|
||||
if (small.length) {
|
||||
const line = el("small");
|
||||
line.append(...small);
|
||||
row.append(line);
|
||||
}
|
||||
if (canJump) {
|
||||
row.addEventListener("click", () => {
|
||||
list.querySelector(".is-picked")?.classList.remove("is-picked");
|
||||
row.classList.add("is-picked");
|
||||
jump(issue);
|
||||
});
|
||||
}
|
||||
list.append(row);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function openPanel() {
|
||||
closePanel();
|
||||
ensureCss();
|
||||
panel = el("div", "ausboss-layout-check");
|
||||
panel.setAttribute("role", "dialog");
|
||||
panel.setAttribute("aria-label", LABEL);
|
||||
const head = el("header");
|
||||
const count = el("span");
|
||||
const again = compactAction("Check again", "Look at the workflow again after a change");
|
||||
const close = compactAction("✕", "Close");
|
||||
head.append(el("b", "", LABEL), count, again, close);
|
||||
const list = el("div", "ausboss-layout-check-list");
|
||||
panel.append(head, list, el("footer", "", "Click an entry to jump to it. Nothing is moved."));
|
||||
again.addEventListener("click", () => fill(list, count));
|
||||
close.addEventListener("click", closePanel);
|
||||
// The panel is not part of the canvas: a press here must not start a drag.
|
||||
panel.addEventListener("pointerdown", (event) => event.stopPropagation());
|
||||
const rect = app.canvas?.canvas?.getBoundingClientRect?.();
|
||||
panel.style.left = `${(rect?.right ?? window.innerWidth) - 376}px`;
|
||||
panel.style.top = `${(rect?.top ?? 0) + 100}px`;
|
||||
document.body.append(panel);
|
||||
window.addEventListener("keydown", onKey, true);
|
||||
fill(list, count);
|
||||
}
|
||||
|
||||
app.registerExtension({
|
||||
name: "AusBoss.LayoutCheck",
|
||||
commands: [{ id: "AusBoss.CheckLayout", label: `AusBoss: ${LABEL}`, function: openPanel }],
|
||||
getCanvasMenuItems() {
|
||||
return [{ content: `${t(LABEL)} 🆎`, callback: openPanel }];
|
||||
},
|
||||
afterConfigureGraph() {
|
||||
closePanel();
|
||||
},
|
||||
});
|
||||
+60
-3
@@ -1,7 +1,7 @@
|
||||
import { api } from "../../../scripts/api.js";
|
||||
import { app } from "../../../scripts/app.js";
|
||||
import { BRAND, chainCallback, keepDomWidgetWidthAuto, notifyAusbossChange, showToast } from "../shared/index.mjs";
|
||||
import { WIDGET_FRAME, fillNodeHeight, holdVueNodeMinWidth } from "../shared/panel_layout.mjs";
|
||||
import { WIDGET_FRAME, fillNodeHeight, growToNodeFloor, holdVueNodeMinWidth } from "../shared/panel_layout.mjs";
|
||||
import { hideInputsInDef, hideWidget as collapseWidget } from "../shared/widget_visibility.mjs";
|
||||
import {
|
||||
closeSettingsMenu,
|
||||
@@ -30,6 +30,8 @@ import {
|
||||
STRENGTH_MIN,
|
||||
appendFolderRows,
|
||||
clampHighlight,
|
||||
followCurve,
|
||||
rowsForNewCurve,
|
||||
fitLoraLabel,
|
||||
formatFileSize,
|
||||
groupName,
|
||||
@@ -225,6 +227,8 @@ const SETTINGS_SCHEMA = [
|
||||
// as much, and the name keeps the same room.
|
||||
const PANEL_MIN_WIDTH = 320;
|
||||
const SEPARATE_EXTRA_WIDTH = 72;
|
||||
// The curve mark and its gap, on every row while a Strength Curve is wired in.
|
||||
const CURVE_MARK_WIDTH = 28;
|
||||
// The popups' font, shared with the picker's width measurement, and the
|
||||
// picker's side paddings, from which an option's text width is worked out.
|
||||
const POP_FONT = "12px system-ui";
|
||||
@@ -260,6 +264,11 @@ function installStyles() {
|
||||
.ausboss-lora-actions { pointer-events: auto; }
|
||||
.ausboss-lora-row { flex: none; display: flex; align-items: center; gap: 6px; height: ${ROW_HEIGHT}px; }
|
||||
.ausboss-lora-row:focus-visible { outline: 2px solid ${BRAND}; outline-offset: 1px; border-radius: 4px; }
|
||||
.ausboss-lora-curve { flex: none; width: 22px; height: 22px; display: grid; place-items: center; padding: 0;
|
||||
border: 0; border-radius: 5px; background: #2d3134; color: #62676d; cursor: pointer; }
|
||||
.ausboss-lora-curve:hover { background: #383c40; color: #b4b9bd; }
|
||||
.ausboss-lora-curve.on { background: rgba(0,180,170,.26); color: #45d6cb; }
|
||||
.ausboss-lora-curve:focus-visible { outline: 2px solid ${BRAND}; outline-offset: 1px; }
|
||||
/* An off row dims its controls, not itself: the row's own opacity would
|
||||
dim the focus outline with them. A dragged row is dimmed as one piece. */
|
||||
.ausboss-lora-row.off > * { opacity: 0.45; }
|
||||
@@ -796,6 +805,31 @@ function linked(state) {
|
||||
return (state.box?.loader ?? state.node).properties?.ausbossLoraLinked !== false;
|
||||
}
|
||||
|
||||
// A Strength Curve is wired into this loader's `curve` input. Only then do
|
||||
// the rows show the mark that makes one follow it.
|
||||
function curveWired(state) {
|
||||
if (state.box || state.readOnly) return false;
|
||||
return Boolean(state.node.inputs?.some((input) => input?.name === "curve" && input.link != null));
|
||||
}
|
||||
|
||||
function setFollowsCurve(state, ids, on) {
|
||||
commitRows(state, followCurve(state.rows, ids, on), { structural: true });
|
||||
}
|
||||
|
||||
// The curve wire came or went: the marks show or hide, and a first curve
|
||||
// marks every row. A workflow being opened keeps the marks it was saved with.
|
||||
function curveLinksChanged(state, { opening = false } = {}) {
|
||||
const wired = curveWired(state);
|
||||
if (wired === state.curveWired) return;
|
||||
state.curveWired = wired;
|
||||
if (wired && !opening && !app.configuringGraph && state.rows.length && !state.rows.some((row) => row.curve)) {
|
||||
commitRows(state, rowsForNewCurve(state.rows), { structural: true });
|
||||
} else {
|
||||
renderRows(state);
|
||||
}
|
||||
growToNodeFloor(state.domWidget);
|
||||
}
|
||||
|
||||
// Picker options honor only hide-extension: their folder context is the
|
||||
// disambiguator (group headers, search prefixes), so it stays.
|
||||
function displayName(state, name) {
|
||||
@@ -876,7 +910,7 @@ function panelHeight(state) {
|
||||
}
|
||||
|
||||
function panelMinWidth(state) {
|
||||
return PANEL_MIN_WIDTH + (linked(state) ? 0 : SEPARATE_EXTRA_WIDTH);
|
||||
return PANEL_MIN_WIDTH + (linked(state) ? 0 : SEPARATE_EXTRA_WIDTH) + (curveWired(state) ? CURVE_MARK_WIDTH : 0);
|
||||
}
|
||||
|
||||
function fitNode(state) {
|
||||
@@ -2011,6 +2045,11 @@ function openRowMenu(state, index, event) {
|
||||
});
|
||||
menu.append(el("div", "ausboss-lora-menu-rule"));
|
||||
}
|
||||
if (curveWired(state)) {
|
||||
const follow = !chosen.every((entry) => entry.curve);
|
||||
item(follow ? "Follow the strength curve" : "Keep a steady strength", () => setFollowsCurve(state, ids, follow));
|
||||
menu.append(el("div", "ausboss-lora-menu-rule"));
|
||||
}
|
||||
item("Insert empty LoRA above", () => insertEmpty(index));
|
||||
item("Insert empty LoRA below", () => insertEmpty(index + 1));
|
||||
item("Move up", () => commitGroups(state, moveRowInStack(state.rows, index, -1)),
|
||||
@@ -3141,7 +3180,20 @@ function renderRows(state) {
|
||||
showHoverThumb(state, row.name, event.clientX, event.clientY));
|
||||
name.addEventListener("pointerleave", hideHoverThumb);
|
||||
|
||||
rowElement.append(grip, toggle, name, strengthBox(state, index, "strength"));
|
||||
rowElement.append(grip, toggle, name);
|
||||
if (curveWired(state)) {
|
||||
const mark = el("button", `ausboss-lora-curve${row.curve ? " on" : ""}`);
|
||||
mark.type = "button";
|
||||
mark.title = row.curve
|
||||
? "This LoRA follows the strength curve. Click to keep it steady."
|
||||
: "This LoRA keeps one strength. Click to make it follow the strength curve.";
|
||||
mark.setAttribute("role", "switch");
|
||||
mark.setAttribute("aria-checked", String(Boolean(row.curve)));
|
||||
mark.innerHTML = '<svg width="14" height="10" viewBox="0 0 14 10" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" aria-hidden="true"><path d="M1 2 C5 2 6 8 13 8"/></svg>';
|
||||
mark.addEventListener("click", () => setFollowsCurve(state, [row.id], !row.curve));
|
||||
rowElement.append(mark);
|
||||
}
|
||||
rowElement.append(strengthBox(state, index, "strength"));
|
||||
if (!linked(state)) rowElement.append(strengthBox(state, index, "strength_clip"));
|
||||
|
||||
const info = el("button", "ausboss-lora-info", "i");
|
||||
@@ -3461,6 +3513,7 @@ function mountCard(node, { box = null, separatorWidget = null, onMissingWidget =
|
||||
state.owner = source.owner;
|
||||
state.note = source.note;
|
||||
state.readOnly = Boolean(source.readOnly);
|
||||
state.curveWired = curveWired(state);
|
||||
if (box) hideWidget(source.widget);
|
||||
state.rows = parseRows(state.widget.value);
|
||||
state.renderedValue = state.widget.value;
|
||||
@@ -3613,9 +3666,13 @@ app.registerExtension({
|
||||
// Now, not later: ComfyUI reads its missing-models list right after
|
||||
// the workflow is restored.
|
||||
syncLoraFiles(this);
|
||||
queueMicrotask(() => {
|
||||
if (this.__ausbossLoraState) curveLinksChanged(this.__ausbossLoraState, { opening: true });
|
||||
});
|
||||
});
|
||||
chainCallback(nodeType.prototype, "onConnectionsChange", function () {
|
||||
syncLoraFiles(this);
|
||||
if (this.__ausbossLoraState) curveLinksChanged(this.__ausbossLoraState);
|
||||
});
|
||||
},
|
||||
// A box (subgraph node) shows the rows of a loader inside once they come
|
||||
|
||||
+182
-7
@@ -32,17 +32,20 @@ import { WIDGET_FRAME, fillNodeHeight, holdVueNodeMinWidth } from "../shared/pan
|
||||
import { hideInputsInDef, hideWidget } from "../shared/widget_visibility.mjs";
|
||||
import { liftSlot, markSocketless } from "../shared/widget_card_math.mjs";
|
||||
import { makeScrubInput } from "../shared/scrub_input.mjs";
|
||||
import { keepKeyInField } from "../shared/canvas_passthrough.mjs";
|
||||
import {
|
||||
closeSettingsMenu,
|
||||
gearIconSvg,
|
||||
loadSettings,
|
||||
openSettingsMenu,
|
||||
saveSetting,
|
||||
} from "../shared/settings_menu.mjs";
|
||||
import {
|
||||
DEFAULT_RAIL,
|
||||
DEFAULT_SNAP,
|
||||
DIM_MAX,
|
||||
DIM_MIN,
|
||||
RAIL_MAX,
|
||||
SNAP_STEPS,
|
||||
applyRatioAtBudget,
|
||||
chipMatch,
|
||||
@@ -54,12 +57,16 @@ import {
|
||||
offGrid,
|
||||
orientRatio,
|
||||
parseRail,
|
||||
parseRatioToken,
|
||||
parseWorkflowSizes,
|
||||
railEntries,
|
||||
railText,
|
||||
ratioKey,
|
||||
readWorkflowPolicy,
|
||||
savedWorkflowPolicy,
|
||||
workflowRatios,
|
||||
quickSizes,
|
||||
ratioLabel,
|
||||
railRatioLabel,
|
||||
reduceRatio,
|
||||
scrubDim,
|
||||
sizeForMegapixels,
|
||||
@@ -102,9 +109,11 @@ const SETTINGS_SCHEMA = [
|
||||
+ "to that ratio's ~1MP size.",
|
||||
},
|
||||
{
|
||||
key: "rail", label: "Ratio rail", type: "text",
|
||||
default: DEFAULT_RAIL, placeholder: DEFAULT_RAIL,
|
||||
hint: "Comma-separated ratios shown as chips, e.g. \"1:1, 21:9\".",
|
||||
// Stored as text ("1:1, 16:9, -21:9"); the gear shows it as a list
|
||||
// editor (editRatioRail), never as this text field.
|
||||
key: "rail", label: "Ratio chips", type: "text",
|
||||
default: DEFAULT_RAIL,
|
||||
hint: "Which ratios show as chips. Switch them on or off, or add your own, like 21:9.",
|
||||
},
|
||||
{ section: "Latent output" },
|
||||
{
|
||||
@@ -146,6 +155,25 @@ function installStyles() {
|
||||
.ausboss-size-dialog [role=alert]{color:#ffd49e}
|
||||
.ausboss-size-dialog p{color:#adc1be;font:12px/1.45 system-ui;margin:7px 0 12px}
|
||||
.ausboss-size-dialog footer{display:flex;justify-content:flex-end;gap:8px;margin-top:12px}
|
||||
.ausboss-size-dialog footer .grow{margin-right:auto}
|
||||
.ausboss-rail-list{list-style:none;margin:0;padding:0;max-height:min(320px,50vh);overflow:auto;
|
||||
border:1px solid #2a3a3a;border-radius:8px;background:#111819}
|
||||
.ausboss-rail-row{display:flex;align-items:center;gap:10px;height:32px;padding:0 6px 0 10px;
|
||||
border-bottom:1px solid #1f2b2b;cursor:pointer}
|
||||
.ausboss-rail-row:last-child{border-bottom:0}
|
||||
.ausboss-rail-row.off{color:#6f8482}
|
||||
.ausboss-rail-row .box{width:24px;height:16px;display:flex;align-items:center;justify-content:center;flex:none}
|
||||
.ausboss-rail-row .box span{display:block;border:1.4px solid currentColor;border-radius:2px;box-sizing:border-box}
|
||||
.ausboss-rail-row .name{font:12px ${MONO};min-width:44px}
|
||||
.ausboss-rail-row .size{flex:1;color:#7f9795;font:11px ${MONO}}
|
||||
.ausboss-rail-row.off .size{color:#4f6260}
|
||||
.ausboss-rail-del{width:24px;height:24px;border:0;border-radius:5px;background:none;color:#7f9795;
|
||||
cursor:pointer;font:15px/1 system-ui}
|
||||
.ausboss-rail-del:hover{background:#3a2424;color:#ffb4a8}
|
||||
.ausboss-rail-add{display:flex;align-items:center;gap:8px;margin-top:10px}
|
||||
.ausboss-rail-add input{flex:1;min-width:0;box-sizing:border-box;height:28px;padding:0 8px;
|
||||
border:1px solid #345554;border-radius:6px;background:#0f1516;color:#d7e4e3;font:12px ${MONO}}
|
||||
.ausboss-rail-add input:focus{outline:none;border-color:#00b4aa}
|
||||
.ausboss-res-sec { flex: none; background: #141515; border: 1px solid #252727;
|
||||
border-radius: 8px; padding: 6px 8px 8px; }
|
||||
.ausboss-res-sechead { display: flex; align-items: baseline;
|
||||
@@ -517,6 +545,146 @@ function editWorkflowSizes(state) {
|
||||
dialog.showModal();
|
||||
}
|
||||
|
||||
// The gear's "Ratio chips" list: every saved ratio with a switch, a delete
|
||||
// button, an add box and a way back to the shipped list. One list for every
|
||||
// Latent Size node in this browser, like the gear's other display options.
|
||||
function editRatioRail(state) {
|
||||
closeSettingsMenu();
|
||||
let entries = railEntries(state.settings?.rail);
|
||||
const dialog = el("dialog", "ausboss-size-dialog");
|
||||
dialog.setAttribute("aria-label", "Ratio chips");
|
||||
const heading = el("label", "", "Ratio chips");
|
||||
const hint = el("p", "", "Ticked ratios show as chips on every Latent Size node. "
|
||||
+ "The flip button on the node turns any of them portrait.");
|
||||
const list = el("ul", "ausboss-rail-list");
|
||||
const addRow = el("div", "ausboss-rail-add");
|
||||
const input = el("input");
|
||||
input.type = "text";
|
||||
input.placeholder = "Add a ratio, like 21:9";
|
||||
input.setAttribute("aria-label", "New ratio");
|
||||
const add = compactAction("Add");
|
||||
addRow.append(input, add);
|
||||
const error = el("div");
|
||||
error.setAttribute("role", "alert");
|
||||
|
||||
const render = () => {
|
||||
list.textContent = "";
|
||||
const snap = currentSnap(state);
|
||||
for (const entry of entries) {
|
||||
const row = el("li", `ausboss-rail-row${entry.on ? "" : " off"}`);
|
||||
const check = el("input");
|
||||
check.type = "checkbox";
|
||||
check.checked = entry.on;
|
||||
check.setAttribute("aria-label", `Show ${entry.label}`);
|
||||
const box = el("span", "box");
|
||||
const glyph = el("span");
|
||||
const fitted = fitRectInBox(entry.x, entry.y, 22, 14);
|
||||
glyph.style.width = `${fitted.w.toFixed(1)}px`;
|
||||
glyph.style.height = `${fitted.h.toFixed(1)}px`;
|
||||
box.append(glyph);
|
||||
const size = defaultSizeForRatio(entry, snap);
|
||||
const del = el("button", "ausboss-rail-del", "×");
|
||||
del.type = "button";
|
||||
del.title = `Remove ${entry.label}`;
|
||||
del.setAttribute("aria-label", `Remove ${entry.label}`);
|
||||
const toggle = () => {
|
||||
entry.on = !entry.on;
|
||||
error.textContent = "";
|
||||
render();
|
||||
};
|
||||
check.addEventListener("click", (event) => { event.stopPropagation(); toggle(); });
|
||||
row.addEventListener("click", (event) => { if (event.target !== del) toggle(); });
|
||||
del.addEventListener("click", (event) => {
|
||||
event.stopPropagation();
|
||||
entries = entries.filter(other => other !== entry);
|
||||
error.textContent = "";
|
||||
render();
|
||||
});
|
||||
row.append(check, box, el("span", "name", entry.label),
|
||||
el("span", "size", `${size.width} × ${size.height}`), del);
|
||||
list.append(row);
|
||||
}
|
||||
add.disabled = entries.length >= RAIL_MAX;
|
||||
};
|
||||
|
||||
const addTyped = () => {
|
||||
const ratio = parseRatioToken(input.value);
|
||||
if (!ratio) {
|
||||
error.textContent = "Type a ratio as two whole numbers, like 21:9 or 5:4.";
|
||||
input.focus();
|
||||
return;
|
||||
}
|
||||
const existing = entries.find(entry => ratioKey(entry) === ratioKey(ratio));
|
||||
if (existing) {
|
||||
existing.on = true;
|
||||
error.textContent = `${existing.label} is already in the list, so it is switched on.`;
|
||||
} else if (entries.length >= RAIL_MAX) {
|
||||
error.textContent = `The list holds up to ${RAIL_MAX} ratios. Remove one first.`;
|
||||
return;
|
||||
} else {
|
||||
entries.push({ ...ratio, on: true });
|
||||
error.textContent = "";
|
||||
}
|
||||
input.value = "";
|
||||
render();
|
||||
list.lastElementChild?.scrollIntoView?.({ block: "nearest" });
|
||||
input.focus();
|
||||
};
|
||||
add.onclick = addTyped;
|
||||
input.addEventListener("keydown", (event) => {
|
||||
keepKeyInField(event);
|
||||
if (event.key !== "Enter") return;
|
||||
event.preventDefault();
|
||||
addTyped();
|
||||
});
|
||||
|
||||
const footer = el("footer");
|
||||
const reset = compactAction("Reset to defaults");
|
||||
reset.classList.add("grow");
|
||||
reset.title = "Back to the shipped list: six chips on, 5:4 and 21:9 off";
|
||||
reset.onclick = () => {
|
||||
entries = railEntries(DEFAULT_RAIL);
|
||||
error.textContent = "";
|
||||
render();
|
||||
};
|
||||
const cancel = compactAction("Cancel");
|
||||
const save = compactAction("Save");
|
||||
cancel.onclick = () => dialog.close();
|
||||
save.onclick = () => {
|
||||
if (!entries.some(entry => entry.on)) {
|
||||
error.textContent = "Keep at least one ratio switched on.";
|
||||
return;
|
||||
}
|
||||
const rail = railText(entries);
|
||||
saveSetting(SETTINGS_SCOPE, SETTINGS_SCHEMA, "rail", rail);
|
||||
for (const other of latentSizeStates()) {
|
||||
other.settings = { ...other.settings, rail };
|
||||
buildPanel(other);
|
||||
fitNode(other);
|
||||
}
|
||||
dialog.close();
|
||||
};
|
||||
footer.append(reset, cancel, save);
|
||||
dialog.append(heading, hint, list, addRow, error, footer);
|
||||
document.body.append(dialog);
|
||||
dialog.addEventListener("close", () => dialog.remove(), { once: true });
|
||||
render();
|
||||
dialog.showModal();
|
||||
}
|
||||
|
||||
// Every live Latent Size panel, in the open graph and the one on screen
|
||||
// (a subgraph), so a changed chip list shows everywhere at once.
|
||||
function latentSizeStates() {
|
||||
const states = new Set();
|
||||
for (const graph of [app.graph, app.canvas?.graph]) {
|
||||
for (const node of graph?.nodes ?? graph?._nodes ?? []) {
|
||||
const state = node?.__ausbossResolution;
|
||||
if (state && !state.disposed) states.add(state);
|
||||
}
|
||||
}
|
||||
return states;
|
||||
}
|
||||
|
||||
function repaint(state) {
|
||||
const { width, height } = getSize(state);
|
||||
const snap = currentSnap(state);
|
||||
@@ -525,7 +693,7 @@ function repaint(state) {
|
||||
|
||||
state.dimLabel.textContent = `${width} × ${height}`;
|
||||
state.subMp.textContent = `${megapixels(width, height).toFixed(2)} MP`;
|
||||
state.subRatio.textContent = state.strict ? `${ratio.x}:${ratio.y}` : ratioLabel(width, height);
|
||||
state.subRatio.textContent = state.strict ? `${ratio.x}:${ratio.y}` : railRatioLabel(width, height, state.railRatios);
|
||||
state.offGridDot.style.display = !state.strict && offGrid(width, height, snap) ? "" : "none";
|
||||
state.dots.style.display = state.settings?.show_grid === false ? "none" : "";
|
||||
|
||||
@@ -606,7 +774,7 @@ function repaint(state) {
|
||||
state.quickHint.textContent = state.policyError ? "Invalid list · edit in settings"
|
||||
: linked && state.strict ? "Linked size checked at run"
|
||||
: state.strict ? `Allowed · ${ratio.x}:${ratio.y}` : picks ? "Workflow recommendations"
|
||||
: onRail ? `for ${ratioLabel(width, height)} · /${snap}` : `custom · /${snap}`;
|
||||
: onRail ? `for ${railRatioLabel(width, height, state.railRatios)} · /${snap}` : `custom · /${snap}`;
|
||||
}
|
||||
state.quickButtons.forEach(({ button, size }) => {
|
||||
button.disabled = linked;
|
||||
@@ -901,6 +1069,10 @@ function buildPanel(state) {
|
||||
key: "workflow_sizes", type: "action", label: "Workflow resolutions", button: "Edit list",
|
||||
onAction: () => editWorkflowSizes(state),
|
||||
}, ...SETTINGS_SCHEMA.filter(e => !state.strict || !["default_snap", "chips_keep_budget", "rail"].includes(e.key)).map((entry) => {
|
||||
if (entry.key === "rail") {
|
||||
return { key: "rail_list", type: "action", label: entry.label, hint: entry.hint,
|
||||
button: "Edit list", onAction: () => editRatioRail(state) };
|
||||
}
|
||||
const input = entry.key === "latent" ? "latent" : entry.key === "batch" ? "batch_size" : null;
|
||||
return input && axisLinked(state, input) ? { section: `${entry.label} is linked` } : entry;
|
||||
})],
|
||||
@@ -912,7 +1084,10 @@ function buildPanel(state) {
|
||||
batch: Number(state.batchWidget?.value ?? 1),
|
||||
},
|
||||
onChange: (values, key) => {
|
||||
state.settings = values;
|
||||
// The menu's values lack the rail (its row is the list editor), so
|
||||
// keep the stored one; after a Reset that is the shipped list.
|
||||
state.settings = { ...loadSettings(SETTINGS_SCOPE, SETTINGS_SCHEMA), ...values };
|
||||
delete state.settings.rail_list;
|
||||
if (key === "latent" && state.latentWidget) {
|
||||
state.latentWidget.value = values.latent;
|
||||
state.latentWidget.callback?.(values.latent);
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
// Film Grain's Auto, on the node's face: what Auto picks for the picture on
|
||||
// hand, shown beside the Amount and Size boxes ("= 0.27", "= 1.0 px").
|
||||
//
|
||||
// The picture is read from its Load Image through ComfyUI's /view route and
|
||||
// its fine noise measured here, with the same measure the node uses
|
||||
// (js/shared/live_grain.mjs). A picture that only exists after a run (a VAE
|
||||
// Decode) is known from the node's last run, which sends Auto's picks with
|
||||
// its result. Until either, the card shows a plain dash.
|
||||
//
|
||||
// With a picture on grain_from, Auto copies that picture's grain instead.
|
||||
// The match is worked out by the node when it runs, and sent with its result
|
||||
// (node.__ausbossMatch = { amount, size, color }); the card's notes and the
|
||||
// live preview use it from then on. The node keeps its last few matches,
|
||||
// one per pair of pictures, in its saved properties: ComfyUI does not run a
|
||||
// node again for pictures it already ran, so a run that comes from its
|
||||
// cache sends no match, and a reopened workflow would otherwise wait for one.
|
||||
import { autoGrain, measureNoise } from "./live_grain.mjs";
|
||||
import { loadPixels, pixelsToImage, planInput } from "./live_sources.mjs";
|
||||
|
||||
// Is a picture wired into grain_from?
|
||||
export const grainFromLinked = (node) => node?.inputs?.some((input) => input?.name === "grain_from" && input.link != null) === true;
|
||||
|
||||
// Does Auto copy grain from a picture right now?
|
||||
export const copiesGrain = (node) => Boolean(node?.widgets?.find((widget) => widget?.name === "auto")?.value) && grainFromLinked(node);
|
||||
|
||||
// The match from the node's last run, or null.
|
||||
export function matchFromRun(record) {
|
||||
const sent = record?.ausboss_grain_match?.[0];
|
||||
return sent && ["base_amount", "base_size", "base_color"].every((key) => Number.isFinite(sent[key]))
|
||||
? { amount: sent.base_amount, size: sent.base_size, color: sent.base_color }
|
||||
: null;
|
||||
}
|
||||
|
||||
// Which pair of pictures a match belongs to: the picture and grain_from's
|
||||
// source (a Load Image's file, or the link a run reads).
|
||||
export const matchKey = (node) => ["image", "grain_from"].map((name) => planInput(node, name).key ?? "-").join("|");
|
||||
|
||||
const KEPT_MATCHES = 8;
|
||||
const validMatch = (match) => match && ["amount", "size", "color"].every((key) => Number.isFinite(match[key])) ? match : null;
|
||||
|
||||
// Remember a run's match for the pictures wired now.
|
||||
export function keepMatch(node, match) {
|
||||
if (!node || !validMatch(match)) return;
|
||||
node.properties ??= {};
|
||||
const kept = { ...(node.properties.ausboss_grain_matches ?? {}) };
|
||||
const key = matchKey(node);
|
||||
delete kept[key];
|
||||
kept[key] = { amount: match.amount, size: match.size, color: match.color };
|
||||
const keys = Object.keys(kept);
|
||||
for (const old of keys.slice(0, Math.max(0, keys.length - KEPT_MATCHES))) delete kept[old];
|
||||
node.properties.ausboss_grain_matches = kept;
|
||||
}
|
||||
|
||||
// The kept match for the pictures wired now, or null.
|
||||
export const keptMatch = (node) => validMatch(node?.properties?.ausboss_grain_matches?.[matchKey(node)]) ?? null;
|
||||
|
||||
export function setMatch(node, match) {
|
||||
const before = node.__ausbossMatch;
|
||||
if (before?.amount === match?.amount && before?.size === match?.size && before?.color === match?.color) return;
|
||||
node.__ausbossMatch = match ?? null;
|
||||
node.__ausbossCard?.refresh?.();
|
||||
node.__ausbossLive?.hooks?.refresh?.();
|
||||
node.setDirtyCanvas?.(true, true);
|
||||
}
|
||||
|
||||
// Auto's picks for the node (node.__ausbossAuto = { amount, size }: the
|
||||
// numbers before the card's multipliers), or null while they are not known.
|
||||
export function setAuto(node, picks) {
|
||||
const before = node.__ausbossAuto;
|
||||
const next = picks && Number.isFinite(picks.amount) && Number.isFinite(picks.size) ? { amount: picks.amount, size: picks.size } : null;
|
||||
if (before?.amount === next?.amount && before?.size === next?.size) return;
|
||||
node.__ausbossAuto = next;
|
||||
node.__ausbossCard?.refresh?.();
|
||||
node.setDirtyCanvas?.(true, true);
|
||||
}
|
||||
|
||||
// From a picture already read (the live stage has it).
|
||||
export function autoFromImage(node, image) {
|
||||
const noise = measureNoise(image);
|
||||
const picks = autoGrain(image.h, image.w, noise);
|
||||
setAuto(node, picks);
|
||||
return picks;
|
||||
}
|
||||
|
||||
// From what the node's last run sent.
|
||||
export function autoFromRun(record) {
|
||||
const sent = record?.ausboss_grain_auto?.[0];
|
||||
return sent && Number.isFinite(sent.base_amount) && Number.isFinite(sent.base_size) ? { amount: sent.base_amount, size: sent.base_size } : null;
|
||||
}
|
||||
|
||||
// Work out Auto's picks for a node now. `viewUrl(query)` turns a /view query
|
||||
// into a URL; `record` is the node's last output record, if any.
|
||||
export async function refreshAuto(node, { viewUrl, record = null }) {
|
||||
if (!node || typeof viewUrl !== "function") return;
|
||||
// The match kept for these two pictures; other pictures wait for a run.
|
||||
setMatch(node, grainFromLinked(node) ? keptMatch(node) : null);
|
||||
const plan = planInput(node, "image");
|
||||
if (plan.state === "direct") {
|
||||
try {
|
||||
const image = pixelsToImage(await loadPixels(viewUrl(plan.query)), 3);
|
||||
// The wiring or the file changed while the picture was being read.
|
||||
if (planInput(node, "image").key !== plan.key) return;
|
||||
autoFromImage(node, image);
|
||||
return;
|
||||
} catch {
|
||||
// A browser that hides picture pixels: fall back to the last run's numbers.
|
||||
}
|
||||
}
|
||||
setAuto(node, plan.state === "none" ? null : autoFromRun(record));
|
||||
}
|
||||
+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(" ");
|
||||
}
|
||||
+62
-2
@@ -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": "画布",
|
||||
@@ -29,7 +30,7 @@ export const ZH = {
|
||||
"Empty fill": "空白填充", "Max zoom": "最大缩放", "Every nth": "每隔几帧", "Offset": "偏移", "Split after": "在此之后拆分",
|
||||
"Mismatch": "尺寸不一致", "Value": "数值", "Split at": "拆分方式", "Numbering": "编号", "Limit": "数量上限",
|
||||
"Length": "长度", "Camera": "镜头", "Look": "风格", "Song starts at": "歌曲起点", "Moments on the beat": "时刻对齐节拍",
|
||||
"Language": "语言", "Clip's own sound": "素材自带声音", "Sound": "声音", "Music": "音乐", "Frame": "帧",
|
||||
"Language": "语言", "Clip's own sound": "素材自带声音", "Tidy up my lines": "整理我的台词", "Sound": "声音", "Music": "音乐", "Frame": "帧",
|
||||
"KV cache": "KV 缓存", "VLM reference": "VLM 参考", "Source": "素材", "Width": "宽度", "Height": "高度",
|
||||
"Longest side": "最长边", "Ratio": "比例", "Keep": "保留", "Round to": "取整到", "Enlarge": "放大小图",
|
||||
"Backdrop": "背景虚化", "Exact padding": "精确扩边", "Left": "左", "Top": "上", "Right": "右", "Bottom": "下",
|
||||
@@ -148,6 +149,7 @@ export const ZH = {
|
||||
"Start the clip at the frame on the stage. The Duration stays.": "让片段从舞台上当前这一帧开始,时长不变。",
|
||||
"How long the clip is. Counted in clip frames at the output rate.": "片段有多长,按输出帧率的片段帧数计算。",
|
||||
"How long the sound is. Clear it, or type 0, to run to the end of the file.": "声音有多长。清空或输入 0 表示播到文件末尾。",
|
||||
"Clean up": "清理", "For a voice recording. On cuts the quiet bits at the start and end, takes out hum and hiss, and evens out the volume. Off hands on the sound as it is.": "用于人声录音。开启后会剪掉开头和结尾的安静部分,去掉嗡嗡声和嘶嘶声,并让音量保持均匀。关闭则按原样输出声音。",
|
||||
"Where the sound starts in the file, of 0:00.": "声音在文件中的起点,从 0:00 起算。", "Where the sound stops in the file. Typing it changes the Duration.": "声音在文件中的终点。输入它会改变时长。",
|
||||
"Keep a frame count the video model takes: LTX wants 8n+1 (49, 97, 121), Wan 4n+1. The Duration steps to those counts. Any keeps every frame.": "保留视频模型能接受的帧数:LTX 需要 8n+1(49、97、121),Wan 需要 4n+1。时长会按这些帧数步进。选“任意”则保留每一帧。",
|
||||
"Keep one frame in this many. Output fps is adjusted to keep real-time playback; the Duration counts the frames kept.": "每隔这么多帧保留一帧。输出帧率会随之调整以保持实时播放;时长按保留的帧数计算。",
|
||||
@@ -177,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.": "“逐行”让每个开关各占一行,各自有关 | 开。“单选”把这些开关合成一个选项条,始终选中其中一个。",
|
||||
@@ -214,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": "提示词、字幕或共用文字",
|
||||
@@ -306,6 +310,8 @@ export const ZH = {
|
||||
"Unlink strength": "断开强度连线", "link": "连线",
|
||||
"Takes 1 off after each run. Tap for Random.": "每次运行后减 1。点一下改为随机。",
|
||||
"The words come from the wire.": "文字来自连线。",
|
||||
"from a link": "来自连线",
|
||||
"Set by a link into this input. Remove the link to type a value here.": "由连到这个输入的连线设置。断开连线后可在此输入数值。",
|
||||
"Tick to add with others": "勾选后与其他一起添加",
|
||||
"Toggle this trigger word into the row's output": "把这个触发词加入或移出该行的输出",
|
||||
"Trigger word separator": "触发词分隔符",
|
||||
@@ -324,6 +330,58 @@ export const ZH = {
|
||||
"Your own ratios from ausboss_presets.json. Picking one works like a ratio button.": "来自 ausboss_presets.json 的自定义比例。选中它的效果和点比例按钮一样。",
|
||||
"Choose or upload an image": "选择或上传图片",
|
||||
"Preview could not load this image": "预览无法加载这张图片",
|
||||
"The strength at the top of the curve box. 1 is full strength.": "曲线框顶部对应的强度。1 为满强度。",
|
||||
"The strength at the bottom of the curve box. 0 is off.": "曲线框底部对应的强度。0 为关闭。",
|
||||
"flat": "平直", "fade out": "渐弱", "fade in": "渐强", "ease out": "缓出", "ease in": "缓入",
|
||||
"The same strength all the way": "全程同一强度",
|
||||
"Full at the start, gone at the end": "开头满强度,结尾消失",
|
||||
"Off at the start, full at the end": "开头关闭,结尾满强度",
|
||||
"Holds, fades out smoothly through the middle, then stays low": "先保持,中段平滑减弱,之后保持低位",
|
||||
"Stays low, comes in smoothly through the middle, then holds": "先保持低位,中段平滑增强,之后保持",
|
||||
"Point at": "点位置", "value": "数值", "start": "开始", "end": "结束",
|
||||
"Drag a point. Double-click adds one, right-click removes it.": "拖动点。双击添加点,右键删除点。",
|
||||
"Where the picked point sits in the run, from the start (0%) to the end (100%).": "选中的点在运行中的位置,从开始(0%)到结束(100%)。",
|
||||
"The strength at the picked point.": "选中点的强度。",
|
||||
"This LoRA follows the strength curve. Click to keep it steady.": "这个 LoRA 跟随强度曲线。点击改为固定强度。",
|
||||
"This LoRA keeps one strength. Click to make it follow the strength curve.": "这个 LoRA 保持同一强度。点击让它跟随强度曲线。",
|
||||
"Follow the strength curve": "跟随强度曲线", "Keep a steady strength": "保持固定强度",
|
||||
// ---- image finishing nodes
|
||||
"Auto": "自动", "1 \u00d7 = Auto's pick": "1 \u00d7 = 自动的选择", "1 \u00d7 = the match": "1 \u00d7 = 匹配结果", "match": "匹配",
|
||||
"Amount": "颗粒量", "Roughness": "粗糙度", "Video grain": "视频颗粒", "moving": "逐帧变化",
|
||||
"Clean edges": "清理边缘", "Clear haze": "清除薄雾", "Solid above": "高于此值为实", "Smooth video": "视频平滑",
|
||||
"white part": "白色部分", "black part": "黑色部分",
|
||||
"Detail size": "细节大小", "Detail": "细节", "color + light": "颜色 + 明暗", "light only": "仅明暗", "Edge safe": "保护边缘",
|
||||
// ---- Check layout
|
||||
"Check layout": "检查布局",
|
||||
"Check again": "再检查一次",
|
||||
"Look at the workflow again after a change": "改动之后再检查一遍工作流",
|
||||
"Click an entry to jump to it. Nothing is moved.": "点击一项即可跳转过去。不会移动任何东西。",
|
||||
"Nothing to fix": "没有要改的",
|
||||
"Nothing to fix.": "没有要改的。",
|
||||
"No overlaps, no hidden or backwards wires, and every node sits in a group.": "没有重叠,没有被挡住或反向的连线,每个节点都在分组里。",
|
||||
"1 thing to look at": "1 处需要看一下",
|
||||
"Overlapping": "重叠",
|
||||
"Groups overlapping": "分组重叠",
|
||||
"Under a node that grows": "在会变高的节点下面",
|
||||
"Wire behind a node": "连线被节点挡住",
|
||||
"Wire runs backwards": "连线反向",
|
||||
"Outside every group": "不在任何分组里",
|
||||
"Zoomed out too far": "缩得太小",
|
||||
"No Workflow Note": "没有工作流说明",
|
||||
"Title bars count too": "标题栏也算在内",
|
||||
"One group crosses the other": "一个分组压到了另一个分组",
|
||||
"Under:": "位于其下:",
|
||||
"Behind:": "挡住它的:",
|
||||
"Ends left of where it starts": "终点在起点左边",
|
||||
"Move it into a group": "把它移进一个分组",
|
||||
"Nothing here is in a group": "这里没有东西在分组里",
|
||||
"Put each step in a numbered group": "把每一步放进带编号的分组",
|
||||
"Saved zoom:": "保存的缩放:",
|
||||
"Below 0.60 the text on nodes stops drawing": "低于 0.60 时节点上的文字不再显示",
|
||||
"The Workflow Note has no title or steps": "工作流说明没有标题或步骤",
|
||||
"Add a Workflow Note": "添加一个工作流说明",
|
||||
"It tells people what the workflow does and how to run it": "它告诉大家这个工作流做什么、怎么运行",
|
||||
"Inside:": "位于:",
|
||||
};
|
||||
|
||||
// Strings that deliberately stay English on a Chinese face: names, symbols
|
||||
@@ -347,4 +405,6 @@ export const PATTERNS = [
|
||||
[/^Source · feather (\d+) px · Fill (#[0-9a-fA-F]{6})$/, (m, f, c) => `素材 · 羽化 ${f} px · 填充 ${c}`],
|
||||
[/^Source · Fill (#[0-9a-fA-F]{6})$/, (m, c) => `素材 · 填充 ${c}`],
|
||||
[/^(\d+):(\d+): reshape to this ratio\. The flip button on the left sets the orientation\.$/, (m, a, b) => `${a}:${b}:重塑为此比例。左侧的翻转按钮用来切换横竖方向。`],
|
||||
[/^(\d+) things to look at$/, (m, n) => `${n} 处需要看一下`],
|
||||
[/^(\d+) wires$/, (m, n) => `${n} 条连线`],
|
||||
];
|
||||
|
||||
+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.28.1";
|
||||
export const AUSBOSS_JS_VERSION = "2.30.0";
|
||||
|
||||
export const BRAND = "#00b4aa"; // AusBoss teal — keep node accents consistent.
|
||||
export const BRAND_DARK = "#007f78";
|
||||
|
||||
@@ -0,0 +1,252 @@
|
||||
// Check layout 🆎: what makes a workflow hard to read, worked out from plain
|
||||
// numbers. No DOM and no ComfyUI imports, so node:test runs it
|
||||
// (tests/layout_check_math.test.mjs); js/layout_check/ reads the canvas
|
||||
// into this shape, shows the list and jumps to an entry. Nothing here moves
|
||||
// anything.
|
||||
//
|
||||
// The graph, in canvas units:
|
||||
// nodes: [{ id, title, x, y, w, h, grows, kind }] x, y is the top left of
|
||||
// the body; the title bar sits above it, titleHeight tall. grows:
|
||||
// the node gets taller when it shows a run's picture or text.
|
||||
// kind: "note" for a Workflow Note, "callout" for a Callout.
|
||||
// groups: [{ id, title, x, y, w, h }]
|
||||
// links: [{ id, from, to, points: [[x, y], ...] }] the output socket, any
|
||||
// reroutes on the way, then the input socket.
|
||||
// scale: the zoom the workflow is saved at (top level only).
|
||||
// noteFilled: for a top-level graph, whether a Workflow Note has a title
|
||||
// and instructions (null when there is no note).
|
||||
|
||||
export const TITLE_HEIGHT = 30;
|
||||
// Below this saved zoom ComfyUI stops drawing widget text
|
||||
// (scripts/workflow_contract.py holds the same number).
|
||||
export const MIN_ZOOM = 0.6;
|
||||
// How much taller a node that shows a picture can get after a run. A node
|
||||
// starting closer than this under it can end up covered.
|
||||
export const GROW_ROOM = 300;
|
||||
// A wire runs backwards when it ends further left than the node it starts
|
||||
// from, by more than this. A wire from a node down to the next one in its
|
||||
// column ends at the same left edge, which reads fine.
|
||||
export const BACKWARD_SLACK = 10;
|
||||
// The order the list shows its kinds in: what hides something first.
|
||||
export const KINDS = [
|
||||
"overlap",
|
||||
"group-overlap",
|
||||
"under-grower",
|
||||
"hidden-wire",
|
||||
"backward-wire",
|
||||
"outside-group",
|
||||
"no-groups",
|
||||
"zoom",
|
||||
"no-note",
|
||||
];
|
||||
|
||||
const finite = (value, fallback = 0) => (Number.isFinite(Number(value)) ? Number(value) : fallback);
|
||||
|
||||
// [left, top, right, bottom] of a node with its title bar.
|
||||
// A node drawn without a title bar (a Callout tile) gives its own
|
||||
// `titleHeight` of 0.
|
||||
export function nodeBox(node, titleHeight = TITLE_HEIGHT) {
|
||||
const x = finite(node?.x);
|
||||
const y = finite(node?.y);
|
||||
const top = Number.isFinite(node?.titleHeight) ? node.titleHeight : titleHeight;
|
||||
return [x, y - top, x + Math.max(0, finite(node?.w)), y + Math.max(0, finite(node?.h))];
|
||||
}
|
||||
|
||||
export function groupBox(group) {
|
||||
const x = finite(group?.x);
|
||||
const y = finite(group?.y);
|
||||
return [x, y, x + Math.max(0, finite(group?.w)), y + Math.max(0, finite(group?.h))];
|
||||
}
|
||||
|
||||
// Two boxes share more than `slack` units both ways.
|
||||
export function boxesOverlap(a, b, slack = 1) {
|
||||
return Math.min(a[2], b[2]) > Math.max(a[0], b[0]) + slack && Math.min(a[3], b[3]) > Math.max(a[1], b[1]) + slack;
|
||||
}
|
||||
|
||||
// `inner` sits wholly inside `outer`, give or take `slack`.
|
||||
export function boxInside(inner, outer, slack = 1) {
|
||||
return inner[0] >= outer[0] - slack && inner[1] >= outer[1] - slack && inner[2] <= outer[2] + slack && inner[3] <= outer[3] + slack;
|
||||
}
|
||||
|
||||
export function unionBox(boxes) {
|
||||
const list = boxes.filter(Boolean);
|
||||
if (!list.length) return null;
|
||||
return [
|
||||
Math.min(...list.map((box) => box[0])),
|
||||
Math.min(...list.map((box) => box[1])),
|
||||
Math.max(...list.map((box) => box[2])),
|
||||
Math.max(...list.map((box) => box[3])),
|
||||
];
|
||||
}
|
||||
|
||||
// Points along a wire, the way the canvas draws one: from each point to the
|
||||
// next a curve that leaves to the right and arrives from the left, its
|
||||
// handles a quarter of the distance long. `mode` "straight" or "linear"
|
||||
// draws straight pieces instead.
|
||||
export function wirePoints(points, mode = "spline", per = 24) {
|
||||
const list = (Array.isArray(points) ? points : []).filter((p) => Array.isArray(p) && p.length >= 2).map((p) => [finite(p[0]), finite(p[1])]);
|
||||
if (list.length < 2) return list;
|
||||
const out = [list[0]];
|
||||
for (let i = 1; i < list.length; i++) {
|
||||
const [ax, ay] = list[i - 1];
|
||||
const [bx, by] = list[i];
|
||||
const reach = mode === "spline" ? Math.hypot(bx - ax, by - ay) * 0.25 : 0;
|
||||
const c1 = [ax + reach, ay];
|
||||
const c2 = [bx - reach, by];
|
||||
for (let s = 1; s <= per; s++) {
|
||||
const t = s / per;
|
||||
const u = 1 - t;
|
||||
out.push([
|
||||
u * u * u * ax + 3 * u * u * t * c1[0] + 3 * u * t * t * c2[0] + t * t * t * bx,
|
||||
u * u * u * ay + 3 * u * u * t * c1[1] + 3 * u * t * t * c2[1] + t * t * t * by,
|
||||
]);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
const inBox = (point, box, inset = 2) => point[0] > box[0] + inset && point[0] < box[2] - inset && point[1] > box[1] + inset && point[1] < box[3] - inset;
|
||||
|
||||
// A Callout standing in a Workflow Note's own column belongs to the note,
|
||||
// the way scripts/workflow_contract.py reads it.
|
||||
function besideNote(node, notes) {
|
||||
if (node.kind !== "callout") return false;
|
||||
const left = finite(node.x);
|
||||
const right = left + finite(node.w);
|
||||
return notes.some((note) => note.x <= left && right <= note.x + note.w + 1);
|
||||
}
|
||||
|
||||
export function checkLayout(graph, options = {}) {
|
||||
const titleHeight = finite(options.titleHeight, TITLE_HEIGHT);
|
||||
const growRoom = finite(options.growRoom, GROW_ROOM);
|
||||
const nodes = (graph?.nodes ?? []).filter((node) => node && node.id !== undefined && node.id !== null);
|
||||
const groups = graph?.groups ?? [];
|
||||
const links = graph?.links ?? [];
|
||||
const box = new Map(nodes.map((node) => [node.id, nodeBox(node, titleHeight)]));
|
||||
const issues = [];
|
||||
const add = (kind, fields) => issues.push({ kind, nodes: [], groups: [], ...fields });
|
||||
|
||||
const overlapping = new Set();
|
||||
for (let i = 0; i < nodes.length; i++) {
|
||||
for (let j = i + 1; j < nodes.length; j++) {
|
||||
const a = nodes[i];
|
||||
const b = nodes[j];
|
||||
if (!boxesOverlap(box.get(a.id), box.get(b.id))) continue;
|
||||
overlapping.add(`${a.id}|${b.id}`).add(`${b.id}|${a.id}`);
|
||||
add("overlap", { nodes: [a.id, b.id], focus: unionBox([box.get(a.id), box.get(b.id)]) });
|
||||
}
|
||||
}
|
||||
|
||||
for (let i = 0; i < groups.length; i++) {
|
||||
for (let j = i + 1; j < groups.length; j++) {
|
||||
const a = groupBox(groups[i]);
|
||||
const b = groupBox(groups[j]);
|
||||
// A group wholly inside another is a nested group, which is fine.
|
||||
if (!boxesOverlap(a, b) || boxInside(a, b) || boxInside(b, a)) continue;
|
||||
add("group-overlap", { groups: [groups[i].id, groups[j].id], focus: unionBox([a, b]) });
|
||||
}
|
||||
}
|
||||
|
||||
for (const grower of nodes.filter((node) => node.grows)) {
|
||||
const top = box.get(grower.id);
|
||||
for (const node of nodes) {
|
||||
if (node === grower || overlapping.has(`${grower.id}|${node.id}`)) continue;
|
||||
const below = box.get(node.id);
|
||||
const sideways = Math.min(top[2], below[2]) - Math.max(top[0], below[0]);
|
||||
const gap = below[1] - top[3];
|
||||
if (sideways > 1 && gap >= -1 && gap < growRoom) {
|
||||
add("under-grower", { nodes: [node.id, grower.id], gap: Math.max(0, Math.round(gap)), focus: unionBox([top, below]) });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Two wires between the same two nodes (a model and a clip, say) are one
|
||||
// entry that counts them.
|
||||
const wireIssues = new Map();
|
||||
const addWire = (kind, key, fields) => {
|
||||
const seen = wireIssues.get(`${kind}|${key}`);
|
||||
if (seen) {
|
||||
seen.wires += 1;
|
||||
seen.links.push(fields.link);
|
||||
return;
|
||||
}
|
||||
const issue = { kind, nodes: [], groups: [], wires: 1, links: [fields.link], ...fields };
|
||||
wireIssues.set(`${kind}|${key}`, issue);
|
||||
issues.push(issue);
|
||||
};
|
||||
const mode = graph?.linkMode ?? "spline";
|
||||
for (const link of links) {
|
||||
const points = wirePoints(link.points, mode);
|
||||
if (points.length < 2) continue;
|
||||
const behind = nodes.filter((node) => node.id !== link.from && node.id !== link.to && points.some((p) => inBox(p, box.get(node.id))));
|
||||
if (behind.length) {
|
||||
addWire("hidden-wire", `${link.from}|${link.to}|${behind.map((node) => node.id).join(",")}`, {
|
||||
link: link.id,
|
||||
nodes: [link.from, link.to, ...behind.map((node) => node.id)],
|
||||
behind: behind.map((node) => node.id),
|
||||
focus: unionBox([...behind.map((node) => box.get(node.id)), unionBox(points.map((p) => [p[0], p[1], p[0], p[1]]))]),
|
||||
});
|
||||
}
|
||||
const corners = link.points.map((p) => [finite(p[0]), finite(p[1])]);
|
||||
const start = box.get(link.from)?.[0] ?? corners[0][0];
|
||||
if (corners.some((p, i) => i > 0 && p[0] < start - BACKWARD_SLACK)) {
|
||||
addWire("backward-wire", `${link.from}|${link.to}`, {
|
||||
link: link.id,
|
||||
nodes: [link.from, link.to],
|
||||
focus: unionBox([box.get(link.from), box.get(link.to)].concat(corners.map((p) => [p[0], p[1], p[0], p[1]]))),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const notes = nodes.filter((node) => node.kind === "note");
|
||||
if (nodes.length && !groups.length) {
|
||||
add("no-groups", { focus: unionBox([...box.values()]) });
|
||||
} else if (groups.length) {
|
||||
const boxes = groups.map(groupBox);
|
||||
for (const node of nodes) {
|
||||
if (node.kind === "note" || besideNote(node, notes)) continue;
|
||||
if (boxes.some((group) => boxInside(box.get(node.id), group))) continue;
|
||||
add("outside-group", { nodes: [node.id], focus: box.get(node.id) });
|
||||
}
|
||||
}
|
||||
|
||||
const scale = Number(graph?.scale);
|
||||
if (Number.isFinite(scale) && scale < MIN_ZOOM) add("zoom", { scale: Math.round(scale * 100) / 100 });
|
||||
if (graph?.topLevel && nodes.length && !graph.noteFilled) {
|
||||
add("no-note", notes.length ? { nodes: [notes[0].id], focus: box.get(notes[0].id), empty: true } : {});
|
||||
}
|
||||
|
||||
return issues.sort((a, b) => KINDS.indexOf(a.kind) - KINDS.indexOf(b.kind));
|
||||
}
|
||||
|
||||
// The issues of a graph and every subgraph inside it, each marked with the
|
||||
// path of box names that leads to it. `graphs` is [{ path: [...names],
|
||||
// graph }], the top level first.
|
||||
export function checkAll(graphs, options = {}) {
|
||||
const out = [];
|
||||
for (const { path = [], graph } of graphs ?? []) {
|
||||
for (const issue of checkLayout({ ...graph, topLevel: path.length === 0 && graph?.topLevel !== false }, options)) {
|
||||
out.push({ ...issue, path });
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// How many issues of each kind, in list order: [[kind, count], ...].
|
||||
export function countByKind(issues) {
|
||||
const counts = new Map();
|
||||
for (const issue of issues ?? []) counts.set(issue.kind, (counts.get(issue.kind) ?? 0) + 1);
|
||||
return KINDS.filter((kind) => counts.has(kind)).map((kind) => [kind, counts.get(kind)]);
|
||||
}
|
||||
|
||||
// The part of the canvas a jump frames its target in: everything left of the
|
||||
// Check layout panel, so what it names never lands under it. `view` and
|
||||
// `panel` are screen boxes ({ left, top, width, height }); the result is
|
||||
// [x, y, width, height] in the canvas's own pixels, or null for the whole
|
||||
// canvas (no panel, or too little room beside it).
|
||||
export function jumpViewport(view, panel, margin = 16, least = 320) {
|
||||
if (!(view?.width > 0) || !(view?.height > 0) || !panel) return null;
|
||||
const room = Math.min(view.width, panel.left - view.left - margin);
|
||||
if (!(room >= least)) return null;
|
||||
return [0, 0, room, view.height];
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
// Cut Out in the browser: the same maths as nodes/_cut_out_helpers.py, for the
|
||||
// live preview (js/shared/live_stage.mjs). The mask becomes the alpha in a
|
||||
// fixed order (white or black part, grow or shrink, feather, clear haze and
|
||||
// solid core), and where the alpha is in between the colours are cleaned of
|
||||
// the old background with the node's blur-fusion pass (clean_colours in
|
||||
// nodes/_fine_edge_helpers.py).
|
||||
import { areaResize, bilinearResize, boxBlur, gaussianBlur, makeImage, pyRound, slidingMax } from "./live_image.mjs";
|
||||
|
||||
export const SNAP = 1e-4;
|
||||
export const CLEAN_RADII = [90, 6];
|
||||
export const CLEAN_FOR = 1440;
|
||||
|
||||
// Grow (positive) or shrink (negative) a plane by whole pixels, soft values
|
||||
// kept: a square maximum, or minimum, of 2n + 1 pixels.
|
||||
export function growShrink(plane, w, h, pixels) {
|
||||
const steps = Math.abs(Math.trunc(pixels));
|
||||
if (steps === 0) return plane;
|
||||
const sign = pixels > 0 ? 1 : -1;
|
||||
let values = sign > 0 ? plane : Float32Array.from(plane, (v) => -v);
|
||||
values = slidingMax(slidingMax(values, w, h, steps, true), w, h, steps, false);
|
||||
return sign > 0 ? values : Float32Array.from(values, (v) => -v);
|
||||
}
|
||||
|
||||
// A Gaussian feather, 3 sigma wide, edges repeated.
|
||||
export function feather(plane, w, h, sigma) {
|
||||
if (!(sigma > 0)) return plane;
|
||||
const image = makeImage(w, h, 1, plane);
|
||||
return gaussianBlur(image, sigma, Math.max(1, Math.ceil(sigma * 3))).data;
|
||||
}
|
||||
|
||||
// The cut-out's alpha for one mask plane the picture's size: 1 where the
|
||||
// picture is kept.
|
||||
export function cutOutAlpha(mask, w, h, { keep = "white", grow = 0, feather: soft = 1, clearHaze = 0, solidAbove = 1 } = {}) {
|
||||
let alpha = Float32Array.from(mask, (v) => (v < 0 ? 0 : v > 1 ? 1 : v));
|
||||
if (keep === "black") alpha = Float32Array.from(alpha, (v) => 1 - v);
|
||||
alpha = growShrink(alpha, w, h, grow);
|
||||
alpha = feather(alpha, w, h, soft);
|
||||
if (clearHaze > 0 || solidAbove < 1) {
|
||||
const span = Math.max(solidAbove - clearHaze, 1e-6);
|
||||
alpha = Float32Array.from(alpha, (v) => Math.min(1, Math.max(0, (v - clearHaze) / span)));
|
||||
}
|
||||
return Float32Array.from(alpha, (v) => (v >= 1 - SNAP ? 1 : v <= SNAP ? 0 : Math.min(1, Math.max(0, v))));
|
||||
}
|
||||
|
||||
// The blur the colour clean-up uses: three box passes, on a smaller copy
|
||||
// when it reaches far.
|
||||
function blur(image, reach) {
|
||||
const step = Math.max(1, Math.floor(reach / 3));
|
||||
return boxBlur(boxBlur(boxBlur(image, step), step), step);
|
||||
}
|
||||
|
||||
function wideBlur(image, reach) {
|
||||
const shrink = Math.max(1, Math.floor(reach / 12));
|
||||
if (shrink === 1) return blur(image, reach);
|
||||
const small = areaResize(image, Math.max(1, Math.floor(image.h / shrink)), Math.max(1, Math.floor(image.w / shrink)));
|
||||
return bilinearResize(blur(small, Math.max(1, Math.floor(reach / shrink))), image.h, image.w);
|
||||
}
|
||||
|
||||
// How far the colour clean-up reaches for a picture whose long side is
|
||||
// `longSide`: the wide pass.
|
||||
export function cleanReach(longSide) {
|
||||
return Math.max(1, pyRound(CLEAN_RADII[0] * (longSide / CLEAN_FOR)));
|
||||
}
|
||||
|
||||
// The subject's own colour for every pixel of `rgb` (3 channels), given its
|
||||
// alpha plane. `longSide` is the long side of the whole picture, so a window
|
||||
// of a big picture reaches as far as the whole one would.
|
||||
export function cleanColours(rgb, alpha, longSide = Math.max(rgb.w, rgb.h)) {
|
||||
const { w, h } = rgb;
|
||||
const n = w * h;
|
||||
const image = makeImage(w, h, 3, Float32Array.from(rgb.data, (v) => (v < 0 ? 0 : v > 1 ? 1 : v)));
|
||||
const cover = makeImage(w, h, 1, Float32Array.from(alpha, (v) => (v < 0 ? 0 : v > 1 ? 1 : v)));
|
||||
const grow = longSide / CLEAN_FOR;
|
||||
let thing = image;
|
||||
let behind = image;
|
||||
for (const base of CLEAN_RADII) {
|
||||
const reach = Math.max(1, pyRound(base * grow));
|
||||
const weight = wideBlur(cover, reach);
|
||||
const byCover = makeImage(w, h, 3, new Float32Array(n * 3));
|
||||
const byRest = makeImage(w, h, 3, new Float32Array(n * 3));
|
||||
for (let i = 0; i < n; i += 1) {
|
||||
for (let k = 0; k < 3; k += 1) {
|
||||
byCover.data[i * 3 + k] = thing.data[i * 3 + k] * cover.data[i];
|
||||
byRest.data[i * 3 + k] = behind.data[i * 3 + k] * (1 - cover.data[i]);
|
||||
}
|
||||
}
|
||||
const blurThing = wideBlur(byCover, reach);
|
||||
const blurBehind = wideBlur(byRest, reach);
|
||||
const nextThing = new Float32Array(n * 3);
|
||||
const nextBehind = new Float32Array(n * 3);
|
||||
for (let i = 0; i < n; i += 1) {
|
||||
for (let k = 0; k < 3; k += 1) {
|
||||
const at = i * 3 + k;
|
||||
const nearThing = blurThing.data[at] / (weight.data[i] + 1e-5);
|
||||
const nearBehind = blurBehind.data[at] / (1 - weight.data[i] + 1e-5);
|
||||
const t = nearThing + cover.data[i] * (image.data[at] - cover.data[i] * nearThing - (1 - cover.data[i]) * nearBehind);
|
||||
nextThing[at] = t < 0 ? 0 : t > 1 ? 1 : t;
|
||||
nextBehind[at] = nearBehind < 0 ? 0 : nearBehind > 1 ? 1 : nearBehind;
|
||||
}
|
||||
}
|
||||
thing = makeImage(w, h, 3, nextThing);
|
||||
behind = makeImage(w, h, 3, nextBehind);
|
||||
}
|
||||
return thing;
|
||||
}
|
||||
|
||||
// How far past a window the mask must be read for the alpha inside it to be
|
||||
// the whole picture's, and how far the colour clean-up looks.
|
||||
export function cutOutReach({ grow = 0, feather: soft = 1, cleanEdges = true }, longSide) {
|
||||
const alpha = Math.abs(Math.trunc(grow)) + Math.ceil(Math.max(soft, 0) * 3) + 1;
|
||||
return alpha + (cleanEdges ? 3 * cleanReach(longSide) + 3 : 0);
|
||||
}
|
||||
|
||||
// The cut-out as RGBA: `image` (c = 3 or 4) and its mask plane the same size.
|
||||
// Pixels the alpha keeps fully solid keep their colours exactly.
|
||||
export function cutOut(image, mask, { keep = "white", grow = 0, feather: soft = 1, cleanEdges = true, clearHaze = 0, solidAbove = 1, longSide = null } = {}) {
|
||||
const { w, h, c } = image;
|
||||
const n = w * h;
|
||||
const alpha = cutOutAlpha(mask, w, h, { keep, grow, feather: soft, clearHaze, solidAbove });
|
||||
const cover = Float32Array.from(alpha);
|
||||
if (c === 4) for (let i = 0; i < n; i += 1) cover[i] *= Math.min(1, Math.max(0, image.data[i * 4 + 3]));
|
||||
const rgb = c === 3 ? image : makeImage(w, h, 3, Float32Array.from({ length: n * 3 }, (_, at) => image.data[Math.floor(at / 3) * 4 + (at % 3)]));
|
||||
let colours = rgb;
|
||||
if (cleanEdges && cover.some((v) => v > 0 && v < 1)) {
|
||||
const clean = cleanColours(rgb, cover, longSide ?? Math.max(w, h));
|
||||
colours = makeImage(w, h, 3, Float32Array.from(rgb.data));
|
||||
for (let i = 0; i < n; i += 1) {
|
||||
if (cover[i] >= 1) continue;
|
||||
for (let k = 0; k < 3; k += 1) colours.data[i * 3 + k] = clean.data[i * 3 + k];
|
||||
}
|
||||
}
|
||||
const out = new Float32Array(n * 4);
|
||||
for (let i = 0; i < n; i += 1) {
|
||||
out[i * 4] = colours.data[i * 3];
|
||||
out[i * 4 + 1] = colours.data[i * 3 + 1];
|
||||
out[i * 4 + 2] = colours.data[i * 3 + 2];
|
||||
out[i * 4 + 3] = cover[i];
|
||||
}
|
||||
return makeImage(w, h, 4, out);
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
// Keep Detail in the browser: the same maths as nodes/_detail_helpers.py, for
|
||||
// the live preview (js/shared/live_stage.mjs). Both pictures are split into a
|
||||
// base (the picture blurred by `detailSize` pixels) and detail (the ratio of
|
||||
// each pixel to that base, in linear light); the result is the edit's base
|
||||
// with the original's detail on it. See the Python file for why.
|
||||
import { boxBlur, gaussianBlur, makeImage, pyRound } from "./live_image.mjs";
|
||||
|
||||
export const LIGHT_FLOOR = 2e-3;
|
||||
const HUE_KEEP = 1e-6;
|
||||
export const EDGE_STEP = 0.15;
|
||||
const LUMA = [0.2126, 0.7152, 0.0722];
|
||||
|
||||
export function srgbToLinear(v) {
|
||||
const x = v < 0 ? 0 : v > 1 ? 1 : v;
|
||||
return x <= 0.04045 ? x / 12.92 : ((x + 0.055) / 1.055) ** 2.4;
|
||||
}
|
||||
|
||||
export function linearToSrgb(v) {
|
||||
const x = v < 0 ? 0 : v;
|
||||
return x <= 0.0031308 ? x * 12.92 : 1.055 * Math.max(x, 1e-12) ** (1 / 2.4) - 0.055;
|
||||
}
|
||||
|
||||
const mapImage = (image, fn) => makeImage(image.w, image.h, image.c, Float32Array.from(image.data, fn));
|
||||
|
||||
// The box radius that spreads as far as a Gaussian of this sigma.
|
||||
export function boxRadius(sigma) {
|
||||
return Math.max(1, pyRound(Math.sqrt(3 * Number(sigma) ** 2 + 0.25) - 0.5));
|
||||
}
|
||||
|
||||
function guided(image, radius) {
|
||||
const mean = boxBlur(image, radius);
|
||||
const squares = boxBlur(mapImage(image, (v) => v * v), radius);
|
||||
const keep = makeImage(image.w, image.h, image.c, new Float32Array(image.data.length));
|
||||
const offset = makeImage(image.w, image.h, image.c, new Float32Array(image.data.length));
|
||||
for (let i = 0; i < image.data.length; i += 1) {
|
||||
const spread = Math.max(squares.data[i] - mean.data[i] * mean.data[i], 0);
|
||||
keep.data[i] = spread / (spread + EDGE_STEP ** 2);
|
||||
offset.data[i] = mean.data[i] - keep.data[i] * mean.data[i];
|
||||
}
|
||||
const keepBlur = boxBlur(keep, radius);
|
||||
const offsetBlur = boxBlur(offset, radius);
|
||||
const out = new Float32Array(image.data.length);
|
||||
for (let i = 0; i < out.length; i += 1) out[i] = keepBlur.data[i] * image.data[i] + offsetBlur.data[i];
|
||||
return makeImage(image.w, image.h, image.c, out);
|
||||
}
|
||||
|
||||
// The base of linear light: what is left once detail smaller than
|
||||
// `detailSize` pixels is smoothed away (on sRGB-curved values).
|
||||
export function baseLight(light, detailSize, edgeSafe) {
|
||||
const curved = mapImage(light, linearToSrgb);
|
||||
const smooth = edgeSafe ? guided(curved, boxRadius(detailSize)) : gaussianBlur(curved, Math.max(Number(detailSize), 0.5));
|
||||
return mapImage(smooth, srgbToLinear);
|
||||
}
|
||||
|
||||
function lightOf(rgb, colorDetail) {
|
||||
const { w, h, c } = rgb;
|
||||
if (colorDetail) {
|
||||
const out = new Float32Array(w * h * 3);
|
||||
for (let i = 0; i < w * h; i += 1) for (let k = 0; k < 3; k += 1) out[i * 3 + k] = srgbToLinear(rgb.data[i * c + Math.min(k, c - 1)]);
|
||||
return makeImage(w, h, 3, out);
|
||||
}
|
||||
const out = new Float32Array(w * h);
|
||||
for (let i = 0; i < w * h; i += 1) {
|
||||
let sum = 0;
|
||||
for (let k = 0; k < 3; k += 1) sum += LUMA[k] * srgbToLinear(rgb.data[i * c + Math.min(k, c - 1)]);
|
||||
out[i] = sum;
|
||||
}
|
||||
return makeImage(w, h, 1, out);
|
||||
}
|
||||
|
||||
// How far a window must reach past what it shows for the result inside it to
|
||||
// be the whole picture's: the guided filter boxes twice, the blur is cut at
|
||||
// three sigma.
|
||||
export function detailReach(detailSize, edgeSafe) {
|
||||
return edgeSafe ? 2 * boxRadius(detailSize) + 1 : Math.ceil(3 * Math.max(Number(detailSize), 0.5)) + 1;
|
||||
}
|
||||
|
||||
// The edit with the original's detail. `edit` and `original` are pictures of
|
||||
// the same size (c = 3 or 4; alpha is left alone), `mask` one plane or null.
|
||||
export function keepDetail(edit, original, { detailSize = 4, strength = 1, colorDetail = false, edgeSafe = true, mask = null } = {}) {
|
||||
strength = Math.max(Number(strength), 0);
|
||||
if (strength === 0) return edit;
|
||||
const own = Math.max(0, 1 - strength);
|
||||
const { w, h, c } = edit;
|
||||
const editLight = lightOf(edit, colorDetail);
|
||||
const origLight = lightOf(original, colorDetail);
|
||||
const editBase = baseLight(editLight, detailSize, edgeSafe);
|
||||
const origBase = baseLight(origLight, detailSize, edgeSafe);
|
||||
const lc = editLight.c;
|
||||
const out = new Float32Array(edit.data);
|
||||
for (let i = 0; i < w * h; i += 1) {
|
||||
const factor = [0, 0, 0];
|
||||
for (let k = 0; k < lc; k += 1) {
|
||||
const at = i * lc + k;
|
||||
const base = editBase.data[at] + LIGHT_FLOOR;
|
||||
const origDetail = (origLight.data[at] + LIGHT_FLOOR) / (origBase.data[at] + LIGHT_FLOOR);
|
||||
const editDetail = (editLight.data[at] + LIGHT_FLOOR) / base;
|
||||
const target = base * origDetail ** strength * editDetail ** own;
|
||||
factor[k] = target / (editLight.data[at] + LIGHT_FLOOR);
|
||||
}
|
||||
const gate = mask ? mask[i] : 1;
|
||||
const linears = [0, 1, 2].map((k) => srgbToLinear(edit.data[i * c + k]));
|
||||
// Light only: the floor's light goes to each channel in proportion, so hue holds.
|
||||
const luma = linears[0] * LUMA[0] + linears[1] * LUMA[1] + linears[2] * LUMA[2];
|
||||
for (let k = 0; k < 3; k += 1) {
|
||||
const f = lc === 1 ? factor[0] : factor[k];
|
||||
const rgb = edit.data[i * c + k];
|
||||
const linear = linears[k];
|
||||
const share = lc === 1 ? (linear + HUE_KEEP) / (luma + HUE_KEEP) : 1;
|
||||
const lit = linear * f + LIGHT_FLOOR * (f - 1) * share;
|
||||
const change = (linearToSrgb(lit) - linearToSrgb(linear)) * gate;
|
||||
const next = rgb + change;
|
||||
out[i * c + k] = next < 0 ? 0 : next > 1 ? 1 : next;
|
||||
}
|
||||
}
|
||||
return makeImage(w, h, c, out);
|
||||
}
|
||||
@@ -0,0 +1,302 @@
|
||||
// Film Grain in the browser: the same maths as nodes/_grain_helpers.py, for
|
||||
// the live preview (js/shared/live_stage.mjs), plus Auto's noise reading.
|
||||
//
|
||||
// What matches the node: the grain's size, roughness and colour shaping, the
|
||||
// tone curve, the strength, the mask, and Auto's measure and picks. What
|
||||
// does not: the random numbers. The node draws them with torch's generator;
|
||||
// here a hash of the grain cell's position gives each cell its value, so a
|
||||
// preview of a part of the picture (100%) has the same grain wherever it is
|
||||
// panned to. The pattern is therefore another draw of the same grain: the
|
||||
// same strength and look, not the same specks. tests/live_preview.test.mjs
|
||||
// feeds this code the node's own random numbers (tests/fixtures/
|
||||
// live_parity.json) and checks the result against the node's.
|
||||
import { areaTaps, bicubicTaps, makeImage, planeStd, pyRound } from "./live_image.mjs";
|
||||
|
||||
// The same constants as nodes/_grain_helpers.py.
|
||||
export const FULL_STRENGTH = 0.15;
|
||||
export const TONE_FLOOR = 0.2;
|
||||
export const CLUMP_DEPTH = 0.6;
|
||||
export const CLUMP_SCALE = 4.0;
|
||||
export const GRAIN_LIMIT = 3.0;
|
||||
export const LUMA = [0.2126, 0.7152, 0.0722];
|
||||
export const AUTO_AMOUNT = 0.25;
|
||||
export const AUTO_SIZE_MEGAPIXELS = 1.0;
|
||||
export const AUTO_AMOUNT_RANGE = [0.05, 1.0];
|
||||
export const AUTO_SIZE_RANGE = [0.5, 16.0];
|
||||
export const OWN_GRAIN_FLOOR = 0.0015;
|
||||
export const NOISE_BINS = 4096;
|
||||
export const NOISE_TOP = 0.25;
|
||||
export const NOISE_GAIN = 6.0;
|
||||
export const HALF_NORMAL_MEDIAN = 0.6744897501960817;
|
||||
|
||||
// ---------- random cells ----------
|
||||
|
||||
function mix32(a) {
|
||||
let h = a | 0;
|
||||
h = Math.imul(h ^ (h >>> 16), 0x85ebca6b);
|
||||
h = Math.imul(h ^ (h >>> 13), 0xc2b2ae35);
|
||||
return (h ^ (h >>> 16)) >>> 0;
|
||||
}
|
||||
|
||||
// A normal random number for grid cell (i, j) of channel `ch`, from a seed.
|
||||
// Two hashes give two uniform numbers, Box-Muller turns them into one normal.
|
||||
export function cellNormal(seed, ch, i, j) {
|
||||
let h = mix32(seed ^ 0x9e3779b9);
|
||||
h = mix32(h + Math.imul(ch + 1, 0x632be5ab));
|
||||
h = mix32(h + Math.imul(i + 0x10000, 0x85ebca6b));
|
||||
const a = mix32(h + Math.imul(j + 0x10000, 0xc2b2ae35));
|
||||
const b = mix32(a ^ 0x68e31da4);
|
||||
const u = (a + 1) / 4294967297;
|
||||
const v = b / 4294967296;
|
||||
return Math.sqrt(-2 * Math.log(u)) * Math.cos(2 * Math.PI * v);
|
||||
}
|
||||
|
||||
// The cell source for a frame's grain: the n-th field drawn gets its own
|
||||
// stream, so fields never repeat each other.
|
||||
//
|
||||
// Grain far smaller than a pixel (a big picture shrunk to fit) averages
|
||||
// hundreds of cells into each pixel. The average of n independent cells is a
|
||||
// normal with 1 / sqrt(n) of their spread, so the browser draws that
|
||||
// directly (`fast`) instead of drawing every cell: the same distribution,
|
||||
// at the cost of the pixels shown.
|
||||
export function hashedCells(seed) {
|
||||
const base = mix32((Number(BigInt(seed) & 0xffffffffn) ^ Number((BigInt(seed) >> 32n) & 0xffffffffn)) >>> 0);
|
||||
const source = (index) => (ch, i, j) => cellNormal(mix32(base + index * 0x9e3779b1), ch, i, j);
|
||||
source.fast = true;
|
||||
return source;
|
||||
}
|
||||
|
||||
// ---------- grain ----------
|
||||
|
||||
// Noise in grains about `size` pixels across for a window of the picture
|
||||
// (`win` = { x0, y0, w, h }) of a picture that is `height` x `width`, as C
|
||||
// planes. The grid is laid over the whole picture, as the node does:
|
||||
// round(height / size) rows by round(width / size) columns of random cells,
|
||||
// smoothed up (bicubic) or, finer than the picture, averaged down (area).
|
||||
export function field(cells, height, width, size, channels, win, fast = false) {
|
||||
const rows = Math.max(1, pyRound(height / size));
|
||||
const cols = Math.max(1, pyRound(width / size));
|
||||
const { x0, y0 } = win;
|
||||
const cw = win.w;
|
||||
const ch = win.h;
|
||||
const out = new Float32Array(channels * cw * ch);
|
||||
if (rows === height && cols === width) {
|
||||
for (let k = 0; k < channels; k += 1) {
|
||||
for (let y = 0; y < ch; y += 1) for (let x = 0; x < cw; x += 1) out[(k * ch + y) * cw + x] = cells(k, y0 + y, x0 + x);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
const area = rows > height || cols > width;
|
||||
if (fast && rows > height && cols > width && rows * cols > 4 * height * width) {
|
||||
const spread = Math.sqrt((height * width) / (rows * cols));
|
||||
for (let k = 0; k < channels; k += 1) {
|
||||
for (let y = 0; y < ch; y += 1) for (let x = 0; x < cw; x += 1) out[(k * ch + y) * cw + x] = cells(k, y0 + y, x0 + x) * spread;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
// The cells each window column and row reads, with their weights.
|
||||
const colTaps = area
|
||||
? areaTaps(cols, width).slice(x0, x0 + cw).map(([a, b]) => ({ at: Array.from({ length: b - a }, (_, n) => a + n), weights: Array(b - a).fill(1 / (b - a)) }))
|
||||
: bicubicTaps(cols, width, x0, cw);
|
||||
const rowTaps = area
|
||||
? areaTaps(rows, height).slice(y0, y0 + ch).map(([a, b]) => ({ at: Array.from({ length: b - a }, (_, n) => a + n), weights: Array(b - a).fill(1 / (b - a)) }))
|
||||
: bicubicTaps(rows, height, y0, ch);
|
||||
const used = (taps) => {
|
||||
const set = new Set();
|
||||
for (const tap of taps) for (const at of tap.at) set.add(at);
|
||||
return [...set].sort((a, b) => a - b);
|
||||
};
|
||||
const usedRows = used(rowTaps);
|
||||
const rowSlot = new Map(usedRows.map((row, slot) => [row, slot]));
|
||||
for (let k = 0; k < channels; k += 1) {
|
||||
// Each needed row of cells, smoothed across to the window's columns.
|
||||
const across = new Float32Array(usedRows.length * cw);
|
||||
for (let slot = 0; slot < usedRows.length; slot += 1) {
|
||||
const cell = new Map();
|
||||
for (let x = 0; x < cw; x += 1) {
|
||||
let sum = 0;
|
||||
const tap = colTaps[x];
|
||||
for (let n = 0; n < tap.at.length; n += 1) {
|
||||
const j = tap.at[n];
|
||||
const key = j;
|
||||
let value = cell.get(key);
|
||||
if (value === undefined) {
|
||||
value = cells(k, usedRows[slot], j);
|
||||
cell.set(key, value);
|
||||
}
|
||||
sum += value * tap.weights[n];
|
||||
}
|
||||
across[slot * cw + x] = sum;
|
||||
}
|
||||
}
|
||||
for (let y = 0; y < ch; y += 1) {
|
||||
const tap = rowTaps[y];
|
||||
for (let x = 0; x < cw; x += 1) {
|
||||
let sum = 0;
|
||||
for (let n = 0; n < tap.at.length; n += 1) sum += across[rowSlot.get(tap.at[n]) * cw + x] * tap.weights[n];
|
||||
out[(k * ch + y) * cw + x] = sum;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!area) {
|
||||
const spread = Math.max(planeStd(out), 1e-6);
|
||||
for (let i = 0; i < out.length; i += 1) out[i] /= spread;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// One frame's grain for a window: C x h x w planes, C = 1 (monochrome) or 3.
|
||||
export function grainFrame(cellsAt, height, width, size, roughness, color, win = { x0: 0, y0: 0, w: width, h: height }) {
|
||||
size = Math.max(Number(size), 1e-3);
|
||||
roughness = Math.min(Math.max(Number(roughness), 0), 1);
|
||||
color = Math.min(Math.max(Number(color), 0), 1);
|
||||
const n = win.w * win.h;
|
||||
let drawn = 0;
|
||||
const draw = (fieldSize, channels) => field(cellsAt(drawn++), height, width, fieldSize, channels, win, Boolean(cellsAt.fast));
|
||||
// Drawn in the node's order, so a setting that adds a layer never changes
|
||||
// the layers drawn before it.
|
||||
let layers = [{ c: 1, d: draw(size, 1) }];
|
||||
if (color > 0) layers.push({ c: 3, d: draw(size, 3) });
|
||||
if (roughness > 0) {
|
||||
const clump = draw(size * CLUMP_SCALE, 1);
|
||||
const weight = Float32Array.from(clump, (v) => Math.exp(CLUMP_DEPTH * v));
|
||||
const fine = layers.map((layer) => draw(size / 2, layer.c));
|
||||
const rough = fine.map((f, index) => {
|
||||
const out = new Float32Array(f.length);
|
||||
for (let i = 0; i < f.length; i += 1) out[i] = f[i] * weight[i % n];
|
||||
const scale = planeStd(f) / Math.max(planeStd(out), 1e-6);
|
||||
for (let i = 0; i < out.length; i += 1) out[i] *= scale;
|
||||
return out;
|
||||
});
|
||||
const mixer = Math.sqrt((1 - roughness) ** 2 + roughness ** 2);
|
||||
layers = layers.map((layer, index) => {
|
||||
const d = new Float32Array(layer.d.length);
|
||||
for (let i = 0; i < d.length; i += 1) d[i] = ((1 - roughness) * layer.d[i] + roughness * rough[index][i]) / mixer;
|
||||
return { c: layer.c, d };
|
||||
});
|
||||
}
|
||||
let grain = layers[0].d;
|
||||
let channels = 1;
|
||||
if (color > 0) {
|
||||
channels = 3;
|
||||
const mixer = Math.sqrt((1 - color) ** 2 + color ** 2);
|
||||
grain = new Float32Array(3 * n);
|
||||
for (let k = 0; k < 3; k += 1) {
|
||||
for (let i = 0; i < n; i += 1) grain[k * n + i] = ((1 - color) * layers[0].d[i] + color * layers[1].d[k * n + i]) / mixer;
|
||||
}
|
||||
}
|
||||
for (let i = 0; i < grain.length; i += 1) grain[i] = GRAIN_LIMIT * Math.tanh(grain[i] / GRAIN_LIMIT);
|
||||
return { c: channels, w: win.w, h: win.h, data: grain };
|
||||
}
|
||||
|
||||
// How strong the grain is for a pixel of this luma: 1 at mid grey, falling to
|
||||
// TONE_FLOOR at black and white.
|
||||
export function toneWeight(luma) {
|
||||
const l = Math.min(Math.max(luma, 0), 1);
|
||||
return TONE_FLOOR + (1 - TONE_FLOOR) * 4 * l * (1 - l);
|
||||
}
|
||||
|
||||
// The picture with the grain laid on: strength = amount * FULL_STRENGTH,
|
||||
// `mask` (one plane the picture's size, or null) limits where.
|
||||
export function layGrain(image, grain, amount, mask = null) {
|
||||
const { w, h, c } = image;
|
||||
const strength = Number(amount) * FULL_STRENGTH;
|
||||
const out = new Float32Array(image.data);
|
||||
const n = w * h;
|
||||
for (let i = 0; i < n; i += 1) {
|
||||
const r = image.data[i * c];
|
||||
const g = c >= 3 ? image.data[i * c + 1] : r;
|
||||
const b = c >= 3 ? image.data[i * c + 2] : r;
|
||||
const tone = toneWeight(LUMA[0] * r + LUMA[1] * g + LUMA[2] * b);
|
||||
const gate = mask ? mask[i] : 1;
|
||||
for (let k = 0; k < Math.min(c, 3); k += 1) {
|
||||
const value = grain.c === 3 ? grain.data[k * n + i] : grain.data[i];
|
||||
const next = image.data[i * c + k] + value * tone * strength * gate;
|
||||
out[i * c + k] = next < 0 ? 0 : next > 1 ? 1 : next;
|
||||
}
|
||||
}
|
||||
return makeImage(w, h, c, out);
|
||||
}
|
||||
|
||||
// A window of a picture with film grain, as the node would make it.
|
||||
// `image` is the window's pixels; `height` x `width` is the whole picture
|
||||
// the grain grid is laid over and `win` where the window sits in it.
|
||||
export function filmGrain(image, { amount, size, roughness, color, cellsAt, height = image.h, width = image.w, win = null, mask = null }) {
|
||||
if (!(Number(amount) > 0)) return image;
|
||||
const window = win ?? { x0: 0, y0: 0, w: image.w, h: image.h };
|
||||
const grain = grainFrame(cellsAt, height, width, size, roughness, color, window);
|
||||
return layGrain(image, grain, amount, mask);
|
||||
}
|
||||
|
||||
// ---------- Auto ----------
|
||||
|
||||
// How much fine noise the picture has in its flat areas (one standard
|
||||
// deviation in 0-1 values), as nodes/_grain_helpers.py measure_noise does:
|
||||
// the median of a Laplacian-difference filter's size, read from a histogram.
|
||||
export function measureNoise(image) {
|
||||
const { w, h, c } = image;
|
||||
if (w < 3 || h < 3) return 0;
|
||||
const luma = new Float32Array(w * h);
|
||||
for (let i = 0; i < w * h; i += 1) {
|
||||
const r = image.data[i * c];
|
||||
const g = c >= 3 ? image.data[i * c + 1] : r;
|
||||
const b = c >= 3 ? image.data[i * c + 2] : r;
|
||||
luma[i] = c >= 3 ? LUMA[0] * r + LUMA[1] * g + LUMA[2] * b : r * (LUMA[0] + LUMA[1] + LUMA[2]);
|
||||
}
|
||||
const bins = new Int32Array(NOISE_BINS);
|
||||
let count = 0;
|
||||
const top = NOISE_TOP * (1 - 1e-6);
|
||||
for (let y = 1; y < h - 1; y += 1) {
|
||||
for (let x = 1; x < w - 1; x += 1) {
|
||||
const at = y * w + x;
|
||||
const d = Math.abs(
|
||||
luma[at - w - 1] - 2 * luma[at - w] + luma[at - w + 1]
|
||||
- 2 * luma[at - 1] + 4 * luma[at] - 2 * luma[at + 1]
|
||||
+ luma[at + w - 1] - 2 * luma[at + w] + luma[at + w + 1],
|
||||
);
|
||||
bins[Math.floor((Math.min(d, top) / NOISE_TOP) * NOISE_BINS)] += 1;
|
||||
count += 1;
|
||||
}
|
||||
}
|
||||
let reached = 0;
|
||||
let middle = NOISE_BINS - 1;
|
||||
for (let b = 0; b < NOISE_BINS; b += 1) {
|
||||
reached += bins[b];
|
||||
if (reached >= count / 2) { middle = b; break; }
|
||||
}
|
||||
return ((middle + 0.5) / NOISE_BINS * NOISE_TOP) / (NOISE_GAIN * HALF_NORMAL_MEDIAN);
|
||||
}
|
||||
|
||||
// Auto's picks for a picture: grain size follows the square root of the
|
||||
// megapixels, the amount is the normal 0.25 plus the picture's own grain.
|
||||
export function autoGrain(height, width, noise) {
|
||||
const megapixels = Math.max((height * width) / 1e6, 1e-6);
|
||||
const size = Math.sqrt(megapixels / AUTO_SIZE_MEGAPIXELS);
|
||||
const amount = AUTO_AMOUNT + Math.max(0, noise - OWN_GRAIN_FLOOR) / FULL_STRENGTH;
|
||||
const clamp = (v, [low, high]) => Math.min(Math.max(v, low), high);
|
||||
return { amount: clamp(amount, AUTO_AMOUNT_RANGE), size: clamp(size, AUTO_SIZE_RANGE) };
|
||||
}
|
||||
|
||||
// What Auto does for a picture: its own picks and the numbers used (the picks
|
||||
// times the card's multipliers, kept inside the same limits as the node).
|
||||
export function autoValues(height, width, noise, amountTimes, sizeTimes) {
|
||||
const base = autoGrain(height, width, noise);
|
||||
return {
|
||||
baseAmount: base.amount,
|
||||
baseSize: base.size,
|
||||
amount: Math.min(Math.max(base.amount * Number(amountTimes), 0), 1),
|
||||
size: Math.min(Math.max(base.size * Number(sizeTimes), AUTO_SIZE_RANGE[0]), AUTO_SIZE_RANGE[1]),
|
||||
noise,
|
||||
};
|
||||
}
|
||||
|
||||
// The numbers used while Auto copies grain from a picture: the node's match
|
||||
// times the card's three multipliers, inside the same limits as the node
|
||||
// (nodes/_grain_match_helpers.py, matched_film_grain_values).
|
||||
export function matchValues(match, amountTimes, sizeTimes, colorTimes) {
|
||||
return {
|
||||
amount: Math.min(Math.max(match.amount * Number(amountTimes), 0), 1),
|
||||
size: Math.min(Math.max(match.size * Number(sizeTimes), AUTO_SIZE_RANGE[0]), AUTO_SIZE_RANGE[1]),
|
||||
color: Math.min(Math.max(match.color * Number(colorTimes), 0), 1),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,262 @@
|
||||
// Small picture maths for the live preview on Film Grain, Keep Detail and
|
||||
// Cut Out (js/shared/live_stage.mjs). No DOM, no imports, so node:test runs
|
||||
// it. These are the pieces the Python nodes get from torch: box and Gaussian
|
||||
// blurs with repeated edges, area, bilinear and bicubic resizes, a sliding
|
||||
// maximum. Each follows torch's own definition (edges repeated, the
|
||||
// align_corners=False pixel centres, adaptive pooling for "area") so the
|
||||
// browser's drawing of a node's result agrees with the node's.
|
||||
//
|
||||
// A picture is { w, h, c, data }: data is a Float32Array of c values per
|
||||
// pixel, row by row, in 0-1 picture values.
|
||||
|
||||
export function makeImage(w, h, c, data = new Float32Array(w * h * c)) {
|
||||
return { w, h, c, data };
|
||||
}
|
||||
|
||||
// Python's round(): halves go to the even number, so a grid of
|
||||
// round(height / size) rows is the same in both languages.
|
||||
export function pyRound(value) {
|
||||
const floor = Math.floor(value);
|
||||
const diff = value - floor;
|
||||
if (diff < 0.5) return floor;
|
||||
if (diff > 0.5) return floor + 1;
|
||||
return floor % 2 === 0 ? floor : floor + 1;
|
||||
}
|
||||
|
||||
const clampIndex = (index, length) => (index < 0 ? 0 : index >= length ? length - 1 : index);
|
||||
|
||||
// The mean over a (2r+1)-square window, edges repeated: torch's
|
||||
// avg_pool2d of a replicate-padded picture.
|
||||
export function boxBlur(image, radius) {
|
||||
const r = Math.max(0, Math.floor(radius));
|
||||
if (r === 0) return image;
|
||||
const { w, h, c } = image;
|
||||
const win = 2 * r + 1;
|
||||
const across = new Float32Array(image.data.length);
|
||||
for (let y = 0; y < h; y += 1) {
|
||||
for (let ch = 0; ch < c; ch += 1) {
|
||||
const base = y * w * c + ch;
|
||||
let sum = 0;
|
||||
for (let k = -r; k <= r; k += 1) sum += image.data[base + clampIndex(k, w) * c];
|
||||
for (let x = 0; x < w; x += 1) {
|
||||
across[base + x * c] = sum / win;
|
||||
sum += image.data[base + clampIndex(x + r + 1, w) * c] - image.data[base + clampIndex(x - r, w) * c];
|
||||
}
|
||||
}
|
||||
}
|
||||
const out = new Float32Array(image.data.length);
|
||||
const row = w * c;
|
||||
for (let x = 0; x < w; x += 1) {
|
||||
for (let ch = 0; ch < c; ch += 1) {
|
||||
const base = x * c + ch;
|
||||
let sum = 0;
|
||||
for (let k = -r; k <= r; k += 1) sum += across[base + clampIndex(k, h) * row];
|
||||
for (let y = 0; y < h; y += 1) {
|
||||
out[base + y * row] = sum / win;
|
||||
sum += across[base + clampIndex(y + r + 1, h) * row] - across[base + clampIndex(y - r, h) * row];
|
||||
}
|
||||
}
|
||||
}
|
||||
return makeImage(w, h, c, out);
|
||||
}
|
||||
|
||||
// A Gaussian of the given taps, edges repeated.
|
||||
function convolve(image, kernel, radius) {
|
||||
const { w, h, c } = image;
|
||||
const across = new Float32Array(image.data.length);
|
||||
for (let y = 0; y < h; y += 1) {
|
||||
for (let x = 0; x < w; x += 1) {
|
||||
for (let ch = 0; ch < c; ch += 1) {
|
||||
let sum = 0;
|
||||
for (let k = -radius; k <= radius; k += 1) sum += kernel[k + radius] * image.data[(y * w + clampIndex(x + k, w)) * c + ch];
|
||||
across[(y * w + x) * c + ch] = sum;
|
||||
}
|
||||
}
|
||||
}
|
||||
const out = new Float32Array(image.data.length);
|
||||
for (let y = 0; y < h; y += 1) {
|
||||
for (let x = 0; x < w; x += 1) {
|
||||
for (let ch = 0; ch < c; ch += 1) {
|
||||
let sum = 0;
|
||||
for (let k = -radius; k <= radius; k += 1) sum += kernel[k + radius] * across[(clampIndex(y + k, h) * w + x) * c + ch];
|
||||
out[(y * w + x) * c + ch] = sum;
|
||||
}
|
||||
}
|
||||
}
|
||||
return makeImage(w, h, c, out);
|
||||
}
|
||||
|
||||
export function gaussianKernel(sigma, radius) {
|
||||
const kernel = new Float64Array(2 * radius + 1);
|
||||
let total = 0;
|
||||
for (let k = -radius; k <= radius; k += 1) {
|
||||
kernel[k + radius] = Math.exp(-(k * k) / (2 * sigma * sigma));
|
||||
total += kernel[k + radius];
|
||||
}
|
||||
for (let k = 0; k < kernel.length; k += 1) kernel[k] /= total;
|
||||
return kernel;
|
||||
}
|
||||
|
||||
// Gaussian blur. A wide one (sigma over WIDE_SIGMA) is worked out on a
|
||||
// smaller copy, which is smooth anyway, the same shortcut the nodes take for
|
||||
// their wide blurs; a narrow one is exact. `radius` defaults to torch's
|
||||
// choice in Keep Detail (3 sigma, at most the picture's short side less one).
|
||||
const WIDE_SIGMA = 12;
|
||||
export function gaussianBlur(image, sigma, radius = null) {
|
||||
if (!(sigma > 0)) return image;
|
||||
if (sigma > WIDE_SIGMA) {
|
||||
const shrink = Math.floor(sigma / 6);
|
||||
const small = areaResize(image, Math.max(1, Math.floor(image.h / shrink)), Math.max(1, Math.floor(image.w / shrink)));
|
||||
return bilinearResize(gaussianBlur(small, sigma / shrink, radius === null ? null : Math.ceil(radius / shrink)), image.h, image.w);
|
||||
}
|
||||
const taps = radius ?? Math.max(1, Math.min(Math.ceil(3 * sigma), Math.max(1, Math.min(image.w, image.h) - 1)));
|
||||
return convolve(image, gaussianKernel(sigma, taps), taps);
|
||||
}
|
||||
|
||||
// torch's adaptive average pooling (F.interpolate mode="area"): each output
|
||||
// cell averages the input cells from floor(i * in / out) up to
|
||||
// ceil((i + 1) * in / out).
|
||||
export function areaTaps(inLength, outLength) {
|
||||
const taps = [];
|
||||
for (let i = 0; i < outLength; i += 1) {
|
||||
const start = Math.floor((i * inLength) / outLength);
|
||||
const end = Math.ceil(((i + 1) * inLength) / outLength);
|
||||
taps.push([start, Math.max(end, start + 1)]);
|
||||
}
|
||||
return taps;
|
||||
}
|
||||
|
||||
export function areaResize(image, outH, outW) {
|
||||
if (outH === image.h && outW === image.w) return image;
|
||||
const { w, h, c } = image;
|
||||
const xs = areaTaps(w, outW);
|
||||
const ys = areaTaps(h, outH);
|
||||
const across = new Float32Array(h * outW * c);
|
||||
for (let y = 0; y < h; y += 1) {
|
||||
for (let ox = 0; ox < outW; ox += 1) {
|
||||
const [a, b] = xs[ox];
|
||||
for (let ch = 0; ch < c; ch += 1) {
|
||||
let sum = 0;
|
||||
for (let x = a; x < b; x += 1) sum += image.data[(y * w + x) * c + ch];
|
||||
across[(y * outW + ox) * c + ch] = sum / (b - a);
|
||||
}
|
||||
}
|
||||
}
|
||||
const out = new Float32Array(outH * outW * c);
|
||||
for (let oy = 0; oy < outH; oy += 1) {
|
||||
const [a, b] = ys[oy];
|
||||
for (let x = 0; x < outW; x += 1) {
|
||||
for (let ch = 0; ch < c; ch += 1) {
|
||||
let sum = 0;
|
||||
for (let y = a; y < b; y += 1) sum += across[(y * outW + x) * c + ch];
|
||||
out[(oy * outW + x) * c + ch] = sum / (b - a);
|
||||
}
|
||||
}
|
||||
}
|
||||
return makeImage(outW, outH, c, out);
|
||||
}
|
||||
|
||||
// Bilinear with torch's align_corners=False pixel centres.
|
||||
export function bilinearResize(image, outH, outW) {
|
||||
if (outH === image.h && outW === image.w) return image;
|
||||
const { w, h, c } = image;
|
||||
const axis = (inLength, outLength) => {
|
||||
const scale = inLength / outLength;
|
||||
return Array.from({ length: outLength }, (_, o) => {
|
||||
const src = Math.max(0, (o + 0.5) * scale - 0.5);
|
||||
const i0 = Math.min(Math.floor(src), inLength - 1);
|
||||
return [i0, Math.min(i0 + 1, inLength - 1), src - i0];
|
||||
});
|
||||
};
|
||||
const xs = axis(w, outW);
|
||||
const ys = axis(h, outH);
|
||||
const out = new Float32Array(outH * outW * c);
|
||||
for (let oy = 0; oy < outH; oy += 1) {
|
||||
const [y0, y1, fy] = ys[oy];
|
||||
for (let ox = 0; ox < outW; ox += 1) {
|
||||
const [x0, x1, fx] = xs[ox];
|
||||
for (let ch = 0; ch < c; ch += 1) {
|
||||
const top = image.data[(y0 * w + x0) * c + ch] * (1 - fx) + image.data[(y0 * w + x1) * c + ch] * fx;
|
||||
const bottom = image.data[(y1 * w + x0) * c + ch] * (1 - fx) + image.data[(y1 * w + x1) * c + ch] * fx;
|
||||
out[(oy * outW + ox) * c + ch] = top * (1 - fy) + bottom * fy;
|
||||
}
|
||||
}
|
||||
}
|
||||
return makeImage(outW, outH, c, out);
|
||||
}
|
||||
|
||||
// Cubic convolution weights for torch's bicubic (A = -0.75) at offsets
|
||||
// -1, 0, 1, 2 around a source position with fraction t.
|
||||
const CUBIC_A = -0.75;
|
||||
export function cubicWeights(t) {
|
||||
const near = (x) => ((CUBIC_A + 2) * x - (CUBIC_A + 3)) * x * x + 1;
|
||||
const far = (x) => ((CUBIC_A * x - 5 * CUBIC_A) * x + 8 * CUBIC_A) * x - 4 * CUBIC_A;
|
||||
return [far(t + 1), near(t), near(1 - t), far(2 - t)];
|
||||
}
|
||||
|
||||
// A grid of values (rows x cols) sampled for the pixels of a window, for
|
||||
// pictures that are `outH` x `outW`: the window starts at (x0, y0) and is
|
||||
// cw x ch big. Returns the taps each window column and row reads.
|
||||
export function bicubicTaps(inLength, outLength, start, count) {
|
||||
const scale = inLength / outLength;
|
||||
const taps = [];
|
||||
for (let o = start; o < start + count; o += 1) {
|
||||
const src = (o + 0.5) * scale - 0.5;
|
||||
const i0 = Math.floor(src);
|
||||
const weights = cubicWeights(src - i0);
|
||||
taps.push({ at: [-1, 0, 1, 2].map((k) => clampIndex(i0 + k, inLength)), weights });
|
||||
}
|
||||
return taps;
|
||||
}
|
||||
|
||||
export function crop(image, x0, y0, cw, ch) {
|
||||
const out = new Float32Array(cw * ch * image.c);
|
||||
for (let y = 0; y < ch; y += 1) {
|
||||
const sy = clampIndex(y0 + y, image.h);
|
||||
for (let x = 0; x < cw; x += 1) {
|
||||
const sx = clampIndex(x0 + x, image.w);
|
||||
for (let k = 0; k < image.c; k += 1) out[(y * cw + x) * image.c + k] = image.data[(sy * image.w + sx) * image.c + k];
|
||||
}
|
||||
}
|
||||
return makeImage(cw, ch, image.c, out);
|
||||
}
|
||||
|
||||
// Max over the 2 * steps + 1 pixels centred on each pixel along one axis
|
||||
// (pixels off the picture count as nothing), with a monotonic queue: the
|
||||
// work is the same however far it reaches.
|
||||
export function slidingMax(plane, w, h, steps, alongX) {
|
||||
const length = alongX ? w : h;
|
||||
const lines = alongX ? h : w;
|
||||
const out = new Float32Array(plane.length);
|
||||
const queue = new Int32Array(length);
|
||||
for (let line = 0; line < lines; line += 1) {
|
||||
const at = (i) => (alongX ? line * w + i : i * w + line);
|
||||
let head = 0;
|
||||
let tail = 0;
|
||||
let next = 0;
|
||||
for (let i = 0; i < length; i += 1) {
|
||||
const reach = Math.min(length - 1, i + steps);
|
||||
while (next <= reach) {
|
||||
const value = plane[at(next)];
|
||||
while (tail > head && plane[at(queue[tail - 1])] <= value) tail -= 1;
|
||||
queue[tail] = next;
|
||||
tail += 1;
|
||||
next += 1;
|
||||
}
|
||||
while (queue[head] < i - steps) head += 1;
|
||||
out[at(i)] = plane[at(queue[head])];
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export function planeStd(values) {
|
||||
const n = values.length;
|
||||
if (n < 2) return 0;
|
||||
let mean = 0;
|
||||
for (let i = 0; i < n; i += 1) mean += values[i];
|
||||
mean /= n;
|
||||
let sum = 0;
|
||||
for (let i = 0; i < n; i += 1) sum += (values[i] - mean) ** 2;
|
||||
return Math.sqrt(sum / (n - 1));
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
// What each live-preview kind reads and how it draws: the pure half of
|
||||
// js/shared/live_stage.mjs, with no DOM, so node:test runs it.
|
||||
import { pyRound } from "./live_image.mjs";
|
||||
import { autoValues, filmGrain, hashedCells, matchValues } from "./live_grain.mjs";
|
||||
import { detailReach, keepDetail } from "./live_detail.mjs";
|
||||
import { cutOut, cutOutReach } from "./live_cutout.mjs";
|
||||
|
||||
export const num = (value, fallback) => (Number.isFinite(Number(value)) ? Number(value) : fallback);
|
||||
|
||||
// What each node's drawing reads: its inputs, in the order they are told
|
||||
// about, and the widgets its result depends on.
|
||||
export const KINDS = {
|
||||
grain: {
|
||||
inputs: [{ name: "image", channels: 3, noun: "an image" }, { name: "mask", channels: 1, noun: "a mask", optional: true }],
|
||||
values: ["amount", "size", "roughness", "color", "moving", "seed", "auto", "auto_amount", "auto_size", "auto_color"],
|
||||
outChannels: 3,
|
||||
},
|
||||
detail: {
|
||||
inputs: [
|
||||
{ name: "image", channels: 3, noun: "an image" },
|
||||
{ name: "detail_from", channels: 3, noun: "an image" },
|
||||
{ name: "mask", channels: 1, noun: "a mask", optional: true },
|
||||
],
|
||||
values: ["detail_size", "strength", "color_detail", "edge_safe"],
|
||||
outChannels: 3,
|
||||
},
|
||||
cutout: {
|
||||
// Four channels: a see-through picture's alpha limits the cut-out, as in the node.
|
||||
inputs: [{ name: "image", channels: 4, noun: "an image" }, { name: "mask", channels: 1, noun: "a mask" }],
|
||||
values: ["keep", "grow", "feather", "clean_edges", "clear_haze", "solid_above"],
|
||||
outChannels: 4,
|
||||
},
|
||||
};
|
||||
|
||||
// ---------- the nodes' drawing on the pictures at hand ----------
|
||||
|
||||
// `parts` are pictures of the same size ({ image, detail_from?, mask? } as
|
||||
// floats; mask a one-channel picture). `view` says how they sit in the whole
|
||||
// picture: { scale, fullW, fullH, win } (win: where a window of real pixels
|
||||
// starts in the whole picture, null for a whole shrunk copy).
|
||||
export function drawKind(kind, vals, parts, view, noise) {
|
||||
const { image } = parts;
|
||||
const mask = parts.mask?.data ?? null;
|
||||
if (kind === "grain") {
|
||||
// vals.match: the last run's match of grain_from's grain, while Auto
|
||||
// copies it (js/shared/grain_auto.mjs).
|
||||
const picks = !vals.auto ? null
|
||||
: vals.match ? matchValues(vals.match, vals.auto_amount, vals.auto_size, vals.auto_color)
|
||||
: autoValues(view.fullH, view.fullW, noise ?? 0, vals.auto_amount, vals.auto_size);
|
||||
return filmGrain(image, {
|
||||
amount: picks ? picks.amount : vals.amount,
|
||||
size: (picks ? picks.size : vals.size) * (view.win ? 1 : view.scale),
|
||||
roughness: vals.roughness,
|
||||
color: picks?.color ?? vals.color,
|
||||
cellsAt: hashedCells(Math.max(0, Math.floor(num(vals.seed, 0)))),
|
||||
height: view.win ? view.fullH : image.h,
|
||||
width: view.win ? view.fullW : image.w,
|
||||
win: view.win ? { x0: view.win.x, y0: view.win.y, w: image.w, h: image.h } : null,
|
||||
mask,
|
||||
});
|
||||
}
|
||||
if (kind === "detail") {
|
||||
return keepDetail(image, parts.detail_from, {
|
||||
detailSize: vals.detail_size * (view.win ? 1 : view.scale),
|
||||
strength: vals.strength,
|
||||
colorDetail: vals.color_detail,
|
||||
edgeSafe: vals.edge_safe,
|
||||
mask,
|
||||
});
|
||||
}
|
||||
return cutOut(image, mask ?? new Float32Array(image.w * image.h), {
|
||||
keep: vals.keep,
|
||||
grow: view.win ? Math.trunc(vals.grow) : pyRound(vals.grow * view.scale),
|
||||
feather: vals.feather * (view.win ? 1 : view.scale),
|
||||
cleanEdges: vals.clean_edges,
|
||||
clearHaze: vals.clear_haze,
|
||||
solidAbove: vals.solid_above,
|
||||
longSide: Math.max(view.fullW, view.fullH),
|
||||
});
|
||||
}
|
||||
|
||||
// How far past a window a kind reads, so its window comes out as the whole
|
||||
// picture's would.
|
||||
export function reachOf(kind, vals, longSide) {
|
||||
if (kind === "detail") return detailReach(vals.detail_size, vals.edge_safe);
|
||||
if (kind === "cutout") return cutOutReach({ grow: vals.grow, feather: vals.feather, cleanEdges: vals.clean_edges }, longSide);
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,170 @@
|
||||
// Where the live preview (js/shared/live_stage.mjs) and Film Grain's Auto get
|
||||
// the pictures a node works on, and how they are read.
|
||||
//
|
||||
// A picture is known at once when it comes straight from a Load Image: its
|
||||
// file is read through ComfyUI's own /view route (the pack's routes only ever
|
||||
// answer with data they made, never a file by its path). Any other source
|
||||
// (a VAE Decode, another node's result) exists only after a run, so the node
|
||||
// writes the pictures it worked from to ComfyUI's temp folder with its result
|
||||
// (ui.ausboss_live) and the page keeps reading those; they are valid while
|
||||
// the wiring is the one that run had (`connectionKey`).
|
||||
import { linkById, sourceFileWidget, viewQueryForFile } from "./input_preview.mjs";
|
||||
import { makeImage } from "./live_image.mjs";
|
||||
|
||||
// Only ComfyUI's own Load Image hands its file on untouched, as its first
|
||||
// output. (The pack's Load Image can resize or pad, so it is not read this way.)
|
||||
const DIRECT_TYPES = new Set(["LoadImage"]);
|
||||
|
||||
export function inputLink(node, name) {
|
||||
const input = node?.inputs?.find((candidate) => candidate?.name === name);
|
||||
return linkById(node?.graph, input?.link);
|
||||
}
|
||||
|
||||
// How one input of the node will be known:
|
||||
// { state: "none" } nothing is wired to it
|
||||
// { state: "direct", query, key } a Load Image's file: known at once
|
||||
// { state: "run", key } known after one run
|
||||
export function planInput(node, name) {
|
||||
const link = inputLink(node, name);
|
||||
if (!link) return { state: "none" };
|
||||
const origin = node.graph?.getNodeById?.(link.origin_id) ?? null;
|
||||
const widget = origin && DIRECT_TYPES.has(origin.type) && Number(link.origin_slot) === 0 ? sourceFileWidget(origin) : null;
|
||||
if (widget && widget.name === "image" && typeof widget.value === "string" && widget.value) {
|
||||
const query = viewQueryForFile(widget.value);
|
||||
return { state: "direct", query, key: `view:${query}` };
|
||||
}
|
||||
return { state: "run", key: `link:${link.id}:${link.origin_id}:${link.origin_slot}` };
|
||||
}
|
||||
|
||||
// How many channels a source is read with. A Load Image's file is read as
|
||||
// colour only, as ComfyUI's Load Image hands its see-through part to the
|
||||
// mask and not to the picture; a picture a run kept carries its alpha.
|
||||
export const channelsFor = (input, state) => (state === "direct" ? Math.min(input.channels, 3) : input.channels);
|
||||
|
||||
// What the wiring of these inputs is, as one string: the pictures a run kept
|
||||
// belong to this wiring, and are not used once it changes.
|
||||
export function connectionKey(node, names) {
|
||||
return names.map((name) => {
|
||||
const link = inputLink(node, name);
|
||||
return link ? `${name}=${link.id}:${link.origin_id}:${link.origin_slot}` : `${name}=-`;
|
||||
}).join("|");
|
||||
}
|
||||
|
||||
// The /view query of one of the pictures a run kept (ui.ausboss_live[0][name]
|
||||
// is { filename, subfolder, type }), or null.
|
||||
export function keptQuery(record, name) {
|
||||
const entry = record?.ausboss_live?.[0]?.[name];
|
||||
if (!entry || typeof entry.filename !== "string" || !entry.filename) return null;
|
||||
return new URLSearchParams({ filename: entry.filename, subfolder: entry.subfolder ?? "", type: entry.type ?? "temp" }).toString();
|
||||
}
|
||||
|
||||
// ---------- reading pixels ----------
|
||||
|
||||
const cache = new Map();
|
||||
const CACHE_PIXELS = 40e6;
|
||||
|
||||
function forget() {
|
||||
let total = 0;
|
||||
for (const entry of cache.values()) total += entry.pixels;
|
||||
for (const [url, entry] of cache) {
|
||||
if (total <= CACHE_PIXELS || cache.size <= 1) break;
|
||||
cache.delete(url);
|
||||
total -= entry.pixels;
|
||||
}
|
||||
}
|
||||
|
||||
// A picture's pixels as 8-bit RGBA: { w, h, data }. Rejects when the page
|
||||
// cannot read pixels (a privacy browser hands back blank ones), so the
|
||||
// caller falls back to showing the picture as it is.
|
||||
export function loadPixels(url) {
|
||||
const held = cache.get(url);
|
||||
if (held) return held.promise;
|
||||
const entry = { pixels: 0, promise: null };
|
||||
entry.promise = (async () => {
|
||||
// An <img> rather than a fetch: it is the page's own picture, read from
|
||||
// ComfyUI's /view route like any other.
|
||||
const picture = new Image();
|
||||
picture.decoding = "async";
|
||||
picture.src = url;
|
||||
await picture.decode();
|
||||
const w = picture.naturalWidth;
|
||||
const h = picture.naturalHeight;
|
||||
if (!(w > 0 && h > 0)) throw new Error("The picture could not be read.");
|
||||
const canvas = typeof OffscreenCanvas === "function" ? new OffscreenCanvas(w, h) : Object.assign(document.createElement("canvas"), { width: w, height: h });
|
||||
const context = canvas.getContext("2d", { willReadFrequently: true });
|
||||
context.drawImage(picture, 0, 0);
|
||||
const { data } = context.getImageData(0, 0, w, h);
|
||||
if (pixelsLookBlocked(data)) throw new Error("This browser hides picture pixels from the page.");
|
||||
entry.pixels = w * h;
|
||||
return { w, h, data };
|
||||
})();
|
||||
cache.set(url, entry);
|
||||
entry.promise.then(forget, () => cache.delete(url));
|
||||
return entry.promise;
|
||||
}
|
||||
|
||||
// A read that returns nothing but zeros, even the alpha, is a blocked read.
|
||||
export function pixelsLookBlocked(data) {
|
||||
const step = Math.max(4, (Math.floor(data.length / 4 / 997) || 1) * 4);
|
||||
for (let i = 0; i < data.length; i += step) {
|
||||
if (data[i] || data[i + 1] || data[i + 2] || data[i + 3]) return false;
|
||||
}
|
||||
return data.length > 0;
|
||||
}
|
||||
|
||||
// 8-bit RGBA pixels as a picture of 0-1 values: 3 channels (alpha dropped),
|
||||
// 4 (kept), or 1 (the red channel: a mask is saved as grey).
|
||||
export function pixelsToImage(pixels, channels = 3) {
|
||||
const { w, h, data } = pixels;
|
||||
const out = new Float32Array(w * h * channels);
|
||||
for (let i = 0; i < w * h; i += 1) {
|
||||
for (let k = 0; k < channels; k += 1) out[i * channels + k] = data[i * 4 + (channels === 1 ? 0 : k)] / 255;
|
||||
}
|
||||
return makeImage(w, h, channels, out);
|
||||
}
|
||||
|
||||
// A part of a picture's pixels as 0-1 values: the window (x, y, w, h) with
|
||||
// the picture's edge repeated past its sides, `channels` as for pixelsToImage.
|
||||
export function windowImage(pixels, win, channels = 3) {
|
||||
const out = new Float32Array(win.w * win.h * channels);
|
||||
for (let y = 0; y < win.h; y += 1) {
|
||||
const sy = Math.min(Math.max(win.y + y, 0), pixels.h - 1);
|
||||
for (let x = 0; x < win.w; x += 1) {
|
||||
const sx = Math.min(Math.max(win.x + x, 0), pixels.w - 1);
|
||||
const at = (sy * pixels.w + sx) * 4;
|
||||
for (let k = 0; k < channels; k += 1) out[(y * win.w + x) * channels + k] = pixels.data[at + (channels === 1 ? 0 : k)] / 255;
|
||||
}
|
||||
}
|
||||
return makeImage(win.w, win.h, channels, out);
|
||||
}
|
||||
|
||||
// The whole picture shrunk to w x h by averaging (torch's "area"), as 0-1
|
||||
// values with `channels` channels. Reads 8-bit pixels directly, so a big
|
||||
// picture is never held twice as floats.
|
||||
export function scaledImage(pixels, outW, outH, channels = 3) {
|
||||
const out = new Float32Array(outW * outH * channels);
|
||||
const span = (inLength, outLength, i) => [Math.floor((i * inLength) / outLength), Math.max(Math.ceil(((i + 1) * inLength) / outLength), Math.floor((i * inLength) / outLength) + 1)];
|
||||
for (let oy = 0; oy < outH; oy += 1) {
|
||||
const [y0, y1] = span(pixels.h, outH, oy);
|
||||
for (let ox = 0; ox < outW; ox += 1) {
|
||||
const [x0, x1] = span(pixels.w, outW, ox);
|
||||
const count = (y1 - y0) * (x1 - x0);
|
||||
for (let k = 0; k < channels; k += 1) {
|
||||
let sum = 0;
|
||||
for (let y = y0; y < y1; y += 1) for (let x = x0; x < x1; x += 1) sum += pixels.data[(y * pixels.w + x) * 4 + (channels === 1 ? 0 : k)];
|
||||
out[(oy * outW + ox) * channels + k] = sum / count / 255;
|
||||
}
|
||||
}
|
||||
}
|
||||
return makeImage(outW, outH, channels, out);
|
||||
}
|
||||
|
||||
// The picture's brightness as one plane, for measuring its noise without
|
||||
// holding the whole picture as floats.
|
||||
export function lumaImage(pixels) {
|
||||
const out = new Float32Array(pixels.w * pixels.h);
|
||||
for (let i = 0; i < out.length; i += 1) {
|
||||
out[i] = (0.2126 * pixels.data[i * 4] + 0.7152 * pixels.data[i * 4 + 1] + 0.0722 * pixels.data[i * 4 + 2]) / 255;
|
||||
}
|
||||
return makeImage(pixels.w, pixels.h, 1, out);
|
||||
}
|
||||
@@ -0,0 +1,468 @@
|
||||
// The live preview on Film Grain, Keep Detail and Cut Out: the picture on the
|
||||
// node redraws while a value is dragged, before any run.
|
||||
//
|
||||
// It lives inside the node's preview panel (js/input_preview/index.js) and
|
||||
// takes the stage over while it can draw. Two views, chosen with the Fit |
|
||||
// 100% switch on the panel's bar:
|
||||
//
|
||||
// Fit the whole picture, worked out on a copy shrunk to the size it is
|
||||
// shown at (js/shared/live_view_math.mjs fitGeometry)
|
||||
// 100% a window of real pixels; dragging on the picture pans it
|
||||
//
|
||||
// The maths is the nodes' own, in the browser (live_grain.mjs,
|
||||
// live_detail.mjs, live_cutout.mjs; tests/live_preview.test.mjs holds it to
|
||||
// the Python's numbers). The pictures come from a Load Image through
|
||||
// ComfyUI's /view route, or, for any other source, from the copy the node
|
||||
// wrote with its last run (live_sources.mjs). A "not run yet" tag shows
|
||||
// whenever what is drawn is not what the last run made; once the values match
|
||||
// a run, that run's own picture is shown instead.
|
||||
//
|
||||
// Where the browser will not hand the page a picture's pixels (a privacy
|
||||
// setting), the stage stays as it was and shows the run's result.
|
||||
import { FONT_UI, RADIUS_XS, THEME as T } from "./theme.mjs";
|
||||
import { CHECKER } from "./compare_erase.mjs";
|
||||
import { panelSwitch } from "./panel_controls.mjs";
|
||||
import { chainCallback } from "./index.mjs";
|
||||
import { makeImage } from "./live_image.mjs";
|
||||
import { autoGrain, measureNoise } from "./live_grain.mjs";
|
||||
import { KINDS, drawKind, num, reachOf } from "./live_kinds.mjs";
|
||||
import { cropGeometry, fitGeometry, insideOf, paddedWindow, runIsCurrent, valuesSignature } from "./live_view_math.mjs";
|
||||
import { channelsFor, connectionKey, keptQuery, loadPixels, lumaImage, planInput, scaledImage, windowImage } from "./live_sources.mjs";
|
||||
import { copiesGrain, setAuto } from "./grain_auto.mjs";
|
||||
|
||||
const CSS_ID = "ausboss-live-stage-css";
|
||||
const VIEW_PROPERTY = "ausboss_live_view";
|
||||
const RUN_ONCE = "Run once to get the picture. Then it changes as you drag.";
|
||||
const RUN_ONCE_MASK = "Run once to get the mask. Then it changes as you drag.";
|
||||
const RUN_ONCE_MATCH = "Run once to match the grain. Then it changes as you drag.";
|
||||
|
||||
function ensureCss() {
|
||||
if (document.getElementById(CSS_ID)) return;
|
||||
const style = document.createElement("style");
|
||||
style.id = CSS_ID;
|
||||
style.textContent = `
|
||||
.ausboss-input-preview-stage canvas.ausboss-live-canvas{display:none;position:absolute;inset:0;margin:auto;max-width:none;max-height:none;pointer-events:none;image-rendering:auto}
|
||||
.ausboss-input-preview-stage.live-on canvas.ausboss-live-canvas{display:block}
|
||||
.ausboss-input-preview-stage.live-on img,.ausboss-input-preview-stage.live-on video,.ausboss-input-preview-stage.live-on .ausboss-input-preview-hint{display:none!important}
|
||||
.ausboss-input-preview-stage.checker canvas.ausboss-live-canvas{background-image:repeating-conic-gradient(${CHECKER.light} 0 25%,${CHECKER.dark} 0 50%);background-size:${CHECKER.side * 2}px ${CHECKER.side * 2}px}
|
||||
.ausboss-input-preview-stage.live-pan canvas.ausboss-live-canvas{pointer-events:auto;cursor:grab;touch-action:none}
|
||||
.ausboss-input-preview-stage.live-pan.panning canvas.ausboss-live-canvas{cursor:grabbing}
|
||||
.ausboss-live-tag,.ausboss-live-look{display:none;position:absolute;z-index:3;padding:2px 7px;border-radius:999px;background:${T.card};color:${T.inkSoft};font:600 10px/1.3 ${FONT_UI};pointer-events:none;white-space:nowrap}
|
||||
.ausboss-live-tag{left:6px;top:6px}
|
||||
.ausboss-live-look{left:50%;bottom:6px;transform:translateX(-50%);color:${T.label}}
|
||||
.ausboss-input-preview-stage.live-on .ausboss-live-tag.show,.ausboss-input-preview-stage.live-on.live-pan .ausboss-live-look.show{display:block}
|
||||
.ausboss-panel-switch.ausboss-live-view{gap:0;margin-left:auto;padding:2px;min-height:20px;border-radius:${RADIUS_XS}px;background:${T.fill};color:${T.label}}
|
||||
.ausboss-live-view + .ausboss-panel-switch{margin-left:6px}
|
||||
.ausboss-live-view span{padding:2px 7px;border-radius:${RADIUS_XS - 1}px;font:600 10.5px/1.2 ${FONT_UI}}
|
||||
.ausboss-live-view[aria-checked=false] .fit,.ausboss-live-view[aria-checked=true] .full{background:${T.brand};color:${T.onBrand}}
|
||||
.ausboss-live-view.faded{opacity:.4;pointer-events:none}
|
||||
`;
|
||||
document.head.append(style);
|
||||
}
|
||||
|
||||
const widgetValue = (node, name) => node.widgets?.find((widget) => widget?.name === name)?.value;
|
||||
const imageData = (image) => {
|
||||
const out = new Uint8ClampedArray(image.w * image.h * 4);
|
||||
for (let i = 0; i < image.w * image.h; i += 1) {
|
||||
for (let k = 0; k < 3; k += 1) out[i * 4 + k] = Math.round(image.data[i * image.c + (image.c === 1 ? 0 : k)] * 255);
|
||||
out[i * 4 + 3] = image.c === 4 ? Math.round(image.data[i * 4 + 3] * 255) : 255;
|
||||
}
|
||||
return new ImageData(out, image.w, image.h);
|
||||
};
|
||||
|
||||
// ---------- the stage ----------
|
||||
|
||||
export function mountLive(state, kind, hooks) {
|
||||
ensureCss();
|
||||
const spec = KINDS[kind];
|
||||
const node = state.node;
|
||||
const names = spec.inputs.map((input) => input.name);
|
||||
const live = {
|
||||
kind, spec, node, state, alive: true, hooks,
|
||||
pan: null, // 100%: the window's top-left in picture pixels
|
||||
pix: {}, // name -> { key, pixels }
|
||||
noise: new Map(), // pixel key -> measured noise
|
||||
loadedKey: "",
|
||||
loadingKey: "",
|
||||
broken: "", // a key that could not be read: the stage stays as it was
|
||||
drawnKey: "",
|
||||
drawn: false,
|
||||
run: null, // { record, key, sig }: the last run, as first seen here
|
||||
raf: 0,
|
||||
timer: 0,
|
||||
cooldown: 0,
|
||||
};
|
||||
node.__ausbossLive = live;
|
||||
node.properties ??= {};
|
||||
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.className = "ausboss-live-canvas";
|
||||
const tag = Object.assign(document.createElement("div"), { className: "ausboss-live-tag", textContent: "not run yet" });
|
||||
const look = Object.assign(document.createElement("div"), { className: "ausboss-live-look", textContent: "drag to look around" });
|
||||
state.stage.append(canvas, tag, look);
|
||||
live.canvas = canvas;
|
||||
|
||||
// Fit | 100%, left of Preview. A switch (role=switch) that reads Fit when
|
||||
// off and 100% when on, drawn as two segments.
|
||||
const view = panelSwitch("", "Fit shows the whole picture. 100% shows real pixels; drag the picture to look around.");
|
||||
view.classList.add("ausboss-live-view", "faded");
|
||||
const fit = Object.assign(document.createElement("span"), { className: "fit", textContent: "Fit" });
|
||||
const full = Object.assign(document.createElement("span"), { className: "full", textContent: "100%" });
|
||||
view.replaceChildren(fit, full);
|
||||
view.setAttribute("aria-label", "Picture view: Fit or 100%");
|
||||
view.addEventListener("pointerdown", (event) => event.stopPropagation(), { signal: state.abort.signal });
|
||||
view.addEventListener("click", (event) => {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
node.properties[VIEW_PROPERTY] = mode(live) === "100" ? "fit" : "100";
|
||||
live.pan = null;
|
||||
syncView(live);
|
||||
schedule(live);
|
||||
}, { signal: state.abort.signal });
|
||||
state.bar.insertBefore(view, state.switchButton ?? null);
|
||||
live.viewSwitch = view;
|
||||
live.tag = tag;
|
||||
live.look = look;
|
||||
syncView(live);
|
||||
|
||||
// Dragging on the picture pans it (100% only). The node itself still moves
|
||||
// by its title: nothing here listens to the wheel, so it keeps zooming the graph.
|
||||
let drag = null;
|
||||
canvas.addEventListener("pointerdown", (event) => {
|
||||
if (mode(live) !== "100" || event.button !== 0 || !live.geo) return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
canvas.setPointerCapture?.(event.pointerId);
|
||||
drag = { x: event.clientX, y: event.clientY, from: { x: live.geo.x, y: live.geo.y } };
|
||||
state.stage.classList.add("panning");
|
||||
live.looked = true;
|
||||
look.classList.remove("show");
|
||||
}, { signal: state.abort.signal });
|
||||
canvas.addEventListener("pointermove", (event) => {
|
||||
if (!drag || !live.geo) return;
|
||||
// The graph can be zoomed: a screen pixel is not a stage pixel.
|
||||
const box = canvas.getBoundingClientRect();
|
||||
const ratio = canvas.offsetWidth > 0 && box.width > 0 ? box.width / canvas.offsetWidth : 1;
|
||||
live.pan = { x: drag.from.x - (event.clientX - drag.x) / ratio, y: drag.from.y - (event.clientY - drag.y) / ratio };
|
||||
schedule(live);
|
||||
}, { signal: state.abort.signal });
|
||||
const endDrag = (event) => {
|
||||
if (!drag) return;
|
||||
drag = null;
|
||||
state.stage.classList.remove("panning");
|
||||
canvas.releasePointerCapture?.(event.pointerId);
|
||||
};
|
||||
canvas.addEventListener("pointerup", endDrag, { signal: state.abort.signal });
|
||||
canvas.addEventListener("pointercancel", endDrag, { signal: state.abort.signal });
|
||||
|
||||
// Every value the picture depends on redraws it as it changes.
|
||||
const watch = () => {
|
||||
for (const name of spec.values) {
|
||||
const widget = node.widgets?.find((item) => item?.name === name);
|
||||
if (!widget || widget.__ausbossLiveWatch) continue;
|
||||
widget.__ausbossLiveWatch = true;
|
||||
chainCallback(widget, "callback", () => { if (live.alive) schedule(live); });
|
||||
}
|
||||
};
|
||||
live.watch = watch;
|
||||
watch();
|
||||
chainCallback(node, "onConfigure", () => queueMicrotask(() => { if (live.alive) { watch(); schedule(live); } }));
|
||||
if (typeof ResizeObserver === "function") {
|
||||
const watcher = new ResizeObserver(() => { if (live.alive) schedule(live); });
|
||||
watcher.observe(state.stage);
|
||||
state.abort.signal.addEventListener("abort", () => watcher.disconnect(), { once: true });
|
||||
}
|
||||
live.dispose = () => {
|
||||
live.alive = false;
|
||||
cancelAnimationFrame(live.raf);
|
||||
clearTimeout(live.timer);
|
||||
node.__ausbossLive = null;
|
||||
};
|
||||
return live;
|
||||
}
|
||||
|
||||
function mode(live) {
|
||||
return live.node.properties?.[VIEW_PROPERTY] === "100" ? "100" : "fit";
|
||||
}
|
||||
|
||||
function syncView(live) {
|
||||
const full = mode(live) === "100";
|
||||
live.viewSwitch.setAttribute("aria-checked", String(full));
|
||||
live.viewSwitch.classList.toggle("faded", !live.drawn);
|
||||
live.viewSwitch.toggleAttribute("aria-disabled", !live.drawn);
|
||||
live.state.stage.classList.toggle("live-pan", full && live.drawn);
|
||||
live.look.classList.toggle("show", full && live.drawn && !live.looked);
|
||||
}
|
||||
|
||||
// A redraw at most once a frame, and after a slow one, not before the page
|
||||
// has had as long again to answer the pointer: a drag stays smooth.
|
||||
function schedule(live) {
|
||||
if (!live.alive || live.raf || live.timer) return;
|
||||
const wait = live.cooldown - performance.now();
|
||||
if (wait > 4) {
|
||||
live.timer = setTimeout(() => { live.timer = 0; schedule(live); }, wait);
|
||||
return;
|
||||
}
|
||||
live.raf = requestAnimationFrame(() => {
|
||||
live.raf = 0;
|
||||
if (live.alive) live.hooks.refresh();
|
||||
});
|
||||
}
|
||||
|
||||
// What each input of the node is, now: the plan for each, and what to say
|
||||
// when one cannot be drawn from yet.
|
||||
function describe(live) {
|
||||
const { node, spec, hooks } = live;
|
||||
const record = hooks.record();
|
||||
const here = connectionKey(node, spec.inputs.map((input) => input.name));
|
||||
// Which pictures feed the node: a Load Image's file, or a link.
|
||||
const sources = spec.inputs.map((input) => `${input.name}=${planInput(node, input.name).key ?? "-"}`).join("|");
|
||||
// The pictures a run kept belong to the wiring it had, and its result to
|
||||
// the files it read too. A record seen for the first time here belongs to
|
||||
// the wiring, files and values as they are now (a new run, or a workflow
|
||||
// just opened).
|
||||
if (record && live.run?.record !== record) live.run = { record, key: here, sources, sig: valuesSignature(node, spec.values) };
|
||||
if (!record) live.run = null;
|
||||
const kept = live.run && live.run.key === here;
|
||||
const plans = [];
|
||||
for (const input of spec.inputs) {
|
||||
const plan = planInput(node, input.name);
|
||||
if (plan.state === "none") {
|
||||
if (input.optional) continue;
|
||||
return { status: "none", input };
|
||||
}
|
||||
if (input.channels === 1 && plan.state === "direct") plan.state = "run"; // a mask is never a Load Image's file
|
||||
if (plan.state === "direct") {
|
||||
plans.push({ input, key: plan.key, url: hooks.viewUrl(plan.query), channels: channelsFor(input, "direct") });
|
||||
continue;
|
||||
}
|
||||
const query = kept ? keptQuery(record, input.name) : null;
|
||||
if (!query) return { status: "run", input };
|
||||
plans.push({ input, key: `kept:${query}`, url: hooks.viewUrl(query), channels: channelsFor(input, "run") });
|
||||
}
|
||||
return { status: "ready", plans, sources, key: plans.map((plan) => `${plan.input.name}=${plan.key}`).join("|") };
|
||||
}
|
||||
|
||||
function hintFor(input) {
|
||||
return input.channels === 1 ? RUN_ONCE_MASK : RUN_ONCE;
|
||||
}
|
||||
|
||||
function showHint(live, text) {
|
||||
const { stage, hint } = live.state;
|
||||
stage.classList.remove("live-on", "show-image", "show-video", "show-grid");
|
||||
hint.textContent = text;
|
||||
live.drawn = false;
|
||||
live.drawnKey = "";
|
||||
syncView(live);
|
||||
}
|
||||
|
||||
async function loadAll(live, found) {
|
||||
const key = found.key;
|
||||
live.loadingKey = key;
|
||||
try {
|
||||
const pix = {};
|
||||
for (const plan of found.plans) pix[plan.input.name] = { key: plan.key, channels: plan.channels, pixels: await loadPixels(plan.url) };
|
||||
if (!live.alive || live.loadingKey !== key) return;
|
||||
live.pix = pix;
|
||||
live.loadedKey = key;
|
||||
live.broken = "";
|
||||
const image = pix.image?.pixels;
|
||||
if (live.kind === "grain" && image) {
|
||||
let noise = live.noise.get(pix.image.key);
|
||||
if (noise === undefined) {
|
||||
noise = measureNoise(lumaImage(image));
|
||||
live.noise.set(pix.image.key, noise);
|
||||
}
|
||||
setAuto(live.node, autoGrain(image.h, image.w, noise));
|
||||
}
|
||||
} catch {
|
||||
if (live.alive && live.loadingKey === key) live.broken = key;
|
||||
} finally {
|
||||
if (live.loadingKey === key) live.loadingKey = "";
|
||||
}
|
||||
if (live.alive) live.hooks.refresh();
|
||||
}
|
||||
|
||||
function currentValues(live) {
|
||||
const vals = {};
|
||||
for (const name of live.spec.values) vals[name] = widgetValue(live.node, name);
|
||||
for (const name of ["amount", "size", "roughness", "color", "auto_amount", "auto_size", "auto_color", "detail_size", "strength", "grow", "feather", "clear_haze", "solid_above"]) {
|
||||
if (name in vals) vals[name] = num(vals[name], 0);
|
||||
}
|
||||
for (const name of ["auto", "moving", "color_detail", "edge_safe", "clean_edges"]) if (name in vals) vals[name] = Boolean(vals[name]);
|
||||
if (live.kind === "grain" && copiesGrain(live.node)) vals.match = live.node.__ausbossMatch ?? null;
|
||||
return vals;
|
||||
}
|
||||
|
||||
// A picture of the size the work is done at, from the source's pixels (a
|
||||
// window, or the whole shrunk). Another size than the picture's own is
|
||||
// stretched to it.
|
||||
function sourcePart(live, input, pixels, geo, whole) {
|
||||
const channels = input.channels;
|
||||
const same = pixels.w === whole.w && pixels.h === whole.h;
|
||||
if (geo.win) {
|
||||
if (same) return windowImage(pixels, geo.win, channels);
|
||||
const stretched = scaledImage(pixels, whole.w, whole.h, channels);
|
||||
const out = makeImage(geo.win.w, geo.win.h, channels);
|
||||
for (let y = 0; y < geo.win.h; y += 1) {
|
||||
for (let x = 0; x < geo.win.w; x += 1) {
|
||||
const at = (Math.min(Math.max(geo.win.y + y, 0), whole.h - 1) * whole.w + Math.min(Math.max(geo.win.x + x, 0), whole.w - 1)) * channels;
|
||||
for (let k = 0; k < channels; k += 1) out.data[(y * geo.win.w + x) * channels + k] = stretched.data[at + k];
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
// The shrunk copy does not depend on any value: kept for the next drag step.
|
||||
const key = `${live.pix[input.name]?.key}|${geo.workW}x${geo.workH}|${channels}`;
|
||||
live.shrunk ??= new Map();
|
||||
let copy = live.shrunk.get(key);
|
||||
if (!copy) {
|
||||
copy = scaledImage(pixels, geo.workW, geo.workH, channels);
|
||||
if (live.shrunk.size > 6) live.shrunk.delete(live.shrunk.keys().next().value);
|
||||
live.shrunk.set(key, copy);
|
||||
}
|
||||
return copy;
|
||||
}
|
||||
|
||||
// Draw now. Returns true when the stage shows a picture.
|
||||
function paint(live, found) {
|
||||
const { node, hooks, canvas } = live;
|
||||
const { stage } = live.state;
|
||||
const first = live.pix.image?.pixels;
|
||||
if (!first) return false;
|
||||
const whole = { w: first.w, h: first.h };
|
||||
const viewMode = mode(live);
|
||||
const bounds = stage.getBoundingClientRect();
|
||||
const stageW = stage.clientWidth || bounds.width;
|
||||
const stageH = stage.clientHeight || bounds.height;
|
||||
const vals = currentValues(live);
|
||||
const sig = valuesSignature(node, live.spec.values);
|
||||
const matches = runIsCurrent(live.run, sig, found.sources) && hooks.hasResult();
|
||||
const resultUrl = matches ? hooks.resultUrl() : null;
|
||||
const stamp = `${found.key}|${sig}|${JSON.stringify(vals.match ?? null)}|${viewMode}|${stageW}x${stageH}|${live.pan?.x}|${live.pan?.y}|${resultUrl}|${Boolean(resultUrl && live.resultPixels?.url === resultUrl)}`;
|
||||
if (stamp === live.drawnKey && live.drawn) return true;
|
||||
|
||||
let geo;
|
||||
let shown;
|
||||
if (viewMode === "fit") {
|
||||
const fitted = fitGeometry(stageW, stageH, whole.w, whole.h, window.devicePixelRatio || 1);
|
||||
if (!fitted) return live.drawn;
|
||||
geo = { ...fitted, win: null };
|
||||
canvas.width = geo.workW;
|
||||
canvas.height = geo.workH;
|
||||
canvas.style.width = `${geo.displayW}px`;
|
||||
canvas.style.height = `${geo.displayH}px`;
|
||||
shown = { w: geo.workW, h: geo.workH };
|
||||
} else {
|
||||
const window100 = cropGeometry(stageW, stageH, whole.w, whole.h, live.pan);
|
||||
if (!window100) return live.drawn;
|
||||
live.pan = { x: window100.x, y: window100.y };
|
||||
geo = { win: { x: window100.x, y: window100.y, w: window100.w, h: window100.h }, x: window100.x, y: window100.y, scale: 1 };
|
||||
canvas.width = window100.w;
|
||||
canvas.height = window100.h;
|
||||
canvas.style.width = `${window100.w}px`;
|
||||
canvas.style.height = `${window100.h}px`;
|
||||
shown = { w: window100.w, h: window100.h };
|
||||
}
|
||||
live.geo = geo;
|
||||
|
||||
const draw = (image) => canvas.getContext("2d").putImageData(imageData(image), 0, 0);
|
||||
const started = performance.now();
|
||||
const finish = (real) => {
|
||||
live.drawn = true;
|
||||
live.drawnKey = stamp;
|
||||
live.lastMs = performance.now() - started;
|
||||
live.cooldown = performance.now() + Math.min(250, live.lastMs * 0.6);
|
||||
live.tag.classList.toggle("show", !real);
|
||||
stage.classList.add("live-on");
|
||||
stage.classList.remove("show-image", "show-video", "show-grid");
|
||||
syncView(live);
|
||||
return true;
|
||||
};
|
||||
|
||||
if (resultUrl && live.resultPixels?.url === resultUrl) {
|
||||
const result = live.resultPixels.pixels;
|
||||
const channels = live.spec.outChannels;
|
||||
draw(geo.win ? windowImage(result, geo.win, channels) : scaledImage(result, geo.workW, geo.workH, channels));
|
||||
return finish(true);
|
||||
}
|
||||
if (resultUrl && live.resultPixels?.url !== resultUrl && live.resultPixels?.loading !== resultUrl) {
|
||||
// Read the run's own picture; until it is here, draw the live one.
|
||||
live.resultPixels = { url: null, loading: resultUrl };
|
||||
loadPixels(resultUrl).then((pixels) => {
|
||||
if (!live.alive) return;
|
||||
live.resultPixels = { url: resultUrl, pixels };
|
||||
hooks.refresh();
|
||||
}, () => { live.resultPixels = { url: null, loading: null, failed: resultUrl }; });
|
||||
}
|
||||
|
||||
// The pictures the work is done on: a window grown by what the filters
|
||||
// read at 100%, or the whole picture shrunk.
|
||||
const reach = geo.win ? reachOf(live.kind, vals, Math.max(whole.w, whole.h)) : 0;
|
||||
const padded = geo.win ? paddedWindow(geo.win, reach, whole.w, whole.h) : null;
|
||||
const region = geo.win ? { ...geo, win: padded } : geo;
|
||||
const parts = {};
|
||||
for (const input of live.spec.inputs) {
|
||||
const source = live.pix[input.name];
|
||||
if (source) parts[input.name === "mask" ? "mask" : input.name] = sourcePart(live, { ...input, channels: source.channels ?? input.channels }, source.pixels, region, whole);
|
||||
}
|
||||
let noise = null;
|
||||
if (live.kind === "grain") noise = live.noise.get(live.pix.image.key) ?? 0;
|
||||
const view = { scale: geo.scale ?? 1, fullW: whole.w, fullH: whole.h, win: geo.win ? padded : null };
|
||||
let out = drawKind(live.kind, vals, parts, view, noise);
|
||||
if (geo.win && (padded.w !== geo.win.w || padded.h !== geo.win.h)) {
|
||||
const at = insideOf(geo.win, padded);
|
||||
const cut = makeImage(shown.w, shown.h, out.c);
|
||||
for (let y = 0; y < shown.h; y += 1) {
|
||||
cut.data.set(out.data.subarray(((at.y + y) * out.w + at.x) * out.c, ((at.y + y) * out.w + at.x + shown.w) * out.c), y * shown.w * out.c);
|
||||
}
|
||||
out = cut;
|
||||
}
|
||||
draw(out);
|
||||
return finish(false);
|
||||
}
|
||||
|
||||
// The panel's refresh calls this. True: the live stage has the stage, so the
|
||||
// panel leaves it alone. False: the panel shows what it always showed.
|
||||
export function takeStage(state) {
|
||||
const live = state.live;
|
||||
if (!live?.alive) return false;
|
||||
live.watch();
|
||||
const found = describe(live);
|
||||
if (found.status === "none") {
|
||||
live.state.stage.classList.remove("live-on");
|
||||
live.drawn = false;
|
||||
syncView(live);
|
||||
return false;
|
||||
}
|
||||
if (found.status === "run") {
|
||||
showHint(live, hintFor(found.input));
|
||||
return true;
|
||||
}
|
||||
// Copying grain from a picture: the match comes from a run.
|
||||
if (live.kind === "grain" && copiesGrain(live.node) && !live.node.__ausbossMatch) {
|
||||
showHint(live, RUN_ONCE_MATCH);
|
||||
return true;
|
||||
}
|
||||
if (live.broken === found.key) {
|
||||
live.state.stage.classList.remove("live-on");
|
||||
live.drawn = false;
|
||||
syncView(live);
|
||||
return false;
|
||||
}
|
||||
if (live.loadedKey !== found.key) {
|
||||
if (live.loadingKey !== found.key) loadAll(live, found);
|
||||
// Until the pictures are read, what is on the stage stays.
|
||||
return live.drawn;
|
||||
}
|
||||
try {
|
||||
return paint(live, found);
|
||||
} catch (error) {
|
||||
live.broken = found.key;
|
||||
console.warn("[AusBoss] live preview off:", error?.message ?? error);
|
||||
live.state.stage.classList.remove("live-on");
|
||||
live.drawn = false;
|
||||
syncView(live);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
// The geometry of the live preview's two views (js/shared/live_stage.mjs):
|
||||
// Fit draws the whole picture on a downscaled copy, 100% draws a window of
|
||||
// real pixels you can pan. No DOM, so node:test covers it.
|
||||
|
||||
// Longest side of the copy Fit works on, however big the stage is.
|
||||
export const FIT_LONG_MAX = 1200;
|
||||
export const FIT_LONG_MIN = 32;
|
||||
|
||||
// Fit: the picture as large as the stage allows, never bigger than its own
|
||||
// size, and the size of the copy the node's maths runs on (the displayed
|
||||
// size in device pixels, so what is drawn is as sharp as it is shown).
|
||||
// Returns null while the stage has no size yet.
|
||||
export function fitGeometry(stageW, stageH, imageW, imageH, ratio = 1) {
|
||||
if (!(stageW > 0 && stageH > 0 && imageW > 0 && imageH > 0)) return null;
|
||||
const k = Math.min(1, stageW / imageW, stageH / imageH);
|
||||
const displayW = Math.max(1, Math.round(imageW * k));
|
||||
const displayH = Math.max(1, Math.round(imageH * k));
|
||||
const wanted = Math.min(FIT_LONG_MAX, Math.max(FIT_LONG_MIN, Math.round(Math.max(displayW, displayH) * Math.max(1, ratio))));
|
||||
const scale = Math.min(1, wanted / Math.max(imageW, imageH));
|
||||
return {
|
||||
displayW, displayH, scale,
|
||||
workW: Math.max(1, Math.round(imageW * scale)),
|
||||
workH: Math.max(1, Math.round(imageH * scale)),
|
||||
};
|
||||
}
|
||||
|
||||
// 100%: the window of real pixels the stage shows, and where it starts. One
|
||||
// picture pixel is one pixel of the stage. `pan` is the window's top-left
|
||||
// corner in picture pixels (null: centred).
|
||||
export function cropGeometry(stageW, stageH, imageW, imageH, pan = null) {
|
||||
if (!(stageW > 0 && stageH > 0 && imageW > 0 && imageH > 0)) return null;
|
||||
const w = Math.min(imageW, Math.floor(stageW));
|
||||
const h = Math.min(imageH, Math.floor(stageH));
|
||||
const clamp = (value, room) => Math.min(Math.max(Math.round(value), 0), room);
|
||||
return {
|
||||
w, h,
|
||||
x: clamp(pan ? pan.x : (imageW - w) / 2, imageW - w),
|
||||
y: clamp(pan ? pan.y : (imageH - h) / 2, imageH - h),
|
||||
};
|
||||
}
|
||||
|
||||
// The window grown by `reach` pixels each way, kept on the picture: what a
|
||||
// filter must read for the window's own pixels to come out as the whole
|
||||
// picture's would.
|
||||
export function paddedWindow(win, reach, imageW, imageH) {
|
||||
const x0 = Math.max(0, win.x - reach);
|
||||
const y0 = Math.max(0, win.y - reach);
|
||||
const x1 = Math.min(imageW, win.x + win.w + reach);
|
||||
const y1 = Math.min(imageH, win.y + win.h + reach);
|
||||
return { x: x0, y: y0, w: x1 - x0, h: y1 - y0 };
|
||||
}
|
||||
|
||||
// A window's pixels inside a padded window's, for cutting the padding off.
|
||||
export function insideOf(win, padded) {
|
||||
return { x: win.x - padded.x, y: win.y - padded.y, w: win.w, h: win.h };
|
||||
}
|
||||
|
||||
// One string for the values a result depends on, to tell whether the picture
|
||||
// on the node is the one the last run made.
|
||||
// Is the last run's result what the node would give now: the same values
|
||||
// and the same pictures (each Load Image's file, or the link a run reads)?
|
||||
export const runIsCurrent = (run, sig, sources) => Boolean(run) && run.sig === sig && run.sources === sources;
|
||||
|
||||
export function valuesSignature(node, names) {
|
||||
return JSON.stringify(names.map((name) => node?.widgets?.find((widget) => widget?.name === name)?.value ?? null));
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
@@ -51,6 +51,7 @@ export function normalizeRows(parsed) {
|
||||
const group = groupName(entry.group);
|
||||
if (group) row.group = group;
|
||||
if (group && entry.group_off === true) row.group_off = true;
|
||||
if (entry.curve === true) row.curve = true;
|
||||
}
|
||||
return row;
|
||||
}));
|
||||
@@ -68,6 +69,28 @@ export function serializeRows(rows) {
|
||||
return JSON.stringify(rows);
|
||||
}
|
||||
|
||||
// ---------- the strength curve ----------
|
||||
// A row with `curve` follows the Strength Curve wired into the loader's
|
||||
// `curve` input: its model strength is scaled step by step
|
||||
// (nodes/_lora_helpers.py). A row without it keeps one strength all the way.
|
||||
|
||||
// The rows with these ids made to follow the curve (on) or keep steady.
|
||||
export function followCurve(rows, ids, on) {
|
||||
return rows.map((row) => {
|
||||
if (!ids.includes(row.id)) return row;
|
||||
if (on) return { ...row, curve: true };
|
||||
const { curve, ...rest } = row;
|
||||
return rest;
|
||||
});
|
||||
}
|
||||
|
||||
// A curve wired into a loader where no row follows one yet: every row does.
|
||||
// Once any row is marked the person has chosen, and nothing changes.
|
||||
export function rowsForNewCurve(rows) {
|
||||
if (rows.some((row) => row.curve)) return rows;
|
||||
return followCurve(rows, rows.map((row) => row.id), true);
|
||||
}
|
||||
|
||||
export function reorderRows(rows, from, to) {
|
||||
if (from === to) return rows;
|
||||
if (from < 0 || from >= rows.length || to < 0 || to >= rows.length) return rows;
|
||||
|
||||
+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 };
|
||||
}
|
||||
|
||||
@@ -31,8 +31,10 @@ export function stripRows(report) {
|
||||
}));
|
||||
}
|
||||
|
||||
// A time typed at the start of a line: 3s:, 3 s, at 3 seconds, [3s].
|
||||
const TYPED_TIME = /^\[?(?:at\s+)?\d+(?:\.\d+)?\s*(?:seconds?|secs?|s)\b\]?\s*[:,\-]?\s*/i;
|
||||
// A time typed at the start of a line: 3s:, 3s, at 3 seconds, [3s]. As in the
|
||||
// writer, a spelled-out time needs its mark: "7 seconds remain" is an action.
|
||||
const TYPED_TIME =
|
||||
/^(?:\[\s*\d+(?:\.\d+)?\s*(?:seconds?|secs?|s)\b\s*\]\s*[:,\-]?|at\s+\d+(?:\.\d+)?\s*(?:seconds?|secs?|s)\b\s*[:,\-]?|\d+(?:\.\d+)?\s*(?:seconds?|secs?|s)\b\s*[:,\-](?!\d)|\d+(?:\.\d+)?(?:s|secs?)\b)\s*/i;
|
||||
|
||||
// The script with one line set to start at a second: its old time, if any,
|
||||
// gives way to the new one. line counts typed lines from 0.
|
||||
@@ -70,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) {
|
||||
|
||||
@@ -248,7 +248,50 @@ export function chipMatch(width, height, ratio, tolerance = 0.015) {
|
||||
// Parse the gear menu's editable rail text ("1:1, 4:3, 7:4") into ratio
|
||||
// objects; junk entries drop, duplicates collapse, and an empty result
|
||||
// falls back to the shipped defaults so the rail can never vanish.
|
||||
export const DEFAULT_RAIL = "1:1, 4:3, 3:2, 16:9, 7:4, 2:1";
|
||||
// The rail setting is one comma list in chip order. A ratio saved with a
|
||||
// leading "-" ("-21:9") stays in the gear's list but is not shown as a chip;
|
||||
// parseRail skips it, so an older reader of the setting just sees fewer chips.
|
||||
export const DEFAULT_RAIL = "1:1, 4:3, 3:2, 16:9, 7:4, 2:1, -5:4, -21:9";
|
||||
export const RAIL_MAX = 24;
|
||||
|
||||
// One typed ratio ("21:9", "21x9", "9 : 21") as a landscape entry: the flip
|
||||
// button sets the orientation, so 9:16 and 16:9 are the same chip.
|
||||
export function parseRatioToken(text) {
|
||||
const match = String(text ?? "").trim().match(/^(\d{1,3})\s*[:x×]\s*(\d{1,3})$/i);
|
||||
if (!match) return null;
|
||||
const a = Number(match[1]);
|
||||
const b = Number(match[2]);
|
||||
if (!a || !b) return null;
|
||||
const long = Math.max(a, b);
|
||||
const short = Math.min(a, b);
|
||||
const d = gcd(long, short);
|
||||
return { x: long / d, y: short / d, label: `${long}:${short}` };
|
||||
}
|
||||
|
||||
export function ratioKey(ratio) {
|
||||
return `${Math.max(ratio.x, ratio.y)}:${Math.min(ratio.x, ratio.y)}`;
|
||||
}
|
||||
|
||||
// Every ratio in the rail setting, in order, with `on` false for the hidden
|
||||
// ones. With nothing to show it falls back to the shipped list, the same
|
||||
// way parseRail does.
|
||||
export function railEntries(text) {
|
||||
const seen = new Set();
|
||||
const entries = [];
|
||||
for (const raw of String(text ?? "").split(",")) {
|
||||
const token = raw.trim();
|
||||
const on = !token.startsWith("-");
|
||||
const ratio = parseRatioToken(on ? token : token.slice(1));
|
||||
if (!ratio || seen.has(ratioKey(ratio)) || entries.length >= RAIL_MAX) continue;
|
||||
seen.add(ratioKey(ratio));
|
||||
entries.push({ ...ratio, on });
|
||||
}
|
||||
return entries.some((entry) => entry.on) ? entries : railEntries(DEFAULT_RAIL);
|
||||
}
|
||||
|
||||
export function railText(entries) {
|
||||
return entries.map((entry) => `${entry.on ? "" : "-"}${entry.label}`).join(", ");
|
||||
}
|
||||
|
||||
export function parseRail(text) {
|
||||
const seen = new Set();
|
||||
@@ -274,9 +317,23 @@ export function parseRail(text) {
|
||||
export function orientRatio(ratio, portrait) {
|
||||
const long = Math.max(ratio.x, ratio.y), short = Math.min(ratio.x, ratio.y);
|
||||
const x = portrait ? short : long, y = portrait ? long : short;
|
||||
// Keep the name the ratio was given: 21:9 stays 21:9, not 7:3.
|
||||
const named = String(ratio.label ?? "").split(":").map(Number);
|
||||
if (named.length === 2 && named.every(n => n > 0) && named[0] * ratio.y === named[1] * ratio.x) {
|
||||
const [a, b] = [Math.max(...named), Math.min(...named)];
|
||||
return { x, y, label: portrait ? `${b}:${a}` : `${a}:${b}` };
|
||||
}
|
||||
return { x, y, label: `${x}:${y}` };
|
||||
}
|
||||
|
||||
// The readout's name for a size: a rail ratio's own name when the size is
|
||||
// exactly on it (1568x672 reads 21:9, as its chip does), else ratioLabel.
|
||||
export function railRatioLabel(width, height, rail) {
|
||||
const { x, y } = reduceRatio(width, height);
|
||||
const match = (rail ?? []).find(r => (r.x === x && r.y === y) || (r.x === y && r.y === x));
|
||||
return match ? orientRatio(match, height > width).label : ratioLabel(width, height);
|
||||
}
|
||||
|
||||
// ---------- quick sizes ----------
|
||||
|
||||
// The per-ratio quick list, anchored to the canonical square areas
|
||||
|
||||
@@ -136,7 +136,8 @@ function ensureSettingsCss() {
|
||||
.ausboss-set-dl .term { color: ${BRAND}; font-weight: 600; }
|
||||
.ausboss-set-dl .detail { color: #9ba2aa; line-height: 1.4; }
|
||||
.ausboss-set-btn { height: 24px; border: 1px solid #3a4047; border-radius: 5px;
|
||||
background: #23272c; color: #d7dde2; cursor: pointer; padding: 0 12px; font: inherit; }
|
||||
background: #23272c; color: #d7dde2; cursor: pointer; padding: 0 12px; font: inherit;
|
||||
white-space: nowrap; flex: none; }
|
||||
.ausboss-set-btn:hover { border-color: ${BRAND}; }
|
||||
.ausboss-set-btn.primary { margin-left: auto; border-color: ${BRAND}; color: ${BRAND}; }
|
||||
.ausboss-set-btn.primary:hover { background: ${BRAND}; color: #08211f; }
|
||||
|
||||
@@ -0,0 +1,160 @@
|
||||
// Strength Curve's points and line, shared by its face and its tests. No
|
||||
// DOM and no ComfyUI imports, so node:test loads it as it is.
|
||||
//
|
||||
// The same curve as nodes/_curve_helpers.py: points from 0 to 1 joined by a
|
||||
// monotone cubic (Fritsch and Carlson), which never swings past a point. The
|
||||
// face draws what the node will output.
|
||||
|
||||
export const MAX_POINTS = 32;
|
||||
// Two points never sit closer than this along the run.
|
||||
export const MIN_GAP = 0.01;
|
||||
|
||||
export const PRESETS = Object.freeze([
|
||||
{ name: "flat", title: "The same strength all the way", points: [[0, 1], [1, 1]] },
|
||||
{ name: "fade out", title: "Full at the start, gone at the end", points: [[0, 1], [1, 0]] },
|
||||
{ name: "fade in", title: "Off at the start, full at the end", points: [[0, 0], [1, 1]] },
|
||||
{ name: "ease out", title: "Holds, fades out smoothly through the middle, then stays low", points: [[0, 1], [0.25, 0.92], [0.75, 0.08], [1, 0]] },
|
||||
{ name: "ease in", title: "Stays low, comes in smoothly through the middle, then holds", points: [[0, 0], [0.25, 0.08], [0.75, 0.92], [1, 1]] },
|
||||
]);
|
||||
|
||||
const clamp01 = (value) => Math.min(1, Math.max(0, value));
|
||||
|
||||
// Clean, sorted points that start at 0 and end at 1, as the backend reads
|
||||
// them. Anything that cannot be read is a flat line at 1.
|
||||
export function parsePoints(raw) {
|
||||
let data = raw;
|
||||
if (typeof raw === "string") {
|
||||
try { data = raw.trim() ? JSON.parse(raw) : []; } catch { data = []; }
|
||||
}
|
||||
if (!Array.isArray(data)) data = [];
|
||||
const found = new Map();
|
||||
for (const entry of data.slice(0, MAX_POINTS)) {
|
||||
const pair = Array.isArray(entry) ? entry : [entry?.x, entry?.y];
|
||||
const x = Number(pair[0]);
|
||||
const y = Number(pair[1]);
|
||||
if (!Number.isFinite(x) || !Number.isFinite(y)) continue;
|
||||
found.set(clamp01(x), clamp01(y));
|
||||
}
|
||||
const points = [...found.entries()].sort((a, b) => a[0] - b[0]);
|
||||
if (!points.length) return [[0, 1], [1, 1]];
|
||||
if (points[0][0] > 0) points.unshift([0, points[0][1]]);
|
||||
if (points[points.length - 1][0] < 1) points.push([1, points[points.length - 1][1]]);
|
||||
return points;
|
||||
}
|
||||
|
||||
// Rounded so a saved value stays short and reads back the same.
|
||||
const tidy = (value) => Math.round(value * 10000) / 10000;
|
||||
export const pointsText = (points) => JSON.stringify(points.map(([x, y]) => [tidy(x), tidy(y)]));
|
||||
|
||||
function slopes(xs, ys) {
|
||||
const count = xs.length;
|
||||
const secants = [];
|
||||
for (let i = 0; i < count - 1; i++) secants.push((ys[i + 1] - ys[i]) / (xs[i + 1] - xs[i]));
|
||||
const out = new Array(count).fill(0);
|
||||
out[0] = secants[0];
|
||||
out[count - 1] = secants[count - 2];
|
||||
for (let i = 1; i < count - 1; i++) {
|
||||
out[i] = secants[i - 1] * secants[i] <= 0 ? 0 : (secants[i - 1] + secants[i]) / 2;
|
||||
}
|
||||
secants.forEach((secant, i) => {
|
||||
if (secant === 0) { out[i] = 0; out[i + 1] = 0; return; }
|
||||
const a = out[i] / secant;
|
||||
const b = out[i + 1] / secant;
|
||||
const length = a * a + b * b;
|
||||
if (length > 9) {
|
||||
const scale = 3 / Math.sqrt(length);
|
||||
out[i] = scale * a * secant;
|
||||
out[i + 1] = scale * b * secant;
|
||||
}
|
||||
});
|
||||
return out;
|
||||
}
|
||||
|
||||
// The curve's value (0..1) at each place (0..1).
|
||||
export function curveValues(points, places) {
|
||||
const xs = points.map((point) => point[0]);
|
||||
const ys = points.map((point) => point[1]);
|
||||
if (points.length < 2) return places.map(() => ys[0] ?? 1);
|
||||
const m = slopes(xs, ys);
|
||||
return places.map((raw) => {
|
||||
const place = clamp01(Number(raw));
|
||||
let piece = 0;
|
||||
while (piece < xs.length - 2 && place > xs[piece + 1]) piece += 1;
|
||||
const width = xs[piece + 1] - xs[piece];
|
||||
const t = (place - xs[piece]) / width;
|
||||
const t2 = t * t;
|
||||
const t3 = t2 * t;
|
||||
const value = (2 * t3 - 3 * t2 + 1) * ys[piece] + (t3 - 2 * t2 + t) * width * m[piece]
|
||||
+ (-2 * t3 + 3 * t2) * ys[piece + 1] + (t3 - t2) * width * m[piece + 1];
|
||||
return clamp01(value);
|
||||
});
|
||||
}
|
||||
|
||||
export const curveAt = (points, place) => curveValues(points, [place])[0];
|
||||
|
||||
// The preset these points are, or "" for a hand-drawn curve.
|
||||
export function presetOf(points) {
|
||||
const same = (a, b) => a.length === b.length && a.every((p, i) => Math.abs(p[0] - b[i][0]) < 1e-4 && Math.abs(p[1] - b[i][1]) < 1e-4);
|
||||
return PRESETS.find((preset) => same(points, preset.points))?.name ?? "";
|
||||
}
|
||||
|
||||
// Move one point. The two ends stay at the start and the end of the run;
|
||||
// a point between them stays between its neighbours.
|
||||
export function movePoint(points, index, x, y) {
|
||||
const next = points.map((point) => [...point]);
|
||||
const last = next.length - 1;
|
||||
if (index < 0 || index > last) return next;
|
||||
let place = clamp01(Number(x));
|
||||
if (index === 0) place = 0;
|
||||
else if (index === last) place = 1;
|
||||
else place = Math.min(next[index + 1][0] - MIN_GAP, Math.max(next[index - 1][0] + MIN_GAP, place));
|
||||
next[index] = [place, clamp01(Number(y))];
|
||||
return next;
|
||||
}
|
||||
|
||||
// Add a point; gives the new points and the new point's index, or null when
|
||||
// there is no room (too many points, or too close to one).
|
||||
export function addPoint(points, x, y) {
|
||||
if (points.length >= MAX_POINTS) return null;
|
||||
const place = clamp01(Number(x));
|
||||
if (points.some((point) => Math.abs(point[0] - place) < MIN_GAP)) return null;
|
||||
const next = [...points.map((point) => [...point]), [place, clamp01(Number(y))]].sort((a, b) => a[0] - b[0]);
|
||||
return { points: next, index: next.findIndex((point) => point[0] === place) };
|
||||
}
|
||||
|
||||
// Remove a point between the ends; the ends always stay.
|
||||
export function removePoint(points, index) {
|
||||
if (index <= 0 || index >= points.length - 1) return points.map((point) => [...point]);
|
||||
return points.filter((_, i) => i !== index).map((point) => [...point]);
|
||||
}
|
||||
|
||||
// The strength a value of the box (0..1) stands for.
|
||||
export const strengthOf = (value, low, high) => Number(low) + (Number(high) - Number(low)) * value;
|
||||
|
||||
// Where the hover readout goes: beside the spot under the pointer, on the
|
||||
// first side that covers no point (above right, above left, below right,
|
||||
// below left), kept inside the box. With every side covered, the one that
|
||||
// covers the fewest points. All in the stage's pixels; `box` is
|
||||
// { left, top, right, bottom } and each point is [x, y].
|
||||
export function tagPlace({ x, y, width, height, box, points = [], radius = 7, gap = 6 }) {
|
||||
const fit = (left, top) => ({
|
||||
left: Math.min(box.right - width, Math.max(box.left, left)),
|
||||
top: Math.min(box.bottom - height, Math.max(box.top, top)),
|
||||
});
|
||||
const covers = ({ left, top }) => points.filter(([px, py]) =>
|
||||
px + radius > left && px - radius < left + width && py + radius > top && py - radius < top + height).length;
|
||||
const sides = [
|
||||
fit(x + gap, y - height - gap),
|
||||
fit(x - gap - width, y - height - gap),
|
||||
fit(x + gap, y + gap),
|
||||
fit(x - gap - width, y + gap),
|
||||
];
|
||||
let best = sides[0];
|
||||
let fewest = Infinity;
|
||||
for (const side of sides) {
|
||||
const count = covers(side);
|
||||
if (count === 0) return side;
|
||||
if (count < fewest) { best = side; fewest = count; }
|
||||
}
|
||||
return best;
|
||||
}
|
||||
@@ -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 = () => {
|
||||
|
||||
@@ -6,6 +6,7 @@ import { hideInputsInDef, hideWidget } from "./widget_visibility.mjs";
|
||||
import { mountTransformTrim } from "./transform_trim.mjs";
|
||||
import { mountClipWindow } from "./clip_window.mjs";
|
||||
import { clipOutputRate, inputNumber } from "./clip_rate.mjs";
|
||||
import { wiredFieldText, wiredNumber, wiredResize, wiredSummaryParts, wiredSwitch } from "./transform_wired.mjs";
|
||||
import { BRAND, chainCallback, keepDomWidgetWidthAuto, notifyAusbossChange, showToast } from "./index.mjs";
|
||||
import { WIDGET_FRAME, fillNodeHeight, holdVueNodeMinWidth, holdVuePanelMinHeight } from "./panel_layout.mjs";
|
||||
import { mediaViewQuery, unlistedMedia } from "./media_list.mjs";
|
||||
@@ -191,6 +192,7 @@ function installStyles() {
|
||||
.ausboss-transform-group-title{display:inline-flex;align-items:center;gap:6px;letter-spacing:.05em;text-transform:uppercase;white-space:nowrap}
|
||||
.ausboss-transform-group-caret{display:inline-block;color:${BRAND};font-size:11px;transition:transform .14s ease}
|
||||
.ausboss-transform-group.open .ausboss-transform-group-caret{transform:rotate(90deg)}
|
||||
.ausboss-transform-wired{display:inline-flex;align-items:center;justify-content:flex-end;min-height:24px;padding:0 6px;border:1px dashed #3a5352;border-radius:5px;color:#8ca8a5;font:500 11px system-ui;font-variant-numeric:tabular-nums;white-space:nowrap;cursor:default}
|
||||
.ausboss-transform-group-summary{display:inline-flex;align-items:center;gap:6px;min-width:0;color:#8ca8a5;font:500 11px system-ui;font-variant-numeric:tabular-nums;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||||
.ausboss-transform-group-swatch{flex:none;width:10px;height:10px;border:1px solid #555b63;border-radius:3px;box-sizing:border-box}
|
||||
.ausboss-transform-group-meta{min-width:0;overflow:hidden;text-overflow:ellipsis}
|
||||
@@ -632,16 +634,9 @@ export function transformGroupSummary(state) {
|
||||
parts.push(`Custom ${ratioLabel(canvas.width, canvas.height)}`);
|
||||
}
|
||||
if (lockActive(state)) parts.push("held");
|
||||
const feather = Math.round(Number(value(node, "feather", 0)) || 0);
|
||||
if (feather > 0) parts.push(`feather ${feather} px`);
|
||||
const multiple = Math.round(Number(value(node, "canvas_multiple", 1)) || 1);
|
||||
if (multiple > 1) parts.push(`÷${multiple}`);
|
||||
if (widget(node, "resize_to_megapixels") && value(node, "resize_to_megapixels", false)) {
|
||||
const mp = Number(value(node, "megapixels", 1)) || 1;
|
||||
const steps = Math.round(Number(value(node, "resolution_steps", 1)) || 1);
|
||||
parts.push(`${mp.toFixed(2)} MP`);
|
||||
if (steps > 1 && multiple <= 1) parts.push(`÷${steps}`);
|
||||
}
|
||||
// Feather, Align and the resize as the run uses them: a linked input runs
|
||||
// with the wired value, not the widget's own (js/shared/transform_wired.mjs).
|
||||
parts.push(...wiredSummaryParts(node));
|
||||
return parts.join(" · ");
|
||||
}
|
||||
|
||||
@@ -933,6 +928,13 @@ export function installTransformNode(node, kind, mountPanel = null) {
|
||||
for (const trim of state.trimViews) trim.sync();
|
||||
}
|
||||
}
|
||||
// A wired value changed upstream (a Float typed to 24): the summary,
|
||||
// the face fields and the size readout follow it.
|
||||
if (!state.disposed) {
|
||||
const wired = JSON.stringify([wiredSummaryParts(node), wiredResize(node)]);
|
||||
if (state.wiredKey !== undefined && wired !== state.wiredKey) queueMicrotask(() => { if (!state.disposed) draw(state); });
|
||||
state.wiredKey = wired;
|
||||
}
|
||||
if (state.disposed || state.zoomRedraw || !panelBackingStale(state)) return;
|
||||
state.zoomRedraw = requestAnimationFrame(() => { state.zoomRedraw = null; if (!state.disposed) draw(state); });
|
||||
});
|
||||
@@ -956,6 +958,7 @@ export function installTransformNode(node, kind, mountPanel = null) {
|
||||
}
|
||||
chainCallback(node, "onConnectionsChange", () => queueMicrotask(() => {
|
||||
for (const trim of state.trimViews) trim.sync();
|
||||
if (!state.disposed) draw(state);
|
||||
}));
|
||||
chainCallback(node, "onConfigure", () => queueMicrotask(() => {
|
||||
if (state.disposed) return;
|
||||
@@ -1514,6 +1517,12 @@ function buildCanvasRow(state) {
|
||||
stepLabel.append(createElement("span", "", "Step"), steps.root);
|
||||
const hasResize = Boolean(widget(node, "resize_to_megapixels"));
|
||||
resizeRow.append(resizeLabel, budgetLabel, stepLabel);
|
||||
const wired = [
|
||||
wiredStandIn(node, "feather", feather, 0, (amount) => `${Math.round(amount)} px`),
|
||||
wiredStandIn(node, "canvas_multiple", multiple, 1, (amount) => `${Math.round(amount)} px`),
|
||||
wiredStandIn(node, "megapixels", budget, 1, (amount) => `${Number(amount).toFixed(2)} MP`),
|
||||
wiredStandIn(node, "resolution_steps", steps, 1, (amount) => `${Math.round(amount)} px`),
|
||||
];
|
||||
const sync = () => {
|
||||
fill.value = normalizeColor(value(node, "fill_color", "#808080"));
|
||||
fill.title = `${fill.title.split(" Now ")[0]} Now ${fill.value}.`;
|
||||
@@ -1523,7 +1532,9 @@ function buildCanvasRow(state) {
|
||||
resize.sync();
|
||||
budget.set(value(node, "megapixels", 1));
|
||||
steps.set(value(node, "resolution_steps", 1));
|
||||
const resizeOn = hasResize && Boolean(value(node, "resize_to_megapixels", false));
|
||||
for (const standIn of wired) standIn();
|
||||
const switched = wiredSwitch(node, "resize_to_megapixels", false);
|
||||
const resizeOn = hasResize && (!switched.known || Boolean(switched.value));
|
||||
resizeRow.style.display = hasResize ? "" : "none";
|
||||
budgetLabel.style.display = resizeOn ? "" : "none";
|
||||
stepLabel.style.display = resizeOn ? "" : "none";
|
||||
@@ -1537,6 +1548,22 @@ function buildCanvasRow(state) {
|
||||
return [alignRow, row, resizeRow];
|
||||
}
|
||||
|
||||
// A linked setting runs with the wired value, so its number box gives way to
|
||||
// that value (or "from a link" when only the run knows it). The box stays the
|
||||
// way to set the widget's own value once the link is gone. Returns the sync.
|
||||
function wiredStandIn(node, name, control, fallback, format) {
|
||||
const text = createElement("span", "ausboss-transform-wired");
|
||||
text.title = t("Set by a link into this input. Remove the link to type a value here.");
|
||||
text.style.display = "none";
|
||||
control.root.after(text);
|
||||
return () => {
|
||||
const shown = wiredFieldText(wiredNumber(node, name, fallback), format);
|
||||
control.root.style.display = shown === null ? "" : "none";
|
||||
text.style.display = shown === null ? "none" : "";
|
||||
if (shown !== null) text.textContent = shown === "from a link" ? t("from a link") : shown;
|
||||
};
|
||||
}
|
||||
|
||||
// Resize as an off | on pill, on the node face and in the editor.
|
||||
function resizeSwitch(state) {
|
||||
const node = state.node;
|
||||
@@ -1577,7 +1604,7 @@ function syncReadout(state) {
|
||||
const source = rotatedSize(state.sourceWidth, state.sourceHeight, current.rotation_degrees);
|
||||
const resize = resizeRequest(state.node);
|
||||
const chain = sizeChain(current, source, resize);
|
||||
const { tokens, warnings } = litTokens(state, sizeChainTokens(chain));
|
||||
const { tokens, warnings } = readoutTokens(state, chain);
|
||||
const prefix = createElement("span", "ausboss-transform-ellipsis");
|
||||
tokens.forEach((token, index) => {
|
||||
if (index) prefix.append(" → ");
|
||||
@@ -2334,6 +2361,12 @@ function buildControls(state, sidebar) {
|
||||
previewSection.append(finalPreview);
|
||||
state.finalPreviewCanvas = finalPreview;
|
||||
|
||||
const editorWired = [
|
||||
wiredStandIn(node, "feather", featherNumber, 24, (amount) => `${Math.round(amount)} px`),
|
||||
wiredStandIn(node, "canvas_multiple", multiple, 1, (amount) => `${Math.round(amount)} px`),
|
||||
...(budget ? [wiredStandIn(node, "megapixels", budget, 1, (amount) => `${Number(amount).toFixed(2)} MP`)] : []),
|
||||
...(steps ? [wiredStandIn(node, "resolution_steps", steps, 1, (amount) => `${Math.round(amount)} px`)] : []),
|
||||
];
|
||||
sidebar.append(cropSection, rotateSection, padSection);
|
||||
if (resizeSection) sidebar.append(resizeSection);
|
||||
sidebar.append(actions, previewSection);
|
||||
@@ -2343,6 +2376,7 @@ function buildControls(state, sidebar) {
|
||||
featherNumber.set(value(node, "feather", 24));
|
||||
multiple.set(value(node, "canvas_multiple", 1)); color.value = normalizeColor(value(node, "fill_color", "#808080"));
|
||||
resize?.sync(); budget?.set(value(node, "megapixels", 1)); steps?.set(value(node, "resolution_steps", 1));
|
||||
for (const standIn of editorWired) standIn();
|
||||
if (more) more.value = extra.includes(liveRequest(state) ?? "") ? liveRequest(state) : "";
|
||||
};
|
||||
}
|
||||
@@ -2891,10 +2925,23 @@ function drawScene(context, state, render, compact, interactive) {
|
||||
context.restore();
|
||||
}
|
||||
|
||||
// The resize the run makes, wired values included; null when it is off or a
|
||||
// link decides a part of it that only the run knows (resizeFromLink).
|
||||
function resizeRequest(node) {
|
||||
return value(node, "resize_to_megapixels", false)
|
||||
? { megapixels: value(node, "megapixels", 1), steps: value(node, "resolution_steps", 1) }
|
||||
: null;
|
||||
const resize = wiredResize(node);
|
||||
return resize && !resize.unknown ? resize : null;
|
||||
}
|
||||
|
||||
function resizeFromLink(node) {
|
||||
return Boolean(wiredResize(node)?.unknown);
|
||||
}
|
||||
|
||||
// The size chain's steps, ending on a resize a link decides when it does:
|
||||
// the size it lands on is only known at run time.
|
||||
function readoutTokens(state, chain) {
|
||||
const result = litTokens(state, sizeChainTokens(chain));
|
||||
if (resizeFromLink(state.node)) result.tokens = [...result.tokens, { label: "resize", text: "from a link" }];
|
||||
return result;
|
||||
}
|
||||
|
||||
// The size readout, drawn OUTSIDE the image: under the output rect, above
|
||||
@@ -2905,7 +2952,7 @@ function resizeRequest(node) {
|
||||
// amber line when the steps stretch the picture or the resize undoes Align.
|
||||
const READOUT_LINE = 15;
|
||||
function drawOutputSize(context, state, render) {
|
||||
const { tokens } = litTokens(state, sizeChainTokens(sizeChain(values(state.node), render.source, resizeRequest(state.node))));
|
||||
const { tokens } = readoutTokens(state, sizeChain(values(state.node), render.source, resizeRequest(state.node)));
|
||||
// The amber line is the settled note, as on the face: it waits for the hand.
|
||||
const warnings = shownNote(state).warnings;
|
||||
const { outputRect } = render;
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
// What the Crop + Rotate + Pad nodes will really use for a setting that can
|
||||
// be wired: a linked input runs with the wired value, not the widget's own.
|
||||
// A wired value also skips the input's range (ComfyUI only range-checks typed
|
||||
// values), so a Float of 24 wired into Megapixels resizes to 24 MP while the
|
||||
// widget still holds 16.
|
||||
//
|
||||
// Only typed numbers are read across the wire (clip_rate.mjs inputNumber):
|
||||
// a calculated value (Math Expression) stays unknown until the run, and the
|
||||
// face says the value comes from a link instead of showing a wrong one.
|
||||
//
|
||||
// Pure: reads `inputs`, `widgets` and `graph`, so tests run it on plain
|
||||
// objects.
|
||||
|
||||
import { inputNumber, linkOrigin } from "./clip_rate.mjs";
|
||||
|
||||
function widgetValue(node, name, fallback) {
|
||||
return node?.widgets?.find((item) => item.name === name)?.value ?? fallback;
|
||||
}
|
||||
|
||||
export function inputLinked(node, name) {
|
||||
const slot = node?.inputs?.find((input) => input?.name === name || input?.widget?.name === name);
|
||||
return slot?.link !== null && slot?.link !== undefined;
|
||||
}
|
||||
|
||||
// { value, linked, known } for a number setting. Unlinked: the widget's
|
||||
// value. Linked to a typed number: that number. Linked to anything else:
|
||||
// value null, known false.
|
||||
export function wiredNumber(node, name, fallback) {
|
||||
const own = widgetValue(node, name, fallback);
|
||||
if (!inputLinked(node, name)) return { value: own, linked: false, known: true };
|
||||
const read = inputNumber(node, name, own);
|
||||
return read === null ? { value: null, linked: true, known: false } : { value: read, linked: true, known: true };
|
||||
}
|
||||
|
||||
const SWITCHES = ["PrimitiveBoolean"];
|
||||
|
||||
// The same for an on/off setting.
|
||||
export function wiredSwitch(node, name, fallback) {
|
||||
const own = Boolean(widgetValue(node, name, fallback));
|
||||
if (!inputLinked(node, name)) return { value: own, linked: false, known: true };
|
||||
const origin = linkOrigin(node, name);
|
||||
const unknown = { value: null, linked: true, known: false };
|
||||
if (!origin) return unknown;
|
||||
const { node: source, slot } = origin;
|
||||
let read;
|
||||
if ((source.comfyClass ?? source.type) === "PrimitiveNode") read = source.widgets?.[0]?.value;
|
||||
else if (SWITCHES.includes(source.type) && slot === 0
|
||||
&& !source.inputs?.some((input) => input.name === "value" && input.link != null)) {
|
||||
read = source.widgets?.find((item) => item.name === "value")?.value;
|
||||
}
|
||||
return typeof read === "boolean" ? { value: read, linked: true, known: true } : unknown;
|
||||
}
|
||||
|
||||
// The resize the run makes: null when it is off, { megapixels, steps } when
|
||||
// every part is known, { unknown: true } when a link decides a part of it.
|
||||
export function wiredResize(node) {
|
||||
if (!node?.widgets?.some((item) => item.name === "resize_to_megapixels")) return null;
|
||||
const on = wiredSwitch(node, "resize_to_megapixels", false);
|
||||
if (on.known && !on.value) return null;
|
||||
const megapixels = wiredNumber(node, "megapixels", 1);
|
||||
const steps = wiredNumber(node, "resolution_steps", 1);
|
||||
if (!on.known || !megapixels.known || !steps.known) return { unknown: true };
|
||||
return { megapixels: Number(megapixels.value) || 1, steps: Number(steps.value) || 1 };
|
||||
}
|
||||
|
||||
// The end of the "Crop, pad & resize" summary: feather, Align, and the
|
||||
// resize, each as the run will use it.
|
||||
export function wiredSummaryParts(node) {
|
||||
const parts = [];
|
||||
const feather = wiredNumber(node, "feather", 0);
|
||||
if (!feather.known) parts.push("feather from a link");
|
||||
else if (Math.round(Number(feather.value) || 0) > 0) parts.push(`feather ${Math.round(Number(feather.value))} px`);
|
||||
const multiple = wiredNumber(node, "canvas_multiple", 1);
|
||||
const align = multiple.known ? Math.round(Number(multiple.value) || 1) : null;
|
||||
if (align === null) parts.push("align from a link");
|
||||
else if (align > 1) parts.push(`÷${align}`);
|
||||
if (!node?.widgets?.some((item) => item.name === "resize_to_megapixels")) return parts;
|
||||
const on = wiredSwitch(node, "resize_to_megapixels", false);
|
||||
if (on.known && !on.value) return parts;
|
||||
if (!on.known) parts.push("resize from a link");
|
||||
const megapixels = wiredNumber(node, "megapixels", 1);
|
||||
parts.push(megapixels.known ? `${(Number(megapixels.value) || 1).toFixed(2)} MP` : "MP from a link");
|
||||
const steps = wiredNumber(node, "resolution_steps", 1);
|
||||
if (!steps.known) parts.push("step from a link");
|
||||
else if (Math.round(Number(steps.value) || 1) > 1 && align !== null && align <= 1) parts.push(`÷${Math.round(Number(steps.value))}`);
|
||||
return parts;
|
||||
}
|
||||
|
||||
// What a face field shows for a linked setting in place of its number box:
|
||||
// the wired number, or that a link sets it.
|
||||
export function wiredFieldText(reading, format) {
|
||||
if (!reading.linked) return null;
|
||||
return reading.known ? format(reading.value) : "from a link";
|
||||
}
|
||||
@@ -106,6 +106,7 @@ export function ensureCardCss() {
|
||||
.ausboss-card-field>.ausboss-scrub{flex:1 1 0;width:auto;min-width:0}
|
||||
.ausboss-card-field>.ausboss-scrub .ausboss-scrub-input{width:100%}
|
||||
.ausboss-card-sep{flex:none;color:${T.faint};font-size:11px}
|
||||
.ausboss-card-note{flex:none;min-width:58px;color:${T.faint};font:600 10px ${FONT};font-variant-numeric:tabular-nums;white-space:nowrap;user-select:none}
|
||||
.ausboss-card-suffix{flex:none;color:${T.faint};font:600 10px ${FONT};letter-spacing:.1em;text-transform:uppercase;user-select:none}
|
||||
.ausboss-card-section{height:${SECTION_HEIGHT}px;flex:none;display:flex;align-items:flex-end;gap:8px;color:${T.faint};font:600 10px/1 ${FONT};letter-spacing:.1em;text-transform:uppercase;user-select:none}
|
||||
.ausboss-card-section::after{content:"";flex:1;height:1px;margin-bottom:4px;background:${T.rule}}
|
||||
@@ -124,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}}
|
||||
@@ -189,6 +190,7 @@ function isFloatWidget(widget) {
|
||||
|
||||
// Mount a card on `node`. Rows:
|
||||
// { widget, label?, kind?, labels?, suffix?, title?, when?, group?, linkedBy?, snap?, pixels?, step?, limits?, trimZeros? }
|
||||
// - `when(values, node)` shows the row
|
||||
// - `linkedBy` names other inputs
|
||||
// whose link also dims the row
|
||||
// (a wired source replacing a
|
||||
@@ -207,6 +209,8 @@ function isFloatWidget(widget) {
|
||||
// `trimZeros` drops the zeroes
|
||||
// the steps never reach (1.00,
|
||||
// not 1.000)
|
||||
// - `note(node, values)` is small
|
||||
// type after the control ("= 0.27")
|
||||
// { widget, kind: "textarea", placeholder?, height, grow?, looks? }
|
||||
// - a multiline string; `grow` takes
|
||||
// the node's spare height; `looks`
|
||||
@@ -344,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];
|
||||
@@ -402,16 +415,20 @@ export function mountWidgetCard(node, { rows, minWidth = 300, first = false, hid
|
||||
seg.setAttribute("role", "radiogroup");
|
||||
const label = (text, fallback) => (typeof text === "string" && text.length <= SWITCH_LABEL_MAX ? text : fallback);
|
||||
const buttons = new Map();
|
||||
for (const [value, text] of [[false, label(row.offText, "off")], [true, label(row.onText, "on")]]) {
|
||||
// `onText` may be a function of the node, read at every refresh (Film
|
||||
// Grain's Auto reads "match" while a picture to copy from is wired).
|
||||
const onText = () => label(typeof row.onText === "function" ? row.onText(node) : row.onText, "on");
|
||||
for (const [value, text] of [[false, label(row.offText, "off")], [true, onText()]]) {
|
||||
const button = el("button", "", text);
|
||||
button.type = "button";
|
||||
button.title = row.title ?? (widgetTooltip(node, name, widget) || (value ? row.onText ?? "" : row.offText ?? ""));
|
||||
button.title = row.title ?? (widgetTooltip(node, name, widget) || (value ? (typeof row.onText === "string" ? row.onText : "") : row.offText ?? ""));
|
||||
button.addEventListener("click", () => setWidget(name, value));
|
||||
seg.append(button); buttons.set(value, button);
|
||||
}
|
||||
into.append(seg);
|
||||
return (vals) => {
|
||||
const on = Boolean(vals[name]);
|
||||
if (typeof row.onText === "function") buttons.get(true).textContent = onText();
|
||||
for (const [value, button] of buttons) {
|
||||
button.classList.toggle("on", value === on);
|
||||
button.setAttribute("aria-checked", String(value === on));
|
||||
@@ -584,6 +601,14 @@ export function mountWidgetCard(node, { rows, minWidth = 300, first = false, hid
|
||||
fields.set(name, field);
|
||||
});
|
||||
if (row.button) buildButton(row.button, control);
|
||||
// A small line of type after the control: what the value comes to
|
||||
// (`note(node, values)` returns the text, "" for none).
|
||||
if (typeof row.note === "function") {
|
||||
const note = el("span", "ausboss-card-note");
|
||||
note.setAttribute("role", "status");
|
||||
control.append(note);
|
||||
syncs.push((vals) => { note.textContent = String(row.note(node, vals) ?? ""); });
|
||||
}
|
||||
line.append(control);
|
||||
state.rows.push({ row: { ...row, inGroup: row.group ?? null }, element: line, names, syncs, fields });
|
||||
root.append(line);
|
||||
|
||||
@@ -0,0 +1,426 @@
|
||||
// Strength Curve 🆎: the curve is drawn on the node. Drag a point, double-
|
||||
// click to add one, right-click to take one away; the chips start from a
|
||||
// common shape. The points are kept in the node's hidden "points" widget,
|
||||
// which is what the workflow saves and what the run reads. Top and Bottom
|
||||
// (high and low) are on the card under the curve.
|
||||
//
|
||||
// The line is the one the node outputs: js/shared/strength_curve_math.mjs
|
||||
// draws the same curve as nodes/_curve_helpers.py.
|
||||
|
||||
import { app } from "../../../scripts/app.js";
|
||||
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";
|
||||
import {
|
||||
MIN_GAP, PRESETS, addPoint, curveValues, movePoint, parsePoints, pointsText, presetOf, removePoint, strengthOf, tagPlace,
|
||||
} from "../shared/strength_curve_math.mjs";
|
||||
import { FONT_UI, RADIUS_CONTROL, THEME as T } from "../shared/theme.mjs";
|
||||
import { commitWidgetValue } from "../shared/widget_card_math.mjs";
|
||||
|
||||
const NODE_CLASS = "AUSBOSS_NODES_StrengthCurve";
|
||||
const CSS_ID = "ausboss-strength-curve-css";
|
||||
const WIDGET_NAME = "ausboss_strength_curve_panel";
|
||||
const PANEL_MIN_WIDTH = 320;
|
||||
const STAGE_MIN_HEIGHT = 130;
|
||||
const PANEL_MIN_HEIGHT = 22 + 6 + STAGE_MIN_HEIGHT + 6 + 26 + 6 + 14 + 4;
|
||||
const OPENING_WIDTH = 360;
|
||||
const OPENING_ROOM = 40;
|
||||
// Room around the box inside the stage: the strengths on the left, start
|
||||
// and end underneath.
|
||||
const EDGE = { left: 34, right: 10, top: 10, bottom: 18 };
|
||||
const GRAB_RADIUS = 9;
|
||||
const SAMPLES = 120;
|
||||
const SVG = "http://www.w3.org/2000/svg";
|
||||
|
||||
function ensureCss() {
|
||||
if (document.getElementById(CSS_ID)) return;
|
||||
const style = document.createElement("style");
|
||||
style.id = CSS_ID;
|
||||
style.textContent = `
|
||||
.ausboss-curve{box-sizing:border-box;display:flex;flex-direction:column;gap:6px;width:100%;height:100%;padding:0 2px 4px;overflow:hidden;font:12px/1.3 ${FONT_UI};color:${T.inkSoft};pointer-events:none}
|
||||
.ausboss-curve-bar{flex:none;display:flex;gap:4px;align-items:center;min-width:0;overflow:hidden}
|
||||
.ausboss-curve-stage{position:relative;flex:1 1 auto;min-height:${STAGE_MIN_HEIGHT}px;border-radius:${RADIUS_CONTROL}px;background:${T.well};overflow:hidden;cursor:crosshair;touch-action:none;pointer-events:auto}
|
||||
.ausboss-curve-stage svg{position:absolute;inset:0;width:100%;height:100%;display:block}
|
||||
.ausboss-curve-stage svg text{font:10px ${FONT_UI};fill:${T.faint}}
|
||||
.ausboss-curve-stage svg .readout{fill:${T.ink}}
|
||||
.ausboss-curve-stage.on-point{cursor:grab}
|
||||
.ausboss-curve-stage.dragging{cursor:grabbing}
|
||||
.ausboss-curve-point{flex:none;display:flex;gap:6px;align-items:center;height:26px;pointer-events:auto}
|
||||
.ausboss-curve-point>span{${CAPTION_TYPE}white-space:nowrap}
|
||||
.ausboss-curve-point>.ausboss-scrub{flex:1 1 0;min-width:0}
|
||||
.ausboss-curve-point>.held{opacity:.45;pointer-events:none}
|
||||
.ausboss-curve-hint{flex:none;${HINT_TYPE}white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||||
`;
|
||||
document.head.append(style);
|
||||
}
|
||||
|
||||
const widgetByName = (node, name) => node.widgets?.find((widget) => widget?.name === name) ?? null;
|
||||
const numberOf = (node, name, fallback) => {
|
||||
const value = Number(widgetByName(node, name)?.value);
|
||||
return Number.isFinite(value) ? value : fallback;
|
||||
};
|
||||
const svgEl = (name, attrs = {}) => {
|
||||
const element = document.createElementNS(SVG, name);
|
||||
for (const [key, value] of Object.entries(attrs)) element.setAttribute(key, String(value));
|
||||
return element;
|
||||
};
|
||||
|
||||
// The curve sits above the card, whichever of the two was built first.
|
||||
function panelFirst(node) {
|
||||
const widgets = node.widgets;
|
||||
if (!Array.isArray(widgets)) return;
|
||||
const panel = widgets.findIndex((widget) => widget?.name === WIDGET_NAME);
|
||||
const card = widgets.indexOf(node.__ausbossCard?.widget);
|
||||
if (panel < 0 || card < 0 || panel < card) return;
|
||||
widgets.splice(card, 0, widgets.splice(panel, 1)[0]);
|
||||
}
|
||||
|
||||
function build(node) {
|
||||
if (node.__ausbossCurve) return node.__ausbossCurve;
|
||||
ensureCss();
|
||||
const abort = new AbortController();
|
||||
const { signal } = abort;
|
||||
const root = document.createElement("div");
|
||||
root.className = "ausboss-curve";
|
||||
|
||||
const bar = document.createElement("div");
|
||||
bar.className = "ausboss-curve-bar";
|
||||
const chips = PRESETS.map((preset) => {
|
||||
const chip = compactAction(preset.name, preset.title);
|
||||
chip.dataset.preset = preset.name;
|
||||
chip.addEventListener("pointerdown", (event) => event.stopPropagation(), { signal });
|
||||
chip.addEventListener("click", (event) => {
|
||||
event.stopPropagation();
|
||||
face.points = preset.points.map((point) => [...point]);
|
||||
face.selected = Math.min(face.selected, face.points.length - 1);
|
||||
save();
|
||||
}, { signal });
|
||||
return chip;
|
||||
});
|
||||
bar.append(...chips);
|
||||
|
||||
const stage = document.createElement("div");
|
||||
stage.className = "ausboss-curve-stage";
|
||||
const svg = svgEl("svg");
|
||||
stage.append(svg);
|
||||
|
||||
const row = document.createElement("div");
|
||||
row.className = "ausboss-curve-point";
|
||||
const caption = (text) => {
|
||||
const span = document.createElement("span");
|
||||
span.textContent = text;
|
||||
return span;
|
||||
};
|
||||
const at = makeScrubInput({
|
||||
value: 0, min: 0, max: 100, step: 1, fineStep: 0.1, decimals: 1, minDecimals: 0, unit: "%", unitWidth: 14,
|
||||
title: "Where the picked point sits in the run, from the start (0%) to the end (100%).",
|
||||
onChange: (value) => {
|
||||
face.points = movePoint(face.points, face.selected, value / 100, face.points[face.selected][1]);
|
||||
write();
|
||||
},
|
||||
onSettle: () => save(),
|
||||
});
|
||||
const value = makeScrubInput({
|
||||
value: 1, min: 0, max: 1, step: 0.05, fineStep: 0.01, decimals: 2,
|
||||
title: "The strength at the picked point.",
|
||||
onChange: (strength) => {
|
||||
const low = numberOf(node, "low", 0);
|
||||
const high = numberOf(node, "high", 1);
|
||||
if (high === low) return;
|
||||
const point = face.points[face.selected];
|
||||
face.points = movePoint(face.points, face.selected, point[0], (strength - low) / (high - low));
|
||||
write();
|
||||
},
|
||||
onSettle: () => save(),
|
||||
});
|
||||
for (const scrub of [at, value]) {
|
||||
scrub.root.addEventListener("pointerdown", (event) => event.stopPropagation(), { signal });
|
||||
}
|
||||
row.append(caption("Point at"), at.root, caption("value"), value.root);
|
||||
|
||||
const hint = document.createElement("div");
|
||||
hint.className = "ausboss-curve-hint";
|
||||
hint.textContent = "Drag a point. Double-click adds one, right-click removes it.";
|
||||
root.append(bar, stage, row, hint);
|
||||
|
||||
const face = { node, root, points: parsePoints(widgetByName(node, "points")?.value ?? ""), selected: 0, hover: null, drag: null, alive: true };
|
||||
|
||||
// The box inside the stage, in the stage's own pixels.
|
||||
const box = () => {
|
||||
const width = stage.clientWidth || 300;
|
||||
const height = stage.clientHeight || STAGE_MIN_HEIGHT;
|
||||
return {
|
||||
width, height,
|
||||
x: (place) => EDGE.left + place * (width - EDGE.left - EDGE.right),
|
||||
y: (level) => EDGE.top + (1 - level) * (height - EDGE.top - EDGE.bottom),
|
||||
place: (px) => (px - EDGE.left) / Math.max(1, width - EDGE.left - EDGE.right),
|
||||
level: (py) => 1 - (py - EDGE.top) / Math.max(1, height - EDGE.top - EDGE.bottom),
|
||||
};
|
||||
};
|
||||
// A pointer on the page in the stage's pixels. The classic canvas scales
|
||||
// the panel with its zoom, so the screen box and the stage's own size differ.
|
||||
const local = (event) => {
|
||||
const rect = stage.getBoundingClientRect();
|
||||
return {
|
||||
x: ((event.clientX - rect.left) / Math.max(1, rect.width)) * stage.clientWidth,
|
||||
y: ((event.clientY - rect.top) / Math.max(1, rect.height)) * stage.clientHeight,
|
||||
};
|
||||
};
|
||||
const pointUnder = (spot) => {
|
||||
const geo = box();
|
||||
let best = -1;
|
||||
let bestDistance = GRAB_RADIUS;
|
||||
face.points.forEach(([px, py], index) => {
|
||||
const distance = Math.hypot(geo.x(px) - spot.x, geo.y(py) - spot.y);
|
||||
if (distance <= bestDistance) { best = index; bestDistance = distance; }
|
||||
});
|
||||
return best;
|
||||
};
|
||||
|
||||
function render() {
|
||||
if (!face.alive) return;
|
||||
const geo = box();
|
||||
const low = numberOf(node, "low", 0);
|
||||
const high = numberOf(node, "high", 1);
|
||||
svg.setAttribute("viewBox", `0 0 ${geo.width} ${geo.height}`);
|
||||
svg.replaceChildren();
|
||||
svg.append(svgEl("rect", { x: geo.x(0), y: geo.y(1), width: geo.x(1) - geo.x(0), height: geo.y(0) - geo.y(1), fill: "none", stroke: T.rule }));
|
||||
for (const step of [0.25, 0.5, 0.75]) {
|
||||
svg.append(svgEl("line", { x1: geo.x(step), y1: geo.y(1), x2: geo.x(step), y2: geo.y(0), stroke: "#23282b" }));
|
||||
svg.append(svgEl("line", { x1: geo.x(0), y1: geo.y(step), x2: geo.x(1), y2: geo.y(step), stroke: "#23282b" }));
|
||||
}
|
||||
const places = Array.from({ length: SAMPLES + 1 }, (_, i) => i / SAMPLES);
|
||||
const levels = curveValues(face.points, places);
|
||||
const line = places.map((place, i) => `${i ? "L" : "M"}${geo.x(place).toFixed(1)},${geo.y(levels[i]).toFixed(1)}`).join("");
|
||||
svg.append(svgEl("path", { d: `${line}L${geo.x(1)},${geo.y(0)}L${geo.x(0)},${geo.y(0)}Z`, fill: T.brandSoft, stroke: "none" }));
|
||||
svg.append(svgEl("path", { d: line, fill: "none", stroke: T.brand, "stroke-width": 2 }));
|
||||
const text = (content, attrs) => {
|
||||
const element = svgEl("text", attrs);
|
||||
element.textContent = content;
|
||||
svg.append(element);
|
||||
return element;
|
||||
};
|
||||
text(high.toFixed(2), { x: EDGE.left - 5, y: geo.y(1) + 4, "text-anchor": "end" });
|
||||
text(low.toFixed(2), { x: EDGE.left - 5, y: geo.y(0) + 3, "text-anchor": "end" });
|
||||
text("start", { x: geo.x(0), y: geo.height - 5 });
|
||||
text("end", { x: geo.x(1), y: geo.height - 5, "text-anchor": "end" });
|
||||
if (face.hover !== null && !face.drag) {
|
||||
const place = face.hover;
|
||||
const level = curveValues(face.points, [place])[0];
|
||||
svg.append(svgEl("line", { x1: geo.x(place), y1: geo.y(1), x2: geo.x(place), y2: geo.y(0), stroke: T.faint, "stroke-dasharray": "3 3" }));
|
||||
const label = `${Math.round(place * 100)}% · ${strengthOf(level, low, high).toFixed(2)}`;
|
||||
const width = label.length * 6 + 12;
|
||||
// Beside the spot, on a side that leaves every point and its value in view.
|
||||
const { left, top } = tagPlace({
|
||||
x: geo.x(place), y: geo.y(level), width, height: 17,
|
||||
box: { left: geo.x(0), top: geo.y(1), right: geo.x(1), bottom: geo.y(0) },
|
||||
points: face.points.map(([px, py]) => [geo.x(px), geo.y(py)]),
|
||||
});
|
||||
svg.append(svgEl("rect", { x: left, y: top, width, height: 17, rx: 4, fill: T.fill }));
|
||||
text(label, { x: left + width / 2, y: top + 12, "text-anchor": "middle", class: "readout" });
|
||||
}
|
||||
face.points.forEach(([place, level], index) => {
|
||||
const picked = index === face.selected;
|
||||
svg.append(svgEl("circle", {
|
||||
cx: geo.x(place), cy: geo.y(level), r: picked ? 6 : 5,
|
||||
fill: picked ? T.brand : T.ink, stroke: picked ? T.ink : T.well, "stroke-width": 2,
|
||||
}));
|
||||
});
|
||||
const preset = presetOf(face.points);
|
||||
for (const chip of chips) chip.classList.toggle("active", chip.dataset.preset === preset);
|
||||
const point = face.points[face.selected] ?? face.points[0];
|
||||
const last = face.points.length - 1;
|
||||
const end = face.selected <= 0 || face.selected >= last;
|
||||
at.root.classList.toggle("held", end);
|
||||
at.setRange(end
|
||||
? { min: point[0] * 100, max: point[0] * 100 }
|
||||
: { min: (face.points[face.selected - 1][0] + MIN_GAP) * 100, max: (face.points[face.selected + 1][0] - MIN_GAP) * 100 });
|
||||
at.set(point[0] * 100);
|
||||
value.root.classList.toggle("held", high === low);
|
||||
value.setRange({ min: Math.min(low, high), max: Math.max(low, high) });
|
||||
value.set(strengthOf(point[1], low, high));
|
||||
}
|
||||
|
||||
const pointsWidget = () => widgetByName(node, "points");
|
||||
// The points into the hidden widget while a drag is still going: the line
|
||||
// follows the pointer, and the change is kept as one step when it ends.
|
||||
function write() {
|
||||
const widget = pointsWidget();
|
||||
if (widget) widget.value = pointsText(face.points);
|
||||
render();
|
||||
}
|
||||
let settledText = null;
|
||||
// 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);
|
||||
notifyAusbossChange();
|
||||
}
|
||||
}
|
||||
settledText = text;
|
||||
node.setDirtyCanvas?.(true, true);
|
||||
render();
|
||||
}
|
||||
// Read the points back from the widget: a loaded workflow, an undo.
|
||||
face.resync = () => {
|
||||
const raw = pointsWidget()?.value;
|
||||
face.points = parsePoints(raw ?? "");
|
||||
settledText = typeof raw === "string" ? raw : pointsText(face.points);
|
||||
face.selected = Math.max(0, Math.min(face.selected, face.points.length - 1));
|
||||
render();
|
||||
};
|
||||
face.render = render;
|
||||
|
||||
stage.addEventListener("pointerdown", (event) => {
|
||||
if (event.button !== 0) return;
|
||||
event.stopPropagation();
|
||||
event.preventDefault();
|
||||
const index = pointUnder(local(event));
|
||||
if (index < 0) return;
|
||||
face.selected = index;
|
||||
face.drag = { pointerId: event.pointerId, moved: false };
|
||||
stage.setPointerCapture(event.pointerId);
|
||||
stage.classList.add("dragging");
|
||||
render();
|
||||
}, { signal });
|
||||
stage.addEventListener("pointermove", (event) => {
|
||||
const spot = local(event);
|
||||
const geo = box();
|
||||
if (face.drag) {
|
||||
face.drag.moved = true;
|
||||
face.points = movePoint(face.points, face.selected, geo.place(spot.x), geo.level(spot.y));
|
||||
write();
|
||||
return;
|
||||
}
|
||||
const place = geo.place(spot.x);
|
||||
face.hover = place >= 0 && place <= 1 ? place : null;
|
||||
stage.classList.toggle("on-point", pointUnder(spot) >= 0);
|
||||
render();
|
||||
}, { signal });
|
||||
const endDrag = (event) => {
|
||||
if (!face.drag) return;
|
||||
try { stage.releasePointerCapture(event.pointerId); } catch { /* already released */ }
|
||||
const moved = face.drag.moved;
|
||||
face.drag = null;
|
||||
stage.classList.remove("dragging");
|
||||
if (moved) save();
|
||||
else render();
|
||||
};
|
||||
stage.addEventListener("pointerup", endDrag, { signal });
|
||||
stage.addEventListener("pointercancel", endDrag, { signal });
|
||||
stage.addEventListener("pointerleave", () => {
|
||||
if (face.drag) return;
|
||||
face.hover = null;
|
||||
render();
|
||||
}, { signal });
|
||||
stage.addEventListener("dblclick", (event) => {
|
||||
event.stopPropagation();
|
||||
event.preventDefault();
|
||||
const spot = local(event);
|
||||
if (pointUnder(spot) >= 0) return;
|
||||
const geo = box();
|
||||
const added = addPoint(face.points, geo.place(spot.x), geo.level(spot.y));
|
||||
if (!added) return;
|
||||
face.points = added.points;
|
||||
face.selected = added.index;
|
||||
save();
|
||||
}, { signal });
|
||||
stage.addEventListener("contextmenu", (event) => {
|
||||
const index = pointUnder(local(event));
|
||||
if (index <= 0 || index >= face.points.length - 1) return;
|
||||
event.stopPropagation();
|
||||
event.preventDefault();
|
||||
face.points = removePoint(face.points, index);
|
||||
face.selected = index - 1;
|
||||
save();
|
||||
}, { signal });
|
||||
// LiteGraph opens the node's menu on the pointerdown of a right click;
|
||||
// one on a point is the point's own.
|
||||
stage.addEventListener("pointerdown", (event) => {
|
||||
if (event.button !== 2) return;
|
||||
const index = pointUnder(local(event));
|
||||
if (index > 0 && index < face.points.length - 1) event.stopPropagation();
|
||||
}, { signal });
|
||||
|
||||
const resize = typeof ResizeObserver === "function" ? new ResizeObserver(() => render()) : null;
|
||||
resize?.observe(stage);
|
||||
|
||||
const widget = node.addDOMWidget(WIDGET_NAME, "ausboss_strength_curve", root, {
|
||||
serialize: false,
|
||||
hideOnZoom: false,
|
||||
getMinHeight: () => PANEL_MIN_HEIGHT + WIDGET_FRAME,
|
||||
});
|
||||
keepDomWidgetWidthAuto(widget);
|
||||
widget.serialize = false;
|
||||
fillNodeHeight(widget, {
|
||||
minWidth: PANEL_MIN_WIDTH,
|
||||
minHeight: () => PANEL_MIN_HEIGHT + WIDGET_FRAME,
|
||||
minNodeSize: [PANEL_MIN_WIDTH, PANEL_MIN_HEIGHT + 40],
|
||||
exactMinWidth: true,
|
||||
});
|
||||
|
||||
face.watched = new WeakSet();
|
||||
face.watch = () => {
|
||||
for (const name of ["high", "low"]) {
|
||||
const target = widgetByName(node, name);
|
||||
if (!target || face.watched.has(target)) continue;
|
||||
face.watched.add(target);
|
||||
chainCallback(target, "callback", () => render());
|
||||
}
|
||||
};
|
||||
face.destroy = () => {
|
||||
face.alive = false;
|
||||
resize?.disconnect();
|
||||
abort.abort();
|
||||
};
|
||||
node.__ausbossCurve = face;
|
||||
face.watch();
|
||||
panelFirst(node);
|
||||
face.resync();
|
||||
return face;
|
||||
}
|
||||
|
||||
app.registerExtension({
|
||||
name: "ausboss.strength_curve",
|
||||
beforeRegisterNodeDef(nodeType, nodeData) {
|
||||
if (nodeData?.name !== NODE_CLASS) return;
|
||||
chainCallback(nodeType.prototype, "onNodeCreated", function () {
|
||||
const face = build(this);
|
||||
// A new node opens with room for the curve; a loaded workflow puts its
|
||||
// own size back after this.
|
||||
chainCallback(this, "onAdded", () => {
|
||||
panelFirst(this);
|
||||
if (face.sized) return;
|
||||
face.sized = true;
|
||||
const floor = Number(this.computeSize?.()?.[1]);
|
||||
if (Number.isFinite(floor) && this.size?.[1] <= floor + 1) {
|
||||
this.setSize?.([Math.max(this.size[0], OPENING_WIDTH), floor + OPENING_ROOM]);
|
||||
}
|
||||
});
|
||||
});
|
||||
chainCallback(nodeType.prototype, "onConfigure", function (info) {
|
||||
const face = build(this);
|
||||
if (info?.size) face.sized = true;
|
||||
queueMicrotask(() => {
|
||||
if (!face.alive) return;
|
||||
face.watch();
|
||||
panelFirst(this);
|
||||
face.resync();
|
||||
});
|
||||
});
|
||||
// A wire into high or low, or one taken away.
|
||||
chainCallback(nodeType.prototype, "onConnectionsChange", function () {
|
||||
this.__ausbossCurve?.render();
|
||||
});
|
||||
chainCallback(nodeType.prototype, "onRemoved", function () {
|
||||
this.__ausbossCurve?.destroy();
|
||||
this.__ausbossCurve = null;
|
||||
});
|
||||
},
|
||||
});
|
||||
+114
-10
@@ -10,12 +10,15 @@ 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";
|
||||
import { SOCKETLESS_CHOICE, SOCKETLESS_TEXT, commitWidgetValue, markSocketless, resetUnknownValues } from "../shared/widget_card_math.mjs";
|
||||
import { mediaViewQuery } from "../shared/media_list.mjs";
|
||||
@@ -29,6 +32,21 @@ import { valueToTake, wiredLimits } from "../shared/wired_limits.mjs";
|
||||
// The Source lists preview the hovered file straight from ComfyUI's /view.
|
||||
const viewUrl = (value) => api.apiURL(`/view?${mediaViewQuery(value)}`);
|
||||
|
||||
// Film Grain's Auto: what the multiplier comes to for the picture on hand.
|
||||
// The node's live stage (js/shared/live_stage.mjs) keeps Auto's own picks
|
||||
// on node.__ausbossAuto once it knows the picture; until then a plain dash.
|
||||
// Film Grain's Auto notes: the number each multiplier gives ("= 0.27"), from
|
||||
// Auto's pick, or from the match while a picture to copy grain from is wired
|
||||
// (js/shared/grain_auto.mjs keeps both).
|
||||
function autoNote(node, which) {
|
||||
const picked = copiesGrain(node) ? node.__ausbossMatch : node.__ausbossAuto;
|
||||
const widget = node.widgets?.find((item) => item.name === `auto_${which}`);
|
||||
const times = Number(widget?.value);
|
||||
if (!picked || !Number.isFinite(times)) return "= -";
|
||||
if (which === "size") return `= ${Math.min(16, Math.max(0.5, picked.size * times)).toFixed(1)} px`;
|
||||
return `= ${Math.min(1, Math.max(0, picked[which] * times)).toFixed(2)}`;
|
||||
}
|
||||
|
||||
const isMode = (name, ...modes) => (values) => modes.includes(values[name]);
|
||||
// Load Image: the choices that read the width and height boxes.
|
||||
const loadImageUsesBox = (values) => ["fit inside", "crop to fill", "crop"].includes(values.size)
|
||||
@@ -259,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" },
|
||||
@@ -272,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
|
||||
@@ -429,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: "" },
|
||||
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).
|
||||
@@ -445,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" },
|
||||
@@ -458,6 +487,7 @@ const CARDS = {
|
||||
{ widget: "cut_on_beat", label: "Moments on the beat", group: "more" },
|
||||
{ widget: "language", label: "Language", group: "more" },
|
||||
{ widget: "clip_sound", label: "Clip's own sound", group: "more" },
|
||||
{ widget: "tidy", label: "Tidy up my lines", group: "more" },
|
||||
],
|
||||
},
|
||||
// Saved by a 1.x release, these two hold that empty value too and open
|
||||
@@ -496,9 +526,13 @@ const CARDS = {
|
||||
// card (js/load_audio); max_seconds is the Duration there. The card
|
||||
// hides it, so App mode can still show it as a field.
|
||||
minWidth: 280, first: true, hide: ["upload", "max_seconds"],
|
||||
// Older saves hand clean_up the upload button's empty value.
|
||||
resetUnknown: { clean_up: false },
|
||||
rows: [
|
||||
{ widget: "audio", label: "Source", kind: "select",
|
||||
button: { text: PANEL_LABELS.load, title: "Upload a sound file into ComfyUI's input folder", onClick: (node) => node.widgets?.find((w) => w.name === "upload")?.callback?.() } },
|
||||
{ widget: "clean_up", label: "Clean up", onText: PANEL_LABELS.on, offText: PANEL_LABELS.off,
|
||||
title: "For a voice recording. On cuts the quiet bits at the start and end, takes out hum and hiss, and evens out the volume. Off hands on the sound as it is." },
|
||||
],
|
||||
},
|
||||
// Load Image: the file, then where it is in the folder and the size it
|
||||
@@ -558,6 +592,68 @@ const CARDS = {
|
||||
{ widget: "save_metadata", label: PANEL_LABELS.embed, onText: PANEL_LABELS.on, offText: PANEL_LABELS.off, when: formatReads("save_metadata"), title: "On embeds the workflow in the video file, so dropping the file back on the canvas restores the graph that made it." },
|
||||
],
|
||||
},
|
||||
// The strengths at the top and the bottom of the curve box. The curve
|
||||
// itself (js/strength_curve) sits above the card and owns the hidden
|
||||
// `points` widget.
|
||||
AUSBOSS_NODES_StrengthCurve: {
|
||||
minWidth: 320, hide: ["points"], socketless: ["points"],
|
||||
rows: [
|
||||
{ widget: "high", label: "Top", step: 0.05, decimals: 2, title: "The strength at the top of the curve box. 1 is full strength." },
|
||||
{ widget: "low", label: "Bottom", step: 0.05, decimals: 2, title: "The strength at the bottom of the curve box. 0 is off." },
|
||||
],
|
||||
},
|
||||
// Film Grain, Cut Out and Keep Detail show their result: the card sits
|
||||
// above the preview panel (js/input_preview), which owns the hidden
|
||||
// preview switch.
|
||||
// Auto picks the amount and size from the picture (js/shared/live_stage.mjs
|
||||
// measures it), or copies grain_from's grain (the node's run works out the
|
||||
// match); Amount, Size and, while copying, Color then read as multipliers
|
||||
// in their own boxes (auto_amount, auto_size, auto_color), so each mode
|
||||
// keeps its own numbers.
|
||||
AUSBOSS_NODES_FilmGrain: {
|
||||
minWidth: 300, first: true,
|
||||
resetUnknown: { auto: false, auto_amount: 1, auto_size: 1, auto_color: 1 },
|
||||
rows: [
|
||||
// With a picture on grain_from, Auto copies its grain: "on" reads
|
||||
// "match", and Color counts from the match too.
|
||||
{ widget: "auto", label: "Auto", onText: (node) => (grainFromLinked(node) ? "match" : "on"), offText: "off" },
|
||||
{ section: "1 \u00d7 = Auto's pick", when: (v, node) => Boolean(v.auto) && !grainFromLinked(node) },
|
||||
{ section: "1 \u00d7 = the match", when: (v, node) => Boolean(v.auto) && grainFromLinked(node) },
|
||||
{ widget: "amount", label: "Amount", when: (v) => !v.auto },
|
||||
{ widget: "size", label: "Size", suffix: "px", when: (v) => !v.auto },
|
||||
{ widget: "auto_amount", label: "Amount", suffix: "\u00d7", when: (v) => Boolean(v.auto), note: (node) => autoNote(node, "amount") },
|
||||
{ widget: "auto_size", label: "Size", suffix: "\u00d7", when: (v) => Boolean(v.auto), note: (node) => autoNote(node, "size") },
|
||||
{ widget: "roughness", label: "Roughness" },
|
||||
{ widget: "color", label: "Color", when: (v, node) => !(v.auto && grainFromLinked(node)) },
|
||||
{ widget: "auto_color", label: "Color", suffix: "\u00d7", when: (v, node) => Boolean(v.auto) && grainFromLinked(node), note: (node) => autoNote(node, "color") },
|
||||
{ widget: "moving", label: "Video grain", onText: "moving", offText: "still" },
|
||||
{ group: "advanced", label: "More" },
|
||||
{ widget: "seed", label: "Seed", group: "advanced" },
|
||||
],
|
||||
},
|
||||
AUSBOSS_NODES_CutOut: {
|
||||
minWidth: 300, first: true,
|
||||
rows: [
|
||||
{ widget: "keep", label: "Keep", kind: "segment", labels: { white: "white part", black: "black part" } },
|
||||
{ widget: "grow", label: "Grow", suffix: "px" },
|
||||
{ widget: "feather", label: "Feather", suffix: "px" },
|
||||
{ widget: "clean_edges", label: "Clean edges" },
|
||||
{ group: "advanced", label: "More" },
|
||||
{ widget: "clear_haze", label: "Clear haze", group: "advanced" },
|
||||
{ widget: "solid_above", label: "Solid above", group: "advanced" },
|
||||
{ widget: "smooth_frames", label: "Smooth video", suffix: "fr", group: "advanced" },
|
||||
],
|
||||
},
|
||||
AUSBOSS_NODES_KeepDetail: {
|
||||
minWidth: 300, first: true,
|
||||
rows: [
|
||||
{ widget: "detail_size", label: "Detail size", suffix: "px" },
|
||||
{ widget: "strength", label: "Strength" },
|
||||
{ widget: "color_detail", label: "Detail", onText: "color + light", offText: "light only" },
|
||||
{ group: "advanced", label: "More" },
|
||||
{ widget: "edge_safe", label: "Edge safe", group: "advanced" },
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
function cardWidgetNames(config) {
|
||||
@@ -590,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;
|
||||
|
||||
@@ -371,6 +371,9 @@
|
||||
},
|
||||
"full_prompt": {
|
||||
"name": "完整提示词"
|
||||
},
|
||||
"tidy": {
|
||||
"name": "整理我的台词"
|
||||
}
|
||||
},
|
||||
"outputs": {
|
||||
@@ -721,6 +724,9 @@
|
||||
},
|
||||
"mask": {
|
||||
"name": "遮罩"
|
||||
},
|
||||
"reference_curve": {
|
||||
"name": "参考强度曲线"
|
||||
}
|
||||
},
|
||||
"outputs": {
|
||||
@@ -1020,6 +1026,9 @@
|
||||
},
|
||||
"on_missing": {
|
||||
"name": "缺失时"
|
||||
},
|
||||
"curve": {
|
||||
"name": "强度曲线"
|
||||
}
|
||||
},
|
||||
"outputs": {
|
||||
@@ -1263,6 +1272,12 @@
|
||||
},
|
||||
"max_hole_size": {
|
||||
"name": "最大空洞尺寸"
|
||||
},
|
||||
"detail_range": {
|
||||
"name": "细节范围"
|
||||
},
|
||||
"fix_threshold": {
|
||||
"name": "修正阈值"
|
||||
}
|
||||
},
|
||||
"outputs": {
|
||||
@@ -1931,6 +1946,9 @@
|
||||
},
|
||||
"max_seconds": {
|
||||
"name": "最大秒数"
|
||||
},
|
||||
"clean_up": {
|
||||
"name": "清理"
|
||||
}
|
||||
},
|
||||
"outputs": {
|
||||
@@ -2090,5 +2108,157 @@
|
||||
"name": "照片上边"
|
||||
}
|
||||
}
|
||||
},
|
||||
"AUSBOSS_NODES_FilmGrain": {
|
||||
"display_name": "胶片颗粒 🆎",
|
||||
"description": "给图片或视频加上胶片颗粒。颗粒在中间调最明显,在深暗部和高光处较弱,和胶片一样。尺寸是颗粒的像素大小,粗糙度让颗粒更细、更不均匀,颜色让颗粒从黑白颗粒变成彩色胶片的颗粒。在视频上颗粒可以逐帧变化,也可以保持不动。自动会按图片挑选颗粒量和尺寸:小图和大图看起来一样,并与图片自带的颗粒相匹配;此时颗粒量和尺寸变成它的倍数。在颗粒来源接上一张图片,自动就会复制那张图片的颗粒:强度、大小和颜色。可选的遮罩只在白色处加颗粒。同一个种子总是得到同样的颗粒。",
|
||||
"inputs": {
|
||||
"image": {
|
||||
"name": "图像"
|
||||
},
|
||||
"amount": {
|
||||
"name": "颗粒量"
|
||||
},
|
||||
"size": {
|
||||
"name": "尺寸"
|
||||
},
|
||||
"roughness": {
|
||||
"name": "粗糙度"
|
||||
},
|
||||
"color": {
|
||||
"name": "颜色"
|
||||
},
|
||||
"moving": {
|
||||
"name": "逐帧变化"
|
||||
},
|
||||
"seed": {
|
||||
"name": "种子"
|
||||
},
|
||||
"mask": {
|
||||
"name": "遮罩"
|
||||
},
|
||||
"preview": {
|
||||
"name": "预览"
|
||||
},
|
||||
"auto": {
|
||||
"name": "自动"
|
||||
},
|
||||
"auto_amount": {
|
||||
"name": "自动颗粒量倍数"
|
||||
},
|
||||
"auto_size": {
|
||||
"name": "自动尺寸倍数"
|
||||
},
|
||||
"grain_from": {
|
||||
"name": "颗粒来源"
|
||||
},
|
||||
"auto_color": {
|
||||
"name": "自动颜色倍数"
|
||||
}
|
||||
},
|
||||
"outputs": {
|
||||
"0": {
|
||||
"name": "图像"
|
||||
}
|
||||
}
|
||||
},
|
||||
"AUSBOSS_NODES_CutOut": {
|
||||
"display_name": "抠图 🆎",
|
||||
"description": "把图片和遮罩变成背景透明的抠图,可以直接存成 PNG,或放到新的背景上。保留遮罩的白色或黑色部分,扩大或缩小它,并柔化边缘。清理边缘会去掉头发和柔和边缘里旧背景的颜色,让抠图放到新背景上时没有光晕;完全保留的像素保持原样。也适用于视频帧。",
|
||||
"inputs": {
|
||||
"image": {
|
||||
"name": "图像"
|
||||
},
|
||||
"mask": {
|
||||
"name": "遮罩"
|
||||
},
|
||||
"keep": {
|
||||
"name": "保留"
|
||||
},
|
||||
"grow": {
|
||||
"name": "扩大"
|
||||
},
|
||||
"feather": {
|
||||
"name": "羽化"
|
||||
},
|
||||
"clean_edges": {
|
||||
"name": "清理边缘"
|
||||
},
|
||||
"clear_haze": {
|
||||
"name": "清除薄雾"
|
||||
},
|
||||
"solid_above": {
|
||||
"name": "高于此值为实"
|
||||
},
|
||||
"smooth_frames": {
|
||||
"name": "视频平滑"
|
||||
},
|
||||
"preview": {
|
||||
"name": "预览"
|
||||
}
|
||||
},
|
||||
"outputs": {
|
||||
"0": {
|
||||
"name": "图像"
|
||||
},
|
||||
"1": {
|
||||
"name": "透明度"
|
||||
}
|
||||
}
|
||||
},
|
||||
"AUSBOSS_NODES_KeepDetail": {
|
||||
"display_name": "保留细节 🆎",
|
||||
"description": "把原图的细节(皮肤、布料、颗粒)放回修改后的图片上。适合在编辑或重新打光后画面变得太光滑时使用。修改后的图片保留它的形状、光线和颜色,只有小于细节大小的细节来自原图。两张图片必须对齐。仅明暗只带回亮度细节,所以颜色不会变;颜色 + 明暗连细节的颜色一起带回。",
|
||||
"inputs": {
|
||||
"image": {
|
||||
"name": "图像"
|
||||
},
|
||||
"detail_from": {
|
||||
"name": "细节来源"
|
||||
},
|
||||
"detail_size": {
|
||||
"name": "细节大小"
|
||||
},
|
||||
"strength": {
|
||||
"name": "强度"
|
||||
},
|
||||
"color_detail": {
|
||||
"name": "颜色细节"
|
||||
},
|
||||
"edge_safe": {
|
||||
"name": "保护边缘"
|
||||
},
|
||||
"mask": {
|
||||
"name": "遮罩"
|
||||
},
|
||||
"preview": {
|
||||
"name": "预览"
|
||||
}
|
||||
},
|
||||
"outputs": {
|
||||
"0": {
|
||||
"name": "图像"
|
||||
}
|
||||
}
|
||||
},
|
||||
"AUSBOSS_NODES_StrengthCurve": {
|
||||
"display_name": "强度曲线 🆎",
|
||||
"description": "画出从一次运行开始到结束的强度变化,再把曲线接到会逐步跟随它的节点:LoRA 加载器 🆎 的某一行,或 Krea 2 编码 🆎 的参考图。让风格 LoRA 逐渐淡出,细节就更干净;或者让参考图前期稳住构图、后期放开。在节点上拖动点,或从预设开始。",
|
||||
"inputs": {
|
||||
"points": {
|
||||
"name": "点"
|
||||
},
|
||||
"high": {
|
||||
"name": "顶部"
|
||||
},
|
||||
"low": {
|
||||
"name": "底部"
|
||||
}
|
||||
},
|
||||
"outputs": {
|
||||
"0": {
|
||||
"name": "曲线"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,212 @@
|
||||
"""Voice cleanup for Load Audio's clean_up switch.
|
||||
|
||||
One pass, in this order, on the part of the file the node hands on:
|
||||
|
||||
1. one channel (the channels are averaged);
|
||||
2. a high-pass at 80 Hz for rumble and mains hum (a man's voice starts
|
||||
around 85 Hz, so it keeps its depth);
|
||||
3. light hiss reduction: a noise print from the quietest moments, and every
|
||||
sound close to it is turned down by at most ``HISS_REDUCTION_DB``;
|
||||
4. quiet stretches at the start and the end are cut, keeping a short pad;
|
||||
5. an even loudness (``TARGET_LUFS``, measured the way broadcast meters do),
|
||||
with a limiter that keeps every peak under ``PEAK_CEILING_DB``.
|
||||
|
||||
Everything is torch on the CPU, at the file's own sample rate.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
|
||||
from ._execution_helpers import raise_if_interrupted
|
||||
|
||||
HIGH_PASS_HZ = 80.0
|
||||
HISS_REDUCTION_DB = 12.0
|
||||
# A sound counts as hiss below this many dB over the noise print.
|
||||
GATE_MARGIN_DB = 6.0
|
||||
TARGET_LUFS = -18.0
|
||||
PEAK_CEILING_DB = -1.0
|
||||
MAX_BOOST_DB = 30.0
|
||||
# Quiet ends: what stays before the first and after the last sound.
|
||||
LEAD_PAD_SECONDS = 0.1
|
||||
TAIL_PAD_SECONDS = 0.2
|
||||
# Quieter than this everywhere is treated as silence and left alone.
|
||||
SILENCE_DB = -60.0
|
||||
|
||||
_EPS = 1e-10
|
||||
|
||||
|
||||
def _db(value: torch.Tensor) -> torch.Tensor:
|
||||
return 20.0 * torch.log10(value.clamp_min(_EPS))
|
||||
|
||||
|
||||
def _shape_spectrum(signal: torch.Tensor, rate: int, gain_for_hz) -> torch.Tensor:
|
||||
"""Multiply the whole signal's spectrum by ``gain_for_hz(frequencies)``.
|
||||
|
||||
Zero phase. The signal is padded first so the filter's ring at one end
|
||||
does not wrap around into the other.
|
||||
"""
|
||||
length = signal.shape[-1]
|
||||
pad = int(rate * 0.1)
|
||||
padded = F.pad(signal, (pad, pad))
|
||||
spectrum = torch.fft.rfft(padded.double())
|
||||
hz = torch.fft.rfftfreq(padded.shape[-1], d=1.0 / rate, dtype=torch.float64)
|
||||
shaped = torch.fft.irfft(spectrum * gain_for_hz(hz), n=padded.shape[-1])
|
||||
return shaped[..., pad : pad + length].to(signal.dtype)
|
||||
|
||||
|
||||
def _high_pass_gain(hz: torch.Tensor) -> torch.Tensor:
|
||||
# A fourth-order Butterworth's magnitude: -3 dB at the corner, -10 dB at
|
||||
# 60 Hz hum, -16 dB at 50 Hz, -24 dB an octave under. Zero at DC.
|
||||
ratio = (HIGH_PASS_HZ / hz.clamp_min(1e-6)) ** 8
|
||||
return torch.where(hz > 0, 1.0 / torch.sqrt(1.0 + ratio), torch.zeros_like(hz))
|
||||
|
||||
|
||||
def _biquad_magnitude(b, a, hz: torch.Tensor, rate: int) -> torch.Tensor:
|
||||
z = torch.exp(-1j * 2.0 * math.pi * hz / rate)
|
||||
top = b[0] + b[1] * z + b[2] * z * z
|
||||
bottom = a[0] + a[1] * z + a[2] * z * z
|
||||
return (top / bottom).abs()
|
||||
|
||||
|
||||
def _k_weighting_gain(rate: int):
|
||||
"""The loudness meter's ear curve (ITU-R BS.1770) at any sample rate."""
|
||||
# Stage 1: a high shelf, +4 dB above about 1.7 kHz.
|
||||
f0, gain_db, q = 1681.974450955533, 3.999843853973347, 0.7071752369554196
|
||||
k = math.tan(math.pi * f0 / rate)
|
||||
vh = 10.0 ** (gain_db / 20.0)
|
||||
vb = vh ** 0.4996667741545416
|
||||
a0 = 1.0 + k / q + k * k
|
||||
shelf_b = ((vh + vb * k / q + k * k) / a0, 2.0 * (k * k - vh) / a0, (vh - vb * k / q + k * k) / a0)
|
||||
shelf_a = (1.0, 2.0 * (k * k - 1.0) / a0, (1.0 - k / q + k * k) / a0)
|
||||
# Stage 2: a high-pass at about 38 Hz.
|
||||
f0, q = 38.13547087602444, 0.5003270373238773
|
||||
k = math.tan(math.pi * f0 / rate)
|
||||
a0 = 1.0 + k / q + k * k
|
||||
pass_b = (1.0, -2.0, 1.0)
|
||||
pass_a = (1.0, 2.0 * (k * k - 1.0) / a0, (1.0 - k / q + k * k) / a0)
|
||||
|
||||
def gain(hz: torch.Tensor) -> torch.Tensor:
|
||||
return _biquad_magnitude(shelf_b, shelf_a, hz, rate) * _biquad_magnitude(pass_b, pass_a, hz, rate)
|
||||
|
||||
return gain
|
||||
|
||||
|
||||
def integrated_loudness(mono: torch.Tensor, rate: int) -> float:
|
||||
"""Integrated loudness in LUFS of a 1-D signal, or -inf for silence.
|
||||
|
||||
400 ms blocks every 100 ms, gated at -70 LUFS and then 10 LU under the
|
||||
mean, as broadcast meters measure it.
|
||||
"""
|
||||
weighted = _shape_spectrum(mono, rate, _k_weighting_gain(rate)).double()
|
||||
block = int(round(0.4 * rate))
|
||||
hop = int(round(0.1 * rate))
|
||||
if weighted.shape[-1] < block:
|
||||
blocks = weighted.square().mean().reshape(1)
|
||||
else:
|
||||
blocks = weighted.unfold(-1, block, hop).square().mean(dim=-1)
|
||||
|
||||
def lufs(power: torch.Tensor) -> torch.Tensor:
|
||||
return -0.691 + 10.0 * torch.log10(power.clamp_min(1e-20))
|
||||
|
||||
kept = blocks[lufs(blocks) > -70.0]
|
||||
if kept.numel() == 0:
|
||||
return float("-inf")
|
||||
relative = lufs(kept.mean()) - 10.0
|
||||
kept = kept[lufs(kept) > relative]
|
||||
return float(lufs(kept.mean()))
|
||||
|
||||
|
||||
def _fft_size(rate: int) -> int:
|
||||
# About 40 ms: fine enough to tell a voice's harmonics from hiss.
|
||||
return max(256, 1 << int(round(math.log2(rate * 0.04))))
|
||||
|
||||
|
||||
def _reduce_hiss(mono: torch.Tensor, rate: int) -> torch.Tensor:
|
||||
"""Spectral gate: a noise print from the quietest frames, then a soft,
|
||||
smoothed gain that turns down whatever sits close to it."""
|
||||
n_fft = _fft_size(rate)
|
||||
hop = n_fft // 4
|
||||
if mono.shape[-1] < n_fft * 4:
|
||||
return mono # too short to learn what the noise is
|
||||
window = torch.hann_window(n_fft, dtype=mono.dtype)
|
||||
spec = torch.stft(mono, n_fft, hop, window=window, center=True, return_complex=True)
|
||||
level = _db(spec.abs()) # bins x frames
|
||||
# The quietest tenth of the frames, by their total energy, is the print.
|
||||
energy = spec.abs().square().sum(dim=0)
|
||||
count = max(4, energy.shape[0] // 10)
|
||||
quiet = torch.topk(energy, count, largest=False).indices
|
||||
noise = level[:, quiet]
|
||||
threshold = noise.mean(dim=1, keepdim=True) + noise.std(dim=1, keepdim=True) + GATE_MARGIN_DB
|
||||
# 0 for hiss, 1 for anything well over it, a 3 dB soft edge between.
|
||||
keep = torch.sigmoid((level - threshold) / 1.5)
|
||||
# Smooth across nearby bins and frames so the gain does not twinkle.
|
||||
kernel = torch.outer(torch.hann_window(7, periodic=False), torch.hann_window(5, periodic=False))
|
||||
kernel = (kernel / kernel.sum()).to(keep.dtype)[None, None]
|
||||
keep = F.conv2d(keep[None, None], kernel, padding=(3, 2))[0, 0]
|
||||
floor = 10.0 ** (-HISS_REDUCTION_DB / 20.0)
|
||||
gain = floor + (1.0 - floor) * keep
|
||||
return torch.istft(spec * gain, n_fft, hop, window=window, center=True, length=mono.shape[-1])
|
||||
|
||||
|
||||
def _sound_span(mono: torch.Tensor, rate: int) -> tuple[int, int]:
|
||||
"""First and last sample worth keeping, quiet ends cut, pads kept."""
|
||||
frame = max(1, int(rate * 0.02))
|
||||
usable = (mono.shape[-1] // frame) * frame
|
||||
if usable == 0:
|
||||
return 0, mono.shape[-1]
|
||||
levels = _db(mono[:usable].reshape(-1, frame).square().mean(dim=1).sqrt())
|
||||
loudest = float(levels.max())
|
||||
if loudest < SILENCE_DB:
|
||||
return 0, mono.shape[-1]
|
||||
floor = float(torch.quantile(levels, 0.1))
|
||||
# 10 dB over the quiet floor, or halfway to the loudest moment when the
|
||||
# noise sits closer than that, and never more than 50 dB under it.
|
||||
threshold = max(loudest - 50.0, min(floor + 10.0, (floor + loudest) / 2.0))
|
||||
loud = torch.nonzero(levels > threshold).flatten()
|
||||
first = max(0, int(loud[0]) * frame - int(rate * LEAD_PAD_SECONDS))
|
||||
last = min(mono.shape[-1], (int(loud[-1]) + 1) * frame + int(rate * TAIL_PAD_SECONDS))
|
||||
return first, last
|
||||
|
||||
|
||||
def _limit(mono: torch.Tensor, rate: int, ceiling: float) -> torch.Tensor:
|
||||
"""Look-ahead peak limiter: the gain dips just before a peak and comes
|
||||
back after it, so nothing passes the ceiling and nothing is clipped."""
|
||||
needed = (ceiling / mono.abs().clamp_min(_EPS)).clamp(max=1.0)
|
||||
if float(needed.min()) >= 1.0:
|
||||
return mono
|
||||
reach = max(1, int(rate * 0.005))
|
||||
width = 2 * reach + 1
|
||||
# The lowest gain any sample within reach needs, then averaged over the
|
||||
# same reach: every average is at or under what its own sample needs.
|
||||
lowest = -F.max_pool1d(-needed[None, None], width, stride=1, padding=reach)
|
||||
smooth = F.avg_pool1d(lowest, width, stride=1, padding=reach, count_include_pad=False)[0, 0]
|
||||
return (mono * smooth).clamp(-ceiling, ceiling)
|
||||
|
||||
|
||||
def clean_up_voice(sound: dict) -> dict:
|
||||
"""ComfyUI AUDIO in, the cleaned-up voice out as one channel."""
|
||||
waveform = sound["waveform"]
|
||||
rate = int(sound["sample_rate"])
|
||||
mono = waveform[0].float().mean(dim=0)
|
||||
if mono.numel() == 0:
|
||||
return {"waveform": mono.reshape(1, 1, 0), "sample_rate": rate}
|
||||
raise_if_interrupted()
|
||||
mono = _shape_spectrum(mono, rate, _high_pass_gain)
|
||||
raise_if_interrupted()
|
||||
mono = _reduce_hiss(mono, rate)
|
||||
raise_if_interrupted()
|
||||
first, last = _sound_span(mono, rate)
|
||||
mono = mono[first:last]
|
||||
loudness = integrated_loudness(mono, rate)
|
||||
if math.isfinite(loudness):
|
||||
gain_db = min(TARGET_LUFS - loudness, MAX_BOOST_DB)
|
||||
mono = mono * (10.0 ** (gain_db / 20.0))
|
||||
mono = _limit(mono, rate, 10.0 ** (PEAK_CEILING_DB / 20.0))
|
||||
return {"waveform": mono.contiguous().reshape(1, 1, -1), "sample_rate": rate}
|
||||
|
||||
|
||||
__all__ = ["clean_up_voice", "integrated_loudness"]
|
||||
@@ -0,0 +1,220 @@
|
||||
"""Strength Curve: a drawn curve as a per-step schedule.
|
||||
|
||||
The curve is a few points from the start of a run (0) to its end (1), joined
|
||||
by a smooth line that never overshoots them (a monotone cubic, Fritsch and
|
||||
Carlson 1980). It leaves the node as core's FLOATS type: CURVE_SAMPLES values
|
||||
spread evenly from start to end, the same reading core's own Create Hook
|
||||
Keyframes From Floats gives a list. Nodes that take a schedule read "where in
|
||||
the run" the way core's hook keyframes do: by the noise level of the step,
|
||||
not by its number (`keyframe_plan`, then core keyframes or `strength_at_noise`).
|
||||
|
||||
Everything above `hook_keyframes` is plain Python, testable without torch.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import math
|
||||
from typing import Any
|
||||
|
||||
CURVE_SAMPLES = 101
|
||||
MAX_POINTS = 32
|
||||
DEFAULT_POINTS = "[[0, 1], [1, 1]]"
|
||||
SCHEDULE_LIMIT = 10.0
|
||||
# Strengths closer than this are one keyframe: core rebuilds a LoRA's weights
|
||||
# each time the keyframe changes, and a step that moves by less is not worth it.
|
||||
_KEYFRAME_STEP = 1e-4
|
||||
|
||||
|
||||
def _number(value: Any, what: str) -> float:
|
||||
try:
|
||||
number = float(value)
|
||||
except (TypeError, ValueError):
|
||||
raise ValueError(f"Strength Curve: {what} must be a number, got {value!r}.") from None
|
||||
if not math.isfinite(number):
|
||||
raise ValueError(f"Strength Curve: {what} must be a finite number.")
|
||||
return number
|
||||
|
||||
|
||||
def parse_points(raw: Any) -> list[tuple[float, float]]:
|
||||
"""Clean, sorted points that start at 0 and end at 1.
|
||||
|
||||
Accepts the saved JSON text or a list of [where, value] pairs (or
|
||||
{"x", "y"} objects). Both coordinates are held to 0..1; two points at
|
||||
the same place keep the later one. A curve that does not reach an end
|
||||
is carried flat to it. An empty value is a flat line at 1.
|
||||
"""
|
||||
data = raw
|
||||
if raw is None or (isinstance(raw, str) and not raw.strip()):
|
||||
data = json.loads(DEFAULT_POINTS)
|
||||
elif isinstance(raw, str):
|
||||
try:
|
||||
data = json.loads(raw)
|
||||
except json.JSONDecodeError as exc:
|
||||
raise ValueError(f"Strength Curve: the points are not valid JSON ({exc.msg}).") from None
|
||||
if not isinstance(data, list):
|
||||
raise ValueError("Strength Curve: the points must be a list of [where, value] pairs.")
|
||||
if len(data) > MAX_POINTS:
|
||||
raise ValueError(f"Strength Curve: at most {MAX_POINTS} points, got {len(data)}.")
|
||||
found: dict[float, float] = {}
|
||||
for index, entry in enumerate(data, start=1):
|
||||
if isinstance(entry, dict):
|
||||
entry = [entry.get("x"), entry.get("y")]
|
||||
if not isinstance(entry, (list, tuple)) or len(entry) != 2:
|
||||
raise ValueError(f"Strength Curve: point {index} must be a [where, value] pair.")
|
||||
x = min(1.0, max(0.0, _number(entry[0], f"point {index}'s place")))
|
||||
y = min(1.0, max(0.0, _number(entry[1], f"point {index}'s value")))
|
||||
found[x] = y
|
||||
if not found:
|
||||
return [(0.0, 1.0), (1.0, 1.0)]
|
||||
points = sorted(found.items())
|
||||
if points[0][0] > 0.0:
|
||||
points.insert(0, (0.0, points[0][1]))
|
||||
if points[-1][0] < 1.0:
|
||||
points.append((1.0, points[-1][1]))
|
||||
return points
|
||||
|
||||
|
||||
def _slopes(xs: list[float], ys: list[float]) -> list[float]:
|
||||
"""Tangents that keep each piece inside its two points (Fritsch-Carlson)."""
|
||||
count = len(xs)
|
||||
secants = [(ys[i + 1] - ys[i]) / (xs[i + 1] - xs[i]) for i in range(count - 1)]
|
||||
slopes = [secants[0], *[0.0] * (count - 2), secants[-1]]
|
||||
for i in range(1, count - 1):
|
||||
before, after = secants[i - 1], secants[i]
|
||||
slopes[i] = 0.0 if before * after <= 0 else (before + after) / 2
|
||||
for i, secant in enumerate(secants):
|
||||
if secant == 0:
|
||||
slopes[i] = slopes[i + 1] = 0.0
|
||||
continue
|
||||
a, b = slopes[i] / secant, slopes[i + 1] / secant
|
||||
length = a * a + b * b
|
||||
if length > 9:
|
||||
scale = 3 / math.sqrt(length)
|
||||
slopes[i], slopes[i + 1] = scale * a * secant, scale * b * secant
|
||||
return slopes
|
||||
|
||||
|
||||
def curve_values(points: list[tuple[float, float]], places: list[float]) -> list[float]:
|
||||
"""The curve's value (0..1) at each place (0..1)."""
|
||||
xs = [x for x, _ in points]
|
||||
ys = [y for _, y in points]
|
||||
if len(points) < 2:
|
||||
return [ys[0] if ys else 1.0 for _ in places]
|
||||
slopes = _slopes(xs, ys)
|
||||
out = []
|
||||
piece = 0
|
||||
for place in places:
|
||||
place = min(1.0, max(0.0, float(place)))
|
||||
piece = 0
|
||||
while piece < len(xs) - 2 and place > xs[piece + 1]:
|
||||
piece += 1
|
||||
width = xs[piece + 1] - xs[piece]
|
||||
t = (place - xs[piece]) / width
|
||||
t2, t3 = t * t, t * t * t
|
||||
value = ((2 * t3 - 3 * t2 + 1) * ys[piece] + (t3 - 2 * t2 + t) * width * slopes[piece]
|
||||
+ (-2 * t3 + 3 * t2) * ys[piece + 1] + (t3 - t2) * width * slopes[piece + 1])
|
||||
out.append(min(1.0, max(0.0, value)))
|
||||
return out
|
||||
|
||||
|
||||
def build_schedule(points: Any, low: float = 0.0, high: float = 1.0, count: int = CURVE_SAMPLES) -> list[float]:
|
||||
"""The curve as `count` evenly spread values, its 0 at `low` and its 1 at `high`."""
|
||||
low = _number(low, "Bottom")
|
||||
high = _number(high, "Top")
|
||||
places = [i / (count - 1) for i in range(count)]
|
||||
return [low + (high - low) * y for y in curve_values(parse_points(points), places)]
|
||||
|
||||
|
||||
def as_schedule(value: Any) -> list[float] | None:
|
||||
"""A schedule from a FLOATS link: a list of numbers, or one number for a flat line.
|
||||
|
||||
None stays None (nothing linked). Values are held to 0..SCHEDULE_LIMIT.
|
||||
"""
|
||||
if value is None:
|
||||
return None
|
||||
if isinstance(value, (int, float)) and not isinstance(value, bool):
|
||||
items = [value]
|
||||
else:
|
||||
try:
|
||||
items = [float(item) for item in value]
|
||||
except (TypeError, ValueError):
|
||||
raise ValueError("The curve input takes a list of numbers (FLOATS), like Strength Curve's output.") from None
|
||||
if not items:
|
||||
return None
|
||||
out = []
|
||||
for item in items:
|
||||
number = float(item)
|
||||
if not math.isfinite(number):
|
||||
raise ValueError("The curve input holds a value that is not a finite number.")
|
||||
out.append(min(SCHEDULE_LIMIT, max(0.0, number)))
|
||||
return out
|
||||
|
||||
|
||||
def schedule_at(values: list[float], place: float) -> float:
|
||||
"""The schedule's value at `place` (0 = start of the run, 1 = end), read straight between samples."""
|
||||
if not values:
|
||||
return 1.0
|
||||
if len(values) == 1:
|
||||
return float(values[0])
|
||||
spot = min(1.0, max(0.0, float(place))) * (len(values) - 1)
|
||||
left = min(int(spot), len(values) - 2)
|
||||
t = spot - left
|
||||
return float(values[left] * (1 - t) + values[left + 1] * t)
|
||||
|
||||
|
||||
def keyframe_plan(values: list[float], count: int = CURVE_SAMPLES) -> list[tuple[float, float]]:
|
||||
"""(start percent, strength) pairs for core hook keyframes.
|
||||
|
||||
The schedule is read at `count` evenly spread places so a short list
|
||||
still changes smoothly, and a run of equal strengths keeps one keyframe:
|
||||
core rebuilds hooked weights only where the strength moves.
|
||||
"""
|
||||
plan: list[tuple[float, float]] = []
|
||||
for i in range(count):
|
||||
percent = i / (count - 1)
|
||||
strength = round(schedule_at(values, percent), 4)
|
||||
if plan and abs(plan[-1][1] - strength) < _KEYFRAME_STEP:
|
||||
continue
|
||||
plan.append((percent, strength))
|
||||
return plan
|
||||
|
||||
|
||||
def noise_plan(plan: list[tuple[float, float]], percent_to_sigma) -> list[tuple[float, float]]:
|
||||
"""The keyframe plan with each start place turned into the model's noise level for it."""
|
||||
return [(float(percent_to_sigma(percent)), strength) for percent, strength in plan]
|
||||
|
||||
|
||||
def strength_at_noise(starts: list[tuple[float, float]], sigma: float, first: bool = False) -> float:
|
||||
"""The curve's strength for the step at noise level ``sigma``, read the way core reads hook keyframes.
|
||||
|
||||
``starts`` is ``noise_plan``'s list, earliest first. The run's first step
|
||||
takes the first keyframe; a later step takes the last keyframe whose
|
||||
start the run has reached (noise levels fall as the run goes on).
|
||||
"""
|
||||
if not starts:
|
||||
return 1.0
|
||||
strength = starts[0][1]
|
||||
if first:
|
||||
return strength
|
||||
for start, value in starts[1:]:
|
||||
if start >= sigma:
|
||||
strength = value
|
||||
else:
|
||||
break
|
||||
return strength
|
||||
|
||||
|
||||
def hook_keyframes(values: list[float]):
|
||||
"""A core HookKeyframeGroup that follows the schedule over the run.
|
||||
|
||||
Core turns each start percent into a noise level once the model is known
|
||||
and, at every step, takes the last keyframe the run has reached.
|
||||
"""
|
||||
import comfy.hooks
|
||||
|
||||
group = comfy.hooks.HookKeyframeGroup()
|
||||
for index, (percent, strength) in enumerate(keyframe_plan(values)):
|
||||
group.add(comfy.hooks.HookKeyframe(strength=strength, start_percent=percent,
|
||||
guarantee_steps=1 if index == 0 else 0))
|
||||
return group
|
||||
@@ -0,0 +1,128 @@
|
||||
"""A see-through cut-out from a picture and a mask, for Cut Out 🆎.
|
||||
|
||||
The mask becomes the cut-out's alpha (how solid each pixel is) in a fixed
|
||||
order: pick the white or the black part, grow or shrink it, feather it,
|
||||
average it over neighbouring video frames, then clear the faint haze and
|
||||
make the near-solid core fully solid.
|
||||
|
||||
Where the alpha is in between (hair, a soft or blurred edge) the picture's
|
||||
colour is a mix of the subject and the old background, and a cut-out laid on
|
||||
a new background would carry a rim of the old one. Clean edges works out the
|
||||
subject's own colour there with blur-fusion foreground estimation (Forte and
|
||||
Pitie, "Approximate Fast Foreground Colour Estimation", ICIP 2021), the pack's
|
||||
own version of which is `clean_colours` in _fine_edge_helpers.py: blurred
|
||||
averages of the subject and of the background around each pixel, corrected
|
||||
by what the pixel actually shows, once wide and once narrow. Pixels the
|
||||
alpha keeps fully solid keep their colours exactly.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import torch
|
||||
|
||||
from ._execution_helpers import raise_if_interrupted
|
||||
from ._fine_edge_helpers import clean_colours
|
||||
from ._fit_helpers import batch_size, checked_mask, frames_at, mask_at
|
||||
from ._mask_helpers import blur_mask, grow_shrink_mask, remap_mask
|
||||
|
||||
KEEP_CHOICES = ("white", "black")
|
||||
# Frames worked on at once while the colours are cleaned.
|
||||
CHUNK = 8
|
||||
# Alpha this close to solid or clear is made exactly solid or clear.
|
||||
SNAP = 1e-4
|
||||
|
||||
|
||||
def smooth_over_frames(alpha: torch.Tensor, reach: int) -> torch.Tensor:
|
||||
"""Each frame's alpha averaged with up to `reach` frames either side.
|
||||
|
||||
At the start and end of the clip the window is shorter rather than
|
||||
padded, so the first frame is not pulled toward a copy of itself.
|
||||
"""
|
||||
reach = int(reach)
|
||||
count = int(alpha.shape[0])
|
||||
if reach <= 0 or count < 2:
|
||||
return alpha
|
||||
running = torch.cat([alpha.new_zeros((1, *alpha.shape[1:])), alpha.double().cumsum(0)])
|
||||
index = torch.arange(count)
|
||||
low = (index - reach).clamp(min=0)
|
||||
high = (index + reach + 1).clamp(max=count)
|
||||
totals = running[high] - running[low]
|
||||
return (totals / (high - low).view(-1, 1, 1).double()).to(alpha.dtype)
|
||||
|
||||
|
||||
def cut_out_alpha(
|
||||
mask: torch.Tensor,
|
||||
height: int,
|
||||
width: int,
|
||||
keep: str,
|
||||
grow: int,
|
||||
feather: float,
|
||||
smooth_frames: int,
|
||||
clear_haze: float,
|
||||
solid_above: float,
|
||||
device,
|
||||
) -> torch.Tensor:
|
||||
"""The cut-out's alpha, 1 where the picture is kept: one frame per mask
|
||||
frame (a single mask frame serves every picture frame)."""
|
||||
if keep not in KEEP_CHOICES:
|
||||
raise ValueError(f"Cut Out: keep must be one of {', '.join(KEEP_CHOICES)}.")
|
||||
count = int(mask.shape[0])
|
||||
alpha = mask_at(mask, 0, count, height, width, device).clone()
|
||||
if keep == "black":
|
||||
alpha = 1.0 - alpha
|
||||
alpha = grow_shrink_mask(alpha, int(grow))
|
||||
alpha = blur_mask(alpha, float(feather))
|
||||
alpha = smooth_over_frames(alpha, smooth_frames)
|
||||
alpha = remap_mask(alpha, float(clear_haze), float(solid_above)).clamp(0.0, 1.0)
|
||||
# A blur sums its weights to a hair under 1, which would leave the middle
|
||||
# of the subject a hair see-through; values that close count as solid or
|
||||
# clear.
|
||||
alpha = torch.where(alpha >= 1.0 - SNAP, torch.ones_like(alpha), alpha)
|
||||
return torch.where(alpha <= SNAP, torch.zeros_like(alpha), alpha)
|
||||
|
||||
|
||||
def cut_out(
|
||||
image: torch.Tensor,
|
||||
mask: torch.Tensor,
|
||||
keep: str = "white",
|
||||
grow: int = 0,
|
||||
feather: float = 1.0,
|
||||
clean_edges: bool = True,
|
||||
clear_haze: float = 0.0,
|
||||
solid_above: float = 1.0,
|
||||
smooth_frames: int = 0,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
"""The cut-out as RGBA with straight alpha, and its alpha as a MASK."""
|
||||
if not isinstance(image, torch.Tensor) or image.ndim != 4:
|
||||
raise ValueError("Cut Out expected an IMAGE batch.")
|
||||
height, width = int(image.shape[1]), int(image.shape[2])
|
||||
mask = checked_mask(mask, height, width, "Cut Out")
|
||||
frames = batch_size("Cut Out", int(image.shape[0]), int(mask.shape[0]))
|
||||
alpha = cut_out_alpha(
|
||||
mask, height, width, keep, grow, feather, smooth_frames, clear_haze, solid_above, image.device
|
||||
)
|
||||
result = torch.empty((frames, height, width, 4), dtype=image.dtype, device=image.device)
|
||||
alphas = torch.empty((frames, height, width), dtype=torch.float32, device=image.device)
|
||||
for start in range(0, frames, CHUNK):
|
||||
raise_if_interrupted()
|
||||
end = min(frames, start + CHUNK)
|
||||
part = frames_at(image, start, end).float()
|
||||
rgb = part[..., :3]
|
||||
cover = alpha[start:end] if int(alpha.shape[0]) > 1 else alpha[:1].expand(end - start, -1, -1)
|
||||
if int(part.shape[-1]) == 4:
|
||||
cover = cover * part[..., 3].clamp(0.0, 1.0)
|
||||
colours = rgb
|
||||
if clean_edges:
|
||||
colours = rgb.clone()
|
||||
for index in range(end - start):
|
||||
frame_alpha = cover[index]
|
||||
if not bool(((frame_alpha > 0.0) & (frame_alpha < 1.0)).any()):
|
||||
continue
|
||||
clean = clean_colours(rgb[index], frame_alpha).to(rgb.dtype)
|
||||
colours[index] = torch.where((frame_alpha >= 1.0).unsqueeze(-1), rgb[index], clean)
|
||||
result[start:end] = torch.cat([colours, cover.unsqueeze(-1)], dim=-1).to(image.dtype)
|
||||
alphas[start:end] = cover
|
||||
return result, alphas
|
||||
|
||||
|
||||
__all__ = ["KEEP_CHOICES", "cut_out", "cut_out_alpha", "smooth_over_frames"]
|
||||
@@ -0,0 +1,178 @@
|
||||
"""The original's fine detail on an edited picture, for Keep Detail 🆎.
|
||||
|
||||
Both pictures are split into a base (the picture blurred by `detail_size`
|
||||
pixels: shapes, light and colour) and detail (what the blur took away:
|
||||
skin, fabric, grain). The result is the edit's base with the original's
|
||||
detail on it.
|
||||
|
||||
The split is a ratio in linear light: detail is how much brighter or darker
|
||||
each pixel is than the base around it, as a factor. A factor carries over
|
||||
between pictures that are lit differently: pores that are 8 % darker than the
|
||||
skin around them stay 8 % darker on a relit face, where a difference would
|
||||
paint the bright original's texture too strong into a dark edit, or too weak
|
||||
into a bright one. Linear light (the picture's values with the sRGB curve
|
||||
taken off) is where light adds up physically, so the factor means the same
|
||||
in the shadows as in the highlights.
|
||||
|
||||
Light only puts the factor of the luminance on all three channels alike, so
|
||||
each pixel only gets brighter or darker and its colour never shifts. Colour
|
||||
+ light takes a factor per channel, so freckles and stains bring their
|
||||
colour too.
|
||||
|
||||
The base is a Gaussian blur, or with `edge_safe` a guided filter (He, Sun
|
||||
and Tang, 2010) of the picture by itself, which smooths texture but follows
|
||||
strong edges. A plain blur spreads a strong edge into its base, and the
|
||||
detail then carries a light and a dark band along the edge: a halo.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
|
||||
from ._execution_helpers import raise_if_interrupted
|
||||
from ._fit_helpers import batch_size, checked_mask, frames_at, mask_at, resized_frames
|
||||
|
||||
# Added to light before a ratio is taken, so a black pixel has no detail to
|
||||
# give or take instead of dividing by nothing.
|
||||
LIGHT_FLOOR = 2e-3
|
||||
# Below this, a channel counts as black when sharing out light (keeps hue).
|
||||
HUE_KEEP = 1e-6
|
||||
# What the edge-safe base counts as an edge, on the sRGB-curved values: a
|
||||
# step that varies the values around it by more than about this much stays in
|
||||
# the base. Skin, fabric and wood grain vary them less and go to the detail;
|
||||
# at 0.05 even wood grain counted as edges and only half of it came back.
|
||||
EDGE_STEP = 0.15
|
||||
LUMA = (0.2126, 0.7152, 0.0722)
|
||||
CHUNK = 4
|
||||
|
||||
|
||||
def srgb_to_linear(values: torch.Tensor) -> torch.Tensor:
|
||||
values = values.clamp(0.0, 1.0)
|
||||
return torch.where(values <= 0.04045, values / 12.92, ((values + 0.055) / 1.055) ** 2.4)
|
||||
|
||||
|
||||
def linear_to_srgb(values: torch.Tensor) -> torch.Tensor:
|
||||
values = values.clamp_min(0.0)
|
||||
return torch.where(values <= 0.0031308, values * 12.92, 1.055 * values.clamp_min(1e-12) ** (1.0 / 2.4) - 0.055)
|
||||
|
||||
|
||||
def _box(values: torch.Tensor, radius: int) -> torch.Tensor:
|
||||
"""Mean over a (2r+1)-square window, B x C x H x W, edges repeated."""
|
||||
if radius <= 0:
|
||||
return values
|
||||
size = 2 * radius + 1
|
||||
values = F.avg_pool2d(F.pad(values, (radius, radius, 0, 0), mode="replicate"), (1, size), stride=1)
|
||||
return F.avg_pool2d(F.pad(values, (0, 0, radius, radius), mode="replicate"), (size, 1), stride=1)
|
||||
|
||||
|
||||
def _gaussian(values: torch.Tensor, sigma: float) -> torch.Tensor:
|
||||
"""Gaussian blur, B x C x H x W, edges repeated."""
|
||||
radius = max(1, int(math.ceil(3.0 * sigma)))
|
||||
radius = min(radius, max(1, min(values.shape[-2:]) - 1))
|
||||
taps = torch.arange(-radius, radius + 1, dtype=values.dtype, device=values.device)
|
||||
kernel = torch.exp(-(taps**2) / (2.0 * sigma * sigma))
|
||||
kernel = kernel / kernel.sum()
|
||||
channels = int(values.shape[1])
|
||||
across = kernel.view(1, 1, 1, -1).repeat(channels, 1, 1, 1)
|
||||
down = kernel.view(1, 1, -1, 1).repeat(channels, 1, 1, 1)
|
||||
values = F.conv2d(F.pad(values, (radius, radius, 0, 0), mode="replicate"), across, groups=channels)
|
||||
return F.conv2d(F.pad(values, (0, 0, radius, radius), mode="replicate"), down, groups=channels)
|
||||
|
||||
|
||||
def _box_radius(sigma: float) -> int:
|
||||
"""The box radius that spreads as far as a Gaussian of this sigma (the
|
||||
same standard deviation), so both bases split detail at the same size."""
|
||||
return max(1, round(math.sqrt(3.0 * float(sigma) ** 2 + 0.25) - 0.5))
|
||||
|
||||
|
||||
def _guided(values: torch.Tensor, radius: int) -> torch.Tensor:
|
||||
"""The picture smoothed with itself as the guide: texture goes, strong edges stay."""
|
||||
mean = _box(values, radius)
|
||||
spread = (_box(values * values, radius) - mean * mean).clamp_min(0.0)
|
||||
keep = spread / (spread + EDGE_STEP**2)
|
||||
offset = mean - keep * mean
|
||||
return _box(keep, radius) * values + _box(offset, radius)
|
||||
|
||||
|
||||
def base_light(light: torch.Tensor, detail_size: float, edge_safe: bool) -> torch.Tensor:
|
||||
"""The base of linear light, B x C x H x W: what is left once the detail
|
||||
smaller than `detail_size` pixels is smoothed away. The smoothing runs on
|
||||
sRGB-curved values, where an edge's size matches how strong it looks."""
|
||||
curved = linear_to_srgb(light)
|
||||
if edge_safe:
|
||||
smooth = _guided(curved, _box_radius(detail_size))
|
||||
else:
|
||||
smooth = _gaussian(curved, max(float(detail_size), 0.5))
|
||||
return srgb_to_linear(smooth)
|
||||
|
||||
|
||||
def _light(rgb: torch.Tensor, color_detail: bool) -> torch.Tensor:
|
||||
"""B x C x H x W linear light: the three channels, or the luminance alone."""
|
||||
linear = srgb_to_linear(rgb).movedim(-1, 1)
|
||||
if color_detail:
|
||||
return linear
|
||||
return (linear * linear.new_tensor(LUMA).view(1, 3, 1, 1)).sum(1, keepdim=True)
|
||||
|
||||
|
||||
def keep_detail(
|
||||
image: torch.Tensor,
|
||||
detail_from: torch.Tensor,
|
||||
detail_size: float = 4.0,
|
||||
strength: float = 1.0,
|
||||
color_detail: bool = False,
|
||||
edge_safe: bool = True,
|
||||
mask: torch.Tensor | None = None,
|
||||
) -> tuple[torch.Tensor, bool]:
|
||||
"""The edit with the original's detail, and whether `detail_from` was resized.
|
||||
|
||||
Strength 0 leaves the edit as it is, 1 swaps the edit's own detail for the
|
||||
original's, and above 1 lays the original's on stronger.
|
||||
"""
|
||||
for picture, name in ((image, "image"), (detail_from, "detail_from")):
|
||||
if not isinstance(picture, torch.Tensor) or picture.ndim != 4:
|
||||
raise ValueError(f"Keep Detail expected an IMAGE batch on {name}.")
|
||||
height, width = int(image.shape[1]), int(image.shape[2])
|
||||
resized = tuple(detail_from.shape[1:3]) != (height, width)
|
||||
detail_from = resized_frames(detail_from, height, width)
|
||||
if mask is not None:
|
||||
mask = checked_mask(mask, height, width, "Keep Detail")
|
||||
frames = batch_size(
|
||||
"Keep Detail", int(image.shape[0]), int(detail_from.shape[0]), int(mask.shape[0]) if mask is not None else 1
|
||||
)
|
||||
strength = max(float(strength), 0.0)
|
||||
if strength == 0.0:
|
||||
return frames_at(image, 0, frames).clone(), resized
|
||||
own = max(0.0, 1.0 - strength)
|
||||
result = torch.empty((frames, height, width, int(image.shape[3])), dtype=image.dtype, device=image.device)
|
||||
for start in range(0, frames, CHUNK):
|
||||
raise_if_interrupted()
|
||||
end = min(frames, start + CHUNK)
|
||||
edit = frames_at(image, start, end).float()
|
||||
original = frames_at(detail_from, start, end).float().to(edit.device)
|
||||
rgb = edit[..., :3]
|
||||
edit_light = _light(rgb, color_detail)
|
||||
original_light = _light(original[..., :3], color_detail)
|
||||
edit_base = base_light(edit_light, detail_size, edge_safe) + LIGHT_FLOOR
|
||||
original_detail = (original_light + LIGHT_FLOOR) / (base_light(original_light, detail_size, edge_safe) + LIGHT_FLOOR)
|
||||
edit_detail = (edit_light + LIGHT_FLOOR) / edit_base
|
||||
target = edit_base * original_detail.pow(strength) * edit_detail.pow(own)
|
||||
factor = (target / (edit_light + LIGHT_FLOOR)).movedim(1, -1)
|
||||
linear = srgb_to_linear(rgb)
|
||||
# The floor's share of light goes to each channel in proportion to it
|
||||
# when only light is kept, so a saturated colour keeps its hue (black
|
||||
# gets it evenly); the brightness reached is the same.
|
||||
share = 1.0 if color_detail else (linear + HUE_KEEP) / ((linear * linear.new_tensor(LUMA)).sum(-1, keepdim=True) + HUE_KEEP)
|
||||
lit = linear * factor + LIGHT_FLOOR * (factor - 1.0) * share
|
||||
change = linear_to_srgb(lit) - linear_to_srgb(linear)
|
||||
if mask is not None:
|
||||
change = change * mask_at(mask, start, end, height, width, edit.device).unsqueeze(-1)
|
||||
out = edit.clone()
|
||||
out[..., :3] = (rgb + change).clamp(0.0, 1.0)
|
||||
result[start:end] = out.to(image.dtype)
|
||||
return result, resized
|
||||
|
||||
|
||||
__all__ = ["base_light", "keep_detail", "linear_to_srgb", "srgb_to_linear"]
|
||||
@@ -285,6 +285,8 @@ class EditLock:
|
||||
self.wide: float | None = None # share of the picture the lock would free, at the decision
|
||||
self.top: float | None = None # the strongest spot then, in units of the quiet level
|
||||
self.peak: float | None = None # and the strongest hundredth
|
||||
self.vae_channels: int | None = None # when the VAE and model disagree: the picture's channels
|
||||
self.model_channels: int | None = None # and the channels the model predicts
|
||||
self._sigma: float | None = None
|
||||
self._first = True
|
||||
self._first_sigma = 1.0
|
||||
@@ -328,6 +330,7 @@ class EditLock:
|
||||
latent = self.latent[:, :, 0] if self.latent.ndim == 5 else self.latent
|
||||
if latent.shape[1] != flat.shape[1]:
|
||||
self.status = "vae"
|
||||
self.vae_channels, self.model_channels = int(latent.shape[1]), int(flat.shape[1])
|
||||
return pred
|
||||
source = fit_latent(latent.to(device=flat.device, dtype=torch.float32), *flat.shape[-2:])
|
||||
if source is None:
|
||||
@@ -451,5 +454,11 @@ def describe(lock: EditLock) -> str:
|
||||
if lock.status == "video":
|
||||
return "Edit Lock did nothing: it works on single pictures, not video."
|
||||
if lock.status == "vae":
|
||||
return "Edit Lock did nothing: this VAE does not belong to this model."
|
||||
counts = ""
|
||||
if lock.vae_channels is not None and lock.model_channels is not None:
|
||||
counts = (f" (your VAE makes {lock.vae_channels}-channel pictures, "
|
||||
f"the model expects {lock.model_channels})")
|
||||
return ("Edit Lock did nothing: the VAE and the diffusion model don't match"
|
||||
f"{counts}. Either file can be the wrong one. Use the model and VAE listed "
|
||||
"in the workflow's notes. A GGUF or other converted model is a common cause.")
|
||||
return "Edit Lock has not run yet: plug its model output into the sampler."
|
||||
|
||||
+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
|
||||
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
"""Fitting a mask or a second picture to a picture batch.
|
||||
|
||||
Film Grain, Cut Out and Keep Detail all take a picture batch plus a mask or a
|
||||
second picture that may come at another size or with another frame count.
|
||||
These helpers say in plain words when the two cannot go together, and stretch
|
||||
the second one to the picture when they can.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
|
||||
from ._mask_helpers import NO_MASK_PAINTED, UNPAINTED_MASK_SIZE, is_unpainted_mask
|
||||
|
||||
|
||||
def batch_size(source: str, *counts: int) -> int:
|
||||
"""The frame count of a result made from batches of these sizes.
|
||||
|
||||
A batch of one goes with every frame; any other sizes must agree.
|
||||
"""
|
||||
sizes = {int(count) for count in counts if int(count) != 1}
|
||||
if len(sizes) > 1:
|
||||
listed = " and ".join(str(size) for size in sorted(sizes))
|
||||
raise ValueError(
|
||||
f"{source}: the inputs have {listed} frames. Give them the same number of frames, or one frame."
|
||||
)
|
||||
return sizes.pop() if sizes else 1
|
||||
|
||||
|
||||
def frames_at(frames: torch.Tensor, start: int, end: int) -> torch.Tensor:
|
||||
"""Frames start..end of a batch, or its one frame repeated."""
|
||||
if int(frames.shape[0]) == 1:
|
||||
return frames[:1].expand(end - start, *frames.shape[1:])
|
||||
return frames[start:end]
|
||||
|
||||
|
||||
def checked_mask(mask: torch.Tensor, height: int, width: int, source: str) -> torch.Tensor:
|
||||
"""The mask as BHW floats, or a plain-words error for one that cannot be used."""
|
||||
if isinstance(mask, torch.Tensor) and mask.ndim == 2:
|
||||
mask = mask.unsqueeze(0)
|
||||
if not isinstance(mask, torch.Tensor) or mask.ndim != 3:
|
||||
raise ValueError(f"{source} expected a MASK.")
|
||||
if is_unpainted_mask(mask) and (height, width) != UNPAINTED_MASK_SIZE:
|
||||
raise ValueError(f"{source}: {NO_MASK_PAINTED}")
|
||||
return mask
|
||||
|
||||
|
||||
def mask_at(mask: torch.Tensor, start: int, end: int, height: int, width: int, device) -> torch.Tensor:
|
||||
"""Mask frames start..end at the picture's size, as floats from 0 to 1."""
|
||||
part = mask[:1] if int(mask.shape[0]) == 1 else mask[start:end]
|
||||
part = part.to(device=device, dtype=torch.float32)
|
||||
if tuple(part.shape[-2:]) != (height, width):
|
||||
part = F.interpolate(part.unsqueeze(1), size=(height, width), mode="bilinear", align_corners=False)[:, 0]
|
||||
part = part.clamp(0.0, 1.0)
|
||||
if int(part.shape[0]) == 1 and end - start > 1:
|
||||
part = part.expand(end - start, -1, -1)
|
||||
return part
|
||||
|
||||
|
||||
def resized_frames(frames: torch.Tensor, height: int, width: int) -> torch.Tensor:
|
||||
"""A BHWC batch at another size (smooth, antialiased when it shrinks)."""
|
||||
if tuple(frames.shape[1:3]) == (height, width):
|
||||
return frames
|
||||
moved = frames.movedim(-1, 1).float()
|
||||
moved = F.interpolate(moved, size=(height, width), mode="bicubic", align_corners=False, antialias=True)
|
||||
return moved.movedim(1, -1).clamp(0.0, 1.0)
|
||||
|
||||
|
||||
__all__ = ["batch_size", "checked_mask", "frames_at", "mask_at", "resized_frames"]
|
||||
@@ -0,0 +1,247 @@
|
||||
"""Photographic film grain for Film Grain 🆎.
|
||||
|
||||
The grain is random noise shaped to look like film rather than like a
|
||||
digital sensor:
|
||||
|
||||
- Size: the noise is drawn on a grid `size` pixels apart and smoothed up to
|
||||
the picture, so each grain is about `size` pixels across at the picture's
|
||||
own resolution. Grain smaller than a pixel averages out inside the pixel,
|
||||
so below 1 it also gets quieter, as it does on a fine film stock.
|
||||
- Roughness mixes in a second, finer layer whose strength is uneven: a
|
||||
wide, slow noise decides where the fine grain bunches up.
|
||||
- Color mixes one grain shared by red, green and blue (monochrome, like
|
||||
black-and-white film or a scan's luminance grain) with a separate grain
|
||||
per channel (the dye clouds of colour film).
|
||||
- Grain is strongest in the midtones and gentler in deep shadows and bright
|
||||
highlights, where film has little density left to vary.
|
||||
|
||||
Auto mode picks the amount and size from the picture itself. The grain size
|
||||
follows the picture's size (a 4 MP picture gets twice the size a 1 MP one
|
||||
does: the square root of the megapixels), and the amount starts at the normal
|
||||
0.25 and goes up by the grain the picture already has, measured in its flat
|
||||
areas (`measure_noise`). The Film Grain card's Amount and Size then count as
|
||||
multipliers of those picks.
|
||||
|
||||
Every frame's grain comes from its own seed, worked out from the node's seed
|
||||
and the frame number, so the same seed always gives the same result however
|
||||
the batch is split up. Frames go through a few at a time, which keeps a long
|
||||
1080p clip's working memory to a few frames' worth.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
|
||||
from ._execution_helpers import raise_if_interrupted
|
||||
from ._fit_helpers import batch_size, checked_mask, frames_at, mask_at
|
||||
|
||||
# How far the grain moves a mid-grey pixel at amount 1, as one standard
|
||||
# deviation in 0-1 picture values. 0.25, the default amount, is about 10 of
|
||||
# 255: clearly visible 35 mm grain, not snow.
|
||||
FULL_STRENGTH = 0.15
|
||||
# How much grain the darkest and brightest pixels keep, against mid grey.
|
||||
TONE_FLOOR = 0.2
|
||||
# The bunching of rough grain: how much the slow noise moves the fine grain's
|
||||
# strength, and how much wider it is than a grain.
|
||||
CLUMP_DEPTH = 0.6
|
||||
CLUMP_SCALE = 4.0
|
||||
# Grain is rounded off softly past this many standard deviations, so a rare
|
||||
# extreme value never shows as a lone white or black speck.
|
||||
GRAIN_LIMIT = 3.0
|
||||
# Frames worked on at once.
|
||||
CHUNK = 8
|
||||
# Spreads frame numbers over the seed range (the 64-bit golden ratio).
|
||||
FRAME_STEP = 0x9E3779B97F4A7C15
|
||||
SEED_RANGE = 1 << 64
|
||||
LUMA = (0.2126, 0.7152, 0.0722)
|
||||
# Auto: the normal amount, the picture size that gets size 1, and the limits
|
||||
# of what Auto may pick.
|
||||
AUTO_AMOUNT = 0.25
|
||||
AUTO_SIZE_MEGAPIXELS = 1.0
|
||||
AUTO_AMOUNT_RANGE = (0.05, 1.0)
|
||||
AUTO_SIZE_RANGE = (0.5, 16.0)
|
||||
# Grain a picture counts as having of its own, in 0-1 picture values: an
|
||||
# 8-bit picture's rounding alone measures about this much and is not grain.
|
||||
OWN_GRAIN_FLOOR = 0.0015
|
||||
# Noise is read from this many frames of a clip at most.
|
||||
MEASURED_FRAMES = 4
|
||||
# The noise measure sorts |detail| into this many steps up to this value.
|
||||
NOISE_BINS = 4096
|
||||
NOISE_TOP = 0.25
|
||||
# The Laplacian-difference mask's gain on white noise (Immerkaer 1996) and the
|
||||
# median of |x| for a normal x: sigma = median(|mask * picture|) / (gain * median).
|
||||
NOISE_GAIN = 6.0
|
||||
HALF_NORMAL_MEDIAN = 0.6744897501960817
|
||||
|
||||
|
||||
def frame_seed(seed: int, frame: int, moving: bool) -> int:
|
||||
"""The seed of one frame's grain: the node's seed, or with `moving` one per frame."""
|
||||
return (int(seed) + (int(frame) * FRAME_STEP if moving else 0)) % SEED_RANGE
|
||||
|
||||
|
||||
def _field(generator: torch.Generator, height: int, width: int, size: float, channels: int) -> torch.Tensor:
|
||||
"""Noise in grains about `size` pixels across, 1 x C x H x W.
|
||||
|
||||
Above one pixel the grains are smoothed up from a coarser grid and keep a
|
||||
spread of 1. Below one pixel several grains share a pixel and average
|
||||
out, so the spread falls with the size.
|
||||
"""
|
||||
rows = max(1, round(height / size))
|
||||
cols = max(1, round(width / size))
|
||||
noise = torch.randn((1, channels, rows, cols), generator=generator)
|
||||
if (rows, cols) == (height, width):
|
||||
return noise
|
||||
if rows > height or cols > width:
|
||||
return F.interpolate(noise, size=(height, width), mode="area")
|
||||
noise = F.interpolate(noise, size=(height, width), mode="bicubic", align_corners=False)
|
||||
return noise / noise.std().clamp_min(1e-6)
|
||||
|
||||
|
||||
def grain_frame(seed: int, height: int, width: int, size: float, roughness: float, color: float) -> torch.Tensor:
|
||||
"""One frame's grain, C x H x W with C = 1 (monochrome) or 3."""
|
||||
generator = torch.Generator().manual_seed(int(seed))
|
||||
size = max(float(size), 1e-3)
|
||||
roughness = min(max(float(roughness), 0.0), 1.0)
|
||||
color = min(max(float(color), 0.0), 1.0)
|
||||
# Drawn in a fixed order, so a setting that adds a layer never changes
|
||||
# the layers drawn before it.
|
||||
layers = [(1, _field(generator, height, width, size, 1))]
|
||||
if color > 0.0:
|
||||
layers.append((3, _field(generator, height, width, size, 3)))
|
||||
if roughness > 0.0:
|
||||
clump = _field(generator, height, width, size * CLUMP_SCALE, 1)
|
||||
weight = torch.exp(CLUMP_DEPTH * clump)
|
||||
fine = [_field(generator, height, width, size / 2.0, channels) for channels, _ in layers]
|
||||
rough = [(layer * weight) for layer in fine]
|
||||
rough = [layer / layer.std().clamp_min(1e-6) * fine_layer.std() for layer, fine_layer in zip(rough, fine)]
|
||||
mix = (1.0 - roughness) ** 2 + roughness**2
|
||||
layers = [
|
||||
(channels, ((1.0 - roughness) * smooth + roughness * uneven) / mix**0.5)
|
||||
for (channels, smooth), uneven in zip(layers, rough)
|
||||
]
|
||||
grain = layers[0][1]
|
||||
if color > 0.0:
|
||||
grain = ((1.0 - color) * grain + color * layers[1][1]) / ((1.0 - color) ** 2 + color**2) ** 0.5
|
||||
return GRAIN_LIMIT * torch.tanh(grain[0] / GRAIN_LIMIT)
|
||||
|
||||
|
||||
def tone_weight(rgb: torch.Tensor) -> torch.Tensor:
|
||||
"""How strong the grain is at each pixel of a B x H x W x 3 batch: 1 at
|
||||
mid grey, falling to TONE_FLOOR at black and white."""
|
||||
luma = (rgb * rgb.new_tensor(LUMA)).sum(-1, keepdim=True).clamp(0.0, 1.0)
|
||||
return TONE_FLOOR + (1.0 - TONE_FLOOR) * 4.0 * luma * (1.0 - luma)
|
||||
|
||||
|
||||
def add_film_grain(
|
||||
image: torch.Tensor,
|
||||
amount: float,
|
||||
size: float,
|
||||
roughness: float,
|
||||
color: float,
|
||||
moving: bool,
|
||||
seed: int,
|
||||
mask: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
"""The picture batch with film grain, where the mask is white if there is one."""
|
||||
if not isinstance(image, torch.Tensor) or image.ndim != 4:
|
||||
raise ValueError("Film Grain expected an IMAGE batch.")
|
||||
height, width = int(image.shape[1]), int(image.shape[2])
|
||||
if mask is not None:
|
||||
mask = checked_mask(mask, height, width, "Film Grain")
|
||||
frames = batch_size("Film Grain", int(image.shape[0]), int(mask.shape[0]) if mask is not None else 1)
|
||||
if float(amount) <= 0.0:
|
||||
return frames_at(image, 0, frames).clone()
|
||||
strength = float(amount) * FULL_STRENGTH
|
||||
still = None if moving else grain_frame(frame_seed(seed, 0, False), height, width, size, roughness, color)
|
||||
result = torch.empty((frames, height, width, int(image.shape[3])), dtype=image.dtype, device=image.device)
|
||||
for start in range(0, frames, CHUNK):
|
||||
raise_if_interrupted()
|
||||
end = min(frames, start + CHUNK)
|
||||
part = frames_at(image, start, end).float()
|
||||
rgb = part[..., :3]
|
||||
if still is not None:
|
||||
grain = still.unsqueeze(0)
|
||||
else:
|
||||
grain = torch.stack(
|
||||
[grain_frame(frame_seed(seed, index, True), height, width, size, roughness, color) for index in range(start, end)]
|
||||
)
|
||||
grain = grain.movedim(1, -1).to(device=part.device)
|
||||
change = grain * tone_weight(rgb) * strength
|
||||
if mask is not None:
|
||||
change = change * mask_at(mask, start, end, height, width, part.device).unsqueeze(-1)
|
||||
out = part.clone()
|
||||
out[..., :3] = (rgb + change).clamp(0.0, 1.0)
|
||||
result[start:end] = out.to(image.dtype)
|
||||
return result
|
||||
|
||||
|
||||
def measure_noise(image: torch.Tensor) -> float:
|
||||
"""How much fine noise the picture has in its flat areas, as one standard
|
||||
deviation in 0-1 values (0 for a clean render).
|
||||
|
||||
A Laplacian-difference filter removes the picture's shapes and leaves the
|
||||
fine noise; edges and texture are a small part of any picture, so the
|
||||
median of what is left is the noise of the flat areas (Immerkaer, "Fast
|
||||
Noise Variance Estimation", 1996, with a median in place of the mean).
|
||||
The median is read from a histogram, so the browser's copy of this
|
||||
(js/shared/live_grain.mjs) gives the same number. A clip is read from up
|
||||
to four frames spread over it, and the middle value of those is used.
|
||||
"""
|
||||
if not isinstance(image, torch.Tensor) or image.ndim != 4:
|
||||
raise ValueError("Film Grain expected an IMAGE batch.")
|
||||
count = int(image.shape[0])
|
||||
picks = sorted({round(i * (count - 1) / max(MEASURED_FRAMES - 1, 1)) for i in range(min(count, MEASURED_FRAMES))})
|
||||
sigmas = sorted(_frame_noise(image[index]) for index in picks)
|
||||
return sigmas[len(sigmas) // 2]
|
||||
|
||||
|
||||
def _frame_noise(frame: torch.Tensor) -> float:
|
||||
height, width = int(frame.shape[0]), int(frame.shape[1])
|
||||
if height < 3 or width < 3:
|
||||
return 0.0
|
||||
rgb = frame[..., :3].detach().float().clamp(0.0, 1.0)
|
||||
luma = (rgb * rgb.new_tensor(LUMA[: rgb.shape[-1]])).sum(-1)
|
||||
kernel = luma.new_tensor([[1.0, -2.0, 1.0], [-2.0, 4.0, -2.0], [1.0, -2.0, 1.0]]).view(1, 1, 3, 3)
|
||||
detail = F.conv2d(luma.view(1, 1, height, width), kernel).abs().flatten().clamp(max=NOISE_TOP * (1.0 - 1e-6))
|
||||
bins = torch.bincount((detail / NOISE_TOP * NOISE_BINS).long(), minlength=NOISE_BINS)
|
||||
reached = torch.cumsum(bins, 0)
|
||||
middle = int(torch.searchsorted(reached, torch.tensor([detail.numel() / 2.0], dtype=reached.dtype)).item())
|
||||
centre = (min(middle, NOISE_BINS - 1) + 0.5) / NOISE_BINS * NOISE_TOP
|
||||
return centre / (NOISE_GAIN * HALF_NORMAL_MEDIAN)
|
||||
|
||||
|
||||
def auto_grain(height: int, width: int, noise: float) -> tuple[float, float]:
|
||||
"""The amount and size Auto picks for a picture: size follows the
|
||||
picture's size (square root of its megapixels), amount is the normal
|
||||
0.25 plus the picture's own grain."""
|
||||
megapixels = max(float(height) * float(width) / 1e6, 1e-6)
|
||||
size = (megapixels / AUTO_SIZE_MEGAPIXELS) ** 0.5
|
||||
amount = AUTO_AMOUNT + max(0.0, float(noise) - OWN_GRAIN_FLOOR) / FULL_STRENGTH
|
||||
low, high = AUTO_AMOUNT_RANGE
|
||||
amount = min(max(amount, low), high)
|
||||
low, high = AUTO_SIZE_RANGE
|
||||
return amount, min(max(size, low), high)
|
||||
|
||||
|
||||
def auto_film_grain_values(image: torch.Tensor, amount_times: float, size_times: float) -> dict:
|
||||
"""What Auto does for `image`: Auto's own picks ("base_amount",
|
||||
"base_size"), the measured noise, and the amount and size to use, which
|
||||
are the picks times the card's two multipliers, kept inside sensible
|
||||
limits."""
|
||||
noise = measure_noise(image)
|
||||
base_amount, base_size = auto_grain(int(image.shape[1]), int(image.shape[2]), noise)
|
||||
amount = min(max(base_amount * float(amount_times), 0.0), 1.0)
|
||||
size = min(max(base_size * float(size_times), AUTO_SIZE_RANGE[0]), AUTO_SIZE_RANGE[1])
|
||||
return {"amount": amount, "size": size, "base_amount": base_amount, "base_size": base_size, "noise": noise}
|
||||
|
||||
|
||||
__all__ = [
|
||||
"add_film_grain",
|
||||
"auto_film_grain_values",
|
||||
"auto_grain",
|
||||
"frame_seed",
|
||||
"grain_frame",
|
||||
"measure_noise",
|
||||
"tone_weight",
|
||||
]
|
||||
@@ -0,0 +1,245 @@
|
||||
"""Film Grain's grain match: read the grain of another picture and copy it.
|
||||
|
||||
With a picture on Film Grain's `grain_from` input and Auto on, the node
|
||||
reads how strong, how big and how colourful that picture's grain is, and
|
||||
adds grain like it.
|
||||
|
||||
How it reads the grain:
|
||||
|
||||
- Same viewing size. The picture to copy from is scaled to the megapixels
|
||||
of the picture getting the grain (its shape kept), so grain is compared
|
||||
as it would look at the same size on screen.
|
||||
- Plain patches only. Grain shows best where the picture itself is plain:
|
||||
a sky, a wall, skin. Both pictures are cut into small blocks, and only the
|
||||
plainest fifth of the mid-tone blocks is read, so the picture's own detail
|
||||
is mostly not taken for grain.
|
||||
- Several sizes. Fine detail is measured (a Laplacian filter, as in
|
||||
`measure_noise`) on the picture and on copies shrunk 1.5 to 12 times. How
|
||||
the strength falls from one size to the next tells the grain's size: fine
|
||||
grain mostly vanishes in the first shrink, coarse grain survives several.
|
||||
Colour grain is read the same way on two colour-difference channels.
|
||||
- Only the grain missing. What the target picture already has at each size
|
||||
is taken off first, so a picture that is already grainy gets less.
|
||||
- Fitted to Film Grain's own grain. A stored table (`_grain_match_table.py`)
|
||||
holds the same measures of Film Grain's grain at every size and colour;
|
||||
the closest one gives the size, the colour comes from how strong the
|
||||
colour grain is against the brightness grain, and the amount is then
|
||||
checked by adding grain to the target twice and correcting it.
|
||||
|
||||
Roughness is not read; it stays the card's own. A clip is read from its
|
||||
first frame, and so is a clip given as the picture to copy from.
|
||||
|
||||
Technical details: the fit works in log space and weighs each size by the
|
||||
share of grain it adds, with a mild pull toward size 1. Grain smaller than a
|
||||
pixel reads as size 1 and a lower amount, which looks the same. Reading a 1 MP pair takes
|
||||
about a third of a second on the CPU.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
|
||||
from . import _grain_helpers as G
|
||||
|
||||
# The shrink factors the grain is measured at.
|
||||
SCALES = (1.0, 1.5, 2.0, 3.0, 4.0, 6.0, 8.0, 12.0)
|
||||
# Brightness and two colour differences, each with a spread of 1 on white noise.
|
||||
OPPONENT = (
|
||||
(0.2126, 0.7152, 0.0722),
|
||||
(0.7071067811865476, -0.7071067811865476, 0.0),
|
||||
(0.4082482904638631, 0.4082482904638631, -0.8164965809277261),
|
||||
)
|
||||
LAPLACIAN = ((1.0, -2.0, 1.0), (-2.0, 4.0, -2.0), (1.0, -2.0, 1.0))
|
||||
# Mean |Laplacian| of white noise with a spread of 1: 6 * sqrt(2 / pi).
|
||||
LAPLACIAN_MEAN = 6.0 * math.sqrt(2.0 / math.pi)
|
||||
# Block side at each size, the share of the plainest blocks read, the fewest
|
||||
# mid-tone blocks worth reading, and what counts as a mid tone.
|
||||
BLOCK = 16
|
||||
PLAINEST = 0.2
|
||||
MIN_BLOCKS = 8
|
||||
MID_TONES = (0.15, 0.85)
|
||||
# The smallest side a shrunk copy is read at; sizes below it are skipped.
|
||||
MIN_SIDE = 32
|
||||
# Grain weaker than this (0-1 values) counts as none.
|
||||
NO_GRAIN = 1e-4
|
||||
# The pull toward size 1, against the fit's error.
|
||||
SIZE_PULL = 0.01
|
||||
# Rounds of the colour fit and of the amount check.
|
||||
COLOR_ROUNDS = 2
|
||||
AMOUNT_ROUNDS = 2
|
||||
# What the stored table was measured on: grain of this roughness on flat grey
|
||||
# of this side, from this seed.
|
||||
TABLE_ROUGHNESS = 0.5
|
||||
TABLE_SIDE = 640
|
||||
TABLE_SEED = 1234
|
||||
# Sizes from 1 up: grain smaller than a pixel is pixel noise at any size, and
|
||||
# the in-between sizes below 1 measure like coarser grain, so they are left out.
|
||||
TABLE_SIZES = tuple(round(2 ** (i / 6), 4) for i in range(25)) # 1 .. 16
|
||||
TABLE_COLORS = tuple(i / 10 for i in range(11))
|
||||
|
||||
|
||||
def _first_rgb(image: torch.Tensor) -> torch.Tensor:
|
||||
if not isinstance(image, torch.Tensor) or image.ndim != 4 or int(image.shape[0]) < 1:
|
||||
raise ValueError("Film Grain expected an IMAGE batch.")
|
||||
frame = image[0].detach().float()
|
||||
if int(frame.shape[-1]) == 1:
|
||||
frame = frame.expand(-1, -1, 3)
|
||||
return frame[..., :3].clamp(0.0, 1.0)
|
||||
|
||||
|
||||
def _blocks(channel: torch.Tensor, luma: torch.Tensor, side: int) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
"""Each block's grain (mean |Laplacian| as a spread) and mean brightness."""
|
||||
kernel = channel.new_tensor(LAPLACIAN).view(1, 1, 3, 3)
|
||||
detail = F.conv2d(channel[None, None], kernel).abs() / LAPLACIAN_MEAN
|
||||
grain = F.avg_pool2d(detail, side)[0, 0].flatten()
|
||||
tone = F.avg_pool2d(luma[None, None, 1:-1, 1:-1], side)[0, 0].flatten()
|
||||
return grain, tone
|
||||
|
||||
|
||||
def grain_profile(image: torch.Tensor) -> dict[float, tuple[float, float]]:
|
||||
"""The grain of the first frame at each size it is big enough for:
|
||||
{scale: (brightness grain, colour grain)}, as spreads in 0-1 values."""
|
||||
rgb = _first_rgb(image)
|
||||
opponent = torch.einsum("hwc,kc->khw", rgb, rgb.new_tensor(OPPONENT))
|
||||
height, width = int(opponent.shape[1]), int(opponent.shape[2])
|
||||
out: dict[float, tuple[float, float]] = {}
|
||||
for scale in SCALES:
|
||||
rows, cols = round(height / scale), round(width / scale)
|
||||
if min(rows, cols) < MIN_SIDE:
|
||||
continue
|
||||
shrunk = opponent if scale == 1.0 else F.interpolate(opponent[None], size=(rows, cols), mode="area")[0]
|
||||
side = min(BLOCK, max(4, (min(rows, cols) - 2) // 4))
|
||||
bright, tone = _blocks(shrunk[0], shrunk[0], side)
|
||||
mid = (tone > MID_TONES[0]) & (tone < MID_TONES[1])
|
||||
keep = mid if int(mid.sum()) >= MIN_BLOCKS else torch.ones_like(mid)
|
||||
cut = torch.quantile(bright[keep], PLAINEST)
|
||||
chosen = keep & (bright <= cut)
|
||||
red_green, _ = _blocks(shrunk[1], shrunk[0], side)
|
||||
yellow_blue, _ = _blocks(shrunk[2], shrunk[0], side)
|
||||
colour = ((red_green[chosen] ** 2 + yellow_blue[chosen] ** 2) / 2.0).sqrt().mean()
|
||||
out[scale] = (float(bright[chosen].mean()), float(colour))
|
||||
return out
|
||||
|
||||
|
||||
def same_viewing_size(reference: torch.Tensor, height: int, width: int) -> torch.Tensor:
|
||||
"""The reference's first frame scaled to the megapixels of a height x width
|
||||
picture, its shape kept."""
|
||||
rgb = _first_rgb(reference)
|
||||
ref_h, ref_w = int(rgb.shape[0]), int(rgb.shape[1])
|
||||
factor = math.sqrt((float(height) * float(width)) / max(float(ref_h) * float(ref_w), 1.0))
|
||||
rows, cols = max(1, round(ref_h * factor)), max(1, round(ref_w * factor))
|
||||
if (rows, cols) == (ref_h, ref_w):
|
||||
return rgb[None]
|
||||
scaled = F.interpolate(rgb.movedim(-1, 0)[None], size=(rows, cols), mode="bicubic", antialias=True, align_corners=False)
|
||||
return scaled[0].movedim(0, -1).clamp(0.0, 1.0)[None]
|
||||
|
||||
|
||||
def build_match_table() -> dict:
|
||||
"""Film Grain's own grain, measured: for each table size and colour, the
|
||||
brightness and colour grain at every scale per unit of amount. Writes
|
||||
nothing; tests/test_grain_match.py --update stores it."""
|
||||
luma, chroma = [], []
|
||||
for size in TABLE_SIZES:
|
||||
luma_row, chroma_row = [], []
|
||||
for color in TABLE_COLORS:
|
||||
grain = G.grain_frame(TABLE_SEED, TABLE_SIDE, TABLE_SIDE, size, TABLE_ROUGHNESS, color)
|
||||
if int(grain.shape[0]) == 1:
|
||||
grain = grain.expand(3, -1, -1)
|
||||
profile = grain_profile((0.5 + G.FULL_STRENGTH * grain.movedim(0, -1))[None])
|
||||
luma_row.append([round(profile[s][0] / G.FULL_STRENGTH, 6) for s in SCALES])
|
||||
chroma_row.append([round(profile[s][1] / G.FULL_STRENGTH, 6) for s in SCALES])
|
||||
luma.append(luma_row)
|
||||
chroma.append(chroma_row)
|
||||
return {"sizes": list(TABLE_SIZES), "colors": list(TABLE_COLORS), "scales": list(SCALES), "luma": luma, "chroma": chroma}
|
||||
|
||||
|
||||
def _table() -> dict:
|
||||
from ._grain_match_table import TABLE
|
||||
|
||||
return TABLE
|
||||
|
||||
|
||||
def _ratio(weights, top, bottom) -> float:
|
||||
return sum(w * t for w, t in zip(weights, top)) / max(sum(w * b for w, b in zip(weights, bottom)), 1e-12)
|
||||
|
||||
|
||||
def match_grain(reference: torch.Tensor, image: torch.Tensor, roughness: float, seed: int) -> dict:
|
||||
"""The amount, size and colour that give `image` grain like `reference`'s,
|
||||
with Film Grain's roughness and seed. Adds "found": False when the
|
||||
reference has no grain `image` does not already have."""
|
||||
height, width = int(image.shape[1]), int(image.shape[2])
|
||||
if min(height, width) < MIN_SIDE * 2:
|
||||
raise ValueError(f"Film Grain: the picture is too small to match grain to ({width}x{height}); it needs {MIN_SIDE * 2} px a side.")
|
||||
target = _first_rgb(image)[None]
|
||||
wanted = grain_profile(same_viewing_size(reference, height, width))
|
||||
own = grain_profile(target)
|
||||
table = _table()
|
||||
columns = [table["scales"].index(scale) for scale in SCALES if scale in wanted and scale in own]
|
||||
scales = [table["scales"][i] for i in columns]
|
||||
if len(scales) < 2:
|
||||
raise ValueError("Film Grain: the picture to copy grain from is too small to read; it needs 64 px a side.")
|
||||
bright = [math.sqrt(max(wanted[s][0] ** 2 - own[s][0] ** 2, 0.0)) for s in scales]
|
||||
colour = [math.sqrt(max(wanted[s][1] ** 2 - own[s][1] ** 2, 0.0)) for s in scales]
|
||||
if max(bright) < NO_GRAIN:
|
||||
return {"amount": 0.0, "size": 1.0, "color": 0.0, "found": False}
|
||||
# Each size counts by the share of its grain that is to be added.
|
||||
weights = [b * b / max(wanted[s][0] ** 2, 1e-12) for b, s in zip(bright, scales)]
|
||||
total = max(sum(weights), 1e-12)
|
||||
sizes, colors = table["sizes"], table["colors"]
|
||||
|
||||
def fit(color_at: int) -> tuple[float, int]:
|
||||
best = None
|
||||
for size_at, size in enumerate(sizes):
|
||||
row = [table["luma"][size_at][color_at][i] for i in columns]
|
||||
logs = [math.log(max(b, 1e-6) / max(x, 1e-9)) for b, x in zip(bright, row)]
|
||||
level = sum(w * v for w, v in zip(weights, logs)) / total
|
||||
error = sum(w * (v - level) ** 2 for w, v in zip(weights, logs)) + SIZE_PULL * total * math.log(size) ** 2
|
||||
if best is None or error < best[0]:
|
||||
best = (error, math.exp(level), size_at)
|
||||
return best[1], best[2]
|
||||
|
||||
color_at = colors.index(0.5)
|
||||
for _ in range(COLOR_ROUNDS):
|
||||
level, size_at = fit(color_at)
|
||||
share = _ratio(weights, colour, bright)
|
||||
color_at = min(
|
||||
range(len(colors)),
|
||||
key=lambda c: abs(share - _ratio(weights, [table["chroma"][size_at][c][i] for i in columns], [table["luma"][size_at][c][i] for i in columns])),
|
||||
)
|
||||
level, size_at = fit(color_at)
|
||||
size, color = float(sizes[size_at]), float(colors[color_at])
|
||||
amount = min(level, 1.0)
|
||||
# The check: grain on the picture itself, its tones included.
|
||||
want = sum(w * b for w, b in zip(weights, bright)) / total
|
||||
for _ in range(AMOUNT_ROUNDS):
|
||||
if amount <= 0.0:
|
||||
break
|
||||
trial = grain_profile(G.add_film_grain(target, amount, size, roughness, color, False, seed))
|
||||
got = sum(w * math.sqrt(max(trial[s][0] ** 2 - own[s][0] ** 2, 1e-12)) for w, s in zip(weights, scales)) / total
|
||||
amount = min(max(amount * want / max(got, 1e-9), 0.0), 1.0)
|
||||
return {"amount": amount, "size": size, "color": color, "found": True}
|
||||
|
||||
|
||||
def matched_film_grain_values(
|
||||
reference: torch.Tensor, image: torch.Tensor, roughness: float, seed: int,
|
||||
amount_times: float, size_times: float, color_times: float,
|
||||
) -> dict:
|
||||
"""What Auto does with a picture to copy from: the match ("base_amount",
|
||||
"base_size", "base_color") and the values to use, which are the match
|
||||
times the card's three multipliers, kept inside Film Grain's limits."""
|
||||
found = match_grain(reference, image, roughness, seed)
|
||||
return {
|
||||
"amount": min(max(found["amount"] * float(amount_times), 0.0), 1.0),
|
||||
"size": min(max(found["size"] * float(size_times), G.AUTO_SIZE_RANGE[0]), G.AUTO_SIZE_RANGE[1]),
|
||||
"color": min(max(found["color"] * float(color_times), 0.0), 1.0),
|
||||
"base_amount": found["amount"],
|
||||
"base_size": found["size"],
|
||||
"base_color": found["color"],
|
||||
"found": found["found"],
|
||||
}
|
||||
|
||||
|
||||
__all__ = ["build_match_table", "grain_profile", "match_grain", "matched_film_grain_values", "same_viewing_size"]
|
||||
@@ -0,0 +1,561 @@
|
||||
"""Film Grain's own grain, measured, for the grain match (nodes/_grain_match_helpers.py).
|
||||
|
||||
Made by `python tests/test_grain_match.py --update`; do not edit by hand.
|
||||
luma[size][color][scale] and chroma[size][color][scale] are the brightness
|
||||
and colour grain at each scale per unit of amount.
|
||||
"""
|
||||
|
||||
TABLE = {'chroma': [[[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
|
||||
[0.081022, 0.015785, 0.040736, 0.013421, 0.020277, 0.009463, 0.01043, 0.00571],
|
||||
[0.177515, 0.034595, 0.089689, 0.029464, 0.044495, 0.02078, 0.022905, 0.012705],
|
||||
[0.288726, 0.055839, 0.144194, 0.047771, 0.072239, 0.034137, 0.037464, 0.020638],
|
||||
[0.404613, 0.078016, 0.201962, 0.067069, 0.100474, 0.047832, 0.053337, 0.028719],
|
||||
[0.514342, 0.098596, 0.256876, 0.085678, 0.127542, 0.061508, 0.0679, 0.036608],
|
||||
[0.600748, 0.11531, 0.301521, 0.100458, 0.150842, 0.072515, 0.07945, 0.043098],
|
||||
[0.663809, 0.126688, 0.329623, 0.111315, 0.166553, 0.078746, 0.088854, 0.047637],
|
||||
[0.696537, 0.134015, 0.346731, 0.116515, 0.174199, 0.082998, 0.093811, 0.050317],
|
||||
[0.713277, 0.137115, 0.353876, 0.120191, 0.178292, 0.085036, 0.096421, 0.051577],
|
||||
[0.71473, 0.137761, 0.355778, 0.120768, 0.180023, 0.085695, 0.097053, 0.050462]],
|
||||
[[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
|
||||
[0.046489, 0.017845, 0.047519, 0.017529, 0.025711, 0.0123, 0.012001, 0.007155],
|
||||
[0.101956, 0.039302, 0.104463, 0.038443, 0.05646, 0.026267, 0.026357, 0.015705],
|
||||
[0.164978, 0.063733, 0.169568, 0.061985, 0.091361, 0.041855, 0.043378, 0.025485],
|
||||
[0.231842, 0.089746, 0.237808, 0.087021, 0.127985, 0.057941, 0.064251, 0.035849],
|
||||
[0.294155, 0.11411, 0.302318, 0.110995, 0.163457, 0.074084, 0.080794, 0.045704],
|
||||
[0.34567, 0.134196, 0.355631, 0.12869, 0.193603, 0.087496, 0.095026, 0.052154],
|
||||
[0.37913, 0.147533, 0.394638, 0.14094, 0.209378, 0.095946, 0.104566, 0.060184],
|
||||
[0.398258, 0.154732, 0.416139, 0.148105, 0.21791, 0.099724, 0.110376, 0.062192],
|
||||
[0.408334, 0.158015, 0.422217, 0.151836, 0.22064, 0.103517, 0.113082, 0.063705],
|
||||
[0.411363, 0.158807, 0.425757, 0.153222, 0.222403, 0.105604, 0.113056, 0.061097]],
|
||||
[[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
|
||||
[0.036824, 0.01851, 0.049478, 0.019387, 0.027263, 0.013529, 0.014023, 0.008375],
|
||||
[0.080677, 0.040768, 0.108873, 0.04262, 0.060012, 0.029805, 0.031119, 0.019213],
|
||||
[0.13009, 0.065968, 0.175821, 0.069004, 0.096818, 0.04735, 0.050426, 0.031231],
|
||||
[0.182491, 0.092583, 0.249458, 0.097017, 0.134452, 0.066679, 0.070937, 0.044039],
|
||||
[0.231175, 0.118078, 0.316481, 0.121746, 0.170632, 0.084842, 0.090329, 0.05376],
|
||||
[0.270939, 0.13863, 0.371337, 0.143039, 0.20111, 0.099386, 0.106188, 0.063271],
|
||||
[0.297133, 0.152211, 0.407841, 0.15752, 0.221604, 0.109947, 0.115816, 0.070678],
|
||||
[0.312231, 0.160688, 0.428562, 0.166472, 0.237726, 0.116735, 0.12218, 0.074623],
|
||||
[0.319436, 0.164374, 0.439037, 0.170243, 0.243924, 0.119857, 0.125139, 0.076478],
|
||||
[0.321826, 0.165344, 0.442585, 0.171034, 0.243782, 0.120576, 0.127709, 0.077206]],
|
||||
[[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
|
||||
[0.028122, 0.018783, 0.05041, 0.021022, 0.030373, 0.015685, 0.016855, 0.009102],
|
||||
[0.061637, 0.041228, 0.110713, 0.046175, 0.066981, 0.034446, 0.037592, 0.020005],
|
||||
[0.099735, 0.066812, 0.179306, 0.075196, 0.107444, 0.055931, 0.059494, 0.032517],
|
||||
[0.14017, 0.093688, 0.252375, 0.106008, 0.1505, 0.078631, 0.083782, 0.045812],
|
||||
[0.176919, 0.119015, 0.320716, 0.136109, 0.190799, 0.100183, 0.103463, 0.059036],
|
||||
[0.207388, 0.140891, 0.377662, 0.159102, 0.224045, 0.117299, 0.124098, 0.066255],
|
||||
[0.228266, 0.155149, 0.419938, 0.175496, 0.246635, 0.128179, 0.137041, 0.073123],
|
||||
[0.239684, 0.16354, 0.441344, 0.18463, 0.260053, 0.131672, 0.138891, 0.07608],
|
||||
[0.24513, 0.167185, 0.451916, 0.187078, 0.265663, 0.136126, 0.146233, 0.078234],
|
||||
[0.246793, 0.168521, 0.456013, 0.189236, 0.269776, 0.13593, 0.147035, 0.078366]],
|
||||
[[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
|
||||
[0.021188, 0.0184, 0.04981, 0.023254, 0.033819, 0.01675, 0.017779, 0.00997],
|
||||
[0.04637, 0.040471, 0.109581, 0.051018, 0.07439, 0.036761, 0.039329, 0.021804],
|
||||
[0.075145, 0.065727, 0.178263, 0.082969, 0.120979, 0.05952, 0.063888, 0.0356],
|
||||
[0.105389, 0.092408, 0.250857, 0.11698, 0.169744, 0.083706, 0.08997, 0.052452],
|
||||
[0.133665, 0.117082, 0.319004, 0.148089, 0.215855, 0.105436, 0.114376, 0.062093],
|
||||
[0.155563, 0.137112, 0.374433, 0.173737, 0.251972, 0.12199, 0.132854, 0.073095],
|
||||
[0.170241, 0.151075, 0.413673, 0.192386, 0.275937, 0.136149, 0.145241, 0.080793],
|
||||
[0.178181, 0.159293, 0.435262, 0.203601, 0.290054, 0.144135, 0.154609, 0.082337],
|
||||
[0.182298, 0.163153, 0.446011, 0.208018, 0.294, 0.148635, 0.158396, 0.083422],
|
||||
[0.183858, 0.16409, 0.44908, 0.209824, 0.294582, 0.149558, 0.161073, 0.083954]],
|
||||
[[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
|
||||
[0.015811, 0.017031, 0.047418, 0.025263, 0.035637, 0.018404, 0.01863, 0.011469],
|
||||
[0.034685, 0.037349, 0.104726, 0.055556, 0.078286, 0.040182, 0.04093, 0.02474],
|
||||
[0.056113, 0.060597, 0.170256, 0.089747, 0.127591, 0.065282, 0.066502, 0.040971],
|
||||
[0.078404, 0.085328, 0.239409, 0.127054, 0.178565, 0.088571, 0.093667, 0.057655],
|
||||
[0.099573, 0.108708, 0.303544, 0.162021, 0.231187, 0.113813, 0.116227, 0.073414],
|
||||
[0.116405, 0.127057, 0.355677, 0.189252, 0.272365, 0.131267, 0.142441, 0.083412],
|
||||
[0.128323, 0.140099, 0.390273, 0.208149, 0.300568, 0.145002, 0.147461, 0.097517],
|
||||
[0.134446, 0.147206, 0.410873, 0.218699, 0.313441, 0.152963, 0.160397, 0.099822],
|
||||
[0.137188, 0.150687, 0.420476, 0.223277, 0.320945, 0.156652, 0.164334, 0.099927],
|
||||
[0.13854, 0.151755, 0.421093, 0.223562, 0.322008, 0.160782, 0.169023, 0.100554]],
|
||||
[[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
|
||||
[0.039792, 0.017, 0.058748, 0.0274, 0.039976, 0.021457, 0.020799, 0.011972],
|
||||
[0.087366, 0.037316, 0.128822, 0.060065, 0.087842, 0.046854, 0.045636, 0.026282],
|
||||
[0.141542, 0.060383, 0.209402, 0.096985, 0.143129, 0.077085, 0.074007, 0.042633],
|
||||
[0.198654, 0.084775, 0.293447, 0.136232, 0.199401, 0.106257, 0.105172, 0.059912],
|
||||
[0.252158, 0.107721, 0.371834, 0.17483, 0.250898, 0.134745, 0.13343, 0.076201],
|
||||
[0.296849, 0.125801, 0.437329, 0.20349, 0.295042, 0.153616, 0.158046, 0.090093],
|
||||
[0.327158, 0.138552, 0.481008, 0.225135, 0.318787, 0.169131, 0.174846, 0.099413],
|
||||
[0.346519, 0.14602, 0.506263, 0.236879, 0.33335, 0.179067, 0.18457, 0.104189],
|
||||
[0.354012, 0.149382, 0.519356, 0.241615, 0.342259, 0.185088, 0.188112, 0.110103],
|
||||
[0.356724, 0.150308, 0.522859, 0.240178, 0.348896, 0.18611, 0.191883, 0.11079]],
|
||||
[[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
|
||||
[0.023201, 0.015706, 0.045561, 0.029233, 0.044377, 0.022139, 0.023299, 0.013952],
|
||||
[0.051022, 0.034594, 0.100136, 0.063956, 0.096682, 0.048574, 0.051741, 0.032076],
|
||||
[0.082655, 0.056576, 0.161045, 0.103323, 0.155711, 0.080442, 0.084318, 0.052138],
|
||||
[0.115938, 0.078637, 0.22574, 0.144628, 0.221163, 0.113195, 0.117322, 0.073475],
|
||||
[0.147399, 0.100114, 0.286223, 0.182675, 0.282168, 0.142715, 0.14961, 0.092814],
|
||||
[0.172333, 0.117547, 0.335972, 0.215265, 0.321379, 0.167884, 0.179837, 0.10417],
|
||||
[0.190171, 0.129511, 0.368984, 0.236562, 0.352839, 0.184651, 0.198733, 0.122681],
|
||||
[0.200322, 0.136537, 0.391964, 0.251586, 0.3736, 0.193746, 0.210004, 0.12928],
|
||||
[0.20533, 0.140131, 0.400294, 0.25865, 0.382691, 0.199769, 0.215361, 0.131537],
|
||||
[0.206655, 0.140852, 0.402731, 0.261111, 0.383191, 0.203755, 0.213525, 0.132087]],
|
||||
[[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
|
||||
[0.01693, 0.013926, 0.040543, 0.030253, 0.047692, 0.025141, 0.025674, 0.016039],
|
||||
[0.037172, 0.030617, 0.088381, 0.066499, 0.103378, 0.055368, 0.056381, 0.035205],
|
||||
[0.060349, 0.049703, 0.143433, 0.107575, 0.167001, 0.089874, 0.091556, 0.05711],
|
||||
[0.084681, 0.069728, 0.202242, 0.150586, 0.239958, 0.125233, 0.135034, 0.075199],
|
||||
[0.107212, 0.08838, 0.257824, 0.187222, 0.305843, 0.15927, 0.16547, 0.095713],
|
||||
[0.125763, 0.103752, 0.302261, 0.218962, 0.358211, 0.185527, 0.200055, 0.112438],
|
||||
[0.13833, 0.114138, 0.335494, 0.240782, 0.387261, 0.204404, 0.220993, 0.12147],
|
||||
[0.145537, 0.120261, 0.35693, 0.254909, 0.408959, 0.215596, 0.234697, 0.126905],
|
||||
[0.149172, 0.122901, 0.366801, 0.260759, 0.421307, 0.221173, 0.225666, 0.13004],
|
||||
[0.150317, 0.123651, 0.367024, 0.264244, 0.424142, 0.220749, 0.233475, 0.130878]],
|
||||
[[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
|
||||
[0.012124, 0.012457, 0.036725, 0.029992, 0.047115, 0.027563, 0.029847, 0.017663],
|
||||
[0.026571, 0.027298, 0.080624, 0.065992, 0.103597, 0.06047, 0.066475, 0.040725],
|
||||
[0.042986, 0.04443, 0.129885, 0.107823, 0.168355, 0.098077, 0.107773, 0.06754],
|
||||
[0.060075, 0.062461, 0.182236, 0.15174, 0.238348, 0.138136, 0.151425, 0.090169],
|
||||
[0.07614, 0.079355, 0.233663, 0.193292, 0.303243, 0.177046, 0.187007, 0.116032],
|
||||
[0.089148, 0.092983, 0.273301, 0.22649, 0.356125, 0.210464, 0.213199, 0.136428],
|
||||
[0.09791, 0.102155, 0.300448, 0.248504, 0.38599, 0.235742, 0.230627, 0.147277],
|
||||
[0.103288, 0.107386, 0.318215, 0.261227, 0.408817, 0.248823, 0.24007, 0.155449],
|
||||
[0.105659, 0.110192, 0.325348, 0.267286, 0.41938, 0.246618, 0.246, 0.159272],
|
||||
[0.106259, 0.110742, 0.327525, 0.268129, 0.419601, 0.248974, 0.247606, 0.16028]],
|
||||
[[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
|
||||
[0.008225, 0.010516, 0.031818, 0.028452, 0.048786, 0.031493, 0.032569, 0.019854],
|
||||
[0.01811, 0.023093, 0.069742, 0.062445, 0.10712, 0.069323, 0.071487, 0.043559],
|
||||
[0.029431, 0.037417, 0.113128, 0.10172, 0.173547, 0.110489, 0.11509, 0.070642],
|
||||
[0.041462, 0.052698, 0.158125, 0.143352, 0.243686, 0.154133, 0.160249, 0.097639],
|
||||
[0.0527, 0.067001, 0.202067, 0.182969, 0.309514, 0.197191, 0.204629, 0.124158],
|
||||
[0.061901, 0.078952, 0.238007, 0.21501, 0.36309, 0.233352, 0.243874, 0.145542],
|
||||
[0.067604, 0.087039, 0.261994, 0.238957, 0.399768, 0.257705, 0.265549, 0.160768],
|
||||
[0.070591, 0.092111, 0.274709, 0.251851, 0.419019, 0.270212, 0.277501, 0.163326],
|
||||
[0.071975, 0.094014, 0.280762, 0.258564, 0.429964, 0.278046, 0.283999, 0.17383],
|
||||
[0.072353, 0.094481, 0.283934, 0.259759, 0.429171, 0.279844, 0.2856, 0.178242]],
|
||||
[[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
|
||||
[0.00572, 0.00887, 0.027207, 0.026754, 0.047815, 0.033817, 0.036961, 0.021353],
|
||||
[0.012497, 0.019425, 0.059484, 0.058591, 0.104016, 0.074265, 0.081065, 0.046852],
|
||||
[0.020124, 0.031496, 0.096934, 0.095193, 0.168876, 0.121772, 0.131435, 0.075977],
|
||||
[0.028084, 0.044512, 0.135522, 0.133964, 0.235627, 0.168581, 0.17634, 0.106745],
|
||||
[0.035572, 0.056771, 0.171512, 0.170192, 0.300463, 0.214945, 0.225937, 0.135598],
|
||||
[0.041472, 0.066831, 0.200982, 0.199476, 0.347506, 0.253068, 0.256801, 0.156259],
|
||||
[0.045419, 0.073406, 0.222606, 0.219651, 0.383905, 0.275942, 0.272318, 0.176772],
|
||||
[0.047741, 0.077229, 0.233838, 0.230894, 0.405504, 0.293905, 0.282232, 0.182431],
|
||||
[0.048689, 0.079103, 0.239412, 0.23951, 0.411629, 0.29893, 0.288956, 0.186854],
|
||||
[0.049141, 0.079518, 0.241005, 0.239886, 0.413244, 0.301928, 0.290585, 0.18798]],
|
||||
[[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
|
||||
[0.003686, 0.007206, 0.028123, 0.024235, 0.053898, 0.03554, 0.040098, 0.025869],
|
||||
[0.008068, 0.015822, 0.061769, 0.052897, 0.118615, 0.077429, 0.088686, 0.056879],
|
||||
[0.013151, 0.025542, 0.099769, 0.085765, 0.193181, 0.125678, 0.143895, 0.092567],
|
||||
[0.018437, 0.036093, 0.140864, 0.11944, 0.270535, 0.17528, 0.202467, 0.130691],
|
||||
[0.023323, 0.045871, 0.178785, 0.152615, 0.342148, 0.223303, 0.258056, 0.16139],
|
||||
[0.027301, 0.05378, 0.210273, 0.179843, 0.400275, 0.25746, 0.310469, 0.185463],
|
||||
[0.029981, 0.059455, 0.231264, 0.19814, 0.442245, 0.288131, 0.330321, 0.194228],
|
||||
[0.031424, 0.062112, 0.242912, 0.209604, 0.470812, 0.303337, 0.348854, 0.204695],
|
||||
[0.032163, 0.063344, 0.248343, 0.213937, 0.473084, 0.309347, 0.35471, 0.209411],
|
||||
[0.03222, 0.063757, 0.249781, 0.217297, 0.474354, 0.312207, 0.349474, 0.20716]],
|
||||
[[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
|
||||
[0.002408, 0.00554, 0.017633, 0.021953, 0.042867, 0.035616, 0.04095, 0.025808],
|
||||
[0.005291, 0.012169, 0.038777, 0.047486, 0.094138, 0.078235, 0.090091, 0.056677],
|
||||
[0.008536, 0.01972, 0.062918, 0.07717, 0.150728, 0.128845, 0.146543, 0.092058],
|
||||
[0.012002, 0.027793, 0.088596, 0.108983, 0.211448, 0.181486, 0.206449, 0.129674],
|
||||
[0.015118, 0.035502, 0.112628, 0.138971, 0.268541, 0.233508, 0.25914, 0.16265],
|
||||
[0.017649, 0.041542, 0.132683, 0.163571, 0.312623, 0.279438, 0.315848, 0.179119],
|
||||
[0.019321, 0.045463, 0.146345, 0.179267, 0.337582, 0.310349, 0.344253, 0.193607],
|
||||
[0.020278, 0.048067, 0.154789, 0.188897, 0.35822, 0.325591, 0.363629, 0.205548],
|
||||
[0.020604, 0.049402, 0.157586, 0.19504, 0.368267, 0.331742, 0.37271, 0.210548],
|
||||
[0.020744, 0.049737, 0.157237, 0.1963, 0.372554, 0.333584, 0.360973, 0.211823]],
|
||||
[[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
|
||||
[0.001584, 0.004086, 0.013399, 0.019114, 0.03711, 0.03863, 0.044735, 0.030109],
|
||||
[0.003477, 0.008986, 0.029421, 0.041867, 0.082033, 0.08393, 0.098687, 0.066132],
|
||||
[0.005623, 0.014488, 0.047832, 0.06829, 0.134246, 0.136317, 0.160471, 0.105797],
|
||||
[0.007909, 0.02023, 0.067069, 0.095626, 0.188481, 0.192429, 0.225651, 0.147615],
|
||||
[0.009946, 0.025806, 0.084899, 0.122233, 0.237696, 0.24325, 0.287895, 0.188063],
|
||||
[0.011585, 0.030413, 0.099824, 0.143106, 0.270835, 0.285834, 0.338925, 0.221167],
|
||||
[0.012695, 0.033507, 0.109646, 0.157645, 0.295992, 0.312854, 0.373637, 0.232872],
|
||||
[0.013182, 0.035261, 0.115667, 0.166673, 0.317799, 0.327059, 0.393901, 0.250104],
|
||||
[0.013477, 0.036051, 0.118194, 0.169295, 0.32127, 0.325534, 0.398279, 0.25539],
|
||||
[0.013613, 0.036124, 0.1191, 0.170605, 0.321776, 0.326474, 0.400464, 0.2598]],
|
||||
[[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
|
||||
[0.001048, 0.003056, 0.009656, 0.016322, 0.033539, 0.037042, 0.046397, 0.032732],
|
||||
[0.00229, 0.006705, 0.0212, 0.035826, 0.073591, 0.081377, 0.104338, 0.071809],
|
||||
[0.003686, 0.010859, 0.034431, 0.057599, 0.120388, 0.130827, 0.169386, 0.116454],
|
||||
[0.005086, 0.015219, 0.048215, 0.081053, 0.169454, 0.185042, 0.238313, 0.165581],
|
||||
[0.006419, 0.019149, 0.061133, 0.102914, 0.21218, 0.236768, 0.298414, 0.202824],
|
||||
[0.007498, 0.022305, 0.071586, 0.121053, 0.24968, 0.282677, 0.351709, 0.238582],
|
||||
[0.008198, 0.024526, 0.078971, 0.133096, 0.27113, 0.307621, 0.386612, 0.265267],
|
||||
[0.00854, 0.025915, 0.083357, 0.140289, 0.2852, 0.315834, 0.416327, 0.276478],
|
||||
[0.008739, 0.026435, 0.085836, 0.143865, 0.292654, 0.322545, 0.424524, 0.283288],
|
||||
[0.00878, 0.026822, 0.086193, 0.145702, 0.292017, 0.324281, 0.427328, 0.295387]],
|
||||
[[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
|
||||
[0.000688, 0.002151, 0.006943, 0.014234, 0.029051, 0.035529, 0.048098, 0.035662],
|
||||
[0.001499, 0.004719, 0.015279, 0.031348, 0.063791, 0.077982, 0.105594, 0.07789],
|
||||
[0.002394, 0.007684, 0.024644, 0.050836, 0.103247, 0.125395, 0.181719, 0.126499],
|
||||
[0.003343, 0.01076, 0.034515, 0.071392, 0.147608, 0.176293, 0.237593, 0.177972],
|
||||
[0.004217, 0.013655, 0.043406, 0.090911, 0.188714, 0.222863, 0.30562, 0.219427],
|
||||
[0.004901, 0.016176, 0.050327, 0.106617, 0.221583, 0.266009, 0.339292, 0.258043],
|
||||
[0.005301, 0.017322, 0.055658, 0.117085, 0.244736, 0.293324, 0.367302, 0.295751],
|
||||
[0.005544, 0.018044, 0.059308, 0.122396, 0.25242, 0.305522, 0.387299, 0.311872],
|
||||
[0.005692, 0.018493, 0.060791, 0.124623, 0.258953, 0.312111, 0.405775, 0.312285],
|
||||
[0.00567, 0.01861, 0.061221, 0.125989, 0.261449, 0.313972, 0.41421, 0.314181]],
|
||||
[[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
|
||||
[0.000433, 0.00152, 0.004934, 0.011219, 0.025033, 0.032952, 0.04183, 0.037432],
|
||||
[0.00095, 0.003343, 0.010755, 0.024641, 0.054483, 0.072606, 0.091914, 0.082133],
|
||||
[0.001513, 0.005373, 0.017412, 0.040119, 0.089127, 0.116825, 0.149346, 0.127977],
|
||||
[0.002132, 0.007526, 0.024962, 0.056492, 0.126257, 0.16284, 0.222355, 0.180249],
|
||||
[0.002691, 0.009605, 0.031873, 0.071815, 0.161327, 0.206487, 0.283439, 0.236081],
|
||||
[0.003114, 0.011166, 0.037287, 0.084768, 0.193691, 0.243511, 0.315631, 0.278012],
|
||||
[0.003365, 0.012318, 0.040612, 0.093245, 0.213813, 0.266658, 0.358761, 0.308166],
|
||||
[0.003512, 0.013011, 0.042756, 0.098588, 0.222037, 0.274525, 0.378735, 0.312945],
|
||||
[0.003536, 0.013178, 0.043468, 0.100973, 0.226051, 0.281425, 0.401997, 0.320729],
|
||||
[0.003501, 0.013221, 0.043432, 0.101398, 0.229883, 0.283243, 0.404669, 0.318223]],
|
||||
[[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
|
||||
[0.000266, 0.001003, 0.003296, 0.008989, 0.025671, 0.029708, 0.054475, 0.041049],
|
||||
[0.000584, 0.002155, 0.007179, 0.01972, 0.056366, 0.065231, 0.119508, 0.090052],
|
||||
[0.000936, 0.003519, 0.011565, 0.03192, 0.091924, 0.102902, 0.188638, 0.145981],
|
||||
[0.001316, 0.0049, 0.016146, 0.044719, 0.129155, 0.144585, 0.271991, 0.199608],
|
||||
[0.001652, 0.006281, 0.020673, 0.056656, 0.164574, 0.176782, 0.345748, 0.256038],
|
||||
[0.001939, 0.007348, 0.024349, 0.06635, 0.193391, 0.208134, 0.406076, 0.300946],
|
||||
[0.002112, 0.008103, 0.02672, 0.072553, 0.213846, 0.231704, 0.453111, 0.332364],
|
||||
[0.002223, 0.008526, 0.028132, 0.077497, 0.226767, 0.241861, 0.477724, 0.32605],
|
||||
[0.002238, 0.008723, 0.029009, 0.07951, 0.232336, 0.24768, 0.489008, 0.343981],
|
||||
[0.002223, 0.008772, 0.029115, 0.08009, 0.232172, 0.24916, 0.504854, 0.34638]],
|
||||
[[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
|
||||
[0.00018, 0.000682, 0.002328, 0.006615, 0.016436, 0.027383, 0.041569, 0.042816],
|
||||
[0.000393, 0.001518, 0.005107, 0.014319, 0.035918, 0.06044, 0.091216, 0.094061],
|
||||
[0.00063, 0.002444, 0.008206, 0.023602, 0.058269, 0.098022, 0.145184, 0.152673],
|
||||
[0.000874, 0.003341, 0.011635, 0.033546, 0.082219, 0.137471, 0.203922, 0.204862],
|
||||
[0.00111, 0.004268, 0.014368, 0.042359, 0.104575, 0.174238, 0.259846, 0.257209],
|
||||
[0.001268, 0.005046, 0.016538, 0.050278, 0.122784, 0.204664, 0.305209, 0.302594],
|
||||
[0.001378, 0.005552, 0.018183, 0.055251, 0.135834, 0.22535, 0.342189, 0.334279],
|
||||
[0.001433, 0.00576, 0.01917, 0.058081, 0.142919, 0.238197, 0.361005, 0.352888],
|
||||
[0.001447, 0.005945, 0.019393, 0.059962, 0.146433, 0.242213, 0.369829, 0.361646],
|
||||
[0.001473, 0.006048, 0.019298, 0.060159, 0.147224, 0.243509, 0.364774, 0.363999]],
|
||||
[[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
|
||||
[0.000116, 0.000452, 0.001416, 0.004855, 0.012775, 0.021914, 0.036196, 0.041671],
|
||||
[0.00025, 0.00099, 0.003089, 0.01064, 0.028048, 0.048145, 0.079439, 0.091407],
|
||||
[0.000404, 0.001601, 0.005004, 0.017029, 0.045513, 0.078205, 0.128884, 0.150408],
|
||||
[0.00056, 0.002243, 0.00701, 0.023996, 0.063921, 0.11008, 0.181312, 0.211502],
|
||||
[0.000699, 0.002826, 0.009023, 0.030325, 0.081075, 0.140192, 0.230953, 0.262424],
|
||||
[0.000788, 0.003308, 0.010596, 0.035568, 0.094985, 0.164736, 0.271641, 0.298928],
|
||||
[0.000865, 0.003563, 0.01158, 0.039845, 0.103632, 0.181731, 0.282528, 0.326339],
|
||||
[0.000913, 0.003743, 0.01202, 0.041685, 0.110979, 0.191574, 0.298518, 0.344126],
|
||||
[0.00093, 0.00391, 0.011989, 0.042579, 0.112249, 0.196075, 0.306122, 0.352292],
|
||||
[0.000931, 0.003922, 0.012001, 0.042425, 0.112937, 0.197144, 0.308202, 0.354253]],
|
||||
[[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
|
||||
[7e-05, 0.000302, 0.000959, 0.003574, 0.00983, 0.019723, 0.035207, 0.039228],
|
||||
[0.000154, 0.00066, 0.002113, 0.007843, 0.021583, 0.043311, 0.079781, 0.086302],
|
||||
[0.000244, 0.001063, 0.003397, 0.012712, 0.035482, 0.070315, 0.125989, 0.140407],
|
||||
[0.00034, 0.001495, 0.004684, 0.017522, 0.050411, 0.098955, 0.182322, 0.204674],
|
||||
[0.00043, 0.001862, 0.005918, 0.022006, 0.064191, 0.126561, 0.219398, 0.26024],
|
||||
[0.000497, 0.002175, 0.006757, 0.02565, 0.07561, 0.148935, 0.257649, 0.28772],
|
||||
[0.000545, 0.002364, 0.007358, 0.028302, 0.08001, 0.163485, 0.284036, 0.329476],
|
||||
[0.000582, 0.002539, 0.007753, 0.029832, 0.085489, 0.166717, 0.299283, 0.347314],
|
||||
[0.000593, 0.002533, 0.00804, 0.030814, 0.087903, 0.170673, 0.29807, 0.354129],
|
||||
[0.000588, 0.002551, 0.008141, 0.03111, 0.08808, 0.171618, 0.296583, 0.356824]],
|
||||
[[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
|
||||
[4.5e-05, 0.000197, 0.000602, 0.00227, 0.006384, 0.015703, 0.028194, 0.037587],
|
||||
[0.0001, 0.000432, 0.001332, 0.004973, 0.013994, 0.034455, 0.06192, 0.077703],
|
||||
[0.000161, 0.000719, 0.002176, 0.008044, 0.022774, 0.055884, 0.100525, 0.126456],
|
||||
[0.000224, 0.000978, 0.003044, 0.01127, 0.031969, 0.078565, 0.145413, 0.178448],
|
||||
[0.000276, 0.001239, 0.003844, 0.013998, 0.040842, 0.102468, 0.184928, 0.227811],
|
||||
[0.000317, 0.00143, 0.004453, 0.016192, 0.048007, 0.123413, 0.21885, 0.282197],
|
||||
[0.000346, 0.001567, 0.004905, 0.017948, 0.052989, 0.136333, 0.233694, 0.312145],
|
||||
[0.000364, 0.001667, 0.005115, 0.019062, 0.054441, 0.137887, 0.246524, 0.342936],
|
||||
[0.000372, 0.001701, 0.005226, 0.019414, 0.056303, 0.141357, 0.252491, 0.345385],
|
||||
[0.000377, 0.001717, 0.005308, 0.019491, 0.056666, 0.142331, 0.253993, 0.347205]],
|
||||
[[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
|
||||
[2.9e-05, 0.000128, 0.000398, 0.001594, 0.004475, 0.011948, 0.022106, 0.03241],
|
||||
[6.4e-05, 0.000274, 0.000869, 0.003526, 0.009814, 0.026229, 0.048568, 0.07121],
|
||||
[0.000102, 0.000446, 0.001392, 0.005709, 0.01599, 0.042566, 0.077366, 0.115685],
|
||||
[0.000141, 0.000614, 0.001985, 0.007976, 0.022449, 0.05986, 0.108991, 0.166197],
|
||||
[0.000175, 0.000793, 0.002509, 0.010021, 0.027377, 0.076223, 0.138906, 0.210898],
|
||||
[0.000204, 0.00094, 0.002908, 0.011561, 0.032454, 0.089532, 0.16336, 0.265019],
|
||||
[0.000224, 0.001051, 0.003177, 0.012513, 0.035783, 0.099329, 0.180263, 0.292649],
|
||||
[0.000227, 0.001062, 0.003228, 0.012976, 0.037998, 0.105626, 0.190022, 0.308311],
|
||||
[0.000234, 0.001062, 0.00318, 0.013499, 0.038491, 0.107476, 0.197913, 0.320111],
|
||||
[0.000237, 0.001084, 0.003283, 0.013414, 0.039053, 0.107935, 0.198967, 0.321839]],
|
||||
[[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
|
||||
[2.3e-05, 0.000105, 0.000318, 0.001243, 0.003934, 0.011112, 0.030691, 0.032675],
|
||||
[4.9e-05, 0.000229, 0.000699, 0.002729, 0.008631, 0.024373, 0.06743, 0.071982],
|
||||
[7.7e-05, 0.000358, 0.001118, 0.004352, 0.013979, 0.039505, 0.109491, 0.116629],
|
||||
[0.000107, 0.000484, 0.001544, 0.005961, 0.01959, 0.056939, 0.153999, 0.163534],
|
||||
[0.000136, 0.0006, 0.001936, 0.007639, 0.025013, 0.068653, 0.192452, 0.214901],
|
||||
[0.000154, 0.000701, 0.002199, 0.008811, 0.028689, 0.082816, 0.226235, 0.252746],
|
||||
[0.000168, 0.000764, 0.002447, 0.009684, 0.030958, 0.089191, 0.249577, 0.279324],
|
||||
[0.000175, 0.000779, 0.002535, 0.010258, 0.032159, 0.094043, 0.263063, 0.295029],
|
||||
[0.000177, 0.00082, 0.002586, 0.01061, 0.032893, 0.096296, 0.269166, 0.311621],
|
||||
[0.000179, 0.000823, 0.002643, 0.010521, 0.033066, 0.097741, 0.2706, 0.314045]]],
|
||||
'colors': [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0],
|
||||
'luma': [[[0.652683, 0.128425, 0.326929, 0.110533, 0.164445, 0.077012, 0.085234, 0.044089],
|
||||
[0.649067, 0.128219, 0.323193, 0.110393, 0.162813, 0.076648, 0.086335, 0.047199],
|
||||
[0.641697, 0.126908, 0.320035, 0.109371, 0.160527, 0.076157, 0.085668, 0.046804],
|
||||
[0.627197, 0.124169, 0.31315, 0.106846, 0.156769, 0.074837, 0.083968, 0.046085],
|
||||
[0.603851, 0.119648, 0.301714, 0.102635, 0.151221, 0.072481, 0.080311, 0.044317],
|
||||
[0.572879, 0.113633, 0.286669, 0.097123, 0.1437, 0.069612, 0.07552, 0.040534],
|
||||
[0.540292, 0.107181, 0.271262, 0.091538, 0.13666, 0.066236, 0.070373, 0.03681],
|
||||
[0.512258, 0.101908, 0.258081, 0.087092, 0.130411, 0.063103, 0.065887, 0.033658],
|
||||
[0.49449, 0.098548, 0.249944, 0.08424, 0.125426, 0.060884, 0.063035, 0.031805],
|
||||
[0.48614, 0.096925, 0.245629, 0.082787, 0.12246, 0.05962, 0.06142, 0.031765],
|
||||
[0.48394, 0.09647, 0.244659, 0.082275, 0.121452, 0.058899, 0.061091, 0.032495]],
|
||||
[[0.372954, 0.147016, 0.38184, 0.142018, 0.206848, 0.100184, 0.106847, 0.061668],
|
||||
[0.372585, 0.147011, 0.383267, 0.14011, 0.202675, 0.098511, 0.106157, 0.062796],
|
||||
[0.369011, 0.145463, 0.377779, 0.138831, 0.200203, 0.09809, 0.105747, 0.062152],
|
||||
[0.361239, 0.142097, 0.367751, 0.135637, 0.195465, 0.096634, 0.104218, 0.060647],
|
||||
[0.348033, 0.136583, 0.352671, 0.130748, 0.188423, 0.093845, 0.099808, 0.058224],
|
||||
[0.330209, 0.129593, 0.334105, 0.124413, 0.179249, 0.089216, 0.092663, 0.055034],
|
||||
[0.312005, 0.122344, 0.315851, 0.117562, 0.169862, 0.08375, 0.085496, 0.051078],
|
||||
[0.296582, 0.116325, 0.301783, 0.112172, 0.162397, 0.079552, 0.079848, 0.047317],
|
||||
[0.286423, 0.112423, 0.293396, 0.108768, 0.156278, 0.076942, 0.075866, 0.044212],
|
||||
[0.281592, 0.110609, 0.288755, 0.107041, 0.153058, 0.076113, 0.074531, 0.04323],
|
||||
[0.28007, 0.110294, 0.287613, 0.106619, 0.151495, 0.07634, 0.073927, 0.042947]],
|
||||
[[0.293004, 0.151986, 0.400546, 0.15802, 0.22587, 0.113846, 0.117543, 0.063785],
|
||||
[0.290789, 0.151592, 0.398007, 0.155994, 0.222631, 0.111807, 0.11728, 0.068195],
|
||||
[0.287585, 0.150083, 0.393836, 0.153919, 0.219968, 0.110557, 0.116276, 0.067839],
|
||||
[0.281028, 0.146903, 0.384869, 0.150169, 0.214984, 0.107652, 0.113688, 0.065693],
|
||||
[0.270567, 0.141758, 0.370985, 0.14465, 0.206773, 0.103317, 0.110169, 0.062343],
|
||||
[0.256808, 0.134869, 0.352398, 0.137467, 0.196564, 0.097865, 0.106595, 0.057678],
|
||||
[0.242704, 0.12746, 0.333573, 0.13049, 0.18617, 0.092411, 0.103392, 0.053773],
|
||||
[0.230732, 0.12116, 0.316604, 0.125001, 0.177749, 0.088868, 0.100098, 0.050522],
|
||||
[0.222846, 0.116906, 0.306315, 0.120381, 0.172756, 0.086651, 0.097459, 0.048686],
|
||||
[0.218815, 0.114905, 0.301624, 0.11738, 0.168799, 0.085476, 0.096007, 0.048661],
|
||||
[0.217679, 0.114421, 0.30078, 0.116425, 0.166589, 0.085002, 0.095264, 0.048789]],
|
||||
[[0.221568, 0.154721, 0.414385, 0.171468, 0.242261, 0.120643, 0.130931, 0.072576],
|
||||
[0.222463, 0.153712, 0.412471, 0.170869, 0.247083, 0.121304, 0.135766, 0.071861],
|
||||
[0.220008, 0.15246, 0.407972, 0.168489, 0.244999, 0.120361, 0.134064, 0.071189],
|
||||
[0.214785, 0.149503, 0.398476, 0.164631, 0.239712, 0.118854, 0.130535, 0.069798],
|
||||
[0.206656, 0.144432, 0.383233, 0.15893, 0.229805, 0.115494, 0.124761, 0.067683],
|
||||
[0.196041, 0.137556, 0.36433, 0.151398, 0.217148, 0.110619, 0.116681, 0.064439],
|
||||
[0.185551, 0.129768, 0.344506, 0.143616, 0.20264, 0.105695, 0.107496, 0.060675],
|
||||
[0.177006, 0.12329, 0.328302, 0.136754, 0.191345, 0.100652, 0.10073, 0.05843],
|
||||
[0.171465, 0.118853, 0.317728, 0.13237, 0.184309, 0.096383, 0.096536, 0.056782],
|
||||
[0.168632, 0.116848, 0.312454, 0.130157, 0.180894, 0.093156, 0.094706, 0.056315],
|
||||
[0.167745, 0.116401, 0.311097, 0.129775, 0.179469, 0.091007, 0.093865, 0.05634]],
|
||||
[[0.165998, 0.148934, 0.401252, 0.187682, 0.263761, 0.139379, 0.146809, 0.08502],
|
||||
[0.166291, 0.149755, 0.405916, 0.189275, 0.263719, 0.136137, 0.148528, 0.085108],
|
||||
[0.164555, 0.148202, 0.401952, 0.187516, 0.259528, 0.13485, 0.147076, 0.084539],
|
||||
[0.160902, 0.145034, 0.392824, 0.184058, 0.252162, 0.132318, 0.143591, 0.08218],
|
||||
[0.155063, 0.139755, 0.378315, 0.177735, 0.241978, 0.128003, 0.138701, 0.077724],
|
||||
[0.147411, 0.13272, 0.358183, 0.169203, 0.230685, 0.122631, 0.132467, 0.070976],
|
||||
[0.139176, 0.125132, 0.338329, 0.160396, 0.220092, 0.116224, 0.124936, 0.064104],
|
||||
[0.132216, 0.118784, 0.322545, 0.153166, 0.209801, 0.109885, 0.117357, 0.059924],
|
||||
[0.127724, 0.114771, 0.312983, 0.147272, 0.202985, 0.104108, 0.112956, 0.058725],
|
||||
[0.125484, 0.113035, 0.307585, 0.144045, 0.199206, 0.100235, 0.110997, 0.057141],
|
||||
[0.124906, 0.11263, 0.305385, 0.14309, 0.197587, 0.098672, 0.110728, 0.056202]],
|
||||
[[0.125589, 0.139232, 0.386816, 0.20626, 0.284177, 0.150388, 0.155227, 0.097018],
|
||||
[0.125466, 0.13865, 0.383793, 0.207151, 0.285243, 0.152469, 0.161296, 0.089621],
|
||||
[0.124049, 0.137051, 0.380107, 0.204889, 0.2839, 0.15033, 0.157969, 0.087545],
|
||||
[0.121145, 0.133901, 0.372025, 0.200642, 0.279612, 0.146794, 0.152417, 0.084607],
|
||||
[0.116596, 0.128755, 0.358999, 0.1938, 0.271956, 0.142037, 0.145507, 0.080423],
|
||||
[0.110874, 0.122196, 0.341002, 0.18444, 0.259146, 0.133328, 0.13859, 0.076527],
|
||||
[0.104866, 0.115679, 0.321895, 0.174275, 0.243588, 0.123862, 0.131103, 0.073845],
|
||||
[0.099823, 0.110421, 0.30621, 0.165, 0.229936, 0.117013, 0.126943, 0.071792],
|
||||
[0.096524, 0.106756, 0.295064, 0.157927, 0.220434, 0.113312, 0.124072, 0.06995],
|
||||
[0.094898, 0.104968, 0.289274, 0.15453, 0.21621, 0.111966, 0.120452, 0.069543],
|
||||
[0.094407, 0.104518, 0.287, 0.153457, 0.216007, 0.111993, 0.118433, 0.070259]],
|
||||
[[0.343823, 0.141266, 0.479922, 0.222642, 0.3255, 0.160875, 0.176577, 0.097164],
|
||||
[0.342038, 0.140994, 0.479859, 0.217692, 0.318529, 0.162853, 0.172867, 0.099542],
|
||||
[0.338834, 0.139466, 0.476058, 0.216575, 0.315691, 0.161254, 0.169818, 0.097074],
|
||||
[0.331989, 0.136392, 0.466741, 0.212856, 0.309579, 0.158108, 0.165499, 0.093346],
|
||||
[0.320392, 0.131402, 0.450113, 0.205761, 0.299022, 0.153135, 0.158883, 0.088722],
|
||||
[0.305022, 0.124805, 0.427955, 0.19592, 0.285201, 0.145485, 0.151333, 0.083914],
|
||||
[0.288722, 0.117678, 0.404593, 0.184806, 0.269224, 0.137773, 0.142301, 0.0798],
|
||||
[0.274924, 0.111944, 0.38443, 0.175725, 0.256022, 0.132384, 0.136138, 0.076024],
|
||||
[0.265664, 0.108522, 0.369708, 0.169393, 0.245153, 0.129495, 0.131715, 0.073102],
|
||||
[0.26106, 0.107043, 0.362698, 0.166678, 0.239903, 0.12793, 0.128281, 0.070848],
|
||||
[0.259667, 0.106754, 0.36152, 0.166017, 0.238299, 0.127147, 0.127046, 0.070819]],
|
||||
[[0.199093, 0.134043, 0.383732, 0.23983, 0.349834, 0.189666, 0.196628, 0.104299],
|
||||
[0.198326, 0.131949, 0.378126, 0.240614, 0.350307, 0.186983, 0.194221, 0.114001],
|
||||
[0.196224, 0.130721, 0.373731, 0.237697, 0.345989, 0.184654, 0.193571, 0.112961],
|
||||
[0.191878, 0.128031, 0.365006, 0.231737, 0.337647, 0.180933, 0.18889, 0.110507],
|
||||
[0.184846, 0.123614, 0.35073, 0.222268, 0.324719, 0.174667, 0.182702, 0.107126],
|
||||
[0.175646, 0.11747, 0.333091, 0.210792, 0.30882, 0.166378, 0.17512, 0.102666],
|
||||
[0.165898, 0.110922, 0.314398, 0.198786, 0.291391, 0.158016, 0.163473, 0.09611],
|
||||
[0.157859, 0.10552, 0.298629, 0.189344, 0.276497, 0.151316, 0.150431, 0.090071],
|
||||
[0.152626, 0.101738, 0.28858, 0.184075, 0.266716, 0.147213, 0.142182, 0.08437],
|
||||
[0.149927, 0.099865, 0.284141, 0.181824, 0.263553, 0.144593, 0.139811, 0.081161],
|
||||
[0.149173, 0.099404, 0.283099, 0.181578, 0.263884, 0.143026, 0.140535, 0.079442]],
|
||||
[[0.143916, 0.117919, 0.343485, 0.245924, 0.376671, 0.204301, 0.212951, 0.115039],
|
||||
[0.144417, 0.119901, 0.345811, 0.24874, 0.371739, 0.203175, 0.206964, 0.129911],
|
||||
[0.142917, 0.118513, 0.342905, 0.246282, 0.368113, 0.200151, 0.203904, 0.126257],
|
||||
[0.139819, 0.115784, 0.335914, 0.241073, 0.360066, 0.195789, 0.200633, 0.12071],
|
||||
[0.134783, 0.111491, 0.322979, 0.232243, 0.346974, 0.189493, 0.196792, 0.113976],
|
||||
[0.127981, 0.105795, 0.30556, 0.220283, 0.33047, 0.18057, 0.19151, 0.105051],
|
||||
[0.120787, 0.099926, 0.288511, 0.2066, 0.312453, 0.171378, 0.181367, 0.098211],
|
||||
[0.114924, 0.094956, 0.274535, 0.196155, 0.297303, 0.162499, 0.171813, 0.093355],
|
||||
[0.111026, 0.091878, 0.265483, 0.189624, 0.288261, 0.157826, 0.164771, 0.089037],
|
||||
[0.108994, 0.090454, 0.261524, 0.186531, 0.284206, 0.155933, 0.161066, 0.085176],
|
||||
[0.108407, 0.090081, 0.260915, 0.185404, 0.283045, 0.154683, 0.159999, 0.083962]],
|
||||
[[0.100932, 0.106278, 0.310777, 0.247464, 0.392464, 0.229552, 0.234673, 0.144372],
|
||||
[0.100508, 0.106391, 0.313246, 0.2467, 0.381172, 0.224692, 0.228404, 0.141311],
|
||||
[0.099447, 0.105421, 0.309854, 0.245266, 0.378902, 0.223232, 0.227239, 0.139089],
|
||||
[0.097265, 0.103215, 0.302475, 0.240688, 0.372399, 0.220323, 0.223944, 0.134687],
|
||||
[0.0936, 0.099629, 0.290716, 0.233012, 0.361224, 0.214643, 0.22037, 0.127428],
|
||||
[0.088897, 0.094831, 0.275251, 0.22236, 0.345188, 0.207042, 0.217273, 0.118897],
|
||||
[0.084079, 0.089602, 0.259023, 0.210599, 0.326877, 0.197636, 0.212147, 0.11111],
|
||||
[0.080124, 0.085036, 0.245683, 0.19949, 0.310547, 0.188392, 0.206254, 0.104805],
|
||||
[0.077556, 0.082014, 0.236784, 0.191506, 0.298507, 0.183134, 0.197242, 0.101583],
|
||||
[0.076401, 0.080534, 0.232648, 0.187795, 0.29141, 0.179194, 0.18805, 0.100297],
|
||||
[0.076241, 0.080025, 0.231988, 0.186343, 0.288038, 0.17701, 0.183689, 0.10112]],
|
||||
[[0.068981, 0.091236, 0.273129, 0.240375, 0.397069, 0.256557, 0.26086, 0.150538],
|
||||
[0.068852, 0.09142, 0.277724, 0.243366, 0.398721, 0.258836, 0.262885, 0.143411],
|
||||
[0.068126, 0.090397, 0.274459, 0.240706, 0.393014, 0.25694, 0.261304, 0.142702],
|
||||
[0.066581, 0.088309, 0.267674, 0.235, 0.382408, 0.252334, 0.256115, 0.141414],
|
||||
[0.064096, 0.084906, 0.256825, 0.225486, 0.368169, 0.243408, 0.246636, 0.137478],
|
||||
[0.060683, 0.080489, 0.243317, 0.212804, 0.350187, 0.230082, 0.236939, 0.133064],
|
||||
[0.057151, 0.075973, 0.230346, 0.200182, 0.331271, 0.217382, 0.22904, 0.125299],
|
||||
[0.054363, 0.072209, 0.219843, 0.189694, 0.315771, 0.205811, 0.218297, 0.119522],
|
||||
[0.052655, 0.069661, 0.212687, 0.183005, 0.303507, 0.196722, 0.208735, 0.117261],
|
||||
[0.051832, 0.068288, 0.208944, 0.179565, 0.295756, 0.192234, 0.202011, 0.117199],
|
||||
[0.05162, 0.0679, 0.207843, 0.178633, 0.292849, 0.191149, 0.199829, 0.118544]],
|
||||
[[0.043736, 0.073267, 0.232017, 0.227272, 0.38314, 0.267302, 0.28379, 0.179102],
|
||||
[0.045656, 0.076225, 0.235172, 0.226083, 0.390306, 0.271871, 0.283485, 0.171556],
|
||||
[0.045141, 0.075601, 0.232864, 0.223091, 0.387587, 0.267923, 0.281206, 0.168635],
|
||||
[0.044095, 0.074149, 0.227885, 0.217444, 0.379959, 0.261317, 0.277958, 0.164517],
|
||||
[0.042423, 0.071656, 0.219379, 0.208873, 0.365674, 0.25139, 0.271055, 0.157439],
|
||||
[0.040284, 0.068325, 0.207938, 0.198861, 0.346224, 0.239767, 0.257891, 0.14863],
|
||||
[0.038117, 0.064892, 0.196383, 0.188375, 0.324562, 0.229985, 0.241395, 0.139553],
|
||||
[0.036359, 0.061945, 0.186841, 0.179763, 0.307086, 0.221868, 0.227391, 0.132977],
|
||||
[0.035176, 0.059829, 0.180467, 0.173876, 0.298352, 0.215616, 0.215878, 0.128704],
|
||||
[0.034559, 0.058643, 0.177542, 0.171009, 0.295821, 0.210218, 0.2117, 0.126359],
|
||||
[0.034403, 0.05819, 0.176997, 0.170261, 0.295912, 0.207018, 0.212888, 0.126165]],
|
||||
[[0.029566, 0.059562, 0.243806, 0.207322, 0.463634, 0.291584, 0.325791, 0.193909],
|
||||
[0.029298, 0.061726, 0.246011, 0.209549, 0.458765, 0.284765, 0.320308, 0.182122],
|
||||
[0.028968, 0.061057, 0.243338, 0.206377, 0.453594, 0.279703, 0.315468, 0.182056],
|
||||
[0.028267, 0.059642, 0.237384, 0.200645, 0.442402, 0.272115, 0.308655, 0.180162],
|
||||
[0.027137, 0.057377, 0.227716, 0.191872, 0.423647, 0.261575, 0.299658, 0.176199],
|
||||
[0.025681, 0.054436, 0.215303, 0.180651, 0.399507, 0.251328, 0.28745, 0.172239],
|
||||
[0.02417, 0.051239, 0.202306, 0.168953, 0.375398, 0.243321, 0.27559, 0.162706],
|
||||
[0.022952, 0.048545, 0.190989, 0.159814, 0.356878, 0.233677, 0.264156, 0.152101],
|
||||
[0.022227, 0.046819, 0.18402, 0.154438, 0.343659, 0.224139, 0.259843, 0.145105],
|
||||
[0.021936, 0.045935, 0.180616, 0.152628, 0.338249, 0.218227, 0.256523, 0.142398],
|
||||
[0.021882, 0.045678, 0.179959, 0.152495, 0.335621, 0.215501, 0.2523, 0.142617]],
|
||||
[[0.018837, 0.047905, 0.155059, 0.186692, 0.347461, 0.306618, 0.33988, 0.206121],
|
||||
[0.019157, 0.047897, 0.155947, 0.190091, 0.351254, 0.302947, 0.328952, 0.212534],
|
||||
[0.018971, 0.047322, 0.154434, 0.187836, 0.347801, 0.301953, 0.324074, 0.206068],
|
||||
[0.018546, 0.046194, 0.151131, 0.182665, 0.340286, 0.296834, 0.316122, 0.199278],
|
||||
[0.017827, 0.044387, 0.145605, 0.174982, 0.327504, 0.286282, 0.30676, 0.191026],
|
||||
[0.016805, 0.042131, 0.138145, 0.164988, 0.309582, 0.272263, 0.289937, 0.182776],
|
||||
[0.015742, 0.039801, 0.129722, 0.155184, 0.290223, 0.255044, 0.269294, 0.16933],
|
||||
[0.014905, 0.037915, 0.122636, 0.148065, 0.273758, 0.240601, 0.254658, 0.158117],
|
||||
[0.014379, 0.036638, 0.117937, 0.143748, 0.263661, 0.230678, 0.24355, 0.148667],
|
||||
[0.014116, 0.035959, 0.115617, 0.142012, 0.259929, 0.226493, 0.242352, 0.147483],
|
||||
[0.014038, 0.035781, 0.114705, 0.141777, 0.260744, 0.226395, 0.246105, 0.150568]],
|
||||
[[0.012175, 0.034843, 0.11421, 0.161747, 0.327803, 0.317063, 0.365159, 0.226221],
|
||||
[0.011869, 0.034285, 0.111599, 0.163187, 0.314637, 0.314145, 0.362527, 0.22581],
|
||||
[0.011745, 0.034, 0.110855, 0.161831, 0.310338, 0.308415, 0.356777, 0.222747],
|
||||
[0.011487, 0.033299, 0.108665, 0.158769, 0.302403, 0.299896, 0.346128, 0.217086],
|
||||
[0.011073, 0.03209, 0.104775, 0.153531, 0.290298, 0.287939, 0.332834, 0.206972],
|
||||
[0.010543, 0.030438, 0.099546, 0.146234, 0.275708, 0.273456, 0.316216, 0.197314],
|
||||
[0.010011, 0.028725, 0.09395, 0.138218, 0.260062, 0.260962, 0.302801, 0.189266],
|
||||
[0.009594, 0.027325, 0.089147, 0.1313, 0.24726, 0.25297, 0.289186, 0.182721],
|
||||
[0.009322, 0.026358, 0.086084, 0.126786, 0.238269, 0.246997, 0.280433, 0.174297],
|
||||
[0.009183, 0.025849, 0.084578, 0.12419, 0.234864, 0.242953, 0.274018, 0.171498],
|
||||
[0.009136, 0.025663, 0.084085, 0.123012, 0.234125, 0.240611, 0.272288, 0.169165]],
|
||||
[[0.007509, 0.024089, 0.082411, 0.145398, 0.289731, 0.313166, 0.381273, 0.247679],
|
||||
[0.007541, 0.024605, 0.080168, 0.142802, 0.286339, 0.305527, 0.37716, 0.242149],
|
||||
[0.007435, 0.024313, 0.079303, 0.141094, 0.283442, 0.304134, 0.370556, 0.238302],
|
||||
[0.007252, 0.023753, 0.077626, 0.137706, 0.276797, 0.299938, 0.359867, 0.232454],
|
||||
[0.00699, 0.022871, 0.074925, 0.132336, 0.266604, 0.289849, 0.346635, 0.224057],
|
||||
[0.006651, 0.021795, 0.071506, 0.125494, 0.252534, 0.273234, 0.332012, 0.214739],
|
||||
[0.006259, 0.020595, 0.067817, 0.118346, 0.237509, 0.258607, 0.320171, 0.205934],
|
||||
[0.005939, 0.019547, 0.064709, 0.112392, 0.224915, 0.248383, 0.311757, 0.19999],
|
||||
[0.005735, 0.018831, 0.062547, 0.108041, 0.215941, 0.23901, 0.304118, 0.192062],
|
||||
[0.005647, 0.018462, 0.061465, 0.105557, 0.211474, 0.231197, 0.297332, 0.18875],
|
||||
[0.005633, 0.018356, 0.061054, 0.10456, 0.210411, 0.226917, 0.295403, 0.188685]],
|
||||
[[0.004818, 0.017447, 0.058322, 0.121426, 0.259689, 0.291019, 0.396244, 0.265484],
|
||||
[0.00479, 0.017241, 0.057557, 0.123718, 0.249181, 0.293497, 0.389863, 0.282003],
|
||||
[0.004751, 0.017071, 0.057109, 0.122483, 0.248476, 0.291686, 0.385781, 0.276278],
|
||||
[0.004658, 0.016706, 0.055999, 0.119848, 0.245125, 0.286373, 0.378402, 0.2687],
|
||||
[0.00449, 0.016115, 0.053991, 0.1153, 0.237792, 0.276682, 0.366387, 0.257398],
|
||||
[0.004283, 0.015381, 0.051454, 0.109313, 0.226891, 0.263092, 0.349469, 0.243459],
|
||||
[0.004086, 0.014664, 0.048705, 0.103301, 0.215414, 0.247056, 0.329494, 0.229942],
|
||||
[0.0039, 0.014016, 0.046206, 0.097887, 0.205157, 0.234172, 0.311917, 0.217877],
|
||||
[0.00377, 0.013538, 0.044422, 0.094184, 0.197956, 0.223947, 0.302767, 0.208934],
|
||||
[0.003703, 0.013218, 0.043444, 0.092049, 0.191843, 0.219222, 0.297994, 0.203445],
|
||||
[0.003676, 0.013048, 0.043144, 0.091447, 0.189076, 0.217893, 0.295414, 0.201435]],
|
||||
[[0.002932, 0.01178, 0.038592, 0.096374, 0.21585, 0.267907, 0.395344, 0.288182],
|
||||
[0.00302, 0.011987, 0.040122, 0.097762, 0.217541, 0.271422, 0.381104, 0.296581],
|
||||
[0.002991, 0.011837, 0.039742, 0.096663, 0.215649, 0.269808, 0.37786, 0.296125],
|
||||
[0.002921, 0.011545, 0.038907, 0.094429, 0.210735, 0.263966, 0.370613, 0.289672],
|
||||
[0.002807, 0.011109, 0.037498, 0.090835, 0.202823, 0.254078, 0.356742, 0.278056],
|
||||
[0.002672, 0.010582, 0.035656, 0.086318, 0.191821, 0.241435, 0.339297, 0.26332],
|
||||
[0.002537, 0.010034, 0.033859, 0.081891, 0.181414, 0.228069, 0.31976, 0.24871],
|
||||
[0.002424, 0.009583, 0.032462, 0.078276, 0.173399, 0.216106, 0.299852, 0.238783],
|
||||
[0.002348, 0.009277, 0.031557, 0.075869, 0.168239, 0.205064, 0.284484, 0.227899],
|
||||
[0.002299, 0.009107, 0.031041, 0.074752, 0.165375, 0.198503, 0.278475, 0.219589],
|
||||
[0.002286, 0.009019, 0.030837, 0.074456, 0.164336, 0.196146, 0.275984, 0.213088]],
|
||||
[[0.001866, 0.00799, 0.02653, 0.077617, 0.228192, 0.255895, 0.470045, 0.33663],
|
||||
[0.001878, 0.007803, 0.026505, 0.075561, 0.22456, 0.250253, 0.445135, 0.333229],
|
||||
[0.001854, 0.007703, 0.026251, 0.074812, 0.221994, 0.247799, 0.439096, 0.325872],
|
||||
[0.001806, 0.007491, 0.025658, 0.073209, 0.216813, 0.241762, 0.425817, 0.314631],
|
||||
[0.001733, 0.007194, 0.02466, 0.070614, 0.208808, 0.230698, 0.405536, 0.29857],
|
||||
[0.001644, 0.006839, 0.023355, 0.06729, 0.198377, 0.215827, 0.380692, 0.277642],
|
||||
[0.001542, 0.006427, 0.022074, 0.063654, 0.187745, 0.202195, 0.359394, 0.255533],
|
||||
[0.001462, 0.006109, 0.021058, 0.060623, 0.178381, 0.191555, 0.345712, 0.240878],
|
||||
[0.001419, 0.005939, 0.020378, 0.058773, 0.17198, 0.184654, 0.336168, 0.233224],
|
||||
[0.001399, 0.005865, 0.020022, 0.057881, 0.169065, 0.181415, 0.337864, 0.231804],
|
||||
[0.001392, 0.005866, 0.019934, 0.057763, 0.168398, 0.181261, 0.340139, 0.231861]],
|
||||
[[0.001135, 0.005106, 0.017325, 0.054157, 0.145739, 0.227602, 0.352346, 0.340007],
|
||||
[0.001121, 0.004969, 0.017082, 0.054554, 0.137601, 0.233478, 0.346579, 0.326688],
|
||||
[0.00111, 0.004913, 0.016941, 0.053993, 0.136451, 0.232387, 0.347739, 0.321748],
|
||||
[0.001084, 0.004808, 0.016607, 0.052777, 0.13397, 0.229059, 0.345761, 0.315319],
|
||||
[0.001045, 0.004642, 0.016052, 0.050914, 0.129646, 0.222466, 0.339311, 0.304464],
|
||||
[0.001, 0.004428, 0.015297, 0.048643, 0.123952, 0.211784, 0.32332, 0.287065],
|
||||
[0.000955, 0.004216, 0.014489, 0.046431, 0.117648, 0.198573, 0.305751, 0.264775],
|
||||
[0.00092, 0.004073, 0.013803, 0.044777, 0.112305, 0.186397, 0.291345, 0.250223],
|
||||
[0.000899, 0.003988, 0.013432, 0.043631, 0.108717, 0.177924, 0.281948, 0.243653],
|
||||
[0.00089, 0.003939, 0.013315, 0.043199, 0.106845, 0.172378, 0.277072, 0.243999],
|
||||
[0.000887, 0.003915, 0.013278, 0.043189, 0.106241, 0.169059, 0.274576, 0.246788]],
|
||||
[[0.000737, 0.003389, 0.011401, 0.042329, 0.10131, 0.188955, 0.329114, 0.331588],
|
||||
[0.000684, 0.003229, 0.010625, 0.040531, 0.108862, 0.183569, 0.30035, 0.332997],
|
||||
[0.000679, 0.003192, 0.010592, 0.040063, 0.107742, 0.182135, 0.296562, 0.3315],
|
||||
[0.000664, 0.003108, 0.010462, 0.03916, 0.10554, 0.178692, 0.289801, 0.324287],
|
||||
[0.000639, 0.002983, 0.010163, 0.037718, 0.101745, 0.172834, 0.279922, 0.310785],
|
||||
[0.000607, 0.002832, 0.009788, 0.035878, 0.096823, 0.16541, 0.266072, 0.292975],
|
||||
[0.000579, 0.002697, 0.009362, 0.033911, 0.091466, 0.157625, 0.252907, 0.271475],
|
||||
[0.000558, 0.002587, 0.009036, 0.032314, 0.087185, 0.150848, 0.242333, 0.250448],
|
||||
[0.000547, 0.002536, 0.008866, 0.031395, 0.084544, 0.145882, 0.234755, 0.242683],
|
||||
[0.000546, 0.00254, 0.008804, 0.031111, 0.083383, 0.143231, 0.23129, 0.2427],
|
||||
[0.000549, 0.002548, 0.008778, 0.031092, 0.08304, 0.141883, 0.230425, 0.248831]],
|
||||
[[0.000438, 0.00209, 0.006927, 0.028513, 0.080977, 0.175395, 0.283978, 0.317315],
|
||||
[0.000431, 0.002072, 0.007103, 0.028284, 0.080941, 0.163135, 0.308395, 0.31471],
|
||||
[0.000424, 0.002044, 0.007033, 0.027916, 0.08059, 0.162628, 0.306179, 0.30816],
|
||||
[0.000413, 0.001998, 0.00687, 0.02731, 0.079407, 0.160648, 0.297822, 0.298507],
|
||||
[0.000396, 0.001924, 0.006574, 0.026178, 0.077142, 0.156812, 0.284197, 0.285274],
|
||||
[0.000377, 0.001822, 0.006185, 0.024723, 0.074135, 0.150552, 0.265112, 0.267977],
|
||||
[0.000358, 0.001716, 0.005796, 0.023309, 0.070591, 0.143989, 0.245623, 0.252488],
|
||||
[0.000345, 0.001642, 0.005529, 0.022234, 0.067043, 0.138249, 0.230291, 0.236251],
|
||||
[0.000335, 0.001603, 0.005425, 0.021655, 0.064463, 0.13294, 0.222632, 0.228162],
|
||||
[0.000332, 0.001594, 0.005397, 0.021405, 0.063098, 0.129358, 0.219653, 0.231073],
|
||||
[0.000334, 0.001602, 0.005432, 0.021517, 0.062805, 0.127758, 0.219773, 0.233717]],
|
||||
[[0.000259, 0.001318, 0.004615, 0.018197, 0.058734, 0.144307, 0.250173, 0.327878],
|
||||
[0.000261, 0.001278, 0.004364, 0.017692, 0.055408, 0.135773, 0.255457, 0.299149],
|
||||
[0.000258, 0.001263, 0.004315, 0.017501, 0.054945, 0.134624, 0.254467, 0.292231],
|
||||
[0.000252, 0.00124, 0.004227, 0.017182, 0.05359, 0.132356, 0.25002, 0.279887],
|
||||
[0.000245, 0.001207, 0.004099, 0.016728, 0.051377, 0.128686, 0.239888, 0.265269],
|
||||
[0.000235, 0.001169, 0.003951, 0.016042, 0.048484, 0.123597, 0.227074, 0.251621],
|
||||
[0.000225, 0.001128, 0.003784, 0.015228, 0.045462, 0.117528, 0.214543, 0.236935],
|
||||
[0.000215, 0.001087, 0.00364, 0.014478, 0.043168, 0.112353, 0.204079, 0.229124],
|
||||
[0.000208, 0.001047, 0.003519, 0.013885, 0.041578, 0.1087, 0.194682, 0.226638],
|
||||
[0.000203, 0.001025, 0.003442, 0.013583, 0.040542, 0.106395, 0.188369, 0.227661],
|
||||
[0.0002, 0.001011, 0.003387, 0.01346, 0.039907, 0.105684, 0.185467, 0.228179]],
|
||||
[[0.000162, 0.000805, 0.0028, 0.011825, 0.03739, 0.105943, 0.249376, 0.270804],
|
||||
[0.000159, 0.000814, 0.002703, 0.011909, 0.036484, 0.108349, 0.195962, 0.27395],
|
||||
[0.000158, 0.00081, 0.00269, 0.011794, 0.036308, 0.107088, 0.194261, 0.272348],
|
||||
[0.000155, 0.000796, 0.002649, 0.011543, 0.035783, 0.104625, 0.189667, 0.268992],
|
||||
[0.000149, 0.000772, 0.002567, 0.011086, 0.034868, 0.100648, 0.180658, 0.26301],
|
||||
[0.000142, 0.000731, 0.00244, 0.01058, 0.033425, 0.094801, 0.169625, 0.250993],
|
||||
[0.000135, 0.000687, 0.002309, 0.010141, 0.031409, 0.089298, 0.157987, 0.233151],
|
||||
[0.000129, 0.000651, 0.002182, 0.00976, 0.029667, 0.084757, 0.148046, 0.218176],
|
||||
[0.000125, 0.000629, 0.002114, 0.00947, 0.028551, 0.081757, 0.141687, 0.205743],
|
||||
[0.000122, 0.000616, 0.002076, 0.009249, 0.027986, 0.079745, 0.138961, 0.199748],
|
||||
[0.000121, 0.000609, 0.002058, 0.009112, 0.027738, 0.078976, 0.137693, 0.197267]],
|
||||
[[0.000107, 0.000554, 0.001865, 0.009203, 0.027441, 0.093386, 0.24069, 0.269488],
|
||||
[0.000113, 0.000594, 0.002101, 0.009295, 0.031062, 0.09478, 0.260741, 0.261185],
|
||||
[0.000112, 0.00059, 0.002083, 0.009237, 0.030885, 0.094928, 0.258247, 0.257623],
|
||||
[0.00011, 0.000579, 0.002039, 0.009074, 0.030409, 0.094224, 0.251962, 0.252259],
|
||||
[0.000106, 0.000558, 0.001952, 0.008742, 0.029537, 0.091457, 0.242576, 0.24403],
|
||||
[0.0001, 0.000523, 0.001835, 0.008233, 0.028153, 0.087368, 0.229908, 0.23416],
|
||||
[9.4e-05, 0.000487, 0.001715, 0.007637, 0.026328, 0.081842, 0.21503, 0.219172],
|
||||
[8.9e-05, 0.000457, 0.00161, 0.007093, 0.024678, 0.077991, 0.201858, 0.20875],
|
||||
[8.6e-05, 0.000439, 0.001539, 0.006792, 0.023387, 0.07509, 0.19362, 0.20638],
|
||||
[8.4e-05, 0.000431, 0.001504, 0.006647, 0.022488, 0.073348, 0.19096, 0.20527],
|
||||
[8.4e-05, 0.000431, 0.00151, 0.006676, 0.02218, 0.072313, 0.192041, 0.208168]]],
|
||||
'scales': [1.0, 1.5, 2.0, 3.0, 4.0, 6.0, 8.0, 12.0],
|
||||
'sizes': [1.0, 1.1225, 1.2599, 1.4142, 1.5874, 1.7818, 2.0, 2.2449, 2.5198, 2.8284, 3.1748, 3.5636, 4.0, 4.4898,
|
||||
5.0397, 5.6569, 6.3496, 7.1272, 8.0, 8.9797, 10.0794, 11.3137, 12.6992, 14.2544, 16.0]}
|
||||
+59
-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,9 @@ 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.
|
||||
|
||||
BACKGROUND = "The background of {picture} is not kept."
|
||||
@@ -57,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 = {
|
||||
@@ -170,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
|
||||
@@ -185,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> "
|
||||
@@ -297,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):
|
||||
@@ -397,6 +325,7 @@ class Cast:
|
||||
def __init__(self, pictures, video=""):
|
||||
self.pictures = pictures
|
||||
self.video = video
|
||||
self.voiced = False # A voice recording is connected.
|
||||
last = max((picture.subject for picture in pictures), default=0)
|
||||
self.people = [picture for picture in pictures if picture.job in (*ACTORS, START)]
|
||||
self.moves = subject_label(last + 1) if video == MOVES else ""
|
||||
@@ -464,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):
|
||||
@@ -501,6 +418,12 @@ class Cast:
|
||||
defined = {subject_label(picture.subject) for picture in self.of(*ACTORS, THING, START)}
|
||||
return self.main in defined
|
||||
|
||||
@property
|
||||
def as_typed(self):
|
||||
"""Two or more people and no voice recording: each spoken line goes to H3
|
||||
the way it was typed, and H3 reads who says it. The writer picks nobody."""
|
||||
return len(self.people) >= 2 and self.video in ("", MOVES, KEEP) and not self.voiced
|
||||
|
||||
def unclear_speaker(self, moments):
|
||||
"""A refusal when two or more people are connected and a spoken line does not say which one speaks."""
|
||||
if self.video not in ("", MOVES, KEEP) or len(self.people) < 2:
|
||||
@@ -511,6 +434,9 @@ class Cast:
|
||||
if not any(int(slot) in people for slot in TOKEN.findall(moment.text)):
|
||||
count = "two people" if len(self.people) == 2 else "more than one person"
|
||||
return f'With {count}, name who speaks: @{self.people[1].slot} says "hello".'
|
||||
if self.voiced and not any(int(slot) in people for slot in SAYS_AFTER.findall(moment.text)):
|
||||
# The recording's voice goes to one person, so they are named, never guessed.
|
||||
return f'With a voice and more than one person, put who speaks right before the words: @{self.people[1].slot} says "hello".'
|
||||
return ""
|
||||
|
||||
@property
|
||||
@@ -538,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:
|
||||
@@ -556,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
|
||||
+20
-13
@@ -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,12 +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>"
|
||||
said = f"says {delivery}" if delivery else "says"
|
||||
if speaker is None: # The typed line around it already says who speaks.
|
||||
return line
|
||||
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:
|
||||
@@ -296,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
|
||||
@@ -323,6 +331,8 @@ def write_prompt(script, seconds=15.0, camera="", look="", sound="", language="E
|
||||
script, jobs = put_on_from_pictures(script, jobs)
|
||||
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))
|
||||
@@ -335,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]
|
||||
@@ -355,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)
|
||||
|
||||
@@ -365,15 +375,12 @@ 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)
|
||||
|
||||
keeps_song = song_beats is not None and not voice # The song is then all the sound there is.
|
||||
parts = script_parts(
|
||||
scene, seconds, camera=camera, look=look, sound=sound, say=say, cast=cast, sounds=not keeps_song, soundtrack=soundtrack
|
||||
)
|
||||
parts = script_parts(scene, seconds, camera=camera, look=look, sound=sound, say=say, cast=cast, soundtrack=soundtrack)
|
||||
|
||||
if written and (video == EDIT or (video == SWAP and clip_sound)): # The clip's own sound stays in the result.
|
||||
parts["summary"] = add_task(parts["summary"], "audio reuse")
|
||||
|
||||
+436
-159
@@ -11,7 +11,9 @@ 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,
|
||||
KEEP,
|
||||
MAIN,
|
||||
@@ -31,7 +33,6 @@ from ._h3_cast_helpers import (
|
||||
TOKEN,
|
||||
things_that_perform,
|
||||
ONE_GOES,
|
||||
SPOTS,
|
||||
Cast,
|
||||
lower_first,
|
||||
number_pictures,
|
||||
@@ -43,25 +44,45 @@ from ._h3_cast_helpers import (
|
||||
QUOTES = {"“": '"', "”": '"', "‘": "'", "’": "'", "—": " - ", "–": " - ", "…": "..."}
|
||||
|
||||
# A word that starts a new moment inside a line. It goes, the order says it.
|
||||
THEN = r"(?:,?\s*(?:and\s+)?then\b|,?\s*and\s+after\s+that\b|,?\s*after\s+that\b|,?\s*afterwards?\b|,\s*next\b|,\s*later\b|,?\s*moments?\s+later\b)"
|
||||
# "Back then" and "next to her" are not one. "then" starts a moment unless it is part of a phrase like "by then";
|
||||
# "next" and "later" only after a comma, before who acts.
|
||||
WHO_ACTS = r"(?=\s*,|\s+(?:she|he|they|it|we|i|you|@\d|the|a|an|everyone|both)\b)"
|
||||
THEN = (
|
||||
r"(?:^\s*then\b,?|,\s*(?:and\s+)?then\b|\s+and\s+then\b|(?<!\bback)(?<!\bsince)(?<!\buntil)(?<!\btill)(?<!\bby)(?<!\bjust)(?<!\beven)(?<!\bonly)(?<!\bright)(?<!\bnow)\s+then\b|,?\s*and\s+after\s+that\b|,?\s*after\s+that\b"
|
||||
r"|,?\s*afterwards?\b|,\s*next" + WHO_ACTS + r"|,\s*later" + WHO_ACTS + r"|,?\s*moments?\s+later\b)"
|
||||
)
|
||||
# A word that starts a new moment and stays in it.
|
||||
TURN = r"(?=,?\s*\b(?:suddenly|all\s+of\s+a\s+sudden|out\s+of\s+nowhere|finally|at\s+last|(?:hard\s+)?cut\s+to|(?:it\s+|and\s+|(?<!\bit\s))ends?\s+(?:with|on|in|as)|ending\s+(?:with|on|in))\b)"
|
||||
# Only after a comma or an "and": "She suddenly turns" and "The dance ends with a spin" stay one moment.
|
||||
TURN = (
|
||||
r"(?=(?:,\s*(?:and\s+)?|\s+and\s+)(?:suddenly|all\s+of\s+a\s+sudden|out\s+of\s+nowhere|finally|at\s+last"
|
||||
r"|(?:(?:hard|smash|jump)\s+)?cut\s+to|(?:it\s+)?ends?\s+(?:with|on|in|as)|ending\s+(?:with|on|in))\b)"
|
||||
)
|
||||
# Where a line breaks into sentences: a full stop that is not a title, the end of a quote, or a semicolon.
|
||||
# After a quote, a new sentence starts with a capital or an @: in '"Get a job." @1 looks up' the @1 is a new moment,
|
||||
# or its own words are lost behind the first quote's. So is '"Hi" and @2 says "Bye"': one moment holds one quote.
|
||||
SENTENCE = r"(?<!\bMr\.)(?<!\bMs\.)(?<!\bDr\.)(?<!\bSt\.)(?<!\bMrs\.)(?<=[.!?])\s+(?=\S)|(?<=\x00)\s+(?=[A-Z@])|(?<=\x00),?\s+(?:and|but|while)\s+(?=@\d)|\s*;\s*"
|
||||
CUT_WORDS = re.compile(r"^(?:hard\s+)?(?:cut|cuts|smash\s+cut|jump\s+cut)\s+to\b[:,]?\s*", re.I)
|
||||
# "U.S." and "e.g." are not the end of a sentence. Two quotes in one sentence are two moments, in the order typed.
|
||||
SENTENCE = (
|
||||
r"(?<!\bMr\.)(?<!\bMs\.)(?<!\bDr\.)(?<!\bSt\.)(?<!\bMrs\.)(?<!\b[A-Z]\.[A-Z]\.)(?<!\be\.g\.)(?<!\bi\.e\.)(?<!\bvs\.)"
|
||||
r"(?<=[.!?])\s+(?=\S)|(?<=\x00)\s+(?=[A-Z@])|(?<=\x00),?\s+(?:and|but|while|as)\s+(?=@\d|[^\x00]*\x00)|\s*;\s*"
|
||||
)
|
||||
CUT_WORDS = re.compile(r"^(?:hard\s+)?(?:cut|cuts|smash\s+cut|jump\s+cut)\s+(?P<back>back\s+)?to\b[:,]?\s*", re.I)
|
||||
NEW_SHOT = re.compile(r"^(?:new\s+shot|next\s+shot|shot\s+\d+)\b[:,.\-]?\s*", re.I)
|
||||
START = re.compile(r"^(?:it\s+|the\s+(?:clip|video|scene|shot)\s+)?(?:starts?|begins?|opens?)(?:\s+(?:with|on|in|at|as)\b[:,]?|\s*:)\s*", re.I)
|
||||
START = re.compile(r"^(?:it\s+|the\s+(?:clip|video|scene|shot)\s+)?(?:starts?|begins?|opens?)(?:\s+with\b[:,]?|\s+(?:on|in|as)\b(?!\s+(?:\d|(?:a|an|one|two|three|four|five|six|seven|eight|nine|ten|a\s+few)\s+(?:seconds?|minutes?|hours?|days?)\b))[:,]?|\s+at\b(?!\s+(?:\d|one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve|noon|midnight)\b)[:,]?|\s*:)\s*", re.I)
|
||||
END = re.compile(r"^(?:it\s+|the\s+(?:clip|video|scene|shot)\s+)?(?:ends?|ending|finish(?:es)?|closes?)(?:\s+(?:with|on|in|at|as)\b[:,]?|\s*:)\s*", re.I)
|
||||
FINALLY = re.compile(r"^(?:finally|at\s+the\s+end|in\s+the\s+end)\b[:,]?\s*", re.I)
|
||||
FINALLY = re.compile(r"^(?:finally|at\s+the\s+end|in\s+the\s+end)\b(?!\s+of\b)[:,]?\s*", re.I)
|
||||
UNIT = r"(?:seconds?|secs?|s)\b"
|
||||
TIMED = re.compile(
|
||||
r"^\[?(?:at\s+)?(?:(\d+):(\d\d(?:\.\d+)?)|(\d+(?:\.\d+)?)\s*(?:" + UNIT + r"|(?=-\s*\d)))"
|
||||
r"(?:\s*-\s*\d+(?:\.\d+)?\s*(?:" + UNIT + r")?)?\]?\s*[:,\-]?\s*",
|
||||
r"^(?P<open>\[\s*|at\s+)?(?:(?P<min>\d+):(?P<sec>\d\d(?:\.\d+)?)|(?P<num>\d+(?:\.\d+)?)\s*(?:" + UNIT + r"|(?=-\s*\d)))"
|
||||
r"(?:\s*-\s*(?:\d+:\d\d(?:\.\d+)?|\d+(?:\.\d+)?)\s*(?:" + UNIT + r")?)?(?P<close>\s*\]\s*[:,\-]?|\s*[:,\-](?!\d))?\s*",
|
||||
re.I,
|
||||
)
|
||||
COMPACT_TIME = re.compile(r"\d+(?:\.\d+)?(?:s|secs?)\b", re.I)
|
||||
NUMBER = re.compile(
|
||||
r"^\s*(?:\d+[.):](?!\d)|[-*•]|(?:first|second|third|fourth|fifth|sixth)(?:ly)?\b(?!-|\s+(?:person|aid|time|times|thing|things|place"
|
||||
r"|day|days|date|look|light|class|floor|base|step|steps|frame|shot|half|row|line|lady|gear|kiss|snow|impression|of)\b)[:,]?"
|
||||
r"|step\s+\d+\s*[:.),])\s*",
|
||||
re.I,
|
||||
)
|
||||
NUMBER = re.compile(r"^\s*(?:\d+[.)](?!\d)|[-*•]|(?:first|second|third|fourth|fifth|sixth)(?:ly)?\b[:,]?|step\s+\d+[:.]?)\s*", re.I)
|
||||
LABEL = re.compile(r"^(camera|style|look|sound|sounds|audio|music)\s*:\s*(.*)$", re.I)
|
||||
SPEECH_CUE = re.compile(
|
||||
r"\b(?:says?|said|asks?|whispers?|shouts?|yells?|screams?|mutters?|sings?|raps?|chants?|announces?|calls?\s+out|cries"
|
||||
@@ -69,23 +90,36 @@ SPEECH_CUE = re.compile(
|
||||
re.I,
|
||||
)
|
||||
SIGN_CUE = re.compile(
|
||||
r"\b(?:title|titled|called|named|sign|signs|text|caption|card(?!\s+reader)|poster|reads?|saying|logo|banner|headline|words?)\b"
|
||||
r"(\b(?:title|titled|called|named|sign|signs|text|caption|card(?!\s+reader)|poster|logo|banner|headline)\b"
|
||||
r"|\breads?\b(?![^\"]*\b(?:aloud|out\s+loud)\b)|\b(?:with|in|reads?|reading)\s+the\s+words?\b|\bthe\s+word\b"
|
||||
r"|\b(?:t-?shirt|shirt|hoodie|jacket|mug|cap|hat|tattoo|label|note|board|sticker)\s+(?:(?!and\b|while\b)\w+\s+){0,2}?(?:says|reads|saying)\b"
|
||||
r"|\b(?:sign|banner|card|poster|text|caption)\s+(?:(?!and\b|while\b)\w+\s+){0,2}?saying\b)"
|
||||
r"[^\"]{0,24}$",
|
||||
re.I,
|
||||
)
|
||||
NO_MUSIC = re.compile(r"\b(?:no|without|skip)\s+(?:any\s+)?(?:music|soundtrack|score)\b|\bjust\s+(?:the\s+)?(?:ambien\w+|sound of|natural sound)\b", re.I)
|
||||
NO_SOUND = re.compile(r"\b(?:no\s+sound|no\s+audio|silent\s+(?:film|movie|clip|video)|completely\s+silent|total\s+silence|mute(?:d)?\b)", re.I)
|
||||
ONE_TAKE = re.compile(r"\b(?:one|single|continuous|unbroken)\s+(?:long\s+)?(?:shot|take)\b|\b(?:no|without)\s+cuts?\b", re.I)
|
||||
SIDE_NOTE = re.compile(
|
||||
r"^\s*(?:(?:no|without)\s+(?:any\s+)?(?:music|soundtrack|score|sound|audio|cuts?)(?:\s*,?\s*(?:just|only)\s+(?P<only>.+?))?"
|
||||
r"|one\s+(?:long\s+)?(?:shot|take)|single\s+(?:shot|take)|continuous\s+(?:shot|take))\s*[.!]?\s*$",
|
||||
NO_MUSIC = re.compile(r"\b(?:no|without|skip)\s+(?:any\s+)?(?:background\s+)?(?:music|soundtrack|score)\b|\bjust\s+(?:the\s+)?(?:ambien\w+|sound of|natural sound)\b", re.I)
|
||||
NO_SOUND = re.compile(
|
||||
r"\b(?:(?:no|without)\s+(?:any\s+)?(?:sound|audio)\b|silent\s+(?:film|movie|clip|video)\b|completely\s+silent\b|total\s+silence\b"
|
||||
r"|muted\s+(?:audio|sound)\b|on\s+mute\b|mute\s+(?:the\s+)?(?:audio|sound)\b)",
|
||||
re.I,
|
||||
)
|
||||
VOICEOVER = re.compile(r"\b(?:voice-?\s?over|narrator|off-?\s?(?:screen|camera)|behind\s+the\s+camera|a\s+voice)\b|\((?:o\.?s|v\.?o)\.?\)", re.I)
|
||||
ONE_TAKE = re.compile(r"\b(?:one|single|continuous|unbroken)\s+(?:long\s+)?(?:shot|take)\b(?!\s+(?:of|at)\b)|\b(?:no|without)\s+(?:camera\s+)?cuts?\b", re.I)
|
||||
SIDE_NOTE = re.compile(
|
||||
r"^\s*(?:(?:no|without)\s+(?:any\s+)?(?:background\s+|camera\s+)?(?:music|soundtrack|score|sound|audio|cuts?)(?:\s*,?\s*(?:just|only)\s+(?P<only>.+?))?"
|
||||
r"|(?:one|single|continuous|unbroken)\s+(?:long\s+)?(?:shot|take)"
|
||||
r"|(?:an?\s+)?silent\s+(?:film|movie|clip|video)|completely\s+silent|total\s+silence|silent|muted|on\s+mute"
|
||||
r"|(?:muted|mute\s+(?:the\s+)?)(?:audio|sound))\s*[.!]?\s*$",
|
||||
re.I,
|
||||
)
|
||||
VOICEOVER = re.compile(r"\b(?:voice-?\s?over|narrator|v\.?o\.?(?=\s*:)|(?<!looks\s)(?<!glances\s)(?<!stares\s)(?<!points\s)off-?\s?(?:screen|camera)|behind\s+the\s+camera|a\s+voice(?!\s+crack))\b|\((?:o\.?s|v\.?o)\.?\)", re.I)
|
||||
# Where a voice comes from, said beside who it is: "A woman off screen says", "Mom (O.S.):".
|
||||
FROM_OFF_SCREEN = re.compile(
|
||||
r"\b(?:(?:(?:in|as)\s+(?:an?\s+)?(?:off-?\s?screen\s+)?)?voice-?\s?over|off-?\s?(?:screen|camera)|behind\s+the\s+camera)\b|\((?:o\.?s|v\.?o)\.?\)", re.I
|
||||
)
|
||||
AFTER_VOICEOVER = re.compile(
|
||||
r"^\s*[,.]?\s*(?:(?:(?:in|as)\s+(?:an?\s+)?(?:off-?\s?screen\s+)?voice-?\s?over|from\s+off-?\s?(?:screen|camera))\b|\((?:o\.?s|v\.?o)\.?\))\.?",
|
||||
re.I,
|
||||
)
|
||||
PRONOUN = re.compile(r"\b(?:he|she|they|him|her|them)\b", re.I)
|
||||
PERSON_WORDS = re.compile(
|
||||
r"\b(?:man|men|woman|women|person|people|guy|girl|boy|kid|child|lady|gentleman|cashier|customer|clerk|waiter"
|
||||
@@ -99,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 = (
|
||||
@@ -117,7 +169,7 @@ NAMED = {PLACE: "the place", OUTFIT: "the outfit", THING: "the thing"} # What @
|
||||
|
||||
WORDS_A_SECOND = 3 # How fast H3 speaks.
|
||||
# Words that trail off ("I never thought...") keep going: across the next cut, or past the end of the clip.
|
||||
TRAILS_OFF = re.compile(r"(?:\.\.\.|\u2026|\u2014|--)\s*$")
|
||||
TRAILS_OFF = re.compile(r"(?:\.\.\.|\u2026|\u2014|--|\s-)\s*$")
|
||||
LINE_CARRIES = "<scenetrans> The line from the previous shot continues seamlessly across the cut, and the words are not repeated."
|
||||
CUT_OFF = "The line is cut off by the end of the video. <cutoff>"
|
||||
|
||||
@@ -147,7 +199,7 @@ OWN_COLOURS = "Each place keeps its own light and colours."
|
||||
ONE_SHOT = "One continuous shot with no cuts."
|
||||
EVERY_PLACE = "Every shot is a new place."
|
||||
AND_THEN = "Then {line}"
|
||||
STILL_MOVING = "the camera keeps moving forward."
|
||||
STILL_MOVING = "the camera keeps moving the same way."
|
||||
QUIET = "{speaker} stays silent with the lips closed."
|
||||
ONE_LINE = "No other words are spoken."
|
||||
PLACE_SOUND = "The steady sound of the place continues throughout."
|
||||
@@ -183,7 +235,6 @@ VIDEO_LOOKS = {
|
||||
REVOICE: "The target video keeps the look, light and camera of <Video 1>.",
|
||||
EDIT: "Retain the look of <Video 1>.",
|
||||
}
|
||||
NAMES_A_SPOT = re.compile(r"\b(?:left|right|behind|in\s+front|foreground|background)\b", re.I)
|
||||
OPENS_ON_THEM = re.compile(r"^(?:She|He)\b")
|
||||
FOLLOWS_A_COMMA = re.compile(r"^(?:A|An|The|She|He|They|It|Her|His|Their|Its|This|That|These|Those|There|Someone|Everyone|Nobody)\b")
|
||||
|
||||
@@ -229,56 +280,6 @@ LOOKS = {
|
||||
),
|
||||
}
|
||||
|
||||
# What a moment sounds like, said where it happens. H3 leaves a clip close to
|
||||
# silent between big events unless each sound is named in its own moment.
|
||||
MOMENT_SOUNDS = tuple(
|
||||
(re.compile(pattern, re.I), line)
|
||||
for pattern, line in (
|
||||
(r"\b(?:lights?|lamps?|bulbs?|neon)\b.*\b(?:flicker\w*|buzz\w*|go(?:es)?\s+(?:out|off|dark)|dim\w*)\b", "The lights buzz and crackle."),
|
||||
(r"\b(?:screens?|tvs?|televisions?|monitors?)\b.*\b(?:flicker\w*|static|glitch\w*|go(?:es)?\s+(?:black|dark|off)|turn\w*\s+(?:on|off|to))\b", "Static hisses and crackles."),
|
||||
(r"\b(?:thunder|lightning)\b", "Thunder cracks loudly."),
|
||||
(r"\b(?:rain|rainy|raining|downpour)\b", "Rain hisses on the ground."),
|
||||
(r"\b(?:wind|windy|gusts?|gale)\b", "The wind howls."),
|
||||
(r"\b(?:the|ocean|sea|big|huge|giant|crashing|breaking|rolling)\s+(?:\w+\s+)?waves\b|\bwaves\s+(?:crash|break|roll|pound|hit|rise|swell)\w*\b|\bsurf\b", "The water crashes and roars."),
|
||||
(r"\b(?:splash\w*|puddles?)\b", "Water splashes."),
|
||||
(r"\b(?:explo[ds]\w*|blasts?)\b", "A deep boom shakes the air."),
|
||||
(r"\b(?:fire|flames?|burns?|burning)\b", "Flames crackle and roar."),
|
||||
(r"(?<!a )\b(?:breaks?|breaking)\b(?!\s+(?:into|down|out|free|away|up|off|through))|\b(?:shatter\w*|smash\w*)\b", "Something shatters with a loud crack."),
|
||||
(r"\bdoors?\b.*\b(?:opens?|opening|closes?|closing|slams?|swings?|swung|shuts?)\b(?!-)|\b(?:opens?|opening|closes?|closing|slams?|shuts?)\b(?!-).*\bdoors?\b", "The door creaks and thuds."),
|
||||
(r"\b(?:engine|motorbike|motorcycle)\b|\b(?:car|truck)\b.*\b(?:speeds?|drives?|races?|pulls?\s+away)\b", "The engine roars."),
|
||||
(r"\btrains?\b", "The train rumbles on the rails."),
|
||||
(r"\bflash(?:es)?\b(?!\s+(?:a|her|his|their)\b)|\bshutter\b|\btakes? a (?:photo|picture)\b", "The camera shutter clicks loudly."),
|
||||
(r"\b(?:birds?|crows?)\b", "Wings flap."),
|
||||
(r"\b(?:runs?|running)\b(?!\s+(?:her|his|their|one|a)\b)|\b(?:sprints?|sprinting|flees?|fleeing)\b", "Fast footsteps hit the ground."),
|
||||
(r"\b(?:walks?|walking|strides?|striding)\b", "Footsteps sound on the ground."),
|
||||
(r"(?<!night )(?<!snow )(?<!hair )(?<!tears )(?<!silence )(?<!darkness )\b(?:falls?|falling)\b(?!\s+(?:asleep|silent|quiet|still|in\s+love))|\b(?:drops?|dropping|crash(?:es)?|collapses?|slams?)\b", "It lands with a heavy thud."),
|
||||
)
|
||||
)
|
||||
# What stays once it has happened: how it starts, what would change it, what to
|
||||
# say as it happens, and the line that holds it. H3 draws each moment on its
|
||||
# own, so the lights come back on in the next moment unless that moment says not.
|
||||
LASTING = tuple(
|
||||
(re.compile(started, re.I), re.compile(topic, re.I), now, line)
|
||||
for started, topic, now, line in (
|
||||
(
|
||||
r"\blights?\b.*\b(?:go(?:es)?\s+(?:out|off|dark)|die|dies|cut\s+out)\b|\bblackout\b|\b(?:goes|go|went)\s+dark\b",
|
||||
r"\b(?:lights?|lamps?|bulbs?|dark\w*)\b",
|
||||
"The whole place goes dark.",
|
||||
"The lights stay off.",
|
||||
),
|
||||
(r"\b(?:rain|raining|downpour)\b", r"\b(?:rain|raining)\b", "", "The rain keeps falling."),
|
||||
(r"(?<!static )(?<!tv )\bsnow(?:s|ing|fall|storms?)?\b", r"\bsnow", "", "The snow keeps falling."),
|
||||
(
|
||||
r"\b(?:screens?|tvs?|televisions?|monitors?)\b.*\b(?:go(?:es)?\s+(?:black|dark|off)|turn\w*\s+(?:black|off))\b",
|
||||
r"\b(?:screens?|tvs?|televisions?|monitors?)\b",
|
||||
"",
|
||||
"The screens stay dark.",
|
||||
),
|
||||
(r"\bon\s+fire\b|\bcatch(?:es)?\s+fire\b|\bbursts?\s+into\s+flames\b", r"\b(?:fire|flames?)\b", "", "The fire keeps burning."),
|
||||
)
|
||||
)
|
||||
NAMES_A_SOUND = re.compile(r"\b(?:sounds?|hears?|heard|noises?|loud\w*|silen\w*|quiet\w*|rumbl\w*|bangs?|booms?|roars?|hiss\w*|creak\w*|buzz\w*|howl\w*)\b", re.I)
|
||||
|
||||
|
||||
@dataclass
|
||||
class Moment:
|
||||
@@ -295,6 +296,8 @@ class Moment:
|
||||
voice: str = "" # Who says the words when it is nobody on screen: "The card reader".
|
||||
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
|
||||
@@ -305,12 +308,50 @@ 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"
|
||||
# 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 = []
|
||||
|
||||
def keep(match):
|
||||
kept.append(match.group(0))
|
||||
return f"\x01{len(kept) - 1}\x01"
|
||||
|
||||
text = re.sub(r'"[^"\n]*"', keep, text)
|
||||
text = SINGLE_QUOTED.sub(lambda match: f'{match.group(1)}"{match.group(2)}"', text)
|
||||
text = re.sub(r"\x01(\d+)\x01", lambda match: kept[int(match.group(1))], text)
|
||||
return text.replace("\r\n", "\n").replace("\r", "\n").strip()
|
||||
|
||||
|
||||
@@ -336,11 +377,16 @@ def split_line(line):
|
||||
for part in re.split(SENTENCE, masked):
|
||||
for bit in re.split(THEN + r"\s+|" + TURN, part, flags=re.I):
|
||||
bit = re.sub(r"[\s,;]*\band$", "", bit, flags=re.I)
|
||||
bit = re.sub(r"^[\s,;]*and\s+", "", bit, flags=re.I)
|
||||
if bit and bit.strip(" ,.;"):
|
||||
pieces.append(unmask(bit.strip(" ,;"), found))
|
||||
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)
|
||||
@@ -352,13 +398,17 @@ 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
|
||||
|
||||
|
||||
def read_notes(text, script):
|
||||
text = mask_quotes(text)[0]
|
||||
if NO_SOUND.search(text):
|
||||
script.silent = True
|
||||
if NO_MUSIC.search(text):
|
||||
@@ -397,34 +447,74 @@ def quoted_words(moment):
|
||||
return
|
||||
before = moment.text[: match.start()]
|
||||
words = match.group(1).strip()
|
||||
if not (SIGN_CUE.search(before) or (words.isupper() and not SPEECH_CUE.search(before))):
|
||||
sign, spoken = SIGN_CUE.search(before), SPEECH_CUE.search(before)
|
||||
if sign and spoken and re.search(r",|\b(?:and|while|then)\b", before[sign.end(1) : spoken.start()]):
|
||||
sign = None # "holds up a sign and shouts": the shout is the last thing done, so it is said.
|
||||
if not (sign or (words.isupper() and not spoken)):
|
||||
moment.speech = words
|
||||
moment.voiceover = VOICEOVER.search(before) is not None
|
||||
moment.voiceover = VOICEOVER.search(before) is not None or AFTER_VOICEOVER.match(moment.text[match.end() :]) is not None
|
||||
moment.voice = voice_of(before, moment.voiceover)
|
||||
|
||||
|
||||
def one_or_more(text, match):
|
||||
"""What an opening or an ending is on: two words or more, or one when it is
|
||||
set apart with a colon or is black or white ("Start on black.")."""
|
||||
rest = text[match.end() :].strip(" .")
|
||||
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)
|
||||
marked = timed and (timed.group("open") or timed.group("close") or timed.group("min") is not None or COMPACT_TIME.match(text))
|
||||
if timed and not marked:
|
||||
timed = None # "7 seconds remain on the clock" is something that happens; "3s she waves" is a time.
|
||||
if timed:
|
||||
if timed.group(1) is not None:
|
||||
moment.at = int(timed.group(1)) * 60 + float(timed.group(2))
|
||||
if timed.group("min") is not None:
|
||||
moment.at = int(timed.group("min")) * 60 + float(timed.group("sec"))
|
||||
else:
|
||||
moment.at = float(timed.group(3))
|
||||
moment.at = float(timed.group("num"))
|
||||
text = text[timed.end() :]
|
||||
cut = CUT_WORDS.match(text) or NEW_SHOT.match(text)
|
||||
if cut:
|
||||
moment.cut = True
|
||||
moment.back = bool(cut.groupdict().get("back"))
|
||||
text = text[cut.end() :]
|
||||
start = START.match(text)
|
||||
end = END.match(text) or FINALLY.match(text)
|
||||
if start and len(text[start.end() :].split()) > 1:
|
||||
if start and one_or_more(text, start):
|
||||
moment.start = True
|
||||
text = text[start.end() :]
|
||||
elif end and len(text[end.end() :].split()) > 1:
|
||||
elif end and one_or_more(text, end):
|
||||
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)
|
||||
|
||||
@@ -464,6 +554,15 @@ def read_script(text):
|
||||
count = len(script.moments)
|
||||
whole_clip = script.camera, script.sound
|
||||
script.camera = script.sound = ""
|
||||
shot = count # Where the shot that camera: and sound: lines belong to starts.
|
||||
|
||||
def hand_on(shot):
|
||||
"""camera: and sound: typed so far go to the shot they were typed in."""
|
||||
if shot < len(script.moments) and (script.camera or script.sound):
|
||||
moment = script.moments[shot]
|
||||
moment.camera, moment.sound = script.camera or moment.camera, script.sound or moment.sound
|
||||
script.camera = script.sound = ""
|
||||
|
||||
for offset, raw in enumerate(block.split("\n")):
|
||||
line = raw.strip()
|
||||
if not line or take_label(line, script):
|
||||
@@ -478,17 +577,20 @@ def read_script(text):
|
||||
continue
|
||||
moment = Moment(piece, cut=after_gap, line=opens)
|
||||
opens = None
|
||||
after_gap = False
|
||||
read_moment(moment)
|
||||
if moment.text:
|
||||
script.moments.append(moment)
|
||||
if not moment.text:
|
||||
after_gap = after_gap or moment.cut # "Shot 2:" on its own line cuts before the next moment.
|
||||
continue
|
||||
after_gap = False
|
||||
if moment.cut and len(script.moments) > count: # "Shot 2:" inside a block starts a shot of its own.
|
||||
hand_on(shot)
|
||||
shot = len(script.moments)
|
||||
script.moments.append(moment)
|
||||
hand_on(shot)
|
||||
typed = script.camera, script.sound
|
||||
script.camera, script.sound = whole_clip
|
||||
if len(script.moments) > count:
|
||||
script.moments[count].camera, script.moments[count].sound = typed
|
||||
else:
|
||||
if len(script.moments) == count:
|
||||
script.camera, script.sound = typed[0] or script.camera, typed[1] or script.sound
|
||||
read_notes(text, script)
|
||||
put_in_order(script)
|
||||
if script.one_take or not any(moment.cut for moment in script.moments):
|
||||
for moment in script.moments:
|
||||
@@ -532,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):
|
||||
@@ -547,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."""
|
||||
@@ -561,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
|
||||
|
||||
@@ -596,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]
|
||||
@@ -619,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):
|
||||
@@ -636,76 +847,140 @@ 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 = ""
|
||||
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):
|
||||
words = with_labels(without_speech(moment), cast)
|
||||
if moment.start:
|
||||
if moment.speech and cast.as_typed and not moment.voice and f'"{moment.speech}"' in moment.text:
|
||||
# More than one person: the line as typed, with only the words put in H3's speech tag.
|
||||
typed = with_labels(moment.text.replace(f'"{moment.speech}"', "\x02", 1), cast)
|
||||
if moment.start:
|
||||
typed = "The shot opens on " + lower_first(typed)
|
||||
elif moment.end:
|
||||
typed = "The shot ends on " + lower_first(typed)
|
||||
typed = typed.strip()
|
||||
typed = typed if typed.endswith("\x02") else sentence(typed)
|
||||
return typed.replace("\x02", say(moment.speech, not moment.voiceover, bare=True))
|
||||
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
|
||||
|
||||
|
||||
def moment_sound(moment, script):
|
||||
"""The sound of a moment, unless its words or the sound of the place already say it."""
|
||||
words = without_speech(moment)
|
||||
if NAMES_A_SOUND.search(words):
|
||||
# "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 ""
|
||||
for pattern, line in MOMENT_SOUNDS:
|
||||
if pattern.search(words):
|
||||
return "" if pattern.search(script.sound) else line
|
||||
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 still_true(moments):
|
||||
"""For each moment, the lines that hold what earlier moments changed. A
|
||||
moment that speaks of the same thing again decides for itself, and a new
|
||||
place starts clean."""
|
||||
held, found = {}, []
|
||||
for moment in moments:
|
||||
seen = without_speech(moment)
|
||||
if moment.cut and not FRAME_WORDS.match(seen):
|
||||
held = {}
|
||||
lines = [line for topic, line in held.items() if not topic.search(seen)]
|
||||
for started, topic, now, line in LASTING:
|
||||
if started.search(seen):
|
||||
held[topic] = line
|
||||
lines += [now] if now else []
|
||||
found.append(lines)
|
||||
return found
|
||||
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 first person it names, or the main person."""
|
||||
"""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
|
||||
person. With more than one person and no voice, as_typed means nobody is
|
||||
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
|
||||
named = [slot for slot in SAYS_AFTER.findall(before) if int(slot) in people]
|
||||
if named:
|
||||
return cast.subjects[int(named[-1])]
|
||||
for slot in TOKEN.findall(moment.text):
|
||||
if int(slot) in people:
|
||||
return cast.subjects[int(slot)]
|
||||
@@ -716,8 +991,8 @@ def speakers(moments, cast):
|
||||
"""Everyone who speaks, in the order H3 numbers them."""
|
||||
found = []
|
||||
for moment in moments:
|
||||
who = speaker_of(moment, cast)
|
||||
if moment.speech and who not in found:
|
||||
who = moment.voice if cast.as_typed else speaker_of(moment, cast)
|
||||
if moment.speech and who and who not in found:
|
||||
found.append(who)
|
||||
# A voice from off screen, like a card reader, comes after the people, who keep the low numbers.
|
||||
return [who for who in found if who.startswith("<")] + [who for who in found if not who.startswith("<")]
|
||||
@@ -788,9 +1063,9 @@ def before_the_action(number, text, cast, wearers):
|
||||
if places and not any(place in text for place in places):
|
||||
notes.append(IN_THE_PLACE.format(place=places[0]))
|
||||
people = people_in(text, cast)
|
||||
if len(people) > 1 and not NAMES_A_SPOT.search(text) and cast.video != SWAP: # A swap's people stand where the video has them.
|
||||
spots = [f"{person} is on the {spot}" for person, spot in zip(people, SPOTS[len(people)])]
|
||||
notes.append(sentence(", ".join(spots[:-1]) + f" and {spots[-1]} of the frame"))
|
||||
if len(people) > 1 and not any(person in text for person in people) and cast.video != SWAP:
|
||||
# "They sit down" names nobody, so H3 is told who they are. Where they stand is the script's to say.
|
||||
notes.append(f"{', '.join(people[:-1])} and {people[-1]} are in the shot.")
|
||||
for slot, wearer in wearers.items():
|
||||
outfit = cast.subjects[slot]
|
||||
# An edit has no person picture: the person in the video wears an outfit that no line names.
|
||||
@@ -815,10 +1090,12 @@ def after_the_action(text, cast):
|
||||
return notes
|
||||
|
||||
|
||||
def cut_to(words, text, cast):
|
||||
def cut_to(words, text, cast, back=False):
|
||||
"""How a later shot opens, and what is left of its first moment to say."""
|
||||
if FRAME_WORDS.match(words):
|
||||
return f"the camera cuts to {lower_first(words)}", ""
|
||||
if back:
|
||||
return f"the camera cuts back 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:
|
||||
@@ -826,13 +1103,12 @@ def cut_to(words, text, cast):
|
||||
return f"the camera cuts to {'a new view' if places else 'a new place'}.", words
|
||||
|
||||
|
||||
def shot_lines(script, seconds, say, cast, wearers, move="", hold="", sounds=True):
|
||||
def shot_lines(script, seconds, say, cast, wearers, move="", hold=""):
|
||||
"""One line for each shot. H3 jumps at a timed [Shot] mark whatever the words
|
||||
say, so the moments of one take are sentences inside one shot."""
|
||||
starts = timeline(script, seconds)
|
||||
talking = speakers(script.moments, cast)
|
||||
quiet = " ".join(QUIET.format(speaker=speaker) for speaker in talking if speaker.startswith("<"))
|
||||
kept = still_true(script.moments)
|
||||
carried, cut_off = speech_runs_on(script, seconds)
|
||||
lines = []
|
||||
for number, shot in enumerate(shots_of(script), 1):
|
||||
@@ -843,25 +1119,23 @@ def shot_lines(script, seconds, say, cast, wearers, move="", hold="", sounds=Tru
|
||||
for index in shot:
|
||||
moment = script.moments[index]
|
||||
|
||||
def speak(words, on_screen=True, moment=moment):
|
||||
def speak(words, on_screen=True, moment=moment, bare=False):
|
||||
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(
|
||||
[
|
||||
moment_words(moment, speak, cast),
|
||||
*kept[index],
|
||||
*([quiet] if quiet and not moment.speech else []),
|
||||
]
|
||||
).strip()
|
||||
if sounds and not script.silent:
|
||||
words = f"{words} {moment_sound(moment, script)}".strip()
|
||||
said.append(words)
|
||||
text = " ".join(said)
|
||||
first = shot[0]
|
||||
head, said[0] = (cut_to(said[0], text, cast) if number > 1 else ("", said[0]))
|
||||
head, said[0] = (cut_to(said[0], text, cast, script.moments[first].back) if number > 1 else ("", said[0]))
|
||||
if not head and starts[first] > 0: # A swap's first words can start late in the video.
|
||||
said[0] = f"At {stamp(starts[first])}, {after_comma(said[0])}"
|
||||
for place, index in enumerate(shot[1:], 1):
|
||||
@@ -896,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):
|
||||
@@ -929,8 +1203,11 @@ def summary_of(script, cast, new_places, soundtrack):
|
||||
return f"[{tag}] The target video continues directly from the end of <Video 1>{where}."
|
||||
talking = [who for who in speakers(script.moments, cast) if who.startswith("<")]
|
||||
who_speaks = f"{' and '.join(talking)} speak" if len(talking) > 1 else f"{cast.main} speaks"
|
||||
opening = with_labels(without_speech(script.moments[0]), cast) or who_speaks
|
||||
later = [with_labels(without_speech(script.moments[shot[0]]), cast) for shot in shots_of(script)[1:]]
|
||||
# With more than one person the summary keeps the typed line and only stands
|
||||
# "a line" in for the words, which the description already carries once.
|
||||
said = (lambda moment: re.sub(r'"[^"]*"', "a line", moment.text)) if cast.as_typed else without_speech
|
||||
opening = with_labels(said(script.moments[0]), cast) or who_speaks
|
||||
later = [with_labels(said(script.moments[shot[0]]), cast) for shot in shots_of(script)[1:]]
|
||||
if cast.opens and cast.ends:
|
||||
moving = f"moving from {picture_label(cast.opens.picture)} to {picture_label(cast.ends.picture)}"
|
||||
return f"[{task}] In the target video, {lower_first(opening.rstrip('.!? '))}, {moving}."
|
||||
@@ -941,13 +1218,13 @@ def summary_of(script, cast, new_places, soundtrack):
|
||||
return f"{summary} {EVERY_PLACE}" if new_places else summary
|
||||
|
||||
|
||||
def script_parts(script, seconds, camera="", look="", sound="", say=None, cast=None, sounds=True, soundtrack=False):
|
||||
def script_parts(script, seconds, camera="", look="", sound="", say=None, cast=None, soundtrack=False):
|
||||
"""H3's six parts, from a Script. say turns spoken words into H3's line.
|
||||
cast says what each picture and the video are for. sounds says H3 makes
|
||||
the sound, so each moment names its own. soundtrack says a video's own
|
||||
sound is connected."""
|
||||
cast says what each picture and the video are for. soundtrack says a
|
||||
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), "", ""))
|
||||
@@ -958,11 +1235,11 @@ def script_parts(script, seconds, camera="", look="", sound="", say=None, cast=N
|
||||
move = CAMERAS.get(typed, script.camera and sentence(script.camera)) or CAMERAS.get(camera, "")
|
||||
move = move.replace("<Subject 1>", cast.main)
|
||||
wearers = cast.wearers(script.moments)
|
||||
lines = shot_lines(script, seconds, say, cast, wearers, move, hold, sounds)
|
||||
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:]]
|
||||
moved = any(not FRAME_WORDS.match(without_speech(moment)) for moment in cuts)
|
||||
new_places = last > 1 and not cast.of(PLACE) and moved and all(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)
|
||||
if not style and cast.video == EDIT and not cast.of(PLACE):
|
||||
|
||||
@@ -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)
|
||||
@@ -0,0 +1,211 @@
|
||||
"""Tidy up: a small text model rewrites a typed script in plain, ordered sentences.
|
||||
|
||||
Each typed line is tidied on its own, so blank lines (cuts), timed lines and the order of lines
|
||||
never move; camera:, sound:, music: and look: lines are not sent. The model never sees the quoted
|
||||
words of a line: code holds each one out as SPOKEN (or SPOKEN1, SPOKEN2, ...), the model moves the
|
||||
markers next to whoever says them, and code puts the words back exactly as typed. A line's answer
|
||||
is used only when it keeps every marker once and the same @ people, and the writer reads it as it
|
||||
reads the typed line: the same words said in the same order, each typed "@N says" pair kept, nothing
|
||||
on a sign said, the same cuts and timed seconds. Any other line goes on as typed. A one-line idea is
|
||||
left for Auto prompt to fill out.
|
||||
|
||||
The instructions were picked from 25 versions tried on Qwen3-VL 8B: right speaker on
|
||||
38 of 38 lines it had not seen, every check passed on 77 of 79.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
from ._h3_script_helpers import LABEL as SETTING_LINE, SIGN_CUE, SPEECH_CUE, clean, read_script
|
||||
|
||||
TIDY_SYSTEM = (
|
||||
'You tidy up lines of a video script.\n'
|
||||
'\n'
|
||||
'Examples:\n'
|
||||
'\n'
|
||||
'Line: @2 waves while @1 says SPOKEN\n'
|
||||
'Cleaned: @2 waves while @1 says SPOKEN.\n'
|
||||
'\n'
|
||||
'Line: @1 stares at @2 who goes SPOKEN\n'
|
||||
'Cleaned: @1 stares at @2. @2 says SPOKEN.\n'
|
||||
'\n'
|
||||
'Line: @2 hugs @1 and whispers SPOKEN\n'
|
||||
'Cleaned: @2 hugs @1. @2 whispers SPOKEN.\n'
|
||||
'\n'
|
||||
'Line: @2 tells @1 SPOKEN\n'
|
||||
'Cleaned: @2 tells @1 SPOKEN.\n'
|
||||
'\n'
|
||||
'Line: @2 snaps at @1 SPOKEN\n'
|
||||
'Cleaned: @2 snaps at @1 SPOKEN.\n'
|
||||
'\n'
|
||||
'Line: the nurse checks the chart and says SPOKEN\n'
|
||||
'Cleaned: The nurse checks the chart. The nurse says SPOKEN.\n'
|
||||
'\n'
|
||||
'Line: SPOKEN @1 yells running to the door\n'
|
||||
'Cleaned: @1 runs to the door. @1 yells SPOKEN.\n'
|
||||
'\n'
|
||||
'Line: @1 asks SPOKEN1 n @2 shrugs SPOKEN2\n'
|
||||
'Cleaned: @1 asks SPOKEN1. @2 shrugs. @2 says SPOKEN2.\n'
|
||||
'\n'
|
||||
'Line: shot 1: @1 sits down. shot 2: he smiles at @2 n @2 goes SPOKEN\n'
|
||||
'Cleaned: Shot 1: @1 sits down. Shot 2: He smiles at @2. @2 says SPOKEN.\n'
|
||||
'\n'
|
||||
'Line: Voiceover: SPOKEN the man on the right opens the door\n'
|
||||
'Cleaned: The man on the right opens the door as a voiceover says SPOKEN.\n'
|
||||
'\n'
|
||||
'Line: camera: slow pan left\n'
|
||||
'@1 waves at @2 and asks SPOKEN\n'
|
||||
'Cleaned: camera: slow pan left\n'
|
||||
'@1 waves at @2. @1 asks SPOKEN.\n'
|
||||
'\n'
|
||||
'Line: the cat jumps on the table\n'
|
||||
'Cleaned: The cat jumps on the table.\n'
|
||||
'\n'
|
||||
'Rules:\n'
|
||||
'- Keep @1, @2, @3 exactly as written. Each one is a person. Never give a tag to someone the user did not tag: keep "she", "he", "the man on the left" as the user wrote them.\n'
|
||||
'- SPOKEN stands for words someone says out loud. Write each SPOKEN marker exactly once, straight after the person who says it and a speaking verb, like "@2 says SPOKEN."\n'
|
||||
'- Put the speaker right before the speaking verb: "@2 says SPOKEN", never "... and says SPOKEN" or "who says SPOKEN".\n'
|
||||
'- The one who does the action right before SPOKEN is the speaker, even when another tag comes after the action: in "@1 yells at @2 SPOKEN", @1 yells SPOKEN.\n'
|
||||
'- When the user names someone without a tag ("the waiter", "she"), keep those words for them; never swap in a tag or "he".\n'
|
||||
"- Keep the user's speaking verb (asks, whispers, shouts, replies).\n"
|
||||
'- Add nothing the user did not write: no new actions, sounds, music, camera moves, places, moods or lighting.\n'
|
||||
'- Fix spelling and grammar. Use short sentences.\n'
|
||||
'- Keep the labels the user wrote, such as "Shot 1:", "camera:" and "sound:", with their words.\n'
|
||||
'- Answer with the cleaned line only.\n'
|
||||
)
|
||||
|
||||
QUOTED = re.compile(r'"([^"\n]*)"|“([^”\n]*)”')
|
||||
HELD = re.compile(r"\x03(\d+)\x03")
|
||||
TAG = re.compile(r"@(\d+)")
|
||||
SPOKEN = re.compile(r"\bSPOKEN\d*\b")
|
||||
LABEL = re.compile(r"^\s*(?:cleaned(?:\s+line)?|answer)\s*:\s*", re.I)
|
||||
|
||||
|
||||
def marker(index, count):
|
||||
return "SPOKEN" if count == 1 else f"SPOKEN{index + 1}"
|
||||
|
||||
|
||||
def hold(script):
|
||||
"""(held script, markers, quotes): each quoted span swapped for its marker, the words as typed.
|
||||
|
||||
Quotes are taken out before any cleanup, so a quote inside a quote or a curly mark can't
|
||||
move where one ends. Words in single quotes after "says" become a quote in the cleanup and
|
||||
are held out after it."""
|
||||
quotes = []
|
||||
|
||||
def keep(words):
|
||||
quotes.append(words)
|
||||
return f"\x03{len(quotes) - 1}\x03"
|
||||
|
||||
text = QUOTED.sub(lambda match: keep(match.group(1) if match.group(1) is not None else match.group(2)), str(script or ""))
|
||||
text = re.sub(r'"([^"\n]*)"', lambda match: keep(match.group(1)), clean(text))
|
||||
order = [int(found.group(1)) for found in HELD.finditer(text)]
|
||||
marks = {index: marker(place, len(order)) for place, index in enumerate(order)}
|
||||
held = HELD.sub(lambda found: marks[int(found.group(1))], text)
|
||||
return held, [marks[index] for index in order], [quotes[index] for index in order]
|
||||
|
||||
|
||||
def put_back(answer, marks, quotes):
|
||||
"""The answer with each marker swapped for its words, in one pass."""
|
||||
words = dict(zip(marks, quotes))
|
||||
return SPOKEN.sub(lambda found: f'"{words[found.group(0)]}"', answer)
|
||||
|
||||
|
||||
def answer_ok(held, answer, marks):
|
||||
"""The answer keeps every marker once, the same @ people, and adds no long stretch of its own."""
|
||||
if not answer.strip() or sorted(SPOKEN.findall(answer)) != sorted(marks):
|
||||
return False
|
||||
if sorted(set(TAG.findall(answer))) != sorted(set(TAG.findall(held))):
|
||||
return False
|
||||
return len(answer) <= 2 * len(held) + 40
|
||||
|
||||
|
||||
# "@1 says", "@1 softly whispers:": a person named right before the marker they say.
|
||||
SAYS = re.compile(
|
||||
r"@(\d+)\s+(?:\w+ly\s+)?(?:says?|said|asks?|whispers?|shouts?|yells?|screams?|mutters?|sings?|raps?|chants?"
|
||||
r"|announces?|calls?\s+out|cries|replies|answers?|goes)\b(?:\s+\w+ly)?\s*[:,]?\s*$",
|
||||
re.I,
|
||||
)
|
||||
|
||||
|
||||
def before_each(held):
|
||||
"""{marker: the words typed before it, back to the end of the last sentence or the last marker}."""
|
||||
spans, start = {}, 0
|
||||
for found in SPOKEN.finditer(held):
|
||||
span = held[start : found.start()]
|
||||
spans[found.group(0)] = re.split(r"[.!?;]\s", span)[-1]
|
||||
start = found.end()
|
||||
return spans
|
||||
|
||||
|
||||
def same_roles(held, answer):
|
||||
"""Each marker typed right after "@N says" is still said by @N, and each one typed on a sign or a shirt
|
||||
is still on one."""
|
||||
typed, tidied = before_each(held), before_each(answer)
|
||||
for mark, span in typed.items():
|
||||
said, now = SAYS.search(span), SAYS.search(tidied.get(mark, ""))
|
||||
if said and (not now or now.group(1) != said.group(1)):
|
||||
return False
|
||||
shown = SIGN_CUE.search(span) and not SPEECH_CUE.search(span)
|
||||
if shown and not (SIGN_CUE.search(tidied[mark]) and not SPEECH_CUE.search(tidied[mark])):
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def reading(text):
|
||||
"""What the writer reads from the whole script: each spoken line with its shot and timed second, the
|
||||
quotes it shows rather than says, the number of cuts and the timed seconds."""
|
||||
shot, at, said, shown, times = 0, None, [], [], []
|
||||
for moment in read_script(text).moments:
|
||||
shot += bool(moment.cut)
|
||||
if moment.at is not None:
|
||||
at = moment.at
|
||||
times.append(moment.at)
|
||||
if moment.speech:
|
||||
said.append((shot, at, moment.speech))
|
||||
else:
|
||||
shown += [match.group(1).strip() for match in [re.search(r'"([^"\n]+)"', moment.text)] if match]
|
||||
return said, shown, shot, times
|
||||
|
||||
|
||||
def same_reading(typed, tidied):
|
||||
"""The writer reads the tidied script as it reads the typed one: everything said is still said, in the
|
||||
same order, shot and second; nothing it shows on a sign is said; the same cuts and timed seconds. A
|
||||
second quote in one sentence, which the writer can't give a voice, may become its own spoken line."""
|
||||
said, shown, cuts, times = reading(typed)
|
||||
now, _, now_cuts, now_times = reading(tidied)
|
||||
rest = iter(now)
|
||||
if not all(any(line == other for other in rest) for line in said):
|
||||
return False
|
||||
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, 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(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, 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):
|
||||
return script, False
|
||||
typed = read_script(script)
|
||||
if len(typed.moments) == 1 and not typed.moments[0].speech:
|
||||
return script, False # One idea: Auto prompt fills it out from the line as typed.
|
||||
lines = str(script).replace("\r\n", "\n").replace("\r", "\n").split("\n")
|
||||
out = list(lines)
|
||||
for index, line in enumerate(lines):
|
||||
if not line.strip() or SETTING_LINE.match(clean(line)):
|
||||
continue
|
||||
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
|
||||
return ("\n".join(out), True) if out != lines else (script, False)
|
||||
@@ -12,6 +12,7 @@ import hashlib
|
||||
import logging
|
||||
import math
|
||||
import re
|
||||
import statistics
|
||||
from functools import lru_cache
|
||||
from pathlib import Path
|
||||
from typing import Iterable, NamedTuple, Sequence
|
||||
@@ -33,6 +34,18 @@ _FLOW_PAD_MULTIPLE = 8
|
||||
# encoder downsamples by 8, so inputs are padded up to 128 px per side.
|
||||
_FLOW_MIN_SIZE = 128
|
||||
|
||||
# Cut finding (see standout_cuts). Measured on seven MiniMax H3 clips with 29
|
||||
# known cuts: on these settings every cut stood out at least 4.1 times from
|
||||
# its neighbours and motion inside a shot at most 1.9 times, so 3 sits
|
||||
# between them with room on both sides.
|
||||
CUT_THUMBNAIL_SIZE = 64 # long side of the thumbnails cuts are judged on
|
||||
CUT_SEARCH_RADIUS = 3 # thumbnail pixels a block may move between frames
|
||||
CUT_BLOCK = 4 # thumbnail pixels per block side
|
||||
CUT_NEIGHBOURS = 4 # pairs on each side that set the local level
|
||||
CUT_STANDOUT_RATIO = 3.0
|
||||
CUT_FLOOR = 0.02 # matched change a cut must pass, whatever its neighbours
|
||||
CUT_REPEAT_LEVEL = 0.002 # below this a pair is a repeated frame
|
||||
|
||||
|
||||
class FrameJob(NamedTuple):
|
||||
"""One planned output frame.
|
||||
@@ -115,12 +128,114 @@ def adjacent_frame_differences(
|
||||
return differences
|
||||
|
||||
|
||||
def detect_scene_cuts(differences: Sequence[float], threshold: float) -> set[int]:
|
||||
"""Indices a where (a, a+1) is a hard cut. A threshold of 0 disables."""
|
||||
def cut_thumbnails(
|
||||
frames: torch.Tensor, size: int = CUT_THUMBNAIL_SIZE, chunk_size: int = 8
|
||||
) -> torch.Tensor:
|
||||
"""Small BCHW RGB copies of every frame, ``size`` pixels on the long side.
|
||||
|
||||
Cuts are judged on these, so the search below costs the same at any
|
||||
resolution. Chunks stay small: a 1080p chunk is the only large
|
||||
temporary here.
|
||||
"""
|
||||
total, height, width = (int(value) for value in frames.shape[:3])
|
||||
scale = min(1.0, float(size) / max(height, width))
|
||||
target = (max(1, round(height * scale)), max(1, round(width * scale)))
|
||||
pieces = []
|
||||
for start in range(0, total, chunk_size):
|
||||
chunk = frames[start : start + chunk_size, ..., :3].float().permute(0, 3, 1, 2)
|
||||
pieces.append(functional.interpolate(chunk, size=target, mode="area").cpu())
|
||||
return torch.cat(pieces)
|
||||
|
||||
|
||||
def matched_frame_changes(
|
||||
thumbnails: torch.Tensor,
|
||||
radius: int = CUT_SEARCH_RADIUS,
|
||||
block: int = CUT_BLOCK,
|
||||
chunk_size: int = 64,
|
||||
) -> list[float]:
|
||||
"""How much each frame differs from the next once movement is allowed for.
|
||||
|
||||
Every block of the later thumbnail looks for its best match in the
|
||||
earlier one, moved up to ``radius`` pixels each way. Things that move
|
||||
inside a shot find their match, so motion mostly cancels out; after a
|
||||
cut the picture is new and no block finds one, even when both shots
|
||||
share the same place and colors.
|
||||
"""
|
||||
total = int(thumbnails.shape[0])
|
||||
height, width = (int(value) for value in thumbnails.shape[-2:])
|
||||
kernel = max(1, min(int(block), height, width))
|
||||
reach = max(0, int(radius))
|
||||
changes: list[float] = []
|
||||
for start in range(0, total - 1, chunk_size):
|
||||
end = min(start + chunk_size, total - 1)
|
||||
earlier = thumbnails[start:end]
|
||||
if reach:
|
||||
earlier = functional.pad(earlier, (reach, reach, reach, reach), mode="replicate")
|
||||
later = thumbnails[start + 1 : end + 1]
|
||||
best = None
|
||||
for dy in range(2 * reach + 1):
|
||||
for dx in range(2 * reach + 1):
|
||||
shifted = earlier[..., dy : dy + height, dx : dx + width]
|
||||
error = (shifted - later).abs().mean(dim=1, keepdim=True)
|
||||
error = functional.avg_pool2d(error, kernel, ceil_mode=True)
|
||||
best = error if best is None else torch.minimum(best, error)
|
||||
changes.extend(best.mean(dim=(1, 2, 3)).tolist())
|
||||
return changes
|
||||
|
||||
|
||||
def standout_cuts(
|
||||
changes: Sequence[float],
|
||||
ratio: float = CUT_STANDOUT_RATIO,
|
||||
floor: float = CUT_FLOOR,
|
||||
neighbours: int = CUT_NEIGHBOURS,
|
||||
) -> set[int]:
|
||||
"""Indices a where the change from a to a+1 jumps out from its neighbours.
|
||||
|
||||
The local level is the median change of up to ``neighbours`` pairs on
|
||||
each side; a cut is at least ``ratio`` times that and above ``floor``,
|
||||
so grain in a still shot never counts. Repeated frames (a change under
|
||||
``CUT_REPEAT_LEVEL``) say nothing about how fast a shot moves and are
|
||||
left out of the level, or footage drawn on twos or threes would read
|
||||
every real step as a cut. A clip with a single pair has nothing to
|
||||
compare against and gets no cut from this test.
|
||||
"""
|
||||
values = [float(value) for value in changes]
|
||||
if len(values) < 2:
|
||||
return set()
|
||||
cuts: set[int] = set()
|
||||
for index, value in enumerate(values):
|
||||
if value <= floor:
|
||||
continue
|
||||
around = [
|
||||
other
|
||||
for other in values[max(0, index - neighbours) : index]
|
||||
+ values[index + 1 : index + 1 + neighbours]
|
||||
if other >= CUT_REPEAT_LEVEL
|
||||
]
|
||||
level = statistics.median(around) if around else 0.0
|
||||
if value >= ratio * level:
|
||||
cuts.add(index)
|
||||
return cuts
|
||||
|
||||
|
||||
def detect_scene_cuts(
|
||||
differences: Sequence[float],
|
||||
threshold: float,
|
||||
matched_changes: Sequence[float] = (),
|
||||
) -> set[int]:
|
||||
"""Indices a where (a, a+1) is a hard cut. A threshold of 0 disables.
|
||||
|
||||
A pair is a cut when its plain difference is above ``threshold`` (the
|
||||
rule this node always had, so no cut found before is lost), or when its
|
||||
matched change stands out from the pairs around it. The second rule
|
||||
catches a cut between two shots of one place, whose plain difference
|
||||
can be smaller than fast motion inside a single shot.
|
||||
"""
|
||||
level = float(threshold)
|
||||
if level <= 0.0:
|
||||
return set()
|
||||
return {index for index, value in enumerate(differences) if value > level}
|
||||
cuts = {index for index, value in enumerate(differences) if value > level}
|
||||
return cuts | standout_cuts(matched_changes)
|
||||
|
||||
|
||||
def apply_scene_cuts(
|
||||
@@ -503,7 +618,11 @@ def interpolate_frames(
|
||||
jobs = plan_frame_jobs(total_frames, source, target)
|
||||
threshold = float(scene_cut_threshold)
|
||||
if threshold > 0.0 and any(not job.is_copy for job in jobs):
|
||||
cuts = detect_scene_cuts(adjacent_frame_differences(frames), threshold)
|
||||
cuts = detect_scene_cuts(
|
||||
adjacent_frame_differences(frames),
|
||||
threshold,
|
||||
matched_frame_changes(cut_thumbnails(frames)),
|
||||
)
|
||||
jobs = apply_scene_cuts(jobs, cuts)
|
||||
|
||||
if device is None:
|
||||
@@ -528,12 +647,15 @@ __all__ = [
|
||||
"adjacent_frame_differences",
|
||||
"apply_scene_cuts",
|
||||
"backward_warp",
|
||||
"cut_thumbnails",
|
||||
"detect_scene_cuts",
|
||||
"interpolate_frames",
|
||||
"is_passthrough",
|
||||
"matched_frame_changes",
|
||||
"method_uses_optical_flow",
|
||||
"output_frame_count",
|
||||
"plan_frame_jobs",
|
||||
"raft_checkpoint_path",
|
||||
"standout_cuts",
|
||||
"weighted_blend",
|
||||
]
|
||||
|
||||
@@ -27,6 +27,8 @@ from comfy.ldm.flux.layers import timestep_embedding
|
||||
from comfy.ldm.flux.math import apply_rope
|
||||
from comfy.ldm.modules.attention import optimized_attention_masked
|
||||
|
||||
from ._krea2_helpers import REFERENCE_STRENGTH_KEY, combine_attention_mask, reference_key_bias
|
||||
|
||||
|
||||
def _target_grid(x: torch.Tensor, patch: int) -> tuple[int, int]:
|
||||
hs, ws = x.shape[-2], x.shape[-1]
|
||||
@@ -107,6 +109,12 @@ def _attn_kv(
|
||||
if kv_cache is not None:
|
||||
k = torch.cat((k, kv_cache[0].to(k.dtype)), dim=2)
|
||||
v = torch.cat((v, kv_cache[1].to(v.dtype)), dim=2)
|
||||
# Krea 2 Encode 🆎's reference_curve: the cached reference keys are
|
||||
# the last ones, and get the step's strength as an attention bias.
|
||||
strength = transformer_options.get(REFERENCE_STRENGTH_KEY)
|
||||
if strength is not None:
|
||||
mask = combine_attention_mask(mask, reference_key_bias(
|
||||
k.shape[2], kv_cache[0].shape[2], strength.strength, q.dtype, q.device))
|
||||
if attn.kvheads != attn.heads:
|
||||
rep = attn.heads // attn.kvheads
|
||||
k = k.repeat_interleave(rep, dim=1)
|
||||
|
||||
@@ -9,6 +9,8 @@ agree on what a stitcher is, or Stitch Inpaint 🆎 stops serving both.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
|
||||
import torch
|
||||
import torch.nn.functional as functional
|
||||
|
||||
@@ -219,3 +221,91 @@ __all__ = [
|
||||
"snap16",
|
||||
"source_pixel_bbox",
|
||||
]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Reference strength over the run
|
||||
#
|
||||
# A reference reaches Krea 2 as extra tokens that every canvas token can
|
||||
# attend to. Its strength is how much attention those tokens get: adding
|
||||
# log(s) to the attention scores of the reference keys multiplies their
|
||||
# softmax weight by s before the weights are renormalised. s = 1 leaves the
|
||||
# model untouched, s = 0 gives the reference no weight at all (the canvas
|
||||
# then computes exactly as it would with no reference), and values between
|
||||
# fade it. The bias is one row of numbers per step, shared by every query
|
||||
# and every block, so it costs no memory worth counting.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
REFERENCE_STRENGTH_KEY = "ausboss_reference_strength"
|
||||
|
||||
|
||||
def reference_key_bias(key_count: int, reference_count: int, strength: float,
|
||||
dtype: torch.dtype, device: torch.device) -> torch.Tensor | None:
|
||||
"""Additive attention bias (1, 1, 1, keys) that scales the last ``reference_count`` keys by ``strength``.
|
||||
|
||||
None when it would change nothing: strength 1, or no reference keys.
|
||||
"""
|
||||
strength = max(0.0, float(strength))
|
||||
if reference_count <= 0 or abs(strength - 1.0) < 1e-6:
|
||||
return None
|
||||
reference_count = min(int(reference_count), int(key_count))
|
||||
bias = torch.zeros(1, 1, 1, int(key_count), dtype=dtype, device=device)
|
||||
bias[..., key_count - reference_count:] = math.log(strength) if strength > 0 else torch.finfo(dtype).min
|
||||
return bias
|
||||
|
||||
|
||||
def combine_attention_mask(mask: torch.Tensor | None, bias: torch.Tensor | None) -> torch.Tensor | None:
|
||||
"""``mask`` with ``bias`` added. A boolean mask (True = attend) becomes additive first."""
|
||||
if bias is None:
|
||||
return mask
|
||||
if mask is None:
|
||||
return bias
|
||||
if mask.dtype == torch.bool:
|
||||
mask = torch.zeros(mask.shape, dtype=bias.dtype, device=mask.device).masked_fill(
|
||||
~mask, torch.finfo(bias.dtype).min)
|
||||
return mask.to(bias.dtype) + bias
|
||||
|
||||
|
||||
class ReferenceStrength:
|
||||
"""Attention patch that scales the reference tokens by the current keyframe strength.
|
||||
|
||||
Core's Krea 2 appends the references after the canvas and records their
|
||||
token counts in ``reference_image_num_tokens``; the patch biases those
|
||||
keys. Krea 2 Outpaint Model Patch 🆎 feeds cached reference keys instead,
|
||||
and reads this object from transformer_options under
|
||||
REFERENCE_STRENGTH_KEY to bias them itself (_krea2_core._attn_kv).
|
||||
"""
|
||||
|
||||
def __init__(self, keyframes):
|
||||
self.keyframes = keyframes
|
||||
|
||||
@property
|
||||
def strength(self) -> float:
|
||||
return max(0.0, float(self.keyframes.strength))
|
||||
|
||||
def __call__(self, q, k, v, pe=None, attn_mask=None, extra_options=None):
|
||||
counts = (extra_options or {}).get("reference_image_num_tokens")
|
||||
if not counts:
|
||||
return {}
|
||||
bias = reference_key_bias(k.shape[-2], sum(int(n) for n in counts), self.strength, q.dtype, q.device)
|
||||
if bias is None:
|
||||
return {}
|
||||
return {"attn_mask": combine_attention_mask(attn_mask, bias)}
|
||||
|
||||
|
||||
def reference_strength_hooks(schedule: list[float]):
|
||||
"""A core hook group that carries the reference strength schedule on a conditioning."""
|
||||
import comfy.hooks
|
||||
|
||||
from ._curve_helpers import hook_keyframes
|
||||
|
||||
keyframes = hook_keyframes(schedule)
|
||||
patch = ReferenceStrength(keyframes)
|
||||
hook = comfy.hooks.TransformerOptionsHook(
|
||||
transformers_dict={"patches": {"attn1_patch": [patch]}, REFERENCE_STRENGTH_KEY: patch},
|
||||
hook_scope=comfy.hooks.EnumHookScope.HookedOnly,
|
||||
)
|
||||
hook.hook_keyframe = keyframes
|
||||
group = comfy.hooks.HookGroup()
|
||||
group.add(hook)
|
||||
return group
|
||||
|
||||
+211
-3
@@ -71,6 +71,8 @@ def parse_lora_stack(raw: str | None) -> list[dict[str, Any]]:
|
||||
"strength_clip": clamp_strength(entry.get("strength_clip", strength), strength),
|
||||
"enabled": enabled,
|
||||
"triggers": str(entry.get("triggers") or "").strip(),
|
||||
# The row follows the node's strength curve when one is linked.
|
||||
"curve": entry.get("curve") is True,
|
||||
}
|
||||
)
|
||||
return rows
|
||||
@@ -390,18 +392,203 @@ def unreadable_lora_message(name: str, reason: str, detail: str = "") -> str:
|
||||
return f"{message} Technical details: {detail}" if detail else message
|
||||
|
||||
|
||||
CURVE_WRAPPER_KEY = "ausboss_lora_curve"
|
||||
|
||||
|
||||
class LoraCurve:
|
||||
"""Moves the curve rows' strength from step to step.
|
||||
|
||||
The rows are loaded the way core's bypass LoRA loads them: the LoRA is
|
||||
added to each layer's output as the layer runs, and the model's weights
|
||||
are never rewritten. That works on every model file (full size, fp8, fp8
|
||||
scaled, int8) and costs no extra memory. Core reads each adapter's
|
||||
``multiplier`` while the layer runs, so this wrapper, called before the
|
||||
model at every step, sets it to the row's strength times the curve.
|
||||
"Where in the run" is the step's noise level, read the way core reads hook
|
||||
keyframes, so the LoRA curve and Krea 2's reference curve line up.
|
||||
"""
|
||||
|
||||
def __init__(self, curve: list[float]):
|
||||
from ._curve_helpers import keyframe_plan
|
||||
|
||||
self.plan = keyframe_plan(curve)
|
||||
self.rows: list[tuple[float, list]] = []
|
||||
self._starts = None
|
||||
self._sampling = None
|
||||
|
||||
def add_row(self, strength: float, adapters: list):
|
||||
self.rows.append((strength, adapters))
|
||||
|
||||
def set_strength(self, value: float):
|
||||
for strength, adapters in self.rows:
|
||||
for adapter in adapters:
|
||||
adapter.multiplier = strength * value
|
||||
|
||||
def strength_for(self, model_sampling, sigma, first: bool) -> float:
|
||||
"""The curve at this step. ``sigma`` is the step's noise level as the model gets it (a tensor)."""
|
||||
import torch
|
||||
|
||||
from ._curve_helpers import noise_plan, strength_at_noise
|
||||
|
||||
dtype = getattr(sigma, "dtype", torch.float64)
|
||||
if self._starts is None or self._sampling != (model_sampling, dtype):
|
||||
# Core compares keyframe starts with the step's noise level in the
|
||||
# step's own number type; rounding the starts to it reads every
|
||||
# step the same way, keyframe edges included.
|
||||
self._starts = [(torch.tensor(start, dtype=dtype).item(), value)
|
||||
for start, value in noise_plan(self.plan, model_sampling.percent_to_sigma)]
|
||||
self._sampling = (model_sampling, dtype)
|
||||
level = float(sigma.flatten()[0]) if hasattr(sigma, "flatten") else float(sigma)
|
||||
return strength_at_noise(self._starts, level, first)
|
||||
|
||||
def __call__(self, executor, x, t, c_concat, c_crossattn, control, transformer_options, **kwargs):
|
||||
level = float(t.flatten()[0]) if hasattr(t, "flatten") else float(t)
|
||||
sigmas = (transformer_options or {}).get("sample_sigmas")
|
||||
first = sigmas is not None and len(sigmas) > 0 and level >= float(sigmas.max())
|
||||
self.set_strength(self.strength_for(executor.class_obj.model_sampling, t, first))
|
||||
return executor(x, t, c_concat, c_crossattn, control, transformer_options, **kwargs)
|
||||
|
||||
|
||||
def _curve_hook_class():
|
||||
"""Core's bypass layer wrapper, made safe to take off in any order.
|
||||
|
||||
Core wraps a layer by replacing its ``forward`` and takes it off by putting
|
||||
back the ``forward`` it found. Two rows on one layer (two marked rows, or
|
||||
two LoRA Loaders in a chain) stack two wrappers, and core takes them off
|
||||
in the order it put them on, so the first row's wrapper used to stay
|
||||
behind with nothing under it and broke the next run. Taken off, a wrapper
|
||||
here only passes the layer through, and every wrapper that is no longer on
|
||||
top of another is removed for good.
|
||||
"""
|
||||
global _CURVE_HOOK
|
||||
if _CURVE_HOOK is None:
|
||||
import comfy.weight_adapter.bypass as bypass
|
||||
|
||||
class CurveHook(bypass.BypassForwardHook):
|
||||
active = False
|
||||
|
||||
def _bypass_forward(self, x, *args, **kwargs):
|
||||
if not self.active:
|
||||
return self.original_forward(x, *args, **kwargs)
|
||||
return super()._bypass_forward(x, *args, **kwargs)
|
||||
|
||||
def put_on(self):
|
||||
if self.original_forward is None:
|
||||
self.inject()
|
||||
self.active = True
|
||||
|
||||
def take_off(self):
|
||||
self.active = False
|
||||
module = self.module
|
||||
while True:
|
||||
top = getattr(module.forward, "__self__", None)
|
||||
if not isinstance(top, CurveHook) or top.active or top.original_forward is None:
|
||||
return
|
||||
top.eject()
|
||||
|
||||
_CURVE_HOOK = CurveHook
|
||||
return _CURVE_HOOK
|
||||
|
||||
|
||||
_CURVE_HOOK = None
|
||||
|
||||
|
||||
def _curve_row(model, lora_sd: Any, strength: float, curve: LoraCurve):
|
||||
"""Load a row that follows the curve onto the model in core's bypass mode.
|
||||
|
||||
Returns (model, parts): how many of the LoRA's parts reached the model.
|
||||
The few parts that are not low-rank adapters (a plain weight or bias
|
||||
difference) cannot change per step; they stay at the row's strength.
|
||||
"""
|
||||
import comfy.lora
|
||||
import comfy.lora_convert
|
||||
import comfy.patcher_extension
|
||||
import comfy.weight_adapter
|
||||
|
||||
key_map = comfy.lora.model_lora_keys_unet(model.model, {})
|
||||
loaded = comfy.lora.load_lora(comfy.lora_convert.convert_lora(lora_sd), key_map, log_missing=False)
|
||||
model = model.clone()
|
||||
model_keys = set(model.model.state_dict().keys())
|
||||
hook_class = _curve_hook_class()
|
||||
hooks = []
|
||||
adapters = []
|
||||
steady = {}
|
||||
for key, part in loaded.items():
|
||||
if isinstance(part, comfy.weight_adapter.WeightAdapterBase) and isinstance(key, str) and key in model_keys:
|
||||
layer = key[:-len(".weight")] if key.endswith(".weight") else key
|
||||
try:
|
||||
module = model.model.get_submodule(layer)
|
||||
except AttributeError:
|
||||
module = None
|
||||
if module is not None and getattr(module, "weight", None) is not None:
|
||||
hooks.append(hook_class(module, part, multiplier=strength))
|
||||
adapters.append(part)
|
||||
continue
|
||||
steady[key] = part
|
||||
parts = len(model.add_patches(steady, strength)) if steady else 0
|
||||
if hooks:
|
||||
def put_on(patcher, hooks=hooks):
|
||||
for hook in hooks:
|
||||
hook.put_on()
|
||||
|
||||
def take_off(patcher, hooks=hooks):
|
||||
for hook in hooks:
|
||||
hook.take_off()
|
||||
|
||||
# One key per row across the whole chain: a second LoRA Loader with a
|
||||
# curve must not replace the first one's rows.
|
||||
taken = sum(1 for key in getattr(model, "injections", {}) if key.startswith(f"{CURVE_WRAPPER_KEY}_"))
|
||||
model.set_injections(f"{CURVE_WRAPPER_KEY}_{taken}",
|
||||
[comfy.patcher_extension.PatcherInjection(inject=put_on, eject=take_off)])
|
||||
curve.add_row(strength, adapters)
|
||||
parts += len(hooks)
|
||||
return model, parts
|
||||
|
||||
|
||||
def _patch_clip_only(clip, lora_sd: Any, strength_clip: float):
|
||||
"""The CLIP half of a LoRA, applied as usual: the prompt is encoded once."""
|
||||
import comfy.lora
|
||||
import comfy.lora_convert
|
||||
|
||||
key_map = comfy.lora.model_lora_keys_clip(clip.cond_stage_model, {})
|
||||
loaded = comfy.lora.load_lora(comfy.lora_convert.convert_lora(lora_sd), key_map, log_missing=False)
|
||||
clip = clip.clone()
|
||||
clip.add_patches(loaded, strength_clip)
|
||||
return clip
|
||||
|
||||
|
||||
def apply_lora_stack(
|
||||
model, clip, rows: list[dict[str, Any]], on_missing: str = "error", missing: list | None = None
|
||||
model, clip, rows: list[dict[str, Any]], on_missing: str = "error", missing: list | None = None,
|
||||
curve: list[float] | None = None,
|
||||
):
|
||||
"""Apply the enabled, non-zero rows in order and return (model, clip).
|
||||
|
||||
In skip mode a row whose file cannot be found is warned about and left
|
||||
out; pass a list as ``missing`` to collect those rows, which is how the
|
||||
node keeps a LoRA that never loaded from adding its trigger words.
|
||||
|
||||
With a ``curve`` (a schedule from _curve_helpers), a row marked to follow
|
||||
it is loaded in core's bypass mode and its strength moves with the curve
|
||||
step by step (``LoraCurve``). The row's CLIP half is applied as usual.
|
||||
"""
|
||||
import comfy.sd
|
||||
|
||||
for row in rows:
|
||||
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.
|
||||
# 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 given, row in zip(rows, effective):
|
||||
if not row["enabled"]:
|
||||
continue
|
||||
strength_clip = row["strength_clip"] if clip is not None else 0.0
|
||||
@@ -423,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)
|
||||
@@ -435,6 +622,21 @@ def apply_lora_stack(
|
||||
raise ValueError(
|
||||
unreadable_lora_message(row["name"], unreadable_lora_reason(path), detail)
|
||||
) from exc
|
||||
if follower is not None and row.get("curve"):
|
||||
parts, known = 0, True
|
||||
if row["strength"] != 0:
|
||||
model, parts = _curve_row(model, lora_sd, row["strength"], follower)
|
||||
if strength_clip != 0:
|
||||
before = patch_total(None, clip)
|
||||
clip = _patch_clip_only(clip, lora_sd, strength_clip)
|
||||
after = patch_total(None, clip)
|
||||
if before is None or after is None:
|
||||
known = False
|
||||
else:
|
||||
parts += after - before
|
||||
if known and parts == 0:
|
||||
_warn_no_effect(row["name"], base_model_family(read_safetensors_metadata(path)))
|
||||
continue
|
||||
before = patch_total(model, clip)
|
||||
model, clip = comfy.sd.load_lora_for_models(
|
||||
model, clip, lora_sd, row["strength"], strength_clip
|
||||
@@ -444,6 +646,11 @@ def apply_lora_stack(
|
||||
# and future, and never fires on a LoRA that actually did something.
|
||||
if before is not None and after is not None and after == before:
|
||||
_warn_no_effect(row["name"], base_model_family(read_safetensors_metadata(path)))
|
||||
if follower is not None and follower.rows:
|
||||
from comfy.patcher_extension import WrappersMP
|
||||
|
||||
model = model.clone()
|
||||
model.add_wrapper_with_key(WrappersMP.APPLY_MODEL, CURVE_WRAPPER_KEY, follower)
|
||||
return model, clip
|
||||
|
||||
|
||||
@@ -458,6 +665,7 @@ def stack_fingerprint(rows: list[dict[str, Any]]) -> str:
|
||||
identity = "missing"
|
||||
parts.append(
|
||||
f"{row['name']}|{row['strength']}|{row['strength_clip']}|{row['enabled']}|{identity}"
|
||||
+ ("|curve" if row.get("curve") else "")
|
||||
)
|
||||
return ";".join(parts)
|
||||
|
||||
|
||||
+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
|
||||
|
||||
|
||||
@@ -67,7 +67,9 @@ def mask_to_preview_batch(mask: torch.Tensor, source: str = "Preview") -> torch.
|
||||
return mask.unsqueeze(-1)
|
||||
|
||||
|
||||
def save_temp_preview(image: torch.Tensor, prefix: str, source: str = "Preview", keep_alpha: bool = False) -> dict:
|
||||
def save_temp_preview(
|
||||
image: torch.Tensor, prefix: str, source: str = "Preview", keep_alpha: bool = False, compress_level: int = 4
|
||||
) -> dict:
|
||||
"""Write one preview PNG to the temp folder; returns its ui.images entry.
|
||||
|
||||
With ``keep_alpha`` a picture with see-through parts is saved with them,
|
||||
@@ -84,7 +86,7 @@ def save_temp_preview(image: torch.Tensor, prefix: str, source: str = "Preview",
|
||||
)
|
||||
)
|
||||
file = f"{filename}_{counter:05}_.png"
|
||||
preview.save(Path(full_output_folder) / file, compress_level=4)
|
||||
preview.save(Path(full_output_folder) / file, compress_level=compress_level)
|
||||
entry = {
|
||||
"filename": file,
|
||||
"subfolder": subfolder,
|
||||
@@ -97,26 +99,65 @@ def save_temp_preview(image: torch.Tensor, prefix: str, source: str = "Preview",
|
||||
return entry
|
||||
|
||||
|
||||
def preview_payload(image: torch.Tensor, prefix: str, source: str, result: tuple) -> dict:
|
||||
def save_live_sources(prefix: str, sources: dict, source: str = "Preview", keep_alpha: bool = False) -> dict:
|
||||
"""Write the pictures a node worked from to the temp folder, one PNG each,
|
||||
so the node's face can redraw its result while a value is dragged
|
||||
(js/shared/live_stage.mjs). `sources` maps an input name to its IMAGE
|
||||
batch (BHWC) or, for a name that ends in "mask", a MASK (BHW); the first
|
||||
frame of each is kept. With ``keep_alpha`` a picture's see-through parts
|
||||
are kept (Cut Out reads them). Returns { name: ui.images-style entry }; a
|
||||
picture that cannot be written is left out."""
|
||||
found = {}
|
||||
for name, value in sources.items():
|
||||
if value is None:
|
||||
continue
|
||||
try:
|
||||
batch = mask_to_preview_batch(value, source) if str(name).endswith("mask") else value
|
||||
entry = save_temp_preview(batch, f"{prefix}_{name}", source, keep_alpha=keep_alpha, compress_level=1)
|
||||
entry.pop("alpha", None)
|
||||
found[name] = entry
|
||||
except Exception: # noqa: BLE001 - the live picture is a convenience
|
||||
continue
|
||||
return found
|
||||
|
||||
|
||||
def preview_payload(
|
||||
image: torch.Tensor,
|
||||
prefix: str,
|
||||
source: str,
|
||||
result: tuple,
|
||||
keep_alpha: bool = False,
|
||||
extra_ui: dict | None = None,
|
||||
live_sources: dict | None = None,
|
||||
) -> dict:
|
||||
"""The node return that carries both a preview and the real outputs.
|
||||
|
||||
A preview is a convenience, never the job: if writing it fails - a full
|
||||
disk, a temp folder someone cleaned mid-run - the node still returns its
|
||||
outputs and only the panel goes quiet.
|
||||
outputs and only the panel goes quiet. ``keep_alpha`` keeps a cut-out's
|
||||
see-through parts in the preview (save_temp_preview).
|
||||
"""
|
||||
try:
|
||||
images = [save_temp_preview(image, prefix, source)]
|
||||
images = [save_temp_preview(image, prefix, source, keep_alpha)]
|
||||
except Exception as exc: # noqa: BLE001 - any failure here is non-fatal
|
||||
detail = str(exc).encode("ascii", "replace").decode("ascii")
|
||||
print(f"[AusBoss] {source}: preview unavailable ({detail}).")
|
||||
return {"result": result}
|
||||
return {"ui": {"images": images}, "result": result}
|
||||
ui = {"images": images}
|
||||
if extra_ui:
|
||||
ui.update(extra_ui)
|
||||
if live_sources:
|
||||
found = save_live_sources(prefix, live_sources, source, keep_alpha)
|
||||
if found:
|
||||
ui["ausboss_live"] = [found]
|
||||
return {"ui": ui, "result": result}
|
||||
|
||||
|
||||
__all__ = [
|
||||
"first_frame_to_pil",
|
||||
"mask_to_preview_batch",
|
||||
"preview_payload",
|
||||
"save_live_sources",
|
||||
"save_temp_preview",
|
||||
"temp_prefix",
|
||||
]
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
"""Cut Out 🆎."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from ._cut_out_helpers import KEEP_CHOICES, cut_out
|
||||
from ._preview_helpers import preview_payload, temp_prefix
|
||||
|
||||
PREVIEW_TOOLTIP = "Show the cut-out on its face, over a checkerboard. Off skips writing the preview file to ComfyUI's temp folder."
|
||||
|
||||
|
||||
class AusBossCutOut:
|
||||
CATEGORY = "🆎 AusBoss/Image"
|
||||
DESCRIPTION = (
|
||||
"Turns a picture and a mask into a cut-out with a see-through "
|
||||
"background, ready to save as a PNG or lay on a new background. "
|
||||
"Keep the white or the black part of the mask, grow or shrink it and "
|
||||
"soften its edge. Clean edges takes the old background's colour out "
|
||||
"of hair and soft edges, so the cut-out has no halo on a new "
|
||||
"background; pixels that are fully kept stay exactly as they were. "
|
||||
"Works on video frames too."
|
||||
)
|
||||
SEARCH_ALIASES = [
|
||||
"cut out", "cutout", "remove background", "transparent", "alpha", "rgba",
|
||||
"matte", "decontaminate", "edge halo", "ausboss",
|
||||
]
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {
|
||||
"image": ("IMAGE", {"tooltip": "The picture or video frames to cut out."}),
|
||||
"mask": ("MASK", {"tooltip": "What to keep. One mask can serve every frame of a video."}),
|
||||
"keep": (
|
||||
list(KEEP_CHOICES),
|
||||
{"default": "white", "tooltip": "Keep the part under the white of the mask, or under the black."},
|
||||
),
|
||||
"grow": (
|
||||
"INT",
|
||||
{
|
||||
"default": 0,
|
||||
"min": -256,
|
||||
"max": 256,
|
||||
"step": 1,
|
||||
"tooltip": "Grow the kept part by this many pixels, or shrink it with a negative number.",
|
||||
},
|
||||
),
|
||||
"feather": (
|
||||
"FLOAT",
|
||||
{
|
||||
"default": 1.0,
|
||||
"min": 0.0,
|
||||
"max": 256.0,
|
||||
"step": 0.5,
|
||||
"tooltip": "How soft the edge is, in pixels. 0 keeps the mask's own edge.",
|
||||
},
|
||||
),
|
||||
"clean_edges": (
|
||||
"BOOLEAN",
|
||||
{
|
||||
"default": True,
|
||||
"tooltip": "Take the old background's colour out of soft edges and hair, so the cut-out has no halo on a new background.",
|
||||
},
|
||||
),
|
||||
"clear_haze": (
|
||||
"FLOAT",
|
||||
{
|
||||
"default": 0.0,
|
||||
"min": 0.0,
|
||||
"max": 1.0,
|
||||
"step": 0.01,
|
||||
"tooltip": "Parts this see-through or more become fully clear. Raise it a little to clear a faint haze around the cut-out.",
|
||||
},
|
||||
),
|
||||
"solid_above": (
|
||||
"FLOAT",
|
||||
{
|
||||
"default": 1.0,
|
||||
"min": 0.0,
|
||||
"max": 1.0,
|
||||
"step": 0.01,
|
||||
"tooltip": "Parts at least this solid become fully solid. Lower it a little to fill thin see-through spots inside the subject.",
|
||||
},
|
||||
),
|
||||
"smooth_frames": (
|
||||
"INT",
|
||||
{
|
||||
"default": 0,
|
||||
"min": 0,
|
||||
"max": 8,
|
||||
"step": 1,
|
||||
"tooltip": "For a video: blend each frame's edge with this many frames before and after it, which calms a flickering edge. 0 is off.",
|
||||
},
|
||||
),
|
||||
},
|
||||
"optional": {
|
||||
"preview": ("BOOLEAN", {"default": True, "tooltip": PREVIEW_TOOLTIP}),
|
||||
},
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("IMAGE", "MASK")
|
||||
RETURN_NAMES = ("image", "alpha")
|
||||
OUTPUT_TOOLTIPS = (
|
||||
"The cut-out with a see-through background (RGBA). Save Image keeps the transparency in a PNG.",
|
||||
"How solid each pixel of the cut-out is: white is kept, black is clear.",
|
||||
)
|
||||
FUNCTION = "cut"
|
||||
|
||||
def __init__(self):
|
||||
self._prefix = temp_prefix("cut_out")
|
||||
|
||||
def cut(
|
||||
self,
|
||||
image,
|
||||
mask,
|
||||
keep,
|
||||
grow,
|
||||
feather,
|
||||
clean_edges,
|
||||
clear_haze,
|
||||
solid_above,
|
||||
smooth_frames,
|
||||
preview=True,
|
||||
):
|
||||
result, alpha = cut_out(
|
||||
image,
|
||||
mask,
|
||||
keep=str(keep),
|
||||
grow=int(grow),
|
||||
feather=float(feather),
|
||||
clean_edges=bool(clean_edges),
|
||||
clear_haze=float(clear_haze),
|
||||
solid_above=float(solid_above),
|
||||
smooth_frames=int(smooth_frames),
|
||||
)
|
||||
if not preview:
|
||||
return (result, alpha)
|
||||
return preview_payload(
|
||||
result, self._prefix, "Cut Out", (result, alpha), keep_alpha=True,
|
||||
live_sources={"image": image, "mask": mask},
|
||||
)
|
||||
|
||||
|
||||
NODE_CLASS_MAPPINGS = {"AUSBOSS_NODES_CutOut": AusBossCutOut}
|
||||
NODE_DISPLAY_NAME_MAPPINGS = {"AUSBOSS_NODES_CutOut": "Cut Out 🆎"}
|
||||
|
||||
__all__ = ["NODE_CLASS_MAPPINGS", "NODE_DISPLAY_NAME_MAPPINGS"]
|
||||
@@ -0,0 +1,176 @@
|
||||
"""Film Grain 🆎."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from ._grain_helpers import add_film_grain, auto_film_grain_values
|
||||
from ._grain_match_helpers import matched_film_grain_values
|
||||
from ._preview_helpers import preview_payload, temp_prefix
|
||||
|
||||
PREVIEW_TOOLTIP = "Show this node's result on its face. Off skips writing the preview file to ComfyUI's temp folder."
|
||||
|
||||
|
||||
class AusBossFilmGrain:
|
||||
CATEGORY = "🆎 AusBoss/Image"
|
||||
DESCRIPTION = (
|
||||
"Adds film grain to a picture or a video. The grain is strongest in "
|
||||
"the midtones and gentler in deep shadows and bright highlights, as "
|
||||
"on film. Size is the grain's size in pixels, roughness makes it "
|
||||
"finer and more uneven, and color turns it from black-and-white "
|
||||
"grain to colour film's. On a video it can move from frame to "
|
||||
"frame or stay put. An optional mask adds grain only where it is "
|
||||
"white. The same seed always gives the same grain. With Auto on, it "
|
||||
"picks the amount and size for the picture; wire a picture into "
|
||||
"grain from and it copies that picture's grain instead."
|
||||
)
|
||||
SEARCH_ALIASES = ["film grain", "grain", "noise", "35mm", "film look", "analog", "ausboss"]
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {
|
||||
"image": ("IMAGE", {"tooltip": "The picture or video frames to add grain to."}),
|
||||
"amount": (
|
||||
"FLOAT",
|
||||
{
|
||||
"default": 0.25,
|
||||
"min": 0.0,
|
||||
"max": 1.0,
|
||||
"step": 0.01,
|
||||
"tooltip": "How strong the grain is. 0 adds none; 0.25 is a clearly visible film look.",
|
||||
},
|
||||
),
|
||||
"size": (
|
||||
"FLOAT",
|
||||
{
|
||||
"default": 1.0,
|
||||
"min": 0.5,
|
||||
"max": 4.0,
|
||||
"step": 0.1,
|
||||
"tooltip": "How big each grain is, in pixels of this picture. Raise it for a big picture or a coarse film look.",
|
||||
},
|
||||
),
|
||||
"roughness": (
|
||||
"FLOAT",
|
||||
{
|
||||
"default": 0.5,
|
||||
"min": 0.0,
|
||||
"max": 1.0,
|
||||
"step": 0.01,
|
||||
"tooltip": "0 is even, soft grain. Higher mixes in finer grain that bunches up unevenly, like real film.",
|
||||
},
|
||||
),
|
||||
"color": (
|
||||
"FLOAT",
|
||||
{
|
||||
"default": 0.0,
|
||||
"min": 0.0,
|
||||
"max": 1.0,
|
||||
"step": 0.01,
|
||||
"tooltip": "0 is black-and-white grain. Higher gives each colour its own grain, like colour film.",
|
||||
},
|
||||
),
|
||||
"moving": (
|
||||
"BOOLEAN",
|
||||
{
|
||||
"default": True,
|
||||
"tooltip": "For a video. On: new grain on every frame, so it moves like film. Off: every frame gets the same grain.",
|
||||
},
|
||||
),
|
||||
"seed": (
|
||||
"INT",
|
||||
{
|
||||
"default": 0,
|
||||
"min": 0,
|
||||
"max": 0xFFFFFFFFFFFFFFFF,
|
||||
"control_after_generate": False,
|
||||
"tooltip": "Picks the grain pattern. The same seed always gives the same grain.",
|
||||
},
|
||||
),
|
||||
},
|
||||
"optional": {
|
||||
"mask": ("MASK", {"tooltip": "Optional. Grain goes only where the mask is white."}),
|
||||
"preview": ("BOOLEAN", {"default": True, "tooltip": PREVIEW_TOOLTIP}),
|
||||
"auto": (
|
||||
"BOOLEAN",
|
||||
{
|
||||
"default": False,
|
||||
"tooltip": "On: the node picks Amount and Size for this picture, so the grain looks the same on a small or a big one and matches the grain it already has. Amount and Size then become multipliers of its pick.",
|
||||
},
|
||||
),
|
||||
"auto_amount": (
|
||||
"FLOAT",
|
||||
{
|
||||
"default": 1.0,
|
||||
"min": 0.0,
|
||||
"max": 4.0,
|
||||
"step": 0.05,
|
||||
"tooltip": "Used while Auto is on. 1 is Auto's pick; 1.5 is half as strong again.",
|
||||
},
|
||||
),
|
||||
"auto_size": (
|
||||
"FLOAT",
|
||||
{
|
||||
"default": 1.0,
|
||||
"min": 0.25,
|
||||
"max": 4.0,
|
||||
"step": 0.05,
|
||||
"tooltip": "Used while Auto is on. 1 is Auto's pick; 2 is grain twice as big.",
|
||||
},
|
||||
),
|
||||
"grain_from": (
|
||||
"IMAGE",
|
||||
{
|
||||
"tooltip": "Optional. A picture whose grain you like. With Auto on, the node copies its grain: how strong, how big and how colourful. Roughness stays yours.",
|
||||
},
|
||||
),
|
||||
"auto_color": (
|
||||
"FLOAT",
|
||||
{
|
||||
"default": 1.0,
|
||||
"min": 0.0,
|
||||
"max": 4.0,
|
||||
"step": 0.05,
|
||||
"tooltip": "Used while Auto copies grain from a picture. 1 is the copied colour; 0 makes it black-and-white grain.",
|
||||
},
|
||||
),
|
||||
},
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("IMAGE",)
|
||||
RETURN_NAMES = ("image",)
|
||||
OUTPUT_TOOLTIPS = ("The picture or video frames with grain, at the same size.",)
|
||||
FUNCTION = "grain"
|
||||
|
||||
def __init__(self):
|
||||
self._prefix = temp_prefix("film_grain")
|
||||
|
||||
def grain(
|
||||
self, image, amount, size, roughness, color, moving, seed, mask=None, preview=True,
|
||||
auto=False, auto_amount=1.0, auto_size=1.0, grain_from=None, auto_color=1.0,
|
||||
):
|
||||
sent = None
|
||||
if auto and grain_from is not None:
|
||||
# The card's notes and the live preview read the match from here.
|
||||
picked = matched_film_grain_values(
|
||||
grain_from, image, float(roughness), int(seed), float(auto_amount), float(auto_size), float(auto_color),
|
||||
)
|
||||
amount, size, color = picked["amount"], picked["size"], picked["color"]
|
||||
sent = {"ausboss_grain_match": [{key: round(float(value), 5) for key, value in picked.items()}]}
|
||||
elif auto:
|
||||
picked = auto_film_grain_values(image, float(auto_amount), float(auto_size))
|
||||
amount, size = picked["amount"], picked["size"]
|
||||
sent = {"ausboss_grain_auto": [{key: round(value, 5) for key, value in picked.items()}]}
|
||||
result = add_film_grain(image, float(amount), float(size), float(roughness), float(color), bool(moving), int(seed), mask)
|
||||
if not preview:
|
||||
return (result,)
|
||||
return preview_payload(
|
||||
result, self._prefix, "Film Grain", (result,),
|
||||
extra_ui=sent,
|
||||
live_sources={"image": image, "mask": mask},
|
||||
)
|
||||
|
||||
|
||||
NODE_CLASS_MAPPINGS = {"AUSBOSS_NODES_FilmGrain": AusBossFilmGrain}
|
||||
NODE_DISPLAY_NAME_MAPPINGS = {"AUSBOSS_NODES_FilmGrain": "Film Grain 🆎"}
|
||||
|
||||
__all__ = ["NODE_CLASS_MAPPINGS", "NODE_DISPLAY_NAME_MAPPINGS"]
|
||||
@@ -77,10 +77,10 @@ class AusBossFrameInterpolate:
|
||||
"max": 1.0,
|
||||
"step": 0.01,
|
||||
"tooltip": (
|
||||
"Mean absolute frame difference above this counts "
|
||||
"as a hard cut, and the new frame holds the last "
|
||||
"frame before the cut instead of morphing across "
|
||||
"it. 0 disables cut detection."
|
||||
"At a hard cut the node holds a frame instead of "
|
||||
"mixing two shots. A cut is a change that jumps "
|
||||
"out from the frames around it, or any change "
|
||||
"above this number; 0 turns cut finding off."
|
||||
),
|
||||
},
|
||||
),
|
||||
|
||||
@@ -2,11 +2,14 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import inspect
|
||||
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_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
|
||||
|
||||
|
||||
@@ -27,6 +30,7 @@ JOB_HELP = (
|
||||
"best with nobody in the picture. Style gives only the look. Start on it and end on it fix the first or last moment."
|
||||
)
|
||||
NEEDS_TEXT_GENERATE = "This ComfyUI has no Generate Text node. Update ComfyUI, or disconnect the model on clip."
|
||||
TIDY_NEEDS_UPDATE = "[AusBoss] H3 Prompt Writer: this ComfyUI's Generate Text takes no system prompt, so Tidy up is off. Update ComfyUI."
|
||||
SAMPLING = {
|
||||
"sampling_mode": "on",
|
||||
"temperature": 0.5,
|
||||
@@ -68,6 +72,36 @@ def model_asker(clip, image):
|
||||
return ask
|
||||
|
||||
|
||||
def model_tidier(clip):
|
||||
"""ask(system, line, longest) for Tidy up: the same Generate Text, with its own instructions and no picture.
|
||||
|
||||
Greedy, so the same script tidies the same way every run. None on a ComfyUI whose Generate Text
|
||||
takes no system prompt (an older ComfyUI): the rest of the node still works there."""
|
||||
generate = _core_nodes().get("TextGenerate")
|
||||
if generate is None or not hasattr(generate, "execute"):
|
||||
raise RuntimeError(NEEDS_TEXT_GENERATE)
|
||||
if "system_prompt" not in inspect.signature(generate.execute).parameters:
|
||||
print(TIDY_NEEDS_UPDATE)
|
||||
return None
|
||||
|
||||
def ask(system, line, longest):
|
||||
output = generate.execute(clip=clip, prompt=line, max_length=longest, sampling_mode={"sampling_mode": "off"}, system_prompt=system)
|
||||
return output.result[0]
|
||||
|
||||
return ask
|
||||
|
||||
|
||||
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:
|
||||
a workflow can leave Tidy up on and tie it to the switch that turns its small model on."""
|
||||
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, system or TIDY_SYSTEM)[0]
|
||||
|
||||
|
||||
def fill_picture(pictures, jobs):
|
||||
"""What the small model may look at: the scene, never a person's photo, whose place may not be the clip's."""
|
||||
return next((pictures[slot] for job in (PLACE, START) for slot in pictures if jobs.get(slot) == job), None)
|
||||
@@ -298,6 +332,29 @@ class AusBossH3PromptWriter:
|
||||
),
|
||||
},
|
||||
),
|
||||
"tidy": (
|
||||
"BOOLEAN",
|
||||
{
|
||||
"default": False,
|
||||
"tooltip": (
|
||||
"Turn on to have the model on clip tidy your lines first: spelling, short sentences, and "
|
||||
"each spoken line next to whoever says it. Your quoted words stay exactly as typed. With no model on "
|
||||
"clip, your lines go as typed."
|
||||
),
|
||||
},
|
||||
),
|
||||
"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."
|
||||
),
|
||||
},
|
||||
),
|
||||
},
|
||||
}
|
||||
|
||||
@@ -339,7 +396,24 @@ 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, tidy=False, model_asks=""):
|
||||
inputs = dict(locals())
|
||||
del inputs["self"], inputs["script"], inputs["tidy"], inputs["model_asks"]
|
||||
inputs["asks"] = asks = parse_asks(model_asks)
|
||||
if tidy:
|
||||
tidy_text = tidied(script, clip, asks.get("tidy"))
|
||||
if tidy_text != script:
|
||||
try:
|
||||
return self._write(tidy_text, **inputs)
|
||||
except ValueError:
|
||||
pass # The writer turns down the tidied lines: it gets them as typed, and says so if they fail too.
|
||||
return self._write(script, **inputs)
|
||||
|
||||
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, 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 = ""
|
||||
@@ -351,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])
|
||||
@@ -387,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)
|
||||
@@ -413,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:
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user