Compare commits

...
173 Commits
Author SHA1 Message Date
ausboss 77a3fe1ff8 Merge pull request #442 from ausboss/release/2.30.0
Release 2.30.0
2026-11-28 11:54:27 -06:00
ausboss 95ab5f6e0e Release 2.30.0 2026-11-28 11:53:18 -06:00
ausboss aadfcb88ec Merge pull request #440 from ausboss/feat/h3-writer-gear
H3 Prompt Writer gear: working Reset and wording editor
2026-11-28 11:10:51 -06:00
ausboss e8da2a52a2 Drop an unused import from the wording editor's helpers 2026-11-28 11:09:53 -06:00
ausboss 5fec58ace9 Merge branch 'main' of https://github.com/ausboss/ComfyUI-AusBoss into feat/h3-writer-gear
# Conflicts:
#	CHANGELOG.md
2026-11-28 11:03:39 -06:00
ausboss f91c8e48d5 Merge pull request #434 from ausboss/feat/touch-rmbg3
Mask by Touch: RMBG-3.0 as a Fine edges choice
2026-11-28 10:53:24 -06:00
ausboss c5ad611bee Merge pull request #435 from ausboss/feat/h3-writer-sockets
H3 Prompt Writer: show only the sockets and picture chips in use
2026-11-28 10:53:13 -06:00
ausboss f71088b958 Merge remote-tracking branch 'origin/main' into feat/touch-rmbg3
# Conflicts:
#	CHANGELOG.md
2026-11-28 10:49:57 -06:00
ausboss fec84b928c Merge branch 'feat/h3-writer-sockets' into feat/h3-writer-gear 2026-11-28 10:42:10 -06:00
ausboss 4b1ef024b8 Merge branch 'main' into feat/h3-writer-sockets 2026-11-28 10:41:08 -06:00
ausboss 71c1ec2071 Merge pull request #439 from ausboss/fix/h3-swap-reading
H3 Prompt Writer: show how a swap script is read
2026-11-28 10:38:23 -06:00
ausboss 0991ef27bb Merge remote-tracking branch 'origin/main' into feat/touch-rmbg3
# Conflicts:
#	CHANGELOG.md
2026-11-28 10:35:13 -06:00
ausboss 170885cb73 Merge branch 'main' of https://github.com/ausboss/ComfyUI-AusBoss into fix/h3-swap-reading
# Conflicts:
#	CHANGELOG.md
2026-11-28 10:35:10 -06:00
ausboss a4354a47dd Merge pull request #438 from ausboss/fix/h3-writer-qa
H3 Prompt Writer: fixes from a 37-script test run
2026-11-28 10:34:50 -06:00
ausboss cb612c777f Merge remote-tracking branch 'origin/main' into fix/h3-writer-qa
# Conflicts:
#	CHANGELOG.md
2026-11-28 10:32:27 -06:00
ausboss c0e348bedd Merge pull request #441 from ausboss/fix/nodes2-wheel
Scroll long text boxes with the wheel in Nodes 2.0
2026-11-28 10:32:07 -06:00
ausboss 722878d0c1 Mask by Touch help: RMBG-3.0 needs up to about 17 GB of graphics memory 2026-11-28 10:24:03 -06:00
ausboss 0f4a156c6b Drop an unused import in H3 Prompt Writer's helpers 2026-11-28 06:16:14 -06:00
ausboss 78e696ad8b Give each person named in words their own line, and say an unquoted shout, in H3 Prompt Writer
With two people named only in words, every line went to the person in the
picture. Each one now has their own speaker. Words after yells, says or
whispers with no quotes are spoken.
2026-11-28 05:07:50 -06:00
ausboss 6effc61e2d Keep how a line is said in H3 Prompt Writer
Whispers, shouts, sings and the other speech words all reached the model
as "says". The typed word is kept, with any words between it and the
line ("says quietly"). A voiceover keeps its fixed phrase.
2026-11-28 03:51:49 -06:00
ausboss 2b03710023 Read a framing typed without an article as a framing in H3 Prompt Writer 2026-11-28 03:36:29 -06:00
ausboss df5ee8bb08 Leave a chat model's small talk out of H3 Prompt Writer's moments and sound 2026-11-28 03:31:59 -06:00
ausboss da10e98b43 Keep what someone does after a spoken line in H3 Prompt Writer 2026-11-28 03:27:34 -06:00
ausboss 6308a7257f Read single-quoted lines with an apostrophe and none in Sound in H3 Prompt Writer 2026-11-28 03:21:18 -06:00
ausboss 14298c6d7e Say when a style picture is used like a thing in H3 Prompt Writer 2026-11-28 03:06:14 -06:00
ausboss 9a7b8ee5b1 Keep H3 Prompt Writer's picture chips on one line
Four pictures and a video need more width than the node opens with, and
the chips wrapped inside a 30 px row: the video chip was drawn over the
Length row. The chips are now columns on one line that take what their
words need while there is room and give way widest first when there is
not, so a short job stays whole. A chip's hint starts with its job, which
may be cut short on a narrow node.
2026-11-28 03:01:10 -06:00
ausboss acbbb032ef Scroll long text boxes with the wheel in Nodes 2.0
Nodes 2.0 hands every wheel turn over a node to the graph on its way down
to the node, before the node's own parts see it, so a text box with more
lines than fit zoomed the graph and never scrolled. A listener that runs
first now lets a box of the pack's keep the wheel while it can still
scroll that way; the graph zooms once the box is at its end, as in the
classic renderer, which is unchanged.

Checked with real wheel turns on Text, Text Lines, Prompt Variations,
Krea 2 Encode and H3 Prompt Writer, and with the wheel sweep over every
node in both renderers (0 dead points).
2026-11-28 02:51:03 -06:00
ausboss a8321bccad Make the H3 writer gear's Reset work and stop the wording editor losing typing
- Reset puts the sockets back to "in use" and all four wordings back to
  built-in, as one undo step, and the menu shows it. A toast says Ctrl+Z
  brings the wordings back. Before, Reset changed nothing.
- Esc, or a click outside the editor, over typing that is not saved says
  so once; the second press closes. Before, the typing was gone.
- Save over a wording that lost a name the node fills in, such as
  {lines}, says what the model will miss; Save anyway keeps it. A name the
  node does not fill in is called out the same way.
- The editor's buttons stay on one line next to a long message.
2026-11-28 02:33:00 -06:00
ausboss a0b3c2ea95 Show every picture and who speaks in H3 Prompt Writer's swap reading
- The Ref2VA cast lists every subject the written prompt defines, and says
  who wears an outfit picture.
- A line the written prompt uses is no longer shown as not used.
- The Plain tab names the place, outfit, thing and style pictures, and who
  says each line.
- The swap reader's report tests sat below the file's main guard and never
  ran; the guard is now at the end of the file.
2026-11-28 02:20:57 -06:00
ausboss d6a7c630b2 Run the Save Image preview tests that sat below the main guard
Each test file runs as a script, so unittest.main() ran only the classes
above it and SaveImageLightPreviewTests never ran. A new test fails on any
test class or function written after the guard.
2026-11-28 02:13:30 -06:00
ausboss 03ddbc9ef7 Keep face drags as undo steps and fix H3 writer messages
- Moment strip, picture chips, Strength Curve and the Load Image strip
  record an undo step when a drag or pick ends; a test holds every file
  that commits widget values to it.
- The timeline reads the script for problems while a clip sets the
  length, and draws a 4 s bar for a 4 s clip.
- An unclosed quote runs to the end of its line and is spoken.
- Two start or two end pictures, @5 and above, and a missing picture each
  get a message that says what to do.
2026-11-28 02:10:50 -06:00
ausboss 060c40a195 Keep the wording editor's keys to itself and fill each wording in one pass
Ctrl+Enter in the editor saves instead of queuing a run with the old
wording, Tab stays inside it and Escape closes it from any control. The
editor stops at the length the writer reads. A {count} typed in a script
line is no longer filled in, too-deep JSON falls back to the built-in
wording, and the Full prompt tab no longer runs under the gear.
2026-11-28 00:06:43 -06:00
ausboss 9f3ac5a498 Add a gear menu to H3 Prompt Writer: which sockets show, and the wording its model is asked 2026-11-27 22:42:15 -06:00
ausboss c7fe70dde9 Use a chevron for the Read as fold in H3 Prompt Writer 2026-11-27 19:39:12 -06:00
ausboss d28ce0ebb6 Show a swap's reading as the Ref2VA cast or plain words, folded by default, in H3 Prompt Writer 2026-11-27 18:20:44 -06:00
ausboss 72f8830ebd Give the swap reading its own tint in H3 Prompt Writer's report box 2026-11-27 18:02:02 -06:00
ausboss 2477b758a0 Read swap lines sentence by sentence and show the reading in H3 Prompt Writer's report box 2026-11-27 17:58:27 -06:00
ausboss 84515ebd97 Read the description after @N and each swap line's own who-goes in H3 Prompt Writer 2026-11-27 16:43:50 -06:00
ausboss d19e6661b2 Mask by Touch RMBG-3.0: fixes from review
- Cards draw their choice buttons again after R, so a new model file
  gets its button without re-adding the node.
- Turning Fine edges off after RMBG-3.0 asks for Subject and Background
  again, so the face shows what the next run makes.
- RMBG-3.0 reads RMBG-3.0 even when it is the only model, and both of
  Bria's copies say which is which.
- A background-removal file stays one whatever it is called; a broken
  link or a decoder-only VAE is named as missing; one RMBG-3.0 copy is
  held at a time.
- A batch's subjects are kept through both passes of a run, so a long
  batch asks about each picture once.
- The help page and changelog give the real default and speed.
2026-11-27 15:47:22 -06:00
ausboss 2e8a10ec10 H3 Prompt Writer: reword a test comment 2026-11-27 15:05:04 -06:00
ausboss f0f5134c7e Mask by Touch: RMBG-3.0 as a Fine edges choice
With Bria's RMBG-3.0 files installed, Fine edges lists RMBG-3.0 next to
BiRefNet, and the Subject and Background picks use whichever is chosen.
BiRefNet stays the default. RMBG-3.0 is unloaded before BiRefNet runs so
the two never sit in graphics memory together.
2026-11-27 15:04:52 -06:00
ausboss 174d4a81b1 H3 Prompt Writer: the Sound and Music hints read as examples 2026-11-27 14:34:14 -06:00
ausboss c30b124178 H3 Prompt Writer: the socket rule follows the node's own picture sockets, however many 2026-11-27 14:34:14 -06:00
ausboss 37e13da2ae H3 Prompt Writer: wire ends stay on their dots, a copy keeps its size, and a node id cannot add style rules 2026-11-27 14:34:14 -06:00
ausboss 8520951187 H3 Prompt Writer: a picture chip only for a picture that is plugged in 2026-11-27 14:34:14 -06:00
ausboss 7f13daead7 H3 Prompt Writer: help page and changelog for the smaller socket list 2026-11-27 14:34:14 -06:00
ausboss 1fca384aff H3 Prompt Writer: a wire dropped on the node takes a shown socket, and a setting shows them all 2026-11-27 14:34:07 -06:00
ausboss f39396c5d4 H3 Prompt Writer: draw only the sockets in use 2026-11-27 14:34:07 -06:00
ausboss 98dced9d2f H3 Prompt Writer: the rule for which sockets show 2026-11-27 14:34:07 -06:00
ausboss 369702d22a Merge pull request #431 from ausboss/fix/changelog-mask-refine-unreleased
CHANGELOG: the Mask Refine edge change came after 2.29.0
2026-11-27 13:40:45 -06:00
ausboss f453bacf5e Merge main: keep both Unreleased entries (Mask Refine edges, LoRA trigger words) 2026-11-27 13:39:53 -06:00
ausboss 48c0bc0000 Merge pull request #432 from ausboss/fix/flat-curve-missing-trigger-words
LoRA Loader: keep a skipped LoRA's trigger words out on a flat curve
2026-11-27 13:39:30 -06:00
ausboss e76d475eb3 LoRA Loader: keep a skipped LoRA's trigger words out on a flat curve
With Stop on missing LoRA off, a row whose file is missing is skipped
and the node leaves its trigger words out by matching the rows
apply_lora_stack reports in `missing` against its own rows by identity.
A flat Strength Curve made apply_lora_stack swap the rows for scaled
copies, so it reported the copy, the match failed, and the skipped
LoRA's words still reached `triggers`.

apply_lora_stack now keeps the caller's rows, loads from the scaled
copies, and reports the caller's own row as missing. Adds tests for a
missing row on a flat and on a moving curve; the flat one fails before
this change.
2026-11-27 10:52:46 -06:00
ausboss b33ea15575 CHANGELOG: the Mask Refine edge change came after 2.29.0 2026-11-27 10:28:25 -06:00
ausboss 2f080686f9 Merge pull request #415 from kajan988/mask-refine-fix
Mask Refine: guided and matting edges follow the picture, plus Detail range and Fix threshold
2026-11-27 10:27:45 -06:00
ausboss c020e53435 Merge pull request #430 from ausboss/release/2.29.0
Release 2.29.0
2026-11-27 10:24:46 -06:00
ausboss 0632c104ff Merge pull request #429 from ausboss/feat/h3-tidy
Tidy up my lines: check each tidied line against the whole script
2026-11-27 10:24:05 -06:00
ausboss 62413eef53 Merge main into mask-refine-fix
# Conflicts:
#	CHANGELOG.md
2026-11-27 10:24:00 -06:00
ausboss 9943a60e63 Release 2.29.0 2026-11-27 10:23:54 -06:00
ausboss 050723f245 Merge pull request #340 from ausboss/feat/load-audio-clean-up
Load Audio: Clean up switch for voice recordings
2026-11-27 10:23:49 -06:00
ausboss c5bfdcfe93 Tidy: check each line against the whole script
A tidied line is kept only when the whole script reads the same with it, so
a timed line can't speak earlier and a typed cut can't vanish. A quote typed
right after "@N says" keeps that person, and a quote on a sign stays on it
even next to dialogue.
2026-11-27 10:22:49 -06:00
ausboss 5cdb560c0c Merge main into mask-refine-fix
# Conflicts:
#	CHANGELOG.md
2026-11-27 10:20:24 -06:00
ausboss 6640478428 Merge main into feat/load-audio-clean-up
# Conflicts:
#	CHANGELOG.md
2026-11-27 10:17:29 -06:00
ausboss 067e5e946a Merge pull request #428 from ausboss/feat/h3-tidy
H3 Prompt Writer: optional Tidy up (the model on clip cleans up typed lines)
2026-11-27 10:17:06 -06:00
ausboss af923711a2 Pin Mask Refine's two new fallbacks in the saved-fallbacks test 2026-11-27 10:16:03 -06:00
ausboss 7766dad425 Tidy each typed line on its own
Blank lines, timed lines and the order of lines no longer pass through the
model, and camera, sound, music and look lines are not sent. A line's answer
is used only when every typed @N says "..." pair keeps its person, the same
words are said in the same order, and a quote shown on a sign (curly quotes
too) is not voiced.
2026-11-27 10:15:17 -06:00
ausboss 4f54298cac Merge main into mask-refine-fix 2026-11-27 10:10:30 -06:00
ausboss e2cef8e75c Load Audio: Chinese text for the Clean up row 2026-11-27 10:09:56 -06:00
ausboss ce672777c5 Merge remote-tracking branch 'origin/main' into feat/load-audio-clean-up
# Conflicts:
#	CHANGELOG.md
2026-11-27 10:06:41 -06:00
ausboss b9abadc011 Tidy up: use a tidy only when the writer reads it the same way
- Quotes are held out before any cleanup and put back in one pass, so a
  quote inside a quote or a quote that reads like a marker comes back as
  typed.
- @12 is not @1.
- A tidy is used only when everything said is still said, nothing on a
  sign or shirt becomes speech, and the cuts and timed seconds stay. A
  second quote in one sentence, which the writer can't voice, may become
  its own spoken line.
- Tidied lines the writer turns down go through as typed.
- A one-line idea is left for the model to fill out.
- The help no longer says quoted words never reach the model (the sound
  step still reads the lines), and drops a wrong ComfyUI version.
2026-11-27 10:05:41 -06:00
ausboss 7315c9bd30 Tidy up on a ComfyUI older than 0.46.1 leaves the lines as typed and says why in the log 2026-11-27 09:41:29 -06:00
ausboss cf5e5a832b Tidy up with nothing on clip leaves the lines as typed, so a workflow can leave it on 2026-11-27 09:39:49 -06:00
ausboss 4c1d25d81f Merge remote-tracking branch 'origin/main' into feat/h3-tidy 2026-11-27 09:36:49 -06:00
ausboss 3f248d1b98 Merge pull request #426 from ausboss/fix/h3-reading
H3 Prompt Writer follows the script's layout
2026-11-27 09:36:42 -06:00
ausboss 839e00bbac H3 Prompt Writer: optional Tidy up, the model on clip cleans up the typed lines
A new optional tidy switch (off by default, under More). With a text model on
clip it rewrites the typed script in short, ordered sentences and puts each
spoken line right after whoever says it. Quoted words are held out as markers
and put back exactly as typed; an answer that loses or repeats a marker,
changes the @ tags or grows far longer is dropped and the lines go on as typed.
H3's own six parts are never tidied.
2026-11-27 08:49:14 -06:00
ausboss 2a367a90cc Merge remote-tracking branch 'origin/main' into fix/h3-reading 2026-11-27 00:42:18 -06:00
ausboss 9c2fa1e454 Merge pull request #425 from ausboss/fix/h3-sound-words
H3 Prompt Writer keeps to what was typed
2026-11-27 00:41:40 -06:00
ausboss 57672d9058 H3 Prompt Writer: with two or more people, a spoken line goes to H3 as typed 2026-11-27 00:40:43 -06:00
ausboss 365050aa8c H3 Prompt Writer: who, she and a second named person keep the words 2026-11-26 23:37:11 -06:00
ausboss b9c5898285 H3 Prompt Writer: the speaker is who opens the clause, and quotes inside quotes stay put 2026-11-26 23:30:36 -06:00
ausboss b90ee3bf14 H3 Prompt Writer follows the script's layout
Moments split only at sequence words: "Back then", "next to her" and
"U.S." stay whole. A time needs its mark, so "7 seconds remain" is an
action, and a range like [00:02-00:04] is read whole, in the writer and
when a moment is dragged on the bar.

camera: and sound: lines go to the shot they are typed under, and a
Shot 2: header on its own line cuts before the next moment. Two quotes
in one sentence are two lines, single quotes after a speech word are
speech, voiceover said after a quote counts, and the person named just
before the speech word says it.

"Cut back to" returns to a place already shown, "Start on black."
opens on black, a line broken off with a dash trails off, and two
people are no longer placed left and right unless the script says so.
2026-11-26 23:19:26 -06:00
ausboss f3fd30e965 Keep "starts in ten seconds" where it was typed
The time guard covers "starts in" and "starts on" again, for a time
or a date, while "starts on one knee" and "starts with two people"
still open the clip.
2026-11-26 23:05:39 -06:00
ausboss 4186db0a26 Read clip notes only from a note of their own
"The TV plays without audio" no longer silences the clip, and an
opening such as "Starts with two people" moves first again. The time
guard now applies only to "starts at nine".
2026-11-26 22:59:48 -06:00
ausboss 1749792457 H3 Prompt Writer keeps to what was typed
The writer lays the notes out for H3 and no longer adds sound or
state sentences of its own. Notes are read more carefully: clip-wide
switches only match whole notes outside quotes, ordinals and step
numbers keep words like "First person", mid-sentence words such as
"suddenly" or "cut to" no longer split a moment, and words on a
shirt or sign stay written while a shout next to a sign is spoken.

A list of everyday lines checks that nothing is added or switched off.
2026-11-26 22:41:09 -06:00
ausboss 0ba8b5664b Merge pull request #418 from ausboss/feat/strength-curve
Add Strength Curve: change a LoRA's or a reference's strength over the run
2026-11-26 21:57:25 -06:00
ausboss 9136fe88d3 Merge remote-tracking branch 'origin/main' into HEAD
# Conflicts:
#	CHANGELOG.md
#	js/shared/i18n_zh.mjs
#	js/widget_cards/index.js
#	locales/zh/nodeDefs.json
2026-11-26 21:54:32 -06:00
ausboss 9cd87d4778 Merge pull request #419 from ausboss/feat/film-grain-cut-out-keep-detail
Add Film Grain, Cut Out and Keep Detail
2026-11-26 21:49:21 -06:00
ausboss f0ef22c01c Merge branch 'main' of https://github.com/ausboss/ComfyUI-AusBoss into feat/strength-curve
# Conflicts:
#	CHANGELOG.md
#	js/shared/i18n_zh.mjs
2026-11-26 21:48:54 -06:00
ausboss 98e4ddf1ff Merge branch 'main' of https://github.com/ausboss/ComfyUI-AusBoss into feat/film-grain-cut-out-keep-detail
# Conflicts:
#	CHANGELOG.md
#	js/shared/i18n_zh.mjs
2026-11-26 21:48:36 -06:00
ausboss c478c86e73 Merge pull request #420 from ausboss/feat/check-layout
Add Check layout and tidy the example workflows
2026-11-26 21:46:28 -06:00
ausboss bbd1841e42 Merge branch 'main' of https://github.com/ausboss/ComfyUI-AusBoss into feat/strength-curve
# Conflicts:
#	CHANGELOG.md
2026-11-26 21:43:15 -06:00
ausboss 50897144bd Merge branch 'main' of https://github.com/ausboss/ComfyUI-AusBoss into feat/check-layout
# Conflicts:
#	CHANGELOG.md
2026-11-26 21:38:27 -06:00
ausboss 84115ca26e Merge branch 'main' of https://github.com/ausboss/ComfyUI-AusBoss into feat/film-grain-cut-out-keep-detail
# Conflicts:
#	CHANGELOG.md
2026-11-26 21:38:25 -06:00
ausboss 699c435955 Merge pull request #423 from ausboss/ausboss/wizardly-tesla-02b1fe
Frame Interpolate: hold cuts between two shots of the same place
2026-11-26 21:36:28 -06:00
ausboss 017788a2d9 Merge branch 'main' of https://github.com/ausboss/ComfyUI-AusBoss into ausboss/wizardly-tesla-02b1fe
# Conflicts:
#	CHANGELOG.md
2026-11-26 21:35:33 -06:00
ausboss 6bfbfcbf29 Merge branch 'main' of https://github.com/ausboss/ComfyUI-AusBoss into feat/film-grain-cut-out-keep-detail
# Conflicts:
#	CHANGELOG.md
2026-11-26 21:35:20 -06:00
ausboss 7a34c917ae Merge branch 'main' of https://github.com/ausboss/ComfyUI-AusBoss into feat/check-layout
# Conflicts:
#	CHANGELOG.md
2026-11-26 21:35:10 -06:00
ausboss e3871d624c Merge pull request #424 from ausboss/feat/latent-ratio-list
Latent Size: pick which ratio chips show
2026-11-26 21:33:33 -06:00
ausboss 538698d2b2 Keep matting at the subject's size
Fix threshold defaulted to 0.75, which marked the blurred rim as
background and shrank the matte to about two thirds of the subject. It
now defaults to 0.01. Matting no longer reads White point as its upper
bound, so levels and the solve stay separate. When the blur is wider
than the subject, it narrows until the subject keeps a solid core,
instead of silently returning the mask unchanged.

Also: plain tooltips and help rows for Detail range and Fix threshold,
Chinese names for both, a changelog entry, and the card tests updated
for the two new inputs.
2026-11-26 20:49:48 -06:00
ausboss be9db84962 Merge main into mask-refine-fix 2026-11-26 20:45:50 -06:00
ausboss ad7bf01cbc Frame Interpolate: hold cuts between two shots of the same place
The cut test only compared the mean frame difference with a fixed
scene_cut_threshold. Two shots of one place in the same light can change
less than fast movement inside a single shot: on a MiniMax H3 rooftop
clip the three cuts scored 0.14 to 0.17, under the 0.35 default and even
under 0.2, while a fast street clip moved up to 0.15 inside one shot. No
fixed number held both, so the node blended two shots for two frames at
each rooftop cut.

A pair now also counts as a cut when it jumps out from the pairs around
it. The change is measured on 64 px thumbnails after every 4 px block has
looked for its best match up to 3 px away, so movement inside a shot
mostly cancels and a new picture does not. A cut is at least 3 times the
median of the 4 pairs on each side and above 0.02; repeated frames are
left out of that median so footage drawn on twos or threes does not read
every step as a cut. On seven H3 clips with 29 cuts, every cut stood out
at least 4.1 times and movement inside a shot at most 1.9 times; all 29
are held and nothing inside a shot is.

scene_cut_threshold keeps its name, place and default, and keeps its old
rule: a plain difference above it is still a cut, so no cut an earlier
version found is lost, and 0 still turns cut finding off. Saved
workflows, whatever value they hold, get the new test with no new input
on the card.
2026-11-26 14:40:47 -06:00
ausboss 254be062ba Latent Size: pick which ratio chips show
The gear menu gets a Ratio chips list: switch ratios on or off, add your
own (21:9 is in the list, off by default), delete them, or reset to the
defaults. A chip keeps the name it was given, so 21:9 no longer reads 7:3.
2026-11-26 11:56:23 -06:00
ausboss 1d4d619649 Merge branch 'main' of https://github.com/ausboss/ComfyUI-AusBoss into feat/film-grain-cut-out-keep-detail
# Conflicts:
#	CHANGELOG.md
2026-11-26 11:55:45 -06:00
ausboss d9a143b98e Merge branch 'main' of https://github.com/ausboss/ComfyUI-AusBoss into feat/check-layout
# Conflicts:
#	CHANGELOG.md
2026-11-26 11:50:28 -06:00
ausboss f6d01458a8 Merge pull request #422 from ausboss/ausboss/sharp-benz-0b488e
Edit Lock: say what is wrong when the VAE and model don't match
2026-11-26 11:48:51 -06:00
ausboss 60dca17f4a Merge pull request #421 from ausboss/fix/wired-megapixels-readout
Crop + Rotate + Pad: show wired values instead of the widget's own
2026-11-26 11:48:36 -06:00
ausboss 94b1ab1def Edit Lock: say what is wrong when the VAE and model don't match
The readout blamed 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.
2026-11-26 11:27:06 -06:00
ausboss f7fe1ceac8 Crop + Rotate + Pad: show wired values in the summary, fields and size readout
A setting wired from another node runs with the wired value, and a wired
value skips the input's range. A Float of 24 wired into Megapixels resized
to 24 MP while the card summary, the MP field and the size readout all
showed the widget's own 16.00 MP, which read as a 16 MP cap.

The summary, the face fields and the size readout now read feather, Align,
the resize switch, Megapixels and Step through the link: a typed number
shows as itself, and a calculated one says it comes from a link. Shared by
the image and both video Crop + Rotate + Pad nodes.
2026-11-26 11:23:11 -06:00
ausboss e21c06591d Read a Load Image file without alpha in Cut Out's live preview
ComfyUI's Load Image hands a PNG's see-through part to its mask, so the
node's picture has none, but the live preview read the file's own alpha and
showed holes the real cut-out does not have. A Load Image file is now read
as colour only; a picture a run kept still carries its alpha.
2026-11-26 06:29:11 -06:00
ausboss 39af045ecd Keep a see-through picture see-through in Cut Out's live preview
Cut Out multiplies its mask by the picture's own alpha, but the picture its
live preview redraws from was saved and read without alpha, so dragging a
value made a see-through source solid until the next run. Cut Out's source
is now saved with its alpha and read as four channels.
2026-11-26 06:21:33 -06:00
ausboss 043025107d Show a new picture's live preview, not the last result, after picking another file
A run's result counted as current while the values matched, so picking
another file in the same Load Image kept showing the old picture's result
without the "not run yet" tag. The result now also has to come from the
same pictures: each Load Image's file, or the link a run reads.
2026-11-26 06:21:33 -06:00
ausboss 32b42832fc Keep a saturated colour's hue in Keep Detail's light-only mode
The small floor of extra light went to every channel evenly, so a pure red
that the original's detail brightened picked up green and blue. With only
light kept, it now goes to each channel in proportion; black still takes it
evenly, and the brightness reached is the same. The live preview follows.
2026-11-26 06:14:57 -06:00
ausboss 7ab5b333a0 Keep Film Grain's grain match when ComfyUI skips the run
ComfyUI does not run a node again for inputs it already ran, so a run
answered from its cache sent no match and the card waited for one. The
node now keeps the match for each pair of pictures in its saved
properties, and watches grain_from's Load Image as well as the picture's.
2026-11-26 04:54:02 -06:00
ausboss 62e5d26e14 Film Grain copies the grain of another picture
An optional grain_from input: with Auto on, the node reads that picture's
grain (how strong, how big, how colourful) from its plainest mid-tone
patches, at the same viewing size, and adds grain like it. Amount, Size and
Color then count from the match, with the real value beside each box; the
live preview uses the match after a run. Roughness stays the card's own.
2026-11-26 02:04:45 -06:00
ausboss 36d5ee3604 Tidy the Film Grain, Cut Out and Keep Detail example layout
Route the shared picture link through reroutes so no wire crosses a node.
2026-11-25 22:35:00 -06:00
ausboss 6ec510f5e0 Live preview on Film Grain, Keep Detail and Cut Out
The picture on the node redraws while a value is dragged, before any run, with a Fit | 100% switch and a not run yet tag. The maths is ported to the browser and checked against the Python nodes on recorded values.
2026-11-25 22:35:00 -06:00
ausboss 95350d1d77 Add Auto to Film Grain
Auto picks the grain for the picture: the size follows the square root of
the megapixels, and the amount starts at 0.25 and goes up by the grain the
picture already has, measured in its flat areas. Amount and Size become
multipliers while Auto is on, with the real value beside each box. Auto and
the plain numbers keep their own values. The browser measures a Load Image's
picture with the same filter as the node, so the note agrees with the result;
a picture from another node is known from the last run.
2026-11-25 22:35:00 -06:00
ausboss f6f9fb4525 Show a Mask by Name cut-out in the Film Grain example picture
The middle panel showed the no-model sky mask, which leaves blotches in the water. It now shows Cut Out with a Mask by Name mask of the pier and the boat, the subject a person would cut out.
2026-11-25 22:35:00 -06:00
ausboss 3399f6c4f2 Add an example workflow for Film Grain, Cut Out and Keep Detail 2026-11-25 22:35:00 -06:00
ausboss e9864c02cb Add Keep Detail: the original's fine detail back on a smoothed edit 2026-11-25 22:35:00 -06:00
ausboss ccce4073a6 Add Cut Out: a see-through cut-out with clean edges from a picture and a mask 2026-11-25 22:35:00 -06:00
ausboss 5389db5ce5 Add Film Grain: photographic grain for pictures and video 2026-11-25 22:35:00 -06:00
ausboss e8be47102e Note the example tidy in the changelog
One line under Unreleased: the examples moved, nothing in them changed.
2026-11-25 22:28:27 -06:00
ausboss ac9817945e Keep the tile subgraph's two reroutes apart in the Upscale + Restore example
The two reroutes in the tile subgraph sat on one spot. They now sit apart so each wire can be followed.
2026-11-25 22:28:17 -06:00
ausboss 1068b3fb75 Tidy the example workflows so Check layout finds nothing
Only node and group positions and sizes, and reroute spots, changed. No node, link or value was touched.
2026-11-25 22:28:17 -06:00
ausboss 1bf9f0bbb8 Frame a Check layout jump left of its panel, so the panel never covers it
The panel sits at the right of the canvas, so the jump frames the picked node in the free space on its left.
2026-11-25 22:28:06 -06:00
ausboss 201cd54508 Add Check layout: a list of what makes a workflow hard to read
Right-click the canvas or use the command palette. It lists overlaps, wires that run backwards or hide behind a node, 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. Includes the Chinese strings, README lines and the changelog entry.
2026-11-25 22:28:03 -06:00
ausboss 4ce99c7254 Let two curve rows share a layer and leave the plain model clean
Two rows that follow the curve can wrap the same layer: two marked rows in
one loader, or two LoRA Loaders with curves in a chain. ComfyUI takes its
bypass wrappers off in the order it put them on, so on a shared layer the
first row's wrapper stayed behind with nothing under it, and the next run
without those LoRAs failed with "'NoneType' object is not callable".

A curve row's wrapper now only passes the layer through once it is taken
off, and every such wrapper left on top is removed, so the order no longer
matters. Each row also gets its own injection key across the chain: a second
loader with a curve used to replace the first loader's rows.

Tests: two marked rows on one layer add up and the plain model samples clean
after, twice over; two chained loaders with their own curves both apply. Both
fail before this change.
2026-11-25 22:18:01 -06:00
ausboss be078c7da3 Run the LoRA strength curve in bypass mode, so it works on every model file
The curve used core hook keyframes, which rewrite the model's weights at
each keyframe. That crashed on fp8 scaled and int8 models, needed a second
copy of a full-size model in memory, and made plain fp8 2.8x slower.

A following row now loads in ComfyUI's bypass mode: the LoRA is added to
each layer's result as the layer runs. A model wrapper sets each row's
strength before every step, read by noise level the way hook keyframes
read it. On Krea 2 this runs on fp8, fp8 scaled, int8 and full size, with
steps 3 to 8% slower and no extra memory. The prompt no longer has to be
encoded with the loader's clip output.

The Strength Curve hover readout also moves to a corner that covers no point.
2026-11-25 20:10:58 -06:00
ausboss 533fede3b9 Mark which LoRA rows follow the strength curve
While a Strength Curve is wired into the loader's curve input, each row
shows a curve mark beside its strength: teal follows the curve, gray stays
steady. The first curve wired into a loader with no marked rows marks them
all, and the row's right-click menu can follow the curve or keep a steady
strength. Rows keep the mark through a save.
2026-11-25 19:45:38 -06:00
ausboss f8ce7c03b7 Draw Strength Curve on the node
The points are drawn on the node: drag a point, double-click to add one,
right-click to take one away, or start from a preset chip. A readout under
the pointer gives the place in the run and the strength there, and the
picked point's place and value are number boxes. Top and Bottom (high and
low) sit on a card under the curve; the hidden points widget stays what the
workflow saves. The face draws the same monotone curve as the node.
2026-11-25 19:45:38 -06:00
ausboss 6e9651613a Declare the curve sockets in the saved-values guard 2026-11-25 19:45:38 -06:00
ausboss e382402bea Add Chinese names for Strength Curve and the curve inputs 2026-11-25 19:45:38 -06:00
ausboss 676c810538 Document Strength Curve and the curve inputs 2026-11-25 19:45:38 -06:00
ausboss 780177f118 Scale the Krea 2 reference per step from a strength curve 2026-11-25 19:45:19 -06:00
ausboss 1f11996210 Let LoRA Loader rows follow a strength curve through core hooks 2026-11-25 19:45:19 -06:00
ausboss b5481a6bbd Add Strength Curve: a drawn curve as a per-step FLOATS schedule 2026-11-25 19:45:19 -06:00
ausboss 07bb4d792b Merge pull request #417 from ausboss/release/v2.28.1
Release 2.28.1
2026-11-25 08:17:59 -06:00
ausboss 34995f9fdb Release 2.28.1 2026-11-25 08:17:05 -06:00
ausboss 8e00fd07fc Merge remote-tracking branch 'origin/fix/card-rows-reach' into release/v2.28.1 2026-11-25 08:15:17 -06:00
kajan988 c47b4bd36e Merge branch 'Mask_refine=otput_node=true' into mask-refine-fix 2026-11-25 07:11:52 +02:00
kajan988 41260de5b3 Mask refine - output node=true 2026-11-25 06:46:42 +02:00
kajan988 e82fdddfb9 Mask Refine: port LayerStyle-grade edge refinement 2026-11-25 05:37:49 +02:00
ausboss 3213c6a4c1 Merge pull request #412 from ausboss/release/v2.28.0
Release 2.28.0
2026-11-24 10:55:21 -06:00
ausboss b6266d1f13 Release 2.28.0 2026-11-24 10:54:25 -06:00
ausboss fbabc5de42 Merge pull request #411 from ausboss/fix/face-fixes-2.28
Photo Camera More fold, Fetch all LoRAs, Color Match method hint
2026-11-24 10:53:56 -06:00
ausboss 6f2a39502e Photo Camera's More fold, Fetch all LoRAs at full height, a hint under Color Match's Method 2026-11-24 10:53:13 -06:00
ausboss c33fc9a968 Merge pull request #410 from ausboss/fix/drop-photo-backdrop
Pause for Shot: take out the photo backdrop before it ships
2026-11-24 10:46:17 -06:00
ausboss eb1be4f36c Card rows: Image Resize shows Fit only where it is read; Photo Camera's More opens
Image Resize showed Fit, and Fill under pad, for every target, but the node
fits every target except Width x height, so those rows did nothing there.
They now show only for Width x height (js/shared/image_resize_rows.mjs).

Photo Camera folded Crop margin and 360 width into a group with no header
row to open it, so they could not be reached. It gets its More header, and
a test fails on any card that folds rows into a group with no header.
2026-11-24 10:44:16 -06:00
ausboss 0a16f4da32 Pause for Shot: take out the photo backdrop before it ships
The photo-on-a-stage backdrop (the background, background_camera and
background_mode inputs, and Size on the viewer's Backdrop tab) projected the
photo onto a floor and walls. Turned shots smeared walls across the floor,
doubled cars and showed a seam where the photo ends, and the final picture
turned those smears into things. No release has these inputs. A workflow
can leave the backdrop grey and let the image model fill in the place. The
hidden `view` input stays.
2026-11-24 10:43:38 -06:00
ausboss 89a8e2d05d Merge pull request #409 from ausboss/feat/photo-camera
Photo Camera, and your own photo behind the model in Pause for Shot
2026-11-24 10:28:18 -06:00
ausboss 0d1f6cf246 Merge main into feat/photo-camera
# Conflicts:
#	CHANGELOG.md
2026-11-24 10:27:23 -06:00
ausboss f9b142bb76 Merge pull request #408 from ausboss/feat/layout-boxes-placement
Layout Boxes placement sentences; Color Match kept method for edits
2026-11-24 10:27:19 -06:00
ausboss d0ce322d7c Merge main into feat/layout-boxes-placement
# Conflicts:
#	CHANGELOG.md
2026-11-24 10:26:25 -06:00
ausboss 9a52cd8a04 Merge pull request #407 from ausboss/fix/civitai-readable-saves
Make saved pictures readable by civitai.com
2026-11-24 10:25:35 -06:00
ausboss 20f5ea273d Merge main into fix/civitai-readable-saves
# Conflicts:
#	CHANGELOG.md
2026-11-24 10:24:26 -06:00
ausboss f4c123cffb Merge pull request #406 from ausboss/feat/lora-fetch-all
LoRA Loader: fetch Civitai info for every LoRA at once
2026-11-24 10:24:17 -06:00
ausboss 148edbd741 Merge main into feat/lora-fetch-all
# Conflicts:
#	CHANGELOG.md
2026-11-24 10:23:23 -06:00
ausboss d31377a939 Merge pull request #405 from ausboss/feat/toolbox-cut-piece
Image Toolbox: cut a piece of your own size
2026-11-24 10:22:19 -06:00
ausboss 3942e7d9dc Pause for Shot: Size sets how far the walls around her are
The photo backdrop's stage is now a dome around the photo's camera with
the floor cut across it. Size on the viewer's Backdrop tab is its radius
in camera heights; empty keeps today's endless wall. From the photo's own
camera every Size gives the photo back unchanged.
2026-11-24 09:31:24 -06:00
ausboss 28936dbe7e Pause for Shot: your photo behind the model, lined up
Wire the photo with the person taken out into `background` and Photo
Camera's camera into `background_camera`: the viewer and `backdrop` show
that photo on a simple stage (a floor at the model's lowest point,
everything else far away), lined up from the photo's own camera and when
zoomed, with her standing on the photo's floor when the camera turns.
`background_mode` picks photo (the default), 360, or 360 floor; a pick
made while the run waits redraws the viewer at once.

The viewer's 360 settings and Cut now reach a run that goes straight
through in the hidden `view` input, filled by the page as Run is pressed.
They used to be read from the saved workflow, which is not part of what
ComfyUI compares, so a changed Turn handed back the old backdrop from the
cache. A test now keeps every node but the save nodes from reading the
saved workflow.
2026-11-24 08:27:26 -06:00
ausboss f75f7456b0 Color Match: kept method fixes the tone an edit shifted, from the pixels it kept 2026-11-24 08:01:53 -06:00
ausboss 52e1e81838 Cut the front or back off a model in the 3D viewer
Cut front and Cut back on the viewer's Model tab take away part of the
model as the camera sees it, each as a share of the model's depth: Back
hides what should sit behind something in the picture, such as the
inside of a hat behind the head. The viewer clips at two planes that face
the camera and draws both sides while a cut is on, so you see the inside
the way Render Mesh draws it.

Pause for Shot takes an optional mesh and hands it on cut the same way,
from the shot or from the cut saved on the viewer, so the render the
picture is painted from matches the viewer.
2026-11-24 00:48:29 -06:00
ausboss 6c41677b36 Pause for Shot: use the viewer's saved 360 settings when not pausing
A run on 'run through' had no Continue answer to carry the 360's Turn,
Tilt and Shadow, so its backdrop used the 360 unturned. It now reads them
from the viewer as saved in the workflow.
2026-11-24 00:21:47 -06:00
ausboss 33555abf0f Add Photo Camera: line a Pixal3D model up with the photo
Works out the camera a photo was taken with from the photo, the subject's
mask and the lens width (MoGe measures it). Pixal3D gets the crop's field
of view, the 3D viewer gets the photo's own view, and the photo's place on
a 360 canvas follows the camera so the 360 lines up behind the model.
2026-11-24 00:21:47 -06:00
ausboss 6a891d185c Layout Boxes: placement output, the boxes as prompt sentences 2026-11-24 00:17:48 -06:00
ausboss 199a618a94 Tag Civitai uploads with the ComfyUI tool and their technique
The Civitai line now ends with engine: ComfyUI and process: txt2img or
img2img. Civitai keeps lower-case keys from that line as they are, and
reads engine for the post's tool and process for its technique, so a
picture saved with Civitai info gets the ComfyUI tool tag back.
2026-11-23 22:17:01 -06:00
ausboss 62a3fcbacc Drop the json import the EXIF writer no longer uses 2026-11-23 21:20:57 -06:00
ausboss 09bf3e9908 Make saved pictures readable by civitai.com
Civitai flags an upload "Unable to Verify AI Generation" when it finds no
prompt in the file, and it only finds a model by its file hash.

Save Image's WebP (and JPEG XL) wrote the prompt in EXIF Make and the rest
as one JSON object in ImageDescription. Core ComfyUI writes the prompt in
Model and "workflow:<json>" in Make. Civitai looks for "prompt:" in Model,
so our WebP files had no prompt at all for it, and ComfyUI's own canvas
read the workflow entry's key as '{"workflow"' and could not restore the
graph. Both now use core's layout. Save Video's animated webp carries the
same EXIF, as core's animated WebP does.

Save Image also gets an opt-in Civitai choice on its Embed switch (Off |
On | Civitai, new optional civitai_info input, default off). It adds the
A1111-style parameters line Civitai reads first: the prompt and negative
of the nearest sampler upstream of the save, its settings, and AutoV2
hashes of the checkpoint or diffusion model and LoRAs on its model input
(LoRA Loader rows that are off or at 0 are skipped). This covers graphs
Civitai's ComfyUI reader cannot follow: Krea 2 Encode, Qwen Image 2.1's
encoder, prompts inside subgraphs. It is off by default because Civitai
then shows these settings in place of the ComfyUI workflow; the workflow
stays in the file. Hashes reuse the LoRA Loader's cached file SHA256.
2026-11-23 21:17:42 -06:00
ausboss 2e713a4f10 LoRA Loader: fetch Civitai info for every LoRA at once
A stack of 44 LoRAs meant 44 info cards and 44 clicks to get their Civitai
info and pictures. Fetch all, in the info card beside the one-LoRA button
and in the gear menu, runs that same lookup for each LoRA in the stack
that has no Civitai info yet: one file at a time, 1.5 s apart, through the
same browser-side request to civitai.com and the same server routes, so
no new address, no server request and no new write. LoRAs that already
have info are skipped, so a second run only fetches the rest.

The node's footer shows "Civitai 12 / 44 · Stop" while it runs; a click
stops it after the file being fetched. A 429 waits 20 s and retries that
file once, a second one stops the run; an unreachable civitai.com, or
three failures in a row, stop it too. One message at the end counts what
was found, not on Civitai, failed and already had info, instead of a
toast per picture. The picture setting is read per file and a picture
already beside a LoRA is never replaced.

The queue lives in js/shared/civitai_lookup.mjs as runCivitaiQueue, with
tests for skips, repeats, stop, a single failure, three in a row, an
unreachable site and both 429 cases.
2026-11-23 21:07:35 -06:00
ausboss 0b84c467c7 Image Toolbox: cut a piece of your own size
A new job, cut a piece, cuts one piece of a set width and height at a
picked position (a corner, an edge or the centre), moved right or down
by an offset. A new second output, rest, gives back what is left: the
strip beside a piece that takes a whole side, else the picture with the
hole filled with its backdrop colour. Width or height 0 takes the full
side, so one node splits a picture into two parts of different sizes.

Inputs and the output are appended as optional; the card shows the new
rows only for the new job.
2026-11-23 21:03:56 -06:00
ausboss 2b5d5de853 Merge main into feat/load-audio-clean-up
Main moved Load Audio to Start, Duration and Ends at. Clean up stays the
last input, after max_seconds. The card keeps main's layout (Duration
hidden, it lives in the panel) with the Clean up row and its resetUnknown
added. The help page and description use the new box names, and the
changelog entry moves to the current Unreleased section.
2026-11-17 17:29:41 +00:00
ausboss 1276d95708 Load Audio: Clean up switch for voice recordings
- New optional clean_up input (off by default, so saved workflows run
  as before). On, the sound that comes out is one channel, with rumble
  and mains hum under 80 Hz taken out, hiss turned down by up to 12 dB
  from a noise print of the quietest moments, the quiet start and end
  cut (0.1 s kept before the first sound, 0.2 s after the last), and the
  volume set to -18 LUFS with a look-ahead limiter that keeps peaks under
  -1 dBFS.
- It runs after the start/end/max trim, so seconds is the length of the
  sound handed on.
- Torch only, at the file's own sample rate. No new dependency.
- The card gets a Clean up off | on row; older saves, which hand the new
  input the upload button's empty value, open with it off.
2026-11-12 22:17:32 -06:00
201 changed files with 20510 additions and 778 deletions
+5
View File
@@ -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() }}
+302
View File
@@ -2,6 +2,308 @@
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
pad, now show only for a Width × height target. The other targets take
their shape from the picture and always fit it, so those rows did
nothing there.
- **Photo Camera 🆎's More fold opens.** Crop margin and 360 width sat in
a fold with no header, so nothing could open them. The card now has a
More row that shows them.
## 2.28.0 - 2026-11-24
- **New node: Photo Camera 🆎.** It works out the camera your photo was
taken with, so a 3D model of the person lines up with the photo. Wire in
the photo, the person's mask and the photo's lens width (MoGe measures
it). It hands Pixal3D the crop's lens, the 3D viewer your photo's own
view, and where the photo goes on a 360 canvas so the 360 lines up
behind the model.
- **The 3D viewer can cut the front or back off a model.** Cut front and
Cut back on the 360 strip's Model tab take away part of the model as the
camera sees it, such as the inside of a hat that should sit behind the
head. Pause for Shot 🆎 gets an optional `mesh` input and output that cut
the run's model the same way, so the shot matches the viewer.
- **Pause for Shot 🆎 keeps the viewer's 360 settings on runs that don't
pause.** With Pause on *run through*, the backdrop now uses the Turn,
Tilt, Shadow and the rest saved on the viewer, as a paused run does.
Before, such a run used the 360 unturned.
- **Layout Boxes 🆎 says the boxes as sentences for any prompt.** A new
`placement` output writes each box as a plain sentence: what goes there
and where, such as `The words "FRESH" in bold black letters, placed top
left, from 6% to 52% across and 6% to 25% down.` Add it to the prompt of
a model that has no box input, and the things land where you drew them.
- **Color Match 🆎 can fix an edit that looks pasted on.** A new method,
`kept`, takes the picture from before the edit as reference. It learns how
the model shifted the parts it was meant to keep (darker, more contrast,
more colour) and undoes that, so a new word or object sits in the same
tone as the rest. New things keep their own colours.
- **Save Image 🆎 can write Civitai info.** Pick **Civitai** in the Embed
switch (Off | On | Civitai) and a saved picture also carries its prompt,
settings and the fingerprints of its model and LoRAs in the form
civitai.com reads first.
An upload then shows its prompt, lists its resources and gets the ComfyUI
tool and txt2img or img2img technique tags, including for
Krea 2, Qwen Image 2.1 and prompts inside subgraphs, where Civitai found no
prompt and flagged the upload "Unable to Verify AI Generation". It is off
by default, because Civitai then shows those settings in place of the
ComfyUI workflow; the workflow stays in the file and still drags back into
ComfyUI. The first save with a new model takes a moment while its file is
fingerprinted.
- **WebP pictures from Save Image 🆎 and Save Video 🆎 carry the workflow the
way ComfyUI's own WebP does.** ComfyUI could not read the workflow back
out of Save Image's WebP files, and civitai.com did not see them as
ComfyUI pictures at all. They now use core ComfyUI's layout, so a WebP
drags back into ComfyUI with its full graph and Civitai reads its prompt.
Save Video's animated `webp` now embeds the workflow too, as core's
animated WebP does; its Embed workflow row shows for `webp`.
- **LoRA Loader 🆎 can fetch Civitai info for every LoRA at once.** A new
**Fetch all LoRAs** button in a LoRA's info card (also in the gear menu) looks
up each LoRA in the stack that has no Civitai info yet, one at a time
with a short pause, and saves its info and picture the same way the
one-LoRA button does. The bottom of the node shows how far it is
(`Civitai 12 / 44 · Stop`); click it to stop. It follows the Civitai
picture setting, never replaces a picture, and slows down or stops when
Civitai asks it to.
- **Image Toolbox can cut a piece of your own size.** Pick the new job
**cut a piece**, set the width and height in pixels, pick where it sits
(a corner, an edge or the centre) and move it right or down from there.
The piece comes out of the first output, and the rest of the picture out
of a new second output, `rest`. A piece as tall as the picture, against
its left or right edge, leaves the strip beside it, so one node splits a
picture into two parts of different sizes. Width or height 0 takes the
picture's full width or height.
## 2.27.0 - 2026-11-23
- **Video Crop + Rotate + Pad → Clip 🆎 can put a clip window in an App-mode
+31 -3
View File
@@ -138,12 +138,24 @@ Reads a picture's `width`, `height`, `longest_edge`, `shortest_edge` and batch `
### Image Toolbox
Small picture jobs in one node, picked from a list. **split sheet at gaps** cuts a row of pictures, such as a character sheet's views, into separate pictures, cutting at the gaps between them so no piece gets part of its neighbour.
Small picture jobs in one node, picked from a list. **split sheet at gaps** cuts a row of pictures, such as a character sheet's views, into separate pictures, cutting at the gaps between them so no piece gets part of its neighbour. **cut a piece** cuts out one piece of the width and height you set, at the place you pick, and gives back the rest of the picture too.
### Color Match
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,12 +357,20 @@ 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
Stops a run right after a **Preview 3D (Advanced)** viewer, so you can frame your shot on the model that run just made. Turn the camera, zoom, move the model, then press **Continue**: the run goes on with the shot exactly as the viewer shows it, and nothing before the pause runs again. **Stop** ends the run there. Wire a 360 picture into `panorama` and it shows behind the model while you frame, and `backdrop` hands on the part of it the camera sees, with an optional floor shadow. Set **Pause** to *run through* for runs nobody is watching.
### Photo Camera
Works out the camera your photo was taken with, so a 3D model of the person lines up with the photo. Made for **Pixal3D**, the TRELLIS 2 model that builds the model lined up with the photo. Wire in the photo, the person's mask and the photo's lens width (**Get FoV from MoGe** measures it). It hands Pixal3D the crop's lens, the 3D viewer your photo's own view (so the viewer opens where the photo was taken), and where the photo goes on a 360 canvas so the 360 lines up behind the model.
### Extras in ComfyUI's 3D viewers
The pack also adds to ComfyUI's own 3D viewers, with no new node:
@@ -354,7 +378,7 @@ The pack also adds to ComfyUI's own 3D viewers, with no new node:
- **Shape chips** above the width and height of Preview 3D (Advanced) and Save 3D (Advanced): pick a shape and the frame follows.
- **Blender keys** with the mouse over a viewer: G move, R rotate, S scale, X / Y / Z to lock an axis, a typed number for an exact amount, the number keys for front, side and top views, and Home to frame the model.
- **Viewport tools** in the top-right corner: drag the axis gizmo to orbit, the magnifier to zoom, the hand to pan, and a grid switch.
- **A 360 strip** (press N, or the small 360 tab): spin and tip the model, turn, tilt and roll the 360 background, its brightness and blur, the light and the model's colours. The settings save with the workflow.
- **A 360 strip** (press N, or the small 360 tab): spin and tip the model, cut its front or back away, turn, tilt and roll the 360 background, its brightness and blur, the light and the model's colours. The settings save with the workflow.
## Workflow utilities
@@ -376,6 +400,8 @@ Drag to draw a box, drag it to move it and its handles to size it; under the can
The `mask` output is white inside every box: load a picture, draw a box over the words on a sign, and an inpaint chain can write new words there while the rest of the picture stays as it was. For words at a slant, drag the round handle over a box to turn it: the mask turns with it, and a turned text box tells the model its slant.
For a model that reads only a prompt and has no box input, the `placement` output says the boxes as plain sentences, what goes in each box and where, to add to your prompt.
![Layout Boxes over a photo of a woman in front of a neon ramen sign: a text box is drawn over the sign, AUSBOSS and red neon letters are typed in, and MOSS-Image's result wipes in with the sign reading AUSBOSS.](assets/readme/layout-boxes.gif)
### Seed
@@ -489,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.
@@ -503,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.
+5
View File
@@ -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",
@@ -46,6 +49,7 @@ NODE_MODULES = [
"node_mask_by_touch",
"node_math",
"node_pause_shot",
"node_photo_camera",
"node_prompt_variations",
"node_realign_to_source",
"node_refine_mask",
@@ -57,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",
+3 -3
View File
@@ -1,9 +1,9 @@
<svg xmlns="http://www.w3.org/2000/svg" width="105" height="20" role="img" aria-label="release: v2.27.0">
<title>release: v2.27.0</title>
<svg xmlns="http://www.w3.org/2000/svg" width="105" height="20" role="img" aria-label="release: v2.30.0">
<title>release: v2.30.0</title>
<path fill="#555" d="M0 0h48v20H0z"/>
<path fill="#00b4aa" d="M48 0h57v20H48z"/>
<g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" font-size="11">
<text x="24" y="14">release</text>
<text x="76.5" y="14">v2.27.0</text>
<text x="76.5" y="14">v2.30.0</text>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 425 B

After

Width:  |  Height:  |  Size: 425 B

+1
View File
@@ -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
}
+30 -1
View File
@@ -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
}
+58 -1
View File
@@ -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
}
+10 -1
View File
@@ -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);
+16 -3
View File
@@ -2,8 +2,9 @@
Makes one picture's colors match another's. Use it when an inpainted or
stitched area comes back a little too warm, cool, dark or bright next to the
original. Four methods go from a gentle fix to an exact match, and a
first-frame mode matches every frame of a video to its first, which can
original. Four methods go from a gentle fix to an exact match. A fifth,
**kept**, is for edits whose new part looks too crisp and colourful next to
the rest of the picture. A first-frame mode matches every frame of a video to its first, which can
reduce color drift between frames.
## Controls
@@ -15,7 +16,7 @@ reduce color drift between frames.
inpaint, feed the original image here. A single reference broadcasts
across a batch; a matched batch pairs frame to frame. Required unless
**Reference** (`reference_mode`) is **first frame**.
- **Method** (`method`): How the colors move.
- **Method** (`method`): How the colors move. A line under it says what the picked one does.
- **lab** — per-channel mean/std shift in LAB. Perceptual and the safe
default: corrects overall casts and contrast without shifting
individual hues around.
@@ -24,6 +25,13 @@ reduce color drift between frames.
not just shifted.
- **hist** (`histogram`) — matches each channel's distribution exactly.
The strongest and least subtle.
- **kept** — for an edit, with the picture from before the edit as
**reference**. Edit models often hand back the parts they were asked
to keep a little darker, with more contrast and colour, so a new sign or
word looks pasted on. This method learns that shift from the parts the
model kept and undoes it everywhere. New things keep their own colours:
green apples that replaced oranges stay green. The reference must be the
same size as the image.
- **mask** (optional): Restricts the match to the white area — both the
statistics measured on the image and where the correction lands. Black
pixels pass through **bit-identical**. Reference statistics always come
@@ -43,6 +51,11 @@ reduce color drift between frames.
## Notes
- For an edit in a box, put **kept** between the model and **Stitch Inpaint
🆎**: the model's crop into **image**, Crop For Inpaint's crop into
**reference**, its mask into **mask**. The fix is learned and applied
inside the box only.
- The node takes a mask but outputs none on purpose: the mask only scopes
the fix and passes through your graph unchanged — wire your original
mask onward.
+96
View File
@@ -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.
+171
View File
@@ -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.
+44 -8
View File
@@ -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.
+82 -11
View File
@@ -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
+32
View File
@@ -28,6 +28,37 @@ own file.
A batch of sheets is cut sheet by sheet: the first sheet's pieces, then the
next sheet's.
### cut a piece
Cuts one piece out of the picture, at the size and place you set. Use it when
the parts you need are not the same size, or when you know exactly where a
part is.
- **Width** and **Height** (`width`, `height`): the piece's size in pixels.
0 takes the picture's full width or height.
- **Position** (`position`): where the piece sits, from **top left** to
**bottom right**. **center** puts it in the middle.
- **Move right** and **Move down** (`move_right`, `move_down`): move the
piece from that position by this many pixels. Below 0 moves it left or up.
The piece never leaves the picture. A size larger than the picture is cut to
the picture's size, and a move that would push the piece past an edge stops
at that edge.
The piece comes out of **images**. The second output, **rest**, is what is
left of the picture:
- When the piece is as tall as the picture and sits against its left or
right edge, **rest** is the strip beside it. The same goes for a piece as
wide as the picture at the top or bottom. So to split a picture into two
parts of different sizes, set the first part's width, Height 0, and
Position **left**: **images** is the first part and **rest** the second.
- Any other piece leaves a hole, and **rest** is the whole picture with the
hole filled with the picture's backdrop colour.
A batch is cut at the same place in every picture. Other jobs pass the
picture through **rest** unchanged.
## Technical details
- The backdrop colour is the median colour of the picture's border.
@@ -39,6 +70,7 @@ next sheet's.
- When two pictures overlap on the sheet, no column is clean. The cut then
goes where the least of them is lost, and a small part of one can remain
in the other's piece.
- cut a piece fills its hole with the same backdrop colour.
- Pieces set to 1 returns the picture unchanged.
- Pieces higher than the picture's width in pixels gives one piece per
pixel column, so fewer pieces than asked for.
+99
View File
@@ -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.
+25
View File
@@ -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.
+36 -1
View File
@@ -60,6 +60,26 @@ of 6 and the woman 4 of 6, and the room stayed as it was; with empty boxes,
2 of 12. Keep `preview` out of H3
Image's pictures too, or the boxes' lines can stay in the picture.
## Words for a prompt
Some models make a picture from a prompt alone and have no input for boxes.
The `placement` output says your boxes as plain sentences: what goes in each
box and where it is in the picture. Add it to your prompt, for example with
ComfyUI's Concatenate Text node, and the model puts each thing where you drew
it.
For a text box with the word FRESH in the top left and an orange on the right,
it gives:
> The words "FRESH" in huge bold black sans-serif letters, placed top left,
> from 6% to 52% across and 6% to 25% down. One ripe orange with a green
> leaf, placed middle right, from 52% to 94% across and 35% to 85% down.
Write the **Description** of each box the way you would in a prompt. Tried on
SenseNova U1.6, which has no box input: these sentences put all the boxes in
place on two seeds of two, where `elements` as text put the words in the wrong
places.
## Change the words in a picture
The `mask` output is white inside every box. Use it to change only one part
@@ -184,11 +204,12 @@ removes it. The first color also colors the box on the canvas.
| `elements` | The boxes as prompt elements. Wire it to MOSS-Image Layout Prompt. A turned box gives the straight box around it, and a turned text box says its slant in its description. |
| `mask` | White inside every box, black elsewhere, to change only those places of a picture. A turned box is white inside its turned shape only. |
| `h3_prompt` | The boxes as a prompt for MiniMax H3 Image, in words: where each thing goes and how big it is. Name each person's picture and what they do in the box's description. See **Place people with MiniMax H3 Image**. |
| `placement` | The boxes as sentences for a prompt: what goes in each box and where, as parts of the picture. Add it to your prompt for a model that has no box input. See **Words for a prompt**. |
## In place of Create Bounding Boxes
Layout Boxes has the same inputs and the same outputs in the same order (and
`mask` and `h3_prompt` after them), so the wires move straight over. For the same boxes it
`mask`, `h3_prompt` and `placement` after them), so the wires move straight over. For the same boxes it
gives the same `bboxes` and `elements`, and MOSS-Image Layout Prompt makes the
same prompt from them.
@@ -257,5 +278,19 @@ run once: they fill the canvas. Then remove the old node.
overlap (the later box is in front). Text boxes are placed by the frame
only. A turned box is placed by the straight box around it. A text box with
no text and no description is left out. No boxes give an empty text.
- `placement` has one sentence per box, in box order, joined by spaces. A
text box with words gives `The words "TEXT" in DESCRIPTION, placed WHERE.`
(`The words "TEXT", placed WHERE.` without a description); any other box
gives its description, first letter in upper case, then `, placed WHERE.`
A box with no words and no description is left out. The description is
the one `elements` carries, so a turned text box says its slant. WHERE is
a rough place and then the box's edges in whole percents of the canvas,
cut to it: `top left, from 6% to 52% across and 6% to 25% down`. The box
is "top" when its bottom edge is above 40%, "bottom" when its top edge is
below 60%, else "middle"; "left" when its right edge is left of 55%,
"right" when its left edge is right of 45%, else "center"; and the middle
of both is said as "center" alone. A turned box is placed by the straight
box around it. A box with colors gets ` Colors: #FF3399, #00AABB.` after
its sentence. No boxes give an empty text.
- The background is saved, shrunk, in ComfyUI's temp folder for the node's
face. Nothing else is written.
+25
View File
@@ -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.
+52 -1
View File
@@ -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
@@ -347,6 +381,16 @@ show it right away. Gear menu → **Civitai picture** picks which pictures:
takes the first picture whatever its rating, and **off** saves none. It never
replaces a picture you already have.
**All of them at once:** click **Fetch all LoRAs** beside that button (or gear
menu → **Civitai info for every LoRA**). It looks up every LoRA in the stack that
has no Civitai info yet, one after another with a short pause, so Civitai
is not asked too fast. The bottom of the node shows how far it is
(`Civitai 12 / 44 · Stop`); click it to stop after the LoRA being fetched.
A message at the end says how many were found, how many Civitai does not
know, and how many already had their info. LoRAs with info are skipped, so
running it again only fetches the new ones. It follows the same
**Civitai picture** setting and never replaces a picture.
## Trigger words
The info card gathers words from three places: the LoRA file's own metadata,
@@ -367,10 +411,17 @@ switched on for the old one.
(see "Get the pictures from Civitai" above). After that the button reads **Refresh Civitai
info** and the card gets a **View on Civitai** link. A LoRA Civitai does
not know (unpublished or hidden) reads **Not found on Civitai**. Gear
menu → **Civitai lookup button** removes the button. When a lookup fails,
menu → **Civitai lookup button** removes the button, and **Fetch all LoRAs**
with it. When a lookup fails,
a message says why. If it always says it could not reach civitai.com,
check whether ComfyUI was started with `--disable-api-nodes`: that setting
stops the browser from reaching any other site, Civitai included.
- **Fetch all LoRAs** runs that same lookup for each LoRA in the stack that has no
Civitai info yet, one at a time, about one and a half seconds apart. If
Civitai answers "too many requests", it waits 20 seconds and tries that
LoRA once more; a second time, it stops and says so. It also stops when
civitai.com cannot be reached, or after three failures in a row. Only one
Fetch all LoRAs runs at a time on the page.
- **Suggested strength**: a lowest and a highest value at the bottom of the
card (leave one empty for "any"). It is only a reminder: a row set outside
it shows its number in orange, and the tooltip gives the range. Saved per
+38
View File
@@ -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
+26 -1
View File
@@ -28,11 +28,24 @@ Take the 360 out of the viewer while the run waits, and `backdrop` comes out
plain grey, the same as with no 360 wired in. What you see in the viewer is
what you get.
## Cut the front or back off the model
**Cut front** and **Cut back** on the viewer's Model tab take away part of
the model as the camera sees it: Back the far side, Front the near side, each
as a share of the model's depth. Use Back to hide what should sit behind
something in the picture, such as the inside of a hat behind the head. The
viewer shows the cut as you drag.
For the shot to be cut too, wire the model's mesh into `mesh` and take `mesh`
from this node to Render Mesh. A run that goes straight through uses the cut
saved on the viewer.
## Settings
- **Pause**: *wait for me* stops every run here. *run through* lets runs go
straight on with the camera as it was when you pressed Run, for runs nobody
is watching.
is watching. The viewer's 360 settings and Cut go along as they were then
too, and changing one makes the next run redo the shot.
## Technical details
@@ -41,6 +54,12 @@ what you get.
Run a second time.
- Continue sends the viewer's camera, the model's turn and the size as
numbers to the pack's own route. Only a node that is waiting accepts it.
- A run that goes straight through takes the viewer's 360 settings and Cut
from the hidden `view` input, which the page fills from the viewer as Run
is pressed. ComfyUI only runs a node again when one of its inputs changes,
so they ride in an input rather than in the saved workflow. A prompt sent
without the page can fill `view` with the same JSON (`{"sky": {...},
"cut": {...}}`) or leave it empty for the defaults.
- Cancel in ComfyUI's queue ends a pause too. A page reloaded during a pause
shows the Continue bar again.
- Every open page gets the model to frame, not only the one that pressed Run:
@@ -51,3 +70,9 @@ what you get.
tenth of the model. Continue sends that patch with
the camera, and the backdrop is darkened along the same rays Render Mesh
casts, so the shadow lands where the model's feet are drawn.
- The cut planes face the camera. The model's depth is how far the box around
its own points reaches along the view, measured the same way in the viewer
and on the run's mesh. The viewer cuts at the exact plane; the mesh keeps
the triangles whose middle lies between the planes, so the edges agree to
within a triangle. While a cut is on, the viewer draws both sides of the
model, so through the cut you see its inside, the way Render Mesh draws it.
+54
View File
@@ -0,0 +1,54 @@
# Photo Camera 🆎
Works out the camera your photo was taken with, so a 3D model of the person
lines up with the photo. With it, the 3D viewer opens on your photo's own
view: same height, same lens, the person where they stand in the photo. Move
the camera from there and the shot starts from something real instead of a
guess.
It is made for **Pixal3D**, the TRELLIS 2 model in ComfyUI that builds the
model lined up with the photo.
## How to wire it
- `image`: your photo, the one **Crop to Mask** cuts the person from.
- `mask`: the person's mask, the same one Crop to Mask uses.
- `fov`: how wide the photo is, in degrees. Wire **Get FoV from MoGe**
(horizontal, degrees) here, run on the same photo. Without MoGe, 55 suits
most phone photos.
Then:
- `crop_fov` goes into **Pixal3D Conditioning**'s `fov`.
- `camera_info` goes into the 3D viewer's `camera_info`
(**Preview 3D (Advanced)**). The viewer opens on the photo's view.
- `strip_width`, `strip_x` and `strip_y` say where the photo goes on the 360
canvas: its width (into an Image Scale) and its left and top edges (into
the Image Composite that lays it on the canvas). The 360 then lines up
with the camera. Turn the 360 by 90 on the viewer's Angle tab so its middle
sits behind the model.
## Settings
- **Lens**: the photo's field of view across, in degrees.
- **Crop margin** (under **More**): the margin Crop to Mask adds around the person.
Keep it the same as Crop to Mask's `pad_factor`.
- **360 width** (under **More**): the width of the 360 canvas.
## Technical details
- Pixal3D builds from a square crop around the person and the crop's field of
view. Its model comes out with +Y up, and with the crop's camera on +Z
looking at the middle from 0.5 / tan(crop_fov / 2) away.
- The whole photo was taken from the same point. Its centre is off the crop's
middle, so the photo's camera is the crop's camera turned towards the
photo's centre, with no roll. Render Mesh and the viewer can show a turn
but not a shifted sensor, which is what a crop really is. A person near the
middle lands to the pixel. A fifth of the frame off centre, the model's far
edges move by up to 3% of the frame's width; up in a corner with a wide
lens, up to 8%.
- The crop box is the one Crop to Mask cuts: the node asks ComfyUI's own crop
helper for it, and measures it the same way itself on a ComfyUI without
that helper.
- The photo is laid on the 360 canvas flat, at its own width in degrees, with
its centre where the camera's axis meets the canvas.
+16 -6
View File
@@ -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`.
+2 -1
View File
@@ -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
+47 -1
View File
@@ -41,10 +41,18 @@ file's name. A caption on the `caption_text` input writes the paired `.txt`.
workflow in EXIF. **JXL** (`jxl lossless`, lossless JPEG XL) is the most
compact; it needs the optional `pillow-jxl-plugin` in ComfyUI's python
(also the pack's `jxl` extra) and few browsers preview it.
- **Embed workflow** (`save_metadata`): **On** stores the prompt and
- **Embed** (`save_metadata`, `civitai_info`): **On** stores the prompt and
workflow in the file (PNG text chunks, EXIF in webp and jxl) so it drags
back into ComfyUI; **Off** writes a clean file for sharing or datasets.
`--disable-metadata` on the server wins.
- **Civitai** (the Embed switch's third choice, `civitai_info` on): stores
the workflow and also the prompt, the sampler settings and the
fingerprints of the model and LoRAs in the form civitai.com reads, so an
upload shows its prompt and lists its resources. Not the default: Civitai
then shows these settings instead of the ComfyUI workflow, though the
workflow stays in the file and still drags back into ComfyUI. The first save with a new model
takes a moment while its file is fingerprinted; after that it is
remembered. See "Uploading to Civitai" below.
- **Preview** (`preview`): the small switch under the card shows the saved
image on the node. Off, the picture's box goes away and the node is
shorter; on again, the node returns to its height with the last saved
@@ -115,6 +123,44 @@ be, apart from the size, which only a run knows.
and is not read for tokens.
- Other text between percent signs stays as typed.
## Uploading to Civitai
civitai.com reads a ComfyUI picture's prompt from the embedded graph, but
only from nodes it knows. A prompt typed into Krea 2 Encode 🆎, core's Qwen
Image 2.1 encoder or a node inside a subgraph reads as no prompt, and the
upload is flagged "Unable to Verify AI Generation". Civitai also finds a
picture's models only by their file fingerprints, which a ComfyUI graph does
not hold, so a plain ComfyUI picture always says no resources were found.
Pick **Civitai** in the Embed switch before saving pictures you mean to
upload.
### Technical details
- The line is the one A1111 writes (`parameters` text in PNG, EXIF
UserComment in WebP and JPEG XL): prompt, `Negative prompt:`, then
`Steps`, `Sampler`, `Schedule type`, `CFG scale`, `Seed`, `Size`,
`Model hash`, `Model`, `Lora hashes` and a `Hashes` JSON block. Civitai
reads it before the ComfyUI graph.
- It ends with `engine: ComfyUI`, which tags the post with the ComfyUI tool,
and `process: txt2img` or `img2img`, which picks its technique. A sampler
that starts from an encoded picture, an inpaint node, or a denoise under 1
counts as img2img.
- Civitai does not keep the ComfyUI graph from a picture that carries this
line, so its page shows no workflow to copy. The workflow is still in the
file for anyone who downloads it.
- It is built from the run's own graph, walking up from this node to the
nearest sampler (KSampler, KSamplerAdvanced, SamplerCustom and
SamplerCustomAdvanced), its prompt encoder, and the checkpoint or
diffusion model and LoRAs on its model input. LoRA Loader 🆎 rows that are
off or at strength 0 are left out. A graph with no sampler gets no line.
- Fingerprints are AutoV2 hashes (the first ten hex digits of the file's
SHA256), cached in `user/ausboss/` by file size and date. Text encoders and
VAEs are not listed; Civitai does not credit a picture to them.
- A prompt made while the graph runs (Prompt Variations 🆎) is written as
the text typed into its node.
- Videos cannot carry it: Civitai reads only the `prompt` and `workflow`
tags of an mp4 or webm.
## Outputs
- **file_path**: absolute path of the first file saved this run (empty when
+4 -3
View File
@@ -78,13 +78,14 @@ a software format to use instead rather than failing with a driver stack
trace.
`gif` and `webp` have no streaming encoder, so every frame is held in memory
before the first byte is written — keep those to short clips. Neither carries
metadata, so an embedded workflow is not available for them.
before the first byte is written — keep those to short clips. `webp` carries
the embedded workflow the same way ComfyUI's own animated WebP does; `gif` has
no place for it.
The node's face follows the table: widgets the chosen format ignores are
hidden rather than left to look meaningful. The CRF field leaves the
**FPS · CRF** row for `mov prores`, `mkv ffv1` and `gif` (their rows read
*ignored* above), and the **Embed workflow** row disappears for `gif` and `webp`,
*ignored* above), and the **Embed workflow** row disappears for `gif`,
which cannot carry it. Hidden is not removed:
the widget keeps its position and its value, saved workflows store and restore
it exactly as before, and switching the format back brings it back with the
+61
View File
@@ -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.
+5
View File
@@ -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`) |
@@ -47,6 +51,7 @@ help panel.
| Do maths on numbers | Math Expression (`AUSBOSS_NODES_MathExpression`) |
| Show text on the node, or the picture while it is made | Show Text (`AUSBOSS_NODES_ShowText`), Step Preview (`AUSBOSS_NODES_StepPreview`) |
| Stop a run after the 3D viewer to frame the shot on the new model, with a 360 behind it | Pause for Shot (`AUSBOSS_NODES_PauseShot`): [node help](../AUSBOSS_NODES_PauseShot.md) |
| Line a 3D model (Pixal3D) up with the photo: the photo's camera for the viewer, the crop's lens, the photo's place on a 360 | Photo Camera (`AUSBOSS_NODES_PhotoCamera`): [node help](../AUSBOSS_NODES_PhotoCamera.md) |
| Free graphics memory between steps | Free Memory (`AUSBOSS_NODES_FreeMemory`) |
| Time the whole run | Run Timer (`AUSBOSS_NODES_RunTimer`) |
| Turn parts of a workflow off and on | Workflow Switches (`AUSBOSS_NODES_WorkflowSwitches`): [its own agent guide](workflow_switches.md) |
+68
View File
@@ -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);
},
});
+177
View File
@@ -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; });
}));
},
});
+25 -1
View File
@@ -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();
+329
View File
@@ -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();
},
});
+183 -19
View File
@@ -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,
@@ -90,8 +92,9 @@ import {
upsertTemplate,
} from "../shared/lora_stack.mjs";
import {
MAX_PICTURE_BYTES, civitaiButtonLabel, civitaiByHashUrl, civitaiFailureText, isCivitaiAddress,
parseCivitaiBody, pickCivitaiPicture, smallPictureUrl,
MAX_PICTURE_BYTES, civitaiButtonLabel, civitaiByHashUrl, civitaiFailureText, civitaiQueueLabel,
civitaiQueueSummary, isCivitaiAddress, parseCivitaiBody, pickCivitaiPicture, runCivitaiQueue,
smallPictureUrl,
} from "../shared/civitai_lookup.mjs";
const NODE_CLASS = "AUSBOSS_NODES_LoraLoader";
@@ -224,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";
@@ -259,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; }
@@ -496,6 +506,10 @@ function installStyles() {
color: inherit; cursor: pointer; padding: 2px 8px; font-size: 11px; }
.ausboss-lora-chip.active { border-color: ${BRAND}; color: ${BRAND}; }
.ausboss-lora-fetch { align-self: flex-start; }
.ausboss-lora-fetchrow { display: flex; gap: 6px; align-items: center; }
.ausboss-lora-fetchrow .ausboss-lora-fetch { align-self: auto; }
.ausboss-lora-fetchrow .ausboss-lora-fetch-all { height: ${ACTIONS_HEIGHT}px; }
.ausboss-lora-actions .ausboss-lora-civitai-run { align-self: center; margin-left: 6px; }
.ausboss-lora-custom { display: flex; gap: 6px; align-items: center; }
.ausboss-lora-custom input { flex: 1 1 auto; min-width: 0; height: ${ACTIONS_HEIGHT}px;
border: 1px solid #3a4047; box-sizing: border-box;
@@ -791,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) {
@@ -871,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) {
@@ -1524,8 +1563,10 @@ function openPicker(state, index, anchor, { keyboard = false } = {}) {
// about that hash, and the server saves the answer beside the LoRA after
// checking it describes the same file. Returns false when Civitai does not
// know the file (unpublished or hidden models answer 404). `picture` is the
// Civitai picture gear option ("off", "PG-13" or "any").
async function lookUpOnCivitai(serverName, picture = "PG-13") {
// Civitai picture gear option ("off", "PG-13" or "any"). Otherwise it returns
// `{ picture }`: "saved", "none" (Civitai has none to save), "failed" or
// "off". `quiet` keeps the picture's own messages back for Fetch all.
async function lookUpOnCivitai(serverName, picture = "PG-13", { quiet = false } = {}) {
const hashed = await (await api.fetchApi(
`/ausboss/lora/hash?name=${encodeURIComponent(serverName)}`
)).json();
@@ -1534,7 +1575,9 @@ async function lookUpOnCivitai(serverName, picture = "PG-13") {
credentials: "omit", redirect: "error", referrerPolicy: "no-referrer", cache: "no-store",
});
if (response.status === 404) return false;
if (!response.ok) throw new Error(`Civitai answered ${response.status}.`);
if (!response.ok) {
throw Object.assign(new Error(`Civitai answered ${response.status}.`), { status: response.status });
}
const info = parseCivitaiBody(await response.text());
const saved = await (await api.fetchApi("/ausboss/lora/civitai", {
method: "POST",
@@ -1542,24 +1585,28 @@ async function lookUpOnCivitai(serverName, picture = "PG-13") {
body: JSON.stringify({ name: serverName, info }),
})).json();
if (!saved.ok) throw new Error(saved.error || "Could not save the Civitai info.");
if (picture !== "off") {
await saveCivitaiPicture(serverName, info, picture === "any").catch((error) =>
loraToast(`Saved the Civitai info, but not its picture: ${civitaiFailureText(error)}`));
if (picture === "off") return { picture: "off" };
try {
if (await saveCivitaiPicture(serverName, info, picture === "any")) return { picture: "saved" };
if (!quiet) {
loraToast(picture === "any"
? "Civitai has no picture of this LoRA to save."
: "Civitai has no picture of this LoRA rated PG-13 or milder.");
}
return { picture: "none" };
} catch (error) {
if (!quiet) loraToast(`Saved the Civitai info, but not its picture: ${civitaiFailureText(error)}`);
return { picture: "failed" };
}
return true;
}
// The LoRA's first picture on Civitai, saved beside it as its preview. The
// browser downloads a 450-pixel copy from Civitai's picture server without
// cookies; the server checks it is a picture and never replaces one.
// Returns false when Civitai has no picture the setting allows.
async function saveCivitaiPicture(serverName, info, anyRating) {
const picture = pickCivitaiPicture(info, anyRating);
if (!picture) {
loraToast(anyRating
? "Civitai has no picture of this LoRA to save."
: "Civitai has no picture of this LoRA rated PG-13 or milder.");
return;
}
if (!picture) return false;
const response = await fetch(smallPictureUrl(picture.url), {
credentials: "omit", referrerPolicy: "no-referrer", cache: "no-store",
});
@@ -1577,6 +1624,76 @@ async function saveCivitaiPicture(serverName, info, anyRating) {
})).json();
if (!saved.ok) throw new Error(saved.error || "Could not save the picture.");
pictureSaved();
return true;
}
// ---------- Fetch all ----------
// The same one-file lookup for every LoRA in the stack that has no Civitai
// info yet, one file at a time (runCivitaiQueue). One run for the whole
// page: Civitai counts requests per browser, not per node.
let civitaiRun = null;
function fetchAllFromCivitai(state) {
if (state.settings?.civitai_lookup === false) return;
if (civitaiRun) {
if (civitaiRun.state !== state) loraToast("Another LoRA Loader is fetching Civitai info. Wait for it, or stop it there.");
return;
}
const names = state.rows.map((row) => row.name).filter(Boolean)
.map((name) => effectiveLoraName(state, name));
const hasPicture = new Map();
const run = { state, done: 0, total: null, stopping: false, wake: null, button: null };
civitaiRun = run;
renderRows(state);
runCivitaiQueue(names, {
needsLookup: async (name) => {
const data = await (await api.fetchApi(`/ausboss/lora/info?name=${encodeURIComponent(name)}`)).json();
if (!data.ok) throw new Error(data.error || "No such LoRA.");
hasPicture.set(name, Boolean(data.info.has_preview));
return !data.info.has_civitai;
},
// The picture setting is read per file, so a change mid-run counts.
lookUp: (name) => lookUpOnCivitai(name,
hasPicture.get(name) ? "off" : (state.settings?.civitai_picture ?? "PG-13"), { quiet: true }),
wait: (ms) => new Promise((resolve) => {
const timer = setTimeout(resolve, ms);
run.wake = () => { clearTimeout(timer); resolve(); };
}),
shouldStop: () => run.stopping,
onProgress: ({ done, total }) => {
run.done = done;
run.total = total;
showCivitaiRun(run);
},
}).then((result) => loraToast(civitaiQueueSummary(result)))
.catch((error) => loraToast(civitaiFailureText(error)))
.finally(() => {
civitaiRun = null;
if (state.panel?.isConnected) renderRows(state);
});
}
// While a run works, its node's footer holds one button: how far it is, and
// a click stops it after the file being fetched.
function civitaiRunButton(run) {
const button = compactAction("", "Fetching Civitai info for every LoRA in this stack "
+ "that has none yet, one at a time. Click to stop after the current one.");
button.classList.add("ausboss-lora-civitai-run");
button.addEventListener("click", () => {
run.stopping = true;
run.wake?.();
showCivitaiRun(run);
});
run.button = button;
showCivitaiRun(run);
return button;
}
function showCivitaiRun(run) {
if (!run.button) return;
run.button.disabled = run.stopping;
run.button.textContent = run.stopping ? "Stopping..." : civitaiQueueLabel(run.done, run.total);
}
// ---------- info card ----------
@@ -1675,7 +1792,17 @@ function openInfo(state, index, anchor) {
loraToast(fetchButton.title);
}
});
card.append(fetchButton);
const fetchAll = compactAction("Fetch all LoRAs",
"Fetch Civitai info for every LoRA in this stack that has none yet, one at a time.");
fetchAll.classList.add("ausboss-lora-fetch-all");
fetchAll.disabled = Boolean(civitaiRun);
fetchAll.addEventListener("click", () => {
closePopup();
fetchAllFromCivitai(state);
});
const fetchRow = el("div", "ausboss-lora-fetchrow");
fetchRow.append(fetchButton, fetchAll);
card.append(fetchRow);
}
const range = el("div", "ausboss-lora-range");
@@ -1918,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)),
@@ -2680,6 +2812,19 @@ function openSettings(state, anchor) {
runImportChain(state);
},
},
...(state.settings?.civitai_lookup === false ? [] : [{
key: "_civitai_all",
label: "Civitai info for every LoRA",
type: "action",
button: "Fetch all LoRAs",
hint: "Look up every LoRA in this stack that has no Civitai info yet, "
+ "one at a time, the same way the info card's button does. The "
+ "bottom of the node shows how far it is; click there to stop.",
onAction: () => {
closeSettingsMenu();
fetchAllFromCivitai(state);
},
}]),
];
// Inside a subgraph the rows can show on the box's face instead; first in
// the menu there, since it is what a loader in a box is usually set up for.
@@ -3035,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");
@@ -3077,6 +3235,7 @@ function renderRows(state) {
add.addEventListener("click", addRowAndPick);
add.title = "Pick one LoRA, or click a folder name to add all its LoRAs.";
actions.append(add);
if (civitaiRun?.state === state) actions.append(civitaiRunButton(civitaiRun));
stack.append(actions);
body.append(stack);
decorateRows(state);
@@ -3354,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;
@@ -3506,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
+13
View File
@@ -16,6 +16,7 @@ import { compactAction, HINT_TYPE } from "../shared/panel_controls.mjs";
import { holdNodeMinWidth, pinVuePanelHeight } from "../shared/panel_layout.mjs";
import { FONT_UI, RADIUS_CONTROL, THEME as T } from "../shared/theme.mjs";
import { bottomButtons } from "../shared/viewer3d_layout.mjs";
import { viewValue } from "../shared/viewer_view.mjs";
const NODE_CLASS = "AUSBOSS_NODES_PauseShot";
const PANEL = "ausboss_pause_shot_panel";
@@ -58,6 +59,9 @@ async function readShot(viewer) {
}
const sky = viewer?.properties?.["AusBoss View"]?.sky;
if (sky && typeof sky === "object") shot.sky = sky;
// The viewer's Cut, so the run's mesh is cut the way the viewer shows it.
const cut = viewer?.properties?.["AusBoss View"]?.cut;
if (cut && typeof cut === "object") shot.cut = cut;
// The 360 taken out of the viewer (its background image removed) leaves
// the backdrop grey, as with no 360 wired in.
const scene = viewerGizmo(viewer)?.__ausbossScene;
@@ -278,6 +282,15 @@ app.registerExtension({
holdNodeMinWidth(widget, MIN_WIDTH);
widget.options.minNodeSize = [MIN_WIDTH, 60];
this.__ausbossPauseShot = panel;
// The viewer's 360 settings and Cut go into the hidden `view` input as
// the prompt is built, so a run that goes straight through runs again
// when one of them changed (js/shared/viewer_view.mjs). The widget
// itself holds nothing, so a saved workflow carries no copy.
const view = this.widgets?.find((item) => item.name === "view");
if (view) {
view.value = "";
view.serializeValue = () => viewValue(viewerOf(this)?.properties?.["AusBoss View"]);
}
});
chainCallback(nodeType.prototype, "onRemoved", function () {
this.__ausbossPauseShot?.clear();
+182 -7
View File
@@ -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);
+25 -13
View File
@@ -33,7 +33,7 @@ const CARD_HEIGHT = 288;
const WRAPPER_INSET = 16;
const HIDDEN = [
"filename_prefix", "format", "save_metadata", "exact_name", "on_existing",
"output_dir", "caption", "name_counter", "name_date", "name_time", "name_size", "name_batch", "autosave",
"output_dir", "caption", "name_counter", "name_date", "name_time", "name_size", "name_batch", "autosave", "civitai_info",
];
const FONT = `-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif`;
const MONO = `ui-monospace,SFMono-Regular,Menlo,Consolas,monospace`;
@@ -64,6 +64,7 @@ function ensureCss() {
.ausboss-save-half{display:flex;align-items:center;gap:6px;flex:1 1 auto;min-width:0}
.ausboss-save-half .ausboss-card-seg{flex:1 1 0;min-width:0}
.ausboss-save-switches{gap:12px}
.ausboss-save-half.embed{flex-grow:1.5}
.ausboss-save-browse{position:fixed;z-index:10000;width:260px;max-height:320px;overflow:auto;padding:4px;border:1px solid #3a4047;border-radius:7px;background:#1c1f23;box-shadow:0 8px 28px rgba(0,0,0,.5);font:12px/1.3 ${FONT};color:#d8ecea}
.ausboss-save-browse-head{padding:5px 8px 6px;border-bottom:1px solid #2c3238;color:#78908e;font:10px/1 ${FONT};letter-spacing:.08em;text-transform:uppercase;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.ausboss-save-browse button{display:block;width:100%;padding:6px 8px;border:none;border-radius:5px;background:transparent;color:inherit;font:inherit;text-align:left;cursor:pointer}
@@ -273,20 +274,31 @@ function buildCard(node) {
}
root.append(seg);
// Embed workflow: a no | yes pill, the pack's boolean.
// Embed: what goes in the file, in one pill. Off is a clean picture; On
// stores the prompt and workflow for drag-back; Civitai stores them too and
// adds the settings line civitai.com reads (save_metadata + civitai_info).
const embedRow = el("div", "ausboss-save-row");
const embedSeg = el("div", "ausboss-card-seg ausboss-card-bool");
embedSeg.setAttribute("role", "radiogroup");
const embedButtons = new Map();
const embedTitle = "Embed stores the prompt and workflow in the image for drag-back. Off writes a clean image for sharing or datasets.";
for (const [on, text] of [[false, PANEL_LABELS.off], [true, PANEL_LABELS.on]]) {
const embedChoices = [
["off", PANEL_LABELS.off, false, false, "Off writes a clean image, with no prompt or workflow inside - for sharing or datasets."],
["on", PANEL_LABELS.on, true, false, "On stores the prompt and workflow in the image, so it drags back into ComfyUI."],
["civitai", "Civitai", true, true, "Civitai stores the workflow and also the prompt, settings and model and LoRA fingerprints the way civitai.com reads them, so an upload lists its prompt and resources."],
];
for (const [key, text, embed, civitai, title] of embedChoices) {
const button = el("button", "", text);
button.type = "button"; button.title = embedTitle;
button.addEventListener("click", () => { if (setValue(node, "save_metadata", on)) notifyAusbossChange(); state.refresh(); });
embedSeg.append(button); embedButtons.set(on, button);
button.type = "button"; button.title = title;
button.addEventListener("click", () => {
const changedEmbed = setValue(node, "save_metadata", embed);
const changedCivitai = setValue(node, "civitai_info", civitai);
if (changedEmbed || changedCivitai) notifyAusbossChange();
state.refresh();
});
embedSeg.append(button); embedButtons.set(key, button);
}
const embedHalf = el("div", "ausboss-save-half");
embedHalf.append(el("span", "ausboss-save-embed-label", PANEL_LABELS.embed), embedSeg);
const embedHalf = el("div", "ausboss-save-half embed");
embedHalf.append(el("span", "ausboss-save-embed-label", "Embed"), embedSeg);
embedRow.classList.add("ausboss-save-switches");
embedRow.append(embedHalf);
root.append(embedRow);
@@ -348,10 +360,10 @@ function buildCard(node) {
chips.classList.toggle("off", !tagsEnabled(values));
for (const [key, chip] of chipButtons) chip.classList.toggle("on", Boolean(values[key]));
for (const [key, button] of formatButtons) button.classList.toggle("on", values.format === key);
const embed = Boolean(values.save_metadata);
for (const [on, button] of embedButtons) {
button.classList.toggle("on", on === embed);
button.setAttribute("aria-checked", String(on === embed));
const embed = !values.save_metadata ? "off" : values.civitai_info ? "civitai" : "on";
for (const [key, button] of embedButtons) {
button.classList.toggle("on", key === embed);
button.setAttribute("aria-checked", String(key === embed));
}
const auto = values.autosave !== false;
for (const [on, button] of autoButtons) {
+12
View File
@@ -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.
+116
View File
@@ -104,3 +104,119 @@ export function isCivitaiAddress(url) {
return false;
}
}
// ---------- fetch all ----------
// One button runs the same one-file lookup for every LoRA in a stack that has
// no Civitai info yet: one file at a time, with a pause between files so
// Civitai is not asked too fast. Nothing here talks to the network itself;
// the caller hands in the lookup.
// The pause between two lookups, and the longer one after Civitai answers
// 429 ("too many requests"). A second 429 ends the run.
export const QUEUE_PAUSE_MS = 1500;
export const SLOW_DOWN_PAUSE_MS = 20000;
// This many failures in a row ends the run: something is wrong for all files.
export const MAX_FAILURES_IN_A_ROW = 3;
// `names`: the stack's LoRA names (repeats and blanks are dropped).
// `needsLookup(name)`: true when the file has no Civitai info yet; an error
// means the file is missing, and it is left out.
// `lookUp(name)`: false when Civitai does not know the file, else
// `{ picture }` ("saved" when a picture was saved). An error with
// `status: 429` means slow down; a TypeError means Civitai cannot be reached.
// `wait(ms)`: a pause; it may end early once `shouldStop()` is true.
// `onProgress({ done, total, name })`: total is null while files are checked.
export async function runCivitaiQueue(names, {
needsLookup, lookUp, wait, shouldStop = () => false, onProgress = () => {},
pauseMs = QUEUE_PAUSE_MS, slowDownMs = SLOW_DOWN_PAUSE_MS,
}) {
const result = {
total: 0, done: 0, found: 0, pictures: 0, notFound: 0, failed: 0,
alreadyHad: 0, missing: 0, stopped: null, error: null,
};
const unique = [...new Set((names ?? []).filter((name) => typeof name === "string" && name))];
const todo = [];
onProgress({ done: 0, total: null, name: null });
for (const name of unique) {
if (shouldStop()) { result.stopped = "you"; return result; }
try {
if (await needsLookup(name)) todo.push(name);
else result.alreadyHad += 1;
} catch {
result.missing += 1;
}
}
result.total = todo.length;
onProgress({ done: 0, total: result.total, name: null });
let failuresInRow = 0;
for (const name of todo) {
if (result.done > 0) await wait(pauseMs);
if (shouldStop()) { result.stopped = "you"; return result; }
let slowedDown = false;
for (;;) {
try {
const answer = await lookUp(name);
if (answer) {
result.found += 1;
if (answer.picture === "saved") result.pictures += 1;
} else {
result.notFound += 1;
}
failuresInRow = 0;
break;
} catch (error) {
if (error?.status === 429 && !slowedDown) {
slowedDown = true;
await wait(slowDownMs);
if (shouldStop()) { result.stopped = "you"; return result; }
continue;
}
result.error = error;
if (error?.status === 429) { result.stopped = "slow down"; return result; }
if (error instanceof TypeError) { result.stopped = "unreachable"; return result; }
result.failed += 1;
failuresInRow += 1;
break;
}
}
result.done += 1;
onProgress({ done: result.done, total: result.total, name });
if (failuresInRow >= MAX_FAILURES_IN_A_ROW) { result.stopped = "failures"; return result; }
}
return result;
}
// The run's button while it works: where it is, and that a click stops it.
export function civitaiQueueLabel(done, total) {
return total == null ? "Civitai: checking · Stop" : `Civitai ${done} / ${total} · Stop`;
}
const plural = (count, word) => `${count} ${word}${count === 1 ? "" : "s"}`;
// What the run did, in one or two plain sentences for the closing message.
export function civitaiQueueSummary(result) {
if (!result.total && !result.stopped) {
if (result.alreadyHad && !result.missing) return "Every LoRA in this stack already has its Civitai info.";
if (!result.alreadyHad && !result.missing) return "This stack has no LoRAs to look up.";
}
const parts = [];
if (result.found) {
parts.push(`found ${plural(result.found, "LoRA")}`
+ (result.pictures ? ` (${plural(result.pictures, "new picture")})` : ""));
}
if (result.notFound) parts.push(`${result.notFound} not on Civitai`);
if (result.failed) parts.push(`${result.failed} failed`);
if (result.alreadyHad) parts.push(`${result.alreadyHad} already had info`);
if (result.missing) parts.push(`${plural(result.missing, "file")} not found on disk`);
let text = parts.length ? `Civitai: ${parts.join(", ")}.` : "Civitai: nothing fetched.";
const left = result.total - result.done;
if (result.stopped === "you") text += ` Stopped with ${left} left.`;
else if (result.stopped === "slow down") {
text += ` Civitai asked us to slow down, so it stopped with ${left} left. Try again in a few minutes.`;
} else if (result.stopped === "unreachable") text += ` ${civitaiFailureText(result.error)}`;
else if (result.failed && !result.stopped) text += ` Last failure: ${civitaiFailureText(result.error)}`;
else if (result.stopped === "failures") {
text += ` Stopped after ${MAX_FAILURES_IN_A_ROW} failures in a row: ${civitaiFailureText(result.error)}`;
}
return text;
}
+110
View File
@@ -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
View File
@@ -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();
+1 -1
View File
@@ -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,
};
}
+117
View File
@@ -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;
}
+233
View File
@@ -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 };
}
+64
View File
@@ -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(" ");
}
+75 -5
View File
@@ -9,6 +9,8 @@
export const ZH = {
// ---- card rows and group headers
"Lens": "镜头视角", "Crop margin": "裁剪边距", "360 width": "360 宽度",
"How wide the photo is, in degrees across. Wire Get FoV from MoGe here.": "照片横向有多宽,单位为度。把 MoGe 的“获取视角”接到这里。",
"Target": "目标", "Size": "尺寸", "Edge": "边缘", "Budget": "像素预算", "Scale": "缩放", "Fit": "适应",
"Fill": "填充", "Multiple": "倍数", "Filter": "滤镜", "Job": "任务", "Pieces": "分块数",
"Lock": "锁定", "Tolerance": "容差", "Feather": "羽化", "Remove tint": "去除偏色", "Strength": "强度",
@@ -19,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": "画布",
@@ -27,11 +30,11 @@ 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": "下",
"Prefix": "文件名前缀", "Format": "格式", "FPS · CRF": "帧率 · CRF", "Ping-pong": "往返播放", "Embed workflow": "嵌入工作流",
"Prefix": "文件名前缀", "Format": "格式", "FPS · CRF": "帧率 · CRF", "Ping-pong": "往返播放", "Embed workflow": "嵌入工作流", "Embed": "嵌入",
"Pictures and settings": "图片与设置", "What H3 gets": "H3 收到的内容", "What happens": "发生了什么",
"Align": "对齐", "Aspect ratio": "画面比例", "Crop, pad & resize": "裁剪、扩边与缩放", "Duration": "时长", "Ends at": "结束于",
"Frames for": "帧数用于", "Start": "起点", "Whole video": "整段视频", "Clip IN": "片段入点", "Clip OUT": "片段出点",
@@ -56,7 +59,7 @@ export const ZH = {
"gray": "灰色", "edge": "边缘", "edge pixel": "边缘像素", "color": "纯色", "pillarbox blur": "两侧虚化", "replicate": "复制边缘",
"source": "原图", "as typed": "照输入", "from the picture": "取自图片", "text": "文字", "object": "物体", "still": "静止", "handheld": "手持",
"shaky": "抖动", "push in": "推近", "pull back": "拉远", "orbit": "环绕", "walking pov": "步行视角", "anime": "动漫", "comic book": "漫画",
"pencil sketch": "铅笔素描", "watercolor": "水彩", "split sheet at gaps": "按空隙拆分拼图", "Pad": "扩边", "Crop": "裁剪",
"pencil sketch": "铅笔素描", "watercolor": "水彩", "split sheet at gaps": "按空隙拆分拼图", "cut a piece": "裁出一块", "Move right": "右移", "Move down": "下移", "Position": "位置", "Pad": "扩边", "Crop": "裁剪",
"Resize": "缩放", "Center": "居中", "Soft": "柔和", "Simple": "简易", "Full prompt": "完整提示词", "Text": "文字", "Fixed": "固定",
"LTX (8n+1)": "LTX (8n+1)", "Wan (4n+1)": "Wan (4n+1)", "Every group": "每个分组", "Numbered groups": "编号分组",
"Titles matching…": "按标题匹配…", "No groups": "没有分组", "All": "全部", "Background": "背景", "Subject": "主体",
@@ -146,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.": "每隔这么多帧保留一帧。输出帧率会随之调整以保持实时播放;时长按保留的帧数计算。",
@@ -175,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.": "“逐行”让每个开关各占一行,各自有关 | 开。“单选”把这些开关合成一个选项条,始终选中其中一个。",
@@ -212,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": "提示词、字幕或共用文字",
@@ -257,6 +263,13 @@ export const ZH = {
"Each line becomes a moment. A blank line between lines is a cut.": "每一行是一个时刻,两行之间的空行表示切换场景。",
"Enable or disable this LoRA": "启用或停用这个 LoRA",
"Fetching...": "获取中…",
"Fetch all LoRAs": "获取全部 LoRA",
"Fetch Civitai info for every LoRA in this stack that has none yet, one at a time.": "逐个为这组中还没有 Civitai 信息的每个 LoRA 获取信息。",
"Fetching Civitai info for every LoRA in this stack that has none yet, one at a time. Click to stop after the current one.": "正在逐个为这组中还没有 Civitai 信息的每个 LoRA 获取信息。点击可在当前这个完成后停止。",
"Civitai info for every LoRA": "为全部 LoRA 获取 Civitai 信息",
"Look up every LoRA in this stack that has no Civitai info yet, one at a time, the same way the info card's button does. The bottom of the node shows how far it is; click there to stop.": "逐个查询这组中还没有 Civitai 信息的每个 LoRA,方式与信息卡里的按钮相同。节点底部会显示进度;点击那里可停止。",
"Stopping...": "正在停止…",
"Civitai: checking · Stop": "Civitai:检查中 · 停止",
"Group name": "分组名称",
"Held": "已锁定",
"Hide file extension": "隐藏文件扩展名",
@@ -297,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": "触发词分隔符",
@@ -315,12 +330,64 @@ 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
// and technical terms with no everyday Chinese form.
export const STAYS_ENGLISH = new Set([
"W", "H", "FPS", "CFG", "LoRA", "VRAM", "Seed", "H3",
"W", "H", "FPS", "CFG", "LoRA", "VRAM", "Seed", "H3", "Civitai",
"lab", "rgb", "mkl", "bicubic", "bilinear", "lanczos", "nearest", "area",
"gif", "webp", "mp4 h264", "mp4 h265", "mp4 h264 nvenc", "mp4 h265 nvenc", "mov prores", "mkv ffv1", "webm vp9", "webm av1",
"big-lama.pt", "loras", "script", "video", "flashvsr_v1.1_fp16.safetensors", "f(a, b, c)", "a + b",
@@ -332,9 +399,12 @@ export const SCRUB_HINT_ZH = "拖动调节,点击输入数字或算式(如 1
// A few strings carry a number or a name; the number stays and the words around it change.
export const PATTERNS = [
[/^Civitai (\d+) \/ (\d+) · Stop$/, (m, done, total) => `Civitai ${done} / ${total} · 停止`],
[/^The limits of what this is wired to: (.*)\.$/, (m, names) => `它所连接对象的取值范围:${names}。`],
[/^Set by "(.*)"\. Click to show it\. Right-click the row to unlink\.$/, (m, name) => `由“${name}”设置。点击可定位到它。右键该行可断开连线。`],
[/^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} 条连线`],
];
+14
View File
@@ -0,0 +1,14 @@
// Image Resize 🆎: which card rows the node reads for the values set. No DOM
// and no ComfyUI imports, so node:test covers it.
// Only a width × height box can disagree with the picture's shape; every other
// target takes its shape from the picture, and the node always fits it
// (nodes/_resize_helpers.py). So Fit is only read in width × height.
export function readsFit(values) {
return values?.target_mode === "width+height";
}
// The fill colour paints pad's bars, so it is read only where pad is.
export function readsFill(values) {
return readsFit(values) && values?.keep_proportion === "pad";
}
+1 -1
View File
@@ -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.27.0";
export const AUSBOSS_JS_VERSION = "2.30.0";
export const BRAND = "#00b4aa"; // AusBoss teal — keep node accents consistent.
export const BRAND_DARK = "#007f78";
+252
View File
@@ -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];
}
+140
View File
@@ -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);
}
+117
View File
@@ -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);
}
+302
View File
@@ -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),
};
}
+262
View File
@@ -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));
}
+89
View File
@@ -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;
}
+170
View File
@@ -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);
}
+468
View File
@@ -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;
}
}
+66
View File
@@ -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));
}
+3
View File
@@ -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);
+23
View File
@@ -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
View File
@@ -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 };
}
+67 -2
View File
@@ -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) {
+58 -1
View File
@@ -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
+3 -3
View File
@@ -8,8 +8,8 @@
// quality dial of the software and NVENC encoders and maps onto webp's
// quality scale, while prores rides its own profile ladder, ffv1 is lossless
// by definition, and Pillow's gif path quantizes per frame with no quality
// dial at all. gif and webp are written frame by frame through Pillow and
// never carry the workflow metadata the video containers embed.
// dial at all. gif and webp are written frame by frame through Pillow; webp
// carries the workflow in EXIF as core's animated WebP does, gif never does.
export const FORMAT_WIDGET_SETS = {
"mp4 h264": ["crf", "save_metadata"],
"mp4 h265": ["crf", "save_metadata"],
@@ -20,7 +20,7 @@ export const FORMAT_WIDGET_SETS = {
"mov prores": ["save_metadata"],
"mkv ffv1": ["save_metadata"],
"gif": [],
"webp": ["crf"],
"webp": ["crf", "save_metadata"],
};
// The only widgets the format ever toggles. Everything else on the node —
+2 -1
View File
@@ -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; }
+160
View File
@@ -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;
}
+207
View File
@@ -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 };
}
+15 -2
View File
@@ -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
+15
View File
@@ -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 = () => {
+63 -16
View File
@@ -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;
+94
View File
@@ -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";
}
+28
View File
@@ -0,0 +1,28 @@
// The viewer's 360 settings and Cut (its "AusBoss View" property,
// js/viewer_pano) as one string, for Pause for Shot's hidden `view` input.
// ComfyUI runs a node again only when one of its inputs changes, and a
// node's properties in the saved workflow are not inputs: read from there, a
// changed Turn handed back the old backdrop. So the page writes them into
// the input as the prompt is built (js/pause_shot). The keys are sorted, so
// the same settings always give the same string and a run with nothing
// changed still comes from the cache.
const KEYS = ["sky", "cut"];
function sorted(value) {
if (Array.isArray(value)) return value.map(sorted);
if (!value || typeof value !== "object") return value;
const out = {};
for (const key of Object.keys(value).sort()) out[key] = sorted(value[key]);
return out;
}
export function viewValue(view) {
if (!view || typeof view !== "object") return "";
const out = {};
for (const key of KEYS) {
const part = view[key];
if (part && typeof part === "object" && !Array.isArray(part)) out[key] = sorted(part);
}
return Object.keys(out).length ? JSON.stringify(out) : "";
}
+30 -5
View File
@@ -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);
+426
View File
@@ -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;
});
},
});
+122 -7
View File
@@ -3,7 +3,9 @@
// end (the bar itself is full at a normal node width), so it never covers
// the frame. Its tabs:
// - Model: spin, tip and lean the model itself (saved with the shot, so
// the run's 3D shot follows).
// the run's 3D shot follows), and Cut: take away the front or back of
// the model, a share of its depth as the camera sees it (Pause for
// Shot cuts the run's mesh the same way, nodes/_mesh_cut_helpers.py).
// - Angle: turn, tilt and roll the 360 background, and its own field of
// view, and whether the 360 moves as the camera orbits (as the viewer
// draws it) or stays fixed in the frame like a photo backdrop.
@@ -37,6 +39,7 @@ export const SKY_DEFAULTS = Object.freeze({ turn: 0, tilt: 0, roll: 0, fov: null
export const ORBITS = Object.freeze(["moves", "fixed"]);
export const LIGHTS = Object.freeze(["studio", "photo", "360"]);
export const LOOK_DEFAULTS = Object.freeze({ light: "studio", strength: 100, bright: 100, contrast: 100, saturation: 100, warmth: 0 });
export const CUT_DEFAULTS = Object.freeze({ front: 0, back: 0 });
const ICONS = {
sky: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round"><circle cx="12" cy="12" r="8.5"/><ellipse cx="12" cy="12" rx="3.6" ry="8.5"/><path d="M3.5 12h17"/></svg>',
@@ -367,13 +370,112 @@ function applyLook(manager, state) {
state.dirty = false;
}
// ------------------------------------------------------------------ cut
// Two clipping planes square to the camera keep a band of the model's
// depth: Front takes that share off the near side, Back off the far side.
// The depth is how far the box around the model's own points reaches along
// the view, the same box Pause for Shot measures on the run's mesh.
const cutBoxes = new WeakMap();
function modelBox(model) {
if (cutBoxes.has(model)) return cutBoxes.get(model);
const Matrix = model.matrixWorld.constructor;
model.updateMatrixWorld(true);
const toModel = new Matrix().copy(model.matrixWorld).invert();
const lo = [Infinity, Infinity, Infinity];
const hi = [-Infinity, -Infinity, -Infinity];
model.traverse((part) => {
if (!part.isMesh || !part.geometry) return;
if (!part.geometry.boundingBox) part.geometry.computeBoundingBox?.();
const box = part.geometry.boundingBox;
if (!box) return;
const into = new Matrix().multiplyMatrices(toModel, part.matrixWorld);
const point = box.min.clone();
for (const x of [box.min.x, box.max.x]) for (const y of [box.min.y, box.max.y]) for (const z of [box.min.z, box.max.z]) {
point.set(x, y, z).applyMatrix4(into);
["x", "y", "z"].forEach((axis, i) => { lo[i] = Math.min(lo[i], point[axis]); hi[i] = Math.max(hi[i], point[axis]); });
}
});
const box = Number.isFinite(lo[0]) ? { lo, hi } : null;
if (box) cutBoxes.set(model, box);
return box;
}
const materialsOf = (part) => (Array.isArray(part.material) ? part.material : [part.material]).filter(Boolean);
function clearCut(state) {
state.cutModel?.traverse?.((part) => {
if (!part.isMesh) return;
for (const material of materialsOf(part)) {
if (material.clippingPlanes !== state.cutPlanes) continue;
material.clippingPlanes = null;
if ("ausbossCutSide" in material.userData) {
material.side = material.userData.ausbossCutSide;
delete material.userData.ausbossCutSide;
}
material.needsUpdate = true;
}
});
state.cutModel = null;
}
function applyCut(manager, state) {
const cut = state.values.cut;
const model = modelOf(manager);
if (!(cut.front > 0 || cut.back > 0) || !model) { if (state.cutModel) clearCut(state); return; }
const camera = manager.getActiveCamera?.();
const box = modelBox(model);
if (!camera || !box) return;
if (state.cutModel && state.cutModel !== model) clearCut(state);
model.updateMatrixWorld(true);
camera.updateMatrixWorld();
const Vector = camera.position.constructor;
const eye = new Vector().setFromMatrixPosition(camera.matrixWorld);
const forward = camera.getWorldDirection(new Vector());
const point = new Vector();
let lo = Infinity;
let hi = -Infinity;
for (const x of [box.lo[0], box.hi[0]]) for (const y of [box.lo[1], box.hi[1]]) for (const z of [box.lo[2], box.hi[2]]) {
const depth = point.set(x, y, z).applyMatrix4(model.matrixWorld).sub(eye).dot(forward);
lo = Math.min(lo, depth);
hi = Math.max(hi, depth);
}
const front = Math.min(99, Math.max(0, cut.front));
const back = Math.min(99 - front, Math.max(0, cut.back));
const near = lo + (hi - lo) * front / 100;
const far = hi - (hi - lo) * back / 100;
// three keeps the side where normal . p + constant >= 0.
state.cutPlanes ??= [{ normal: new Vector(), constant: 0 }, { normal: new Vector(), constant: 0 }];
const [nearPlane, farPlane] = state.cutPlanes;
const along = eye.dot(forward);
nearPlane.normal.copy(forward);
nearPlane.constant = -(along + near);
farPlane.normal.copy(forward).negate();
farPlane.constant = along + far;
manager.renderer.localClippingEnabled = true;
// The viewer swaps materials for its own modes, so check them each frame.
model.traverse((part) => {
if (!part.isMesh) return;
for (const material of materialsOf(part)) {
if (material.clippingPlanes === state.cutPlanes) continue;
material.clippingPlanes = state.cutPlanes;
material.clipShadows = true;
// Through the cut you see the model's inside, as Render Mesh draws
// it, not a hole: both sides while cut (three's DoubleSide is 2).
if (!("ausbossCutSide" in material.userData)) material.userData.ausbossCutSide = material.side;
material.side = 2;
material.needsUpdate = true;
}
});
state.cutModel = model;
}
// ------------------------------------------------------- viewer registry
const managers = new Set();
function stateOf(manager) {
return (manager.__ausbossViewState ??= {
values: { sky: { ...SKY_DEFAULTS }, look: { ...LOOK_DEFAULTS } },
values: { sky: { ...SKY_DEFAULTS }, look: { ...LOOK_DEFAULTS }, cut: { ...CUT_DEFAULTS } },
sky: null, skyWasOn: false, envTexture: null, lookUsed: false, frame: 0, dirty: true,
node: null, panorama: false, restored: false, lastMode: null,
});
@@ -418,6 +520,7 @@ function patchSceneManager() {
const state = stateOf(this);
keepPanorama(this, state);
applyLook(this, state);
applyCut(this, state);
if (skyActive(this, state.values.sky)) {
if (drawSky(this, state)) { state.skyWasOn = true; drawShadow(this, state); return undefined; }
} else if (state.skyWasOn) {
@@ -583,10 +686,15 @@ const COLOUR = { title: "Colour", group: "look", fields: [
// The model's own turn. These read and write the loaded model's rotation
// directly, which the viewer saves with the shot and hands to the run (its
// model_3d_info), so the 3D shot follows. Nothing extra is saved here.
// Front and Back cut are saved with the viewer ("cut" in its properties).
const MODEL = { title: "Model", group: "model", fields: [
{ key: "spin", label: "Spin", min: -180, max: 180, step: 1, fineStep: 0.1, decimals: 1, unit: "°", title: "Turn the model around, left or right." },
{ key: "tip", label: "Tip", min: -90, max: 90, step: 1, fineStep: 0.1, decimals: 1, unit: "°", title: "Tip the model forward or back." },
{ key: "lean", label: "Lean", min: -90, max: 90, step: 1, fineStep: 0.1, decimals: 1, unit: "°", title: "Lean the model left or right." },
{ key: "front", store: "cut", label: "Cut front", min: 0, max: 99, step: 1, fineStep: 0.1, decimals: 1, unit: "%",
title: "Cut away the part of the model nearest the camera, as a share of its depth." },
{ key: "back", store: "cut", label: "Cut back", min: 0, max: 99, step: 1, fineStep: 0.1, decimals: 1, unit: "%",
title: "Cut away the far side of the model, as a share of its depth: the inside of a hat behind the head, a hood, a back you don't want seen. Pause for Shot cuts the run's model the same way." },
] };
const TABS = [MODEL, ANGLE, BACKDROP, LIGHT, COLOUR];
@@ -615,7 +723,7 @@ function readSaved(node, state) {
if (node?.properties?.["Scene Config"]?.backgroundRenderMode === "panorama") state.panorama = true;
if (!saved || typeof saved !== "object") return;
if (saved.panorama === true) state.panorama = true;
for (const [group, defaults] of [["sky", SKY_DEFAULTS], ["look", LOOK_DEFAULTS]]) {
for (const [group, defaults] of [["sky", SKY_DEFAULTS], ["look", LOOK_DEFAULTS], ["cut", CUT_DEFAULTS]]) {
const from = saved[group] ?? {};
for (const key of Object.keys(defaults)) {
const value = from[key];
@@ -636,8 +744,12 @@ function writeSaved(node, state) {
node.properties ??= {};
const skyDefault = isDefault(state.values.sky, SKY_DEFAULTS);
const lookDefault = isDefault(state.values.look, LOOK_DEFAULTS);
if (skyDefault && lookDefault && !state.panorama) delete node.properties[PROP];
else node.properties[PROP] = { panorama: state.panorama, sky: { ...state.values.sky }, look: { ...state.values.look } };
const cutDefault = isDefault(state.values.cut, CUT_DEFAULTS);
if (skyDefault && lookDefault && cutDefault && !state.panorama) delete node.properties[PROP];
else {
node.properties[PROP] = { panorama: state.panorama, sky: { ...state.values.sky }, look: { ...state.values.look } };
if (!cutDefault) node.properties[PROP].cut = { ...state.values.cut };
}
app.graph?.setDirtyCanvas?.(true, false);
}
@@ -791,7 +903,8 @@ function buildStrip(box, root, manager) {
});
}
for (const field of spec.fields) {
const row = field.pill ? pillField(field, values) : scrubField(field, values);
const own = field.store ? state.values[field.store] : values;
const row = field.pill ? pillField(field, own) : scrubField(field, own);
rows.push({ row, spec: field });
fields.append(row);
}
@@ -810,7 +923,9 @@ function buildStrip(box, root, manager) {
reset.addEventListener("click", () => {
if (tab.group === "model") {
const model = modelOf(manager);
if (model) { writeModelTurn(model, { spin: 0, tip: 0, lean: 0 }); redraw(manager); }
if (model) writeModelTurn(model, { spin: 0, tip: 0, lean: 0 });
state.values.cut = { ...CUT_DEFAULTS };
changed();
show(tab);
return;
}
+154 -13
View File
@@ -10,15 +10,19 @@ 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";
import { readsFill, readsFit } from "../shared/image_resize_rows.mjs";
import { gearIconSvg, openSettingsMenu } from "../shared/settings_menu.mjs";
import { SEAM_MENU, SEAM_MUTE_TITLES, isBlendIn, seamCornerReserve } from "../shared/stitch_seam.mjs";
import { NUMBER_LOOK_MENU, TEXT_LOOK_MENU, setTextLook, textLook, textLookCornerReserve } from "../shared/text_look.mjs";
@@ -28,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)
@@ -77,6 +96,24 @@ function seamCorner(node, card) {
},
};
}
// Color Match: one line under Method that says what the picked method does,
// so the short pill names need no trip to the tooltip.
const COLOR_MATCH_METHOD_HINTS = {
lab: "Moves the colours to match. The safe default.",
rgb: "The same as lab, in plain red, green and blue.",
mkl: "For colours that are turned, not just shifted.",
histogram: "An exact match. The strongest, least subtle.",
kept: "For an edit: wire the picture from before the edit as reference.",
};
function colorMatchMethodHint() {
const element = document.createElement("div");
element.style.cssText = "display:flex;align-items:center;height:100%;padding:0 2px;box-sizing:border-box;"
+ `color:${THEME.faint};font:11px/14px ${FONT_UI};`;
return {
element,
sync: (values) => { element.textContent = COLOR_MATCH_METHOD_HINTS[values.method] ?? ""; },
};
}
// Text, Integer and Float: the gear in the card's corner picks the node's
// look, the usual box or big and centred (shared/text_look.mjs). The look is
// kept on the node, not in a widget, so the node's inputs and saved values
@@ -120,8 +157,8 @@ const CARDS = {
{ widget: "edge_length", label: "Edge", suffix: "px", when: isMode("target_mode", "longest_edge", "shortest_edge") },
{ widget: "megapixels", label: "Budget", suffix: "MP", when: isMode("target_mode", "megapixels") },
{ widget: "scale_factor", label: "Scale", suffix: "×", when: isMode("target_mode", "scale_factor") },
{ widget: "keep_proportion", label: "Fit", kind: "segment", labels: { cover_crop: "cover" } },
{ widget: "fill_color", label: "Fill", kind: "color", when: isMode("keep_proportion", "pad") },
{ widget: "keep_proportion", label: "Fit", kind: "segment", labels: { cover_crop: "cover" }, when: readsFit },
{ widget: "fill_color", label: "Fill", kind: "color", when: readsFill },
{ widget: "divisible_by", label: "Multiple" },
{ widget: "interpolation", label: "Filter", kind: "select" },
],
@@ -130,12 +167,29 @@ const CARDS = {
// its own rows show only while it is picked.
AUSBOSS_NODES_ImageToolbox: {
minWidth: 280,
resetUnknown: { width: 512, height: 512, position: "top left", move_right: 0, move_down: 0 },
rows: [
{ widget: "job", label: "Job", kind: "select" },
{ widget: "pieces", label: "Pieces", when: isMode("job", "split sheet at gaps") },
{ widget: "width", label: "Width", suffix: "px", when: isMode("job", "cut a piece") },
{ widget: "height", label: "Height", suffix: "px", when: isMode("job", "cut a piece") },
{ widget: "position", label: "Position", kind: "select", when: isMode("job", "cut a piece") },
{ widget: "move_right", label: "Move right", suffix: "px", when: isMode("job", "cut a piece") },
{ widget: "move_down", label: "Move down", suffix: "px", when: isMode("job", "cut a piece") },
],
},
AUSBOSS_NODES_PauseShot: { minWidth: 260, first: true, hide: ["view"], socketless: ["view"], rows: [
{ widget: "pause", label: "Pause", onText: "wait for me", offText: "run through" },
] },
AUSBOSS_NODES_PhotoCamera: {
minWidth: 260,
rows: [
{ widget: "fov", label: "Lens", suffix: "°", step: 1, decimals: 1, title: "How wide the photo is, in degrees across. Wire Get FoV from MoGe here." },
{ group: "advanced", label: "More" },
{ widget: "pad_factor", label: "Crop margin", suffix: "×", step: 0.05, decimals: 2, group: "advanced" },
{ widget: "canvas_width", label: "360 width", suffix: "px", step: 256, snap: true, group: "advanced" },
],
},
AUSBOSS_NODES_PauseShot: { minWidth: 260, first: true, rows: [{ widget: "pause", label: "Pause", onText: "wait for me", offText: "run through" }] },
AUSBOSS_NODES_EditLock: {
minWidth: 300,
rows: [
@@ -156,6 +210,7 @@ const CARDS = {
rows: [
{ widget: "strength", label: "Strength" },
{ widget: "method", label: "Method", kind: "segment", labels: { histogram: "hist" }, titles: { histogram: "histogram" } },
{ panel: colorMatchMethodHint, height: 28 },
{ widget: "reference_mode", label: "Reference", kind: "segment", labels: { reference: "reference", first_frame: "first frame" } },
{ widget: "invert_mask", label: "Invert mask" },
],
@@ -222,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" },
@@ -235,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
@@ -392,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).
@@ -408,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" },
@@ -421,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
@@ -459,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
@@ -521,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) {
@@ -553,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;
+240 -2
View File
@@ -48,7 +48,7 @@
},
"AUSBOSS_NODES_ColorMatch": {
"display_name": "颜色匹配 🆎",
"description": "把参考图的颜色统计转移到输入图上,用来修正局部重绘或拼回区域的色差。四种方法:lab 和 rgb 按通道调整均值和标准差,mkl 映射完整的颜色协方差,histogram 让每个通道的分布完全一致。可选的 mask 把测量和校正都限制在白色区域(invert_mask 反转),所以节点接收遮罩但不输出遮罩:遮罩只决定修正范围,在你的图中原样通过。strength 在原图和完全匹配的结果之间混合。视频用 reference_mode:first_frame 让每一帧都匹配批次自己的第一帧,不需要参考图也能减少帧间色彩漂移;它不会稳定画面运动。",
"description": "把参考图的颜色统计转移到输入图上,用来修正局部重绘或拼回区域的色差。五种方法:lab 和 rgb 按通道调整均值和标准差,mkl 映射完整的颜色协方差,histogram 让每个通道的分布完全一致,kept 用于编辑:从模型本该保留的部分学出它带来的偏移并整体撤销,新内容保留自己的颜色。可选的 mask 把测量和校正都限制在白色区域(invert_mask 反转),所以节点接收遮罩但不输出遮罩:遮罩只决定修正范围,在你的图中原样通过。strength 在原图和完全匹配的结果之间混合。视频用 reference_mode:first_frame 让每一帧都匹配批次自己的第一帧,不需要参考图也能减少帧间色彩漂移;它不会稳定画面运动。",
"inputs": {
"image": {
"name": "图像"
@@ -371,6 +371,9 @@
},
"full_prompt": {
"name": "完整提示词"
},
"tidy": {
"name": "整理我的台词"
}
},
"outputs": {
@@ -644,7 +647,7 @@
},
"AUSBOSS_NODES_ImageToolbox": {
"display_name": "图像工具箱 🆎",
"description": "把几个小的图像任务放在一个节点里:从列表里选任务。split sheet at gaps 会把一排并列的图(比如角色设定图的四个视角)切成单独的图。每一刀都切在两张图之间的空隙,而不是按宽度平均切,所以不会有哪一张带上邻图的一部分。切好的图作为一个批次输出,尺寸相同,用设定图的背景色补齐。",
"description": "把几个小的图像任务放在一个节点里:从列表里选任务。split sheet at gaps 会把一排并列的图(比如角色设定图的四个视角)切成单独的图。每一刀都切在两张图之间的空隙,而不是按宽度平均切,所以不会有哪一张带上邻图的一部分。切好的图作为一个批次输出,尺寸相同,用设定图的背景色补齐。cut a piece 按你设定的宽度和高度,在你选的位置裁出一块,同时给出图的其余部分。",
"inputs": {
"image": {
"name": "图像"
@@ -654,11 +657,29 @@
},
"pieces": {
"name": "份数"
},
"width": {
"name": "宽度"
},
"height": {
"name": "高度"
},
"position": {
"name": "位置"
},
"move_right": {
"name": "右移"
},
"move_down": {
"name": "下移"
}
},
"outputs": {
"0": {
"name": "图像"
},
"1": {
"name": "其余部分"
}
}
},
@@ -703,6 +724,9 @@
},
"mask": {
"name": "遮罩"
},
"reference_curve": {
"name": "参考强度曲线"
}
},
"outputs": {
@@ -795,6 +819,9 @@
},
"4": {
"name": "H3 提示词"
},
"5": {
"name": "位置描述"
}
}
},
@@ -999,6 +1026,9 @@
},
"on_missing": {
"name": "缺失时"
},
"curve": {
"name": "强度曲线"
}
},
"outputs": {
@@ -1242,6 +1272,12 @@
},
"max_hole_size": {
"name": "最大空洞尺寸"
},
"detail_range": {
"name": "细节范围"
},
"fix_threshold": {
"name": "修正阈值"
}
},
"outputs": {
@@ -1910,6 +1946,9 @@
},
"max_seconds": {
"name": "最大秒数"
},
"clean_up": {
"name": "清理"
}
},
"outputs": {
@@ -2003,6 +2042,12 @@
},
"panorama": {
"name": "360 全景"
},
"mesh": {
"name": "网格"
},
"view": {
"name": "查看器设置"
}
},
"outputs": {
@@ -2020,6 +2065,199 @@
},
"4": {
"name": "背景"
},
"5": {
"name": "网格"
}
}
},
"AUSBOSS_NODES_PhotoCamera": {
"display_name": "照片相机 🆎",
"description": "算出拍这张照片的相机,让人物的 3D 模型和照片对齐。接入照片、人物遮罩和照片的视角宽度(MoGe 的“获取视角”可测出)。crop_fov 接到 Pixal3D 条件,camera_info 接到 3D 查看器,查看器就会从照片本身的视角打开;三个位置数字决定照片放在 360 画布的哪里,让 360 在模型后面对齐。",
"inputs": {
"image": {
"name": "照片"
},
"mask": {
"name": "遮罩"
},
"fov": {
"name": "视角"
},
"pad_factor": {
"name": "裁剪边距"
},
"canvas_width": {
"name": "360 宽度"
}
},
"outputs": {
"0": {
"name": "裁剪视角"
},
"1": {
"name": "相机"
},
"2": {
"name": "照片宽度"
},
"3": {
"name": "照片左边"
},
"4": {
"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": "曲线"
}
}
}
+212
View File
@@ -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"]
+327
View File
@@ -0,0 +1,327 @@
"""The Civitai line: an A1111-style ``parameters`` text for Save Image 🆎.
civitai.com reads a ComfyUI picture's prompt out of the embedded graph, and
only for the nodes it knows: a prompt typed into a node it does not know
(Krea 2 Encode 🆎, core's Qwen Image 2.1 encoder, a prompt inside a
subgraph) reads as no prompt at all, and the upload is flagged "Unable to
Verify AI Generation". It also never matches a ComfyUI picture's models,
because it matches models by file hash and the graph holds only file names.
This module writes the line A1111 puts in its pictures, which Civitai reads
first: the prompt, the sampler settings, and the model and LoRA hashes
(AutoV2, the first ten hex digits of the file's SHA256). It is built from the
run's own graph (the hidden PROMPT input), walking up from the save node, so
a second sampler on another branch is not mistaken for this picture's.
Everything here is best effort and never raises into a save: a graph it
cannot read gives no line, and the file saves as it always did.
"""
from __future__ import annotations
import json
from pathlib import Path
from typing import Any, Callable
# How far a walk follows links before it gives up (cycles, odd graphs).
MAX_DEPTH = 40
# Inputs that hold a prompt's words, in the order they are tried.
TEXT_KEYS = ("text", "prompt", "populated_text", "text_g", "string", "value")
# Inputs that pass conditioning through from an earlier node.
CONDITIONING_KEYS = ("conditioning", "conditioning_1", "conditioning_to", "cond", "positive")
# Which model folder each loader input names a file in. Text encoders, VAEs
# and the like are left out: Civitai never credits a picture to one.
MODEL_KEYS = {
"ckpt_name": ("checkpoints",),
"unet_name": ("diffusion_models", "unet_gguf"),
}
LORA_FOLDERS = ("loras",)
LORA_LOADER = "AUSBOSS_NODES_LoraLoader"
def _is_link(value: Any) -> bool:
return (
isinstance(value, list) and len(value) == 2
and isinstance(value[0], (str, int)) and isinstance(value[1], int)
)
class _Graph:
def __init__(self, prompt: dict):
self.nodes = {str(key): node for key, node in prompt.items() if isinstance(node, dict)}
def node(self, link) -> dict | None:
return self.nodes.get(str(link[0])) if _is_link(link) else None
@staticmethod
def inputs(node: dict | None) -> dict:
values = (node or {}).get("inputs")
return values if isinstance(values, dict) else {}
def upstream(self, start: str | None) -> list[str]:
"""Node ids feeding ``start``, nearest first (breadth first)."""
if start is None or str(start) not in self.nodes:
return list(self.nodes)
order: list[str] = []
seen = {str(start)}
queue = [str(start)]
while queue:
current = queue.pop(0)
for value in self.inputs(self.nodes.get(current)).values():
if _is_link(value) and str(value[0]) in self.nodes and str(value[0]) not in seen:
seen.add(str(value[0]))
order.append(str(value[0]))
queue.append(str(value[0]))
return order
def literal(self, value: Any, keys: tuple[str, ...], depth: int = 0):
"""A typed value, or the value a linked primitive node holds."""
if not _is_link(value):
return value
if depth > MAX_DEPTH:
return None
inputs = self.inputs(self.node(value))
for key in keys:
if key in inputs:
return self.literal(inputs[key], keys, depth + 1)
return None
def words(self, value: Any, depth: int = 0) -> str | None:
"""The text a STRING input carries: typed, or from a text node."""
if isinstance(value, str):
return value
if not _is_link(value) or depth > MAX_DEPTH:
return None
inputs = self.inputs(self.node(value))
for key in TEXT_KEYS:
if key in inputs:
found = self.words(inputs[key], depth + 1)
if found is not None:
return found
if "string_a" in inputs or "string_b" in inputs:
parts = [self.words(inputs.get(key), depth + 1) for key in ("string_a", "string_b")]
delimiter = inputs.get("delimiter") if isinstance(inputs.get("delimiter"), str) else ""
return delimiter.join(part for part in parts if part)
return None
def conditioning_text(self, link: Any, depth: int = 0) -> str | None:
"""The prompt behind a CONDITIONING link, through encoders and the
nodes that pass conditioning on (ControlNet, guidance, inpaint)."""
node = self.node(link)
if node is None or depth > MAX_DEPTH:
return None
inputs = self.inputs(node)
slot = link[1]
# An encoder with both prompts (Krea 2 Encode 🆎, Qwen Image 2.1):
# its second output is the negative.
if "negative_prompt" in inputs and slot == 1:
return self.words(inputs["negative_prompt"])
for key in TEXT_KEYS[:4]:
if key in inputs:
found = self.words(inputs[key])
if found is not None:
return found
# A node that takes and returns a positive/negative pair.
if _is_link(inputs.get("positive")) and _is_link(inputs.get("negative")):
return self.conditioning_text(inputs["negative" if slot == 1 else "positive"], depth + 1)
for key in CONDITIONING_KEYS:
if _is_link(inputs.get(key)):
return self.conditioning_text(inputs[key], depth + 1)
return None
def _sampler(graph: _Graph, order: list[str]) -> dict | None:
"""The settings of the nearest sampler upstream of the save node."""
for node_id in order:
node = graph.nodes[node_id]
inputs = graph.inputs(node)
settings: dict[str, Any] = {}
if "positive" in inputs and "negative" in inputs and ("steps" in inputs or "sigmas" in inputs):
# KSampler, KSamplerAdvanced, SamplerCustom and look-alikes.
positive, negative = inputs["positive"], inputs["negative"]
settings["seed"] = graph.literal(inputs.get("seed", inputs.get("noise_seed")), ("seed", "noise_seed", "value", "int"))
settings["cfg"] = graph.literal(inputs.get("cfg"), ("cfg", "value", "float"))
settings["sampler"] = graph.literal(inputs.get("sampler_name"), ("sampler_name", "value"))
settings["scheduler"] = graph.literal(inputs.get("scheduler"), ("scheduler", "value"))
settings["steps"] = graph.literal(inputs.get("steps"), ("steps", "value", "int"))
settings["denoise"] = graph.literal(inputs.get("denoise"), ("denoise", "value", "float"))
sampler_link, sigmas_link = inputs.get("sampler"), inputs.get("sigmas")
model_link = inputs.get("model")
elif "guider" in inputs and ("sigmas" in inputs or "noise" in inputs):
# SamplerCustomAdvanced: the settings sit on the nodes it takes.
guider = graph.inputs(graph.node(inputs["guider"]))
if "positive" in guider:
positive, negative = guider.get("positive"), guider.get("negative")
else:
positive, negative = guider.get("conditioning"), None
settings["cfg"] = graph.literal(guider.get("cfg"), ("cfg", "value", "float"))
noise = graph.inputs(graph.node(inputs.get("noise")))
settings["seed"] = graph.literal(noise.get("noise_seed", noise.get("seed")), ("noise_seed", "seed", "value", "int"))
sampler_link, sigmas_link = inputs.get("sampler"), inputs.get("sigmas")
model_link = guider.get("model")
else:
continue
sampler_inputs = graph.inputs(graph.node(sampler_link))
if settings.get("sampler") is None and "sampler_name" in sampler_inputs:
settings["sampler"] = graph.literal(sampler_inputs["sampler_name"], ("sampler_name", "value"))
sigmas = graph.inputs(graph.node(sigmas_link))
for key in ("steps", "scheduler", "denoise"):
if settings.get(key) is None and key in sigmas:
settings[key] = graph.literal(sigmas[key], (key, "value"))
settings["positive"] = graph.conditioning_text(positive) or ""
settings["negative"] = graph.conditioning_text(negative) or ""
settings["model_link"] = model_link
settings["latent_link"] = inputs.get("latent_image")
return settings
return None
def _lora_rows(graph: _Graph, node: dict) -> list[tuple[str, Any]]:
"""(file name, strength) of every LoRA a loader node applies."""
inputs = graph.inputs(node)
rows: list[tuple[str, Any]] = []
if node.get("class_type") == LORA_LOADER and isinstance(inputs.get("loras"), str):
try:
from ._lora_helpers import parse_lora_stack
for row in parse_lora_stack(inputs["loras"]):
if row["enabled"] and row["strength"]:
rows.append((row["name"], row["strength"]))
except Exception:
pass
return rows
if isinstance(inputs.get("lora_name"), str):
strength = graph.literal(inputs.get("strength_model", inputs.get("strength", 1.0)), ("value", "float"))
if strength != 0:
rows.append((inputs["lora_name"], strength))
# Stack loaders that keep one entry per row: {"on", "lora", "strength"}.
for value in inputs.values():
if isinstance(value, dict) and isinstance(value.get("lora"), str) and value.get("on", True):
if value.get("strength", 1.0) != 0:
rows.append((value["lora"], value.get("strength", 1.0)))
return [(name, strength) for name, strength in rows if name and name.lower() != "none"]
def _starts_from_a_picture(graph: _Graph, latent_link: Any, denoise: Any) -> bool:
"""True when the sampler reworks an existing picture rather than noise."""
if isinstance(denoise, (int, float)) and denoise < 1:
return True
start = graph.node(latent_link)
if start is None:
return False
first = str(latent_link[0])
for node_id in [first] + graph.upstream(first):
kind = str(graph.nodes[node_id].get("class_type", ""))
if "VAEEncode" in kind or "Inpaint" in kind:
return True
return False
def _short_name(name: str) -> str:
return Path(str(name).replace("\\", "/")).stem
def _quote(value: str) -> str:
"""An A1111 value: quoted when a comma, colon or quote would split it."""
return json.dumps(value) if any(mark in value for mark in ',:"\n') else value
def civitai_parameters(
prompt: dict | None,
save_node_id: str | None,
width: int,
height: int,
find_file: Callable[[tuple[str, ...], str], Path | None],
file_hash: Callable[[Path], str],
) -> str | None:
"""The A1111-style line for one save, or None when the graph holds no
sampler to describe. ``find_file(folders, name)`` resolves a model file;
``file_hash(path)`` returns its SHA256 (cached by the caller)."""
if not isinstance(prompt, dict):
return None
try:
graph = _Graph(prompt)
order = graph.upstream(save_node_id)
settings = _sampler(graph, order)
if settings is None or settings.get("steps") is None:
return None
def autov2(folders, name) -> str | None:
try:
path = find_file(folders, name)
return file_hash(path)[:10] if path is not None else None
except Exception:
return None
# Models and LoRAs are looked for up the sampler's model input, so a
# loader that only feeds another branch (a mask model, an upscaler
# pass) is not credited; a graph without that link falls back to
# everything upstream of the save.
model_node = graph.node(settings["model_link"])
model_order = order
if model_node is not None:
start = str(settings["model_link"][0])
model_order = [start] + graph.upstream(start)
model_name = model_hash = None
loras: list[tuple[str, Any, str]] = []
seen_loras: set[str] = set()
for node_id in model_order:
node = graph.nodes[node_id]
inputs = graph.inputs(node)
if model_name is None:
for key, folders in MODEL_KEYS.items():
name = inputs.get(key)
if isinstance(name, str) and name:
model_name, model_hash = name, autov2(folders, name)
break
for name, strength in _lora_rows(graph, node):
if name in seen_loras:
continue
seen_loras.add(name)
found = autov2(LORA_FOLDERS, name)
if found:
loras.append((name, strength, found))
if not settings["positive"].strip() and not model_hash and not loras:
return None
lines = [settings["positive"].strip()]
if settings["negative"].strip():
lines.append("Negative prompt: " + settings["negative"].strip())
details = [f"Steps: {settings['steps']}"]
for label, key in (("Sampler", "sampler"), ("Schedule type", "scheduler"), ("CFG scale", "cfg"), ("Seed", "seed")):
value = settings.get(key)
if value is not None and not _is_link(value):
details.append(f"{label}: {_quote(str(value))}")
details.append(f"Size: {int(width)}x{int(height)}")
hashes: dict[str, str] = {}
if model_name:
if model_hash:
details.append(f"Model hash: {model_hash}")
hashes["model"] = model_hash
details.append(f"Model: {_quote(_short_name(model_name))}")
denoise = settings.get("denoise")
if isinstance(denoise, (int, float)) and denoise < 1:
details.append(f"Denoising strength: {denoise}")
if loras:
listed = ", ".join(f"{_short_name(name)}: {digest}" for name, _strength, digest in loras)
details.append(f"Lora hashes: {json.dumps(listed)}")
for name, _strength, digest in loras:
hashes[f"lora:{_short_name(name)}"] = digest
if hashes:
details.append("Hashes: " + json.dumps(hashes, separators=(",", ":")))
details.append("Version: ComfyUI")
# Lower-case keys Civitai keeps as they are: "engine" tags the post
# with the ComfyUI tool, "process" picks its technique.
details.append("engine: ComfyUI")
img2img = _starts_from_a_picture(graph, settings.get("latent_link"), denoise)
details.append("process: " + ("img2img" if img2img else "txt2img"))
lines.append(", ".join(details))
return "\n".join(lines)
except Exception:
return None
__all__ = ["civitai_parameters"]
+96 -4
View File
@@ -154,8 +154,9 @@ def lab_to_rgb(lab: torch.Tensor) -> torch.Tensor:
# Method names are the node's combo values. All are textbook constructions
# implemented here from the math: per-channel mean/std transfer in LAB or RGB,
# the closed-form Monge-Kantorovich linear covariance mapping, and per-channel
# histogram (quantile) matching.
COLOR_MATCH_METHODS = ("lab", "rgb", "mkl", "histogram")
# histogram (quantile) matching. "kept" is the pack's own: a robust fit on
# the pixels an edit left alone (see _kept_matched).
COLOR_MATCH_METHODS = ("lab", "rgb", "mkl", "histogram", "kept")
def _weighted_lab_stats(
@@ -294,6 +295,94 @@ def _histogram_matched(
return torch.stack(frames, dim=0).clamp(0.0, 1.0)
# A kept-pixel fit never moves contrast or saturation further than this; a
# larger number means the fit read new content as kept, not a real drift.
_KEPT_GAIN = {"lightness": (0.7, 1.3), "chroma": (0.6, 1.3)}
_KEPT_SAMPLES = 200_000
def _kept_fit(source: torch.Tensor, target: torch.Tensor, keep: float = 0.6, rounds: int = 4):
"""Robust tone fit, N x 3 LAB source onto N x 3 LAB target.
Fits lightness gain and offset, one chroma gain about the source's mean
colour, and an a/b offset. Each round keeps the best-fitting share
(``keep``) of the pixels and fits again, so content the edit changed
falls out as outliers and only the pixels it kept decide the fit.
"""
chosen = torch.ones(source.shape[0], dtype=torch.bool, device=source.device)
params = (1.0, 0.0, 1.0, torch.zeros(2, dtype=source.dtype, device=source.device),
source[:, 1:].mean(0))
for _ in range(rounds):
s, t = source[chosen], target[chosen]
if s.shape[0] < 16:
break
sl, tl = s[:, 0], t[:, 0]
sl_mean, tl_mean = sl.mean(), tl.mean()
var = ((sl - sl_mean) ** 2).sum()
gain_l = float(((sl - sl_mean) * (tl - tl_mean)).sum() / var) if var > 1e-6 else 1.0
gain_l = min(max(gain_l, _KEPT_GAIN["lightness"][0]), _KEPT_GAIN["lightness"][1])
offset_l = float(tl_mean - gain_l * sl_mean)
centre = s[:, 1:].mean(0)
sc, tc = s[:, 1:] - centre, t[:, 1:] - t[:, 1:].mean(0)
cvar = (sc * sc).sum()
gain_c = float((sc * tc).sum() / cvar) if cvar > 1e-6 else 1.0
gain_c = min(max(gain_c, _KEPT_GAIN["chroma"][0]), _KEPT_GAIN["chroma"][1])
tint = (t[:, 1:] - s[:, 1:]).mean(0)
params = (gain_l, offset_l, gain_c, tint, centre)
residual = (_kept_apply(source, params) - target).norm(dim=-1)
limit = torch.quantile(residual[chosen], keep)
chosen = chosen & (residual <= limit)
return params
def _kept_apply(lab: torch.Tensor, params) -> torch.Tensor:
gain_l, offset_l, gain_c, tint, centre = params
lightness = lab[..., :1] * gain_l + offset_l
colour = (lab[..., 1:] - centre) * gain_c + centre + tint
return torch.cat([lightness, colour], dim=-1)
def _kept_matched(
rgb: torch.Tensor, reference: torch.Tensor, mask: torch.Tensor | None
) -> torch.Tensor:
"""Undo an edit's tone drift, learned from the pixels the edit kept.
The reference is the same picture before the edit, pixel for pixel. An
edit model often hands back the parts it was asked to keep a little
darker, with more contrast and colour. Measured on those kept parts
(inside the mask, if one is given), the drift is a lightness gain and
offset, a saturation gain and a tint; undoing it everywhere brings the
new content into the same tone without pulling its own colours toward
what used to be there.
"""
if reference.shape[1:3] != rgb.shape[1:3]:
raise ValueError(
"Color Match kept needs the picture from before the edit, at the same "
f"size: the image is {rgb.shape[2]}x{rgb.shape[1]}, the reference "
f"{reference.shape[2]}x{reference.shape[1]}."
)
frames = []
for index in range(rgb.shape[0]):
lab = rgb_to_lab(rgb[index : index + 1])[0]
pick = index if reference.shape[0] > 1 else 0
ref = rgb_to_lab(reference[pick : pick + 1])[0]
source, target = lab.reshape(-1, 3), ref.reshape(-1, 3)
if mask is not None:
region = mask[index if mask.shape[0] > 1 else 0].reshape(-1) > 0.5
source, target = source[region], target[region]
if source.shape[0] < 64:
frames.append(rgb[index])
continue
if source.shape[0] > _KEPT_SAMPLES:
# An even spread of pixels: the same answer every run.
step = source.shape[0] // _KEPT_SAMPLES + 1
source, target = source[::step], target[::step]
params = _kept_fit(source.double(), target.double())
params = tuple(p.to(lab.dtype) if isinstance(p, torch.Tensor) else p for p in params)
frames.append(lab_to_rgb(_kept_apply(lab, params).unsqueeze(0))[0])
return torch.stack(frames, dim=0)
def match_colors(
image: torch.Tensor,
reference: torch.Tensor,
@@ -307,8 +396,9 @@ def match_colors(
``method`` picks the construction: "lab" and "rgb" move per-channel
mean/std in that space, "mkl" maps the full RGB covariance through the
Monge-Kantorovich linear transform, "histogram" matches each channel's
quantiles exactly. With a mask, both the measured statistics and the
applied correction are restricted to the white region (``invert_mask``
quantiles exactly, "kept" undoes an edit's tone drift learned from the
pixels it kept (the reference is the picture before the edit). With a
mask, both the measured statistics and the applied correction are restricted to the white region (``invert_mask``
flips which side that is); pixels where the mask is zero are returned
bit-identical. ``strength`` lerps between the original (0) and the
fully matched image (1). A batch-1 reference broadcasts across an
@@ -360,6 +450,8 @@ def match_colors(
matched = _mkl_matched(rgb, ref_rgb, mask)
elif method == "histogram":
matched = _histogram_matched(rgb, ref_rgb, mask)
elif method == "kept":
matched = _kept_matched(rgb, ref_rgb, mask)
else:
matched = _stats_matched(rgb, ref_rgb, mask, in_lab=method == "lab")
+220
View File
@@ -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
+128
View File
@@ -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"]
+104
View File
@@ -0,0 +1,104 @@
"""Cut a piece of a chosen size out of a picture.
The piece's place is a position on the picture (a corner, an edge's middle
or the centre) moved by an offset in pixels. The piece always stays inside
the picture: a size larger than the picture is cut to the picture's size,
and an offset that would push it past an edge stops at that edge.
Besides the piece, the job gives back the rest of the picture. When the
piece takes a whole side (the full height against the left or right edge,
or the full width against the top or bottom), the rest is the strip beside
it, so one cut splits a picture into two parts of different sizes. Any
other piece leaves a hole, and the rest is the whole picture with that
hole filled with the picture's backdrop colour.
"""
from __future__ import annotations
import torch
from ._sheet_split_helpers import backdrop_color
# Reading order, so the list reads like the picture: top row, middle, bottom.
POSITIONS = (
"top left",
"top",
"top right",
"left",
"center",
"right",
"bottom left",
"bottom",
"bottom right",
)
def piece_box(
height: int,
width: int,
piece_width: int,
piece_height: int,
position: str = "top left",
move_right: int = 0,
move_down: int = 0,
) -> tuple[int, int, int, int]:
"""(top, left, bottom, right) of the piece, inside a height x width picture.
A piece width or height of 0 (or less) means the picture's full width or
height; a larger one is cut to the picture.
"""
if position not in POSITIONS:
raise ValueError(f"Cut a piece has no position named {position!r}.")
piece_width = width if piece_width <= 0 else min(int(piece_width), width)
piece_height = height if piece_height <= 0 else min(int(piece_height), height)
if "left" in position:
left = 0
elif "right" in position:
left = width - piece_width
else:
left = (width - piece_width) // 2
if position.startswith("top"):
top = 0
elif position.startswith("bottom"):
top = height - piece_height
else:
top = (height - piece_height) // 2
left = max(0, min(width - piece_width, left + int(move_right)))
top = max(0, min(height - piece_height, top + int(move_down)))
return top, left, top + piece_height, left + piece_width
def rest_of(image: torch.Tensor, box: tuple[int, int, int, int]) -> torch.Tensor:
"""What is left of a BHWC batch once the piece in ``box`` is cut out."""
top, left, bottom, right = box
height, width = image.shape[1], image.shape[2]
full_height = top == 0 and bottom == height
full_width = left == 0 and right == width
if full_height and not full_width:
if left == 0:
return image[:, :, right:].clone()
if right == width:
return image[:, :, :left].clone()
if full_width and not full_height:
if top == 0:
return image[:, bottom:].clone()
if bottom == height:
return image[:, :top].clone()
rest = image.clone()
for index in range(rest.shape[0]):
rest[index, top:bottom, left:right] = backdrop_color(image[index])
return rest
def cut_piece(
image: torch.Tensor,
piece_width: int,
piece_height: int,
position: str = "top left",
move_right: int = 0,
move_down: int = 0,
) -> tuple[torch.Tensor, torch.Tensor]:
"""The piece and the rest, for every picture of a BHWC batch at the same place."""
box = piece_box(image.shape[1], image.shape[2], piece_width, piece_height, position, move_right, move_down)
top, left, bottom, right = box
return image[:, top:bottom, left:right].clone(), rest_of(image, box)
+178
View File
@@ -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"]
+10 -1
View File
@@ -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
View File
@@ -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
+70
View File
@@ -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"]
+247
View File
@@ -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",
]
+245
View File
@@ -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"]

Some files were not shown because too many files have changed in this diff Show More