Compare commits

..
129 Commits
Author SHA1 Message Date
ausboss 852af46786 Merge pull request #397 from ausboss/release/2.26.7
Release 2.26.7
2026-11-21 22:07:54 -06:00
ausboss 63790c2e10 Release 2.26.7 2026-11-21 22:07:00 -06:00
ausboss 2289ef77aa Merge pull request #395 from ausboss/fix/old-copy-warning 2026-11-21 21:02:15 -06:00
ausboss 7d09daeb39 Workflow Note: a missing AusBoss node offers an update in the Manager, not a GitHub clone 2026-11-21 20:44:51 -06:00
ausboss 7c61ae226d Workflow skill: clone into ausboss-nodes too 2026-11-21 20:07:17 -06:00
ausboss 52cb5d8493 README: clone into ausboss-nodes, the folder ComfyUI-Manager uses 2026-11-21 20:07:11 -06:00
ausboss bfa7c35a64 Say in the browser when an old copy of the pack loads instead of the new one 2026-11-21 20:02:28 -06:00
ausboss 916197fb28 Merge pull request #394 from ausboss/feat/lora-strength-links
LoRA Loader: set a row's strength with a wire
2026-11-21 16:39:12 -06:00
ausboss 286866fa0f LoRA Loader strength links: help page and changelog 2026-11-21 16:37:24 -06:00
ausboss a9fe941b03 LoRA Loader strength links: outline the whole linked box 2026-11-21 16:33:50 -06:00
ausboss f684af1273 LoRA Loader strength links: wires shown by default 2026-11-21 16:28:38 -06:00
ausboss 734e88af1f LoRA Loader strength links: Nodes 2.0 drop, Chinese labels, tests 2026-11-21 16:24:45 -06:00
ausboss a3a5cf2826 LoRA Loader: link a number wire to a row's strength 2026-11-21 16:15:09 -06:00
ausboss 2fa296fe89 Merge pull request #393 from ausboss/fix/saved-fallbacks-follow-run
Saved-fallback test follows run() into write() (#391)
2026-11-21 16:14:58 -06:00
ausboss 07461b5972 Merge pull request #392 from ausboss/feat/zh-node-faces
Show Chinese on node faces when ComfyUI's language is Chinese
2026-11-21 16:05:54 -06:00
ausboss 952f72bedf Saved-fallback test: follow run() into write() for H3 Prompt Writer (#391) 2026-11-21 15:40:53 -06:00
ausboss 3792649ae5 Merge pull request #390 from ausboss/fix/workflow-note-shared-folders
Workflow Note: find models in Stability Matrix's shared folders
2026-11-21 15:31:16 -06:00
ausboss 5b00d85094 Merge remote-tracking branch 'origin/main' into fix/workflow-note-shared-folders
# Conflicts:
#	CHANGELOG.md
2026-11-21 15:30:22 -06:00
ausboss 09b8c499e7 Merge pull request #389 from ausboss/fix/py310-tomllib
Load on Python 3.10, where tomllib does not exist
2026-11-21 15:30:11 -06:00
ausboss d2782a2a90 Show Chinese on node faces when ComfyUI's language is Chinese
Cards, panels, buttons, choices and tooltips follow Settings > Language through js/shared/i18n.mjs and the table in js/shared/i18n_zh.mjs. Text with no entry stays English; widget names and values are untouched. Adds the missing Chinese socket names for H3 Prompt Writer and a few other nodes.
2026-11-21 12:28:18 -06:00
ausboss 3ef50e0262 Workflow Note: find models in Stability Matrix's shared folders (#386)
A row in folder clip or unet was never checked: ComfyUI's /models/<folder>
list answers 404 for those old names, though it files them as
text_encoders and diffusion_models everywhere else. Stability Matrix uses
both. Rows now ask for the folder by the name ComfyUI lists it under.

The card also names the folders this install reads with a name of their
own (Stability Matrix's Data/Models/Lora, from extra_model_paths.yaml) under
the usual ComfyUI/models/<folder> heading, and a missing file's dot lists
every folder that was searched. Both come from ComfyUI's
/experiment/models; without it the card reads as before.

Fixes #386
2026-11-21 09:28:11 -06:00
ausboss f9cd259a3e Load on Python 3.10, where tomllib does not exist (#387)
__init__.py and the single-copy guard imported tomllib at the top, which
only exists from Python 3.11, so on a 3.10 install (some Stability Matrix
setups) the whole pack failed to import. Both now read pyproject.toml
through nodes/_pyproject.py: tomllib when it is there, the tomli backport
when installed, else a small reader for the plain name and version lines
of [project]. No new dependency.

Fixes #387
2026-11-21 09:23:56 -06:00
ausboss 9ab4365245 Merge pull request #385 from ausboss/fix/latent-size-chips-keep-default
Latent Size: ratio chips keep the current megapixels by default
2026-11-20 22:33:46 -06:00
ausboss 5dfbcdd99c Merge remote-tracking branch 'origin/main' into fix/latent-size-chips-keep-default
# Conflicts:
#	CHANGELOG.md
2026-11-20 22:33:13 -06:00
ausboss 20f860d5ff Merge pull request #382 from ausboss/feat/h3-full-prompt-tab
H3 Prompt Writer: a Full prompt tab to see and change the written prompt
2026-11-20 22:32:59 -06:00
ausboss 44edcc633c Latent Size: ratio chips keep the current megapixels by default
Fixes #377. The gear setting lived only in browser storage, so private
windows lost it every time. It now starts on; turning it off still brings
back the ~1MP jump.
2026-11-20 21:29:18 -06:00
ausboss c99425cef1 Merge branch 'main' of https://github.com/ausboss/ComfyUI-AusBoss into feat/h3-full-prompt-tab
# Conflicts:
#	CHANGELOG.md
2026-11-20 21:26:03 -06:00
ausboss dcb9be2bdc Merge pull request #384 from ausboss/release/2.26.6
Release 2.26.6
2026-11-20 21:24:57 -06:00
ausboss 9304be69a8 Release 2.26.6: Image Toolbox help says what too many pieces does 2026-11-20 21:13:24 -06:00
ausboss 743126d86f H3 Prompt Writer help: drop the reset-and-edit-again line 2026-11-20 15:42:37 -06:00
ausboss fb430afca1 Merge branch 'main' of https://github.com/ausboss/ComfyUI-AusBoss into feat/h3-full-prompt-tab
# Conflicts:
#	CHANGELOG.md
2026-11-20 15:39:03 -06:00
ausboss c636d73223 Merge pull request #383 from ausboss/release/2.26.5
Release 2.26.5: Image Toolbox
2026-11-20 15:35:21 -06:00
ausboss 6db92cdd28 Release 2.26.5 2026-11-20 15:33:27 -06:00
ausboss 3c6cbd3a41 Image Toolbox: one node for small picture jobs, starting with split sheet at gaps
A sheet of side-by-side pictures, such as a character sheet's four views,
rarely puts each picture on its equal share of the width, so cutting into
equal parts left part of a neighbour in one piece. Each cut now goes to the
cleanest column near its equal-share line. The pieces come out as one batch
of the same size, padded with the sheet's backdrop colour; the outer pieces
keep the sheet's own edge at their outer edge.

New jobs are new choices in the job list, so they need no new node.
2026-11-20 15:29:12 -06:00
ausboss a606d34b97 H3 Prompt Writer: a Full prompt tab to see and change the written prompt
The node gets two tabs. Simple is the card as before and stays the
default. Full prompt shows the prompt the node wrote on its last run, in a
box you can edit; when it holds an edit, that text is sent to H3 instead.
An amber dot on the tab, a note under the box and a line on the Simple tab
say an edit is being sent. Reset to written clears it.

- New optional `full_prompt` input, appended last, with a "" fallback for
  older saves. The node now returns the written prompt as ui output
  (`written_prompt`); `write` is unchanged and `run` wraps it.
- Widget card: `when` gets the node as well as the values, a panel row can
  grow, and `refreshByHand` lets a panel redraw the card.
- Fix: a hidden textarea or panel row stayed visible, because the later
  `display:block` rules for those rows beat `.hidden`.
2026-11-20 14:03:47 -06:00
ausboss aaf3ae6ae6 Merge pull request #379 from ausboss/feat/stitch-follow-changes 2026-11-18 22:25:04 -06:00
ausboss d62d263725 Merge branch 'main' of https://github.com/ausboss/ComfyUI-AusBoss into feat/stitch-follow-changes
# Conflicts:
#	CHANGELOG.md
2026-11-18 21:22:00 -06:00
ausboss ffd4e66654 Merge pull request #376 from ausboss/feat/lora-picker-fold-all 2026-11-18 21:20:01 -06:00
ausboss 7f97d84a88 Stitch Inpaint: Follow changes pastes what the model drew past the box
Edit models that redraw the whole crop draw a boot, a plate rim or a
collar a little past the box, and the classic paste cut it off at the
box's edge. Follow changes lines the model's crop up with the picture's
own (zoom and shift), then grows the paste to every change that touches
the box and fades it out before the crop border. When the model redrew
nearly everything, the paste stays the box. Off by default.
2026-11-18 20:12:31 -06:00
ausboss acfe587691 Merge branch 'main' of https://github.com/ausboss/ComfyUI-AusBoss into feat/lora-picker-fold-all
# Conflicts:
#	CHANGELOG.md
2026-11-18 19:30:19 -06:00
ausboss f87d710d14 Merge pull request #378 from ausboss/perf/box-edit-speed
Make the box-edit nodes cost the box, not the picture
2026-11-18 19:29:31 -06:00
ausboss 85da4a4d0e Make the box-edit nodes cost the box, not the picture
Crop For Inpaint, Image Crop + Rotate + Pad and Stitch Inpaint grew and
blurred masks over the whole frame. On a 17 MP photo with a small box this
took about 5 s of CPU before sampling, most of it in a 97 px max pool and a
blur over millions of zero pixels.

- Grow, shrink and blur run on a window around the mask's nonzero pixels;
  an empty mask costs one scan.
- Grows use an exact doubling running max instead of a wide max pool.
- Crop + Rotate + Pad reuses its stored original when nothing is
  see-through and drops two redundant copies.

Grows match the old filters to the bit; blurs match within one float32
rounding step. tests/test_box_edit_speed.py checks both and holds 17 MP
timing bounds the old code fails.
2026-11-18 17:46:58 -06:00
ausboss 4832789b48 LoRA Loader: + LoRA list opens folded, with Fold all / Open all
The + LoRA list now opens with every folder folded, so a big LoRA folder
starts as a short list of top folders. A Fold all / Open all button beside
the search box folds or opens every folder at once, and Alt- or Shift-click
on a folder's arrow does the same for that folder and everything inside it.
Left on a highlighted file folds the folder it is in and moves up to it.

A setting (LoRA Loader > Picker folders) brings back the old way: Remember
my folds opens the list as it was left in this browser.
2026-11-18 15:53:04 -06:00
ausboss 9e9121accb Merge pull request #375 from ausboss/release/2.26.4
Release 2.26.4
2026-11-18 14:55:35 -06:00
ausboss 905ee4033f Release 2.26.4 2026-11-18 14:53:34 -06:00
ausboss 3ef9e5f51d Stop a video upload at 4 GB and remove the partial file 2026-11-18 14:50:46 -06:00
ausboss 05628b7834 Merge pull request #370 from ausboss/feat/h3-camera-from-video
H3 Prompt Writer: Camera reads "from the video" when the clip sets it
2026-11-18 14:50:35 -06:00
ausboss c1c1a5e054 Move the Layout Boxes and Camera notes to Unreleased 2026-11-18 14:49:20 -06:00
ausboss a3eb72a30c H3 Prompt Writer: Camera reads "from the video" when the clip sets it
The first Camera choice adds no camera words. With a live clip wired for
copy its moves, swap the person, new voice or change something, the prompt
already hands H3 the clip's own camera, so the list now shows that choice
as "from the video". Keep going makes new footage and keeps "as typed".

Only the shown text changes: the saved value stays "as typed", so saved
workflows and API prompts are unchanged. Card labels functions now also
receive the node, which the label needs to read the wire and the job.
2026-11-18 14:48:54 -06:00
ausboss cacadcf3b1 Merge pull request #369 from ausboss/feat/layout-boxes-h3
Layout Boxes: h3_prompt output for MiniMax H3 Image
2026-11-18 14:48:31 -06:00
ausboss 467505748d Merge pull request #373 from ausboss/test/privacy-browser-faces
Nightly face test: also run as a privacy browser
2026-11-18 14:48:26 -06:00
ausboss c100ef82c4 Merge pull request #374 from KBerwari/patch-1
Fix image previews for filenames with leading spaces
2026-11-18 14:48:22 -06:00
Kurdin Bekes Berwari fa695038ce Add regression tests for image filename whitespace in media_list.test.mjs 2026-11-18 15:36:59 +01:00
Kurdin Bekes Berwari 30cc27b985 Add regression tests for image filename whitespace 2026-11-18 15:35:50 +01:00
Kurdin Bekes Berwari 081379ae97 Preserve empty image selection handling 2026-11-18 15:27:28 +01:00
ausboss 21f97580e9 Merge pull request #372 from ausboss/fix/compare-rest-switch
Image Compare: save the picture it rests on, B for a new node
2026-11-17 23:38:09 -06:00
ausboss 8c6599d2d4 Run the face smoke test as a privacy browser too
--blocked-reads blanks every canvas pixel read the page makes, gives each
node that loads a picture a sample picture, and fails when its face then
draws none. The nightly ComfyUI check runs it beside classic and Nodes 2.0.
2026-11-17 23:34:19 -06:00
ausboss 78312c7bf5 Image Compare: save the picture it rests on, B for a new node
A new node rests on B, the after picture, and saves that with the
workflow. Right-click the node to rest on A instead. A workflow saved by an
earlier version has no saved side: it is worked out from the links as
before and held in memory, so older workflows show what they did and do not
open marked as changed. It is written only when a side is picked.
2026-11-17 23:21:43 -06:00
ausboss 16796566c4 Image Compare: rest on the result when the before comes out of a switch
A before picture that is a switch, handing on your picture for an edit and
the result for a new picture, is fed by the result. The panel read that as
the before being made from the result and rested on it. A switch now only
counts as made from the other picture when one branch is and no branch can
hand on the picture that one started from; a picture the other side can
hand on is the result.
2026-11-17 22:44:32 -06:00
ausboss 3f36952095 Merge pull request #371 from ausboss/fix/blocked-pixel-reads
Show the crop node's picture where the browser blanks pixel reads
2026-11-17 22:43:34 -06:00
ausboss 0f4bd5b135 Draw the crop node's picture where the browser blanks pixel reads
Some browsers and privacy add-ons return blank pixels when a page reads a
canvas. The see-through check read that as a fully see-through picture,
so the stage drew nothing. Probe pixel reads once per page and draw the
picture as it is when they cannot be trusted.
2026-11-17 22:36:57 -06:00
ausboss 8a5fbfe1fb Layout Boxes: drop an unused import 2026-11-17 20:31:01 -06:00
ausboss f6503cc7af Layout Boxes: h3_prompt output for MiniMax H3 Image
A fifth output says the boxes in words for MiniMax H3 Image: where each
box is across and up and down, how much of the frame it takes, and which
box it stands beside. The picture on background is <Picture 1>. An
object box with no description takes the next reference picture.

Places are said only in words, never as coordinates: H3 Image draws
numbers from the prompt onto the picture as text. The help page leads
with descriptions that name the picture and the pose ("the man from
<Picture 2>, sitting on the couch"). With those, people land in their
boxes far more often than with empty boxes.
2026-11-17 20:21:04 -06:00
ausboss 51993c0a2c Merge pull request #367 from ausboss/release/2.26.3 2026-11-17 14:12:39 -06:00
ausboss b043f6f1a7 Merge pull request #365 from ausboss/fix/stitch-tone-match 2026-11-17 14:12:27 -06:00
ausboss 29c986cfdc Merge main into release/2.26.3 2026-11-17 19:02:33 +00:00
ausboss 171ad422b9 Merge pull request #368 from ausboss/registry-scan-fixes 2026-11-17 13:01:54 -06:00
ausboss f4061f4255 Accept either answer for a thumbnail inside a looping link
Python 3.12 raises on the loop while resolving and answers 400; 3.13
resolves it and answers 404. Neither names the path.
2026-11-17 18:57:30 +00:00
Kurdin Bekes Berwari 9d7bcfbfb6 Fix image previews for filenames with leading spaces
Preserve filename whitespace when building image preview URLs. Trimming caused files with leading spaces to fail to display in Image Crop + Rotate + Pad and other nodes using the shared parser.
2026-11-17 19:13:20 +01:00
ausboss 8d139cdfc5 Merge branch 'main' of https://github.com/ausboss/ComfyUI-AusBoss into fix/stitch-tone-match
# Conflicts:
#	CHANGELOG.md
2026-11-17 11:58:55 -06:00
ausboss fae68ecb77 Merge pull request #358 from ausboss/codex/fix-crop-image-copy
Copy original pictures by default with optional edits in the gear menu
2026-11-17 11:53:33 -06:00
ausboss 661c33a926 Merge remote-tracking branch 'origin/main' into codex/fix-crop-image-copy
# Conflicts:
#	CHANGELOG.md
2026-11-17 17:52:23 +00:00
ausboss 9b27bc9c4c Merge pull request #363 from ausboss/fix/looks-line-same-line
H3 Prompt Writer: a swap reads the new person's looks however they are typed
2026-11-17 11:51:58 -06:00
ausboss de530e2eac Merge remote-tracking branch 'origin/main' into codex/fix-crop-image-copy
# Conflicts:
#	CHANGELOG.md
2026-11-17 17:24:29 +00:00
ausboss 7d81a43133 H3 Prompt Writer: split a looks sentence off only after a full stop
"Put @1 looks like a friend here." was cut into "Put" and a looks line
for @1, because the split happened after any character. Now it happens
only where a new sentence starts (after ".", "!" or "?"), so the typed
swap line "with @1 .@1 looks like ..." still splits and a sentence that
merely holds the words stays whole. test_h3_swap_appearance passes again,
and test_h3_prompt_writer checks both cases.
2026-11-17 17:24:00 +00:00
ausboss 0067575b0c Merge branch 'main' of https://github.com/ausboss/ComfyUI-AusBoss into fix/stitch-tone-match
# Conflicts:
#	CHANGELOG.md
2026-11-17 11:23:08 -06:00
ausboss 8cc90794d8 Merge main into fix/looks-line-same-line 2026-11-17 11:23:08 -06:00
ausboss d82ed510b9 Merge pull request #362 from ausboss/fix/h3-writer-all-lines
H3 Prompt Writer: every line in a row is spoken, and a looks line keeps only the looks
2026-11-17 11:17:38 -06:00
ausboss 3f06362f9c Merge pull request #359 from ausboss/fix/h3-writer-video-jobs
H3 Prompt Writer: more video jobs work, carry a line across a cut
2026-11-17 11:17:14 -06:00
ausboss d37e0cd026 Merge pull request #366 from ausboss/docs/skill-example-count
Agent skill: Person Swap page now has 4 examples
2026-11-17 11:17:04 -06:00
ausboss 38bdddded8 Keep tool attribution off commits and PRs 2026-11-17 17:03:06 +00:00
ausboss f0f6ca9f0c Check names as text before the disk and keep paths out of errors
LoRA routes match a name against ComfyUI's list before any lookup.
Image Folder refuses drive letters and control characters anywhere in a
name, checks the joined path before resolving it, and sends a hash in
place of each picture's size and time. Library errors keep their kind
and drop their words when they name a server path.
2026-11-17 17:03:06 +00:00
ausboss d47a6743e3 Release 2.26.3 2026-11-17 16:38:19 +00:00
ausboss ab8389d598 Match new content to the picture beside it when Tone match is on
Skin painted where a shirt was has no before of its own to be read
against, so Tone match left it as painted. It is now compared with the
untouched picture right beside it and matched where the two look alike.
Something different from what is beside it is still left as painted.
2026-11-16 23:19:08 -06:00
ausboss 5b10b3a23f Leave new content as painted when Tone match is on
When the painted area held something new, the inside reading stood down
and the soft edge was read instead. A model that repaints the edge too
puts the new colour there, so that reading took the new colour for drift
and shifted the whole patch the other way: a yellow swimsuit over skin
came back with blue skin and a blue wall.

New content now holds at a zero shift. The edge is read only when the
rim is too small to judge.
2026-11-16 21:45:28 -06:00
ausboss f2d966afd1 Read the inpaint's tone drift at the size the model painted
The reading inside the painted area ran at the pasted size. On a large
picture that made the stitch several times slower, and its 32 px rim was a
sliver at the very edge of what the model painted, where the colour drifts
least.

It is now taken at the model's size and the rim is found with one pass
along each axis. A 3072 px crop reads in 2.6 s instead of 16 s on a CPU, and
a picture of any size is read the same way.
2026-11-16 20:20:23 -06:00
ausboss 182abca56f Agent skill: Person Swap page now has 4 examples 2026-11-16 19:50:23 -06:00
ausboss c1c9831378 Read an inpaint's tone drift inside the painted area
Tone match on Stitch Inpaint barely moved the colour of an inpaint. The
drift was read from the soft edge of the patch, where the sampler had
mostly kept the original, so only a fraction of it was measured.

An inpaint is now read just inside the fully painted area: the middle
colour change of the same pixels in a 32 px rim. It is used when at least
half of those pixels agree and the change is 20 LAB or less; new content
keeps the old reading and is left as painted. Outpaints, blend in and
Tone match 0 are unchanged.

Fixes #361
2026-11-16 18:59:55 -06:00
ausboss 6418940761 Merge branch 'main' of https://github.com/ausboss/ComfyUI-AusBoss into fix/h3-writer-video-jobs
# Conflicts:
#	CHANGELOG.md
2026-11-16 14:09:31 -06:00
ausboss 72af858975 Merge main into fix/looks-line-same-line 2026-11-16 14:09:24 -06:00
ausboss 80e5221403 Merge pull request #364 from ausboss/docs/agent-skill
Add an agent skill for the video workflows
2026-11-16 14:08:32 -06:00
ausboss f658ac58b0 Add an agent skill for the video workflows
npx skills add ausboss/ComfyUI-AusBoss installs skills/ausboss-workflows:
how to write the words for the MiniMax H3 Pika Person Swap and Pika Remix
workflows, which model files to get, and how to run a workflow in ComfyUI.
The folder stays out of the Registry archive.
2026-11-16 13:55:12 -06:00
ausboss adb1eaacc4 H3 Prompt Writer: read a swap's looks sentence on the same line, and clothes on their own line
Both were dropped without a message, so the swap ran with no description of
the new person and the clip often came back unchanged.
2026-11-16 12:25:33 -06:00
ausboss b0f8b5ec55 H3 Prompt Writer: a Chinese or Japanese line keeps its own full stop
Spoken words ending in 。 got a second full stop ('。.'), and words ending
in a full-width comma got ',.'. Those count as line ends now, and a line
in Chinese or Japanese that needs a stop gets 。.
2026-11-16 12:25:19 -06:00
ausboss a3984bf656 H3 Prompt Writer: every line in a row is spoken, and a looks line keeps only the looks
A line holding two quotes, like '"Get a job." @1 looks up and says "What?"'
or '@1 says "Hi" and @2 says "Bye"', was one moment, and only its first
quote reached the prompt. A quote followed by an @ (or by 'and @2') now ends
the moment.

A swap's '@1 looks like' line took the whole line as the appearance, so a
later sentence such as 'The trees behind @1 stay the same.' went into the
description with a raw @1. A sentence there that names an @ again is read
as its own script line.

Spoken words that end in a comma ('"Hi," she says') end in a full stop
instead of ',.'.
2026-11-16 11:50:03 -06:00
ausboss 232e1dcdb7 H3 Prompt Writer: more video jobs work, carry a line across a cut
- Copy its moves with no person picture keeps the video's own person and
  takes its length from the video.
- Change something with a place or style picture restyles the video from
  the picture, and an empty clip no longer gets a made-up person.
- A thing picture that the lines make do the action takes the moves in its
  own look; a held or worn thing stays a prop.
- Words ending in "..." carry across the next cut once, or end the clip
  mid-sentence on the last line.
- Clips can be 4 seconds long.
- The job lists on the chips are the node's own menu and take a click.
2026-11-15 20:05:06 -06:00
ausboss ab67a1f77f Copy the original picture by default with optional edits in settings 2026-11-15 19:05:26 -06:00
ausboss 2af3fd9c83 Fix crop image clipboard copies including editor controls 2026-11-15 16:36:14 -06:00
ausboss 9986ded109 Merge pull request #356 from ausboss/fix/cache-guard-version-order
Ask for a reload only when the pack is newer than the page
2026-11-14 18:00:18 -06:00
ausboss 197ac04a8c Ask for a reload only when the pack is newer than the page
The update guard asked for a reload whenever the server's version and the
page's differed. After the Manager switches the pack on disk, the server
keeps reporting the old version until ComfyUI restarts, so a reload in
between loads the new files and the message said the page was older when
it was newer.

Now the guard speaks only when the server's version is the newer one, and
versions compare part by part as numbers. A version that is not three
plain numbers, such as "unknown", stays silent.

A page newer than the server stays silent rather than asking for a
restart: from two version numbers it cannot be told apart from a downgrade
with the tab left open, which needs a reload, and the Manager already asks
for its own restart after a switch.
2026-11-14 17:47:11 -06:00
ausboss be2a2a1444 Merge pull request #355 from ausboss/release/2.26.2
Release 2.26.2
2026-11-14 10:58:10 -06:00
ausboss 76eb4fc7e7 Release 2.26.2 2026-11-14 10:57:05 -06:00
ausboss 057f2bd05a Keep refused file names, script addresses and held runs off the disk
Three findings from the Comfy Registry's review of 2.25.2, all still in
2.26.1:

- The change check of Load Image, Load Image + Pad, Image Crop + Rotate +
  Pad and both Video Crop + Rotate + Pad nodes handed a value its resolver
  had refused to os.stat and Path.resolve. stable_file_fingerprint now
  opens only a Path a resolver returned; a refused value is hashed as text.
- The script version tagging joined the request's address to the js folder
  and resolved it before checking it. It now looks the address up in a
  list of the pack's scripts made at startup.
- Save Image's keep route read the run's list from a JSON file in the temp
  folder, which takes uploads, and built the copy source from its
  extension, so a planted list could copy a server file into output. Runs
  now stay in memory (the last 256), held pictures are named from the
  token, their number and Save Image's own formats, must sit directly in
  the held folder, and a run holds at most 10,000 pictures.
2026-11-14 10:56:27 -06:00
ausboss 172252ab02 Merge pull request #353 from ausboss/release/2.26.1
Release 2.26.1
2026-11-14 07:09:37 -06:00
ausboss ebc81ea57e Release 2.26.1 2026-11-14 07:08:54 -06:00
ausboss bc235e96e5 Merge pull request #352 from ausboss/fix/no-home-path-expansion
Stop expanding ~ paths and opening a typed LaMa model path
2026-11-14 06:53:14 -06:00
ausboss 6572b49386 Stop expanding "~" paths and opening a typed LaMa model path
Image Folder compared a pasted "~/..." path after expanding it; only a
path written out in full is compared now. LaMa Inpaint resolved a typed
path when ComfyUI's folder list was missing; it only takes a name from
models/lama now. Neither could read outside ComfyUI's folders, but both
read like it to a code scan.
2026-11-14 06:28:13 -06:00
ausboss d593e01fc9 Merge pull request #351 from ausboss/release/2.26.0
Release 2.26.0
2026-11-14 06:21:08 -06:00
ausboss 009aa95d98 Merge remote-tracking branch 'origin/main' into release/2.26.0 2026-11-14 06:12:49 -06:00
ausboss b61b3efc94 Merge pull request #350 from ausboss/feat/clip-timing
Clip timing as Start, Duration and Ends at, on the clip node, Load Video and Load Audio
2026-11-14 05:58:07 -06:00
ausboss 6cfed25a8e Timing wording follows the new boxes
Backend tooltips and descriptions, the README and the help pages say
Start, Duration and Ends at where they still said IN, OUT, Length or
Max length. Load Video's help no longer says a typed 0 runs to the end:
Whole video does that.

Load Video's timing card refreshes when a wire is connected or removed.
The old Length switch function is gone from the timing card.
2026-11-14 05:42:17 -06:00
ausboss 27e175aa08 Release 2.26.0 2026-11-14 05:31:40 -06:00
ausboss 6224bae13c Timing boxes: App mode fields, Duration 0, one link reader
Every nth, the frame limit and the audio Duration are hidden by the
widget card again, so App mode can still show them as fields.

Load Audio: an empty or 0 Duration runs to the end of the file, and a
box whose linked value is only known at run time stays empty. The rules
for what a pick stores are in audio_window.mjs with tests.

The shared link reader asks the frontend for an input's link before
reading the link table, and Layout Boxes and H3's clip lookup use it
alone.
2026-11-14 05:28:02 -06:00
ausboss bd49afae19 Merge main: keep both sets of Unreleased entries 2026-11-14 05:28:02 -06:00
ausboss 13e4d73dbd Merge pull request #347 from ausboss/feat/app-mode-cards
Make App mode work with AusBoss nodes: card fields, found models, clip upload
2026-11-14 05:17:16 -06:00
ausboss 37584519e8 Merge pull request #349 from ausboss/fix/lora-in-missing-models
List missing LoRAs in ComfyUI's missing-models list
2026-11-14 05:16:45 -06:00
ausboss 1ed921b6fb Load Video and Load Audio on Start, Duration and Ends at
Load Video uses the clip node's timing card: Start, Duration and Ends at
replace the IN/OUT fields and the Limit row. Its face reads the frame
count from the file, so a 247-frame clip no longer shows 248.

Load Audio gets the same three boxes in place of IN/OUT and Max length;
the Duration is the max_seconds widget, so saved values are unchanged.

One linked-number reader (linkOrigin) follows Reroutes, subgraphs and
older Primitive nodes for the clip node, both loaders and Layout Boxes.
2026-11-14 04:07:29 -06:00
ausboss 15e5803a06 List LoRA Loader's missing files in ComfyUI's missing-models list
ComfyUI builds its missing-models list (the Issues panel and Download all)
from list widgets only. LoRA Loader keeps its files in the rows' text, so a
LoRA a workflow needs was never listed, and Download all then Run stopped on
'missing LoRA file'. Each row that needs a file now gets a hidden list widget
holding its name: kept out of the saved workflow and the prompt, with no
socket, made again from the rows whenever they change. A replacement picked
in the Issues panel goes back to its row.
2026-11-14 03:57:14 -06:00
ausboss a0327f6ddd Clip timing as Start, Duration and Ends at
The clip node's Length on/off switch is replaced by three boxes. Dragging
the start moves the clip, dragging the end or typing a Duration changes
its length, and a seconds | frames switch picks the units. Extra details
moved into hover text, and a note shows only when something needs fixing.

With a linked frame rate, the latest start was worked out on the source
frame grid, so a typed start of 60 settled on 7. It now uses the output
rate. A rate typed inside a subgraph is followed, so Person Swap shows its
clip length before a run. A cap the video cannot fill says so, and Ends
at no longer runs past the video's last frame.

H3 Prompt Writer shows how many of the clip's frames H3 makes. The Crop +
Rotate + Pad panel rows fill the node's width instead of stopping at
460 px, and the size line drops its empty warning row.

Frontend only: inputs, outputs and saved values are unchanged.
2026-11-14 03:27:00 -06:00
ausboss e65612bb28 Merge main: keep the tile snap entry and the App mode entries in Unreleased 2026-11-14 02:55:58 -06:00
ausboss 11d79b252d Merge pull request #348 from ausboss/fix/tile-snap-visible-edge
Snap tiles by their visible card
2026-11-14 02:52:00 -06:00
ausboss 7e5cadaa06 Snap tiles by their visible card
A frameless tile (link, title or note tile) draws a card inside a wider
transparent node. Snap into line and Line up measured the node, so tiles
lined up with a gap around them. A tile also moves itself and keeps its
pointer moves to itself, so Snap into line never saw a tile being dragged.

The tile now names its card as its outline, and its drag reports each
move to Snap into line once the tile is placed. The move itself still
stops at the tile: letting it through made Nodes 2.0 pan the canvas.
2026-11-14 01:59:46 -06:00
ausboss 94d302e112 Contributor guide: App mode needs upload flags on file lists 2026-11-13 23:15:34 -06:00
ausboss fb26f3ae06 Let the video crop nodes take uploads in App mode
Their video list did not carry video_upload, so in an App mode form the
clip field was a bare list with no way to upload a clip, while the picture
field next to it had a picker and an Upload button. Both video crop nodes
now declare the flag, as Load Video does. ComfyUI adds its upload button to
the node, which the crop panel already hides, so the node face is unchanged.
2026-11-13 21:58:15 -06:00
ausboss 11638b0557 Pick a model the user already has in a subfolder without a click
A workflow saved with a bare model name opens with that loader red when
the user keeps the file in a subfolder. The Guide already found the copy
and offered Use it; App mode shows no Guide, so the form opened with
"2 issues found" and Run blocked. Now the Guide points the loaders at the
copy as the workflow opens, when there is exactly one, and says so in a
toast. Two copies in different subfolders still get the Use it button.
Setting AusBoss.Models.PickFoundCopy (on by default) turns it off.
2026-11-13 19:41:17 -06:00
ausboss ad81fbcca1 Show card widgets as real controls in App mode
App mode reads the same hidden flag the pack's cards set on the widgets
they replace, so every field from a carded node (Load Image, the video
loaders, H3 Prompt Writer) drew an empty row in the form. While the open
workflow is in App mode, the widgets its form lists are now shown; back in
the graph they are hidden again, so node faces do not change.

showWidget also stops leaving computeSize, computeLayoutSize and draw
behind as own undefined properties: the frontend took those for a
custom-drawn widget and picked the legacy renderer.
2026-11-13 19:04:50 -06:00
ausboss 9cc91ffba8 Merge pull request #346 from ausboss/fix/playhead-readout-hint
Release 2.25.3
2026-11-13 15:15:54 -06:00
ausboss 0450466422 Release 2.25.3 2026-11-13 15:15:00 -06:00
ausboss d5442cd659 Explain the video clip's frame readout in plain words
The readout beside Play (fr 52 · 0:02.17) now says on hover which frame
the picture shows and how many seconds into the video it is, and the
help page explains it.
2026-11-13 15:12:53 -06:00
157 changed files with 8674 additions and 1242 deletions
+6
View File
@@ -0,0 +1,6 @@
{
"attribution": {
"commit": "",
"pr": ""
}
}
+4
View File
@@ -24,6 +24,10 @@ SECURITY.md
.claude/
/docs/
# the skill an AI agent installs from the repository (npx skills add);
# nothing in the pack loads it
/skills/
# README media: GitHub shows it on the repository page, nothing in the
# pack loads it
/assets/
+5 -2
View File
@@ -13,7 +13,9 @@ name: ComfyUI updates
# and required input the example workflows use.
# 4. scripts/dev/face_smoke.mjs puts every node on a graph in headless
# Chrome, in the classic node view and in Nodes 2.0: its face comes up
# and nothing throws.
# 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.
#
# 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
@@ -117,7 +119,7 @@ jobs:
echo "ComfyUI did not come up"; tail -60 "$GITHUB_WORKSPACE/comfyui.log"; exit 1
- name: Every node is offered and every example still fits
run: python ComfyUI-AusBoss/scripts/compat_boot.py --url http://127.0.0.1:8188 --log comfyui.log
- name: Every node's face comes up, classic and Nodes 2.0
- name: Every node's face comes up, classic, Nodes 2.0 and a privacy browser
run: |
google-chrome --headless=new --remote-debugging-port=9333 --no-sandbox --disable-gpu --disable-dev-shm-usage \
--user-data-dir="$RUNNER_TEMP/chrome" about:blank > "$GITHUB_WORKSPACE/chrome.log" 2>&1 &
@@ -125,6 +127,7 @@ jobs:
status=0
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
exit "$status"
- name: ComfyUI's log
if: ${{ always() }}
+344
View File
@@ -2,6 +2,350 @@
All notable changes to ComfyUI-AusBoss are documented here.
## 2.26.7 - 2026-11-21
- **An old copy of the pack that keeps loading now says so in the browser.**
With an old git clone in `custom_nodes/ComfyUI-AusBoss` and a newer
Manager install in `custom_nodes/ausboss-nodes`, the old clone loads,
because copies from before 2.24.0 cannot step aside. Every node added
since, such as Edit Lock, then shows as missing, and updating does not
help. The newer copy now shows a message in ComfyUI that names the old
folder to delete. Before, the only sign was a line in the console.
- **Workflow Note: a missing AusBoss node asks for an update, not a GitHub
clone.** When a workflow needs an AusBoss node your version doesn't have,
the note's AusBoss row now shows **Update**. It opens ComfyUI-Manager's
updates list and says to restart afterwards. Before, the row showed
**Get it**, which opened GitHub, and cloning from there added a second
copy of the pack. **Detect from this workflow** now lists the pack as
AusBoss nodes with its Comfy Registry link, whatever folder it is in.
- **LoRA Loader: set a LoRA's strength with a wire.** Drag a number wire,
from a slider or a Float node, onto any row and that row's strength follows
it. The row's box turns dashed teal and shows the number coming in; click
it to find the source, or right-click the row to unlink. The CLIP strength
keeps its ratio to the model strength (#388).
- **Node faces show Chinese when ComfyUI's language is Chinese.** The
labels, buttons, choices and tooltips the pack draws on its nodes, such as
the cards on FlashVSR and Image Resize, H3 Prompt Writer, Workflow Switches
and the video and image crop faces, now follow Settings > Language
(Chinese, in Simplified characters). Reload the page after changing the language. Nothing
saved in a workflow changes, and text with no Chinese yet stays English.
H3 Prompt Writer's socket names are translated too.
- **H3 Prompt Writer: see and change the full prompt.** A new **Full
prompt** tab at the top of the node shows the prompt it wrote on its last
run. Edit it there, for example to take out one camera move, and H3 gets
your text as it is. An amber dot shows an edit is being sent, and **Reset
to written** goes back to the node's own prompt. The **Simple** tab works
as before and stays the default.
- **Latent Size's ratio chips keep your megapixels.** Clicking a ratio chip
now changes the shape at the size you set, instead of jumping back to about
one megapixel. The old jump is still in the gear: turn off **Chips keep
current budget**. The setting is kept in the browser, so a private window
forgot it every time; it now starts on.
- **The pack loads on Python 3.10 again.** On a 3.10 install, such as some
Stability Matrix setups, the whole pack failed to load with
`No module named 'tomllib'`. It now loads there with nothing extra to
install (#387).
- **Workflow Note finds models in Stability Matrix's shared folders.**
A row whose folder uses an old name, `clip` or `unet`, was never checked
("This install has no model folder") even with the file in place. Those
rows are now checked like `text_encoders` and `diffusion_models`, the
names ComfyUI files them under. When the install also reads a kind of
model from a folder with a different name, such as Stability Matrix's
`Data/Models/Lora`, the card names that folder under the usual one, so
you know where your files are found and where a new one can go (#386).
## 2.26.6 - 2026-11-20
- **Image Toolbox's help page says what happens with too many pieces.**
Asking for more pieces than the picture is wide in pixels gives one piece
per pixel column, so fewer pieces than asked for. The page now says so.
## 2.26.5 - 2026-11-20
- **New node: Image Toolbox.** Small picture jobs in one node: pick the job
from a list. Its first job, split sheet at gaps, cuts a row of pictures
such as a character sheet's four views into separate pictures. Each cut
goes to the gap between two pictures instead of an equal share of the
width, so no piece gets part of its neighbour's sleeve. The pieces come out
as one batch of the same size, padded with the sheet's backdrop colour.
- **Box edits on big photos start much sooner.** Crop For Inpaint,
Image Crop + Rotate + Pad and Stitch Inpaint grew and softened their
masks across the whole picture, even when the box was small or there was
nothing to do. On a 17 MP photo that took about 5 seconds before the
model started. The work now covers only the area around the mask:
Crop For Inpaint went from 3.1 s to 0.14 s, and Image Crop + Rotate + Pad
with nothing to do from 2.2 s to 0.5 s. The results are the same pixels.
- **Stitch Inpaint can paste past the box.** Edit models that redraw the
whole crop, such as MiniMax H3 Image, often draw a new boot, a plate rim
or a collar a little past the box, and the paste cut it off at the box's
edge. Turn on the new **Follow changes** switch: the paste then grows to
every change that touches the box, and fades out before the edge of the
crop. It first undoes the small zoom or shift such a model can draw, so
the wall or table around the edit lines up again. When the model redrew
nearly everything around the box, the paste stays the box. It is off by
default, so saved workflows paste exactly as before.
- **LoRA Loader's + LoRA list opens with its folders folded.** A big LoRA
folder now opens as a short list of top folders. **Open all** and
**Fold all** beside the search box open or fold every folder at once,
and **Alt**- or **Shift**-click on a folder's arrow does the same for
that folder and every folder inside it. **Left** on a highlighted file
folds the folder it is in and moves up to it. To keep the old way, where
the list opens as you left it, set **Settings → 🆎 AusBoss → LoRA Loader
→ Picker folders** to **Remember my folds**.
## 2.26.4 - 2026-11-18
- **A video upload stops at 4 GB.** Dropping a video on Load Video had no
size limit, so a huge file could fill the input folder. An upload over
4 GB is now refused with a message, and the partly saved file is removed.
- **Image Crop + Rotate + Pad shows your picture in every browser.** Some
browsers and privacy add-ons (Firefox's fingerprint protection, Brave
Shields, canvas blockers) blank a picture when a page reads its pixels.
The node read that as a fully see-through picture and drew an empty stage,
although the size line and the run were right. It now checks first and,
where reads are blocked, draws the picture as it is; only the teal tint
over see-through parts is missing there.
- **Image Compare A/B always rests on the same picture.** While the
pointer is away, a new node shows B, the "after" picture. To show A
instead, right-click the node; the choice is saved with the workflow.
Earlier versions worked the side out from the links on every run, and a
workflow whose "before" came out of a switch showed the before. A
workflow saved by an earlier version keeps showing the picture it did.
- **Layout Boxes 🆎 places people for MiniMax H3 Image.** A new
`h3_prompt` output says the boxes in words: who goes where, how big, and
who stands beside whom. Describe each person in their box by their
picture and what they do, such as "the man from <Picture 2>, sitting on
the couch"; the scene on `background` is `<Picture 1>`. Places are said in
words only, because H3 Image draws numbers from a prompt onto the picture.
- **H3 Prompt Writer's Camera says "from the video" when the video sets
the camera.** With a clip wired to copy its moves, swap the person, give it
a new voice or change something, the first Camera choice now reads "from
the video": the camera does what it does in the clip. It is the same
choice as "as typed", so saved workflows are unchanged.
- **A picture whose name starts with a space now shows its preview.** The
name was trimmed before the preview was asked for, so Image Crop + Rotate
+ Pad and the other nodes that share that code looked for a file that
did not exist.
## 2.26.3 - 2026-11-17
- **Tone match now works on inpaints.** On a Crop For Inpaint 🆎 crop,
Stitch Inpaint 🆎 read the colour shift in the soft edge around the
painted area. Workflows such as Krea 2 Inpaint Masked let the model paint
a little wider than that edge, so the edge came back close to your picture
and the slider hardly did anything: in a test on skin it took off a
third of the shift at 1. It is now read just inside the painted area and
takes off more than half, on a picture of any size. A workflow that already had Tone match on for
an inpaint gives a slightly different picture, closer to the original's
colour. When the painted area holds something new, it is matched to your
picture right beside it where the two look alike, such as new skin where
a shirt was. Something different from what is beside it, such as a
swimsuit over skin, is left as painted; before, Tone match could tint the
whole patch with the opposite colour. Outpaints, blend in and Tone match 0
are unchanged.
- **Copy a crop node's picture without its handles.** Right-click the picture
on Image Crop + Rotate + Pad and choose Copy image. By default it copies
the original picture. To include crop, rotation, padding and resize, turn
on Copy with crop, rotation and padding in the gear menu. Editing controls
and guides are never copied. Open image provides a clean
picture to copy with the browser on plain HTTP addresses too.
- **H3 Prompt Writer: a swap reads the new person's looks however you type
them.** `@1 looks like ...` on the same line as the swap sentence, and
clothes on a line of their own (`@1 is wearing a black suit.`), were
left out of the prompt without a word, and the clip often came back
unchanged. Both are now used.
- **H3 Prompt Writer no longer drops lines.** When one line held two
people talking, like `The phone says: "Get a job." @1 looks up and says:
"What?"`, only the first words reached the prompt. Each quote is its own
moment now. A swap's `@1 looks like` line also keeps only the looks: a
sentence after it that names an `@` again, like `The trees behind @1 stay
the same.`, is read as its own line instead of going into the description
with a raw `@1`. `"Hi," she says` is spoken as "Hi." instead of "Hi,.",
and a Chinese or Japanese line keeps its own full stop: "。", not "。.".
- **H3 Prompt Writer can carry a line across a cut.** End the words with
`...` and the person keeps talking into the next shot, without saying the
words twice. On the last line, `...` lets the clip end mid-sentence. A line
too long for its shot carries on the same way instead of a warning.
- **H3 Prompt Writer makes 4-second clips.** The shortest length went from
5 to 4 seconds.
- **H3 Prompt Writer can put the person from your video somewhere new.** With
Copy its moves and no person picture, the person in the video keeps their
own look and moves. Give a picture the job place and type `He dances in @1.`
Before, the node asked for a person picture and stopped. Copy its moves
also takes its length from the video now, like Swap, Change something and
New voice.
- **H3 Prompt Writer can restyle a video from a picture.** With Change
something and a style or place picture, the look comes from the picture
instead of the video. Type `It looks like @1.` A clip with nobody in it,
like an empty hallway, no longer gets a made-up person in its prompt.
- **H3 Prompt Writer can make a thing do the moves.** With Copy its moves or
Swap the person and no person picture, a thing picture your lines make do
the action (a cartoon hand, a toy) takes the moves in its own look. A thing
that is held or worn stays a prop.
- **H3 Prompt Writer's job lists take a click again.** Picking a job from a
chip's list closed the list without changing the job.
- **H3 Prompt Writer's job lists match the node.** The pick list on each
picture and on the video opens under its chip in the node's own colours
and grows with the zoom. Before, it was the browser's small plain list.
- **An AI agent can now learn the video workflows from the repository.**
`npx skills add ausboss/ComfyUI-AusBoss` gives your agent a skill for the
MiniMax H3 Pika Person Swap and Pika Remix workflows: how to write the
words, which model files to get, and how to run a workflow in your
ComfyUI. The same page is at https://ausboss-examples.vercel.app/skill.md.
- **The "AusBoss was updated" message no longer asks for a reload by
mistake.** After the Manager switched the pack to another version, a
page reload before ComfyUI restarted brought up the message, telling you
the page was older than the pack when it was newer. A restart was what
was needed. Now the message only comes up when the pack really is newer
than the page, and versions such as 2.25.10 and 2.25.9 are compared as
numbers.
- **LoRA routes only open files on ComfyUI's LoRA list.** The LoRA
Loader's info, hash and preview routes used to hand the name they were
given to ComfyUI's file lookup and check the answer afterwards. Now the
name is matched against the list first, and a name that is not on it is
refused before anything on disk is looked up.
- **Image Folder 🆎 checks a folder or picture name as text before the
disk.** A drive letter in the middle of a name, or a control character,
is refused like `..`, and the joined path is checked before it is
resolved as well as after. The list no longer sends each picture's size
and time; the thumbnail's cache tag is a short hash instead.
- **Error messages no longer pass on server paths.** When a model,
decoder or encoder fails, its message can name a file on the server's
disk. SAM 3 masks, LoRA loading and video saving now keep the kind of
error and drop its words when they name a path, since node errors reach
the browser and stay in the history.
## 2.26.2 - 2026-11-14
- **Loaders never look up a file name they refused.** Before each run,
Load Image 🆎, Load Image + Pad 🆎, Image Crop + Rotate + Pad 🆎 and both
Video Crop + Rotate + Pad nodes check whether their file changed. When the
name was one they do not accept, such as a whole path or a network share,
that check still looked it up on disk. On Windows, looking up a share
contacts its server and hands it the computer's login. Now a refused name
is only compared as text.
- **The pack's scripts are found without looking up the address.** The pack
tags its scripts with a version as the browser asks for them. It found
each one by joining the address the browser sent to its own folder and
looking the result up on disk, and only then checked that the file was
its own. Now it looks the address up in a list of its scripts made when
ComfyUI starts, so no address reaches the disk.
- **Save Image's Save button copies only pictures it holds.** With Auto
save off, the list of a run's held pictures was a file in ComfyUI's temp
folder. That folder takes uploads, so a planted list could copy another
file on the server into the output folder. The list now stays in
ComfyUI's memory, and a held picture is found only by its run, its number
and one of Save Image's formats. The Save button works for the last 256
runs, up to 10,000 pictures each; held pictures still go when ComfyUI
restarts, as before.
## 2.26.1 - 2026-11-14
- **A path that starts with `~` is no longer expanded.** Image Folder used
to turn a pasted `~/...` path into a full one before checking that it sits
inside ComfyUI's folders; now only a path written out in full is checked.
LaMa Inpaint only opens a model from ComfyUI's `models/lama` list. Nothing
outside those folders could be read before either; this removes the code
that looked as if it could.
## 2.26.0 - 2026-11-14
- **Missing LoRAs show in ComfyUI's missing-models list.** When a workflow
needs a LoRA you don't have, ComfyUI's Issues panel now lists it with the
other missing models, so **Download all** fetches it too. Before, the
list skipped every LoRA in a LoRA Loader 🆎, and Run then stopped on
"missing LoRA file". A LoRA that moved to another folder, or a row that is
switched off, is not listed.
- **Link tiles and title tiles snap by the edge you see.** A tile draws a
card inside a wider see-through frame, and Snap into line used that frame,
so tiles lined up with a gap around them, and a tile you dragged never
snapped at all. Now a dragged tile lines up, and other nodes line up with
it, by the card's own edges.
- **Cards work in App mode.** App mode is ComfyUI's simple form view of a
workflow: a few labelled fields and a Run button. A field from a node
with a card (a picture or video loader, H3 Prompt Writer) used to show
as an empty row there. Now it shows a real control: a file list with an
upload button, a video list, a text box. Back in the graph, the node
looks the same as before.
- **The video crop nodes take uploads in App mode.** Video Crop + Rotate +
Pad and its Clip version now tell ComfyUI that their video list takes
uploads, as the picture nodes do. In App mode the clip field gets the same
picker as a picture field: your videos as thumbnails, an Upload button and
a folder button. On the node itself nothing changes.
- **Models you already have are picked for you.** When a workflow asks for
a model file you keep in a subfolder (`minimax-h3/model.safetensors`),
ComfyUI used to mark its loader red until you clicked **Use it** on the
workflow's Guide. Now the Guide switches the loader to your copy as the
workflow opens and says so in a short message. That matters most in App
mode, which shows no Guide to click. With two copies in different
subfolders it still asks. Turn it off in Settings, 🆎 AusBoss, Models.
- **The video clip's timing is three boxes: Start, Duration, Ends at.** On
Video Crop + Rotate + Pad (Clip), the Length on/off switch is gone. Drag
the start to move the clip, drag the end or type a Duration to change how
long it is, and switch between seconds and frames. Details sit in hover
text; a short note shows only when something needs fixing, with a button
to fix it. Saved workflows open with the same values and run the same.
- **A linked frame rate no longer stops the clip's start too early.** With
a rate wired in, a typed start of frame 60 used to settle on frame 7; it
now lands where you put it, and the start handle stops only where the
Duration no longer fits. A rate set inside a subgraph now counts as
known, so the clip shows its length before you run.
- **Linked clip lengths say where they come from.** A box set by another
node shows a **linked** button that jumps to that node. A cap that the
video cannot fill says how many frames you get, and a count only known
when the graph runs shows the room left after the start.
- **H3 Prompt Writer says how much of the clip H3 uses.** When the video
comes from the clip node, it shows how many of the clip's frames H3
makes and where in the video that stops, and which Durations use all of
it.
- **Crop + Rotate + Pad panels fill the node's width.** The rows under the
picture used to stop at 460 px and sit in the middle of a wide node.
- **Load Video uses the same timing boxes as the clip node.** Start,
Duration and Ends at replace the IN and OUT fields and the separate
Limit row, with the same seconds | frames switch. Saved workflows open
with the same values and run the same.
- **Load Video counts the frames the file really has.** The face used to
work the count out from the length and could say one frame too many (248
for a 247-frame clip); it now reads it from the file.
- **Load Audio has Start, Duration and Ends at boxes.** They replace the IN
and OUT times and the separate Max length row, so the red "cut" stripe is
gone: the Duration is the length you get.
- **A number wired through a Reroute or a subgraph now shows on the face.**
The clip node, Load Video, Load Audio and Layout Boxes read a linked
number the same way, so it no longer drops out behind a Reroute, a
subgraph or an older Primitive node.
## 2.25.3 - 2026-11-13
- **The video clip's frame readout explains itself.** On Video Crop + Rotate
+ Pad (Clip), the small `fr 52 · 0:02.17` beside Play now says in plain
words, when you point at it, which frame the picture shows and how many
seconds into the video it is. The help page explains it too.
## 2.25.2 - 2026-11-13
- **The video clip's IN handle always drags.** On Video Crop + Rotate + Pad
+19 -4
View File
@@ -150,6 +150,13 @@ example_workflows/ # example workflows (regular workflow JSON, not API JSON)
- Category: `🆎 AusBoss/<Group>`. The emoji is safe here — categories reach
the frontend as JSON and are never printed to the console at import time.
- Every node gets `DESCRIPTION`, input `tooltip`s, and `OUTPUT_TOOLTIPS`.
- Words a node face draws itself (card labels, buttons, choices, tooltips)
are translated for a Chinese ComfyUI by `js/i18n/index.js`: add the English
text and its Chinese to `js/shared/i18n_zh.mjs`, or to `STAYS_ENGLISH` there
when it should not change. Text with no entry stays English, and a widget's
name and value are never translated. Never read a label back from the DOM
to decide something; keep that in state (the translator changes the text).
`tests/i18n.test.mjs` fails on a card word with no entry.
- IMAGE tensors are BHWC float batches; MASK is BHW. Return tuples always,
even for one output: `(value,)`.
- Console output at import time must stay ASCII — ComfyUI on Windows often
@@ -210,8 +217,7 @@ example_workflows/ # example workflows (regular workflow JSON, not API JSON)
never a classic canvas number widget on a finished node face. Units
(`px`, `MP`, `×`) ride inside the box in a fixed-width slot that every
single-field row reserves, so the numbers down a card share one centre
line. Known, deliberate exceptions: the Seed card's seed (typed) and Load
Video's trim timecodes (typed).
line. Known, deliberate exception: the Seed card's seed (typed).
- **Node faces are widget cards.** A node whose face would be classic
LiteGraph widgets (full-width rows with an arrow at each end) gets an
entry in `js/widget_cards/index.js` instead: `mountWidgetCard` from
@@ -234,6 +240,13 @@ example_workflows/ # example workflows (regular workflow JSON, not API JSON)
widget per row. A value that is meant to be wired rather than typed is a
backend `forceInput: True` socket (Math Expression `a`/`b`/`c`), and a
multi-type string such as `"FLOAT,INT"` accepts either kind of link.
- **App mode** is ComfyUI's form view of a workflow (fields and a Run
button). A file list from the input folder declares its upload flag
(`image_upload`, `video_upload`, `audio_upload`): the form builds the
field's Upload button from it, and without it the field is a bare list.
`tests/test_video_upload_flag.py` holds the video lists to it. A card's
hidden widgets reach the form through `js/app_mode/`, so a card needs
nothing of its own for App mode.
- Preview-carrying nodes (Select Frame, Mask Refine, Mask by Name, LaMa
Inpaint, Save Image) share
`js/input_preview/`: a thin bar (node tools left, a small `preview`
@@ -324,7 +337,7 @@ run by hand against any ComfyUI:
```bash
AUSBOSS_COMFY_ROOT=<ComfyUI> python tests/test_comfy_core_contract.py
python scripts/compat_boot.py --url http://127.0.0.1:8188
node scripts/dev/face_smoke.mjs <chrome port> # and again with --vue
node scripts/dev/face_smoke.mjs <chrome port> # and again with --vue, and --blocked-reads
```
- `test_comfy_core_contract.py` reads the pack's own source for everything
@@ -335,7 +348,9 @@ node scripts/dev/face_smoke.mjs <chrome port> # and again with --vue
- `compat_boot.py` asks a running ComfyUI which nodes it offers: every public
node of the pack, and every node and required input the examples use.
- `face_smoke.mjs` puts every node on a graph and fails when a face does not
come up or something throws.
come up or something throws. With `--blocked-reads` it acts like a privacy
browser that blanks pixel reads, and fails when a node that loads a
picture then draws none.
A failure on the release opens an issue labelled `comfyui-update`. What these
cannot see is anything that needs a model: run the real thing on a GPU
+20 -6
View File
@@ -38,17 +38,27 @@ In **ComfyUI-Manager**, open the Custom Nodes Manager, search for **AusBoss** an
```bash
cd ComfyUI/custom_nodes
git clone https://github.com/ausboss/ComfyUI-AusBoss.git
git clone https://github.com/ausboss/ComfyUI-AusBoss.git ausboss-nodes
```
Restart ComfyUI and search the node library for **AusBoss**.
Install it one way, not both. Manager puts the pack in `custom_nodes/ausboss-nodes` and a clone in `custom_nodes/ComfyUI-AusBoss`. They are the same pack, so if both folders are there, delete one. The console says which copy it skipped.
Clone into `ausboss-nodes`, the folder ComfyUI-Manager uses, so Manager sees the same copy and updates it instead of adding a second one. If you also have a `custom_nodes/ComfyUI-AusBoss` folder from an older clone, delete it: with two copies, an old one can keep loading after every update, and its newer nodes show as missing. ComfyUI shows a message naming the folder when this happens.
After an update, through Manager or `git pull`, restart ComfyUI and hard-refresh the browser with **Ctrl+Shift+R**. Otherwise the browser keeps the old JavaScript, and the pack warns you about it. Manager can install a version or two behind while the Comfy Registry reviews a new release. To get the newest one, pick it in Manager's version list, or update by hand: delete the pack's folder in `ComfyUI/custom_nodes` and clone the repository as shown above.
The pack uses the Pillow, NumPy, Torch and PyAV that come with ComfyUI. Each example lists the models it needs on its Workflow Note. LaMa Inpaint also needs [`big-lama.pt`](https://github.com/Sanster/models/releases/download/add_big_lama/big-lama.pt) in `ComfyUI/models/lama/`. The pack never downloads weights by itself.
### Using an AI agent
Your agent (Claude Code, Codex, Cursor or another one) can learn the video workflows: how to write the words for them, set them up, and run them on your computer.
```bash
npx skills add ausboss/ComfyUI-AusBoss
```
Or tell it: "Read https://ausboss-examples.vercel.app/skill.md and help me use these workflows." The skill is [skills/ausboss-workflows/SKILL.md](skills/ausboss-workflows/SKILL.md). For picking and wiring single nodes, point it at the [agent guide](js/docs/agents/README.md).
### Upgrading from 1.x
2.0 removed **LM Studio Chat** (use **Text** for a fixed prompt) and Align Image's `offset_x` and `offset_y` outputs. Math Expression's `a`, `b` and `c` are sockets now instead of typed boxes, so put constants in the expression itself. 1.2 removed **Drop Shadow**, **Pad Image** (use **Load Image + Pad**) and **Frame Chooser**. Save Image writes only inside ComfyUI's output folder. The [changelog](CHANGELOG.md) has the details.
@@ -126,6 +136,10 @@ Rounds a picture's size to a multiple you choose, by resizing, cropping or paddi
Reads a picture's `width`, `height`, `longest_edge`, `shortest_edge` and batch `count` as whole numbers. Wire them into a resize, a latent, a frame count or Math Expression, so the rest of the graph follows the source's size. After a run the node shows each number beside its output.
### 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.
### 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.
@@ -180,13 +194,13 @@ The example keeps the clip's audio when there is any. The outpaint LoRA needs a
### Load Video
Upload a video, or pick one from the Source list, which plays the clip under the pointer. Trim it with IN and OUT handles or typed timecodes. The player plays the part you kept and can loop it. Width and height resize while decoding, and setting only one keeps the shape. `every_nth` skips frames and lowers the reported fps so the timing stays right, and `max_frames` caps how many frames load.
Upload a video, or pick one from the Source list, which plays the clip under the pointer. Set the part you want with Start, Duration and Ends at, in seconds or frames, or drag the handles under the player. The player plays the part you kept and can loop it. Width and height resize while decoding, and setting only one keeps the shape. `every_nth` skips frames and lowers the reported fps so the timing stays right, and the Duration caps how many frames load.
It returns the frames, audio, frame count, fps, width, height, duration and a core `VIDEO`. Only the part you kept is decoded, and it checks memory before a large load. When you save the frames, wire its fps into the save node.
### Load Audio
Upload a sound file, or pick one from the Source list, and the node shows it as a wave. Drag the IN and OUT handles to keep only the part you want, or type the times. Press play to hear just that part. Set **Max length** to the longest sound the next step can take, such as a video's length: anything past it turns red and is cut off, so you see what comes out before you run. Click the red length next to OUT to move OUT to the cut.
Upload a sound file, or pick one from the Source list, and the node shows it as a wave. Drag the two handles to keep only the part you want, or type a Start, a Duration or an Ends at. Press play to hear just that part. Set the Duration to the length the next step needs, such as a video's length.
It returns the `audio` you kept and its length in `seconds`. Only that part is decoded. [Help page](js/docs/AUSBOSS_NODES_LoadAudio.md).
@@ -196,7 +210,7 @@ Picks one frame from a video, then gives you the same rotate, crop and pad contr
### Video Crop + Rotate + Pad → Clip
Applies one rotate, crop and pad to every frame of a trimmed clip. It has the source picker, a timeline with a playhead and frame-accurate IN and OUT handles, frame skipping, a frame limit, the transform handles and output resizing. While you drag a trim handle, the node shows the exact first or last frame the run keeps. The bright part of the selection is what gets output.
Applies one rotate, crop and pad to every frame of a trimmed clip. It has the source picker, a timeline with a playhead and frame-accurate start and end handles, Start, Duration and Ends at boxes, frame skipping, the transform handles and output resizing. While you drag a trim handle, the node shows the exact first or last frame the run keeps. The bright part of the selection is what gets output.
Fill, feather and the resize budget are in **Crop, pad & resize** below the timeline, and a new clip keeps them. That matters for video outpainting, because the black, hard-edged canvas the model needs survives a source swap. A fresh Clip node starts with that canvas, and the editor's **Reset transform** goes back to it. **Frames for** trims the end to the frame count the next video model takes: LTX (8n+1) or Wan (4n+1). Tap a ratio to pad the clip to it; a new clip is padded to the lit ratio too. The padlock keeps the shape while you drag a handle.
@@ -486,7 +500,7 @@ People who download your workflow get the nodes through ComfyUI-Manager's missin
- Hold Shift while you turn the green rotation handle to snap to 15° steps.
- In the full-screen editor, the mouse wheel zooms, and the middle mouse button or Alt-drag pans. On the node itself, the wheel and middle mouse button still move the graph.
- **Alt+E** opens the selected node's transform editor. Change the key in Settings → Keybindings.
- The video editors have frame stepping, playback and exact timeline seeking, on the node face as well as in the editor. The Clip node's IN and OUT handles sit on the source's own frames, so the frame shown for IN is the first one decoded and the frame shown for OUT is the last.
- The video editors have frame stepping, playback and exact timeline seeking, on the node face as well as in the editor. The Clip node's start and end handles sit on the source's own frames, so the frame shown at the start is the first one decoded and the frame shown at the end is the last.
- Your own aspect presets go in `ausboss_presets.json` beside the pack. Copy [`ausboss_presets_example.json`](ausboss_presets_example.json) to start. Your file survives updates.
LoRA Loader and Latent Size have their own gear menus for per-node preferences.
+16 -5
View File
@@ -11,7 +11,6 @@ of taking the whole pack down, so one broken node never hides the rest.
import importlib
import os
import tomllib
import traceback
# One entry per file in nodes/, kept alphabetical. The order has no
@@ -31,6 +30,7 @@ NODE_MODULES = [
"node_image_folder",
"node_image_resize",
"node_image_size",
"node_image_toolbox",
"node_inpaint_crop_stitch",
"node_krea2_encode",
"node_krea2_model_patch",
@@ -92,8 +92,10 @@ for _module_name in NODE_MODULES:
traceback.print_exc()
# Folder ComfyUI serves to the browser; every .js file in it is loaded as a
# frontend extension. Shared modules use .mjs so they are import-only.
WEB_DIRECTORY = None if _other_copy else "./js"
# frontend extension. Shared modules use .mjs so they are import-only. A copy
# that steps aside serves only the script that warns about it in the browser,
# since the console line alone is easy to miss.
WEB_DIRECTORY = "./web_second_copy" if _other_copy else "./js"
__all__ = ["NODE_CLASS_MAPPINGS", "NODE_DISPLAY_NAME_MAPPINGS", "WEB_DIRECTORY"]
@@ -101,9 +103,10 @@ __all__ = ["NODE_CLASS_MAPPINGS", "NODE_DISPLAY_NAME_MAPPINGS", "WEB_DIRECTORY"]
def _read_version():
"""Version straight from pyproject.toml so it is never duplicated."""
try:
from .nodes._pyproject import read_project
pyproject = os.path.join(os.path.dirname(__file__), "pyproject.toml")
with open(pyproject, "rb") as f:
version = tomllib.load(f).get("project", {}).get("version")
version = read_project(pyproject).get("version")
return version if isinstance(version, str) and version.strip() else "unknown"
except Exception:
return "unknown"
@@ -143,6 +146,14 @@ def _print_second_copy():
if _other_copy:
_print_second_copy()
try:
from .nodes._single_copy import register_second_copy_notice, second_copy_notice
register_second_copy_notice(
second_copy_notice(os.path.dirname(__file__), _read_version(), _other_copy)
)
except Exception:
traceback.print_exc()
else:
try:
from .nodes._frontend_cache import register_frontend_cache_guard
+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.25.2">
<title>release: v2.25.2</title>
<svg xmlns="http://www.w3.org/2000/svg" width="105" height="20" role="img" aria-label="release: v2.26.7">
<title>release: v2.26.7</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.25.2</text>
<text x="76.5" y="14">v2.26.7</text>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 425 B

After

Width:  |  Height:  |  Size: 425 B

+1 -1
View File
@@ -42,7 +42,7 @@ recipe.
| `cdp_drag.mjs <port> <setup.js> <mid.png\|-> <after.png\|-> [check.js]` | `setup.js` returns `{from, to, __clip}` in client pixels; presses at `from`, moves to `to`, screenshots mid-drag, releases, evaluates `check.js`, screenshots again |
| `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] [--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. Needs no model, so it also runs in the nightly ComfyUI check |
| `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 |
| `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 |
+45
View File
@@ -0,0 +1,45 @@
// App mode for nodes with cards: the simple form view shows a real control
// for each field instead of an empty row. The logic is in
// js/shared/app_mode.mjs; this file watches which mode the open workflow is
// in and hands the fields over.
import { app } from "../../../scripts/app.js";
import { createAppModeSync, workflowMode } from "../shared/app_mode.mjs";
const sync = createAppModeSync({
find(nodeId, name) {
const graph = app.rootGraph ?? app.graph;
const node = graph?.getNodeById?.(/^\d+$/.test(nodeId) ? Number(nodeId) : nodeId);
const widget = node?.widgets?.find((entry) => entry.name === name);
return widget ? { node, widget } : null;
},
changed(node) {
node.setDirtyCanvas?.(true, true);
},
});
let queued = false;
// After the current task: a card hides its widgets in a microtask once the
// node has loaded, and the form's fields are shown after that.
function schedule() {
if (queued) return;
queued = true;
setTimeout(() => {
queued = false;
try {
const workflow = app.extensionManager?.workflow?.activeWorkflow;
sync(workflowMode(workflow), (app.rootGraph ?? app.graph)?.extra?.linearData);
} catch (error) {
console.warn("[AusBoss] App mode fields:", error);
}
}, 0);
}
app.registerExtension({
name: "ausboss.app.mode",
setup() {
app.extensionManager?.workflow?.$subscribe?.(schedule);
},
afterConfigureGraph() {
schedule();
},
});
+20 -1
View File
@@ -49,6 +49,25 @@ function askForReload(installed) {
}
}
// "2.26.2" -> [2, 26, 2]. Anything else, such as "unknown", is null.
function parseVersion(version) {
const match = /^(\d+)\.(\d+)\.(\d+)$/.exec(typeof version === "string" ? version : "");
return match ? match.slice(1).map(Number) : null;
}
// Only a server newer than the page means this tab runs old files. The page
// is newer when the Manager switched the pack on disk and the page was
// reloaded before ComfyUI restarted, and then a restart is what is needed.
// Two version numbers cannot tell that apart from a downgrade with the tab
// left open, which needs a reload, so in that case the guard says nothing.
function serverIsNewer(installed, running) {
const server = parseVersion(installed);
const page = parseVersion(running);
if (!server || !page) return false;
const step = server.findIndex((part, index) => part !== page[index]);
return step >= 0 && server[step] > page[step];
}
// The installed version this page already asked a reload for. A server that
// drops and comes back several times must not stack the same message.
let asked = null;
@@ -58,7 +77,7 @@ async function check() {
try {
const installed = (await (await api.fetchApi("/ausboss/pack_version")).json())?.version;
const running = await runningVersion();
if (!installed || installed === "unknown" || !running || installed === running || installed === asked) return;
if (!serverIsNewer(installed, running) || installed === asked) return;
asked = installed;
const listing = await (await api.fetchApi("/ausboss/pack_modules")).json();
await refreshModules(Array.isArray(listing?.modules) ? listing.modules : []);
+60 -9
View File
@@ -14,6 +14,10 @@ import {
compareBadges,
compareClip,
compareResultSide,
REST_PROPERTY,
savedRestSide,
SWITCH_CONTROL_INPUTS,
SWITCH_NODE_TYPES,
compareSizeLabel,
compareSwitchValue,
findComparePairs,
@@ -182,9 +186,15 @@ function linkView(graph) {
const link = lookupLink(graph, linkId);
return link ? { id: String(link.origin_id), slot: link.origin_slot } : null;
};
const inputs = (id) => graph?.getNodeById?.(id)?.inputs ?? [];
return {
origin,
feeds: (id) => (graph?.getNodeById?.(id)?.inputs ?? []).map((input) => origin(input?.link)?.id),
feeds: (id) => inputs(id).map((input) => origin(input?.link)?.id),
branches(id) {
const node = graph?.getNodeById?.(id);
if (!SWITCH_NODE_TYPES.has(node?.comfyClass ?? node?.type)) return null;
return inputs(id).filter((input) => !SWITCH_CONTROL_INPUTS.has(input?.name)).map((input) => origin(input?.link)?.id);
},
inside(id) {
const subgraph = graph?.getNodeById?.(id)?.subgraph;
if (!subgraph) return null;
@@ -195,18 +205,40 @@ function linkView(graph) {
}
// Which input holds the result, read from the graph the panel sits in.
function resultSide(node) {
function guessResultSide(node) {
const view = linkView(node.graph);
const source = (name) => view.origin(node.inputs?.find((input) => input?.name === name)?.link);
return compareResultSide(source("image_a"), source("image_b"), view);
}
// Slide mode rests on the result while the pointer is away.
// The picture the panel rests on, saved with the node. A node from a
// workflow saved before the choice existed has none: its side is worked out
// from the links, as earlier versions did, and held in memory only. Writing
// it into the node would mark every older workflow as changed when it opens;
// it is written when someone picks a side in the menu.
function restSide(node) {
const saved = savedRestSide(node.properties?.[REST_PROPERTY]);
if (saved) return saved;
node.__ausbossRestGuess ??= guessResultSide(node);
return node.__ausbossRestGuess;
}
// Slide mode rests on its saved picture while the pointer is away.
function showResult(state) {
state.fraction = resultSide(state.node) === "B" ? 0 : 1;
state.fraction = restSide(state.node) === "B" ? 0 : 1;
applyClip(state);
}
// The right-click choice: rest on the other picture from now on.
function setRestSide(node, side) {
node.properties ??= {};
node.properties[REST_PROPERTY] = side;
const state = node.__ausbossCompare;
if (state && getMode(node) === "slide" && !state.stage.matches(":hover")) showResult(state);
node.setDirtyCanvas?.(true, true);
notifyAusbossChange();
}
// A click on the mode switch. The mode saves with the workflow; a flip
// between A and B within the lock does too, through the side it stores.
function pickMode(state, value) {
@@ -433,10 +465,11 @@ app.registerExtension({
defaultValue: true,
category: ["🆎 AusBoss", "Image Compare", "Rest on the result"],
tooltip:
"While the pointer is away, Image Compare A/B shows the result: "
+ "after every run, and again each time the pointer leaves the "
+ "picture. Off: it stays on the picture nearest to where the "
+ "pointer left, and a new run does not change it.",
"While the pointer is away, Image Compare A/B shows the picture it "
+ "rests on: B on a new node, or the one picked in the node's "
+ "right-click menu. It does after every run, and again each time "
+ "the pointer leaves the picture. Off: it stays on the picture "
+ "nearest to where the pointer left, and a new run does not change it.",
onChange(value) {
restOnResult = value !== false;
},
@@ -454,6 +487,9 @@ app.registerExtension({
beforeRegisterNodeDef(nodeType, nodeData) {
if (nodeData?.name !== NODE_NAME) return;
chainCallback(nodeType.prototype, "onNodeCreated", function () {
// A new node rests on B. A loaded one gets its saved side back in onConfigure.
this.properties ??= {};
this.properties[REST_PROPERTY] = "B";
buildPanel(this);
// Only for a genuinely new node: onConfigure restores a saved size after
// this runs, so a workflow's own dimensions still win.
@@ -462,8 +498,12 @@ app.registerExtension({
Math.max(DEFAULT_NODE_SIZE[1], this.size?.[1] ?? 0),
]);
});
chainCallback(nodeType.prototype, "onConfigure", function () {
chainCallback(nodeType.prototype, "onConfigure", function (info) {
const state = this.__ausbossCompare;
// Saved before the choice existed: drop the new node's B, so the side
// is worked out from the links.
if (!savedRestSide(info?.properties?.[REST_PROPERTY])) delete this.properties?.[REST_PROPERTY];
this.__ausbossRestGuess = undefined;
queueMicrotask(() => {
if (!state || this.__ausbossCompare !== state || state.abort.signal.aborted) return;
state.showingB = this.properties?.ausboss_compare_side === "B";
@@ -482,8 +522,19 @@ app.registerExtension({
if (!pairs.length) setEmpty(state, "Execution finished without compare previews");
app.canvas?.setDirty?.(true, true);
});
// Which picture the panel rests on, kept with the workflow.
chainCallback(nodeType.prototype, "getExtraMenuOptions", function (_canvas, options) {
if (!Array.isArray(options)) return;
const side = restSide(this);
const other = side === "A" ? "B" : "A";
options.unshift(
{ content: `Show ${other} when the pointer is away (now ${side})`, callback: () => setRestSide(this, other) },
null,
);
});
// A link on the filename input decides whether the name is typed here.
chainCallback(nodeType.prototype, "onConnectionsChange", function () {
this.__ausbossRestGuess = undefined; // an older node's side follows its links
this.__ausbossCompare?.eraser?.refresh();
});
chainCallback(nodeType.prototype, "onRemoved", function () {
+15 -14
View File
@@ -20,10 +20,9 @@ middle of a graph without breaking anything downstream.
Run the workflow once to load the previews. The switch under the picture
picks what the panel does, and its marker slides to your choice:
- **Slide** (default): the panel shows the result. Move the pointer across
it to compare: A appears on the left of the line and B on the right. Move
the pointer away and the result is back. Every new run shows its result
too.
- **Slide** (default): the panel shows B, the result. Move the pointer
across it to compare: A appears on the left of the line and B on the
right. Move the pointer away and B is back. Every new run shows it too.
- **A** / **B**: show that picture and hold it, whatever the pointer does.
- **Erase**: mix the two pictures by hand. One picture is on top; paint on
it and it rubs away, so the other one shows through. Then save the mix.
@@ -132,11 +131,12 @@ Your paint is kept with the workflow. A new run keeps it while the picture
keeps its size, so you can change a seed and look again; press **CLEAR**
to start over. Pictures of another size start clean.
## Which picture is the result
## Which picture shows when the pointer is away
B, the "after" picture. If your graph makes A out of B's picture (B is the
picture you loaded and A is the edited one), the result is A. To keep one
picture up whatever happens, use the **A** or **B** button.
B, the "after" picture, on a new node. If your result is wired to A,
right-click the node and choose **Show A when the pointer is away**. The
choice is saved with the workflow. To keep one picture up whatever the
pointer does, use the **A** or **B** button.
## Outputs
@@ -152,12 +152,13 @@ network requests are made.
## Technical details
- While sliding, the outer 6% on either side snaps to a full image.
- The result is found from the links: when the node that feeds `image_b` is
somewhere upstream of the node that feeds `image_a`, A was made from B and
A is the result. When both pictures come out of one subgraph, the same
check is made inside it. In every other case it is B: two unrelated
pictures, both pictures out of one plain node, or a link the node cannot
follow (a Set and Get pair, for example).
- The side is saved in the node's `ausboss_compare_rest` property. A
workflow saved by an earlier version has none, so its side is worked out
from the links, the way earlier versions did, until a side is picked in
the menu: when A is made from B's picture, A is the result. A switch
counts only when it cannot hand on the picture B started from. When both
pictures come out of one subgraph, the same check is made inside it. In
every other case it is B.
- Settings → AusBoss → Image Compare → **Rest on the result** switches this
off. The panel then stays on the picture nearest to where the pointer
left, and a new run does not change it.
+44 -9
View File
@@ -84,31 +84,42 @@ from.
Connect a video, then pick what it is for:
- **copy its moves**: your person does the moves in the video. It needs a
picture of your person. Say where in your lines:
`@1 dances on a rooftop at sunset.` The clothes can come from words or from an
outfit picture.
- **copy its moves**: someone does the moves in the video. With a picture of
your person, your person does them. Say where in your lines:
`@1 dances on a rooftop at sunset.` With no person picture, the person in
the video keeps their own moves and goes somewhere new: give a picture the
job **place** and type `He dances in @1.` The clothes can come from words or
from an outfit picture. It doesn't have to be a person: give a cartoon hand,
a toy or a mascot the job **thing** and type `@1 waves.` It does the moves in
its own look, and nothing of the video's subject is kept.
- **swap the person**: your person takes over from the one in the video. The
place, the moves and the camera stay. With two person pictures, the first
replaces the person on the left and the second replaces the person on the
right. To choose who goes, type one line per picture, for example
`@1 replaces the man in the hat`. Put spoken words in quotes and name
the speaker. If a voice comes from off screen, say so in the line.
A line like `@1 dances.` is not read as who goes; only a description such
as `the man in the hat` is. With two people, name who speaks.
- **change something**: keep the video and describe the change, for example
`She wears a red raincoat`. Be specific about what should change.
`She wears a red raincoat`. Be specific about what should change. To change
the whole look, connect a picture with the job **style** (or **place**, for
the same room looking different) and type `It looks like @1.` A clip with
nobody in it, such as an empty hallway, stays empty.
- **keep going**: more of the same clip, from where it ends. Say what happens
next, or leave the box empty and it just carries on. Connect the whole clip:
the node sends H3 only the last 2 seconds.
- **new voice**: the same clip with a new voice. Connect the voice, and type
what they say in quotes.
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
**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.
With an active video, **swap the person**, **change something** and **new voice**
use the incoming clip to set the frame count. **Length** says **From the clip**;
With an active video, **copy its moves**, **swap the person**, **change
something** and **new voice** use the incoming clip to set the frame count. **Length** says **From the clip**;
set the clip's length upstream. The bar does not show a guessed duration or offer
retiming controls for these jobs. H3 rounds the frame count to a supported length.
Other video jobs, or turning the video off, use the editable **Length** again.
@@ -137,6 +148,9 @@ workflows and scripts keep their previous behavior when it is absent.
`ends on her sitting by the window`.
- **Speech**: put the words in quotes: `@1 says "we are late."` Each person
keeps their own voice.
- **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.
- **Words on a sign**: name the sign: `a neon sign reads "OPEN"`.
- **Sound and music**: use the **Sound** and **Music** boxes, or type
`sound: rain on a tin roof` and `music: slow sad piano`. With no music you get
@@ -150,6 +164,17 @@ own, with blank lines around it, it is for the whole clip.
Already wrote H3's six parts yourself? Paste them in and they go through as
they are.
## See and change the full prompt
The **Full prompt** tab at the top of the node shows the prompt the node wrote
on its last run. To change one thing, such as taking out "A slow push in.",
edit it there and run again: H3 gets your text exactly as it is in the box. An
amber dot on the tab shows that an edit is being sent. **Reset to written**
throws the edit away and goes back to what the **Simple** tab writes.
While an edit is in place, changes on the Simple tab do nothing, because your
text is sent instead.
## What you can plug in
- **picture_1** to **picture_4**: your pictures.
@@ -195,8 +220,10 @@ as not plugged in.
- **Sound** (`sound`): what the clip sounds like, for the whole clip. Same as a
`sound:` line.
- **Music** (`music`): the music for the whole clip. Same as a `music:` line.
- **Length** (`seconds`): how long the clip is, 5 to 15.
- **Camera** (`camera`): how the camera moves the whole way through.
- **Length** (`seconds`): how long the clip is, 4 to 15.
- **Camera** (`camera`): how the camera moves the whole way through. The first
choice adds no camera words. With a video wired it reads **from the video**:
the camera does what it does in the video. Pick a move only to change it.
- **Look** (`look`): from the picture keeps your photo's look. The others redraw
the clip. Clay and 3D don't work from words, so change your picture first with
an edit model.
@@ -208,6 +235,8 @@ as not plugged in.
- **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.
- **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.
## Tips
@@ -264,5 +293,11 @@ 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.
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
go back to it. The last written prompt is kept with the node in a saved
workflow.
H3's own rewriter runs only on paid services, and the open model reads a prompt as
it is. This node does that job on your machine, with no model needed.
@@ -24,6 +24,15 @@ pan. **Save & close** keeps your edits. **Cancel** or Escape puts everything
back, and asks first if anything changed. You do not need the editor: a run
uses what the node shows.
Right-click the picture and choose **Copy image** to copy the original picture,
without added padding, rotation, crop, resize, handles or guides. To include
your edits, open the gear and turn on **Copy with crop, rotation and padding**.
That also includes resize, and is remembered for this browser. **Open image**
follows the same choice. This works on the node and in the editor.
Direct copying needs localhost or HTTPS. On a plain HTTP address, choose
**Open image**, then right-click that
picture and use the browser's **Copy image**.
## On the node
From top to bottom:
+44
View File
@@ -0,0 +1,44 @@
# Image Toolbox
Small picture jobs in one node. Pick the job from the **Job** list (`job`);
the rows under it change to what that job needs.
## Jobs
### split sheet at gaps
Cuts a row of pictures that sit side by side, such as the four views of a
character sheet, into separate pictures.
- **Pieces** (`pieces`): how many pictures are on the sheet. 4 for a
four-view character sheet.
Each cut goes to the gap between two pictures, not to an equal share of the
width. An image model rarely puts each view exactly on its quarter of a
sheet, so cutting into equal parts can leave part of a neighbour's sleeve in
one piece and cut another's off. Here every piece holds one picture.
The pieces come out as one batch, from left to right, all the same size.
Narrower pieces are padded with the sheet's backdrop colour. The first and
last pieces keep the sheet's own left and right edges at their outer edge,
so a person drawn up to the edge of the sheet does not look cut off by a
band of padding. Wire the batch into Save Image to save each piece as its
own file.
A batch of sheets is cut sheet by sheet: the first sheet's pieces, then the
next sheet's.
## Technical details
- The backdrop colour is the median colour of the picture's border.
- A pixel counts as part of a picture when any channel differs from the
backdrop by more than 0.1 (on a 0-1 scale).
- Each cut looks for the column with the fewest such pixels, up to 40% of
one piece's width either side of the equal-share line, and takes the
middle of the longest run of those columns.
- 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.
- 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.
+49 -1
View File
@@ -26,6 +26,40 @@ Boxes only shows "Node 2.0 only".
Wire `preview` to a Preview Image to see the boxes with their numbers and words.
## Place people with MiniMax H3 Image
The `h3_prompt` output says the boxes in words for MiniMax H3 Image: who goes
where, what they do there, how big, and who stands beside whom. Use it to put the people from your
reference pictures into a scene, each one where you drew a box.
1. Wire your scene picture into `background` and into the first picture of
the H3 Image node: it is `<Picture 1>`, the picture that is changed.
2. Wire the people's pictures into the next ones: `<Picture 2>`,
`<Picture 3>` and so on.
3. Draw one **object** box for each person. In its **Description**, name
their picture and say what they do there, for example "the man from
`<Picture 2>`, sitting on the couch". That second part is what puts them
in the box: told only where to go, H3 Image keeps people standing as in
their own picture, often outside the box.
4. A box with no description still gets the next picture, `<Picture 2>`, then
`<Picture 3>`, in the order of the boxes, and keeps that person's face,
hair and clothes. It is a rough place only. A description without a
picture is a thing: a dog, a sofa. A **text** box writes its words at its
place.
5. Wire `h3_prompt` to the prompt of the H3 Image node. To add words of your
own, such as the light or the mood, join the two texts first, for example
with ComfyUI's Concatenate Text node.
Without a picture on `background` there is no scene picture, and the people
start at `<Picture 1>`.
The prompt says every place in words, never in numbers: H3 Image draws
numbers from a prompt onto the picture as text. Tried on three rooms and two
seeds: with a description like the one above, the man was in his box 6 times
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.
## Change the words in a picture
The `mask` output is white inside every box. Use it to change only one part
@@ -149,11 +183,12 @@ removes it. The first color also colors the box on the canvas.
| `bboxes` | The boxes in pixels of the canvas (x, y, width, height), for nodes that take bounding boxes. A turned box gives the straight box around it. |
| `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**. |
## In place of Create Bounding Boxes
Layout Boxes has the same inputs and the same outputs in the same order (and
`mask` after them), so the wires move straight over. For the same boxes it
`mask` and `h3_prompt` 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.
@@ -209,5 +244,18 @@ run once: they fill the canvas. Then remove the old node.
- Like Create Bounding Boxes, it is an output node: it runs with the workflow
even when nothing is wired to its outputs, so new boxes on the `bboxes` wire
reach the canvas.
- `h3_prompt` has an opening sentence (one photograph of the scene in
`<Picture 1>`, kept as it is), one sentence per box in box order, and a
closing one (the same ground and light for everything). Across, a box is at
the far left, left, middle, right or far right by its centre; it is "high"
or "low" when its centre is in the top or bottom third and it is less than
0.6 of the frame tall. Its height and width are said as a tenth, a quarter,
a third, half, two thirds, three quarters or all of the frame. Each object
is placed against the object on its left when the two share some height:
right beside it (a gap under 5% of the frame), a little to the right (under
15%), well to the right, or partly in front of or behind it when they
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.
- The background is saved, shrunk, in ComfyUI's temp folder for the node's
face. Nothing else is written.
+16 -22
View File
@@ -5,37 +5,31 @@ clip, a song or any sound a video model or a save node takes, when you want
one part of the file and not the whole thing.
The node shows the whole file as a wave, so you can see where the loud parts
are. The part that comes out is bright. Drag the white **IN** and **OUT**
handles to set where it starts and stops, drag the bright part to slide it,
or click somewhere else on the wave to move it there. You can also type a time
under the wave, in seconds (`12.5`) or minutes and seconds (`1:02.5`).
are. The part that comes out is bright. Under the wave are three boxes:
**Start**, **Duration** and **Ends at**, in seconds. Drag the left handle to
move the start, drag the right handle or type a Duration to change how long
the sound is, or drag the bright part to slide it. Click somewhere else on
the wave to move it there. Typing **Ends at** sets the Duration for you.
Press **▶** to hear only the part that comes out. **LOOP** plays it again and
again.
## Max length
Set the Duration to the length the next step needs, such as the length of
the video you are making. An empty Duration runs to the end of the file.
Set **Max length** to the longest sound the next step can take, such as the
length of the video you are making. The start stays where it is, and anything
past the limit turns red with a dashed line where it is cut. Next to OUT,
the node shows how long the sound that comes out is, such as `15.0 s`. It
turns red when part of your pick is cut; hold the mouse over it to see how
much, and click it to move OUT to the cut. Play stops at the cut, so what you
hear is what comes out. `0` means no limit.
Max length can be wired. When the wire comes from a number node such as
Float 🆎, the wave shows the cut for that number; otherwise the length's tooltip says
`max wired` and the run still cuts the sound to the wired length.
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.
## Controls
- **Source** (`audio`): a sound file in ComfyUI's input folder. **Upload**
adds one. Videos are listed as well, for their sound.
- **Max length** (`max_seconds`): the longest the sound may be, in seconds.
`0` means no limit.
- **IN** (`start_seconds`): where the sound starts.
- **OUT** (`end_seconds`): where the sound stops. `0` means the end of the
file.
- **Start** (`start_seconds`): where the sound starts.
- **Duration** (`max_seconds`): how long the sound is, in seconds. Empty, or
`0`, runs to the end of the file.
- **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.
## Outputs
@@ -49,4 +43,4 @@ Float 🆎, the wave shows the cut for that number; otherwise the length's toolt
- The sound keeps its own sample rate and channels.
- 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 four values above.
stored with the workflow besides the node's own values.
+39 -43
View File
@@ -1,37 +1,33 @@
# Load Video
Loads a video from ComfyUI's input folder as an `IMAGE` frame batch plus its
audio. One responsive player shows the source and previews the selected trim.
Drag the high-contrast **IN** and **OUT** handles below it, drag the selected
range to move the whole window, or type a time into the two fields, in seconds
(`95.5`) or as a timecode (`1:35.5`). Click the strip outside the selection to
move the window to that spot.
The playhead follows each edit, so the frame at either boundary is visible
while trimming. In **Source**, the list plays the clip under the pointer, muted, and filters as you type.
audio. The player shows the video; the timing card under it picks the part
that comes out.
Playback is constrained to the selected window. **LOOP** repeats it; turn loop
off and playback pauses at OUT. The reload button refreshes the source without
creating a second preview. The player takes the height you give the node:
drag the node taller for a bigger picture. A tall video is shown whole, never
cropped.
The timing card has three boxes: **Start**, **Duration** and **Ends at**.
Drag the left handle on the bar to move the start, drag the right handle or
type a Duration to change how long the clip is, or drag the middle of the
clip to slide it. **s | fr** switches every box between seconds and frames;
it only changes what you see, never a saved value. **Use as start** starts
the clip at the frame in the picture, and **Whole video** puts the clip back
to the full file. In **Source**, the list plays the clip under the pointer,
muted, and filters as you type.
**FRAME** switches the loader into a frame picker: the trim strip becomes a
single scrub rail, and only the frame at the marker loads — a one-image batch,
ready for image workflows without a separate frame-select node. Click or drag
anywhere on the rail to choose the frame, or type an exact time into the AT
field. Playback runs the whole source freely in this mode so you can hunt for
the right moment. Picking a frame moves IN to that time. When you toggle back,
OUT stays where it was, unless the frame is at or after OUT: then OUT moves to
the end of the video.
The player takes the height you give the node: drag the node taller for a
bigger picture. A tall video is shown whole, never cropped. **LOOP** plays
the clip again and again; with it off, playback pauses at the clip's end.
The reload button refreshes the source.
The label between IN and OUT reports what one Run will actually load — e.g.
`0:04.0 of 0:10.0 · 48 frames @ 12 fps`, or `1 frame at 0:05.2` while FRAME
is on. The preview cannot re-render `every_nth` frame drops or a `max_frames`
cap, so it counts them instead: the frame total and playback rate come from
the source's real frame rate (probed from the file, since the browser's
player never exposes it) with `every_nth` and `max_frames` applied. When a
deciding value arrives over a link, or the rate cannot be probed, the count
drops out rather than guessing.
**FRAME** turns the loader into a frame picker: only the frame at the marker
loads, as a one-image batch, ready for image workflows without a separate
frame-select node. Drag the bar to choose the frame, or type it into the
**FRAME** box. Playback runs the whole video in this mode so you can hunt for
the right moment. Picking a frame moves the clip's start there.
The boxes count real frames: the frame rate and frame count come from the
file itself, so a 4.1 s clip at 60 fps reads 247 frames, the same number
the run loads. When a box is set by another node it shows a **linked**
button that jumps to that node.
## Drop a video onto the node
@@ -48,21 +44,21 @@ embedded workflow replaces the whole graph.
- **Source** (`video`): A file in the input folder; **Upload** adds new ones.
A video ComfyUI made, named like `clip.mp4 [output]`, loads too.
- **IN** (`start_seconds`): Skip everything before this time.
- **OUT** (`end_seconds`): Stop at this time; `0` means the source end until a
handle is moved.
- **Every nth** (`every_nth`): Keep one frame in this many — `2` halves the frame count.
The `fps` output divides to match, so the clip still plays at real speed
downstream.
- **Limit** (`max_frames`): Stop after this many kept frames; `0` loads the
whole trim window. Caps memory on long clips — the decode ends early
instead of loading and discarding.
- **LOOP**: Repeat the selected window during preview. It starts on and is
saved with the workflow.
- **FRAME** (`single_frame`): Load only the frame at the IN time (the field
reads **AT** while FRAME is on) as a one-image batch; `end_seconds`,
`every_nth`, and `max_frames` are ignored while it is on.
- **↻**: Reload the selected source preview.
- **Start** (`start_seconds`): Skip everything before this time.
- **Duration** (`max_frames`): How many frames the clip keeps. **Whole
video** removes the limit, so the clip runs to the end (the widget holds
`0`). The decode stops early, so a short clip from a long video stays
quick.
- **Ends at**: Where the clip stops. Typing it sets the Duration. A
workflow saved with an end time (`end_seconds`) keeps it and runs the same.
- **Every nth** (`every_nth`): Keep one frame in this many; `2` halves the
frame count. The `fps` output divides to match, so the clip still plays at
real speed downstream.
- **LOOP**: Repeat the clip during preview. It starts on and is saved with
the workflow.
- **FRAME** (`single_frame`): Load only the frame at the marker as a
one-image batch; the Duration and Every nth are ignored while it is on.
- **↻**: Reload the source preview.
- **Width** / **Height** (`custom_width` / `custom_height`): `0` keeps the
source size. Set one side only and the other follows the aspect ratio,
rounded to an even number.
+41 -2
View File
@@ -134,6 +134,30 @@ A group that a switch turns on and off shows the lock on its header
instead. The LoRAs in it keep plain grips, so each one is still yours to
turn on or off. Click the header's lock to take the group over.
## A strength set by a wire
To set one LoRA's strength from somewhere else, such as a slider, a Float
node or a sweep, drag that number's wire onto the row and let go. The row
under the pointer lights up teal while you aim; anywhere across the row
works. The wire runs to that row and its strength box turns dashed teal,
showing the number coming in. The bar behind the name follows it.
- **Click the dashed box** to jump to the node the number comes from.
- **Right-click the row → Unlink strength** to take the wire off. The row
goes back to the strength it had.
- The wire sets the model strength. The CLIP strength keeps the same ratio
to it, so a row at 1.0 / 0.5 fed 0.6 runs at 0.6 / 0.3.
- Gear menu → **Linked strength wires** shows the wire (the default), shows
it only while the pointer is on the loader or the number's node, or hides
it.
### Technical details
Each linked row has its own input, `strength_<row id>`, which exists only
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 bars
Every named row paints a center-zero bar behind its name: teal grows right
@@ -176,8 +200,15 @@ last one you ticked and the one you click. Ticks stay while you search, so you c
gather files from several searches; **Clear** unticks them all. Files that
are already in the stack say **in stack** and have no box. With the
keyboard, **Ctrl+Enter** ticks the highlighted file and **Shift+Enter**
ticks the run up to it. Use the arrow beside a folder to collapse or expand it without
adding anything. Folded folders are remembered in this browser. Search
ticks the run up to it. The list opens with every folder folded. Use the
arrow beside a folder to open or fold it without adding anything.
**Open all** beside the search box opens every folder at once (it then
reads **Fold all**), and **Alt**- or **Shift**-click on a folder's arrow
opens or folds that folder and every folder inside it. With the keyboard,
**Right** opens the highlighted folder and **Left** folds it; **Left** on a
file folds the folder it is in and moves up to it. To have the list open
the way you left it instead, set **Settings → 🆎 AusBoss → LoRA Loader →
Picker folders** to **Remember my folds**. Search
reveals matching files; clearing it brings back your folded view. You can
also fold folders while searching.
@@ -266,6 +297,14 @@ red with advice to re-pick. Thumbnails, the info card, and range lookups
all use the resolved name, so a moved file keeps its previews and Civitai
data.
A missing LoRA is also listed in ComfyUI's own missing-models list (the
Issues panel, and the "Download all" button) next to the other models the
workflow needs, with a Download button when the workflow saved where the
file comes from. Rows that are switched off, at zero strength, or whose
file moved folders are left off that list, because the run does not need
them or finds them anyway. Rows that come into the node over a link are
listed by the node that sets them, not here.
The run side matches: a stale saved path resolves by name at load time
(exact → unique case-insensitive path → unique basename, with a one-line
console note when it remaps). A LoRA that is genuinely missing **stops the
+1 -1
View File
@@ -2,7 +2,7 @@
Pick a picture size by shape and megapixels, or by dragging. Use it in place of an Empty Latent node: it gives you the width, the height and a blank latent of that size.
- **Shape:** the left button selects landscape or portrait. Ratio chips follow that choice; square retains it for the next selection. Clicking a chip uses its generated size near one megapixel. Enable **Chips keep current budget** in the gear to retain the current area.
- **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.
+1 -1
View File
@@ -65,7 +65,7 @@ file's name. A caption on the `caption_text` input writes the paired `.txt`.
are saved under the name and folder set above, in the format picked,
with the workflow inside if **Embed workflow** is on. They wait in
ComfyUI's temp folder, which is emptied when ComfyUI restarts, so save
what you want before that.
what you want before that. The Save button works for the last 256 runs.
- **Preview steps** (`step_preview`, off by default): the switch left of
**preview** shows the picture while it is being made, one step at a time,
where the saved image goes, with a **STOP** button on the bar. Stop a run
+56 -3
View File
@@ -7,6 +7,43 @@ from **Crop For Inpaint 🆎**, **Load Image + Pad 🆎** or any
result, it is resized to fit first, then joined to your picture the way
**Seam** says.
## Follow changes
Turn on **Follow changes** when the model draws past your box and the paste
cuts it off: a boot that ends at the box's edge, half a plate rim, a collar
sliced flat. Edit models that redraw the whole crop they are given, such as
MiniMax H3 Image, do this often.
With it on, the paste is no longer just the box. It takes the box plus every
change the model made that touches the box, and fades out before the edge
of the crop that went to the model. Before that, it undoes the small zoom or
shift such a model can draw, so the wall, tiles or table around the edit line
up with your picture again.
When the model changed nearly everything around the box, there is no single
new thing to follow, and the paste stays the box. The console says what was
done on each run. Follow changes works on a Crop For Inpaint stitcher with
the classic seam; an outpaint has no picture under its new area to compare
against, so it pastes as before.
### Technical details
- The model's crop is lined up with the picture's own crop by the zoom and
shift Realign to Source measures (up to 20% zoom). An unreliable
measurement leaves the crop as it came back.
- A pixel counts as changed when the lined-up crop differs from your
picture by more than 0.10 (on 0 to 1, averaged over red, green and blue,
after a 4 px blur). Changes are joined to the box when they come within
8 px of it, then closed by 6 px, filled, widened by 10 px and softened by
10 px.
- The paste fades to nothing over 24 px before each crop edge that lies
inside your picture, and runs to the picture's own edge where the crop
reaches it.
- When the changes outside the box cover more than half of the crop outside
the box, the paste stays the box.
- The work runs at most 768 px on the long side and takes under a second
on a 4 MP crop.
## Paste onto: crop or original
**Paste onto** picks what you get back. It lives in the gear menu, next to
@@ -155,9 +192,25 @@ correction turns the corner without a crease.
The shift is subtracted from the pasted region before the blend. In the
padding that is the whole shift; inside the feathered band the paste
alpha scales it, which is exactly the share of each band pixel the
sampler painted. Source pixels stay bit-identical. A crop stitcher, which
has no source rectangle, gets a single global shift measured in its
blend band instead.
sampler painted. Source pixels stay bit-identical.
A Crop For Inpaint crop has no source rectangle, so it gets one shift for
the whole painted area. That shift is read inside the painted area, in the
32 pixels next to its edge: the same pixels before and after, taking the
middle value. Those 32 pixels are counted at the size the model painted, so
a large picture is read the same way and takes no longer. Most inpaint workflows let the model paint a little wider
than the paste, so the soft edge itself comes back close to your picture
and shows only a fraction of the drift. When the painted area holds
something new (less than half of that rim agrees, or the change is larger
than 20 LAB units, such as a black jacket over skin), it is not drift: the
old pixels in that place show something else. The new part is then
compared with your untouched picture right beside it, each side averaged
within 48 pixels of the seam. Where the two sides look alike (within 20
LAB units, on at least a quarter of the seam, such as new skin next to
skin), the gap between them is taken off. Where they do not, such as a
jacket next to skin, Tone match leaves that picture as painted. Before,
the soft edge was read there instead, and a model that repaints the edge
too could tint the whole patch: a yellow swimsuit over skin came back blue.
On a Crop + Rotate + Pad canvas the source rectangle is the crop, so it
can also hold the rotation's empty corners and any transparency. The
+45 -37
View File
@@ -14,28 +14,43 @@ model that paints black regions.
- **Inputs**: Pick an existing input video (the list plays the clip under the pointer, muted, and filters as you type), click **Load**, or drop a video file
onto the node. The old source widgets remain compatible with saved workflows, but
are now driven by this compact card. Choosing another video keeps the canvas
settings - Fill, Feather, **Align**, Resize, Every nth, Frames for, Length - and
settings - Fill, Feather, **Align**, Resize, Every nth, Frames for, Duration - and
fits the new clip to the lit ratio button, the way **Fit** is set. Rotation, crop,
padding, IN/OUT and the playhead start over.
padding, the clip's timing and the playhead start over.
- **Outputs** (`source_mode` / `local_path`): Pick a video from ComfyUI's output folder,
such as one you just rendered. The list shows the newest first and previews the video
under the pointer. The video is read in place, without an upload copy. In an API prompt
it is named the way ComfyUI names a file there: `clip.mp4 [output]`. A whole path such
as `/home/me/ComfyUI/output/clip.mp4` is not read, for queued runs and the editor's live
preview alike.
- **Play / Pause** beside the scrubber previews the selected frames and stops at OUT. Press Play at OUT to start from IN again.
- **Timeline** (right under the preview and size line): The rail on the node and in the editor is one timeline. Press or
drag anywhere on it to scrub the **playhead**, with Length on or off; the stage shows
that frame. Drag the **IN** or **OUT** handle to trim: the playhead rides on the handle, so what you see
is the first (IN) or last (OUT) frame the run keeps, and it stays there when you let
go. IN and OUT are frames, snapped to the source's frame grid; the boxes under the
rail take a frame number, and `start_seconds` / `end_seconds` are derived from them
(OUT is exclusive, 0 means the end of the source). Arrow keys on a handle move one
second, Shift one frame. **OUT always sits on the last frame the run outputs**, so
the handle and the bright bar end together; with Every nth or Frames for it steps to the
frames the run keeps, and a dim tail marks frames the window holds but the run
drops. In the editor, **Set IN** / **Set OUT** (or the **I** / **O** keys) put a
trim point at the playhead, and **Full clip** resets the window. The editor also
- **Play / Pause** beside the timeline plays the clip from its start and stops at its end. Pause and Play again to carry on from where you stopped.
- **Timeline** (right under the picture): Press or drag anywhere on it to look at
another frame; the picture shows it. Point at the bar to see where you are, the
clip in words and the source's frame rate. Drag the **start** handle to move the
clip (its Duration stays), and the **end** handle to change the Duration. The
start stops where the whole Duration still fits, and a short note says so.
**Use as start** starts the clip at the frame on the picture.
- **Start / Duration / Ends at**: the clip in three boxes. Start and Ends at are
places in the source video; Duration is how long the clip is. Type any of them,
or drag over a box to scrub it. The small **s | fr** switch shows them in seconds
or frames: Start and Ends at count source frames, Duration counts the frames the
clip sends on, at the output rate. Point at a box for the other unit and what it
covers. Typing a Start that leaves too little video is allowed: an amber note says
how many frames still fit and offers to shorten the clip or move the start.
- **Linked timing**: when another node feeds `start_frame`, `end_frame`,
`frame_load_cap` or `fixed_frames`, that box is locked and its label shows a small
**linked** button that jumps to the node. `fixed_frames` is an exact count;
`frame_load_cap` is only a limit, so when the video ends first the note says how
many frames you get. A count only worked out when the graph runs (a Math
Expression, say) shows as **at run time**, and the timeline shows striped room
after the start instead of a clip. A rate typed inside a subgraph counts as known.
- **Technical details**: `start_seconds` / `end_seconds` are derived from the frames
(the end is exclusive, 0 means the end of the source), and the Duration is stored
as `max_frames`. Arrow keys on a handle move one second, Shift one frame. With
Every nth or Frames for the end steps to the frames the run keeps, and a dim tail
marks frames the window holds but the run drops.
In the editor, **Set IN** / **Set OUT** (or the **I** / **O** keys) put a
trim point at the playhead, and **Whole video** resets the clip. The editor also
has buttons for the first and last frame, steps of 1, 25, 50 and 100 frames, and
**Play**. Arrow keys step one frame (10 with Shift), Home and End jump to the
ends, and Space plays or pauses. **Save & close** keeps your edits; **Cancel** or
@@ -55,23 +70,16 @@ model that paints black regions.
fill colour with a faint hatch, so black bands show on the black stage. A fresh clip node starts
with black and feather 0 and the editor's **Reset transform** returns to them;
the image nodes keep their grey fill and feathered mask.
- **Length** (`max_frames`): the one other way to set how long the clip is. **Off**
(the default): OUT ends the clip. **On**: a number of output frames from IN; OUT
sits that many frames after IN and follows it when you drag IN, and dragging OUT or
typing the number changes the Length. To move the whole clip, drag IN or the small
grip in the middle of the kept part (the grip also slides a trimmed window with
Length off). When the Length is as long as the clip or longer, the row says
"= the whole clip": the clip's own end is OUT, and dragging IN starts the clip
later without changing the Length. The Length stays when you
swap the video, so a workflow built for 97 frames keeps taking 97. Turning it on or
off never moves anything: the count becomes the OUT, or the OUT the count. If the
source ends first, the footer says how many frames are left. **To start** moves IN
to the start of the source.
- **Whole video / To start** (bottom right of the timing card): **Whole video**
uses the whole source, with no Duration limit. When the length is linked, the
button reads **To start** and moves the start to the beginning instead. The
Duration stays when you swap the video, so a workflow built for 97 frames keeps
taking 97.
- **Every nth** (`every_nth`): Thin the batch. The `fps` output divides to match
every_nth, so the clip keeps real-time downstream; a Length counts the frames kept.
every_nth, so the clip keeps real-time downstream; a Duration counts the frames kept.
- **Frames for** (`frame_snap`): Keep a frame count a video model takes:
**LTX (8n+1)** (49, 97, 121) or **Wan (4n+1)**. **any** keeps every frame in the window.
OUT drags and the Length step through those counts.
Dragging the end and typing a Duration step through those counts.
With it on, `frame_count`, `duration`, the audio window and the stitcher all match the
clip the sampler hands back, so wiring `frame_count` into the empty latent's length
never leaves the stitch with more source frames than generated ones.
@@ -103,7 +111,7 @@ with the padlock on it also takes away the bands the lock added.
**Reset** on the node clears rotation, crop and padding and turns the padlock off;
fill, feather, **Align** and the timeline stay.
**Reset transform** in the editor resets rotation, crop, padding, fill, feather and
**Align**; it keeps the source, current frame, trim, Length, resize and stitch
**Align**; it keeps the source, current frame, trim, Duration, resize and stitch
settings. **Align** makes the width and height divide evenly by the number
you pick: padding grows by a few pixels, and a side with no padding is trimmed by
a few instead. Some models need sizes divisible by 8, 16 or 32; 1 turns it off.
@@ -163,8 +171,8 @@ Five optional sockets sit on the left, above the editor:
| `force_rate` | Sample at this fps before Every nth. 0 keeps the source rate. Drops or repeats frames to keep playback speed. Accepts FLOAT or INT. |
| `start_frame` | Zero-based source start frame. Overrides timeline IN. |
| `end_frame` | Exclusive source end frame. 0 means the end of the source. Overrides timeline OUT. |
| `fixed_frames` | Exact output frames from IN; the source must be long enough. Connected, it sets the length: OUT, Length and Frames for step aside. |
| `frame_load_cap` | Maximum frames after rate conversion and Every nth, before Frames for. 0 means unlimited. Connected, it sets the length in place of Length. When the count is known, dragging IN stops at the last start that fits the kept frames. |
| `fixed_frames` | Exact output frames from IN; the source must be long enough. Connected, it sets the length: Duration, Ends at and Frames for step aside. |
| `frame_load_cap` | Maximum frames after rate conversion and Every nth, before Frames for. 0 means unlimited. Connected, it sets the length in place of Duration. When the count is known, dragging the start stops at the last start that fits the kept frames. |
| `last_seconds` | Load only this many seconds from the end of the clip, or of the part before OUT. 0 loads all of it. Use it to carry on from a clip: a long clip then costs no more memory than a short one. |
Frame bounds use the source's frame-rate grid, independent of `force_rate`.
@@ -178,17 +186,17 @@ For example, start 24 and end 72 select two seconds from a 24 fps source.
A 12 fps forced rate returns 24 frames; a cap of 10 then keeps only the first
10 of those. Audio and duration follow the returned batch.
A connected start or end locks that handle and its IN/OUT field on both
A connected start or end locks that handle and its box on both
the node and fullscreen editor. Hover to see why. Disconnect to restore
local control. While timing inputs are connected, the preview shows the local
trim as a reference and avoids claiming an output count before the linked
values are evaluated at run time.
**A connected length input takes over the length.** Connect a count to
`fixed_frames` (exact) or `frame_load_cap` (at most) and the OUT handle goes
away, OUT and Length grey out, and only IN is left to set: the clip starts at
IN and the input decides where it ends. Literal Integer/Float nodes (including
`fixed_frames` (exact) or `frame_load_cap` (at most) and the end handle goes
away, Duration and Ends at lock, and only Start is left to set: the clip starts
there and the input decides where it ends. Literal Integer/Float nodes (including
AusBoss cards and reroutes) show the resulting frames on the rail before
running; calculated counts show "at run time". An older workflow that saved a
Fixed frames number without a connection reads as a Length; the first change
Fixed frames number without a connection reads as a Duration; the first change
here turns it into one.
+12 -4
View File
@@ -60,12 +60,20 @@ answered on the same line as the button.
- A found file swaps its Download button for an **✓ installed** pill; hovering
the pill shows where it was found. A file that lives in a subfolder still
counts. When a loader in the workflow still asks for the bare file name,
which ComfyUI cannot find there (it marks that loader red), the row says
where the file is instead (**in LTXV 2.3/**) and **Use it** points those
loaders at the copy it found. The check only asks the ComfyUI server for its
own model lists.
which ComfyUI cannot find there (it marks that loader red), the note points
that loader at your copy by itself and says so in a short message. If you
have two copies in different subfolders, the row says where one is
(**in LTXV 2.3/**) and **Use it** picks it. To always choose yourself, turn
off Settings, 🆎 AusBoss, Models, **Pick found files**. The check only asks
the ComfyUI server for its own model lists.
- **↻ check files** re-runs the check after you move files in. ComfyUI's own
**R** refresh triggers it as well.
- Launchers such as Stability Matrix keep models in shared folders of their
own, for example `Data/Models/Lora`. Files there count, and the card names
such a folder under the usual heading ("also read from ..."), so you can
see where your files are found and put new ones there. The old folder
names `clip` and `unet` are checked as `text_encoders` and
`diffusion_models`, the names ComfyUI uses for them.
- Folder `input` is for a sample image or clip shipped with the workflow: it
is looked for in `ComfyUI/input`.
- Clicking a file name copies it — handy for searching a loader's picker.
+14
View File
@@ -0,0 +1,14 @@
// On a Chinese ComfyUI (Settings > Language), the pack's own node faces show
// Chinese. js/shared/i18n.mjs holds the rules, js/shared/i18n_zh.mjs the words.
// The language is read when the page loads, so a change in Settings shows
// after a reload.
import { app } from "../../../scripts/app.js";
import { chineseActive, followFaces, useLocaleSource } from "../shared/i18n.mjs";
app.registerExtension({
name: "ausboss.i18n",
async setup() {
useLocaleSource(() => app.ui?.settings?.getSettingValue?.("Comfy.Locale"));
if (chineseActive()) followFaces(document.body);
},
});
+28 -13
View File
@@ -20,21 +20,36 @@ export function outputWindow(durationValue, startValue, endValue, maxValue = 0)
return { start, end, keepEnd, length: keepEnd - start, cut: Math.max(0, end - keepEnd) };
}
// "0:12.0" style, the way the IN and OUT fields write a time.
export function secondsLabel(value) {
const seconds = Math.max(0, finite(value));
if (seconds < 60) return `${seconds.toFixed(1)} s`;
const minutes = Math.floor(seconds / 60);
return `${minutes}:${(seconds - minutes * 60).toFixed(1).padStart(4, "0")}`;
const hundredth = (value) => Math.round(value * 100) / 100;
// What the face stores for a pick from `start` to `end`: a Start and a
// Duration (max_seconds, with end_seconds at 0, "to the end"). A pick that
// reaches the end of the file needs no Duration. When another node sets the
// Duration or the end, the pick is stored as a start and an end instead.
// A key left out is not written.
export function pickWrites(durationValue, startValue, endValue, { maxLinked = false, endLinked = false } = {}) {
const duration = Math.max(0, finite(durationValue));
const start = hundredth(Math.min(Math.max(0, finite(startValue)), duration));
const end = hundredth(Math.max(start, Math.min(finite(endValue), duration)));
const toEnd = end >= duration - 0.005;
if (endLinked) return { start };
if (maxLinked) return { start, end: toEnd ? 0 : end };
return { start, end: 0, max: toEnd ? 0 : Math.max(0.01, hundredth(end - start)) };
}
// The line between IN and OUT: what comes out, and what the max cuts off.
export function outputSummary(window, { maxFromLink = false } = {}) {
if (!window || window.length <= 0) return "";
const parts = [secondsLabel(window.length)];
if (window.cut > 0.005) parts.push(`cut ${secondsLabel(window.cut)}`);
if (maxFromLink) parts.push("max wired");
return parts.join(" · ");
// A value typed into Start, Duration or Ends at, as the pick it makes.
// Start keeps the Duration; Duration and Ends at keep the start. An empty
// or 0 Duration, and an empty Ends at, run to the end of the file.
export function typedPick(key, value, window, durationValue, minimum = 0.1) {
const duration = Math.max(0, finite(durationValue));
const clampTime = (time) => Math.min(duration, Math.max(0, finite(time)));
if (key === "start") {
const start = clampTime(value);
return { start, end: Math.min(duration, start + window.length) };
}
if (value == null || (key === "duration" && !(finite(value) > 0))) return { start: window.start, end: duration };
const end = key === "duration" ? window.start + Math.max(minimum, finite(value)) : Math.max(window.start + minimum, finite(value));
return { start: window.start, end: clampTime(end) };
}
// Loud and quiet across the file: for each of `buckets` slices, the lowest
+118 -110
View File
@@ -1,30 +1,35 @@
// Load Audio 🆎 - the wave, the trim and the player.
// Load Audio 🆎 - the wave, the timing and the player.
//
// The card above (js/widget_cards) holds Source and Max length. This panel
// draws the whole file as a wave: the part that comes out is bright, the
// part a Max length cuts off is red, and the rest is dim. Drag a handle to
// move IN or OUT, drag the middle to slide the pick, or click elsewhere to
// move it there. Play plays only what comes out. The widgets underneath
// (start_seconds, end_seconds, max_seconds) stay the source of truth.
// The card above (js/widget_cards) holds Source. This panel draws the whole
// file as a wave: the part that comes out is bright and the rest is dim.
// Under it, Start, Duration and Ends at, as on the video nodes. Drag a
// handle on the wave to move the start or the end, drag the middle to slide
// the sound, or click elsewhere to move it there. Play plays only what comes
// out. The widgets underneath stay the source of truth: the Duration is
// max_seconds with end_seconds at 0. A saved end (or a linked Max length)
// still works: the part a Max length cuts off shows red.
import { api } from "../../../scripts/api.js";
import { app } from "../../../scripts/app.js";
import { BRAND, chainCallback, keepDomWidgetWidthAuto, notifyAusbossChange, showToast } from "../shared/index.mjs";
import { keepKeyInField } from "../shared/canvas_passthrough.mjs";
import { WIDGET_FRAME, fillNodeHeight } from "../shared/panel_layout.mjs";
import { formatTimecode, parseTimecode } from "../shared/timecode.mjs";
import { formatTimecode } from "../shared/timecode.mjs";
import { inputNumber } from "../shared/clip_rate.mjs";
import { makeScrubInput } from "../shared/scrub_input.mjs";
import { linkedNodeInfo } from "../shared/timing_links.mjs";
import { parseImageReference } from "../shared/pad_canvas.mjs";
import { mediaViewQuery, splitMediaName } from "../shared/video_preview.mjs";
import { ensureVideoCss, hideCanvasWidget, makeToolButton } from "../shared/video_ui.mjs";
import { MIN_TRIM_SECONDS, dragTrimHandle, slideTrimWindow } from "../load_video/trim_preview.mjs";
import { grabZone, outputSummary, outputWindow, secondsLabel, wavePeaks } from "./audio_window.mjs";
import { grabZone, outputWindow, pickWrites, typedPick, wavePeaks } from "./audio_window.mjs";
const NODE_NAME = "AUSBOSS_NODES_LoadAudio";
const PANEL_WIDGET = "ausboss_load_audio_wave";
// The frontend's own player for an audio_upload input. The wave replaces it.
const CORE_AUDIO_WIDGET = "audioUI";
const MIN_WIDTH = 280;
// 8px root padding + the wave's 28px floor + 6px gap + the 22px play, IN/OUT and loop row.
const PANEL_MIN_HEIGHT = 64;
// 8px root padding + the wave's 28px floor + 6px gap + the 38px Start,
// Duration and Ends at row (a label over a box).
const PANEL_MIN_HEIGHT = 80;
// Opens small and neat: 300 px wide, with a wave about as tall as a field
// (32 px). Drag the corner down for a taller wave.
const DEFAULT_WIDTH = 300;
@@ -50,26 +55,32 @@ function hideCoreAudio(node) {
}
}
// A wired Max length: the number the wire carries, when the far end is a
// node that shows it (Float, Integer, a Primitive). null when it can't be known.
function wiredMax(node) {
const input = node.inputs?.find((slot) => slot?.widget?.name === "max_seconds");
if (!input || input.link == null) return { wired: false, value: null };
const graph = node.graph;
const link = graph?.getLink?.(input.link) ?? graph?.links?.get?.(input.link) ?? graph?.links?.[input.link];
const origin = link ? graph?.getNodeById?.(link.origin_id) : null;
const shown = origin?.widgets?.find((widget) => typeof widget?.value === "number");
return { wired: true, value: shown ? Number(shown.value) : null };
function linked(node, name) {
return !!node.inputs?.some((slot) => slot?.widget?.name === name && slot.link != null);
}
// A value as the run will see it: the widget, or the number a linked input
// carries when the far end is a typed number (through Reroutes and
// subgraphs). null when only the run knows it.
function valueOf(state, name, widget) {
if (!linked(state.node, name)) return Number(widget?.value) || 0;
return inputNumber(state.node, name, null);
}
function maxSeconds(state) {
const wired = wiredMax(state.node);
if (wired.wired) return { value: wired.value ?? 0, fromLink: true, known: wired.value != null };
return { value: Number(state.maxWidget?.value) || 0, fromLink: false, known: true };
const fromLink = linked(state.node, "max_seconds");
const value = valueOf(state, "max_seconds", state.maxWidget);
return { value: value ?? 0, fromLink, known: value != null };
}
function currentWindow(state) {
return outputWindow(state.duration, state.startWidget.value, state.endWidget.value, maxSeconds(state).value);
const start = valueOf(state, "start_seconds", state.startWidget) ?? 0;
const max = maxSeconds(state).value;
let end = valueOf(state, "end_seconds", state.endWidget) ?? 0;
// No end and a Duration: the Duration is where the sound stops, so
// nothing past it shows as cut off. Only an end past the Duration does.
if (!(end > 0) && max > 0 && state.duration > 0) end = Math.min(state.duration, Math.max(0, start) + max);
return outputWindow(state.duration, start, end, max);
}
async function loadPeaks(name, route) {
@@ -105,16 +116,15 @@ function ensureAudioCss() {
.ausboss-audio-error{pointer-events:auto;border:0;background:transparent;color:#e6bf87;font:11px system-ui;cursor:pointer;white-space:nowrap}
.ausboss-audio-root canvas.ausboss-audio-wave{position:absolute;inset:0;width:100%;height:100%;display:block;}
.ausboss-audio-root .ausboss-video-stage:not(.is-empty) .ausboss-video-status{display:none;}
.ausboss-audio-root .ausboss-audio-row{display:flex;align-items:center;gap:6px;flex:none;padding:0 2px;}
.ausboss-audio-root .ausboss-audio-row .ausboss-video-values{flex:1 1 auto;min-width:0;}
.ausboss-audio-root .ausboss-audio-play{min-width:30px;font-size:10px;}
.ausboss-audio-root .ausboss-audio-length{flex:none;padding:0 2px;color:#7fd9d2;font-size:10px;font-variant-numeric:tabular-nums;white-space:nowrap;cursor:default;}
.ausboss-audio-root .ausboss-audio-length:empty{display:none;}
.ausboss-audio-root .ausboss-audio-length.has-cut{color:#ff9aa0;cursor:pointer;text-decoration:underline dotted rgba(224,82,90,.8);text-underline-offset:2px;}
.ausboss-audio-root .ausboss-audio-row .ausboss-video-tool{flex:none;}
.ausboss-audio-root .ausboss-video-values{display:flex;gap:8px;}
.ausboss-audio-root .ausboss-video-value input{width:48px;}
.ausboss-audio-root .ausboss-audio-length{margin-left:auto;}
.ausboss-audio-root .ausboss-audio-wave-row{display:flex;align-items:stretch;gap:6px;flex:1 1 auto;min-height:28px;}
.ausboss-audio-root .ausboss-audio-wave-row .ausboss-video-stage{flex:1 1 auto;min-width:0;}
.ausboss-audio-root .ausboss-audio-play{flex:none;align-self:center;min-width:30px;font-size:10px;}
.ausboss-audio-fields{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:6px;flex:none;padding:0 2px;color:#ddd;font:11px system-ui;}
.ausboss-audio-field{display:flex;flex-direction:column;gap:2px;min-width:0;}
.ausboss-audio-field .ausboss-scrub{width:100%;box-sizing:border-box;}
.ausboss-audio-field-label{display:flex;align-items:center;gap:6px;min-width:0;color:#cadddb;}
.ausboss-audio-go{border:0;background:transparent;padding:0;color:#45d6cb;font:600 10px system-ui;text-decoration:underline;cursor:pointer;}
.ausboss-audio-go[hidden]{display:none;}
`;
document.head.appendChild(style);
}
@@ -192,21 +202,31 @@ function draw(state) {
}
}
// One box's look: its value, whether it can be typed, and the "linked"
// button when another node sets it.
function showField(state, key, value, lockedBy, tip) {
const field = state.fields[key];
field.control.set(value);
field.control.root.style.opacity = lockedBy ? ".45" : "";
field.control.root.inert = Boolean(lockedBy);
field.go.hidden = !lockedBy;
field.cell.title = lockedBy ? `Set by ${lockedBy.title}. Click "linked" to go to that node.` : tip;
if (lockedBy) field.go.onclick = () => lockedBy.go?.();
}
function updateFace(state) {
const win = currentWindow(state);
const max = maxSeconds(state);
if (document.activeElement !== state.startInput) state.startInput.value = formatTimecode(win.start);
if (document.activeElement !== state.endInput) state.endInput.value = formatTimecode(win.end);
if (state.duration > 0) {
const summary = outputSummary(win, { maxFromLink: max.fromLink && !max.known });
state.summary.textContent = win.length > 0 ? secondsLabel(win.length) : "";
state.summary.classList.toggle("has-cut", win.cut > 0.005);
state.summary.title = win.cut > 0.005
? `${summary}. Max length is ${max.value} s, so ${formatTimecode(win.keepEnd)} to ${formatTimecode(win.end)} is cut off (red). Click to move OUT to ${formatTimecode(win.keepEnd)}.`
: `${summary}: ${formatTimecode(win.start)} to ${formatTimecode(win.keepEnd)} comes out.`;
} else {
state.summary.textContent = "";
}
const link = (name) => (linked(state.node, name) ? linkedNodeInfo(state.node, name) : null);
// A linked value the page cannot read is only known when the graph runs:
// its box, and the boxes that depend on it, stay empty.
const known = (name) => !linked(state.node, name) || inputNumber(state.node, name, null) != null;
const has = state.duration > 0;
const startKnown = has && known("start_seconds");
const lengthKnown = startKnown && known("max_seconds") && known("end_seconds");
showField(state, "start", startKnown ? win.start : null, link("start_seconds"), `Where the sound starts in the file, of ${formatTimecode(state.duration)}.`);
showField(state, "duration", lengthKnown ? win.length : null, link("max_seconds"),
win.cut > 0.005 ? `How long the sound is. It stops ${formatTimecode(win.cut)} before the saved end (red).` : "How long the sound is. Clear it, or type 0, to run to the end of the file.");
showField(state, "end", lengthKnown ? win.keepEnd : null, link("end_seconds"), "Where the sound stops in the file. Typing it changes the Duration.");
draw(state);
}
@@ -217,12 +237,19 @@ function writeWidget(widget, value) {
widget.callback?.(next);
}
// The pick, stored the way the face shows it (pickWrites): a Start and a
// Duration, or a start and an end when another node sets the Duration.
function writeTrim(state, bounds) {
state.writing = true;
try {
writeWidget(state.startWidget, bounds.start);
// OUT at the very end stays 0, the widget's own "to the end".
writeWidget(state.endWidget, bounds.end >= state.duration - 0.005 ? 0 : bounds.end);
const startLinked = linked(state.node, "start_seconds");
const writes = pickWrites(state.duration, startLinked ? currentWindow(state).start : bounds.start, bounds.end, {
maxLinked: linked(state.node, "max_seconds") || !state.maxWidget,
endLinked: linked(state.node, "end_seconds"),
});
if (!startLinked) writeWidget(state.startWidget, writes.start);
if (writes.end !== undefined) writeWidget(state.endWidget, writes.end);
if (writes.max !== undefined) writeWidget(state.maxWidget, writes.max);
} finally {
state.writing = false;
}
@@ -248,7 +275,7 @@ function installDrag(state) {
event.preventDefault();
event.stopPropagation();
const initial = infoAt(event.clientX);
const bounds = { start: initial.win.start, end: initial.win.end };
const bounds = { start: initial.win.start, end: initial.win.keepEnd };
const anchor = initial.fraction * state.duration;
const downX = event.clientX;
let moved = false;
@@ -262,7 +289,7 @@ function installDrag(state) {
const next = infoAt(clientX);
if (initial.zone === "start" || initial.zone === "end") {
const now = currentWindow(state);
writeTrim(state, dragTrimHandle(state.duration, { start: now.start, end: now.end }, initial.zone, next.fraction, MIN_TRIM_SECONDS));
writeTrim(state, dragTrimHandle(state.duration, { start: now.start, end: now.keepEnd }, initial.zone, next.fraction, MIN_TRIM_SECONDS));
} else if (initial.zone === "move") {
writeTrim(state, slideTrimWindow(state.duration, bounds, next.fraction * state.duration - anchor));
} else {
@@ -336,19 +363,6 @@ function installPlayer(state) {
state.stopPlayer = () => { audio.pause(); stop(); };
}
function commitTimeInput(state, edge, input) {
if (state.duration <= 0) return;
const seconds = parseTimecode(input.value);
const win = currentWindow(state);
if (seconds === null) {
input.value = formatTimecode(edge === "start" ? win.start : win.end);
return;
}
writeTrim(state, dragTrimHandle(state.duration, { start: win.start, end: win.end }, edge, seconds / state.duration, MIN_TRIM_SECONDS));
notifyAusbossChange();
input.blur();
}
function watchWidget(state, widget) {
if (!widget || widget.__ausbossAudioWatch) return;
widget.__ausbossAudioWatch = true;
@@ -385,37 +399,44 @@ function buildPanel(node) {
playButton.classList.add("ausboss-audio-play");
const loopButton = makeToolButton("LOOP", "Play it again and again");
stage.append(canvas, status);
// Play and Loop sit either side of the wave, so neither covers a handle.
loopButton.classList.add("ausboss-audio-play");
const waveRow = document.createElement("div");
waveRow.className = "ausboss-audio-wave-row";
waveRow.append(playButton, stage, loopButton);
const values = document.createElement("div");
values.className = "ausboss-video-values";
const makeValue = (labelText, title) => {
const wrap = document.createElement("div");
wrap.className = "ausboss-video-value";
const label = document.createElement("label");
label.textContent = labelText;
const input = document.createElement("input");
input.type = "text";
input.inputMode = "decimal";
input.placeholder = "m:ss.s";
input.title = title;
input.addEventListener("keydown", (event) => {
keepKeyInField(event);
if (event.key === "Enter") input.dispatchEvent(new Event("change"));
});
wrap.append(label, input);
return { wrap, input };
// Start, Duration and Ends at, as on the video nodes, in seconds.
const fieldsRow = document.createElement("div");
fieldsRow.className = "ausboss-audio-fields";
const fields = {};
const commit = (key, value) => {
const state = node.__ausbossLoadAudio;
if (!state || state.duration <= 0) return;
writeTrim(state, typedPick(key, value, currentWindow(state), state.duration, MIN_TRIM_SECONDS));
};
const startValue = makeValue("IN", "Where the sound starts. Type seconds (12.5) or a time (0:12.5).");
const endValue = makeValue("OUT", "Where the sound stops. Type seconds (24) or a time (0:24.0).");
// How long the output is, beside OUT and off the wave. Red when Max
// length cuts the pick short; the tooltip says how much.
const summary = document.createElement("div");
summary.className = "ausboss-audio-length";
values.append(startValue.wrap, endValue.wrap);
const row = document.createElement("div");
row.className = "ausboss-audio-row";
row.append(playButton, values, summary, loopButton);
root.append(stage, row);
for (const [key, caption] of [["start", "Start"], ["duration", "Duration"], ["end", "Ends at"]]) {
const cell = document.createElement("div");
cell.className = "ausboss-audio-field";
const label = document.createElement("span");
label.className = "ausboss-audio-field-label";
label.textContent = caption;
const go = document.createElement("button");
go.type = "button";
go.className = "ausboss-audio-go";
go.textContent = "linked";
go.hidden = true;
label.append(go);
const control = makeScrubInput({
value: 0, min: 0, max: 86400, step: 0.1, fineStep: 0.01, decimals: 2, minDecimals: 0, unit: "s", unitWidth: 14,
allowEmpty: true,
onChange: (value) => commit(key, value),
onSettle: () => notifyAusbossChange(),
});
cell.append(label, control.root);
fieldsRow.append(cell);
fields[key] = { cell, control, go };
}
root.append(waveRow, fieldsRow);
const widget = node.addDOMWidget(PANEL_WIDGET, "ausboss_audio", root, {
serialize: false,
@@ -435,22 +456,11 @@ function buildPanel(node) {
audio.preload = "auto";
const abort = new AbortController();
const state = node.__ausbossLoadAudio = {
node, root, stage, canvas, status, playButton, loopButton, summary, audio,
startInput: startValue.input, endInput: endValue.input,
node, root, stage, canvas, status, playButton, loopButton, audio, fields,
audioWidget, startWidget, endWidget, maxWidget: findWidget(node, "max_seconds"),
duration: 0, peaks: null, abort, writing: false, dragging: false, raf: 0, loading: 0,
};
// Clicking the red length moves OUT to where the sound really ends.
summary.addEventListener("click", (event) => {
const win = currentWindow(state);
if (win.cut <= 0.005) return;
event.preventDefault();
event.stopPropagation();
writeTrim(state, { start: win.start, end: win.keepEnd });
notifyAusbossChange();
});
const updateLoop = () => loopButton.classList.toggle("active", loopEnabled(node));
updateLoop();
loopButton.addEventListener("click", (event) => {
@@ -509,8 +519,6 @@ function buildPanel(node) {
watchWidget(state, startWidget);
watchWidget(state, endWidget);
watchWidget(state, state.maxWidget);
startValue.input.addEventListener("change", () => commitTimeInput(state, "start", startValue.input));
endValue.input.addEventListener("change", () => commitTimeInput(state, "end", endValue.input));
const observer = new ResizeObserver(() => draw(state));
observer.observe(stage);
state.observer = observer;
+145 -355
View File
@@ -1,9 +1,11 @@
import { api } from "../../../scripts/api.js";
import { app } from "../../../scripts/app.js";
import { chainCallback, keepDomWidgetWidthAuto, notifyAusbossChange } from "../shared/index.mjs";
import { keepKeyInField } from "../shared/canvas_passthrough.mjs";
import { WIDGET_FRAME, fillNodeHeight } from "../shared/panel_layout.mjs";
import { formatTimecode, parseTimecode } from "../shared/timecode.mjs";
import { inputNumber } from "../shared/clip_rate.mjs";
import { clipInfo, windowSeconds } from "../shared/timeline_math.mjs";
import { mountTransformTrim } from "../shared/transform_trim.mjs";
import { linkedNodeInfo, timingUnits } from "../shared/timing_links.mjs";
import { parseImageReference } from "../shared/pad_canvas.mjs";
import {
mediaInfo,
@@ -19,42 +21,31 @@ import {
suppressCoreVideoPreview,
} from "../shared/video_ui.mjs";
import {
MIN_TRIM_SECONDS,
clampTrimSeek,
closestTrimHandle,
dragTrimHandle,
loadSummary,
playbackBoundaryAction,
singleFrameFraction,
singleFrameTime,
slideTrimWindow,
trimAfterFramePick,
trimBounds,
trimFractions,
} from "./trim_preview.mjs";
const NODE_NAME = "AUSBOSS_NODES_LoadVideo";
const PREVIEW_WIDGET = "ausboss_load_video_viewer";
const PREVIEW_CHROME = 88;
// The shared video root's CSS minimum: 8px root padding + the stage's 112px
// floor + 6px gap + the 76px trim strip. The declared floor adds
// WIDGET_FRAME on top, or the element comes up short and clips the trim
// strip's bottom border at the node's minimum height.
const PANEL_MIN_HEIGHT = 202;
// 8px root padding + the stage's 112px floor + 6px gap + the 152px timing
// card (js/shared/transform_trim.mjs). The declared floor adds WIDGET_FRAME
// on top, or the element comes up short and clips the card's bottom border
// at the node's minimum height.
const PANEL_MIN_HEIGHT = 278;
// Height the node opens at. It used to fall out of the panel's computeSize;
// with the panel free to follow the node, the default has to be stated. The
// chrome covers the transport row and the trim strip under the player.
const DEFAULT_NODE_SIZE = [380, responsivePreviewHeight(380) + PREVIEW_CHROME + 190];
// extra covers the tools over the picture and the timing card under it.
const DEFAULT_NODE_SIZE = [380, responsivePreviewHeight(380) + PREVIEW_CHROME + 210];
const TRIM_EPSILON = 0.04;
function findWidget(node, name) {
return node.widgets?.find((widget) => widget.name === name);
}
function roundHundredth(value) {
return Math.round(Number(value || 0) * 100) / 100;
}
function getLoopEnabled(node) {
node.properties ??= {};
if (node.properties.ausboss_load_video_loop === undefined) {
@@ -66,14 +57,25 @@ function getLoopEnabled(node) {
function setEmpty(state, text) {
state.stage.classList.add("is-empty");
state.status.textContent = text;
state.status.hidden = false;
}
function setReady(state, text) {
state.stage.classList.remove("is-empty");
state.status.textContent = text;
state.status.hidden = !text;
}
// The run's window in seconds, as the timing card works it out (Start, and
// the Duration or the end), or the plain start/end before the video's frame
// rate is known.
function currentBounds(state) {
const info = clipInfo(state.metadata);
const window = state.card?.window?.();
if (info.fps > 0 && window && Number.isFinite(window.first)) {
const last = Number.isFinite(window.last) ? window.last : info.count - 1;
return { start: window.first / info.fps, end: Math.min(info.duration || Infinity, (last + 1) / info.fps) };
}
return trimBounds(state.video.duration, state.startWidget.value, state.endWidget.value);
}
@@ -82,271 +84,116 @@ function isSingleFrame(state) {
}
// Where the preview belongs for the current mode: the chosen frame, or the
// trim window's IN point.
// clip's start.
function homeTime(state) {
return isSingleFrame(state)
? singleFrameTime(state.video.duration, state.startWidget.value)
: currentBounds(state).start;
}
function applyMode(state) {
const single = isSingleFrame(state);
state.root.classList.toggle("is-single-frame", single);
state.frameButton?.classList.toggle("active", single);
state.startLabel.textContent = single ? "AT" : "IN";
state.range.title = single
? "Drag or click to choose the frame that loads"
: "Drag either handle to set the trim; drag the selected range to move it";
updateTrimFace(state);
}
function widgetLinkDriven(node, name) {
return !!node.inputs?.some((input) => input?.widget?.name === name && input.link != null);
}
// The honest "what will actually load" text for the label under the trim
// strip, or "" when there is nothing honest to say. Any of the deciding
// widgets driven by a link means its face value is stale, so the count
// drops out rather than guessing.
function trimLoadSummary(state, duration, bounds) {
const deciders = ["start_seconds", "end_seconds", "every_nth", "max_frames", "single_frame"];
if (deciders.some((name) => widgetLinkDriven(state.node, name))) return "";
return loadSummary(
duration,
bounds,
state.sourceFps,
state.everyNthWidget?.value,
state.maxFramesWidget?.value,
isSingleFrame(state),
);
}
// The <video> element never exposes the source frame rate, so the frame
// count in the label needs a probe of the pack's metadata route. Fail-soft:
// on any error the label simply omits the count and the timecodes stand.
async function probeSourceFps(state, name) {
state.sourceFps = 0;
// Frame rate and the real frame count come from the pack's metadata route:
// the <video> element knows neither, and its length rounds up a frame.
// Fail-soft: without it the card waits for a source.
async function probeMetadata(state, name) {
state.metadata = null;
try {
const query = new URLSearchParams({ source_mode: "input folder", video: name });
const type = parseImageReference(name)?.type;
if (type && type !== "input") {
query.set("source_mode", "local path");
query.set("local_path", name);
}
const response = await api.fetchApi(`/ausboss/transform/video/metadata?${query}`);
if (!response.ok) return;
const metadata = await response.json();
if (state.videoWidget.value !== name) return; // a newer selection won
state.sourceFps = Math.max(0, Number(metadata?.fps) || 0);
updateTrimFace(state);
state.metadata = metadata;
state.card?.sync();
} catch (_error) {
/* no fps, no frame count */
/* no metadata, no timing card numbers */
}
}
function writeWidget(widget, value) {
const next = roundHundredth(value);
if (Math.abs(Number(widget.value || 0) - next) < 0.0001) return;
widget.value = next;
widget.callback?.(next);
function setWidget(widget, value) {
if (!widget) return;
if (widget.value === value) return;
widget.value = value;
widget.callback?.(value);
}
function writeTrim(state, bounds, seekEdge = null) {
state.writing = true;
try {
writeWidget(state.startWidget, bounds.start);
writeWidget(state.endWidget, bounds.end);
} finally {
state.writing = false;
}
updateTrimFace(state);
if (state.video.readyState >= 1 && seekEdge) {
state.video.currentTime = seekEdge === "start"
? bounds.start
: Math.max(bounds.start, bounds.end - TRIM_EPSILON);
}
state.node.setDirtyCanvas?.(true, true);
state.node.graph?.setDirtyCanvas?.(true, true);
}
function writeFrameTime(state, timeValue) {
const duration = Number.isFinite(state.video.duration) ? state.video.duration : 0;
const time = singleFrameTime(duration, timeValue);
state.writing = true;
try {
writeWidget(state.startWidget, time);
} finally {
state.writing = false;
}
updateTrimFace(state);
if (state.video.readyState >= 1) state.video.currentTime = time;
state.node.setDirtyCanvas?.(true, true);
state.node.graph?.setDirtyCanvas?.(true, true);
}
function updateTrimFace(state) {
const duration = Number.isFinite(state.video.duration) ? state.video.duration : 0;
if (isSingleFrame(state)) {
const time = singleFrameTime(duration, state.startWidget.value);
const percent = singleFrameFraction(duration, time) * 100;
state.selection.style.width = "0%";
state.startHandle.style.left = `${percent}%`;
if (document.activeElement !== state.startInput) state.startInput.value = formatTimecode(time);
// "1 frame at 0:05.2" - the count comes from the same pure summary the
// trim label uses, so both modes report what one Run will load.
const summary = trimLoadSummary(state, duration, null);
state.durationLabel.textContent = duration > 0
? `${summary || "frame"} at ${formatTimecode(time)}`
: "load a video to pick a frame";
if (duration > 0) state.status.textContent = `frame at ${formatTimecode(time)}`;
return;
}
const bounds = trimBounds(duration, state.startWidget.value, state.endWidget.value);
const fractions = trimFractions(duration, bounds);
const startPercent = fractions.start * 100;
const endPercent = fractions.end * 100;
state.selection.style.left = `${startPercent}%`;
state.selection.style.width = `${Math.max(0, endPercent - startPercent)}%`;
state.startHandle.style.left = `${startPercent}%`;
state.endHandle.style.left = `${endPercent}%`;
if (document.activeElement !== state.startInput) state.startInput.value = formatTimecode(bounds.start);
if (document.activeElement !== state.endInput) state.endInput.value = formatTimecode(bounds.end);
const selected = Math.max(0, bounds.end - bounds.start);
// The preview cannot re-render every_nth or max_frames, so the label
// reports them instead: "0:04.0 of 0:10.0 · 48 frames @ 12 fps".
const summary = trimLoadSummary(state, duration, bounds);
state.durationLabel.textContent = duration > 0
? `${formatTimecode(selected)} of ${formatTimecode(duration)}${summary ? ` · ${summary}` : ""}`
: "load a video to trim";
state.status.textContent = duration > 0
? `${formatTimecode(bounds.start)} → ${formatTimecode(bounds.end)}`
: state.status.textContent;
}
function installTrimDrag(state) {
const { range } = state;
const infoAt = (clientX) => {
const rect = range.getBoundingClientRect();
const duration = Number.isFinite(state.video.duration) ? state.video.duration : 0;
const bounds = currentBounds(state);
const fractions = trimFractions(duration, bounds);
const x = clientX - rect.left;
const hit = 10;
let zone = "jump";
const closest = closestTrimHandle(
fractions.start,
fractions.end,
rect.width ? x / rect.width : 0,
rect.width,
hit,
);
if (closest) zone = closest;
else if (x > fractions.start * rect.width && x < fractions.end * rect.width) zone = "move";
return { rect, duration, bounds, fraction: rect.width ? x / rect.width : 0, zone };
};
range.addEventListener("pointermove", (event) => {
if (state.dragging) return;
if (isSingleFrame(state)) {
range.style.cursor = "ew-resize";
return;
}
const { zone } = infoAt(event.clientX);
range.style.cursor = zone === "start" || zone === "end"
? "ew-resize"
: zone === "move" ? "grab" : "pointer";
});
range.addEventListener("pointerdown", (event) => {
if (event.button !== 0 || state.dragging) return;
const initial = infoAt(event.clientX);
if (initial.duration <= 0) return;
event.preventDefault();
event.stopPropagation();
if (isSingleFrame(state)) {
// Frame-picker gesture: the strip is one scrub rail. A click already
// sets the frame; a drag keeps refining it until release.
state.dragging = true;
try { range.setPointerCapture(event.pointerId); } catch (_error) { /* mouse fallback */ }
const scrub = (clientX) => {
const next = infoAt(clientX);
writeFrameTime(state, next.fraction * next.duration);
};
scrub(event.clientX);
const move = (moveEvent) => {
if (!(moveEvent.buttons & 1)) { finish(); return; }
scrub(moveEvent.clientX);
};
const finish = () => {
if (!state.dragging) return;
state.dragging = false;
range.removeEventListener("pointermove", move);
try { range.releasePointerCapture(event.pointerId); } catch (_error) { /* already released */ }
// One notification per gesture: the frame changed on pointerdown.
notifyAusbossChange();
};
range.addEventListener("pointermove", move);
range.addEventListener("pointerup", finish, { once: true });
range.addEventListener("pointercancel", finish, { once: true });
range.addEventListener("lostpointercapture", finish, { once: true });
return;
}
state.dragging = true;
try { range.setPointerCapture(event.pointerId); } catch (_error) { /* mouse fallback */ }
const downX = event.clientX;
const anchorTime = initial.fraction * initial.duration;
let moved = false;
const apply = (clientX) => {
const next = infoAt(clientX);
if (initial.zone === "start" || initial.zone === "end") {
writeTrim(
state,
dragTrimHandle(next.duration, currentBounds(state), initial.zone, next.fraction),
initial.zone,
);
} else if (initial.zone === "move") {
const pointerTime = next.fraction * next.duration;
writeTrim(
state,
slideTrimWindow(next.duration, initial.bounds, pointerTime - anchorTime),
"start",
);
} else {
const span = initial.bounds.end - initial.bounds.start;
const centeredStart = next.fraction * next.duration - span / 2;
writeTrim(
state,
slideTrimWindow(next.duration, initial.bounds, centeredStart - initial.bounds.start),
"start",
);
// The timing card: the clip node's own, with Start, Duration and Ends at,
// or, while FRAME is on, its frame picker. The player above it is the
// picture, so the card leaves out its own Play button.
function mountCard(state) {
const { node } = state;
const widgetFor = (name) => node.widgets?.find((widget) => widget.name === name);
const fps = () => clipInfo(state.metadata).fps;
const single = isSingleFrame(state);
const card = mountTransformTrim({
get: (name, fallback) => {
if (name === "frame_index") return state.head ?? 0;
const widget = widgetFor(name);
return widget ? widget.value : fallback;
},
set: (name, value) => {
state.writing = true;
try { setWidget(widgetFor(name), value); } finally { state.writing = false; }
if (state.video.readyState >= 1 && !state.video.paused) return;
node.setDirtyCanvas?.(true, true);
},
has: (name) => Boolean(widgetFor(name)),
driven: (name) => widgetLinkDriven(node, name),
number: (name, fallback) => inputNumber(node, name, fallback),
metadata: () => state.metadata,
trim: !single,
play: false,
isPlaying: () => !state.video.paused,
onTogglePlayback: () => {},
onSeek: (frame, settled) => {
state.head = frame;
const rate = fps();
if (single && rate > 0) {
state.writing = true;
try { setWidget(state.startWidget, windowSeconds(clipInfo(state.metadata), frame, frame).start_seconds); } finally { state.writing = false; }
}
};
const move = (moveEvent) => {
if (!(moveEvent.buttons & 1)) { finish(moveEvent); return; }
if (!moved && Math.abs(moveEvent.clientX - downX) < 3) return;
moved = true;
apply(moveEvent.clientX);
};
const finish = (finishEvent) => {
if (!state.dragging) return;
state.dragging = false;
range.removeEventListener("pointermove", move);
try { range.releasePointerCapture(event.pointerId); } catch (_error) { /* already released */ }
if (!moved && initial.zone === "jump") {
const next = infoAt(finishEvent?.clientX ?? downX);
const span = initial.bounds.end - initial.bounds.start;
const centeredStart = next.fraction * next.duration - span / 2;
writeTrim(
state,
slideTrimWindow(next.duration, initial.bounds, centeredStart - initial.bounds.start),
"start",
);
}
// One notification per gesture, on release — never per pointermove.
if (moved || initial.zone === "jump") notifyAusbossChange();
};
range.addEventListener("pointermove", move);
range.addEventListener("pointerup", finish, { once: true });
range.addEventListener("pointercancel", finish, { once: true });
range.addEventListener("lostpointercapture", finish, { once: true });
if (state.video.readyState >= 1 && rate > 0) state.video.currentTime = Math.min(state.video.duration || Infinity, (frame + 0.5) / rate);
if (settled) notifyAusbossChange();
},
onCommit: notifyAusbossChange,
linkInfo: (name) => linkedNodeInfo(node, name),
units: () => timingUnits(),
setUnits: (next) => timingUnits(next),
});
state.card?.root.remove();
state.card = card;
state.cardSlot.append(card.root);
return card;
}
function applyMode(state) {
const single = isSingleFrame(state);
state.root.classList.toggle("is-single-frame", single);
state.frameButton?.classList.toggle("active", single);
if (state.cardMode !== single) {
state.cardMode = single;
mountCard(state);
}
state.card?.sync();
}
// The playhead follows the player, so the card's marker and readout move
// with the picture.
function followPlayer(state) {
const rate = clipInfo(state.metadata).fps;
if (!(rate > 0)) return;
const frame = Math.max(0, Math.floor(state.video.currentTime * rate + 1e-6));
if (frame === state.head) return;
state.head = frame;
state.card?.sync();
}
function installPlayback(state) {
@@ -356,9 +203,9 @@ function installPlayback(state) {
state.playRaf = 0;
};
const tick = () => {
if (video.paused || video.ended) { stopTick(); return; }
// Frame picking plays the whole source freely — the trim window is not
// in force, so there is no boundary to loop or stop at.
if (video.paused || video.ended) { stopTick(); followPlayer(state); return; }
// Frame picking plays the whole source freely - the clip is not in
// force, so there is no boundary to loop or stop at.
if (!isSingleFrame(state)) {
const bounds = currentBounds(state);
const action = playbackBoundaryAction(video.currentTime, bounds, getLoopEnabled(state.node), TRIM_EPSILON);
@@ -367,9 +214,11 @@ function installPlayback(state) {
} else if (action === "stop") {
video.pause();
video.currentTime = Math.max(bounds.start, bounds.end - TRIM_EPSILON);
followPlayer(state);
return;
}
}
followPlayer(state);
state.playRaf = requestAnimationFrame(tick);
};
video.addEventListener("play", () => {
@@ -390,7 +239,7 @@ function installPlayback(state) {
state.correctingSeek = true;
video.currentTime = target;
}, { signal: state.abort.signal });
video.addEventListener("seeked", () => { state.correctingSeek = false; }, { signal: state.abort.signal });
video.addEventListener("seeked", () => { state.correctingSeek = false; followPlayer(state); }, { signal: state.abort.signal });
state.stopTick = stopTick;
}
@@ -401,8 +250,8 @@ function watchTrimWidget(state, widget) {
widget.callback = function (...args) {
const result = prior?.apply(this, args);
if (!state.writing) {
updateTrimFace(state);
if (state.video.readyState >= 1) state.video.currentTime = homeTime(state);
state.card?.sync();
if (state.video.readyState >= 1 && state.video.paused) state.video.currentTime = homeTime(state);
}
return result;
};
@@ -416,7 +265,10 @@ function watchFrameWidget(state, widget) {
const result = prior?.apply(this, args);
if (!isSingleFrame(state)) {
const reopened = trimAfterFramePick(state.startWidget.value, state.endWidget.value);
if (reopened) writeTrim(state, reopened);
if (reopened) {
state.writing = true;
try { setWidget(state.endWidget, reopened.end); } finally { state.writing = false; }
}
}
applyMode(state);
if (state.video.readyState >= 1) state.video.currentTime = homeTime(state);
@@ -424,28 +276,6 @@ function watchFrameWidget(state, widget) {
};
}
function commitTimeInput(state, edge, input) {
const duration = Number.isFinite(state.video.duration) ? state.video.duration : 0;
if (duration <= 0) return;
const seconds = parseTimecode(input.value);
if (seconds === null) {
// Malformed entry: restore the previous value and keep focus for a retry.
const bounds = currentBounds(state);
input.value = formatTimecode(edge === "start" ? bounds.start : bounds.end);
return;
}
if (isSingleFrame(state)) {
writeFrameTime(state, seconds);
notifyAusbossChange();
input.blur();
return;
}
const fraction = seconds / duration;
writeTrim(state, dragTrimHandle(duration, currentBounds(state), edge, fraction), edge);
notifyAusbossChange();
input.blur();
}
function buildPreview(node) {
if (node.__ausbossLoadVideo) return node.__ausbossLoadVideo;
const videoWidget = findWidget(node, "video");
@@ -461,6 +291,8 @@ function buildPreview(node) {
hideCanvasWidget(startWidget);
hideCanvasWidget(endWidget);
if (frameWidget) hideCanvasWidget(frameWidget);
// Every nth and the frame limit (the Duration) live in the timing card;
// the widget card hides their widgets (js/widget_cards).
const root = document.createElement("div");
root.className = "ausboss-video-root";
@@ -475,7 +307,7 @@ function buildPreview(node) {
status.textContent = "Choose or upload a video";
const tools = document.createElement("div");
tools.className = "ausboss-video-tools";
const loopButton = makeToolButton("LOOP", "Loop playback inside the selected trim");
const loopButton = makeToolButton("LOOP", "Play the clip again and again");
loopButton.classList.add("ausboss-video-loop");
const reloadButton = makeToolButton("↻", "Reload the selected source video");
const frameButton = frameWidget
@@ -485,45 +317,12 @@ function buildPreview(node) {
tools.append(loopButton, reloadButton);
stage.append(video, status, tools);
const trim = document.createElement("div");
trim.className = "ausboss-video-trim";
const range = document.createElement("div");
range.className = "ausboss-video-range";
range.title = "Drag either handle to set the trim; drag the selected range to move it";
const selection = document.createElement("div");
selection.className = "ausboss-video-selection";
const startHandle = document.createElement("div");
startHandle.className = "ausboss-video-handle";
const endHandle = document.createElement("div");
endHandle.className = "ausboss-video-handle is-end";
range.append(selection, startHandle, endHandle);
const values = document.createElement("div");
values.className = "ausboss-video-values";
const makeValue = (labelText) => {
const wrap = document.createElement("div");
wrap.className = "ausboss-video-value";
const label = document.createElement("label");
label.textContent = labelText;
const input = document.createElement("input");
input.type = "text";
input.inputMode = "decimal";
input.placeholder = "m:ss.s";
input.title = `${labelText} point - type seconds (95.5) or a timecode (1:35.5, 1:02:03.5)`;
input.addEventListener("keydown", (event) => {
keepKeyInField(event);
if (event.key === "Enter") input.dispatchEvent(new Event("change"));
});
wrap.append(label, input);
return { wrap, input, label };
};
const startValue = makeValue("IN");
const endValue = makeValue("OUT");
endValue.wrap.classList.add("is-end");
const durationLabel = document.createElement("div");
durationLabel.className = "ausboss-video-duration";
values.append(startValue.wrap, durationLabel, endValue.wrap);
trim.append(range, values);
root.append(stage, trim);
// The timing card goes here (mountCard): the clip node's Start,
// Duration and Ends at, or the frame picker while FRAME is on.
const cardSlot = document.createElement("div");
cardSlot.className = "ausboss-video-timing";
cardSlot.style.flex = "none";
root.append(stage, cardSlot);
const widget = node.addDOMWidget(PREVIEW_WIDGET, "ausboss_video", root, {
serialize: false,
@@ -544,15 +343,9 @@ function buildPreview(node) {
const abort = new AbortController();
const state = node.__ausbossLoadVideo = {
node, root, stage, video, status, loopButton, reloadButton, frameButton,
trim, range, selection, startHandle, endHandle, startInput: startValue.input,
endInput: endValue.input, startLabel: startValue.label, durationLabel,
cardSlot, card: null, cardMode: null, metadata: null, head: 0,
videoWidget, startWidget, endWidget, frameWidget,
// Absent on a backend without these widgets; the summary then reads
// its defaults (keep every frame, no cap).
everyNthWidget: findWidget(node, "every_nth"),
maxFramesWidget: findWidget(node, "max_frames"),
sourceFps: 0,
widget, abort, writing: false, dragging: false, correctingSeek: false, playRaf: 0,
widget, abort, writing: false, correctingSeek: false, playRaf: 0,
};
const updateLoopButton = () => loopButton.classList.toggle("active", getLoopEnabled(node));
@@ -583,9 +376,9 @@ function buildPreview(node) {
if (!name || typeof name !== "string") {
video.pause();
video.removeAttribute("src");
state.sourceFps = 0;
state.metadata = null;
setEmpty(state, "Choose or upload a video");
updateTrimFace(state);
state.card?.sync();
return;
}
const parts = splitMediaName(name);
@@ -595,7 +388,7 @@ function buildPreview(node) {
const type = parseImageReference(name)?.type ?? "input";
video.src = api.apiURL(`/view?${mediaViewQuery({ ...parts, type }, "input")}`);
video.load();
probeSourceFps(state, name);
probeMetadata(state, name);
};
state.refresh = refresh;
reloadButton.addEventListener("click", (event) => {
@@ -605,31 +398,23 @@ function buildPreview(node) {
});
video.addEventListener("loadedmetadata", () => {
const single = isSingleFrame(state);
const bounds = currentBounds(state);
if (!single && bounds.end - bounds.start < MIN_TRIM_SECONDS && video.duration >= MIN_TRIM_SECONDS) {
writeTrim(state, { start: Math.max(0, bounds.end - MIN_TRIM_SECONDS), end: bounds.end });
}
video.currentTime = homeTime(state);
setReady(state, single
? `frame at ${formatTimecode(homeTime(state))}`
: `${formatTimecode(currentBounds(state).start)} → ${formatTimecode(currentBounds(state).end)}`);
// Quiet source hint: resolution and duration from the loaded metadata.
// The card says where the clip is; the stage only names the source on hover.
setReady(state, "");
const sourceInfo = mediaInfo(null, video);
durationLabel.title = sourceInfo ? `Source: ${sourceInfo}` : "";
updateTrimFace(state);
stage.title = sourceInfo ? `Source: ${sourceInfo}` : "";
state.card?.sync();
node.setDirtyCanvas?.(true, true);
}, { signal: abort.signal });
video.addEventListener("error", () => setEmpty(state, "Preview could not load this video"), { signal: abort.signal });
installTrimDrag(state);
installPlayback(state);
watchTrimWidget(state, startWidget);
watchTrimWidget(state, endWidget);
watchFrameWidget(state, frameWidget);
watchTrimWidget(state, findWidget(node, "every_nth"));
watchTrimWidget(state, findWidget(node, "max_frames"));
applyMode(state);
startValue.input.addEventListener("change", () => commitTimeInput(state, "start", startValue.input));
endValue.input.addEventListener("change", () => commitTimeInput(state, "end", endValue.input));
const priorVideoCallback = videoWidget.callback;
videoWidget.callback = function (...args) {
@@ -664,6 +449,11 @@ app.registerExtension({
}
});
});
// A wire into a timing input changes what the card can show.
chainCallback(nodeType.prototype, "onConnectionsChange", function () {
const state = this.__ausbossLoadVideo;
if (state) queueMicrotask(() => state.card?.sync());
});
chainCallback(nodeType.prototype, "onRemoved", function () {
const state = this.__ausbossLoadVideo;
state?.stopTick?.();
+202 -17
View File
@@ -9,10 +9,15 @@ import {
loadSettings,
openSettingsMenu,
} from "../shared/settings_menu.mjs";
import { compactAction } from "../shared/panel_controls.mjs";
import {
STRENGTH_LINK_STYLES, WIRE_LOOKS, installStrengthLinks, sourceTitle, sourceValue, syncStrengthLinks, unlinkRow,
} from "./strength_links.mjs";
import { makeScrubInput } from "../shared/scrub_input.mjs";
import { isAppShortcut, keepKeyInField } from "../shared/canvas_passthrough.mjs";
import { resetUnknownValues } from "../shared/widget_card_math.mjs";
import { boxRowInputs, boxRowsWidget, boxesOf, hostBox, rowsInputName, workflowNodes } from "../shared/lora_box.mjs";
import { coreLoraList, syncFileWidgets } from "../shared/lora_file_widgets.mjs";
import {
SETTINGS_PROPERTY as SWITCHES_PROPERTY, releaseStackGroup, releaseStackRow, renameStackGroup, stackGroupOwners, stackRowOwners,
} from "../shared/workflow_switches.mjs";
@@ -46,6 +51,8 @@ import {
collectUpstreamLoaders,
collectDownstreamLoaders,
absorbChainIssue,
anyFolderOpen,
parentFolder,
mergeImportedRows,
moveGroup,
moveHighlight,
@@ -64,6 +71,7 @@ import {
scrubValue,
serializeRows,
setGroupEnabled,
setFolderFolds,
setGroupOff,
setStrength,
shortLoraName,
@@ -138,6 +146,14 @@ const SETTINGS_SCHEMA = [
hint: "Two strength boxes per row on this node. New nodes always start "
+ "unified.",
},
{
key: "strength_wires", label: "Linked strength wires", type: "choice",
options: WIRE_LOOKS, default: "shown",
hint: "A number wire dropped on a row sets that row's strength. shown: "
+ "the wire runs to the row. on hover: it shows while the pointer is on "
+ "this node or its source. hidden: never drawn; the row still says "
+ "what sets it.",
},
{
key: "strength_bars", label: "Strength bars", type: "toggle",
default: true,
@@ -218,7 +234,7 @@ function installStyles() {
if (document.getElementById("ausboss-lora-styles")) return;
const style = document.createElement("style");
style.id = "ausboss-lora-styles";
style.textContent = `
style.textContent = STRENGTH_LINK_STYLES + `
.ausboss-lora-panel, .ausboss-lora-panel *,
.ausboss-lora-pop, .ausboss-lora-pop *,
.ausboss-lora-hoverthumb { box-sizing: border-box; }
@@ -393,6 +409,10 @@ function installStyles() {
.ausboss-lora-pop { position: fixed; z-index: 10000; background: #1c1f23;
border: 1px solid #3a4047; border-radius: 7px; box-shadow: 0 8px 28px rgba(0,0,0,.5);
font: ${POP_FONT}; color: #d7dde2; display: flex; flex-direction: column; }
.ausboss-lora-pickhead { display: flex; align-items: center; gap: 6px; margin: 8px; }
.ausboss-lora-pickhead .ausboss-lora-search { flex: 1 1 auto; min-width: 0; margin: 0; }
/* Wide enough for either label, so the search box keeps its width. */
.ausboss-lora-pickhead .ausboss-compact-action { min-width: 64px; }
.ausboss-lora-search { margin: 8px; height: 26px; border: 1px solid #3a4047; border-radius: 5px;
background: #23272c; color: inherit; padding: 0 8px; outline: none; }
.ausboss-lora-search:focus { border-color: ${BRAND}; }
@@ -724,9 +744,47 @@ function commitRows(state, rows, { structural = false, record = true } = {}) {
state.node.graph?.setDirtyCanvas(true, true);
if (structural) renderRows(state);
else updateRowValues(state);
syncLoraFiles(state.node);
if (record) notifyAusbossChange();
}
// ComfyUI's missing-models list sees a row's file only through a list
// widget, so each row that needs a file gets a hidden one
// (js/shared/lora_file_widgets.mjs). Rows that come in over a link (from a
// box or another node) are not this node's to list.
function syncLoraFiles(node) {
if (node?.type !== NODE_CLASS) return;
const widget = node.widgets?.find((item) => item.name === "loras");
if (!widget) return;
const fed = node.inputs?.find((item) => item?.name === "loras")?.link != null;
syncFileWidgets(node, fed ? [] : parseRows(widget.value), {
installed: () => coreLoraList(globalThis.LiteGraph?.registered_node_types?.LoraLoader?.nodeData)
?? node.__ausbossLoraState?.available ?? null,
hide: hideWidget,
onPick: (rowId, name) => pickRowFile(node, rowId, name),
});
}
// ComfyUI put another file in a row's hidden list (a replacement picked in
// its Issues panel): the row takes that file.
function pickRowFile(node, rowId, name) {
const widget = node.widgets?.find((item) => item.name === "loras");
if (!widget) return;
const rows = parseRows(widget.value);
const row = rows.find((item) => item.id === rowId);
if (!row || row.name === name) return;
row.name = name;
const state = node.__ausbossLoraState;
if (state && !state.disposed && !state.readOnly && state.widget === widget) {
commitRows(state, rows, { structural: true });
return;
}
widget.value = serializeRows(rows);
node.graph?.setDirtyCanvas(true, true);
syncLoraFiles(node);
notifyAusbossChange();
}
// A box shows its loader's rows the way the loader does: one strength per
// row, or model and CLIP apart.
function linked(state) {
@@ -870,7 +928,11 @@ function strengthBox(state, index, key) {
input.dataset.ausbossStrength = key;
// A short name; the tooltip above stays as the longer description.
input.setAttribute("aria-label", key === "strength" ? "Model strength" : "CLIP strength");
input.__ausbossRead = () => state.rows[index]?.[key].toFixed(2) ?? "1.00";
input.__ausbossRead = () => {
const entry = linkedEntry(state, index);
if (entry) return sourceValue(entry)?.toFixed(2) ?? "link";
return state.rows[index]?.[key].toFixed(2) ?? "1.00";
};
input.__ausbossTint = () => state.rows[index] && applyRangeTint(input, state.rows[index], key);
ensureRange(state, state.rows[index].name);
@@ -884,6 +946,16 @@ function strengthBox(state, index, key) {
let drag = null;
input.addEventListener("pointerdown", (event) => {
if (event.button !== 0 || !input.readOnly) return;
// A linked strength is set by its wire: a click shows where it comes from.
const entry = linkedEntry(state, index);
if (entry) {
event.preventDefault();
if (entry.source) {
app.canvas?.selectNode?.(entry.source);
app.canvas?.centerOnNode?.(entry.source);
}
return;
}
drag = { x: event.clientX, y: event.clientY, start: state.rows[index][key], scrubbed: false };
input.setPointerCapture(event.pointerId);
event.preventDefault();
@@ -955,6 +1027,34 @@ function strengthBox(state, index, key) {
return box;
}
function linkedEntry(state, index) {
const row = state.rows[index];
return row ? state.linkedStrengths?.get(row.id) ?? null : null;
}
// Mark the rows a wire sets: the strength box shows the incoming number,
// and its tooltip names where it comes from.
function decorateStrengthLinks(state) {
if (state.disposed || state.box) return;
state.linkedStrengths = syncStrengthLinks(state);
for (const box of state.panel.querySelectorAll(".ausboss-lora-strengthbox")) {
const rowId = box.closest(".ausboss-lora-row")?.dataset.rowId;
const entry = rowId ? state.linkedStrengths.get(rowId) : null;
box.classList.toggle("linked", Boolean(entry));
const input = box.querySelector(".ausboss-lora-strength");
if (!input) continue;
input.title = entry
? `Set by "${sourceTitle(entry)}". Click to show it. Right-click the row to unlink.`
: input.dataset.baseTitle ?? "";
if (input.readOnly && input.__ausbossRead) input.value = input.__ausbossRead();
}
const signature = [...state.linkedStrengths].map(([id, entry]) => `${id}:${sourceValue(entry)}`).join("|");
if (signature !== state.linkSignature) {
state.linkSignature = signature;
decorateRows(state);
}
}
// ---------- picker ----------
// Width of the longest label in the picker's font. Remembered across opens,
@@ -967,6 +1067,14 @@ let widestPickerLabel = 0;
const COLLAPSED_FOLDERS_KEY = "AusBoss.lora_loader.collapsedFolders";
let rememberedCollapsedFolders = new Set();
// "Start folded" (the default) opens the picker with every folder folded
// and forgets folds when it closes. "Remember my folds" keeps them.
const PICKER_FOLDERS_SETTING = "AusBoss.LoraLoader.PickerFolders";
const START_FOLDED = "Start folded";
const REMEMBER_FOLDS = "Remember my folds";
const pickerStartsFolded = () =>
(app.ui?.settings?.getSettingValue?.(PICKER_FOLDERS_SETTING) ?? START_FOLDED) !== REMEMBER_FOLDS;
function loadCollapsedFolders() {
try {
const raw = window.localStorage?.getItem(COLLAPSED_FOLDERS_KEY);
@@ -1001,9 +1109,15 @@ function openPicker(state, index, anchor, { keyboard = false } = {}) {
const search = el("input", "ausboss-lora-search");
search.placeholder = "Search LoRAs...";
search.setAttribute("aria-label", "Search LoRAs");
// Folds or opens every folder at once. Hidden until the list has folders.
const foldAll = compactAction("Fold all");
foldAll.hidden = true;
foldAll.addEventListener("keydown", keepKeyInField);
const head = el("div", "ausboss-lora-pickhead");
head.append(search, foldAll);
const list = el("div", "ausboss-lora-list");
list.append(el("div", "ausboss-lora-empty", "Loading..."));
pop.append(search, list);
pop.append(head, list);
if (adding) pop.append(el("div", "ausboss-lora-picker-note",
"Click a file to add it. Tick boxes (or Ctrl-click) to add several at once. Click a folder name to add all of it. Skips files already in this stack."));
const anchorRect = anchor.getBoundingClientRect();
@@ -1026,7 +1140,8 @@ function openPicker(state, index, anchor, { keyboard = false } = {}) {
const inStack = () => new Set(state.rows.map((row) => pathKey(row.name)));
let loadError = false;
let highlight = -1;
const collapsedFolders = loadCollapsedFolders();
const startFolded = pickerStartsFolded();
const collapsedFolders = startFolded ? new Set() : loadCollapsedFolders();
// Search reveals matches without losing the user's usual folded view.
let searchCollapsed = new Set();
const currentFolds = () => search.value.trim() ? searchCollapsed : collapsedFolders;
@@ -1034,15 +1149,21 @@ function openPicker(state, index, anchor, { keyboard = false } = {}) {
// after: "highlight" keeps the folder highlighted for the search box's
// arrow keys, "arrow" keeps focus on the fold arrow that was pressed with
// the keyboard, "search" hands the keys back to the search box.
const toggleFolder = (name, collapsed = !currentFolds().has(name), after = "highlight") => {
// subtree: the folder's own folders fold or open with it (Alt- or
// Shift-click on its arrow). A null name means every folder (Fold all).
const toggleFolder = (name, collapsed = !currentFolds().has(name), after = "highlight", { subtree = false } = {}) => {
const folds = currentFolds();
if (collapsed) folds.add(name);
if (subtree || name == null) {
const next = setFolderFolds(folds, folders.keys(), collapsed, name);
folds.clear();
for (const folder of next) folds.add(folder);
} else if (collapsed) folds.add(name);
else folds.delete(name);
if (folds === collapsedFolders) saveCollapsedFolders(folds);
if (folds === collapsedFolders && !startFolded) saveCollapsedFolders(folds);
const scrollTop = list.scrollTop;
highlight = -1;
renderList();
if (after === "highlight" && adding) {
if (after === "highlight" && adding && name != null) {
highlight = options.findIndex((entry) => entry.kind === "folder" && entry.name === name);
list.querySelector(`[data-ausboss-flat="${highlight}"]`)?.classList.add("highlight");
}
@@ -1059,15 +1180,16 @@ function openPicker(state, index, anchor, { keyboard = false } = {}) {
button.dataset.folder = name;
button.innerHTML = chevronIconSvg(false);
button.setAttribute("aria-expanded", String(expanded));
button.title = `${expanded ? "Collapse" : "Expand"} ${name}`;
button.setAttribute("aria-label", button.title);
button.setAttribute("aria-label", `${expanded ? "Collapse" : "Expand"} ${name}`);
button.title = `${button.getAttribute("aria-label")} (Alt-click: and every folder inside it)`;
button.addEventListener("keydown", keepKeyInField);
button.addEventListener("click", (event) => {
// Only the folder name adds files; its arrow is browse-only.
event.stopPropagation();
// A click made with a key (detail 0) stays on the arrow. A mouse click
// goes back to the search box, so typing keeps searching.
toggleFolder(name, !currentFolds().has(name), event.detail === 0 ? "arrow" : "search");
toggleFolder(name, !currentFolds().has(name), event.detail === 0 ? "arrow" : "search",
{ subtree: event.altKey || event.shiftKey });
});
row.append(button);
};
@@ -1290,6 +1412,11 @@ function openPicker(state, index, anchor, { keyboard = false } = {}) {
for (const entry of entries) if (entry.kind === "file") entry.inStack = have.has(pathKey(entry.name));
}
options = entries.filter((entry) => adding || entry.kind === "file");
const open = anyFolderOpen(entries, currentFolds());
foldAll.hidden = !entries.some((entry) => entry.kind === "folder");
foldAll.textContent = open ? "Fold all" : "Open all";
foldAll.dataset.folds = open ? "1" : "";
foldAll.title = open ? "Fold every folder in this list" : "Open every folder in this list";
if (highlight >= 0) highlight = clampHighlight(highlight, options.length);
list.textContent = "";
hideHoverThumb();
@@ -1317,6 +1444,9 @@ function openPicker(state, index, anchor, { keyboard = false } = {}) {
place();
};
foldAll.addEventListener("click", () => {
toggleFolder(null, foldAll.dataset.folds === "1", "search");
});
search.addEventListener("input", () => { highlight = -1; searchCollapsed = new Set(); renderList(); });
search.addEventListener("keydown", (event) => {
keepKeyInField(event);
@@ -1326,9 +1456,18 @@ function openPicker(state, index, anchor, { keyboard = false } = {}) {
highlight = moveHighlight(highlight, event.key === "ArrowDown" ? 1 : -1, options.length);
renderList();
} else if ((event.key === "ArrowLeft" || event.key === "ArrowRight")
&& options[highlight]?.kind === "folder") {
&& options[highlight]?.kind === "folder"
&& !(event.key === "ArrowLeft" && currentFolds().has(options[highlight].name)
&& parentFolder(options[highlight].name) && !event.altKey && !event.shiftKey)) {
event.preventDefault();
toggleFolder(options[highlight].name, event.key === "ArrowLeft");
toggleFolder(options[highlight].name, event.key === "ArrowLeft", "highlight",
{ subtree: event.altKey || event.shiftKey });
} else if (event.key === "ArrowLeft" && adding && highlight >= 0
&& parentFolder(options[highlight]?.name)) {
// On a file, or on a folder that is already folded, Left folds the
// folder it sits in and moves up to it, as in a file tree.
event.preventDefault();
toggleFolder(parentFolder(options[highlight].name), true);
} else if (event.key === "Home" || event.key === "End") {
event.preventDefault();
highlight = event.key === "Home" ? 0 : options.length - 1;
@@ -1357,6 +1496,13 @@ function openPicker(state, index, anchor, { keyboard = false } = {}) {
if (!pop.isConnected) return;
names = fetched;
folders = new Map(loraFolders(fetched).map(({ folder, names }) => [folder, names]));
if (startFolded) {
for (const folder of folders.keys()) collapsedFolders.add(folder);
// A row's own picker opens the way to that row's file.
for (let folder = parentFolder(state.rows[index]?.name); folder; folder = parentFolder(folder)) {
collapsedFolders.delete(folder);
}
}
state.available = fetched;
state.nameStatus = new Map();
widestPickerLabel = widestLabel(names.map((name) => displayName(state, name))) + (adding ? 110 : 30);
@@ -1765,6 +1911,13 @@ function openRowMenu(state, index, event) {
commitRows(state, rows, { structural: true });
fitNode(state);
};
if (state.linkedStrengths?.has(row.id)) {
item("Unlink strength", () => {
unlinkRow(state, row.id);
decorateStrengthLinks(state);
});
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)),
@@ -2291,7 +2444,12 @@ function renameOwnedGroup(state, from, to) {
// value update - the bar scale can change whenever any row's strength does.
function decorateRows(state) {
const showBars = state.settings?.strength_bars !== false;
const scale = strengthBarScale(state.rows);
// A linked row's bar shows the number coming in on its wire.
const shown = state.rows.map((row, index) => {
const value = sourceValue(linkedEntry(state, index));
return value === null ? row : { ...row, strength: value };
});
const scale = strengthBarScale(shown);
const dups = duplicateLoraKeys(state.rows);
state.panel.querySelectorAll(".ausboss-lora-name").forEach((button, index) => {
const row = state.rows[index];
@@ -2302,8 +2460,8 @@ function decorateRows(state) {
}
const notes = [row.name];
if (showBars) {
button.style.background = strengthBarBackground(row.strength, scale);
notes.push(`Model strength ${row.strength.toFixed(2)}; `
button.style.background = strengthBarBackground(shown[index].strength, scale);
notes.push(`Model strength ${shown[index].strength.toFixed(2)}; `
+ `bar edges are ±${scale.toFixed(2)}`);
} else {
button.style.background = "";
@@ -2348,6 +2506,7 @@ function updateRowValues(state) {
master.classList.toggle("mixed", overall === "mixed");
}
decorateRows(state);
decorateStrengthLinks(state);
}
// ---------- absorb the loader chain ----------
@@ -2829,7 +2988,7 @@ function renderRows(state) {
let nameDrag = null;
name.addEventListener("pointerdown", (event) => {
if (event.button !== 0 || !row.name
|| state.settings?.name_scrub === false) return;
|| state.settings?.name_scrub === false || linkedEntry(state, index)) return;
nameDrag = { x: event.clientX, y: event.clientY,
start: state.rows[index].strength, scrubbed: false };
name.setPointerCapture(event.pointerId);
@@ -2921,6 +3080,7 @@ function renderRows(state) {
stack.append(actions);
body.append(stack);
decorateRows(state);
decorateStrengthLinks(state);
state.lockSignature = null;
refreshLocks(state);
// Names refit whenever the stack's box changes - the node was resized,
@@ -3027,6 +3187,7 @@ function syncRows(state) {
state.toggleSnapshot = snapshotEnabled(state.rows);
renderRows(state);
fitNode(state);
syncLoraFiles(state.node);
return true;
}
@@ -3051,6 +3212,7 @@ function ensureRedrawHook() {
if (state.node.graph !== shown) continue;
syncRows(state);
refreshLocks(state);
decorateStrengthLinks(state);
}
}, 250);
});
@@ -3156,6 +3318,7 @@ function watchBox(box) {
function unmountCard(state, { resize = true } = {}) {
liveCards.delete(state);
state.disposed = true;
state.unlinkStrengthWatch?.();
state.nameObserver?.disconnect();
closePopup();
try {
@@ -3249,6 +3412,10 @@ function mountCard(node, { box = null, separatorWidget = null, onMissingWidget =
panel.style.height = `calc(100% + ${reclaim}px)`;
}
if (!box) {
state.unlinkStrengthWatch = installStrengthLinks(state, app);
state.onStrengthLinks = () => decorateStrengthLinks(state);
}
renderRows(state);
refreshAvailable(state);
node.setSize?.([Math.max(336, node.size?.[0] || 336), node.computeSize?.()[1] || 220]);
@@ -3311,6 +3478,18 @@ function installLoraNode(node) {
app.registerExtension({
name: "AusBoss.LoraLoader",
settings: [
{
id: PICKER_FOLDERS_SETTING,
name: "+ LoRA list folders",
type: "combo",
options: [START_FOLDED, REMEMBER_FOLDS],
defaultValue: START_FOLDED,
category: ["🆎 AusBoss", "LoRA Loader", "Picker folders"],
tooltip: "Start folded opens the + LoRA list with every folder folded. "
+ "Remember my folds opens it the way you left it in this browser.",
},
],
setup() {
watchEnteredBoxes();
ensureRedrawHook();
@@ -3324,6 +3503,12 @@ app.registerExtension({
});
chainCallback(nodeType.prototype, "onConfigure", function () {
resetUnknownValues(this.widgets, RESET_UNKNOWN);
// Now, not later: ComfyUI reads its missing-models list right after
// the workflow is restored.
syncLoraFiles(this);
});
chainCallback(nodeType.prototype, "onConnectionsChange", function () {
syncLoraFiles(this);
});
},
// A box (subgraph node) shows the rows of a loader inside once they come
+303
View File
@@ -0,0 +1,303 @@
// A row's strength can come in on a link: drag a number wire onto a row and
// let go. The link lands on a hidden input named strength_<row id> that sits
// on the node's left edge at that row's height. Nothing marks the spot until
// a number wire is dragged over the node: then the row under the pointer
// lights up. Once linked, the row's strength box shows the incoming value,
// and the wire is shown, shown on hover, or hidden (gear menu).
//
// How the input stays out of sight: the frontend treats an input that names
// a widget as a widget's socket. It leaves such a socket out of the node's
// height, draws it only while a link is dragged or hovered or once it is
// connected, and keeps the position it is given when no widget by that name
// exists. The socket is also drawn in a clear colour, so a linked row shows
// no dot. The frontend does not hit-test such a socket either, so the
// loader's getInputOnPos finds the row under a drop itself.
//
// The frontend also removes, when a workflow loads, every widget socket
// whose widget it cannot find. So the input is saved as a plain input and
// becomes a widget socket again once the workflow has loaded.
import { chainCallback } from "../shared/index.mjs";
const NAME = /^strength_[A-Za-z0-9_-]{1,64}$/;
const CLEAR = "rgba(0,0,0,0)";
// Where the hidden socket sits from the node's left edge, as the frontend
// places a widget's socket.
const SOCKET_X = 10;
const NUMBER_TYPES = new Set(["FLOAT", "INT"]);
export const WIRE_LOOKS = ["shown", "on hover", "hidden"];
// The canvas skips drawing a wire it is told is being dragged, shadow and
// all, so a hidden wire carries that mark. The mark is not saved.
export const rowInputName = (rowId) => `strength_${rowId}`;
export const isRowInput = (input) => typeof input?.name === "string" && NAME.test(input.name);
const rowIdOf = (input) => input.name.slice("strength_".length);
const states = new Set();
let watching = false;
let hoverTarget = null;
function canvasOf(app) {
return app?.canvas ?? null;
}
function clientPoint(app, x, y) {
const canvas = canvasOf(app);
const rect = canvas.canvas.getBoundingClientRect();
const scale = canvas.ds.scale || 1;
const [ox, oy] = canvas.ds.offset;
return [rect.left + (x + ox) * scale, rect.top + (y + oy) * scale];
}
function graphPoint(app, clientX, clientY) {
const canvas = canvasOf(app);
const rect = canvas.canvas.getBoundingClientRect();
const scale = canvas.ds.scale || 1;
const [ox, oy] = canvas.ds.offset;
return [(clientX - rect.left) / scale - ox, (clientY - rect.top) / scale - oy];
}
function linkOf(graph, id) {
if (id === null || id === undefined || !graph) return null;
return graph.links?.get?.(id) ?? graph.links?.[id] ?? graph._links?.get?.(id) ?? null;
}
function rowElements(state) {
return [...state.panel.querySelectorAll(".ausboss-lora-row")]
.filter((element) => !element.classList.contains("folded-away"));
}
function rowElement(state, rowId) {
return rowElements(state).find((element) => element.dataset.rowId === rowId) ?? null;
}
// The row under a point in client pixels: anywhere across the node's width,
// so a drop does not have to hit the strength box itself.
function rowAtClient(state, clientX, clientY) {
const node = state.node;
const app = state.app;
const [left] = clientPoint(app, node.pos[0], node.pos[1]);
const [right] = clientPoint(app, node.pos[0] + node.size[0], node.pos[1]);
if (clientX < left - 4 || clientX > right + 4) return null;
for (const element of rowElements(state)) {
const rect = element.getBoundingClientRect();
if (clientY >= rect.top - 3 && clientY <= rect.bottom + 3) return element;
}
return null;
}
function isNumberDrag(app) {
const connector = canvasOf(app)?.linkConnector;
if (!connector?.isConnecting) return false;
if (connector.state?.connectingTo && connector.state.connectingTo !== "input") return false;
const types = (connector.renderLinks ?? []).map((link) => String(link?.fromSlot?.type ?? ""));
return types.length > 0 && types.every((type) => type.split(",").some((part) => NUMBER_TYPES.has(part.trim())));
}
export function rowInputs(node) {
return (node.inputs ?? []).filter(isRowInput);
}
// {row id: {input, link, source}} for every row a link sets now.
export function linkedRows(node) {
const found = new Map();
for (const input of rowInputs(node)) {
const link = linkOf(node.graph, input.link);
if (!link) continue;
const source = node.graph?.getNodeById?.(link.origin_id) ?? null;
found.set(rowIdOf(input), { input, link, source });
}
return found;
}
// What a linked row shows: the source's own number when it has one in
// sight (a Float or Int node, a slider), else just that it is linked.
export function sourceValue(entry) {
const widgets = entry?.source?.widgets ?? [];
const widget = widgets.find((item) => item.name === "value") ?? widgets.find((item) => typeof item.value === "number");
return typeof widget?.value === "number" ? widget.value : null;
}
export function sourceTitle(entry) {
return String(entry?.source?.title || entry?.source?.type || "another node");
}
function placeInput(state, input) {
const element = rowElement(state, rowIdOf(input));
if (!element) return;
const rect = element.getBoundingClientRect();
const [, y] = graphPoint(state.app, 0, rect.top + rect.height / 2);
const pos = [SOCKET_X, Math.round((y - state.node.pos[1]) * 10) / 10];
if (input.pos?.[0] !== pos[0] || input.pos?.[1] !== pos[1]) input.pos = pos;
}
const HIDDEN = () => ({ label: " ", localized_name: " ", color_on: CLEAR, color_off: CLEAR });
function hideInput(input) {
Object.assign(input, HIDDEN());
if (!input.widget) input.widget = { name: input.name };
}
function ensureRowInput(state, rowId) {
const node = state.node;
const name = rowInputName(rowId);
let input = node.inputs?.find((item) => item.name === name);
if (!input) input = node.addInput(name, "FLOAT,INT", { ...HIDDEN(), widget: { name } });
placeInput(state, input);
return input;
}
export function unlinkRow(state, rowId) {
const node = state.node;
const index = (node.inputs ?? []).findIndex((input) => input.name === rowInputName(rowId));
if (index < 0) return;
node.removeInput(index);
node.setDirtyCanvas?.(true, true);
}
function wireHidden(state, entry) {
const look = state.settings?.strength_wires ?? "shown";
if (look === "hidden") return true;
return look === "on hover" && hoverTarget !== state.node && hoverTarget !== entry.source;
}
function setWireHidden(entry, hidden) {
const link = entry.link;
if (hidden === Boolean(link._dragging)) return false;
// A wire the user is moving keeps the mark the canvas gave it.
if (!hidden && link.__ausbossHidden !== true) return false;
link._dragging = hidden;
link.__ausbossHidden = hidden;
return true;
}
// Keep the hidden inputs in step with the rows: drop the ones nothing is
// linked to or whose row is gone, move each to its row, colour its wire.
// Returns the linked rows.
export function syncStrengthLinks(state) {
const node = state.node;
const connecting = canvasOf(state.app)?.linkConnector?.isConnecting;
// Rows not yet read from a workflow that is loading say nothing about
// which inputs are stale.
const rowsCurrent = state.widget && state.renderedValue === state.widget.value;
if (!connecting && rowsCurrent) {
const ids = new Set(state.rows.map((row) => row.id));
for (let index = (node.inputs?.length ?? 0) - 1; index >= 0; index -= 1) {
const input = node.inputs[index];
if (!isRowInput(input)) continue;
if (!ids.has(rowIdOf(input)) || !linkOf(node.graph, input.link)) node.removeInput(index);
}
}
for (const input of rowInputs(node)) placeInput(state, input);
const linked = linkedRows(node);
let changed = false;
for (const entry of linked.values()) {
if (setWireHidden(entry, wireHidden(state, entry))) changed = true;
}
if (changed) node.setDirtyCanvas?.(true, true);
return linked;
}
function paintTarget(element) {
for (const state of states) {
for (const row of state.panel.querySelectorAll(".ausboss-lora-row.link-target")) {
if (row !== element) row.classList.remove("link-target");
}
}
element?.classList.add("link-target");
}
function watchPointer(app) {
if (watching) return;
watching = true;
window.addEventListener("pointermove", (event) => {
let target = null;
let over = null;
for (const state of states) {
if (state.disposed) continue;
const node = state.node;
const [x, y] = graphPoint(app, event.clientX, event.clientY);
if (x >= node.pos[0] && x <= node.pos[0] + node.size[0] && y >= node.pos[1] - 30 && y <= node.pos[1] + node.size[1]) over = node;
if (!target && !state.box && !state.readOnly && isNumberDrag(app)) target = rowAtClient(state, event.clientX, event.clientY);
}
paintTarget(target);
if (!over) {
const [x, y] = graphPoint(app, event.clientX, event.clientY);
over = canvasOf(app)?.graph?.getNodeOnPos?.(x, y) ?? null;
}
if (over !== hoverTarget) {
hoverTarget = over;
for (const state of states) if (!state.disposed) syncStrengthLinks(state);
}
}, true);
// Nodes 2.0 finishes a link drag in its own pointerup handler and never asks
// the node which input is under the pointer. So there the drop on a row is
// made here, before that handler runs; it then finds the link made.
window.addEventListener("pointerup", (event) => {
if (globalThis.LiteGraph?.vueNodesMode && isNumberDrag(app)) {
for (const state of states) {
if (state.disposed || state.box || state.readOnly) continue;
const element = rowAtClient(state, event.clientX, event.clientY);
if (element?.dataset.rowId) {
dropOnRow(state, element.dataset.rowId, canvasOf(app).linkConnector);
break;
}
}
}
requestAnimationFrame(() => {
paintTarget(null);
for (const state of states) if (!state.disposed) state.onStrengthLinks?.();
});
}, true);
}
function dropOnRow(state, rowId, connector) {
const input = ensureRowInput(state, rowId);
for (const link of connector.renderLinks ?? []) {
if (link.node === state.node) continue;
link.connectToInput?.(state.node, input, connector.events);
}
}
export function installStrengthLinks(state, app) {
state.app = app;
states.add(state);
watchPointer(app);
const node = state.node;
// Saved as plain inputs (see the top of this file), hidden again on load.
chainCallback(node, "onSerialize", (data) => {
if (!Array.isArray(data?.inputs)) return;
data.inputs = data.inputs.map((input) => {
if (!isRowInput(input)) return input;
const { widget, ...plain } = input;
return plain;
});
});
const rehide = () => {
for (const input of rowInputs(node)) hideInput(input);
requestAnimationFrame(() => { if (!state.disposed) state.onStrengthLinks?.(); });
};
chainCallback(node, "onGraphConfigured", rehide);
chainCallback(node, "onConfigure", () => requestAnimationFrame(rehide));
const original = node.getInputOnPos;
node.getInputOnPos = function (pos) {
const found = typeof original === "function" ? original.call(this, pos) : undefined;
if (found && !isRowInput(found)) return found;
if (state.disposed || state.box || state.readOnly || !isNumberDrag(app)) return found;
const [clientX, clientY] = clientPoint(app, pos[0], pos[1]);
const element = rowAtClient(state, clientX, clientY);
if (!element?.dataset.rowId) return found;
return ensureRowInput(state, element.dataset.rowId);
};
return () => {
states.delete(state);
if (node.getInputOnPos !== original) delete node.getInputOnPos;
};
}
export const STRENGTH_LINK_STYLES = `
.ausboss-lora-row.link-target{outline:2px solid #00b4aa;outline-offset:-1px;background:rgba(0,180,170,.14);}
.ausboss-lora-strengthbox.linked{border-color:transparent;outline:2px dashed rgba(0,180,170,.7);outline-offset:-2px;}
.ausboss-lora-strengthbox.linked .ausboss-lora-strength{color:#5fe3d9;cursor:pointer;}
.ausboss-lora-strengthbox.linked .ausboss-lora-step{display:none;}
`;
+3 -3
View File
@@ -97,9 +97,9 @@ const SETTINGS_SCHEMA = [
},
{
key: "chips_keep_budget", label: "Chips keep current budget", type: "toggle",
default: false,
hint: "Ratio chips reshape at your current megapixels instead of jumping "
+ "to that ratio's ~1MP default size.",
default: true,
hint: "On: ratio chips keep your current megapixels. Off: a chip jumps "
+ "to that ratio's ~1MP size.",
},
{
key: "rail", label: "Ratio rail", type: "text",
+59
View File
@@ -0,0 +1,59 @@
// App mode and the pack's cards. Pure logic, no DOM: tested under node:test.
//
// App mode is ComfyUI's simple form view of a workflow: a saved list of
// fields (extra.linearData.inputs) and a Run button. Each field is a
// widget. A node with a card or panel hides its standard widgets and shows
// its own controls instead, and App mode reads that hidden flag too, so the
// form drew an empty row for every field on such a node.
//
// While a workflow is in App mode, the widgets its form lists are shown
// again; App mode draws its own control for each. Back in the graph they are
// hidden again, so the node's face is unchanged. Only listed widgets move.
import { hideWidget, isWidgetHidden, showWidget } from "./widget_visibility.mjs";
export const APP_MODE = "app";
// "app", "graph" or "builder:..." for the open workflow.
export function workflowMode(workflow) {
return workflow?.activeMode ?? workflow?.initialMode ?? "graph";
}
// The form's fields as { nodeId, widget } pairs. A field is saved as
// [nodeId, widgetName] or [nodeId, widgetName, { description }].
export function appFields(linearData) {
const inputs = Array.isArray(linearData?.inputs) ? linearData.inputs : [];
const fields = [];
for (const entry of inputs) {
if (!Array.isArray(entry) || entry.length < 2) continue;
const [nodeId, widget] = entry;
if ((typeof nodeId !== "string" && typeof nodeId !== "number") || typeof widget !== "string") continue;
fields.push({ nodeId: String(nodeId), widget });
}
return fields;
}
// find(nodeId, widgetName) -> { node, widget } or null
// changed(node) is called after a widget on that node changed visibility.
export function createAppModeSync({ find, changed = () => {} }) {
const lent = new Map(); // widget -> node, shown for the form
return function sync(mode, linearData) {
if (mode === APP_MODE) {
for (const { nodeId, widget: name } of appFields(linearData)) {
const found = find(nodeId, name);
if (!found?.widget || !isWidgetHidden(found.widget)) continue;
showWidget(found.widget);
// An explicit false, not a deleted flag: the frontend keeps its own
// copy of the hidden state and only hears about a written value.
if (found.widget.options) found.widget.options.hidden = false;
lent.set(found.widget, found.node);
changed(found.node);
}
return lent.size;
}
for (const [widget, node] of lent) {
if (hideWidget(widget)) changed(node);
}
lent.clear();
return 0;
};
}
+64 -16
View File
@@ -1,30 +1,78 @@
// Read only literal numeric sources. Calculated inputs must remain unknown
// until execution; never evaluate an arbitrary upstream graph for a label.
export function inputNumber(node, name, fallback) {
const input = node.inputs?.find((slot) => slot.name === name || slot.widget?.name === name);
if (input?.link == null) return fallback;
const graph = node.graph;
let linkId = input.link;
// A subgraph's output that comes straight from a literal inside it (Person
// Swap's "Pick the model files" hands out its video fps that way) counts as
// that literal: it is still a typed number, not a calculation.
function tableLink(graph, id) {
if (id == null || !graph) return null;
return graph.getLink?.(id) ?? graph.links?.get?.(id) ?? graph.links?.[id] ?? graph._links?.get?.(id) ?? null;
}
// The link into one of a node's inputs: the frontend's own accessor first
// (newer frontends warn on reading input.link), the link table after it.
// undefined when nothing is connected.
function linkInto(node, index, graph) {
if (typeof node?.getInputLink === "function" && node.graph) {
try {
return node.getInputLink(index) ?? undefined;
} catch {
return undefined;
}
}
const id = node?.inputs?.[index]?.link;
return id == null ? undefined : tableLink(node.graph ?? graph, id);
}
// Where a linked input really comes from: the node and output slot at the
// far end, through Reroutes and into a subgraph whose output is wired
// straight to a node inside it. null for a muted or bypassed source, a loop,
// or a subgraph output with nothing behind it. undefined when the input is
// not linked at all.
export function linkOrigin(node, name) {
const index = node?.inputs?.findIndex((slot) => slot?.name === name || slot?.widget?.name === name) ?? -1;
if (index < 0) return undefined;
let graph = node.graph;
let link = linkInto(node, index, graph);
if (link === undefined) return undefined;
const seen = new Set();
for (let depth = 0; depth < 16; depth++) {
if (seen.has(linkId)) return null;
seen.add(linkId);
const link = graph?.links?.[linkId] ?? graph?._links?.get?.(linkId);
const source = graph?.getNodeById?.(link?.origin_id);
if (!link || seen.has(link)) return null;
seen.add(link);
const source = graph?.getNodeById?.(link.origin_id);
if (!source || (source.mode ?? 0) !== 0) return null;
if (source.type === "Reroute") {
linkId = source.inputs?.[0]?.link;
if (linkId == null) return null;
if ((source.comfyClass ?? source.type) === "Reroute") {
link = linkInto(source, 0, graph) ?? null;
continue;
}
if (!["PrimitiveFloat", "PrimitiveInt", "AUSBOSS_NODES_Integer", "AUSBOSS_NODES_Float"].includes(source.type) || link.origin_slot !== 0) return null;
if (source.inputs?.some((slot) => slot.name === "value" && slot.link != null)) return null;
const value = source.widgets?.find((widget) => widget.name === "value")?.value;
return typeof value === "number" && Number.isFinite(value) ? value : null;
const inner = source.subgraph;
if (inner && typeof source.isSubgraphNode === "function" && source.isSubgraphNode()) {
link = tableLink(inner, inner.outputs?.[link.origin_slot]?.linkIds?.[0]);
graph = inner;
continue;
}
return { node: source, slot: link.origin_slot };
}
return null;
}
const LITERALS = ["PrimitiveFloat", "PrimitiveInt", "AUSBOSS_NODES_Integer", "AUSBOSS_NODES_Float"];
export function inputNumber(node, name, fallback) {
const origin = linkOrigin(node, name);
if (origin === undefined) return fallback;
if (!origin) return null;
const { node: source, slot } = origin;
// ComfyUI's older Primitive node holds the value of the widget it feeds.
if ((source.comfyClass ?? source.type) === "PrimitiveNode") {
const value = source.widgets?.[0]?.value;
return typeof value === "number" && Number.isFinite(value) ? value : null;
}
if (!LITERALS.includes(source.type) || slot !== 0) return null;
if (source.inputs?.some((input) => input.name === "value" && input.link != null)) return null;
const value = source.widgets?.find((widget) => widget.name === "value")?.value;
return typeof value === "number" && Number.isFinite(value) ? value : null;
}
export function clipOutputRate(node, sourceFps, everyNth = 1) {
const forced = inputNumber(node, "force_rate", 0);
const nth = inputNumber(node, "every_nth", everyNth);
+42 -6
View File
@@ -131,6 +131,21 @@ export function compareBadges(fraction, stageWidth, badgeWidth = 22, gap = 5) {
return { a: a >= 4 ? a : null, b: b + badgeWidth <= width - 4 ? b : null };
}
// The node property that holds the picture the panel rests on: "A" or "B",
// saved with the workflow. A new node rests on B, the "after" picture.
export const REST_PROPERTY = "ausboss_compare_rest";
// A saved resting side, or null when the node has none yet (a workflow
// saved before the choice existed).
export function savedRestSide(value) {
return value === "A" || value === "B" ? value : null;
}
// Node types that hand on one of their pictures and make nothing new.
export const SWITCH_NODE_TYPES = new Set(["ComfySwitchNode", "ComfySoftSwitchNode", "AUSBOSS_NODES_Switch"]);
// The inputs of a switch that choose a branch rather than carry a picture.
export const SWITCH_CONTROL_INPUTS = new Set(["switch", "select", "boolean", "index"]);
// Is `target` somewhere upstream of `start`? `feeds(id)` lists the ids of
// the nodes wired into node `id`.
function isUpstream(target, start, feeds) {
@@ -147,15 +162,34 @@ function isUpstream(target, start, feeds) {
return false;
}
// Is the picture out of `start` made from `target`'s picture? A switch only
// hands one of its pictures on, so it counts only when one branch is made
// from `target` and no branch can hand on a picture from before `target`.
// `branches(id)` lists a switch's picture branches, null for other nodes.
function madeFrom(start, target, graph, memo = new Map()) {
if (start === target) return true;
if (memo.has(start)) return memo.get(start);
memo.set(start, false); // a loop in the links proves nothing
const branches = graph.branches?.(start) ?? null;
const ids = (branches ?? graph.feeds(start) ?? []).filter((id) => id != null);
const answer = ids.some((id) => madeFrom(id, target, graph, memo))
&& !(branches && ids.some((id) => id !== target && isUpstream(id, target, graph.feeds)));
memo.set(start, answer);
return answer;
}
// Which input holds the result, the picture the panel rests on. B is the
// "after" picture by convention. When B's picture feeds the node that makes
// A, they are wired the other way round and the result is A.
// "after" picture by convention. When A is made from B's picture, they are
// wired the other way round and the result is A. A switch that can hand on
// either the other picture or the one it started from is a "before" picker:
// the picture it can hand on is the result.
//
// `a` and `b` say where the two pictures come from: { id, slot } of the node
// and output wired to each input. `graph` reads the links: feeds(id) lists
// the ids of the nodes wired into node `id`, and inside(id) opens a
// subgraph: the same two calls for the graph in it, plus output(slot),
// where that output comes from in there.
// the ids of the nodes wired into node `id`, branches(id) the picture
// branches of a switch (null for other nodes), and inside(id) opens a
// subgraph: the same calls for the graph in it, plus output(slot), where
// that output comes from in there.
export function compareResultSide(a, b, graph) {
// Both pictures out of one subgraph: the answer is inside it.
for (let depth = 0; a && b && a.id === b.id && depth < 16; depth += 1) {
@@ -164,5 +198,7 @@ export function compareResultSide(a, b, graph) {
[a, b, graph] = [inner.output(a.slot), inner.output(b.slot), inner];
}
if (!a || !b || a.id === b.id) return "B";
return isUpstream(b.id, a.id, graph.feeds) ? "A" : "B";
if (madeFrom(a.id, b.id, graph)) return "A";
if (madeFrom(b.id, a.id, graph)) return "B";
return isUpstream(a.id, b.id, graph.feeds) ? "A" : "B";
}
+114 -11
View File
@@ -4,6 +4,7 @@
// source of truth: a chip only changes their value.
import { app } from "../../../scripts/app.js";
import { BRAND, chainCallback } from "./index.mjs";
import { THEME as T, FONT_UI } from "./theme.mjs";
import { liftSocket } from "./widget_card.mjs";
import { commitWidgetValue, comboValues } from "./widget_card_math.mjs";
@@ -21,9 +22,15 @@ function ensureCss() {
.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 select{field-sizing:content;min-width:0;max-width:120px;height:22px;padding:0 11px 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;appearance:none;-webkit-appearance:none;cursor:pointer;text-overflow:ellipsis}
.ausboss-chip select:focus-visible{outline:2px solid ${BRAND};outline-offset:2px}
.ausboss-chip select option{background:#0f1516;color:#d8ecea}
.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: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}}
.ausboss-chip-item{display:flex;align-items:center;gap:.5em;padding:.45em .75em .45em .5em;border-radius:.4em;white-space:nowrap;cursor:pointer;user-select:none}
.ausboss-chip-item::before{content:"";flex:none;width:.9em;text-align:center;color:${T.brand}}
.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.off{border-style:dashed;background:transparent;color:#56706d}
.ausboss-chip.off:hover{border-color:#2a3437}
.ausboss-chip.wired{color:#8ba3a1}
@@ -56,17 +63,109 @@ function add(parent, tag, text, className) {
return child;
}
// The open job list, one at a time across every chip on the page.
let openMenu = null;
// The job list a chip opens. A native <select> lets the browser draw its own
// list (small system font, light highlight, pinned to the select's left
// edge); this one wears the node's colours, sits under the whole chip and
// grows with the canvas zoom like the chip does.
function openJobMenu(chipElement, button, values, current, choose) {
openMenu?.close();
const menu = add(document.body, "div", undefined, "ausboss-chip-menu");
menu.setAttribute("role", "listbox");
const items = values.map((value) => {
const item = add(menu, "div", value, "ausboss-chip-item");
item.setAttribute("role", "option");
if (value === current) { item.classList.add("current"); item.setAttribute("aria-selected", "true"); }
return item;
});
let hot = -1;
const setHot = (index) => {
items[hot]?.classList.remove("hot");
hot = (index + items.length) % items.length;
items[hot]?.classList.add("hot");
items[hot]?.scrollIntoView({ block: "nearest" });
};
setHot(Math.max(0, values.indexOf(current)));
// The chip is drawn scaled with the canvas: the list matches that size,
// starts at the chip's left edge and is at least as wide as the chip.
function place() {
const box = chipElement.getBoundingClientRect();
const zoom = Math.min(2.5, Math.max(0.85, box.height / (chipElement.offsetHeight || 24)));
menu.style.fontSize = `${12 * zoom}px`;
menu.style.minWidth = `${box.width}px`;
const width = menu.offsetWidth;
const height = menu.offsetHeight;
let top = box.bottom + 4;
if (top + height > window.innerHeight - 8 && box.top - height - 4 >= 8) top = box.top - height - 4;
menu.style.left = `${Math.max(8, Math.min(box.left, window.innerWidth - width - 8))}px`;
menu.style.top = `${Math.max(8, top)}px`;
}
const abort = new AbortController();
const close = () => {
abort.abort();
menu.remove();
chipElement.classList.remove("open");
if (openMenu?.menu === menu) openMenu = null;
};
const pick = (index) => { close(); button.focus(); choose(values[index]); };
items.forEach((item, index) => {
item.addEventListener("pointermove", () => { if (hot !== index) setHot(index); });
item.addEventListener("click", () => pick(index));
});
menu.addEventListener("pointerdown", (event) => event.stopPropagation());
const outside = (event) => !menu.contains(event.target) && !button.contains(event.target);
const on = { capture: true, signal: abort.signal };
window.addEventListener("pointerdown", (event) => { if (outside(event)) close(); }, on);
window.addEventListener("wheel", (event) => { if (outside(event)) close(); }, { ...on, passive: true });
// The page fires resize on its own now and then: the list follows the chip
// instead of vanishing, and goes only when the chip itself is gone.
window.addEventListener("resize", () => (chipElement.isConnected ? place() : close()), on);
// Only the window itself losing focus (another app, another tab). Pressing an item takes
// focus off the chip's button, and a capturing blur listener would hear that and close
// the list before the click lands. The press keeps focus on the button instead.
window.addEventListener("blur", (event) => { if (event.target === window) close(); }, { signal: abort.signal });
menu.addEventListener("mousedown", (event) => event.preventDefault());
window.addEventListener("keydown", (event) => {
const step = { ArrowDown: 1, ArrowUp: -1 }[event.key];
if (step) setHot(hot + step);
else if (event.key === "Home") setHot(0);
else if (event.key === "End") setHot(items.length - 1);
else if (event.key === "Enter" || event.key === " ") pick(hot);
else if (event.key === "Escape" || event.key === "Tab") { close(); if (event.key === "Escape") button.focus(); }
else return;
if (event.key !== "Tab") { event.preventDefault(); event.stopPropagation(); }
}, on);
place();
chipElement.classList.add("open");
openMenu = { owner: button, menu, close };
}
function choice(node, name, into) {
const widget = widgetOf(node, name);
const select = add(into, "select");
for (const value of comboValues(widget)) add(select, "option", value).value = value;
select.value = widget?.value ?? "";
select.title = widget?.options?.tooltip ?? "";
select.addEventListener("change", () => {
if (widget) commitWidgetValue(node, widget, select.value, app.canvas);
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 ?? ""); };
show(widget?.value);
const choose = (value) => {
show(value);
if (widget && value !== widget.value) commitWidgetValue(node, widget, value, app.canvas);
node.setDirtyCanvas?.(true, true);
};
button.addEventListener("pointerdown", (event) => event.stopPropagation());
button.addEventListener("click", (event) => {
event.preventDefault();
if (openMenu?.owner === button) { openMenu.close(); return; }
const values = comboValues(widget).map(String);
openJobMenu(into, button, values, String(widget?.value ?? ""), choose);
});
return (values) => { if (document.activeElement !== select) select.value = values[name] ?? ""; };
return (values) => { if (openMenu?.owner !== button) show(values[name]); };
}
// The jobs have no socket of their own, but a page saved by an earlier
@@ -90,6 +189,7 @@ export function castChips(node) {
let syncs = [];
let latest = {};
const build = (values) => {
if (openMenu && element.contains(openMenu.owner)) openMenu.close();
element.textContent = "";
syncs = [];
for (const number of [1, 2, 3, 4]) {
@@ -136,7 +236,10 @@ export function castChips(node) {
for (const run of syncs) run(values);
};
const watch = setInterval(() => sync(latest), WATCH);
chainCallback(node, "onRemoved", () => clearInterval(watch));
chainCallback(node, "onRemoved", () => {
clearInterval(watch);
if (openMenu && element.contains(openMenu.owner)) openMenu.close();
});
chainCallback(node, "onConfigure", () => queueMicrotask(() => keepOldJobLinks(node)));
return { element, sync };
}
+53 -1
View File
@@ -1,3 +1,5 @@
import { linkOrigin } from "./clip_rate.mjs";
// The same live-input rule used by the writer timeline: muted/bypassed
// sources do not reach this node. This inspects the wire, never media bytes.
export function linkSource(node, name) {
@@ -9,8 +11,58 @@ export function linkSource(node, name) {
return (source?.mode ?? 0) === 0 ? source ?? null : null;
}
// Keep in step with Python video_frames (node_h3_prompt_writer.py): H3 makes
// 5 frames plus steps of 17, at most 15 s at 24 fps, rounding a clip down.
export const H3_FPS = 24;
export function h3VideoFrames(frames) {
const count = Math.trunc(Number(frames));
if (!(count > 0)) return null;
return Math.max(1, Math.floor((Math.min(count, 15 * H3_FPS) - 5) / 17)) * 17 + 5;
}
// What the clip node's face last worked out for its run ({frames,
// startSeconds, endSeconds}), or null when the clip is not that node or its
// count is only known at run time.
export function clipTimingFor(node) {
// Through Reroutes and subgraphs, as every linked value is read.
const timing = linkOrigin(node, "video")?.node?.__ausbossClipTiming;
return timing && timing.frames > 0 ? timing : null;
}
// The words under "From the clip": what H3 will make of the clip's frames.
export function clipLengthWords(timing) {
if (!timing) return null;
const made = h3VideoFrames(timing.frames);
const seconds = (frames) => String(Number((frames / H3_FPS).toFixed(2)));
if (made < timing.frames) {
const up = made + 17;
const room = timing.roomFrames ?? Infinity;
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` : ""}.`,
warn: true,
};
}
if (made === timing.frames) return { title: `H3 uses all ${made} frames · ${seconds(made)} s`, note: "The clip is already a length H3 makes.", warn: false };
return { title: `H3 makes ${made} frames · ${seconds(made)} s`, note: `That is its shortest length; the clip has ${timing.frames} frames.`, warn: true };
}
// These video jobs keep the clip's own camera (Python MOVES_ARE and
// SWAP_VIDEO say so; a new voice or a change keeps the clip as it was shot).
// "keep going" makes new footage, so its camera is still the user's words.
const CAMERA_FROM_CLIP = ["copy its moves", "swap the person", "new voice", "change something"];
// The Camera list's first choice adds no camera words. With a clip wired for
// one of those jobs that means the clip's own camera, so it reads that way.
export function cameraChoiceLabel(value, values, node) {
if (value !== "as typed" || !node) return undefined;
const job = node.widgets?.find((widget) => widget.name === "video_job")?.value;
return CAMERA_FROM_CLIP.includes(job) && linkSource(node, "video") !== null ? "from the video" : undefined;
}
// Keep in step with Python KEEPS_ITS_LENGTH. Other jobs use seconds normally.
export function clipSetsDuration(node, values) {
return ["swap the person", "new voice", "change something"].includes(values.video_job)
return ["copy its moves", "swap the person", "new voice", "change something"].includes(values.video_job)
&& linkSource(node, "video") !== null;
}
+156
View File
@@ -0,0 +1,156 @@
// H3 Prompt Writer's two tabs. Simple is the card as it always was: your
// lines, the chips and the menus. Full prompt shows the prompt the node wrote
// on its last run, in a box you can change; whatever you type there is what
// H3 gets, until Reset to written. The `full_prompt` widget underneath holds
// the edit (empty when there is none), so it saves and loads like any value.
import { app } from "../../../scripts/app.js";
import { chainCallback, notifyAusbossChange } from "./index.mjs";
import { keepKeyInField } from "./canvas_passthrough.mjs";
import { compactAction } from "./panel_controls.mjs";
import { THEME as T } from "./theme.mjs";
import { commitWidgetValue } from "./widget_card_math.mjs";
import { FULL, SIMPLE, TAB_PROPERTY, WRITTEN_PROPERTY, boxText, editValue, isEdited, promptTab, writtenFromOutput } from "./h3_full_prompt_math.mjs";
export { FULL, SIMPLE, isEdited, promptTab };
const CSS_ID = "ausboss-h3-full-prompt-css";
const EDITED_NOTE = "Edited by you. This text is sent as it is; the Simple tab is not used until you reset.";
function ensureCss() {
if (document.getElementById(CSS_ID)) return;
const style = document.createElement("style");
style.id = CSS_ID;
style.textContent = `
.ausboss-prompt-tabs .dot{display:inline-block;width:6px;height:6px;margin-left:6px;border-radius:3px;background:${T.warn};vertical-align:1px}
.ausboss-prompt-tabs .dot[hidden]{display:none}
.ausboss-full-prompt{display:flex;flex-direction:column;gap:6px;height:100%;min-height:0}
.ausboss-full-prompt-area{display:block;flex:1 1 auto;width:100%;min-width:0;min-height:0;padding:5px 8px;box-sizing:border-box;border:1px solid transparent;border-radius:6px;background:${T.fill};color:${T.ink};font:11.5px/1.45 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;resize:none;overflow:auto}
.ausboss-full-prompt-area:focus{outline:none;border-color:${T.brand}}
.ausboss-full-prompt-area::placeholder{color:${T.faint}}
.ausboss-full-prompt-note{flex:none;padding:5px 8px;border-radius:5px;background:${T.warnSoft};color:${T.warnInk};font-size:11px;line-height:1.35}
.ausboss-full-prompt-note[hidden]{display:none}
.ausboss-full-prompt-foot{flex:none;display:flex;align-items:center;gap:8px;min-height:24px}
.ausboss-full-prompt-foot span{flex:1 1 auto;min-width:0;color:${T.faint};font-size:11px;overflow:hidden;white-space:nowrap;text-overflow:ellipsis}
.ausboss-simple-edited{display:flex;align-items:center;height:100%;padding:0 8px;box-sizing:border-box;border-radius:5px;background:${T.warnSoft};color:${T.warnInk};font-size:11px;line-height:1.3}
`;
document.head.append(style);
}
const widgetOf = (node, name) => node.widgets?.find((widget) => widget.name === name) ?? null;
const redraw = (node) => (node.__ausbossCard?.refreshByHand ?? node.__ausbossCard?.refresh)?.();
const writtenOf = (node) => String(node.properties?.[WRITTEN_PROPERTY] ?? "");
function setEdit(node, value) {
const widget = widgetOf(node, "full_prompt");
if (!widget || widget.value === value) return;
commitWidgetValue(node, widget, value, app?.canvas);
node.graph?.setDirtyCanvas?.(true, true);
}
// The tab switch at the top of the card. The open tab is a display choice
// kept on the node, not a value: it changes nothing that is sent.
export function promptTabs(node) {
ensureCss();
const element = document.createElement("div");
element.className = "ausboss-card-seg ausboss-prompt-tabs";
const make = (tab, label, title) => {
const button = document.createElement("button");
button.type = "button";
button.textContent = label;
button.title = title;
button.addEventListener("click", () => {
if (promptTab(node) === tab) return;
node.properties ??= {};
node.properties[TAB_PROPERTY] = tab;
redraw(node);
});
element.append(button);
return button;
};
const simple = make(SIMPLE, "Simple", "Your lines, the pictures and the menus. The node writes the full prompt from them.");
const full = make(FULL, "Full prompt", "The prompt the node wrote on its last run. Change it here to send your own.");
const dot = document.createElement("span");
dot.className = "dot";
dot.title = "Edited: this text is sent instead of the Simple tab.";
full.append(dot);
return {
element,
sync(values) {
const tab = promptTab(node);
simple.classList.toggle("on", tab === SIMPLE);
full.classList.toggle("on", tab === FULL);
dot.hidden = !isEdited(values);
},
};
}
// One line on the Simple tab while an edit is being sent instead.
export function simpleEditedNote() {
ensureCss();
const element = document.createElement("div");
element.className = "ausboss-simple-edited";
element.textContent = "Full prompt is edited, so these lines are not used until you reset it there.";
return { element };
}
// The Full prompt tab: the box, a note while it holds an edit, and Reset.
export function fullPromptBox(node) {
ensureCss();
const element = document.createElement("div");
element.className = "ausboss-full-prompt";
const area = document.createElement("textarea");
// Not the card's own textarea class: the script's colouring takes the
// first box with that class, and it belongs to the script.
area.className = "ausboss-full-prompt-area";
area.spellcheck = false;
area.placeholder = "Run the workflow once and the prompt the node writes shows here. Change it to send your own.";
area.title = "What H3 gets. Type here to send your own text instead of the node's.";
const note = document.createElement("div");
note.className = "ausboss-full-prompt-note";
note.textContent = EDITED_NOTE;
const foot = document.createElement("div");
foot.className = "ausboss-full-prompt-foot";
const hint = document.createElement("span");
hint.textContent = "Filled in after each run.";
const reset = compactAction("Reset to written", "Throw your edit away and send what the Simple tab writes again.");
foot.append(hint, reset);
element.append(area, note, foot);
area.addEventListener("input", () => {
setEdit(node, editValue(area.value, writtenOf(node)));
redraw(node);
});
area.addEventListener("change", () => notifyAusbossChange());
area.addEventListener("keydown", (event) => {
keepKeyInField(event, { weights: true });
if (event.key === "Escape") area.blur();
});
// Leaving the box shows what is sent: emptied, it is the written prompt again.
area.addEventListener("blur", () => redraw(node));
reset.addEventListener("click", () => {
setEdit(node, "");
area.value = writtenOf(node);
notifyAusbossChange();
redraw(node);
});
// Each run hands back the prompt the node wrote. It is kept on the node, so
// a saved workflow opens with it.
chainCallback(node, "onExecuted", (output) => {
const written = writtenFromOutput(output);
if (written === null) return;
node.properties ??= {};
node.properties[WRITTEN_PROPERTY] = written;
redraw(node);
});
return {
element,
sync(values) {
const edited = isEdited(values);
if (document.activeElement !== area) area.value = boxText(values, writtenOf(node));
note.hidden = !edited;
reset.disabled = !edited;
},
};
}
+39
View File
@@ -0,0 +1,39 @@
// What H3 Prompt Writer's Full prompt tab decides, kept apart from the DOM so
// it can be tested. The node writes the prompt; the tab shows what it wrote
// after a run, and text typed there is sent in its place until Reset.
export const SIMPLE = "simple";
export const FULL = "full";
// Display choices kept on the node: the open tab, and the last prompt the
// node wrote (so a saved workflow opens the tab with it).
export const TAB_PROPERTY = "ausboss_prompt_tab";
export const WRITTEN_PROPERTY = "ausboss_written_prompt";
export function promptTab(node) {
return node?.properties?.[TAB_PROPERTY] === FULL ? FULL : SIMPLE;
}
// The widget holds an edit only when there is one: empty text, or the
// written prompt typed back unchanged, means "send what the node writes".
export function editValue(text, written = "") {
const typed = String(text ?? "");
if (!typed.trim()) return "";
if (written && typed.trim() === String(written).trim()) return "";
return typed;
}
export function isEdited(values) {
return String(values?.full_prompt ?? "").trim() !== "";
}
// What the box shows: the edit, else the last prompt the node wrote.
export function boxText(values, written = "") {
return isEdited(values) ? String(values.full_prompt) : String(written ?? "");
}
// The prompt the node wrote on its last run, from the run's ui output.
export function writtenFromOutput(output) {
const text = output?.written_prompt;
if (Array.isArray(text)) return typeof text[0] === "string" ? text[0] : null;
return typeof text === "string" ? text : null;
}
+117
View File
@@ -0,0 +1,117 @@
// Language for the pack's own node faces. ComfyUI translates node names and
// socket names from locales/<language>/nodeDefs.json; the controls the pack
// draws itself (widget cards, panels, bars, menus) are translated here.
//
// t("Preview") the Chinese text on a Chinese ComfyUI, else the same text
// translateText(text) the lookup alone, no locale check
//
// The Chinese table is js/shared/i18n_zh.mjs, keyed by the English text, so a
// string with no entry stays English. Only what is displayed changes; widget
// names, widget values and saved workflows never go through this.
import { PATTERNS, SCRUB_HINT_EN, SCRUB_HINT_ZH, ZH } from "./i18n_zh.mjs";
// "zh", "zh-CN", "zh-TW" ... all take the Chinese table.
export function isChineseLocale(code) {
return typeof code === "string" && /^zh(?:[-_]|$)/i.test(code.trim());
}
// ComfyUI's language setting, read each time so a changed setting is seen on
// the next call.
let localeSource = null;
// js/i18n/index.js hands over ComfyUI's own `app`, which is there before
// `window.app` is.
export function useLocaleSource(read) { localeSource = typeof read === "function" ? read : null; }
export function currentLocale() {
try {
const value = localeSource ? localeSource() : globalThis.app?.ui?.settings?.getSettingValue?.("Comfy.Locale");
return typeof value === "string" ? value : "";
} catch {
return "";
}
}
export const chineseActive = () => isChineseLocale(currentLocale());
// Look `text` up in the Chinese table, keeping any spaces around it. Returns
// the text itself when there is no entry.
export function translateText(text, table = ZH, patterns = PATTERNS) {
if (typeof text !== "string" || text === "") return text;
const trimmed = text.trim();
if (trimmed === "") return text;
// A number box's tooltip is "<its own tooltip> <the scrub hint>".
if (table === ZH && trimmed.endsWith(` ${SCRUB_HINT_EN}`)) {
const own = trimmed.slice(0, -SCRUB_HINT_EN.length - 1);
return text.replace(trimmed, () => `${translateText(own, table, patterns)} ${SCRUB_HINT_ZH}`);
}
const hit = Object.hasOwn(table, trimmed) ? table[trimmed] : undefined;
let result = typeof hit === "string" && hit !== "" ? hit : null;
if (result === null) {
for (const [pattern, build] of patterns) {
const match = pattern.exec(trimmed);
if (match) { result = build(...match); break; }
}
}
if (result === null) return text;
return text.replace(trimmed, () => result);
}
export function t(text) {
return chineseActive() ? translateText(text) : text;
}
// ---------- translating a face that is already built ----------
const ATTRIBUTES = ["title", "placeholder", "aria-label"];
// Text that belongs to the user or the graph, or that code reads back.
const SKIP = "[data-no-i18n],[class*='ausboss-callout'],[class*='ausboss-note'],.ausboss-show-text-body,.ausboss-lora-label";
// Text inside these is a value (what is typed, or the page's own scripts), not a label.
const VALUE_HOLDERS = "textarea,input,script,style,[contenteditable]";
const SCOPE = "[class*='ausboss']";
function inScope(element, text = false) {
if (!element?.closest?.(SCOPE) || element.closest(SKIP)) return false;
return !(text && element.closest(VALUE_HOLDERS));
}
function translateNode(node) {
if (node.nodeType === 3) {
const parent = node.parentElement;
// An <option>'s text is what the list shows; its value is its own attribute.
if (!parent || !inScope(parent, true)) return;
const next = translateText(node.nodeValue);
if (next !== node.nodeValue) node.nodeValue = next;
return;
}
if (node.nodeType !== 1 || !(node.matches?.(SCOPE) || node.querySelector?.(SCOPE) || node.closest?.(SCOPE))) return;
const walker = node.ownerDocument.createTreeWalker(node, 1 | 4);
const visit = (current) => {
if (current.nodeType === 3) translateNode(current);
else if (current.nodeType === 1 && inScope(current)) {
for (const name of ATTRIBUTES) {
const value = current.getAttribute(name);
if (!value) continue;
const next = translateText(value);
if (next !== value) current.setAttribute(name, next);
}
}
};
visit(node);
for (let current = walker.nextNode(); current; current = walker.nextNode()) visit(current);
}
// Keep every pack face in `root` translated, including text a face writes
// later. Returns a function that stops it.
export function followFaces(root = document.body) {
translateNode(root);
const observer = new MutationObserver((records) => {
for (const record of records) {
if (record.type === "characterData") translateNode(record.target);
else if (record.type === "attributes") translateNode(record.target);
else for (const added of record.addedNodes) translateNode(added);
}
});
observer.observe(root, { subtree: true, childList: true, characterData: true, attributes: true, attributeFilter: ATTRIBUTES });
return () => observer.disconnect();
}
+339
View File
@@ -0,0 +1,339 @@
// Simplified Chinese for the text the pack draws on its own node faces
// (widget cards, panels, bars and menus). The key is the English text as the
// code writes it; a string with no entry here simply stays English.
// Only what is DISPLAYED changes: widget names, values, saved workflows and
// the API prompt never see these strings.
//
// Product and model names (H3, Pika, Qwen, FlashVSR, LoRA, VRAM, SAM 3) and
// file names, codec names and algorithm names stay as they are.
export const ZH = {
// ---- card rows and group headers
"Target": "目标", "Size": "尺寸", "Edge": "边缘", "Budget": "像素预算", "Scale": "缩放", "Fit": "适应",
"Fill": "填充", "Multiple": "倍数", "Filter": "滤镜", "Job": "任务", "Pieces": "分块数",
"Lock": "锁定", "Tolerance": "容差", "Feather": "羽化", "Remove tint": "去除偏色", "Strength": "强度",
"Method": "方法", "Reference": "参考", "Invert mask": "反转遮罩", "Megapixels": "百万像素",
"More": "更多", "MORE": "更多", "Tile size": "分块大小", "Overlap": "重叠", "Redraw limit": "重绘上限",
"Keep colors": "保持颜色", "Tone match": "色调匹配", "Fix edge halo": "修复边缘光晕", "Follow changes": "跟随变化",
"Context": "上下文", "Stay in picture": "不出画面", "Blend": "混合", "Grow": "扩大", "Blur": "模糊",
"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": "白场",
"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": "画布",
"Find": "查找", "If several": "有多个时", "Sureness": "把握度", "FPS": "帧率", "Scene cut": "场景切换", "Batch": "批量",
"Model": "模型", "Mode": "模式", "Anchor": "对齐位置", "Pad fill": "扩边填充", "Pad color": "扩边颜色", "Color": "颜色",
"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": "帧",
"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": "嵌入工作流",
"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": "片段出点",
"Colors": "颜色", "Preview steps": "预览步骤", "Show picture": "显示图片", "Preview": "预览",
"Settings": "设置", "Show as": "显示为", "When off": "关闭时", "Group order": "分组顺序", "Groups": "分组", "Inputs": "输入", "Outputs": "输出",
"Fit to ratio": "适应比例", "Hold the shape": "保持形状", "Box 1 is": "框 1 是",
// ---- on / off pills and short states
"on": "开", "off": "关", "On": "开", "Off": "关", "keep": "保留", "remove": "移除", "once per run": "每次运行一次", "every step": "每一步",
"forward, back": "正放、倒放", "not used": "未使用", "by blend in": "(融合模式下)", "blend in": "融合", "blend": "混合",
// ---- choice labels
"Width × height": "宽 × 高", "Longest edge": "最长边", "Shortest edge": "最短边", "Scale factor": "缩放倍数",
"cover": "填满", "fit": "适应", "fit inside": "放入框内", "crop to fill": "裁剪填满", "crop to ratio": "按比例裁剪", "crop": "裁剪",
"pad": "扩边", "resize": "缩放", "stretch": "拉伸", "megapixels": "百万像素", "longest side": "最长边", "scale": "缩放",
"hist": "直方图", "histogram": "直方图", "first frame": "首帧", "reference": "参考图", "guided": "引导", "matting": "抠图",
"optical flow (RAFT)": "光流 (RAFT)", "match a": "匹配 a", "match b": "匹配 b", "error": "报错", "source rect": "源矩形",
"whole canvas": "整个画布", "all in one run": "一次全部", "one per run": "每次一张", "all of them": "全部", "none": "无", "None": "无",
"any": "任意", "always": "始终", "auto": "自动", "stay": "保持", "start over": "重新开始", "keep picks": "保留选择",
"stop the run": "停止运行", "empty mask": "空遮罩", "newest first": "最新在前", "oldest first": "最旧在前", "random": "随机", "Random": "随机",
"next": "下一张", "name": "名称", "title": "标题", "canvas": "画布", "each line": "每行一次", "blank line": "空行分隔",
"rows": "逐行", "one pill": "单选", "bypass": "绕过", "mute": "静音", "mirror": "镜像", "follow": "跟随", "linked": "已连接",
"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": "裁剪",
"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": "主体",
// ---- buttons, bars, captions
"Add": "添加", "Browse": "浏览", "Clear": "清除", "Done": "完成", "Erase": "擦除", "Paint": "绘制", "Pick": "选取", "Load": "加载",
"Open editor": "打开编辑器", "Reset": "重置", "Reset crop": "重置裁剪", "Reset padding": "重置扩边", "Reset to written": "恢复为所写内容",
"Undo": "撤销", "Use as start": "设为起点", "Use last run": "用上次的", "New seed": "新种子", "Step +1": "步进 +1", "STOP": "停止",
"FIND": "查找", "FRAME": "帧", "LOOP": "循环", "AUTO": "自动", "Turn": "旋转", "Step": "步进", "Match": "匹配",
"+ Choice": "+ 选项", "+ LoRA": "+ LoRA", "+ new": "+ 新建", "+ video": "+ 视频", "Layouts ▾": "布局 ▾",
"Select nodes, then add a switch": "先选中节点,再添加开关", "Description": "说明",
"Choose a file…": "选择文件…", "Choose a sound file": "选择声音文件", "Choose an input video…": "选择输入视频…",
"Choose an uploaded image…": "选择已上传的图片…", "Choose an uploaded video…": "选择已上传的视频…",
"Choose or upload a video": "选择或上传视频", "Choose an input image": "选择输入图片", "Choose an input video": "选择输入视频",
"Copy a folder from your computer": "从电脑复制一个文件夹", "Load image": "加载图片", "Load video": "加载视频",
"Connect a mask to see it here": "连接遮罩即可在此查看", "Connect an image to see it here": "连接图像即可在此查看",
"Connect frames to see it here": "连接帧即可在此查看",
"Connect a picture or a video. H3 needs one to start from.": "请连接一张图片或一段视频,H3 需要一个起点。",
"Drag on the canvas to draw a box": "在画布上拖动来画一个框",
"Each box you draw gets its words here: a thing to show, or text to write in the picture.": "你画的每个框都在这里写描述:要显示的东西,或要写在图里的文字。",
"Edited by you. This text is sent as it is; the Simple tab is not used until you reset.": "已由你修改。这段文字将原样发送,重置之前不会使用“简易”标签页。",
"Edited: this text is sent instead of the Simple tab.": "已修改:发送的是这段文字,而不是“简易”标签页。",
"Full prompt is edited, so these lines are not used until you reset it there.": "完整提示词已被修改,所以这些行在那边重置之前不会使用。",
"Filled in after each run.": "每次运行后自动填入。",
"No LoRAs yet": "还没有 LoRA", "no LoRAs": "没有 LoRA", "No pictures here yet. Drop a folder or pictures on the node, or bring a folder in:": "这里还没有图片。把文件夹或图片拖到节点上,或导入一个文件夹:",
"no pictures": "没有图片", "Working on the fine details…": "正在处理细节…", "Run to preview the saved video": "运行后预览保存的视频",
"run the graph to see the text that arrives here": "运行工作流即可在此看到传入的文字",
"rolls a new seed each queue": "每次排队都会换新种子", "Source · feather 24 px": "素材 · 羽化 24 px",
"Select the nodes of one part, such as a box and its Save, then press + Switch.": "选中某个部分的节点(例如一个框和它的保存节点),然后点“+ 开关”。",
"Choose an uploaded image or drop one onto this node.": "选择已上传的图片,或把图片拖到此节点上。",
"Choose an uploaded video or add one to ComfyUI's input folder.": "选择已上传的视频,或把视频放进 ComfyUI 的 input 文件夹。",
"Choose a file from ComfyUI's input folder or load a new image.": "从 ComfyUI 的 input 文件夹选择文件,或加载新图片。",
"Choose a file from ComfyUI's input folder or load a new video.": "从 ComfyUI 的 input 文件夹选择文件,或加载新视频。",
"Choose a rendered image from ComfyUI's output folder.": "从 ComfyUI 的 output 文件夹选择已生成的图片。",
"Choose a rendered video from ComfyUI's output folder.": "从 ComfyUI 的 output 文件夹选择已生成的视频。",
"Choose a picture or video to center.": "选择要居中的图片或视频。",
"Upload a picture into ComfyUI's input folder": "把图片上传到 ComfyUI 的 input 文件夹",
"Upload an image into ComfyUI's input folder": "把图片上传到 ComfyUI 的 input 文件夹",
"Upload a video into ComfyUI's input folder": "把视频上传到 ComfyUI 的 input 文件夹",
"Upload a sound file into ComfyUI's input folder": "把声音文件上传到 ComfyUI 的 input 文件夹",
// ---- tooltips written in the pack's own code
"Add a LoRA": "添加 LoRA", "Pick one LoRA, or click a folder name to add all its LoRAs.": "选一个 LoRA,或点文件夹名把里面的 LoRA 全部加入。",
"Re-check LoRA files: refresh the list and reconnect rows whose files moved or came back": "重新检查 LoRA 文件:刷新列表,并重新连接文件被移动或重新出现的行",
"LoRA templates: save this stack, or apply a saved one": "LoRA 模板:保存当前这组,或套用已保存的",
"Toggle every LoRA: mixed saves your setup and turns all on; on turns all off; off brings your saved setup back": "切换所有 LoRA:混合时保存当前设置并全部开启;全开时全部关闭;全关时恢复你保存的设置",
"Serialized LoRA stack managed by the node's row editor; edit the rows, not this value.": "由节点的行编辑器管理的 LoRA 列表;请编辑各行,不要改这个值。",
"LoRA Loader settings": "LoRA 加载器设置",
"Click to type a seed": "点击输入种子", "Copy the seed": "复制种子", "Copy the text": "复制文字", "Earlier seeds this node ran with": "此节点用过的历史种子",
"Increment the seed after each queue (click again for decrement)": "每次排队后种子加 1(再点一次改为减 1)",
"Keep this seed for every queue": "每次排队都用这个种子",
"Put the last run's seed back and pin it (Fixed)": "恢复上次运行的种子并固定",
"Roll a fresh seed and pin it (Fixed)": "随机一个新种子并固定",
"Roll a new seed after every queue": "每次排队后随机新种子",
"Rolls a new seed after each run. Tap for Fixed.": "每次运行后随机新种子。点一下切换为固定。",
"Seed settings: full or compact look": "种子设置:完整或紧凑外观", "Number settings": "数字设置", "Text settings": "文字设置",
"Image Crop + Rotate + Pad settings": "图像裁剪 + 旋转 + 扩边设置", "Stitch Inpaint settings": "拼回重绘设置",
"Step down; Shift = fine.": "减小;按住 Shift 精细调节。", "Step up; Shift = fine.": "增大;按住 Shift 精细调节。",
"Arithmetic over a, b and c: numbers, + - * / // % **, parentheses, and min/max/abs/round/floor/ceil/sqrt.": "对 a、b、c 做运算:数字、+ - * / // % **、括号,以及 min/max/abs/round/floor/ceil/sqrt。",
"Center side to side": "左右居中", "Center top to bottom": "上下居中",
"Choose how to reach the next ratio. Crop trims the picture and Pad adds fill.": "选择如何达到下一个比例:裁剪会切掉画面,扩边会补上填充。",
"Comma-separated text; a group is listed when its title contains any of it": "用逗号分隔的文字;分组标题包含其中任意一项就会列出",
"Drag a handle to set where the sound starts or stops. Drag the middle to slide it.": "拖动手柄设置声音的起点或终点,拖动中间可整体滑动。",
"Drag to change the Duration; the start stays.": "拖动来改变时长,起点不变。",
"Drag to move the clip; its Duration stays. Shift + arrow moves one frame.": "拖动来移动片段,时长不变。Shift + 方向键每次移动一帧。",
"Drag to slide the clip; its Duration stays.": "拖动来滑动片段,时长不变。",
"Fill #000000": "填充 #000000", "Fill #808080": "填充 #808080",
"Fill colour of the padding and rotation corners. Now #808080.": "扩边和旋转后空角的填充颜色。当前为 #808080。",
"Keep the canvas size.": "保持画布尺寸。", "Keep the whole picture and add fill to reach the selected ratio.": "保留整张图片,并补上填充以达到所选比例。",
"Trim the picture to the selected ratio.": "把图片裁剪到所选比例。",
"Pad to 16:9: keep every pixel and add fill around it.": "扩边到 16:9:保留每个像素,四周补上填充。",
"Pad to 1:1: keep every pixel and add fill around it.": "扩边到 1:1:保留每个像素,四周补上填充。",
"Pad to 21:9: keep every pixel and add fill around it.": "扩边到 21:9:保留每个像素,四周补上填充。",
"Pad to 3:2: keep every pixel and add fill around it.": "扩边到 3:2:保留每个像素,四周补上填充。",
"Pad to 4:3: keep every pixel and add fill around it.": "扩边到 4:3:保留每个像素,四周补上填充。",
"Tap a ratio to pad the picture to it (or crop it, with Fit on crop). Tap the lit one to go back to the whole picture.": "点一个比例,把图片扩边到该比例(“适应”选裁剪时则是裁剪)。再点亮着的那个可回到完整图片。",
"Show the portrait ratios": "显示竖版比例", "Show ratio, fit, align, fill, feather, center and resize settings": "显示比例、适应、对齐、填充、羽化、居中和缩放设置",
"Reset rotation, crop and padding, and turn the padlock off. Fill, feather, Align and the timeline stay.": "重置旋转、裁剪和扩边,并解除锁定。填充、羽化、对齐和时间线保持不变。",
"Show the whole picture again; rotation, padding and the timeline stay. With the padlock on, the bands it added to keep the shape go too.": "重新显示整张图片;旋转、扩边和时间线保持不变。锁定时,为保持形状而补的边也会去掉。",
"The diamonds and crop squares drag freely; the orange corners always keep the shape. Tap to hold this shape whatever you drag.": "菱形和裁剪方块可自由拖动;橙色角点始终保持形状。点一下,无论怎么拖都保持当前形状。",
"Make the canvas width and height multiples of this number before resizing. Padding grows or unpadded edges are trimmed. Use 1 to turn alignment off.": "缩放前先让画布宽高成为此数的倍数。扩边会加大,没扩边的边缘会被裁掉。填 1 表示不对齐。",
"Rounds each resized side to a multiple of this (32 for LTX and Wan, 8 or 64 for image models). Each side rounds on its own, so a large step can stretch the picture slightly; the readout warns above 1%.": "把缩放后的每条边取整为此数的倍数(LTX 和 Wan 用 32,图像模型用 8 或 64)。每条边各自取整,步长大时画面可能略有拉伸;超过 1% 时读数会提醒。",
"Output budget in megapixels (x 1024x1024). The size readout under the picture shows where it lands.": "输出像素预算,单位百万像素(x 1024x1024)。图片下方的尺寸读数会显示最终大小。",
"Resize the output to a megapixel budget, each side rounded to the step (32 for LTX and Wan).": "把输出缩放到像素预算,每条边取整到步长(LTX 和 Wan 用 32)。",
"Resize to the megapixel budget and round each side to the step.": "缩放到像素预算,每条边取整到步长。",
"Feather of the mask into the kept pixels; the image keeps a hard edge against the fill.": "遮罩向保留像素内的羽化;图片与填充之间保持硬边。",
"Feather of the mask into the kept frames, in pixels. The frames keep a hard edge against the fill whatever the feather, so a black-band outpaint still sees its bars.": "遮罩向保留画面内的羽化,单位像素。无论羽化多少,画面与填充之间都保持硬边,所以黑边外扩仍能看到黑条。",
"Where the clip starts in the source video.": "片段在源视频中的起点。", "Where the clip ends in the source video. Typing it changes the Duration.": "片段在源视频中的终点。输入它会改变时长。",
"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 表示播到文件末尾。",
"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.": "每隔这么多帧保留一帧。输出帧率会随之调整以保持实时播放;时长按保留的帧数计算。",
"Use the whole video: start at 0 with no Duration limit. Keeps Every nth and Frames for.": "使用整段视频:从 0 开始,不限制时长。“每隔几帧”和“帧数用于”仍然有效。",
"Play it again and again": "循环播放", "Play the clip from its start": "从头播放片段", "Play the part that comes out": "播放最终输出的部分",
"Show times in frames: source frames for Start and Ends at, clip frames for Duration.": "以帧显示时间:起点和终点用源视频帧,时长用片段帧。", "Show times in seconds.": "以秒显示时间。",
"Playback frame rate; wire Load Video's fps output to match the source. A connected video input brings its own rate and overrides this widget. Fractional rates like 23.976 and 29.97 can be typed in.": "播放帧率;把加载视频的 fps 输出连过来可与源视频一致。连接了视频输入时会使用它自带的帧率,并覆盖这个控件。可以输入 23.976、29.97 这类小数帧率。",
"Play the clip forward then backward so it loops seamlessly. Roughly doubles the frame count and the encode time; the first and last frames are not repeated at the turnaround.": "先正放再倒放,让片段无缝循环。帧数和编码时间大约翻倍;转折处首尾帧不会重复。",
"On embeds the workflow in the video file, so dropping the file back on the canvas restores the graph that made it.": "开启后会把工作流嵌入视频文件,把文件拖回画布即可还原生成它的工作流。",
"Container and codec. mp4 h264 plays everywhere; mp4 h265 halves the size at the same quality where supported; the nvenc pair encodes on an NVIDIA GPU instead of the CPU (much faster, slightly larger); webm vp9 and webm av1 suit the web and mux Opus; mov prores": "封装格式和编码。mp4 h264 到处都能播放;mp4 h265 在支持的设备上同画质体积减半;两个 nvenc 选项用 NVIDIA 显卡而不是 CPU 编码(快得多,体积略大);webm vp9 和 webm av1 适合网页并封装 Opus;mov prores",
"Encode quality: lower is better and larger. 19 is visually lossless for h264; h265 and vp9 read the same scale (vp9 tolerates a few points higher).": "编码质量:数值越小画质越好、文件越大。h264 用 19 在视觉上无损;h265 和 vp9 用同样的刻度(vp9 可以高几个点)。",
"Show the clip's first frame here while it is being made, one step at a time, with a Stop button. Off by default.": "生成过程中在这里逐步显示片段的首帧,并带一个停止按钮。默认关闭。",
"Stop this run now. The next run in the queue still starts.": "立即停止这次运行。队列里的下一次运行仍会开始。",
"Moves each moment onto the nearest beat of the song. Pick off to keep your own seconds.": "把每个时刻移到歌曲最近的节拍上。选“关”则保留你自己写的秒数。",
"The second of the song to start from, so the clip gets the good part.": "从歌曲的第几秒开始,让片段用上最精彩的部分。",
"This video job uses the incoming clip, so Length is not used.": "这个视频任务使用传入的片段,所以不使用“长度”。", "From the clip": "取自片段",
"Plug a picture into picture_1 to name it @1 in your lines.": "把图片接到 picture_1,就能在文字里用 @1 称呼它。",
"Plug a picture into picture_2 to name it @2 in your lines.": "把图片接到 picture_2,就能在文字里用 @2 称呼它。",
"Plug a picture into picture_3 to name it @3 in your lines.": "把图片接到 picture_3,就能在文字里用 @3 称呼它。",
"Plug a picture into picture_4 to name it @4 in your lines.": "把图片接到 picture_4,就能在文字里用 @4 称呼它。",
"Plug a video into video to copy its moves, swap the person, keep it going or give it a new voice.": "把视频接到 video,可以复制它的动作、换人、接着往下拍,或换一个新声音。",
"Turn on when a swap keeps the video's own sound. Each line is timed from that sound, and words from anyone else are left out so only the new person's mouth moves.": "换人并保留视频原声时开启。每一行按原声计时,其他人的台词会被去掉,只有新人物的嘴在动。",
"Run the workflow once and the prompt the node writes shows here. Change it to send your own.": "运行一次工作流后,节点写出的提示词会显示在这里。修改它就会发送你自己的版本。",
"The prompt the node wrote on its last run. Change it here to send your own.": "节点上次运行写出的提示词。在这里修改即可发送你自己的版本。",
"Throw your edit away and send what the Simple tab writes again.": "放弃你的修改,重新发送“简易”标签页写出的内容。",
"What H3 gets. Type here to send your own text instead of the node's.": "H3 收到的内容。在这里输入即可用你自己的文字代替节点写的。",
"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": "舒缓钢琴:加了音乐会更响",
"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.": "“逐行”让每个开关各占一行,各自有关 | 开。“单选”把这些开关合成一个选项条,始终选中其中一个。",
"Show only the labels and their switches. Double-click a label, or right-click the node, to edit again.": "只显示名称和开关。双击名称或右键节点可重新编辑。",
"Select the nodes of one part on the canvas, then press this: they get one switch": "在画布上选中某一部分的节点再按这里,它们会得到一个开关",
"Set the nodes the way this choice should be, then press this and give it a name. Do it again for each choice: the card becomes one pill, and picking one sets the nodes that way.": "先把节点调成这个选项该有的样子,再按这里并起个名字。每个选项都这样做一遍:卡片会变成一个选项条,选中某项就会把节点设成对应状态。",
"What a switched-off part does. Bypass: its nodes hand their inputs straight through, so the rest of the workflow still runs. Mute: its nodes do not run, and nor does anything that needs their output.": "关闭的部分怎么处理。绕过:节点把输入直接传出去,工作流其余部分照常运行。静音:节点不运行,依赖它们输出的节点也不运行。",
"What off means, which groups get a switch of their own, and their order": "“关”是什么意思、哪些分组有各自的开关,以及它们的顺序",
"Which groups get a switch of their own, listed under the switches you made: none, every group, the numbered ones (titles starting with a digit, like 1 · Load), or titles matching text.": "哪些分组有各自的开关,列在你创建的开关下面:无、每个分组、编号分组(标题以数字开头,如 1 · Load),或标题匹配某段文字。",
"The order of the group rows. Canvas: the way the workflow reads, column by column from the left and top to bottom within a column. Title: by title, with numbers in numeric order.": "分组行的顺序。画布:按工作流的阅读顺序,从左到右逐列,每列从上到下。标题:按标题排序,数字按数值大小排。",
"Toggle looping for this saved preview": "切换此预览的循环播放",
// ---- tooltips of the nodes the Person Swap and Pika Remix workflows use
"A sound file in ComfyUI's input folder. Use Upload to add one.": "ComfyUI input 文件夹里的声音文件。用“上传”添加新的。",
"Fill colour of the padding and rotation corners. Video outpaint models key on it: the LTX IC-LoRA paints pure black (#000000) and leaves other colours alone. Now #000000.": "扩边和旋转后空角的填充颜色。视频外扩模型会以它为依据:LTX IC-LoRA 画纯黑(#000000),其他颜色保持不动。当前为 #000000。",
"Container and codec.": "封装格式和编码。mp4 h264 到处都能播放;mp4 h265 在支持的设备上同画质体积减半;两个 nvenc 选项用 NVIDIA 显卡而不是 CPU 编码(快得多,体积略大);webm vp9 和 webm av1 适合网页并封装 Opus;mov prores 是 ProRes HQ 剪辑母版;mkv ffv1 是逐位无损,文件非常大;gif 和 webp 没有声音、无限循环,并把每一帧都放进内存,只适合短片段。",
"Feather of the mask into the kept frames, in pixels. The frames keep a hard edge against the fill whatever the feather, so a black-band outpaint still sees its bars.": "遮罩向保留画面内的羽化,单位像素。无论羽化多少,画面与填充之间都保持硬边,所以黑边外扩仍能看到黑条。",
"From the picture keeps your photo's look. The others redraw it in that style.": "“取自图片”保留你照片原本的样子,其他选项会把它重绘成对应风格。",
"How long the clip is. Plan on about one moment a second at most.": "片段有多长。大约每秒最多安排一个时刻。",
"How many times larger each side gets. 1 keeps the size and only sharpens.": "每条边放大多少倍。1 表示尺寸不变,只做锐化。",
"How the camera moves the whole way through. As typed leaves it to your words; with a video wired it shows as from the video and keeps the video's own camera.": "镜头从头到尾怎么运动。“照输入”交给你写的文字;连了视频时显示为“取自视频”,沿用视频自带的镜头。",
"Keeps each frame's colours the same as your video. Leave it on.": "让每一帧的颜色与你的视频保持一致。建议保持开启。",
"Saved under the output folder; subfolders are created automatically.": "保存在 output 文件夹下;子文件夹会自动创建。",
"The FlashVSR model file, from ComfyUI/models/diffusion_models.": "FlashVSR 模型文件,位于 ComfyUI/models/diffusion_models。",
"The integer to output.": "要输出的整数。",
"The language of the words in quotes.": "引号里台词所用的语言。",
"The music, like a slow lo-fi beat. A clip with music comes out louder. Empty means no music.": "音乐,比如舒缓的 lo-fi 节奏。带音乐的片段声音会更响。留空表示没有音乐。",
"What you hear the whole way through, like rain on a window. Leave it empty for none.": "从头到尾都能听到的声音,比如窗上的雨声。留空表示没有。",
"Play": "播放",
"Load image": "加载图片",
"Load video": "加载视频",
"One at a time": "一次一个",
"applies to the next ratio": "应用于下一个比例",
"rain on a window": "窗上的雨声",
// ---- card tooltips and placeholders
"Size of the finished picture. 0 keeps the picture's own size.": "成品图片的大小。0 表示保持图片原有大小。",
"Used only while Fill holes is on.": "仅在“填补孔洞”开启时使用。",
"the folder itself": "文件夹本身",
"Choose a folder inside ComfyUI's input or output folder.": "选择 ComfyUI 的 input 或 output 文件夹里的一个文件夹。",
"Prompt, caption, or shared text": "提示词、字幕或共用文字",
"type here": "在此输入",
"One line for each run": "每次运行写一行",
"A woman in a {red|blue|green} {sweater|jacket}. One choice is picked from each set.": "一位穿着{红色|蓝色|绿色}{毛衣|夹克}的女士。每组花括号里会随机选一项。",
"Prompt - describe the whole finished canvas": "提示词:描述整个成品画面",
"Negative prompt (ignored at CFG 1)": "负面提示词(CFG 为 1 时忽略)",
"On, the vision tower also sees the reference images. Use on for AnyPaint with a whole-canvas reference; use off for Registered Outpaint with a source-rectangle reference. Match the adapter's conditioning contract.": "开启时,视觉模块也会看到参考图。AnyPaint 配整张画布的参考图时开启;Registered Outpaint 配源矩形参考图时关闭。要与适配器的条件约定保持一致。",
"0 keeps the source width; set one side only to keep the aspect.": "0 表示保持源宽度;只设一边即可保持宽高比。",
"0 keeps the source height; set one side only to keep the aspect.": "0 表示保持源高度;只设一边即可保持宽高比。",
"Lock the untouched parts; step aside when the whole picture changes": "锁住没改动的部分;整张图都变了就不介入",
"Lock even when the whole picture changes": "即使整张图都变了也锁定",
"Do nothing": "什么都不做",
"A separate horizontal and vertical zoom plus a shift: how Qwen edits drift": "水平和垂直方向各自缩放,再加平移:Qwen 编辑后画面通常就是这样偏移的",
"Also a slight rotation or shear": "另外还修正轻微的旋转或倾斜",
"Stretch the nearest edge pixels": "拉伸最近的边缘像素",
"The original's pixels": "使用原图的像素",
"Flat #808080, for an inpaint pass": "纯 #808080,用于重绘",
"resize b to a's size": "把 b 缩放到 a 的尺寸",
"resize a to b's size": "把 a 缩放到 b 的尺寸",
// ---- panels, menus and lists of the same nodes
"Absorb chain LoRAs": "并入串联的 LoRA",
"Add your own trigger word...": "添加自己的触发词…",
"Adds 1 after each run. Tap for -1.": "每次运行后加 1。点一下改为减 1。",
"Advisory range for this LoRA; out-of-range strengths tint orange on the row.": "这个 LoRA 的建议范围;超出范围的强度会让该行显示为橙色。",
"Asks civitai.com about this one file, from this browser.": "由此浏览器向 civitai.com 查询这一个文件。",
"Audio preview unavailable ⓘ": "无法预览音频 ⓘ",
"Audio preview unavailable. Show details.": "无法预览音频。查看详情。",
"Back to defaults for this node type": "恢复此节点类型的默认值",
"Changed from the suggested value": "与建议值不同",
"Choice": "选项",
"Choose a source to set the clip": "先选择素材,再设置片段",
"Choose a source to begin": "选择素材后开始",
"Civitai lookup button": "Civitai 查询按钮",
"Civitai lookup failed": "Civitai 查询失败",
"Civitai picture": "Civitai 图片",
"Close without saving: puts back everything as it was when the editor opened (Esc)": "不保存关闭:恢复为打开编辑器时的样子(Esc)",
"Crop image — right-click to copy": "裁剪后的图片,右键可复制",
"Default strength": "默认强度",
"Drag to move the whole group": "拖动可移动整个分组",
"Drag to reorder": "拖动可调整顺序",
"Each line becomes a moment. A blank line between lines is a cut.": "每一行是一个时刻,两行之间的空行表示切换场景。",
"Enable or disable this LoRA": "启用或停用这个 LoRA",
"Fetching...": "获取中…",
"Group name": "分组名称",
"Held": "已锁定",
"Hide file extension": "隐藏文件扩展名",
"Hide folder names": "隐藏文件夹名",
"Keeps this seed for every run. Tap for +1.": "每次运行都用这个种子。点一下改为加 1。",
"Loading…": "加载中…",
"Long names": "长名称",
"Mask feather in pixels.": "遮罩羽化,单位像素。",
"More ratios": "更多比例",
"Name this stack; saving over an existing name replaces it": "给这组 LoRA 起个名字;用已有名字保存会覆盖它",
"Not found on Civitai": "Civitai 上没有找到",
"Output budget in megapixels (x 1024x1024).": "输出像素预算,单位百万像素(x 1024x1024)。",
"Playhead frame / last frame": "当前帧 / 最后一帧",
"Preview thumbnails": "预览缩略图",
"Preview, base model, and trigger words": "预览图、基础模型和触发词",
"Put this seed back and pin it": "恢复这个种子并固定",
"Remove all padding.": "清除所有扩边。",
"Rotation in degrees: 1° per step, Shift for 0.1°. The crop stays over the same part of the picture.": "旋转角度:每步 1°,按住 Shift 为 0.1°。裁剪框保持在画面的同一部分上。",
"Rounds each resized side to a multiple of this (32 for LTX and Wan).": "把缩放后的每条边取整为此数的倍数(LTX 和 Wan 用 32)。",
"Rows on the box": "框上的行",
"Save current as...": "另存当前为…",
"Scrub strength on the name": "在名称上拖动调节强度",
"Search LoRAs": "搜索 LoRA",
"Search LoRAs...": "搜索 LoRA…",
"Seed settings": "种子设置",
"Select every node this switch turns off and on": "选中此开关控制的所有节点",
"Select nodes or groups on the canvas first, then add them to this switch": "先在画布上选中节点或分组,再把它们加入这个开关",
"Select nodes that run only while this is off, then take them off that side. They stay as they are.": "选中只在此项关闭时才运行的节点,再把它们放到“关”的一侧。节点本身保持原样。",
"Select nodes this switch holds first, then take them out of it": "先选中此开关管理的节点,再把它们移出",
"Select the nodes only this choice needs. They are switched off while another choice is picked.": "选中只有这个选项才需要的节点。选了其他选项时,它们会被关闭。",
"Separate model / CLIP strength": "分开设置模型 / CLIP 强度",
"Set the nodes the way this choice should be, then pick this": "先把节点调成这个选项该有的样子,再选中它",
"Show the mask on the picture": "在图片上显示遮罩",
"Stop on missing LoRA": "缺少 LoRA 时停止",
"Strength bars": "强度条",
"Strength step": "强度步长",
"Linked strength wires": "强度连线显示", "shown": "显示", "on hover": "悬停时显示", "hidden": "隐藏",
"Unlink strength": "断开强度连线", "link": "连线",
"Takes 1 off after each run. Tap for Random.": "每次运行后减 1。点一下改为随机。",
"The words come from the wire.": "文字来自连线。",
"Tick to add with others": "勾选后与其他一起添加",
"Toggle this trigger word into the row's output": "把这个触发词加入或移出该行的输出",
"Trigger word separator": "触发词分隔符",
"Turn this group on or off. Each LoRA in it keeps its own switch.": "开启或关闭这个分组。组里的每个 LoRA 仍有各自的开关。",
"Untick every file": "取消勾选所有文件",
"seeds this node ran with": "此节点用过的历史种子",
"the last run delivered an empty string": "上次运行传来的是空字符串",
"Start and Ends at are places in the source video. Duration counts the frames the clip sends on, at the output rate.": "起点和终点是源视频里的位置。时长是片段送出的帧数,按输出帧率计算。",
"The frame this node outputs (frame_index).": "此节点输出的帧(frame_index)。",
"Pick a color": "选择颜色",
"Show the advanced mask controls": "显示高级遮罩控制",
"Reset rotation, crop, padding, fill, feather and Align. Keep the source, current frame, trim window, fixed length and picture.": "重置旋转、裁剪、扩边、填充、羽化和对齐。素材、当前帧、截取范围、固定长度和图片保持不变。",
"Up/Down chooses a row, Space toggles it, and Left/Right changes strength.": "上下键选择一行,空格切换开关,左右键调整强度。",
"Tint the paste mask the stitcher will use - the same mask math as the backend, at preview resolution.": "给拼回时使用的贴回遮罩上色,计算方式与后端一致,只是分辨率为预览分辨率。",
"Ramp where generated pixels fade over the source, in pixels of the output. Separate from the padding feather.": "生成的像素渐隐到原图上的过渡宽度,单位为输出像素。与扩边羽化相互独立。",
"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": "预览无法加载这张图片",
};
// 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",
"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",
]);
// The hint js/shared/scrub_input.mjs adds to every number box's tooltip.
export const SCRUB_HINT_EN = "Drag to scrub, click to type a number or a sum (1024*1.5), arrows to step; Shift = fine.";
export const SCRUB_HINT_ZH = "拖动调节,点击输入数字或算式(如 1024*1.5),方向键步进;按住 Shift 精细调节。";
// A few strings carry a number or a name; the number stays and the words around it change.
export const PATTERNS = [
[/^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}:重塑为此比例。左侧的翻转按钮用来切换横竖方向。`],
];
+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.25.2";
export const AUSBOSS_JS_VERSION = "2.26.7";
export const BRAND = "#00b4aa"; // AusBoss teal — keep node accents consistent.
export const BRAND_DARK = "#007f78";
+5 -2
View File
@@ -13,6 +13,7 @@
// what it always was. The turn is made in canvas pixels, so a turned box is a
// true rectangle on a canvas of any shape (nodes/_layout_boxes_helpers.py
// turns it the same way).
import { linkOrigin } from "./clip_rate.mjs";
export const DIM_MIN = 64;
export const DIM_MAX = 16384;
@@ -683,8 +684,10 @@ const isNumber = (value) => typeof value === "number" && Number.isFinite(value);
// (Integer, Primitive). Reroutes are followed. Null when the input is not
// wired or the value is only known once the workflow runs.
export function wiredNumber(node, inputName) {
const source = wiredSource(node, inputName);
return source ? wiredFrom(source.node, source.slot) : null;
// Through Reroutes and into subgraphs (js/shared/clip_rate.mjs), then
// this node's own rule for which numbers count.
const origin = linkOrigin(node, inputName);
return origin ? wiredFrom(origin.node, origin.slot) : null;
}
// The node (and its output slot) an input is wired to, through Reroutes.
+87
View File
@@ -0,0 +1,87 @@
// ComfyUI's missing-models list (the Issues panel, "Download all") only
// looks at list widgets: a model is listed when a list on some node holds a
// file name that is not one of its choices. LoRA Loader keeps its files in
// the rows' text, so a LoRA a workflow needs never made that list, and
// "Download all" then Run stopped on "missing LoRA file".
//
// The loader therefore carries one hidden list widget per row that needs a
// file. Nothing else reads them: they are kept out of the saved workflow and
// the prompt, have no socket, and are made again from the rows every time.
// The rows stay the one source of truth.
import { resolveLoraName } from "./lora_stack.mjs";
export const FILE_WIDGET_PREFIX = "ausboss_lora_file_";
export const FILE_WIDGET_FLAG = "ausbossLoraFile";
// Rows the server needs a file for when it runs: named, on, in a group that
// is on, and not at zero strength (nodes/_lora_helpers.py, missing_lora_rows).
export function rowsNeedingFiles(rows) {
return (Array.isArray(rows) ? rows : []).filter((row) => {
const name = typeof row?.name === "string" ? row.name.trim() : "";
if (!name || row.enabled === false || row.group_off === true) return false;
const strength = Number(row.strength ?? 1);
const clip = Number(row.strength_clip ?? strength);
return !(strength === 0 && clip === 0);
});
}
// The list ComfyUI checks a row's file against. A file the loader would
// find anyway (saved in another folder, or with other capitals) counts as
// installed; so does every file while the install's list is unknown, so a
// slow list never shows a false alarm.
export function fileChoices(name, installed) {
if (!Array.isArray(installed)) return [name];
return resolveLoraName(name, installed).status === "missing" ? installed : [...installed, name];
}
// The install's LoRA files as ComfyUI's own LoRA loader lists them. The node
// list arrives before any workflow opens, so this answers at once; null when
// there is no such node to ask.
export function coreLoraList(definition) {
const spec = definition?.input?.required?.lora_name;
if (!Array.isArray(spec)) return null;
if (Array.isArray(spec[0])) return spec[0];
if (spec[0] === "COMBO" && Array.isArray(spec[1]?.options)) return spec[1].options;
return null;
}
export function isFileWidget(widget) {
return Boolean(widget?.[FILE_WIDGET_FLAG]);
}
// Bring the node's file widgets in line with its rows. `installed()` returns
// the install's files (or null), `hide(widget)` folds a widget away, and
// `onPick(rowId, name)` runs when ComfyUI puts another file in a widget
// (choosing a replacement in the Issues panel). Returns true when a widget
// was added or removed.
export function syncFileWidgets(node, rows, { installed, hide, onPick }) {
if (!node || !Array.isArray(node.widgets)) return false;
const needed = rowsNeedingFiles(rows);
const current = node.widgets.filter(isFileWidget);
let changed = false;
needed.forEach((row, index) => {
let widget = current[index];
if (!widget) {
widget = node.addWidget("combo", `${FILE_WIDGET_PREFIX}${index + 1}`, row.name, (value) => {
if (typeof value === "string" && value !== widget.ausbossRowName) onPick?.(widget.ausbossRowId, value);
}, { values: () => fileChoices(widget.value, installed?.()), serialize: false });
widget[FILE_WIDGET_FLAG] = true;
widget.serialize = false;
hide?.(widget);
changed = true;
}
widget.value = row.name;
widget.ausbossRowName = row.name;
widget.ausbossRowId = row.id;
});
for (const widget of current.slice(needed.length)) {
if (typeof node.removeWidget === "function") node.removeWidget(widget);
else {
const at = node.widgets.indexOf(widget);
if (at >= 0) node.widgets.splice(at, 1);
}
changed = true;
}
return changed;
}
+29
View File
@@ -599,6 +599,35 @@ export function loraPickerEntries(names, query = "", collapsedFolders = new Set(
return visit(tree);
}
// Fold or open many folders at once: every folder in `folders`, or with
// `root` that folder and every folder inside it. Returns a new Set; folds
// of folders not named in `folders` are kept as they were.
export function setFolderFolds(collapsedFolders, folders, fold, root = null) {
const next = new Set([...collapsedFolders].map(loraPath));
const base = root == null ? null : loraPath(root);
for (const name of folders) {
const folder = loraPath(name);
if (base != null && folder !== base && !folder.startsWith(`${base}/`)) continue;
if (fold) next.add(folder);
else next.delete(folder);
}
return next;
}
// The folder a file or folder sits in, or null at the top of the list. The
// picker's Left key folds it and moves up to it.
export function parentFolder(name) {
const parts = loraPath(String(name ?? "")).split("/");
return parts.length > 1 ? parts.slice(0, -1).join("/") : null;
}
// The picker's fold-all control offers "Fold all" while any folder in view
// is open, and "Open all" once every folder in view is folded.
export function anyFolderOpen(entries, collapsedFolders) {
const collapsed = new Set([...collapsedFolders].map(loraPath));
return entries.some((entry) => entry.kind === "folder" && !collapsed.has(entry.name));
}
// Append the folder in one step, preserving duplicates, disabled rows and
// empty slots already in the stack. Deduplicate new files by full path.
export function appendFolderRows(rows, names, defaultStrength = 1) {
+16 -6
View File
@@ -2,7 +2,7 @@
// 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 { clipSetsDuration, linkSource } from "./h3_duration.mjs";
import { clipLengthWords, clipSetsDuration, clipTimingFor, linkSource } from "./h3_duration.mjs";
import { api } from "../../../scripts/api.js";
import { app } from "../../../scripts/app.js";
import { BRAND, chainCallback } from "./index.mjs";
@@ -38,7 +38,8 @@ function ensureCss() {
.ausboss-strip-handle::before{content:"";position:absolute;left:5px;top:5px;bottom:5px;width:2px;border-radius:1px;background:rgba(207,232,229,.35)}
.ausboss-strip-handle:hover::before,.ausboss-strip-handle.dragging::before{background:#cfe8e5}
.ausboss-strip-handle span{position:absolute;bottom:100%;left:50%;transform:translateX(-50%);padding:1px 4px;border-radius:3px;background:#cfe8e5;color:#0b0f10;font-size:9px;white-space:nowrap;display:none}
.ausboss-strip-handle.dragging span{display:block}
.ausboss-strip-handle:hover span,.ausboss-strip-handle.dragging span{display:block}
.ausboss-strip-handle.cuts::before{background:${BRAND}}
.ausboss-strip-block.movable{cursor:grab;touch-action:none}
.ausboss-strip-block.moving{z-index:3;cursor:grabbing;opacity:.85;box-shadow:0 4px 14px rgba(0,0,0,.5)}
.ausboss-strip-drop{position:absolute;top:-3px;bottom:-3px;z-index:4;width:3px;margin-left:-2px;border-radius:2px;background:#f5b53d;pointer-events:none}
@@ -108,7 +109,12 @@ export function momentStrip(node) {
const label = document.createElement("span");
handle.append(label);
handle.style.left = `${rows[index].from}%`;
handle.title = range ? "Drag to set when this moment starts. Click to add or remove a cut." : "Click to add or remove a cut.";
const isCut = Boolean(rows[index].cut);
handle.classList.toggle("cuts", isCut);
// Shown on hover: what a click does here. Dragging swaps it for the time.
const hint = isCut ? "\u2702 join" : "\u2702 cut";
label.textContent = hint;
handle.title = `${isCut ? "Click to join these two shots." : "Click to cut to a new shot here."}${range ? " Drag to set when this moment starts." : ""}`;
track.append(handle);
handle.addEventListener("pointerdown", (event) => {
if (event.button !== 0) return;
@@ -134,6 +140,7 @@ export function momentStrip(node) {
handle.removeEventListener("pointerup", stop);
handle.removeEventListener("pointercancel", stop);
handle.classList.remove("dragging");
label.textContent = hint;
if (!moved) commitScript((text) => toggleCut(text, rows[index].line));
else if (second !== null && second !== rows[index].start) commitScript((text) => retime(text, rows[index].line, second));
};
@@ -290,12 +297,15 @@ export function momentStrip(node) {
asked += 1;
ruler.textContent = "";
track.textContent = "";
const message = el("ausboss-strip-words", "Length comes from the clip");
// 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 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 = "Set the clip's length upstream. Timing controls are unavailable here.";
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.";
note.title = note.textContent;
note.classList.remove("warn");
note.classList.toggle("warn", Boolean(words?.warn));
return;
}
if (wired(node, "script")) {
+5 -4
View File
@@ -59,14 +59,15 @@ export function dragRange(rows, index, seconds) {
export function stripCaption(report) {
if (report?.warning) return { text: report.warning, warn: true };
const moments = report?.moments ?? [];
if (!moments.length) return { text: "Each line becomes a moment.", warn: false };
if (!moments.length) return { text: "Each line becomes a moment. A blank line between lines is a cut.", warn: false };
const count = moments.length === 1 ? "1 moment" : `${moments.length} moments`;
const cuts = moments.filter((moment) => moment.cut).length;
if (cuts) return { text: `${count}, ${cuts === 1 ? "1 cut" : `${cuts} cuts`}.`, warn: false };
// Say how to cut, since nothing on the bar shows it until you hover an edge.
if (cuts) return { text: `${count}, ${cuts === 1 ? "1 cut" : `${cuts} cuts`}. Click a cut on the bar to join the shots.`, warn: false };
const each = moments.map((moment) => trimmed(moment.end - moment.start));
if (moments.length === 1) return { text: `${count}, ${each[0]} s, one take.`, warn: false };
if (moments.length === 1) return { text: `${count}, ${each[0]} s, one take. Add a line for the next moment, a blank line to cut.`, warn: false };
const even = each.every((length) => length === each[0]);
return { text: even ? `${count}, ${each[0]} s each, one take.` : `${count}, one take.`, warn: false };
return { text: `${even ? `${count}, ${each[0]} s each` : count}, one take. Click between two moments to cut there.`, warn: false };
}
// The seconds the bar under the script marks: every second up to 10 s,
+10
View File
@@ -5,6 +5,11 @@
// 2.0 draws each node as an element on the page, which can run past those
// bounds (its frame, a footer), so there the element itself is measured.
// Groups are drawn on the canvas in both looks.
//
// A frameless tile (a link tile, a title, a note tile) draws only a card
// inside a transparent node, so what people see is the card, not the node's
// bounds. Such a node names that card as `ausbossOutlineElement`, and its
// outline is the card's, in both looks.
function graphRectOf(element, canvas) {
const box = element.getBoundingClientRect();
@@ -34,6 +39,11 @@ export function nodeElements() {
}
export function outlineOf(item, canvas, { node = true, elements = null } = {}) {
const face = node && !item?.flags?.collapsed ? item?.ausbossOutlineElement : null;
if (face?.isConnected && canvas?.canvas && canvas.ds) {
const rect = graphRectOf(face, canvas);
if (rect) return rect;
}
if (node && globalThis.LiteGraph?.vueNodesMode === true && item?.id != null && canvas?.canvas && canvas.ds) {
const element = elements
? elements.get(String(item.id))
+5 -4
View File
@@ -19,13 +19,14 @@ export const PAD_SIDES = ["left", "top", "right", "bottom"];
// "sub/dir\\name.png [temp]" -> { filename, subfolder, type } for a /view
// query. Handles Windows backslashes, subfolders, and the "name [type]"
// annotation ComfyUI appends outside the input folder.
// Preserves filename whitespace.
export function parseImageReference(value) {
let text = String(value ?? "").trim();
if (!text) return null;
let text = String(value ?? "");
if (!text.trim()) return null;
let type = "input";
const annotated = /^(.*)\s+\[(input|output|temp)\]$/i.exec(text);
const annotated = /^(.*) \[(input|output|temp)\]$/i.exec(text);
if (annotated) {
text = annotated[1].trim();
text = annotated[1];
type = annotated[2].toLowerCase();
}
const normalized = text.replaceAll("\\", "/");
+4 -3
View File
@@ -10,6 +10,7 @@
// writePad(side, value) write one raw pad widget (with callbacks)
// onGestureEnd() called once per completed drag
import { t } from "./i18n.mjs";
import { canvasLocalPoint } from "./transform_geometry.mjs";
import {
edgeCursor,
@@ -86,7 +87,7 @@ function drawPill(ctx, text, cx, cy, accent = false) {
ctx.fillStyle = accent ? "#8de0da" : "#e7f4f2";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(text, cx, cy + 0.5);
ctx.fillText(t(text), cx, cy + 0.5);
ctx.restore();
return width;
}
@@ -99,7 +100,7 @@ function drawBandText(ctx, text, cx, cy) {
ctx.shadowColor = "rgba(0,0,0,0.9)";
ctx.shadowBlur = 3;
ctx.fillStyle = "#ffe2c2";
ctx.fillText(text, cx, cy);
ctx.fillText(t(text), cx, cy);
ctx.restore();
}
@@ -247,7 +248,7 @@ export function createPadStage(canvas, options) {
ctx.shadowColor = "rgba(0,0,0,0.85)";
ctx.shadowBlur = 4;
ctx.fillStyle = "#78908e";
ctx.fillText(source.emptyText, w / 2, h / 2);
ctx.fillText(t(source.emptyText), w / 2, h / 2);
ctx.restore();
}
+13
View File
@@ -136,6 +136,19 @@ export function seeThroughMap(rgba) {
return map;
}
// Some browsers and privacy add-ons hand back blank or made-up pixels when a
// page reads a canvas (Firefox's fingerprint protection, canvas blockers).
// Blank pixels read as a fully see-through picture, so the stage would draw
// nothing. PIXEL_PROBE is painted on a small canvas and read back; the read
// is trusted only when it comes back solid and close to what was painted
// (small colour noise, as Brave adds, is fine: only alpha decides here).
export const PIXEL_PROBE = [[255, 0, 0], [0, 0, 255]];
export function pixelReadTrusted(rgba) {
if (!rgba || rgba.length < PIXEL_PROBE.length * 4) return false;
return PIXEL_PROBE.every((color, p) =>
rgba[p * 4 + 3] === 255 && color.every((channel, c) => Math.abs(rgba[p * 4 + c] - channel) <= 16));
}
// Work-resolution planning for the overlay. Blend and grow are output
// pixels AFTER any resize; the stage draws the pre-resize canvas. One
// output pixel is `unit` work pixels (the two axes can differ by a step
+1
View File
@@ -50,6 +50,7 @@ export function isBlendIn(values) {
// Hover hints on the rows blend in does not read.
export const SEAM_MUTE_TITLES = {
fix_edge_halo: "Blend in doesn't use Fix edge halo. Switch Seam back to classic in the gear menu to use it.",
follow_changes: "Blend in doesn't use Follow changes. Switch Seam back to classic in the gear menu to use it.",
};
// Room the corner tools take from every row's control, so the controls keep
+10
View File
@@ -28,11 +28,15 @@ export function setTileFace(node, root, enabled, onEdit) {
});
}
const listeners = new AbortController();
// Snap into line and Line up use the card people see, not the
// transparent node around it (js/shared/outline.mjs).
node.ausbossOutlineElement = root.querySelector(".ausboss-callout-card,.ausboss-note-card") || root;
installTileDrag(node, root, listeners.signal, onEdit);
installTileResize(node, root, listeners.signal);
originalDescriptors.set(node, { descriptors, listeners });
} else {
previous.listeners.abort();
delete node.ausbossOutlineElement;
for (const [key, descriptor] of previous.descriptors) {
if (descriptor) Object.defineProperty(node, key, descriptor);
else delete node[key];
@@ -44,6 +48,9 @@ export function setTileFace(node, root, enabled, onEdit) {
function skipBadges() {}
// Sent from a tile's own drag after each move: js/snap_lines/ lines it up.
export const TILE_MOVE = "ausboss-tile-move";
// A normal node moves by its header. Give the tile that gesture while
// keeping a short click on a link or the info button as its usual action.
function installTileDrag(node, root, signal, onEdit) {
@@ -87,6 +94,9 @@ function installTileDrag(node, root, signal, onEdit) {
for (const start of press.starts) start.item.pos = [start.x + dx / zoom, start.y + dy / zoom];
node.setDirtyCanvas?.(true, true);
event.stopPropagation();
// The move stops here (Nodes 2.0 would pan the canvas with it), so tell
// Snap into line separately, after the tile has been placed.
root.dispatchEvent(new CustomEvent(TILE_MOVE, { bubbles: true, detail: event }));
}, capture);
const finish = (event) => {
if (event.pointerId !== press?.id) return;
+29 -1
View File
@@ -273,7 +273,14 @@ export function clipLengthPlan(info, values = {}) {
latestStart = clamp(Math.floor((end - lastTick - TRIM_EPSILON) * info.fps), 0, endFrame);
}
}
if (values.resampled) return { ...base, last: cap > 0 ? null : window.last, requested, latestStart };
if (values.resampled) {
// A known output rate places every output frame: the backend samples
// and holds on ticks at start + k / rate (decode_video_range), so the
// count, the last source frame shown and the end are all known here.
if (!(values.outputFps > 0) || !(info.fps > 0)) return { ...base, last: cap > 0 ? null : window.last, requested, latestStart };
const resampled = resampledFrames(info, values, nth, requested, snap);
return { ...base, ...resampled, requested, latestStart, truncated: requested != null && resampled.frames < requested };
}
const kept = keptFrames(window, nth, cap, snap);
return { ...base, last: kept.lastKept, frames: kept.frames, requested, latestStart, truncated: requested != null && kept.frames < requested };
};
@@ -288,6 +295,27 @@ export function clipLengthPlan(info, values = {}) {
return capped(mode === "length" ? stored : 0);
}
// Output frames of a run that resamples to a known rate: ticks at
// start + k / tickRate while before the end, thinned by every nth, capped,
// then snapped. `last` is the source frame the final tick holds.
export function resampledFrames(info, values, everyNth = 1, cap = null, snap = "free") {
const nth = Math.max(1, Math.floor(finite(everyNth, 1)) || 1);
const tickRate = finite(values.outputFps) * nth;
const duration = info.duration || info.count / info.fps;
const start = Math.max(0, finite(values.start));
const end = finite(values.end) > 0 ? Math.min(finite(values.end), duration) : duration;
const ticks = Math.max(0, Math.ceil((end - start) * tickRate - TRIM_EPSILON));
let frames = Math.ceil(ticks / nth);
if (cap != null && cap > 0) frames = Math.min(frames, cap);
frames = snapFrameCount(frames, snap);
const first = frameWindow(info, start, values.end).first;
const lastTime = start + Math.max(0, frames - 1) * nth / tickRate;
const last = clamp(Math.floor(lastTime * info.fps + TRIM_EPSILON), first, info.count - 1);
const windowLast = frameWindow(info, start, values.end).last;
// The last frame is held for one output frame, but never past the video.
return { first, last, windowLast, frames, endSeconds: Math.min(end, start + frames / finite(values.outputFps)) };
}
// Playback rate for a label, trimmed of float noise: 24 -> "24",
// 23.976023... -> "23.976".
export function formatFps(value) {
+40
View File
@@ -0,0 +1,40 @@
// Small pieces every timing card shares (the clip node, Load Video, Load
// Audio): the seconds | frames choice and the "linked" button that goes to
// the node feeding a value.
import { app } from "../../../scripts/app.js";
// Seconds or frames on a timing card: a per-browser choice, like a view
// setting. It never changes a stored value.
const UNITS_KEY = "AusBoss.ClipTiming.Units";
let unitsCache = null;
export function timingUnits(next) {
if (next === "s" || next === "f") {
unitsCache = next;
try { localStorage.setItem(UNITS_KEY, next); } catch { /* private window */ }
return next;
}
if (unitsCache) return unitsCache;
try { unitsCache = localStorage.getItem(UNITS_KEY) === "f" ? "f" : "s"; } catch { unitsCache = "s"; }
return unitsCache;
}
// The node feeding a linked input, by its title, with a way to go to it.
export function linkedNodeInfo(node, name) {
const slot = node.inputs?.find((input) => input?.name === name || input?.widget?.name === name);
if (slot?.link == null) return null;
const graph = node.graph;
const link = graph?.links?.get?.(slot.link) ?? graph?.links?.[slot.link] ?? graph?._links?.get?.(slot.link);
const source = graph?.getNodeById?.(link?.origin_id);
if (!source) return { title: "the subgraph's input", go: null };
const title = source.title || source.type || "another node";
return {
title,
go: () => {
try {
app.canvas?.selectNode?.(source);
app.canvas?.centerOnNode?.(source);
app.canvas?.setDirty?.(true, true);
} catch { /* an older canvas */ }
},
};
}
+104 -8
View File
@@ -1,5 +1,6 @@
import { api } from "../../../scripts/api.js";
import { app } from "../../../scripts/app.js";
import { linkedNodeInfo, timingUnits as clipUnits } from "./timing_links.mjs";
import { PANEL_LABELS } from "./panel_controls.mjs";
import { hideInputsInDef, hideWidget } from "./widget_visibility.mjs";
import { mountTransformTrim } from "./transform_trim.mjs";
@@ -10,9 +11,10 @@ import { mediaViewQuery, unlistedMedia } from "./media_list.mjs";
import { createMediaPicker } from "./media_picker.mjs";
import { normalizeFillColor } from "./fill_color.mjs";
import { makeSlideSwitch } from "./slide_switch.mjs";
import { t } from "./i18n.mjs";
import { makeScrubInput } from "./scrub_input.mjs";
import { confirmDiscard } from "./discard_prompt.mjs";
import { featherGeneratedMask, generatedAreaMask, overlayPlan, seeThroughMap, stitchBlendFromMask } from "./stitch_preview.mjs";
import { PIXEL_PROBE, featherGeneratedMask, generatedAreaMask, overlayPlan, pixelReadTrusted, seeThroughMap, stitchBlendFromMask } from "./stitch_preview.mjs";
import { suppressCoreVideoPreview } from "./core_preview.mjs";
import { gearIconSvg, loadSettings, openSettingsMenu } from "./settings_menu.mjs";
import { createSettle } from "./settle.mjs";
@@ -81,6 +83,7 @@ import {
} from "./transform_geometry.mjs";
import { clampFrame, clipInfo, frameTime } from "./timeline_math.mjs";
import { liftSocket } from "./widget_card.mjs";
import { COPY_EDITS_SETTING, copyPicture, transformPicture } from "./transform_picture.mjs";
const HIDDEN_WIDGETS = [
"image", "upload",
@@ -103,11 +106,10 @@ const trimInputDriven = (node, name) => node.inputs?.some(
const RESIZE_METHODS = ["lanczos", "area", "bicubic", "bilinear", "nearest-exact"];
// The widest the control rows get on a big node; the picture takes the rest.
const CONTROL_MAX_WIDTH = 460;
const TRANSFORM_DEFAULTS = resetTransformValues(false);
const CORE_IMAGE_PREVIEW_WIDGET = "$$canvas-image-preview";
// The gear on the image node's source card. Display choices only, kept for
// The gear on the image node's source card. Browser preferences, kept for
// every image node on this browser (settings_menu.mjs stores them).
const SETTINGS_SCOPE = "image_crop_rotate_pad";
const SETTINGS_SCHEMA = [
@@ -115,6 +117,7 @@ const SETTINGS_SCHEMA = [
key: "show_mask", label: "Show the mask on the picture", type: "toggle", default: true,
hint: "Teal over the parts of your picture the model paints: a mask drawn in the MaskEditor, or see-through parts of a PNG.",
},
COPY_EDITS_SETTING,
];
let transformSettings = null;
function settings() {
@@ -150,7 +153,7 @@ function installStyles() {
style.id = "ausboss-transform-styles";
style.textContent = `
.ausboss-transform-panel{display:flex;flex-direction:column;gap:8px;padding:8px;color:#ddd;font:12px system-ui;box-sizing:border-box;width:100%;height:100%;overflow:hidden}
.ausboss-transform-panel>:not(.ausboss-transform-preview){width:100%;max-width:${CONTROL_MAX_WIDTH}px;align-self:center;box-sizing:border-box}
.ausboss-transform-panel>:not(.ausboss-transform-preview){width:100%;align-self:stretch;box-sizing:border-box}
.ausboss-transform-preview{width:100%;flex:1 1 180px;min-height:0;border:1px solid #50555b;border-radius:8px;background:#111;display:block;touch-action:none}
.ausboss-transform-source{display:flex;flex-direction:column;gap:7px;flex:0 0 auto;padding:8px;border:1px solid rgba(0,184,174,.28);border-radius:8px;background:rgba(0,0,0,.24)}
.ausboss-transform-source-image{display:grid;grid-template-columns:minmax(0,1fr) auto;align-items:center}
@@ -189,13 +192,14 @@ function installStyles() {
.ausboss-transform-group-meta{min-width:0;overflow:hidden;text-overflow:ellipsis}
.ausboss-transform-group-body{display:flex;flex-direction:column;gap:7px;padding:8px;box-sizing:border-box}
.ausboss-transform-group-body[hidden]{display:none}
.ausboss-transform-readout{flex:0 0 auto;margin-top:-3px;color:#c9d0d6;font:11px/14px system-ui;font-variant-numeric:tabular-nums;text-align:center;overflow:hidden;cursor:default;user-select:none}
.ausboss-transform-readout{flex:0 0 auto;margin:-5px 0 -3px;color:#c9d0d6;font:11px/14px system-ui;font-variant-numeric:tabular-nums;text-align:center;overflow:hidden;cursor:default;user-select:none}
.ausboss-transform-readout:empty{display:none}
.ausboss-transform-readout span{color:#8ca8a5}.ausboss-transform-readout b{color:#fff;font-weight:600}
.ausboss-transform-readout>div,.ausboss-transform-readout i{display:flex;align-items:center;justify-content:center;gap:3px;height:14px;white-space:nowrap}
.ausboss-transform-readout .ausboss-transform-ellipsis{min-width:0;overflow:hidden;text-overflow:ellipsis;color:inherit}
.ausboss-transform-readout b,.ausboss-transform-readout button{flex:none}
.ausboss-transform-readout i{color:#ffc46b;font-style:normal}
.ausboss-transform-readout i:empty{display:none}
.ausboss-transform-readout em{color:#8ca8a5;font-style:normal}
.ausboss-transform-readout em.note.ausboss-transform-ellipsis{color:#ffc46b}
.ausboss-transform-readout button{margin:0 0 0 6px;height:14px;padding:0 6px;border:1px solid #6b5a33;border-radius:3px;background:#2a2417;color:#ffd79a;font:600 9.5px/12px system-ui;cursor:pointer;vertical-align:top}
@@ -1048,7 +1052,7 @@ function buildAspectChipRow(state) {
caption.textContent = untouched ? "Source" : "Custom";
caption.title = `${untouched ? "The picture's own shape" : "No ratio button has this shape"}: ${canvas.width}×${canvas.height} (${ratioLabel(canvas.width, canvas.height)}). Tap a ratio to use one.`;
}
caption.classList.toggle("generic", caption.textContent === "Ratio");
caption.classList.toggle("generic", !held && Boolean(request || !picture));
caption.classList.toggle("custom", Boolean(picture && !request && !untouched && !held));
caption.classList.toggle("held", held);
for (const { chip, aspect } of chips) {
@@ -2320,6 +2324,11 @@ function buildTrim(state) {
onTogglePlayback: () => timelineCommand(state, "play"),
onSeek: (frame, settled) => scrubTo(state, frame, settled),
onCommit: notifyAusbossChange,
linkInfo: (name) => linkedNodeInfo(state.node, name),
// H3 Prompt Writer reads this to say what H3 makes of the clip.
publish: (timing) => { state.node.__ausbossClipTiming = timing; },
units: () => clipUnits(),
setUnits: (next) => { clipUnits(next); for (const view of state.trimViews) view.sync(); },
});
state.trimViews.add(control);
return control.root;
@@ -2340,6 +2349,7 @@ function setPlayhead(state, index) {
// also snaps the widgets to the decoded frame.
function scrubTo(state, index, settled) {
if (state.playing) stopPlayback(state, false);
state.pausedAt = null;
const frame = setPlayhead(state, index);
syncTimelineRange(state);
if (settled) { void seekFrame(state); return; }
@@ -2400,7 +2410,11 @@ function startPlayback(state) {
const trim = [...state.trimViews][0];
const { first, last } = trim.window();
const head = clampFrame(value(state.node, "frame_index", 0), info);
let next = head < first || head >= last ? first : head + 1;
// Play shows the clip from its start, so what plays is what the run
// keeps; only a resume right after a pause inside the clip carries on.
const resume = state.pausedAt != null && state.pausedAt === head && head >= first && head < last;
let next = resume ? head + 1 : first;
state.pausedAt = null;
state.playing = true;
syncTimelineRange(state);
const session = ++state.playbackSession;
@@ -2421,6 +2435,7 @@ function startPlayback(state) {
function stopPlayback(state, settle = true) {
const wasPlaying = Boolean(state.playing);
state.playing = false;
if (wasPlaying) state.pausedAt = clampFrame(value(state.node, "frame_index", 0), clipInfo(state.metadata));
state.playbackSession = (state.playbackSession || 0) + 1; // orphan in-flight ticks
if (state.playbackTimer) clearTimeout(state.playbackTimer);
state.playbackTimer = null;
@@ -2849,6 +2864,9 @@ function maskLayer(state) {
if (state.seeThrough?.image === state.image) return state.seeThrough.layer;
let layer = null;
try {
// A browser that blanks pixel reads would make the whole picture look
// see-through: draw it as it is instead.
if (!canReadPixels()) throw new Error("pixel reads are blocked");
const k = Math.min(1, MASK_LAYER_SIDE / Math.max(state.sourceWidth, state.sourceHeight));
const width = Math.max(1, Math.round(state.sourceWidth * k));
const height = Math.max(1, Math.round(state.sourceHeight * k));
@@ -2876,6 +2894,22 @@ function maskLayer(state) {
return layer;
}
// Whether this browser hands back the pixels a canvas holds (pixelReadTrusted).
// Asked once per page.
let pixelReadsWork = null;
function canReadPixels() {
if (pixelReadsWork !== null) return pixelReadsWork;
try {
const probe = document.createElement("canvas"); probe.width = PIXEL_PROBE.length; probe.height = 1;
const context = probe.getContext("2d");
PIXEL_PROBE.forEach(([r, g, b], x) => { context.fillStyle = `rgb(${r},${g},${b})`; context.fillRect(x, 0, 1, 1); });
pixelReadsWork = pixelReadTrusted(context.getImageData(0, 0, PIXEL_PROBE.length, 1).data);
} catch {
pixelReadsWork = false;
}
return pixelReadsWork;
}
// White where the tint is, for Show blend's raster.
function maskStencil(layer) {
if (!layer.stencil) {
@@ -3094,6 +3128,68 @@ function drawRotateGlyph(context, x, y, radius, color) {
// node itself can still drag, and pointercancel plus mouseleave both end a
// gesture in case the capture was refused.
function attachStageHandlers(state, canvas, signal) {
if (state.kind === "image") {
canvas.addEventListener("contextmenu", (event) => {
event.preventDefault(); event.stopPropagation();
if (!state.image) return;
const picture = async () => {
let source = state.image;
const sourceWidth = state.sourceWidth, sourceHeight = state.sourceHeight;
const current = values(state.node), resize = resizeRequest(state.node);
const includeEdits = settings().copy_edits;
if (includeEdits && maskLayer(state)) {
if (value(state.node, "painted_area", "fill") === "keep picture") {
// The browser loses colours under fully transparent pixels. Core's
// RGB view restores the stored picture under MaskEditor strokes.
source = new Image();
source.src = api.apiURL(`/view?${mediaViewQuery(value(state.node, "image", ""))}&channel=rgb`);
await source.decode();
} else {
// The stage's mask layer is capped at 2048px. Copy from the source
// at full size, using the same rule for which pixels stay picture.
const full = document.createElement("canvas");
full.width = sourceWidth; full.height = sourceHeight;
const context = full.getContext("2d");
context.drawImage(source, 0, 0);
const pixels = context.getImageData(0, 0, full.width, full.height);
const map = seeThroughMap(pixels.data);
if (map) for (let i = 0; i < map.length; i++) pixels.data[i * 4 + 3] = map[i] ? 0 : 255;
context.putImageData(pixels, 0, 0);
source = full;
}
}
return transformPicture({
sourceWidth, sourceHeight, values: current, resize, includeEdits,
fill: normalizeColor(current.fill_color),
drawSource: (context) => context.drawImage(source, -sourceWidth / 2, -sourceHeight / 2, sourceWidth, sourceHeight),
});
};
const report = (error) => showToast({ severity: "error", summary: "Copy image", detail: error?.message ?? String(error) });
new globalThis.LiteGraph.ContextMenu([
{ content: "Copy image", callback: () => {
try {
Promise.resolve(copyPicture(picture)).then(
() => showToast({ summary: "Copy image", severity: "success", detail: "The picture is on the clipboard." }), report,
);
} catch (error) { report(error); }
} },
{ content: "Open image", callback: async () => {
try {
// A real image retains the browser's native Copy image on plain
// HTTP too. A data URL stays usable for as long as the tab is open.
const tab = window.open("about:blank", "_blank");
if (!tab) throw new Error("Allow pop-ups to open the picture.");
tab.opener = null;
const image = tab.document.createElement("img");
image.src = (await picture()).toDataURL("image/png");
image.style.maxWidth = "100%";
tab.document.title = "Crop image — right-click to copy";
tab.document.body.append(image);
} catch (error) { report(error); }
} },
], { event });
}, { signal });
}
canvas.addEventListener("pointerdown", (event) => pointerDown(state, canvas, event), { signal });
canvas.addEventListener("pointermove", (event) => pointerMove(state, canvas, event), { signal });
canvas.addEventListener("pointerup", (event) => pointerUp(state, canvas, event), { signal });
@@ -3331,7 +3427,7 @@ function sizeLines(state) {
return lines;
}
function drawEmpty(state, text) { state.render = null; state.panelRender = null; syncReadout(state); for (const canvas of [state.canvas, state.previewCanvas]) { if (!canvas) continue; const prepared = prepareCanvas(canvas); drawEmptyCanvas(prepared.context, prepared.width, prepared.height, text); } }
function drawEmptyCanvas(context, width, height, text) { context.fillStyle = "#111"; context.fillRect(0, 0, width, height); context.fillStyle = "#9ba2aa"; context.font = "13px system-ui"; context.textAlign = "center"; context.fillText(text, width / 2, height / 2); context.textAlign = "left"; }
function drawEmptyCanvas(context, width, height, text) { context.fillStyle = "#111"; context.fillRect(0, 0, width, height); context.fillStyle = "#9ba2aa"; context.font = "13px system-ui"; context.textAlign = "center"; context.fillText(t(text), width / 2, height / 2); context.textAlign = "left"; }
// True when the node is an AusBoss transform node whose editor can open
// (installed by installTransformNode). Used by the pack-wide command.
+54
View File
@@ -0,0 +1,54 @@
import { keptCrop, resolveCrop, resolvePadding, rotatedSize, scaleToMegapixels } from "./transform_geometry.mjs";
export const COPY_EDITS_SETTING = Object.freeze({
key: "copy_edits", label: "Copy with crop, rotation and padding", type: "toggle", default: false,
hint: "Off: copy the original picture. On: include crop, rotation, padding and resize. Handles and guides are never copied.",
});
// Render picture pixels into a separate canvas. The editor's canvas contains
// handles, hatching and stage margins and must never be a clipboard source.
export function transformPicture({ sourceWidth, sourceHeight, values, resize, fill, drawSource, includeEdits = false, createCanvas = () => document.createElement("canvas") }) {
const canvas = createCanvas();
if (!includeEdits) {
canvas.width = sourceWidth; canvas.height = sourceHeight;
const context = canvas.getContext("2d");
if (!context) throw new Error("The browser could not make the picture.");
context.translate(sourceWidth / 2, sourceHeight / 2);
drawSource(context);
return canvas;
}
const source = rotatedSize(sourceWidth, sourceHeight, values.rotation_degrees);
const whole = resolveCrop(values, source);
const padding = resolvePadding(values, whole);
const crop = keptCrop(whole, padding);
const size = resize
? scaleToMegapixels(padding.outputWidth, padding.outputHeight, resize.megapixels, resize.steps)
: { width: padding.outputWidth, height: padding.outputHeight };
canvas.width = size.width; canvas.height = size.height;
const context = canvas.getContext("2d");
if (!context) throw new Error("The browser could not make the picture.");
context.fillStyle = fill;
context.fillRect(0, 0, canvas.width, canvas.height);
context.save();
context.scale(size.width / padding.outputWidth, size.height / padding.outputHeight);
context.beginPath();
context.rect(padding.left, padding.top, crop.width, crop.height);
context.clip();
context.translate(padding.left - crop.x + source.width / 2, padding.top - crop.y + source.height / 2);
context.rotate((Number(values.rotation_degrees) || 0) * Math.PI / 180);
drawSource(context);
context.restore();
return canvas;
}
// Start the clipboard write in the click's activation, including in browsers
// that require a promised PNG rather than a write after toBlob has finished.
export function copyPicture(picture, { clipboard = globalThis.navigator?.clipboard, ClipboardItem = globalThis.ClipboardItem } = {}) {
if (!clipboard?.write || !ClipboardItem) throw new Error("Open ComfyUI on localhost or HTTPS to copy directly. Choose Open image, then right-click the picture to copy it instead.");
const png = Promise.resolve().then(() => typeof picture === "function" ? picture() : picture).then((canvas) => new Promise((resolve, reject) => {
canvas.toBlob((blob) => blob ? resolve(blob) : reject(new Error("The browser could not make the picture.")), "image/png");
}));
// Also observe encoding failure when write() is refused before it reads png.
png.catch(() => {});
return clipboard.write([new ClipboardItem({ "image/png": png })]);
}
+389 -169
View File
@@ -41,7 +41,7 @@ import {
windowSeconds,
} from "./timeline_math.mjs";
const CSS_ID = "ausboss-transform-trim-css-v4";
const CSS_ID = "ausboss-transform-trim-css-v5";
const HANDLE_HIT_PX = 9;
// Connected inputs that set the length themselves, in the backend's order of
// precedence: fixed_frames replaces the window, a cap replaces the Length.
@@ -101,6 +101,25 @@ function installCss() {
.ausboss-transform-trim-reset{flex:none;height:18px;box-sizing:border-box;border:1px solid #2c4d4b;border-radius:4px;background:#1b2627;color:#cadddb;font:600 10px/16px system-ui;cursor:pointer;padding:0 8px;white-space:nowrap}
.ausboss-transform-trim-reset:hover{border-color:#8fa3a1;color:#fff}
.ausboss-transform-trim-reset:disabled{opacity:.45;cursor:not-allowed}
.ausboss-transform-trim-span.is-room{background:repeating-linear-gradient(90deg,rgba(0,180,170,.38) 0 6px,rgba(0,180,170,.1) 6px 12px)}
.ausboss-transform-trim-line .ausboss-transform-trim-readout{text-align:left}
.ausboss-transform-trim-inside{color:#45d6cb}
.ausboss-transform-trim-outside{color:#8ca8a5}
.ausboss-transform-trim-clip{flex:1 1 0;min-width:0;color:#45d6cb;font-weight:600;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;font-variant-numeric:tabular-nums}
.ausboss-transform-trim-fields{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:8px;min-width:0}
.ausboss-transform-trim-field{display:flex;flex-direction:column;gap:3px;min-width:0}
.ausboss-transform-trim-field .ausboss-scrub{width:100%;box-sizing:border-box}
.ausboss-transform-trim-field-label{color:#cadddb;display:flex;align-items:center;gap:6px;min-width:0}
.ausboss-transform-trim-go[hidden]{display:none}
.ausboss-transform-trim-sub{color:#8ca8a5;font-size:10px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;font-variant-numeric:tabular-nums;min-height:12px}
.ausboss-transform-trim-link{color:#9fe3dc;font-size:10px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.ausboss-transform-trim-link[hidden]{display:none}
.ausboss-transform-trim-go{border:0;background:transparent;padding:0;color:#45d6cb;font:600 10px system-ui;text-decoration:underline;cursor:pointer}
.ausboss-transform-trim-note{display:flex;align-items:center;gap:6px;flex-wrap:wrap;color:#9fe3dc;font-size:11px;line-height:1.35}
.ausboss-transform-trim-note[hidden]{display:none}
.ausboss-transform-trim-note>span{flex:1 1 180px;min-width:0}
.ausboss-transform-trim-note.warn{background:#3a2a10;box-shadow:inset 3px 0 0 #e0a040;border-radius:6px;padding:6px 8px;color:#ffdca8}
.ausboss-transform-trim-note button[hidden]{display:none}
`;
document.head.append(style);
}
@@ -113,6 +132,8 @@ function el(tag, className = "", text = "") {
}
const pct = (fraction) => `${(fraction * 100).toFixed(3)}%`;
// Seconds for people: at most two decimals (1, 1.5, 2.17).
const secondsText = (value) => String(Number((Number(value) || 0).toFixed(2)));
// options:
// get(name, fallback) / set(name, value) widget access
@@ -126,7 +147,12 @@ const pct = (fraction) => `${(fraction * 100).toFixed(3)}%`;
// (the clip node) or playhead only
// onSeek(frame, settled) the playhead moved; settled on release
// onCommit() a stored value settled (undo point)
export function mountTransformTrim({ get, set, has = () => true, driven = () => false, number = (name, fallback) => get(name, fallback), outputRate, metadata, trim = true, isPlaying, onTogglePlayback, onSeek, onCommit }) {
// linkInfo(name) {title, go()} of the node feeding
// a linked input, or null
// publish(timing) the clip's {frames, startSeconds,
// endSeconds, roomFrames}, or null
// units() / setUnits(units) "s" (seconds) or "f" (frames)
export function mountTransformTrim({ get, set, has = () => true, driven = () => false, number = (name, fallback) => get(name, fallback), outputRate, metadata, trim = true, isPlaying, onTogglePlayback, onSeek, onCommit, linkInfo = () => null, publish, units: getUnits = () => "s", setUnits = () => {}, play: showPlay = true }) {
installCss();
const root = el("div", "ausboss-transform-trim");
const rail = el("div", "ausboss-transform-trim-rail");
@@ -144,7 +170,9 @@ export function mountTransformTrim({ get, set, has = () => true, driven = () =>
const play = el("button", "ausboss-transform-trim-play");
play.type = "button";
play.addEventListener("click", onTogglePlayback);
transport.append(play, rail);
// A host with its own player (Load Video) leaves out the Play button.
if (showPlay) transport.append(play);
transport.append(rail);
const info = () => clipInfo(metadata());
const everyNth = () => Math.max(1, Math.trunc(Number(number("every_nth", get("every_nth", 1))) || 1));
const snapRule = () => String(get("frame_snap", "free"));
@@ -160,11 +188,10 @@ export function mountTransformTrim({ get, set, has = () => true, driven = () =>
return number(name, get(name, 0)) ?? get(name, 0);
};
const countAtRunTime = () => COUNT_INPUTS.some((name) => driven(name) && number(name, null) == null);
const plan = () => {
if (!trim) return null;
const clip = info();
const outFps = () => (outputRate ? outputRate() : info().fps / everyNth());
const planValues = () => {
const wired = wiredBy();
return clipLengthPlan(clip, {
return {
start: boundSeconds("start"),
end: boundSeconds("end"),
everyNth: everyNth(),
@@ -173,9 +200,48 @@ export function mountTransformTrim({ get, set, has = () => true, driven = () =>
fixedFrames: driven("fixed_frames") ? 0 : get("fixed_frames", 0),
wired,
wiredFrames: wired ? number(wired, null) : null,
outputFps: outputRate ? outputRate() : clip.fps,
outputFps: outputRate ? outputRate() : info().fps,
resampled: driven("force_rate"),
});
};
};
const plan = () => (trim ? clipLengthPlan(info(), planValues()) : null);
// Output frames that fit between IN and the end of the video: the most a
// Duration can be from here.
const roomFrames = () => {
if (!trim) return null;
const room = clipLengthPlan(info(), { ...planValues(), maxFrames: 0, fixedFrames: 0, wired: null, wiredFrames: null });
return room.frames ?? null;
};
// Where the clip ends, in source seconds (exclusive), when it is known.
const endSecondsOf = (current) => {
const clip = info();
if (current?.endSeconds != null) return current.endSeconds;
if (current?.last == null || !clip.fps) return null;
return (current.last + 1) / clip.fps;
};
const endDriven = () => driven("end_frame") || driven("end_seconds");
// The latest IN that keeps the whole Duration. With a connected rate the
// count is in output frames, so the source grid would stop IN far too soon
// (the 2.25 face stopped a 240-frame Length at IN 7 on a 247-frame clip).
const latestIn = (current) => {
const clip = info();
if (driven("force_rate")) {
if (current.latestStart == null) return clip.count - 1;
return current.latestStart > 0 ? current.latestStart : clip.count - 1;
}
return latestInFor(clip, current.requested ?? get("max_frames", 1), everyNth());
};
// A Duration as long as the whole video only caps it: IN moves freely and
// the clip runs to the end.
const durationFills = (current) => {
if (current.mode !== "length" || current.requested == null) return false;
const whole = roomFromStart();
return whole != null && current.requested >= whole;
};
const roomFromStart = () => {
if (!trim) return null;
const room = clipLengthPlan(info(), { ...planValues(), start: 0, maxFrames: 0, fixedFrames: 0, wired: null, wiredFrames: null });
return room.frames ?? null;
};
const currentWindow = () => {
const clip = info();
@@ -185,7 +251,8 @@ export function mountTransformTrim({ get, set, has = () => true, driven = () =>
};
const playheadFrame = () => clampFrame(get("frame_index", 0), info());
const controls = {};
let syncLength = () => {};
// A short line under the fields after a drag stops at the video's end.
let stopNote = "";
// IN is locked by a connected bound; OUT by a connected bound in free
// trim, and always when a connected input sets the length.
const locked = (edge) => {
@@ -196,10 +263,10 @@ export function mountTransformTrim({ get, set, has = () => true, driven = () =>
return false;
};
const lockTip = (edge) => edge === "start"
? "The starting frame is supplied by a connected input. Disconnect it to edit IN here."
? "The starting frame is supplied by a connected input. Disconnect it to set Start here."
: wiredBy()
? `The connected ${wiredBy()} input sets the length, so the clip ends where it says. Disconnect it to use OUT or Length.`
: "The ending frame is supplied by a connected input. Disconnect it to edit OUT here.";
? `The connected ${wiredBy()} input sets the length, so the clip ends where it says. Disconnect it to set Duration or Ends at here.`
: "The ending frame is supplied by a connected input. Disconnect it to set Ends at here.";
const disableControl = (control, disabled, tip) => {
if (!control) return;
control.root.style.opacity = disabled ? ".45" : "";
@@ -217,7 +284,16 @@ export function mountTransformTrim({ get, set, has = () => true, driven = () =>
const writeEnd = (first, last) => set("end_seconds", windowSeconds(info(), first, last).end_seconds);
// An older face's Fixed frames reads as a Length; the first edit makes it
// one, keeping the window where the fixed count had placed it.
// The face has no modes: a clip is a Start and a Duration. A window saved
// as IN -> OUT (Length off) becomes a Duration of the same frames on its
// first edit, so the run outputs exactly what it did. A connected end
// keeps the window as it is.
const adoptLength = (current) => {
if (current.mode === "free" && !endDriven() && current.frames != null) {
set("max_frames", Math.max(1, current.frames));
set("end_seconds", 0);
return plan();
}
if (current.mode !== "fixed") return current;
set("fixed_frames", 0);
set("max_frames", Math.max(1, current.requested ?? current.frames ?? 1));
@@ -235,9 +311,14 @@ export function mountTransformTrim({ get, set, has = () => true, driven = () =>
let parked;
if (edge === "start") {
if (current.mode === "length") {
// A Length drags the whole window, stopping where OUT meets the end;
// a Length past the clip's end only caps it, so IN moves freely.
parked = Math.max(0, Math.min(clampFrame(frame, clip), latestInFor(clip, current.requested ?? get("max_frames", 1), nth)));
// A Duration drags the whole clip, stopping where its end meets the
// video's end; a Duration past the video's end only caps it, so IN
// moves freely.
const latest = latestIn(current);
parked = Math.max(0, Math.min(clampFrame(frame, clip), latest));
stopNote = clampFrame(frame, clip) > latest
? `Start stops at ${secondsText(parked / clip.fps)} s so all ${current.requested} frames fit.`
: "";
set("end_seconds", 0);
} else if (current.mode === "wired" && current.latestStart != null && !countAtRunTime()) {
parked = Math.min(clampFrame(frame, clip), current.latestStart);
@@ -247,11 +328,18 @@ export function mountTransformTrim({ get, set, has = () => true, driven = () =>
writeStart(parked);
} else {
const target = Math.max(current.first, clampFrame(frame, clip));
const frames = framesThrough(current.first, target, nth, snapRule());
stopNote = "";
let frames = framesThrough(current.first, target, nth, snapRule());
if (driven("force_rate") && outFps() > 0) {
// Output frames at the linked rate from IN to the handle's boundary.
frames = snapToValid(Math.max(1, Math.round(((target + 1) / clip.fps - boundSeconds("start")) * outFps())), snapRule());
const room = roomFrames();
if (room != null) frames = Math.min(frames, Math.max(1, room));
}
if (current.mode === "length") {
set("max_frames", frames);
set("end_seconds", 0);
parked = Math.min(clip.count - 1, lastFrameFor(current.first, frames, nth));
parked = plan()?.last ?? Math.min(clip.count - 1, lastFrameFor(current.first, frames, nth));
} else {
parked = driven("force_rate") ? target : lastFrameFor(current.first, frames, nth);
writeEnd(current.first, parked);
@@ -263,7 +351,8 @@ export function mountTransformTrim({ get, set, has = () => true, driven = () =>
// The grip slides the kept part: a Length moves with IN (OUT follows), a
// free window keeps its span and both edges move.
const canSlide = () => {
if (!trim || locked("start")) return false;
// With a connected rate, IN itself slides the clip at its Duration.
if (!trim || locked("start") || driven("force_rate")) return false;
const current = plan();
if (!current || !["length", "fixed", "free"].includes(current.mode)) return false;
if (current.mode === "free" && locked("end")) return false;
@@ -285,26 +374,6 @@ export function mountTransformTrim({ get, set, has = () => true, driven = () =>
}
moveEdge("start", first, settled);
};
// Length on keeps what the rail shows now as the count; off turns the
// Length into an OUT at the same frame. Either way nothing moves.
const setLength = (on) => {
const current = plan();
if (!current || current.mode === "wired" || (on === (current.mode !== "free"))) return;
if (on) {
const frames = current.frames ?? framesThrough(current.first, current.windowLast, everyNth(), snapRule());
set("max_frames", Math.max(1, frames));
set("end_seconds", 0);
} else {
const last = current.last ?? current.windowLast;
writeStart(current.first);
writeEnd(current.first, last);
set("max_frames", 0);
if (!driven("fixed_frames")) set("fixed_frames", 0);
}
sync();
onCommit?.();
};
const readout = el("span", "ausboss-transform-trim-readout");
const summary = el("div", "ausboss-transform-trim-summary");
@@ -312,7 +381,7 @@ export function mountTransformTrim({ get, set, has = () => true, driven = () =>
const clip = info();
const playing = isPlaying();
play.setAttribute("aria-label", playing ? "Pause" : "Play");
play.title = playing ? "Pause on this frame" : trim ? "Play the selected clip" : "Play the video to pick a frame";
play.title = playing ? "Pause on this frame" : trim ? "Play the clip from its start" : "Play the video to pick a frame";
play.classList.toggle("is-playing", playing);
play.disabled = !clip.count;
const head = playheadFrame();
@@ -320,33 +389,41 @@ export function mountTransformTrim({ get, set, has = () => true, driven = () =>
playhead.style.left = pct(fractionOfFrame(head, clip, "center"));
playhead.style.visibility = clip.count ? "" : "hidden";
readout.replaceChildren();
const current = trim ? plan() : null;
if (clip.count) {
readout.append(el("b", "", `fr ${head}`), document.createTextNode(` · ${formatTimecode(frameTime(head, clip))}`));
readout.title = `Playhead: frame ${head} of ${clip.count} at ${frameTime(head, clip).toFixed(3)} s. Press or drag the rail to scrub; ${trim ? "the trim handles carry it with them." : "this is the frame the node outputs."}`;
readout.append(document.createTextNode("Preview "), el("b", "", `${secondsText(frameTime(head, clip))} s`), document.createTextNode(` · src fr ${head}`));
if (trim) {
const end = countAtRunTime() ? null : current.last;
const inside = head >= current.first && (end == null || head <= end);
readout.append(el("span", inside ? "ausboss-transform-trim-inside" : "ausboss-transform-trim-outside", inside ? " · in the clip" : " · outside the clip"));
}
readout.title = `The picture shows frame ${head} of ${clip.count}, ${frameTime(head, clip).toFixed(2)} seconds into the video. Press or drag the bar to look at another frame${trim ? "; Use as start starts the clip here." : "; this is the frame the node outputs."}`;
}
controls.frame?.set(head);
if (!trim) return;
const current = plan();
const wired = wiredBy();
const unknown = countAtRunTime();
const hasOut = current.last != null && current.mode !== "wired";
const hasOut = current.last != null && current.mode !== "wired" && !unknown;
const outFrame = current.last ?? current.windowLast;
const startFraction = fractionOfFrame(current.first, clip, "start");
const endFraction = fractionOfFrame(outFrame, clip, "end");
const endSec = endSecondsOf(current);
const endFraction = endSec != null && !unknown
? Math.max(startFraction, Math.min(1, endSec * clip.fps / clip.count))
: fractionOfFrame(outFrame, clip, "end");
// Dim: frames the free window holds but the run drops (every nth, snap).
const tailFraction = current.mode === "free" ? fractionOfFrame(current.windowLast, clip, "end") : endFraction;
span.style.left = pct(startFraction);
span.style.width = pct(current.last == null && current.mode !== "free" ? 0 : Math.max(0, tailFraction - startFraction));
span.classList.toggle("is-room", unknown || current.last == null);
// A length only the run knows: the dim part is the room the clip has.
span.style.width = pct(unknown || current.last == null ? 1 - startFraction : Math.max(0, tailFraction - startFraction));
kept.style.left = pct(startFraction);
kept.style.width = current.last == null || unknown ? "0%" : pct(Math.max(0, endFraction - startFraction));
const fills = lengthFillsClip(clip, current, everyNth());
span.title = unknown || current.last == null ? "Room for the clip: its length is set when the graph runs." : "";
const railWidth = rail.getBoundingClientRect().width || 0;
const keptWidth = Math.max(0, endFraction - startFraction) * railWidth;
grip.hidden = !canSlide() || unknown || (railWidth > 0 && keptWidth < 34);
grip.style.left = pct((startFraction + endFraction) / 2);
grip.title = current.mode === "free"
? "Drag to slide the kept part: IN and OUT move together."
: "Drag to slide the clip: OUT follows at the Length.";
grip.title = "Drag to slide the clip; its Duration stays.";
for (const edge of ["start", "end"]) {
const handle = handles[edge];
const frame = edge === "start" ? current.first : outFrame;
@@ -359,10 +436,9 @@ export function mountTransformTrim({ get, set, has = () => true, driven = () =>
handle.style.cursor = isLocked ? "not-allowed" : "";
handle.title = isLocked ? lockTip(edge)
: edge === "start"
? current.mode === "free" ? "Drag IN to trim; Shift + arrow moves one frame."
: fills ? "Drag IN to start later. The Length is as long as the clip, so the clip's end is OUT."
: "Drag IN to move the clip; OUT follows at the Length. Shift + arrow moves one frame."
: current.mode === "free" ? "Drag OUT to trim; it lands on the last frame the run keeps." : "Drag OUT to change the Length; IN stays.";
? durationFills(current) ? "Drag to start later. The Duration is longer than the video, so the clip runs to its end."
: "Drag to move the clip; its Duration stays. Shift + arrow moves one frame."
: "Drag to change the Duration; the start stays.";
handle.setAttribute("aria-valuemin", "0");
const maxFrame = edge === "start" && current.mode === "wired" && !unknown
? current.latestStart ?? current.windowLast : Math.max(0, clip.count - 1);
@@ -370,16 +446,16 @@ export function mountTransformTrim({ get, set, has = () => true, driven = () =>
handle.setAttribute("aria-valuenow", String(frame));
handle.setAttribute("aria-valuetext", `frame ${frame}, ${formatTimecode(frameTime(frame, clip))}`);
}
controls.start_seconds?.set(current.first);
controls.end_seconds?.set(outFrame);
disableControl(controls.start_seconds, locked("start"), lockTip("start"));
disableControl(controls.end_seconds, locked("end") || !hasOut, lockTip("end"));
syncLength(current, wired);
if (useStart) {
useStart.disabled = !clip.count || locked("start");
useStart.title = locked("start") ? lockTip("start") : "Start the clip at the frame on the stage. The Duration stays.";
}
if (clip.count) syncFields(clip, current, wired, unknown);
if (controls.reset) {
const free = current.mode === "free";
controls.reset.textContent = free ? "Full clip" : "To start";
controls.reset.title = free ? "Reset IN/OUT to the full source. Keeps Every nth and Frames for." : "Move IN to the start of the source; the length stays.";
controls.reset.disabled = !free && locked("start");
const free = current.mode !== "wired";
controls.reset.textContent = free ? "Whole video" : "To start";
controls.reset.title = free ? `Use the whole video: start at 0 with no Duration limit. Keeps Every nth${has("frame_snap") ? " and Frames for" : ""}.` : "Move the start to the beginning of the video; the linked length stays.";
controls.reset.disabled = locked("start") && !free;
}
controls.every_nth?.set(get("every_nth", 1));
disableControl(controls.every_nth, driven("every_nth"), "Every nth is supplied by a connected input.");
@@ -387,50 +463,21 @@ export function mountTransformTrim({ get, set, has = () => true, driven = () =>
controls.frame_snap.value = snapRule();
const exact = current.mode === "fixed" || (current.mode === "wired" && wired === "fixed_frames");
controls.frame_snap.disabled = exact || driven("frame_snap");
controls.frame_snap.title = exact ? "An exact fixed_frames count is used as it is; this does not apply." : "Keep a frame count the video model takes: LTX wants 8n+1 (49, 97, 121), Wan 4n+1. OUT and Length step to those counts. Any keeps every frame.";
controls.frame_snap.title = exact ? "An exact fixed_frames count is used as it is; this does not apply." : "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.";
}
syncSummary(clip, current, wired, unknown);
syncSummary(clip);
};
const syncSummary = (clip, current, wired, unknown) => {
const syncSummary = (clip) => {
if (!clip.count) {
summary.textContent = "Choose a source to set the clip window";
summary.textContent = "Choose a source to set the clip";
summary.title = "";
return;
}
const rate = outputRate?.();
const fps = `Source ${formatFps(clip.fps)} fps → Output ${rate == null ? "rate at run time" : `${formatFps(rate)} fps`}`;
if (current.mode === "wired") {
summary.textContent = current.frames == null ? `${fps} · length from ${wired} at run time` : `${fps} · ${current.frames} frames from ${wired}`;
summary.title = `The connected ${wired} input sets the length, so only IN is set here. Disconnect it to use OUT or a Length.`;
return;
}
if (unknown || current.frames == null) {
summary.textContent = `${fps} · frame count at run time`;
summary.title = "IN, OUT and the playhead refer to source frames. A connected input decides the exact frame count when the workflow runs. Connect the fps output to the next video node's fps input.";
return;
}
const from = formatTimecode(frameTime(current.first, clip));
const to = formatTimecode((current.last + 1) / clip.fps);
if (current.mode === "fixed") {
summary.textContent = current.tooLong
? `Fixed length needs more than the source's ${clip.duration.toFixed(3)}s`
: `${fps} · exactly ${current.frames} frames · ${from} → ${to}`;
summary.title = "An older Fixed frames value: an exact count from IN. Any change here turns it into a Length.";
return;
}
const total = current.windowLast - current.first + 1;
const count = current.mode === "length"
? current.truncated ? `${current.frames} of ${current.requested} frames, source ends` : `${current.frames} frames`
: current.frames < total ? `${current.frames} of ${total} frames` : `${current.frames} frames`;
summary.textContent = `${fps} · ${count} · ${from} → ${to}`;
summary.title = current.mode === "length"
? current.truncated
? `The source ends ${current.frames} frames after IN, before the Length of ${current.requested}. Move IN earlier or shorten the Length.`
: "Length keeps OUT this many output frames after IN; drag IN to move the clip, OUT to change the Length."
: current.frames < total
? `The window holds ${total} frames; every nth and the snap rule keep ${current.frames}, ending at frame ${current.last}, where OUT sits. The dim part is dropped.`
: "Frames the run outputs, at the fps the node reports.";
summary.textContent = `Source ${formatFps(clip.fps)} fps · ${clip.count} frames · ends at ${secondsText(clip.duration || clip.count / clip.fps)} s · clip out at ${rate == null ? "the rate set at run time" : `${formatFps(rate)} fps`}`;
summary.title = "Start and Ends at are places in the source video. Duration counts the frames the clip sends on, at the output rate.";
if (trim) rail.title = [clipLine?.textContent, summary.textContent, readout.textContent].filter(Boolean).join("\n");
};
// --- rail gestures --------------------------------------------------------
@@ -532,21 +579,19 @@ export function mountTransformTrim({ get, set, has = () => true, driven = () =>
}
// --- rows -----------------------------------------------------------------
const timeRow = el("div", "ausboss-transform-trim-line");
// The clip node: Preview (the playhead, and Use as start), the clip in
// words with a Seconds | Frames switch, then Start, Duration and Ends at.
// Start and Ends at are positions in the source video; Duration counts the
// frames the clip sends on, at the output rate. No modes: dragging IN
// slides the clip, dragging OUT or typing a Duration or an end changes the
// Duration.
const previewRow = el("div", "ausboss-transform-trim-line");
let useStart = null;
if (trim) {
for (const [name, caption, edge] of [["start_seconds", "IN", "start"], ["end_seconds", "OUT", "end"]]) {
const label = el("label");
label.append(el("span", "ausboss-transform-trim-caption", caption));
controls[name] = makeScrubInput({
value: 0, min: 0, max: 10000000, step: 1, decimals: 0,
title: edge === "start" ? "IN frame: the first frame the run keeps (stored as start_seconds)." : "OUT frame: the last frame the run keeps. With Length on it follows IN; typing it changes the Length.",
onChange: (frame) => moveEdge(edge, frame, false),
onSettle: () => { const window = currentWindow(); seek(edge === "start" ? window.first : window.last, true); onCommit?.(); },
});
label.append(controls[name].root);
timeRow.append(label);
if (edge === "start") timeRow.append(readout);
}
useStart = el("button", "ausboss-transform-trim-reset", "Use as start");
useStart.type = "button";
useStart.title = "Start the clip at the frame on the stage. The Duration stays.";
useStart.addEventListener("click", () => moveEdge("start", playheadFrame(), true));
} else {
const label = el("label");
label.append(el("span", "ausboss-transform-trim-caption", "FRAME"));
@@ -557,67 +602,237 @@ export function mountTransformTrim({ get, set, has = () => true, driven = () =>
onSettle: () => seek(playheadFrame(), true),
});
label.append(controls.frame.root);
timeRow.append(label, readout);
previewRow.append(label, readout);
}
root.append(transport, timeRow);
root.append(transport);
if (!trim) root.append(previewRow);
// Length: off, OUT ends the clip; on, a frame count from IN (max_frames,
// end left open), so OUT follows IN and the count survives a new source.
if (trim && has("max_frames")) {
const lengthRow = el("div", "ausboss-transform-trim-line wrap");
const label = el("label", "", "Length");
const pill = el("div", "ausboss-transform-trim-pill");
const off = el("button", "", "off");
const on = el("button", "", "on");
off.type = on.type = "button";
off.title = "OUT ends the clip: drag both handles freely.";
on.title = "Set the clip by a frame count from IN: OUT follows IN, and the count stays when you swap the video.";
off.addEventListener("click", () => setLength(false));
on.addEventListener("click", () => setLength(true));
pill.append(off, on);
const hint = el("span", "ausboss-transform-trim-hint");
const count = makeScrubInput({ value: 1, min: 1, max: 100000, step: 1, decimals: 0, unit: "fr", width: 72,
title: "Output frames from IN. Under a snap rule it steps to the counts the model keeps (97, 105, ... for 8n+1).",
onChange: (next) => {
const current = adoptLength(plan());
if (current.mode !== "length") { sync(); return; }
const was = current.requested ?? get("max_frames", 1);
set("max_frames", snapToValid(next, snapRule(), Math.sign(next - was)));
set("end_seconds", 0);
sync();
},
onSettle: () => { const window = currentWindow(); seek(window.last, true); onCommit?.(); },
});
label.append(pill, count.root);
lengthRow.append(label, hint);
root.append(lengthRow);
syncLength = (current, wired) => {
const active = current.mode !== "free";
const blocked = current.mode === "wired";
off.classList.toggle("on", !active);
on.classList.toggle("on", active);
off.setAttribute("aria-pressed", String(!active));
on.setAttribute("aria-pressed", String(active));
pill.classList.toggle("is-disabled", blocked);
off.disabled = on.disabled = blocked;
pill.title = blocked ? lockTip("end") : "";
count.root.style.display = active ? "" : "none";
const step = snapStep(snapRule());
count.setStep(step, step);
count.set(blocked ? (current.requested ?? current.frames ?? 0) : (current.requested ?? get("max_frames", 1)));
disableControl(count, blocked, lockTip("end"));
const fills = lengthFillsClip(info(), current, everyNth());
hint.textContent = blocked ? `from ${wired}` : current.mode === "fixed" ? "exact (older setting)" : fills ? "= the whole clip" : active ? "" : "OUT ends the clip";
hint.classList.toggle("note", fills && !blocked);
hint.title = fills && !blocked ? `The Length (${current.requested ?? current.frames} frames) is as long as the clip, so the clip's end is OUT. Drag IN to start later; drag OUT or type a smaller Length to end sooner.` : "";
const fields = {};
let clipLine = null;
let unitPill = null;
let noteRow = null;
let noteText = null;
const noteButtons = [];
if (trim) {
const clipRow = el("div", "ausboss-transform-trim-line");
clipLine = el("span", "ausboss-transform-trim-clip");
unitPill = el("div", "ausboss-transform-trim-pill");
for (const [key, words, tip] of [["s", "s", "Show times in seconds."], ["f", "fr", "Show times in frames: source frames for Start and Ends at, clip frames for Duration."]]) {
const button = el("button", "", words);
button.type = "button";
button.dataset.units = key;
button.title = tip;
button.addEventListener("click", () => { setUnits(key); sync(); });
unitPill.append(button);
}
const grid = el("div", "ausboss-transform-trim-fields");
const toFrames = {
start: (value) => (getUnits() === "f" ? Math.round(value) : Math.round(value * info().fps)),
};
// Output frames for a Duration typed in the current units.
const durationFrames = (value) => {
if (getUnits() === "f") return Math.round(value);
const rate = outFps();
return rate > 0 ? Math.round(value * rate) : null;
};
// Output frames from IN to an end typed in the current units.
const framesToEnd = (value) => {
const clip = info();
const current = plan();
const end = getUnits() === "f" ? (Math.round(value) + 1) / clip.fps : value;
if (driven("force_rate")) {
const rate = outFps();
return rate > 0 ? Math.round((end - boundSeconds("start")) * rate) : null;
}
return framesThrough(current.first, Math.ceil(end * clip.fps - 1e-7) - 1, everyNth(), snapRule());
};
const setDuration = (frames) => {
if (frames == null || !Number.isFinite(frames)) return;
const current = adoptLength(plan());
if (current.mode !== "length") return;
const was = current.requested ?? get("max_frames", 1);
set("max_frames", snapToValid(Math.max(1, frames), snapRule(), Math.sign(frames - was)));
set("end_seconds", 0);
stopNote = "";
};
const defs = [
["start", "Start", "Where the clip starts in the source video."],
["duration", "Duration", "How long the clip is. Counted in clip frames at the output rate."],
["end", "Ends at", "Where the clip ends in the source video. Typing it changes the Duration."],
];
for (const [key, caption, tip] of defs) {
const cell = el("div", "ausboss-transform-trim-field");
const label = el("span", "ausboss-transform-trim-field-label", caption);
const go = el("button", "ausboss-transform-trim-go", "linked");
go.type = "button";
label.append(go);
const control = makeScrubInput({
value: 0, min: 0, max: 10000000, step: 1, decimals: 2, minDecimals: 0, unit: "s", unitWidth: 34,
title: tip,
onChange: (value) => {
if (key === "start") {
if (locked("start")) return;
// A typed start is kept even when the Duration no longer fits;
// the note below says what fits and offers both fixes.
adoptLength(plan());
const frame = clampFrame(toFrames.start(value), info());
writeStart(frame);
stopNote = "";
seek(frame, false);
return;
}
if (key === "duration") setDuration(durationFrames(value));
else setDuration(framesToEnd(value));
sync();
},
onSettle: () => { const window = currentWindow(); seek(key === "start" ? window.first : window.last, true); onCommit?.(); },
});
cell.append(label, control.root);
grid.append(cell);
fields[key] = { control, go, cell, label };
}
noteRow = el("div", "ausboss-transform-trim-note");
noteText = el("span");
noteRow.append(noteText);
for (let index = 0; index < 2; index++) {
const button = el("button", "ausboss-transform-trim-reset");
button.type = "button";
noteButtons.push(button);
noteRow.append(button);
}
root.append(grid, noteRow);
}
// One field's look: its value in the current units, the line under it,
// and, when another node sets it, that node's name and a Go to button.
const showField = (key, { value, unit, decimals, sub, lockedBy, readOnly, placeholder = "" }) => {
const field = fields[key];
if (!field) return;
field.control.setRange({ decimals, minDecimals: 0, step: decimals ? 0.1 : 1, fineStep: decimals ? 0.01 : 1 });
field.control.set(value);
if (value == null) field.control.input.value = "";
field.control.input.placeholder = placeholder;
const unitSlot = field.control.root.querySelector(".ausboss-scrub-unit");
if (unitSlot) unitSlot.textContent = unit;
const tip = lockedBy ? `Set by ${lockedBy.title}: ${sub}. Click "linked" to go to that node.` : sub;
disableControl(field.control, readOnly, tip);
field.cell.title = tip;
field.go.hidden = !lockedBy;
if (lockedBy) {
field.go.title = `Set by ${lockedBy.title}. Click to go to that node.`;
field.go.onclick = () => lockedBy.go?.();
}
};
const showNote = (text, kind = "", actions = []) => {
if (!noteRow) return;
noteRow.hidden = !text;
noteRow.classList.toggle("warn", kind === "warn");
noteText.textContent = text;
noteButtons.forEach((button, index) => {
const action = actions[index];
button.hidden = !action;
if (action) { button.textContent = action.label; button.onclick = () => { action.run(); sync(); onCommit?.(); }; }
});
};
const syncFields = (clip, current, wired, unknown) => {
const seconds = getUnits() !== "f";
for (const button of unitPill.children) button.classList.toggle("on", button.dataset.units === (seconds ? "s" : "f"));
const rate = outFps();
const rateText = rate > 0 ? `${formatFps(rate)} fps` : "the output rate";
const first = current.first;
const endSec = unknown ? null : endSecondsOf(current);
const frames = unknown ? null : current.frames;
const startLink = locked("start") ? linkInfo(driven("start_frame") ? "start_frame" : "start_seconds") : null;
const lengthLink = current.mode === "wired" && wired ? linkInfo(wired) : null;
const endLink = endDriven() && current.mode === "free" ? linkInfo(driven("end_frame") ? "end_frame" : "end_seconds") : null;
const room = roomFrames();
const fills = durationFills(current);
showField("start", {
value: seconds ? frameTime(first, clip) : first,
unit: seconds ? "s" : "fr", decimals: seconds ? 2 : 0,
sub: seconds ? `source frame ${first}` : `source frame · ${secondsText(frameTime(first, clip))} s`,
lockedBy: startLink, readOnly: locked("start"),
});
// Duration: what was asked for (a Duration longer than what is left
// only caps the clip), in clip frames or seconds at the output rate.
const asked = current.mode === "wired" ? current.requested ?? current.frames : current.mode === "length" ? current.requested : frames;
let durationSub;
if (current.mode === "wired" && current.frames == null && current.requested == null) {
durationSub = room != null && rate > 0 ? `up to ${secondsText(room / rate)} s (${room} frames) fit after this start` : "set when the graph runs";
} else if (current.mode === "wired" && wired !== "fixed_frames" && current.truncated) {
durationSub = `the video ends first: ${frames} frames${rate > 0 ? ` (${secondsText(frames / rate)} s)` : ""}`;
} else if (current.mode === "wired") {
durationSub = wired === "fixed_frames" ? `${asked} clip frames required` : `up to ${asked} clip frames`;
} else if (frames == null) {
durationSub = "frame count at run time";
} else if (current.truncated) {
durationSub = `the video ends first: ${frames} frames${rate > 0 ? ` (${secondsText(frames / rate)} s)` : ""}`;
} else {
durationSub = seconds ? `${frames} clip frames at ${rateText}` : rate > 0 ? `clip frames · ${secondsText(frames / rate)} s at ${rateText}` : "seconds known at run time";
}
const durationInSeconds = seconds && rate > 0;
showField("duration", {
value: asked == null ? null : durationInSeconds ? asked / rate : asked,
unit: durationInSeconds ? "s" : "fr", decimals: durationInSeconds ? 2 : 0,
sub: durationSub, lockedBy: lengthLink,
readOnly: current.mode === "wired" || Boolean(endLink) || asked == null,
placeholder: current.mode === "wired" && asked == null ? "at run time" : "",
});
const lastSource = endSec == null ? null : Math.min(clip.count - 1, Math.max(first, Math.ceil(endSec * clip.fps - 1e-7) - 1));
showField("end", {
value: endSec == null ? null : seconds ? endSec : lastSource,
unit: seconds ? "s" : "fr", decimals: seconds ? 2 : 0,
sub: endSec == null ? "known after the run" : seconds ? `last source frame ${lastSource}` : `last source frame · ${secondsText(endSec)} s`,
lockedBy: endLink, readOnly: current.mode === "wired" || Boolean(endLink) || endSec == null,
placeholder: endSec == null ? "after Run" : "",
});
// The clip in words.
if (endSec == null) {
clipLine.textContent = `Clip from ${seconds ? `${secondsText(frameTime(first, clip))} s` : `src fr ${first}`} · length set when the graph runs`;
} else {
const span = seconds
? `Clip ${secondsText(frameTime(first, clip))} → ${secondsText(endSec)} s`
: `Clip src fr ${first} → ${lastSource}`;
clipLine.textContent = `${span} · ${frames} frames out`;
}
// What needs saying: a start that leaves too little video, a linked
// exact count that does not fit, or a drag that stopped at the end.
const latest = current.mode === "length" ? latestIn(current) : current.latestStart;
if (current.mode === "wired" && wired === "fixed_frames" && current.tooLong) {
showNote(`Needs ${asked} frames; the video is shorter.`, "warn");
} else if (current.mode === "wired" && wired === "fixed_frames" && latest != null && first > latest && !unknown) {
showNote(`Needs ${asked} frames; only ${room ?? "fewer"} fit from here. The run will fail.`, "warn",
locked("start") ? [] : [{ label: `Move start to ${secondsText(latest / clip.fps)} s`, run: () => writeStart(latest) }]);
} else if (current.mode === "length" && current.truncated && !fills) {
const actions = [{ label: `Shorten to ${rate > 0 ? `${secondsText(frames / rate)} s` : `${frames} frames`}`, run: () => { set("max_frames", Math.max(1, frames)); set("end_seconds", 0); } }];
if (!locked("start") && latest != null && latest < first) actions.push({ label: `Move start to ${secondsText(latest / clip.fps)} s`, run: () => writeStart(latest) });
showNote(`Only ${frames} of ${current.requested} frames fit from here.`, "warn", actions);
} else if (current.mode === "wired" && wired !== "fixed_frames" && current.truncated && frames != null) {
showNote(`Video ends first: ${frames} of ${asked} frames.`);
} else if (current.mode === "length" && fills && current.truncated) {
showNote("Runs to the end of the video.");
} else if (stopNote) {
showNote(stopNote);
} else {
showNote("");
}
publish?.(endSec == null || frames == null ? null : { frames, startSeconds: frameTime(first, clip), endSeconds: endSec, roomFrames: room });
};
if (trim) {
const sampling = el("div", "ausboss-transform-trim-line wrap");
const nthLabel = el("label", "", "Every nth");
controls.every_nth = makeScrubInput({ value: get("every_nth", 1), min: 1, max: 512, step: 1, decimals: 0,
title: "Keep one frame in this many. Output fps is adjusted to keep real-time playback; a Length counts the frames kept.",
title: "Keep one frame in this many. Output fps is adjusted to keep real-time playback; the Duration counts the frames kept.",
onChange: (next) => { if (!driven("every_nth")) set("every_nth", next); sync(); }, onSettle: onCommit,
});
nthLabel.append(controls.every_nth.root);
@@ -649,15 +864,20 @@ export function mountTransformTrim({ get, set, has = () => true, driven = () =>
reset.type = "button";
reset.addEventListener("click", () => {
const current = plan();
if (current.mode === "free") {
if (current.mode !== "wired") {
// The whole video: no start, no end, no Duration limit.
if (!locked("start")) set("start_seconds", 0);
if (!locked("end")) set("end_seconds", 0);
sync(); onCommit?.();
if (!endDriven()) set("end_seconds", 0);
set("max_frames", 0);
if (!driven("fixed_frames")) set("fixed_frames", 0);
stopNote = "";
seek(0, true); onCommit?.();
} else {
moveEdge("start", 0, true);
}
});
footer.append(summary, reset);
sampling.append(unitPill);
footer.append(useStart, el("span", "spacer"), reset);
root.append(sampling, footer);
}
root.addEventListener("pointerdown", (event) => {
+12 -7
View File
@@ -81,7 +81,7 @@ export function ensureCardCss() {
style.textContent = `
.ausboss-card{position:relative;box-sizing:border-box;width:100%;height:100%;display:flex;flex-direction:column;gap:${ROW_GAP}px;padding:${CARD_PADDING}px 8px;overflow:hidden;border:1px solid transparent;border-radius:${RADIUS_CARD}px;background:${T.card};font:12px/1.3 ${FONT};color:${T.inkSoft};pointer-events:none}
.ausboss-card-row{display:grid;grid-template-columns:minmax(56px,30%) 1fr;align-items:center;gap:8px;height:${ROW_HEIGHT}px;flex:none;pointer-events:auto}
.ausboss-card-row.hidden{display:none}
.ausboss-card .ausboss-card-row.hidden{display:none}
.ausboss-card-row.linked{opacity:.5}
.ausboss-card-row.linked .ausboss-card-control{pointer-events:none}
.ausboss-card-row.muted .ausboss-card-control{opacity:.35;pointer-events:none}
@@ -97,6 +97,7 @@ export function ensureCardCss() {
.ausboss-card-row.area{display:block}
.ausboss-card-row.panel{display:block}
.ausboss-card-row.area.grow{flex:1 1 auto;height:auto}
.ausboss-card-row.panel.grow{flex:1 1 auto;height:auto}
.ausboss-card-label{overflow:hidden;white-space:nowrap;text-overflow:ellipsis;color:${T.label};font-size:11px;user-select:none}
.ausboss-card-control{display:flex;align-items:center;gap:6px;min-width:0;height:100%}
.ausboss-card-field{display:flex;align-items:center;gap:6px;flex:1 1 0;min-width:0;height:100%}
@@ -215,9 +216,10 @@ function isFloatWidget(widget) {
// - `top` lifts the widgets' sockets
// into the node's slot column
// { section: "Caption" }
// { panel: (node) => ({ element, sync(values) }), height }
// { panel: (node) => ({ element, sync(values) }), height, grow?, when? }
// - the node's own display, on a row
// of the card
// of the card; `grow` takes the
// node's spare height
// { group: "advanced", label: "More" } - a disclosure; later rows with
// group: "advanced" sit under it
// A numeric row may have readOnlyText(node, values): nonempty text replaces
@@ -337,7 +339,7 @@ export function mountWidgetCard(node, { rows, minWidth = 300, first = false, hid
const seg = el("div", "ausboss-card-seg");
const buttons = new Map();
const add = (value, values) => {
const button = el("button", "", choiceLabel(row, value, values));
const button = el("button", "", choiceLabel(row, value, values, node));
button.type = "button"; button.title = row.titles?.[value] ?? String(value);
button.addEventListener("click", () => setWidget(name, value));
seg.append(button); buttons.set(value, button);
@@ -381,7 +383,7 @@ export function mountWidgetCard(node, { rows, minWidth = 300, first = false, hid
const options = comboValues(widget);
const list = options.includes(current) || current === undefined || current === "" ? options : [...options, current];
for (const value of list) {
const option = el("option", "", choiceLabel(row, value, options)); option.value = String(value); select.append(option);
const option = el("option", "", choiceLabel(row, value, options, node)); option.value = String(value); select.append(option);
}
select.value = String(current ?? "");
};
@@ -538,7 +540,8 @@ export function mountWidgetCard(node, { rows, minWidth = 300, first = false, hid
}
if (row.panel) {
const line = el("div", "ausboss-card-row panel");
line.style.height = `${rowHeight(row)}px`;
if (row.grow) { line.classList.add("grow"); line.style.minHeight = `${rowHeight(row)}px`; }
else line.style.height = `${rowHeight(row)}px`;
const panel = row.panel(node);
line.append(panel.element);
state.rows.push({ row, element: line, syncs: panel.sync ? [panel.sync] : [] });
@@ -762,7 +765,7 @@ export function mountWidgetCard(node, { rows, minWidth = 300, first = false, hid
}
const groups = {};
for (const entry of state.rows) if (entry.header) groups[entry.row.group] = groupOpen(entry.row.group);
const visible = visibleRows(state.rows.map((entry) => entry.row), vals, groups);
const visible = visibleRows(state.rows.map((entry) => entry.row), vals, groups, node);
const visibleSet = new Set(visible);
const tops = rowTops(visible, look);
state.rowTop = new Map();
@@ -863,5 +866,7 @@ export function mountWidgetCard(node, { rows, minWidth = 300, first = false, hid
refresh();
state.refresh = refresh; state.setGroupOpen = setGroupOpen; state.groupOpen = groupOpen;
// A panel that changes the card's rows itself (a tab) redraws it as a change by hand.
state.refreshByHand = () => byHand(refresh);
return state;
}
+6 -4
View File
@@ -18,12 +18,14 @@ const SEGMENT_MAX_CHARS = 26;
// Which rows the current values leave visible. `groups` maps a group name to
// its open state; a row inside a closed group is out, a row whose `when`
// says no is out, a group header stays as long as any row under it exists.
export function visibleRows(rows, values, groups = {}) {
// `when(values, node)` gets the node too, for a row that follows a display
// choice kept on the node rather than a widget value (a tab).
export function visibleRows(rows, values, groups = {}, node = null) {
return rows.filter((row) => {
if (row.group !== undefined && row.widget === undefined && row.pair === undefined && row.section === undefined) {
return true; // the disclosure header itself
}
if (row.when && row.when(values) === false) return false;
if (row.when && row.when(values, node) === false) return false;
if (row.inGroup && !groups[row.inGroup]) return false;
return true;
});
@@ -196,8 +198,8 @@ export function markSocketless(nodeData, names) {
// `labels` is a map from value to words, or a function of the value and of
// all the values, for a list that is only known on the user's machine (the
// model files they have).
export function choiceLabel(row, value, values = []) {
const own = typeof row?.labels === "function" ? row.labels(value, values) : row?.labels?.[value];
export function choiceLabel(row, value, values = [], node = null) {
const own = typeof row?.labels === "function" ? row.labels(value, values, node) : row?.labels?.[value];
return own ?? String(value);
}
+14 -3
View File
@@ -10,6 +10,7 @@
// panel's hidden storage widget stays hidden whichever renderer is on.
const STASH = "__ausbossVisibilityStash";
const PAINT_KEYS = ["computeSize", "computeLayoutSize", "draw"];
// Collapse a widget to zero height. Returns true when this call changed
// visibility, false when it was already hidden (callers use the return to
@@ -27,6 +28,10 @@ export function hideWidget(widget) {
computeSize: widget.computeSize,
computeLayoutSize: widget.computeLayoutSize,
draw: widget.draw,
// Which of the three the widget carried itself. One it lacked is deleted
// again on show: left behind as `undefined`, the frontend takes it for a
// custom-drawn widget and App mode draws an empty row.
own: Object.fromEntries(PAINT_KEYS.map((key) => [key, Object.prototype.hasOwnProperty.call(widget, key)])),
hidden: widget.hidden,
optionsHidden: options.hidden,
optionsDescriptor: Object.getOwnPropertyDescriptor(widget, "options"),
@@ -61,9 +66,10 @@ export function hideWidget(widget) {
export function showWidget(widget) {
const stash = widget?.[STASH];
if (!stash) return false;
widget.computeSize = stash.computeSize;
widget.computeLayoutSize = stash.computeLayoutSize;
widget.draw = stash.draw;
for (const key of PAINT_KEYS) {
if (stash.own && !stash.own[key]) delete widget[key];
else widget[key] = stash[key];
}
widget.hidden = stash.hidden;
const options = widget.options;
try {
@@ -84,6 +90,11 @@ export function showWidget(widget) {
return true;
}
// True while hideWidget holds the widget hidden.
export function isWidgetHidden(widget) {
return Boolean(widget?.[STASH]);
}
// Drive a widget toward a target visibility; true when anything changed.
export function setWidgetVisible(widget, visible) {
return visible ? showWidget(widget) : hideWidget(widget);
+75
View File
@@ -181,6 +181,43 @@ export function folderPath(dir) {
return `ComfyUI/models/${dir}`;
}
// ComfyUI still accepts two old folder names everywhere except in its
// /models/<folder> list, which answers 404 for them. Stability Matrix and
// older notes use them, so a row naming one is checked under the new name.
const LEGACY_FOLDERS = { clip: "text_encoders", unet: "diffusion_models" };
export function modelFolderKey(dir) {
const key = str(dir, 200).trim();
return Object.hasOwn(LEGACY_FOLDERS, key) ? LEGACY_FOLDERS[key] : key;
}
// Every folder this install reads for `dir`, from ComfyUI's
// /experiment/models list ([{ name, folders: [path, ...] }]). Launchers
// such as Stability Matrix add their own shared folders through
// extra_model_paths.yaml, so a file may live outside ComfyUI/models.
export function installFolders(dir, folderList) {
if (!dir || dir === INPUT_FOLDER || !Array.isArray(folderList)) return [];
const key = modelFolderKey(dir);
const entry = folderList.find((item) => item && item.name === key);
if (!entry || !Array.isArray(entry.folders)) return [];
return [...new Set(entry.folders.map((folder) => str(folder, 1000)).filter(Boolean))];
}
// The folders from `installFolders` with a name of their own, such as
// Stability Matrix's Data/Models/Lora: the ones worth showing, since a
// person would not guess them. A folder named like the kind itself
// (models/loras, output/loras, a shared .../loras) reads the way the card
// already says, so it is left out.
export function sharedFolders(dir, folderList) {
const key = modelFolderKey(dir);
const usual = new Set([key, ...Object.keys(LEGACY_FOLDERS).filter((name) => LEGACY_FOLDERS[name] === key)]
.map((name) => name.toLowerCase()));
return installFolders(dir, folderList).filter((folder) => {
const last = folder.replace(/\\/g, "/").replace(/\/+$/, "").split("/").pop().toLowerCase();
return !usual.has(last);
});
}
// Rows grouped by folder in first-seen order, so the card reads like the
// install tree: one heading per folder, its files beneath.
export function groupModels(models) {
@@ -213,6 +250,19 @@ export function matchInstalled(name, files) {
return loose ? { found: true, path: loose } : { found: false, path: null };
}
// The copy of `name` to pick without asking: the exact path when the folder
// has it, else the only file of that name in any subfolder. Two copies in
// different subfolders give null: which one to use is the user's choice.
export function onlyCopy(name, files) {
const match = matchInstalled(name, files);
if (!match.found) return null;
const wanted = str(name, 1000).trim().replace(/\\/g, "/").toLowerCase();
if (match.path.toLowerCase() === wanted) return match.path;
const base = baseName(name).toLowerCase();
const copies = files.filter((file) => baseName(str(file, 1000).replace(/\\/g, "/")).toLowerCase() === base);
return copies.length === 1 ? match.path : null;
}
// Node packs present in a graph, from each node type's python_module
// ("custom_nodes.ComfyUI-AusBoss"). Core modules ("nodes",
// "comfy_extras.*") are skipped: nobody needs to install those. The first
@@ -232,6 +282,31 @@ export function packsFromGraph(nodeTypes, moduleOf) {
return packs;
}
// This pack, as a Workflow Note lists it. Its folder is ausboss-nodes from
// the Manager and ComfyUI-AusBoss from a git clone, so a row is named and
// linked by the Registry id: a GitHub link sent people to clone a second copy.
export const OWN_PACK = Object.freeze({
name: "AusBoss nodes",
url: "https://registry.comfy.org/nodes/ausboss-nodes",
});
const OWN_PACK_NAMES = new Set(["ausboss nodes", "ausboss-nodes", "comfyui-ausboss"]);
const OWN_PACK_URL = /^https?:\/\/(?:www\.)?(?:github\.com\/ausboss\/comfyui-ausboss(?:\.git)?|registry\.comfy\.org\/nodes\/ausboss-nodes)\/?$/i;
// Whether a saved pack row is this pack, by its name or link. The probe node
// does not decide it: other AusBoss packs use AUSBOSS_NODES_ class names too.
export function isOwnPackRow(row) {
const name = str(row?.name, 200).trim().toLowerCase();
const url = str(row?.url, 500).trim();
return OWN_PACK_NAMES.has(name) || OWN_PACK_URL.test(url);
}
// Detect names a pack by its folder. The folder this pack runs from becomes
// OWN_PACK, so a workflow saved on a git clone does not send people to GitHub.
export function nameOwnPack(packs, ownFolder) {
return packs.map((pack) => (ownFolder && pack.name === ownFolder ? { ...OWN_PACK, node: pack.node } : pack));
}
// How tall the node must be for the card to show all of its content, from
// three numbers the page measures: the card's natural height at its current
// width, the node's height, and the part of the node height the card never
+9
View File
@@ -11,6 +11,7 @@ import {
unionOf,
} from "../shared/snap_lines.mjs";
import { boundsOf, nodeElements, outlineOf } from "../shared/outline.mjs";
import { TILE_MOVE } from "../shared/tile_face.mjs";
// Snap into line: a node or group being dragged lines up with the nodes and
// groups around it, and a teal line shows what it lines up with. A corner
@@ -294,6 +295,13 @@ function onPointerMove(event) {
});
}
// A frameless tile moves itself and keeps its pointer moves to itself
// (js/shared/tile_face.mjs), then reports each move here once placed.
function onTileMove(event) {
if (!state.before || !event.detail) return;
step(event.detail);
}
function end() {
state.before = null;
state.corner = null;
@@ -348,6 +356,7 @@ function install() {
window.addEventListener("pointerdown", onPointerDown, true);
window.addEventListener("pointerdown", afterPointerDown);
window.addEventListener("pointermove", onPointerMove);
window.addEventListener(TILE_MOVE, onTileMove);
// Capture phase: the classic canvas stops its pointerup from bubbling.
window.addEventListener("pointerup", end, true);
window.addEventListener("pointercancel", end, true);
+36 -17
View File
@@ -11,7 +11,8 @@ 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 { clipSetsDuration } from "../shared/h3_duration.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 { mountWidgetCard } from "../shared/widget_card.mjs";
@@ -125,6 +126,15 @@ const CARDS = {
{ widget: "interpolation", label: "Filter", kind: "select" },
],
},
// One node, many small jobs: a new job is a new choice in the list, and
// its own rows show only while it is picked.
AUSBOSS_NODES_ImageToolbox: {
minWidth: 280,
rows: [
{ widget: "job", label: "Job", kind: "select" },
{ widget: "pieces", label: "Pieces", when: isMode("job", "split sheet at gaps") },
],
},
AUSBOSS_NODES_EditLock: {
minWidth: 300,
rows: [
@@ -169,7 +179,7 @@ const CARDS = {
// A workflow saved before Seam existed holds the card's own empty value
// in the slot Seam now takes; it loads as classic. One saved with Seam
// holds it in Paste onto's slot, and loads as crop.
resetUnknown: { seam: "classic", paste_onto: "crop" },
resetUnknown: { seam: "classic", paste_onto: "crop", follow_changes: false },
// Seam and Paste onto have no row and no socket: the gear menu sets them.
hide: ["seam", "paste_onto"],
socketless: ["seam", "paste_onto"],
@@ -177,6 +187,7 @@ const CARDS = {
rows: [
{ widget: "color_match", label: "Tone match" },
{ widget: "fix_edge_halo", label: "Fix edge halo", mute: isBlendIn, muteTitle: SEAM_MUTE_TITLES.fix_edge_halo },
{ widget: "follow_changes", label: "Follow changes", mute: isBlendIn, muteTitle: SEAM_MUTE_TITLES.follow_changes },
],
},
AUSBOSS_NODES_CropForInpaint: {
@@ -380,22 +391,29 @@ 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"],
socketless: ["job_1", "job_2", "job_3", "job_4", "video_job"],
resetUnknown: { sound: "", music: "", clip_sound: false },
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: "" },
rows: [
{ section: "What happens" },
// 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).
{ panel: promptTabs, height: 30 },
{ panel: simpleEditedNote, height: 30, when: (values, node) => promptTab(node) !== FULL && isEdited(values) },
{ section: "What H3 gets", when: (values, node) => promptTab(node) === FULL },
{ panel: fullPromptBox, height: 210, grow: true, when: (values, node) => promptTab(node) === FULL },
{ section: "What happens", when: (values, node) => promptTab(node) !== FULL },
{
when: (values, node) => promptTab(node) !== FULL,
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 },
{ widget: "sound", label: "Sound", placeholder: "rain on a window" },
{ widget: "music", label: "Music", placeholder: "slow piano: music makes it louder" },
{ 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 },
{ section: "Pictures and settings" },
{ panel: castChips, height: 30 },
{ 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" },
{ widget: "camera", label: "Camera", kind: "select", labels: cameraChoiceLabel },
{ widget: "look", label: "Look", kind: "select" },
{ group: "more", label: "More" },
{ widget: "song_start", label: "Song starts at", suffix: "s", decimals: 1, trimZeros: true, group: "more" },
@@ -424,24 +442,25 @@ const CARDS = {
],
},
AUSBOSS_NODES_LoadVideo: {
minWidth: 320, first: true, hide: ["upload"],
// Every nth and the frame limit (as Duration) are in the timing card
// under the player (js/load_video). The card hides them, so App mode can
// still show them as fields.
minWidth: 320, first: true, hide: ["upload", "every_nth", "max_frames"],
rows: [
{ widget: "video", label: "Source", kind: "select", preview: { kind: "video", url: viewUrl },
button: { text: PANEL_LABELS.load, title: "Upload a video into ComfyUI's input folder", onClick: (node) => node.widgets?.find((w) => w.name === "upload")?.callback?.() } },
{ widget: "custom_width", label: "Width", suffix: "px", title: "0 keeps the source width; set one side only to keep the aspect." },
{ widget: "custom_height", label: "Height", suffix: "px", title: "0 keeps the source height; set one side only to keep the aspect." },
{ widget: "every_nth", label: "Every nth" },
{ widget: "max_frames", label: "Limit" },
],
},
AUSBOSS_NODES_LoadAudio: {
// The wave, IN and OUT live in the panel under the card (js/load_audio).
minWidth: 280, first: true, hide: ["upload"],
// The wave and Start, Duration and Ends at live in the panel under the
// 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"],
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: "max_seconds", label: "Max length", suffix: "s", decimals: 1, trimZeros: true,
title: "The longest the sound may be. Anything past it is cut off and shows in red. 0 means no limit." },
],
},
// Load Image: the file, then where it is in the folder and the size it
+160 -28
View File
@@ -15,7 +15,7 @@ import { app } from "../../../scripts/app.js";
import { setTileFace, TILE_FACE_CSS } from "../shared/tile_face.mjs";
import { NOTE_TYPES, serializeNoteIdentity } from "../shared/note_identity.mjs";
import { compactAction } from "../shared/panel_controls.mjs";
import { BRAND, chainCallback, keepDomWidgetWidthAuto, notifyAusbossChange } from "../shared/index.mjs";
import { BRAND, chainCallback, keepDomWidgetWidthAuto, notifyAusbossChange, showToast } from "../shared/index.mjs";
import { collectGraphNodes } from "../shared/appearance.mjs";
import { copyToClipboard } from "../shared/clipboard.mjs";
import { confirmDiscard } from "../shared/discard_prompt.mjs";
@@ -30,24 +30,59 @@ import {
MODEL_COLUMNS,
groupModels,
hostLabel,
installFolders,
listedSpelling,
loadersNeeding,
loraRowsNeeding,
matchInstalled,
modelFolderKey,
noteFit,
noteIsEmpty,
noteShowsTileFace,
normalizeNote,
onlyCopy,
OWN_PACK,
isOwnPackRow,
nameOwnPack,
packsFromGraph,
parseMarkdown,
rowFromCells,
serializeNote,
sharedFolders,
subfolderOf,
} from "../shared/workflow_note.mjs";
import { comboValues, commitWidgetValue } from "../shared/widget_card_math.mjs";
import { parseRows, serializeRows } from "../shared/lora_stack.mjs";
import { isFileWidget } from "../shared/lora_file_widgets.mjs";
const CSS_ID = "ausboss-workflow-note-css";
const PICK_FOUND_SETTING = "AusBoss.Models.PickFoundCopy";
function pickFoundCopies() {
return app.ui?.settings?.getSettingValue?.(PICK_FOUND_SETTING) !== false;
}
// Point the loaders (and LoRA Loader rows) that ask for a file by another
// spelling at the copy the note found. Returns how many it changed.
function useFoundCopy(path, loaders, loraRows, files) {
for (const entry of loaders) {
commitWidgetValue(entry.node, entry.widget, listedSpelling(path, entry.options), app.canvas);
entry.node.setDirtyCanvas?.(true, true);
}
const stacks = new Map();
for (const entry of loraRows) stacks.set(entry.widget, [...(stacks.get(entry.widget) ?? []), entry]);
for (const [widget, entries] of stacks) {
const rows = parseRows(widget.value);
for (const entry of entries) {
if (rows[entry.index]) rows[entry.index] = { ...rows[entry.index], name: listedSpelling(path, files) };
}
commitWidgetValue(entries[0].node, widget, serializeRows(rows), app.canvas);
entries[0].node.setDirtyCanvas?.(true, true);
}
app.graph?.setDirtyCanvas?.(true, true);
notifyAusbossChange();
return loaders.length + loraRows.length;
}
const WIDGET_NAME = "ausboss_workflow_note_panel";
const PANEL_MIN_WIDTH = 300;
const CARD_MIN_HEIGHT = 160;
@@ -65,12 +100,13 @@ const PANEL_TOP = 2;
const folderLists = new Map(); // dir -> { at, promise }
let modelFolders = null; // Promise<string[]> from GET /models
let folderInfo = null; // { at, promise } of GET /experiment/models
function listFolder(dir, fresh = false) {
const cached = folderLists.get(dir);
if (!fresh && cached && performance.now() - cached.at < FOLDER_CACHE_MS) return cached.promise;
const promise = api
.fetchApi(`/models/${encodeURIComponent(dir)}`)
.fetchApi(`/models/${encodeURIComponent(modelFolderKey(dir))}`)
.then((response) => (response.ok ? response.json() : null))
.then((files) => (Array.isArray(files) ? files : null))
.catch(() => null);
@@ -95,6 +131,22 @@ function knownFolders() {
return modelFolders;
}
// Where this install looks for each kind of model: [{ name, folders }].
// Launchers such as Stability Matrix add shared folders outside
// ComfyUI/models through extra_model_paths.yaml. [] when the endpoint is
// missing (an older or newer ComfyUI): the card then just names the usual
// folder, as before.
function installFolderList(fresh = false) {
if (!fresh && folderInfo && performance.now() - folderInfo.at < FOLDER_CACHE_MS) return folderInfo.promise;
const promise = api
.fetchApi("/experiment/models")
.then((response) => (response.ok ? response.json() : []))
.then((list) => (Array.isArray(list) ? list : []))
.catch(() => []);
folderInfo = { at: performance.now(), promise };
return promise;
}
function nodeTypeRegistered(type) {
return Boolean(type && globalThis.LiteGraph?.registered_node_types?.[type]);
}
@@ -103,6 +155,36 @@ function moduleOfType(type) {
return globalThis.LiteGraph?.registered_node_types?.[type]?.nodeData?.python_module;
}
// The custom_nodes folder this pack runs from, read off the Workflow Note's
// own registration.
function ownPackFolder() {
return /^custom_nodes\.([^.]+)/.exec(String(moduleOfType("AUSBOSS_NODES_WorkflowNote") ?? ""))?.[1] ?? "";
}
// Open ComfyUI-Manager on its updates list, or its node list. Without the
// Manager, say what to do and open the Registry page instead.
const MANAGER_COMMANDS = [
"Comfy.Manager.ShowUpdateAvailablePacks",
"Comfy.Manager.CustomNodesManager.ShowCustomNodesMenu",
"Comfy.Manager.Menu.ToggleVisibility",
];
async function openManagerForUpdate(tip) {
const command = app.extensionManager?.command;
const known = new Set((command?.commands ?? []).map((entry) => entry?.id));
for (const id of MANAGER_COMMANDS) {
if (!known.has(id)) continue;
try {
await command.execute(id);
showToast({ severity: "info", summary: "AusBoss nodes", detail: tip, life: 12000 });
return;
} catch (_error) {
// Try the next way into the Manager.
}
}
showToast({ severity: "info", summary: "AusBoss nodes", detail: tip, life: 12000 });
window.open(OWN_PACK.url, "_blank", "noopener,noreferrer");
}
// ---------------------------------------------------------------------------
// CSS
// ---------------------------------------------------------------------------
@@ -185,6 +267,8 @@ ${TILE_FACE_CSS}
.ausboss-note-body a:hover,.ausboss-note-link:hover{text-decoration:underline;}
.ausboss-note-folder{margin:8px 0 4px;color:#a9c4c2;font:11px ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;}
.ausboss-note-folder:first-child{margin-top:0;}
.ausboss-note-folder-also{margin:-2px 0 4px 18px;color:#7f9896;font:10.5px ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;overflow-wrap:anywhere;}
.ausboss-note-folder-also[hidden]{display:none;}
.ausboss-note-row{display:flex;align-items:center;gap:8px;min-height:30px;padding:3px 0;}
.ausboss-note-dot{flex:none;width:8px;height:8px;border-radius:50%;background:#4b5a5a;}
.ausboss-note-dot.checking{background:#4b5a5a;animation:ausboss-note-pulse 1s ease-in-out infinite;}
@@ -417,22 +501,7 @@ function modelRow(state, row) {
use.title = `Point ${names} at ${path}.`;
use.addEventListener("pointerdown", (event) => event.stopPropagation());
use.addEventListener("click", () => {
for (const entry of loaders) {
commitWidgetValue(entry.node, entry.widget, listedSpelling(path, entry.options), app.canvas);
entry.node.setDirtyCanvas?.(true, true);
}
const stacks = new Map();
for (const entry of loraRows) stacks.set(entry.widget, [...(stacks.get(entry.widget) ?? []), entry]);
for (const [widget, entries] of stacks) {
const rows = parseRows(widget.value);
for (const entry of entries) {
if (rows[entry.index]) rows[entry.index] = { ...rows[entry.index], name: listedSpelling(path, files) };
}
commitWidgetValue(entries[0].node, widget, serializeRows(rows), app.canvas);
entries[0].node.setDirtyCanvas?.(true, true);
}
app.graph?.setDirtyCanvas?.(true, true);
notifyAusbossChange();
useFoundCopy(path, loaders, loraRows, files);
checkModels(state, false);
});
action.append(pill, use);
@@ -461,6 +530,18 @@ function packRow(state, row) {
pill.append(link);
}
action.append(pill);
} else if (installed === false && isOwnPackRow(row)) {
// This note is running, so the pack is installed: the workflow needs a
// newer version. Cloning from GitHub would add a second copy.
const tip = `This workflow needs a newer version of AusBoss nodes (${row.node} is missing). `
+ "Update AusBoss nodes in ComfyUI-Manager, then restart ComfyUI.";
setDot(dot, "missing", tip);
const button = el("button", "ausboss-note-dl", "Update");
button.type = "button";
button.title = tip;
button.addEventListener("pointerdown", (event) => event.stopPropagation());
button.addEventListener("click", () => openManagerForUpdate(tip));
action.append(button);
} else {
setDot(dot, installed === false ? "missing" : "unknown",
installed === false ? `${row.node} is not registered here - install the pack` : "No probe node set, so this row is not checked");
@@ -511,6 +592,7 @@ function render(state) {
const scroll = state.scroll;
scroll.textContent = "";
state.rows = [];
state.folderHints = new Map();
const head = el("div", "ausboss-note-head");
head.append(el("h1", "ausboss-note-title", note.title || "Untitled workflow"));
@@ -598,6 +680,10 @@ function renderSections(state, scroll) {
section.append(heading);
for (const group of groupModels(note.models)) {
section.append(el("div", "ausboss-note-folder", `📂 ${group.path}`));
const also = el("div", "ausboss-note-folder-also");
also.hidden = true;
section.append(also);
(state.folderHints ??= new Map()).set(group.dir, also);
for (const row of group.rows) section.append(modelRow(state, row));
}
scroll.append(section);
@@ -625,10 +711,26 @@ function renderSections(state, scroll) {
checkModels(state, false);
}
// A launcher's shared model folder (Stability Matrix keeps LoRAs in
// Data/Models/Lora) under the usual ComfyUI/models/<dir> line, so the card
// says where this install also finds the files and where to put new ones.
function showSharedFolders(state, dir, list) {
const also = state.folderHints?.get(dir);
if (!also) return;
const shared = sharedFolders(dir, list);
also.hidden = !shared.length;
also.textContent = shared.length ? `also read from ${shared.join(", ")}` : "";
also.title = shared.length
? "This install also reads this kind of model from here (set in extra_model_paths.yaml, for example by Stability Matrix). A file in either place counts."
: "";
}
async function checkModels(state, fresh) {
const generation = (state.checkGeneration = (state.checkGeneration || 0) + 1);
const rows = state.rows;
const picked = [];
for (const entry of rows) setDot(entry.dot, "checking", "checking…");
const folderList = installFolderList(fresh);
const byDir = new Map();
for (const entry of rows) {
const dir = entry.row.dir;
@@ -654,8 +756,13 @@ async function checkModels(state, fresh) {
}));
return;
}
const files = await listFolder(dir, fresh);
const [files, list] = await Promise.all([listFolder(dir, fresh), folderList]);
if (generation !== state.checkGeneration) return;
showSharedFolders(state, dir, list);
const searched = installFolders(dir, list);
const notFound = searched.length
? `Not found in the ${searched.length === 1 ? "folder" : "folders"} this install reads for ${dir}: ${searched.join(", ")}`
: `Not found in ComfyUI/models/${dir}`;
for (const entry of entries) {
if (files === null) {
setDot(entry.dot, "unknown", `This install has no "${dir}" model folder, so the file is not checked`);
@@ -666,18 +773,33 @@ async function checkModels(state, fresh) {
const elsewhere = match.found && subfolderOf(match.path);
const loaders = elsewhere ? loadersNeeding(entry.row.name, match.path, graphListWidgets()) : [];
const loraRows = elsewhere ? loraRowsNeeding(entry.row.name, match.path, graphLoraLoaders(), files) : [];
if (match.found && (loaders.length || loraRows.length)) {
if (match.found && (loaders.length || loraRows.length) && pickFoundCopies() && onlyCopy(entry.row.name, files) === match.path) {
// One copy, so nothing to choose: the loaders take it without a
// click (App mode shows no Guide to click in).
useFoundCopy(match.path, loaders, loraRows, files);
picked.push(match.path);
setDot(entry.dot, "ok", `Found in ${subfolderOf(match.path)}/ and picked: ${match.path}`);
entry.showInstalled(match.path);
} else if (match.found && (loaders.length || loraRows.length)) {
setDot(entry.dot, "ok", `Found in ${subfolderOf(match.path)}/: ${match.path}`);
entry.showElsewhere(match.path, loaders, loraRows, files);
} else if (match.found) {
setDot(entry.dot, "ok", `Found: ${match.path}`);
entry.showInstalled(match.path);
} else {
setDot(entry.dot, "missing", `Not found in ComfyUI/models/${dir}`);
setDot(entry.dot, "missing", notFound);
entry.showDownload();
}
}
}));
if (picked.length && generation === state.checkGeneration) {
const folders = [...new Set(picked.map(subfolderOf))].map((folder) => `${folder}/`).join(", ");
showToast({
summary: "Models found",
detail: `${picked.length === 1 ? "1 model file" : `${picked.length} model files`} found in ${folders} and picked for this workflow.`,
life: 4000,
});
}
if (state.domWidget && generation === state.checkGeneration) fitNote(state);
}
@@ -756,7 +878,7 @@ function graphListWidgets() {
seen.add(graph);
for (const node of graph._nodes ?? graph.nodes ?? []) {
for (const widget of node.widgets ?? []) {
if (widget?.type !== "combo" || typeof widget.value !== "string") continue;
if (widget?.type !== "combo" || typeof widget.value !== "string" || isFileWidget(widget)) continue;
out.push({ node, widget, value: widget.value, options: comboValues(widget) });
}
if (node.subgraph) walk(node.subgraph);
@@ -972,8 +1094,8 @@ async function openEditor(state) {
form.append(field("Models", models.box, "Each row shows a Download button until the file is found in its folder (subfolders count). The note shows in grey under the file name."), modelTools);
const packs = table("packs", ["Pack", "URL", "Probe node class"], draft.packs, (row) => [
input(row.name, "ComfyUI-AusBoss"),
input(row.url, "https://github.com/ausboss/ComfyUI-AusBoss"),
input(row.name, OWN_PACK.name),
input(row.url, OWN_PACK.url),
input(row.node, "AUSBOSS_NODES_LoraLoader"),
]);
const packTools = el("div");
@@ -988,11 +1110,9 @@ async function openEditor(state) {
detect.addEventListener("click", () => {
const types = collectGraphNodes(app.rootGraph ?? app.graph).map((node) => node.type);
const have = new Set(packs.entries.map((entry) => entry.controls[0].value.trim()));
for (const pack of packsFromGraph(types, moduleOfType)) {
for (const pack of nameOwnPack(packsFromGraph(types, moduleOfType), ownPackFolder())) {
if (have.has(pack.name)) continue;
packs.add(pack.name === "ComfyUI-AusBoss"
? { ...pack, url: "https://github.com/ausboss/ComfyUI-AusBoss" }
: pack);
packs.add(pack);
}
});
packTools.append(addPack, detect);
@@ -1178,6 +1298,18 @@ function buildPanel(node) {
app.registerExtension({
name: "AusBoss.WorkflowNote",
settings: [
{
id: PICK_FOUND_SETTING,
name: "Pick model files found in a subfolder",
type: "boolean",
defaultValue: true,
category: ["🆎 AusBoss", "Models", "Pick found files"],
tooltip:
"When a workflow's Guide finds a model you already have in a subfolder, the workflow switches to that "
+ "file by itself. Off: the Guide shows a Use it button instead.",
},
],
beforeRegisterNodeDef(nodeType, nodeData) {
if (!NOTE_TYPES.has(nodeData?.name)) return;
hideInputsInDef(nodeData, ["note"]);
+195 -3
View File
@@ -216,6 +216,9 @@
},
"feather": {
"name": "羽化"
},
"remove_tint": {
"name": "去除偏色"
}
},
"outputs": {
@@ -292,7 +295,128 @@
},
"AUSBOSS_NODES_H3PromptWriter": {
"display_name": "H3 提示词写手 🆎",
"description": "每发生一件事写一行,给每张图片和视频分配一个任务,它就会写出 MiniMax H3 需要的提示词,并给出匹配的宽度和高度。视频里有两个人时,写明要换谁,就只替换那个人。"
"description": "每发生一件事写一行,给每张图片和视频分配一个任务,它就会写出 MiniMax H3 需要的提示词,并给出匹配的宽度和高度。视频里有两个人时,写明要换谁,就只替换那个人。",
"inputs": {
"script": {
"name": "脚本"
},
"seconds": {
"name": "长度"
},
"clip": {
"name": "片段"
},
"picture_1": {
"name": "图片 1"
},
"picture_2": {
"name": "图片 2"
},
"picture_3": {
"name": "图片 3"
},
"picture_4": {
"name": "图片 4"
},
"video": {
"name": "视频"
},
"video_sound": {
"name": "视频声音"
},
"voice": {
"name": "人声"
},
"song": {
"name": "歌曲"
},
"camera": {
"name": "镜头"
},
"look": {
"name": "风格"
},
"song_start": {
"name": "歌曲起点"
},
"cut_on_beat": {
"name": "按节拍切换"
},
"language": {
"name": "语言"
},
"job_1": {
"name": "图片 1 任务"
},
"job_2": {
"name": "图片 2 任务"
},
"job_3": {
"name": "图片 3 任务"
},
"job_4": {
"name": "图片 4 任务"
},
"video_job": {
"name": "视频任务"
},
"sound": {
"name": "声音"
},
"music": {
"name": "音乐"
},
"clip_sound": {
"name": "片段自带声音"
},
"full_prompt": {
"name": "完整提示词"
}
},
"outputs": {
"0": {
"name": "提示词"
},
"1": {
"name": "图片 1"
},
"2": {
"name": "图片 2"
},
"3": {
"name": "图片 3"
},
"4": {
"name": "图片 4"
},
"5": {
"name": "视频"
},
"6": {
"name": "视频声音"
},
"7": {
"name": "人声"
},
"8": {
"name": "歌曲"
},
"9": {
"name": "垫底歌曲"
},
"10": {
"name": "帧数"
},
"11": {
"name": "宽度"
},
"12": {
"name": "高度"
},
"13": {
"name": "保留片段声音"
}
}
},
"AUSBOSS_NODES_ImageCropRotatePad": {
"display_name": "图像裁剪 + 旋转 + 扩边 🆎",
@@ -518,6 +642,26 @@
}
}
},
"AUSBOSS_NODES_ImageToolbox": {
"display_name": "图像工具箱 🆎",
"description": "把几个小的图像任务放在一个节点里:从列表里选任务。split sheet at gaps 会把一排并列的图(比如角色设定图的四个视角)切成单独的图。每一刀都切在两张图之间的空隙,而不是按宽度平均切,所以不会有哪一张带上邻图的一部分。切好的图作为一个批次输出,尺寸相同,用设定图的背景色补齐。",
"inputs": {
"image": {
"name": "图像"
},
"job": {
"name": "任务"
},
"pieces": {
"name": "份数"
}
},
"outputs": {
"0": {
"name": "图像"
}
}
},
"AUSBOSS_NODES_Integer": {
"display_name": "整数 🆎",
"description": "一个独立的 INT 值。在一个地方设置步数、尺寸或数量,送给所有需要同一个数字的节点。",
@@ -648,6 +792,9 @@
},
"3": {
"name": "遮罩"
},
"4": {
"name": "H3 提示词"
}
}
},
@@ -961,6 +1108,9 @@
},
"fine_edges": {
"name": "精细边缘"
},
"new_picture": {
"name": "换新图时"
}
},
"outputs": {
@@ -981,6 +1131,15 @@
"inputs": {
"expression": {
"name": "表达式"
},
"a": {
"name": "a"
},
"b": {
"name": "b"
},
"c": {
"name": "c"
}
},
"outputs": {
@@ -998,6 +1157,12 @@
"inputs": {
"on_mismatch": {
"name": "不匹配时"
},
"a": {
"name": "a"
},
"b": {
"name": "b"
}
},
"outputs": {
@@ -1103,6 +1268,9 @@
},
"batch_size": {
"name": "批次大小"
},
"workflow_sizes": {
"name": "工作流尺寸"
}
},
"outputs": {
@@ -1314,6 +1482,14 @@
"index": {
"name": "索引"
}
},
"outputs": {
"0": {
"name": "a"
},
"1": {
"name": "b"
}
}
},
"AUSBOSS_NODES_StepPreview": {
@@ -1341,6 +1517,9 @@
},
"paste_onto": {
"name": "贴到"
},
"follow_changes": {
"name": "跟随变化"
}
},
"outputs": {
@@ -1665,6 +1844,9 @@
},
"fixed_frames": {
"name": "固定帧数"
},
"last_seconds": {
"name": "最后几秒"
}
},
"outputs": {
@@ -1741,11 +1923,21 @@
},
"AUSBOSS_NODES_CalloutTile": {
"display_name": "标注卡片 🆎",
"description": "紧凑的标题或彩色链接按钮。双击编辑,拖动角落调整大小。旧版节点包会将它显示为缺失节点,请更新 ComfyUI-AusBoss。"
"description": "紧凑的标题或彩色链接按钮。双击编辑,拖动角落调整大小。旧版节点包会将它显示为缺失节点,请更新 ComfyUI-AusBoss。",
"inputs": {
"text": {
"name": "文字"
}
}
},
"AUSBOSS_NODES_WorkflowNoteTile": {
"display_name": "工作流说明卡片 🆎",
"description": "点击打开完整说明的小按钮。点击铅笔编辑,拖动角落调整大小。旧版节点包会将它显示为缺失节点,请更新 ComfyUI-AusBoss。"
"description": "点击打开完整说明的小按钮。点击铅笔编辑,拖动角落调整大小。旧版节点包会将它显示为缺失节点,请更新 ComfyUI-AusBoss。",
"inputs": {
"note": {
"name": "备注"
}
}
},
"AUSBOSS_NODES_FlashVSRUpscale": {
"display_name": "FlashVSR 视频放大 🆎",
+205
View File
@@ -0,0 +1,205 @@
"""Stitch Inpaint's Follow changes: paste what the model changed, not only the box.
A model that redraws the whole crop it is given (MiniMax H3 Image, and any
edit model run at full denoise) does not keep to the box: a new person's
boots, a plate's rim or a coat's collar reach past it, and a paste of the
box alone cuts them off at its edge. The model can also draw the crop a
touch zoomed or shifted, so the redrawn background no longer lines up with
the picture around it.
Follow changes does two things before the usual classic paste:
1. It lines the model's crop up with the picture's own crop (the zoom and
shift that Realign to Source measures). When the measurement does not
hold up, the crop is used as it came back.
2. It grows the paste from the box to every change that touches it: pixels
where the lined-up crop differs from the picture, joined to the box. The
grown edge fades out before the crop window's border, so nothing ends in
a hard line. When the change covers most of the window outside the box,
the model redrew everything, and the paste stays the box.
The work runs at most ``WORK_SIDE`` pixels on the long side, on the CPU,
and the grown mask is scaled back to the window. Distances below are in
pixels of the crop window at full size and scale with it.
"""
from __future__ import annotations
import torch
import torch.nn.functional as F
from ._realign_helpers import crop_if_shift, measure, warp_to_source
WORK_SIDE = 768
# A change this large (0..1, mean over RGB, after a light blur) counts.
CHANGE_LEVEL = 0.10
CHANGE_BLUR = 4.0
# How close a change has to come to the box to join it, how far the joined
# shape is closed and widened, and how soft its edge is.
TOUCH = 8.0
CLOSE = 6.0
WIDEN = 10.0
SOFT = 10.0
# The paste fades to nothing over this many pixels before a window border
# that lies inside the picture.
BORDER_FADE = 24.0
# When the change outside the box covers more than this share of the window
# outside the box, the model redrew everything: keep the box.
REDREW_ALL = 0.5
MAX_ZOOM = 0.2
def _blur(image: torch.Tensor, sigma: float) -> torch.Tensor:
"""Gaussian blur of an HW map, edges extended."""
if sigma <= 0.3:
return image
radius = max(1, int(round(sigma * 3)))
x = torch.arange(-radius, radius + 1, dtype=torch.float32)
kernel = torch.exp(-(x * x) / (2 * sigma * sigma))
kernel = kernel / kernel.sum()
out = image[None, None]
out = F.conv2d(F.pad(out, (radius, radius, 0, 0), mode="replicate"), kernel.view(1, 1, 1, -1))
out = F.conv2d(F.pad(out, (0, 0, radius, radius), mode="replicate"), kernel.view(1, 1, -1, 1))
return out[0, 0]
def _dilate(mask: torch.Tensor, radius: int) -> torch.Tensor:
if radius <= 0:
return mask
k = 2 * radius + 1
return F.max_pool2d(mask[None, None].float(), k, stride=1, padding=radius)[0, 0] > 0.5
def _erode(mask: torch.Tensor, radius: int) -> torch.Tensor:
return ~_dilate(~mask, radius)
def _reconstruct(seed: torch.Tensor, allowed: torch.Tensor) -> torch.Tensor:
"""Every pixel of ``allowed`` connected to ``seed`` (8-neighbour fill)."""
region = seed & allowed
# Steps of 2 px: a gap of a pixel or two in the change still joins,
# and the fill takes a quarter of the passes.
for _ in range(sum(allowed.shape)):
grown = _dilate(region, 2) & allowed
if torch.equal(grown, region):
break
region = grown
return region
def _fill_holes(mask: torch.Tensor) -> torch.Tensor:
border = torch.zeros_like(mask)
border[0, :] = border[-1, :] = border[:, 0] = border[:, -1] = True
outside = _reconstruct(border & ~mask, ~mask)
return ~outside
def _border_ramp(height: int, width: int, fade: float, open_sides: tuple[bool, bool, bool, bool]) -> torch.Tensor:
"""1 inside, falling to 0 at each window border inside the picture.
open_sides: (top, bottom, left, right) borders that are the picture's own
edge, where nothing is cut and nothing fades."""
top, bottom, left, right = open_sides
ys = torch.arange(height, dtype=torch.float32)
xs = torch.arange(width, dtype=torch.float32)
big = float(height + width)
dy = torch.minimum(ys if not top else torch.full_like(ys, big),
(height - 1 - ys) if not bottom else torch.full_like(ys, big))
dx = torch.minimum(xs if not left else torch.full_like(xs, big),
(width - 1 - xs) if not right else torch.full_like(xs, big))
return (torch.minimum(dy[:, None], dx[None, :]) / max(fade, 1.0)).clamp(0.0, 1.0)
def _resize_hw(mask: torch.Tensor, height: int, width: int) -> torch.Tensor:
return F.interpolate(mask[None, None].float(), size=(height, width), mode="bilinear", align_corners=False)[0, 0]
def realign_crop(source: torch.Tensor, patch: torch.Tensor) -> tuple[torch.Tensor, bool]:
"""The patch (HWC, window size) lined up with the source crop (HWC).
Returns (patch, moved); an unreliable measurement leaves it as it is."""
height, width = int(source.shape[0]), int(source.shape[1])
result = measure(source, patch, "zoom + shift", MAX_ZOOM)
if not result.reliable:
return patch, False
out = crop_if_shift(patch, result.matrix, width, height)
if out is None:
out, _ = warp_to_source(patch, result.matrix, width, height, "source", source)
return out, True
def follow_mask(source: torch.Tensor, patch: torch.Tensor, box: torch.Tensor,
open_sides: tuple[bool, bool, bool, bool]) -> tuple[torch.Tensor, dict]:
"""The grown paste mask (HW, 0..1) for one frame, in window pixels.
source, patch: HWC at window size, patch already lined up. box: HW blend
mask in the window. Returns (mask, info) where info says what was done."""
height, width = int(box.shape[0]), int(box.shape[1])
scale = min(1.0, WORK_SIDE / max(height, width))
wh, ww = max(8, int(round(height * scale))), max(8, int(round(width * scale)))
def px(value: float) -> float:
return value * scale
small = lambda img: F.interpolate(img.permute(2, 0, 1)[None, :3].float(), size=(wh, ww),
mode="area")[0]
diff = (small(patch) - small(source)).abs().mean(0)
diff = _blur(diff, px(CHANGE_BLUR))
core = _resize_hw(box, wh, ww) >= 0.5
if not bool(core.any()):
return box.clone(), {"grew": False, "why": "no box"}
changed = diff > CHANGE_LEVEL
joined = _reconstruct(_dilate(core, max(1, round(px(TOUCH)))) & changed, changed) | core
outside = ~core
added = (joined & outside).sum().item()
room = max(1, outside.sum().item())
if added / room > REDREW_ALL:
return box.clone(), {"grew": False, "why": "the model redrew most of the window"}
close = max(1, round(px(CLOSE)))
joined = _erode(_dilate(joined, close), close) | core
joined = _fill_holes(joined)
joined = _dilate(joined, max(1, round(px(WIDEN))))
soft = _blur(joined.float(), px(SOFT))
soft = _resize_hw(soft, height, width).clamp(0.0, 1.0)
ramp = _border_ramp(height, width, BORDER_FADE, open_sides)
grown = torch.maximum(soft * ramp, box.float() * ramp)
# The box itself always pastes as it did, ramp or not.
grown = torch.maximum(grown, box.float() * (box >= 0.999).float())
share = float((grown > 0.5).sum()) / max(1.0, float((box > 0.5).sum()))
return grown, {"grew": True, "share": share}
def follow_changes(stitcher: dict, patch: torch.Tensor, resize) -> tuple[torch.Tensor, dict, list[str]]:
"""Line the patch up and grow the paste. Returns (patch at window size,
a stitcher copy whose blend is the grown mask, one line per frame).
``resize(patch, width, height, algorithm)`` brings the patch to the
window size the way the classic stitch does."""
canvas = stitcher["canvas"]
blend = stitcher["blend"]
cx, cy, cw, ch = stitcher["crop_to_canvas"]
if (patch.shape[1], patch.shape[2]) != (ch, cw):
patch = resize(patch, cw, ch, stitcher.get("algorithm", "bilinear"))
full_h, full_w = int(canvas.shape[1]), int(canvas.shape[2])
open_sides = (cy <= 0, cy + ch >= full_h, cx <= 0, cx + cw >= full_w)
frames = int(patch.shape[0])
patches, blends, lines = [], [], []
for index in range(frames):
src = canvas[min(index, canvas.shape[0] - 1), cy:cy + ch, cx:cx + cw, :3].detach().float().cpu()
edit = patch[index, ..., :3].detach().float().cpu()
box = blend[min(index, blend.shape[0] - 1), cy:cy + ch, cx:cx + cw].detach().float().cpu()
lined, moved = realign_crop(src, edit)
grown, info = follow_mask(src, lined, box, open_sides)
if patch.shape[-1] > 3:
lined = torch.cat([lined, patch[index, ..., 3:].detach().float().cpu()], dim=-1)
patches.append(lined)
whole = blend[min(index, blend.shape[0] - 1)].detach().float().cpu().clone()
whole[cy:cy + ch, cx:cx + cw] = grown
blends.append(whole)
what = "lined up" if moved else "not moved"
if info["grew"]:
lines.append(f"Follow changes: {what}; paste grown to {info['share']:.2f}x the box.")
else:
lines.append(f"Follow changes: {what}; paste kept to the box ({info['why']}).")
out_patch = torch.stack(patches).to(device=patch.device, dtype=patch.dtype)
new = dict(stitcher)
new["blend"] = torch.stack(blends).to(device=blend.device, dtype=blend.dtype)
return out_patch, new, lines
+25 -5
View File
@@ -60,6 +60,26 @@ def add_module_version(source, token):
return _MODULE_IMPORT.sub(lambda m: f"{m.group(1)}{m.group(2)}{m.group(3)}?v={token}{m.group(2)}", source)
def list_served_scripts(js_root):
"""The pack's own scripts by their address below the js folder:
{"shared/index.mjs": <path>}. Made once at startup, so a request is
only looked up in it and the address a browser sends never reaches the
disk: no whole path, network share or ".." is ever opened. Links are
left out, and anything that resolves outside the js folder."""
root = Path(js_root).resolve()
scripts = {}
for path in sorted(root.rglob("*")):
try:
if path.suffix not in (".js", ".mjs") or path.is_symlink() or not path.is_file():
continue
if not path.resolve().is_relative_to(root):
continue
except OSError:
continue
scripts[path.relative_to(root).as_posix()] = path
return scripts
def make_revalidate_middleware(pack_name, js_root=None, token=None):
"""aiohttp middleware for this pack's scripts, nothing else touched.
@@ -69,7 +89,7 @@ def make_revalidate_middleware(pack_name, js_root=None, token=None):
from aiohttp import web
marker = f"/extensions/{pack_name}/"
root = Path(js_root).resolve() if js_root and token else None
scripts = list_served_scripts(js_root) if js_root and token else None
served = {}
def versioned(path):
@@ -90,15 +110,15 @@ def make_revalidate_middleware(pack_name, js_root=None, token=None):
def tagged_response(request):
"""The tagged script for this request, or None to let ComfyUI serve it."""
if root is None or request.method not in ("GET", "HEAD"):
if not scripts or request.method not in ("GET", "HEAD"):
return None
start = request.path.find(marker)
if start < 0 or not request.path.endswith((".js", ".mjs")):
return None
target = scripts.get(request.path[start + len(marker):])
if target is None:
return None
try:
target = (root / request.path[start + len(marker):]).resolve()
if not target.is_relative_to(root) or not target.is_file():
return None
found = versioned(target)
except (OSError, ValueError, UnicodeDecodeError):
return None
+230 -40
View File
@@ -19,6 +19,10 @@ STYLE = "style"
START = "start on it"
END = "end on it"
JOBS = (PERSON, SHEET, PLACE, OUTFIT, THING, STYLE, START, END)
# Not a pick on the node: a thing picture that does the action of a move copy or a swap (a cartoon hand, a toy,
# a mascot). It takes the place a person would, with its own shape and look.
PERFORMER = "thing that moves"
ACTORS = (PERSON, SHEET, PERFORMER)
MOVES = "copy its moves"
SWAP = "swap the person"
@@ -26,7 +30,7 @@ KEEP = "keep going"
REVOICE = "new voice"
EDIT = "change something"
VIDEO_JOBS = (MOVES, SWAP, KEEP, REVOICE, EDIT)
KEEPS_ITS_LENGTH = (SWAP, REVOICE, EDIT) # These change a clip, so the new one runs as long as the old one.
KEEPS_ITS_LENGTH = (MOVES, SWAP, REVOICE, EDIT) # These follow a clip, so the new one runs as long as the old one.
NEEDS_NO_WORDS = (SWAP, KEEP)
TOKEN = re.compile(r"@(\d)\b")
@@ -35,14 +39,31 @@ MAIN = "@0" # The main person, for lines the node writes itself.
BACKGROUND = "The background of {picture} is not kept."
NOTHING_IN = "Connect a picture or a video. H3 needs one to start from."
NEEDS_A_PERSON = {
MOVES: "To copy the moves, connect a picture of your person and pick person for it.",
SWAP: "To swap the person, connect a picture of the new person and pick person for it.",
}
# A hat or a shirt with no person picture: the user wants the video's own person to wear it.
DRESS_THE_VIDEO_PERSON = 'To put this on the person in your video, pick the video job "change something" and type "He wears @1".'
SWAP_NEEDS_PERSON_THING = (
'A swap needs a picture of the new person, and pick person for it. To show a thing in the clip, '
'pick the video job "change something" and type "He holds @1".'
)
SWAP_NEEDS_PERSON_PLACE = (
'A swap keeps the place of the video. Connect a picture of the new person and pick person for it. '
'To change the place, pick the video job "change something" and type "It looks like @1".'
)
REVOICE_KEEPS_PERSON = (
"New voice keeps the person in the clip, so a person picture can't change who is in it. "
'Take the picture off, or pick the video job "swap the person".'
)
HE_SHE = re.compile(r"\b(?:he|she|they)\b", re.I)
# (what the label is, how it is kept). {picture} is H3's number for the picture.
JOB_WORDS = {
PERFORMER: (
"{subject} is the character in {picture}, with the same shape, colours and drawing style.",
"fully_preserved - the shape, colours and drawing style are retained.",
),
PERSON: (
"{subject} is the person in {picture}, with the same face, hair and clothes.",
"fully_preserved - the face, hair and clothes are retained.",
@@ -91,6 +112,18 @@ MOVES_KEPT = (
"keep the source performer's face, body, clothes, props, background and colours out of the target.\n"
"<Video 1>: attribute_transfer - apply only its camera movement to the target scene."
)
# Copy its moves with no person picture: the person in the video keeps their own moves and goes where the
# script or a place picture says.
OWN_MOVES_ARE = (
"{main} is the person in <Video 1>, with the same face, hair, body{clothes} and the same moves, gestures and "
"timing.\n<Video 1> provides the camera movement."
)
OWN_MOVES_KEPT = (
"{main} (appears in {shots}): {kept}\n"
"<Video 1>: attribute_transfer - apply its person, their moves and its camera movement to the target scene; {place}"
)
OWN_PLACE_FROM = "the background of <Video 1> is not kept, and the place is {place}."
OWN_PLACE_KEPT = "keep its place unless the script names a new one."
SWAP_VIDEO = "<Video 1> supplies the place, the action, the timing, the camera movement and the look."
SWAP_IS = "{replaced} is {who} in <Video 1>, selected for replacement."
SWAP_VIDEO_KEPT = (
@@ -99,7 +132,28 @@ SWAP_VIDEO_KEPT = (
)
SWAP_KEPT = "{replaced}: removed - replace {who} with {main} throughout."
ONE_GOES = "the original person"
THE_PERSON = "the person in the shot"
APPEARANCE_LINE = re.compile(r'^\s*@([1-4])\s+looks like\s+([^"\n]+?)\s*$', re.I)
# Two ways people type a swap that used to be dropped without a word, so the swap ran with no description and H3
# often gave the clip back: the looks sentence on the same line as the swap sentence, and the clothes on a line of
# their own ("@1 is wearing a black suit"). A looks sentence starts after a full stop, ! or ?; "Put @1 looks like a
# friend here." is one sentence and stays whole.
LOOKS_MID_LINE = re.compile(r"(?<=[.!?])[ \t]*(?=@[1-4]\s+looks like\b)", re.I)
WEARS_LINE = re.compile(r'^\s*@([1-4])\s+(?:is\s+wearing|wears|is\s+dressed\s+in|has\s+on)\s+([^"@\n]+?)\s*$', re.I)
QUOTE = re.compile(r'["\u201c\u201d]')
def looks_on_own_lines(text):
"""The script with each @N looks like sentence on a line of its own. A spoken line is left alone."""
text = str(text or "")
lines = []
for line in text.splitlines():
if QUOTE.search(line) or not LOOKS_MID_LINE.search(line):
lines.append(line)
continue
first, *rest = LOOKS_MID_LINE.sub("\n", line).splitlines()
lines += [re.sub(r"\s+([.,;:])$", r"\1", first), *rest]
return "\n".join(lines) if len(lines) != len(text.splitlines()) else text
# Hair and face only, no clothes, expression or background. When the line names clothes that differ from what the
@@ -115,6 +169,7 @@ def add_looks(text, jobs, describe):
"""A swap's script with an @N looks like line for each new person who has none, written by describe(slot), a
small picture-reading model shown that person's picture. Without such a line H3 kept the original person for the
first seconds (2026-11-07), so a connected model writes it when the user didn't."""
text = looks_on_own_lines(text)
typed = {int(match.group(1)) for match in map(APPEARANCE_LINE.match, text.splitlines()) if match}
for slot in sorted(jobs):
if jobs[slot] not in (PERSON, SHEET) or slot in typed:
@@ -137,8 +192,12 @@ def swap_appearances(text, jobs, video):
"""
if video != SWAP:
return text, {}
kept, descriptions = [], {}
for line in str(text or "").splitlines():
kept, descriptions, clothes = [], {}, {}
for line in looks_on_own_lines(text).splitlines():
worn = WEARS_LINE.fullmatch(line)
if worn and (jobs or {}).get(int(worn.group(1))) in (PERSON, SHEET):
clothes.setdefault(int(worn.group(1)), []).append(worn.group(2).strip().rstrip(" ."))
continue
match = APPEARANCE_LINE.fullmatch(line)
if match is None:
kept.append(line)
@@ -150,10 +209,18 @@ def swap_appearances(text, jobs, video):
raise ValueError(f"Picture {slot} must be a person or character sheet for a swap's looks like line.")
if slot in descriptions:
raise ValueError(f"Describe Picture {slot} once, in one looks like line.")
description = match.group(2).strip().rstrip(" .")
# A sentence on the looks line that names an @ again ("The trees behind @1 stay the same.") is not how
# the person looks: it goes back to the script as its own line, or H3 reads a raw @1 in the appearance.
sentences = re.split(r"(?<=[.!?])\s+", match.group(2).strip())
looks = [sentence for sentence in sentences if not TOKEN.search(sentence)]
kept.extend(sentence for sentence in sentences if TOKEN.search(sentence))
description = " ".join(looks).strip().rstrip(" .")
if not description:
raise ValueError(f"Say what Picture {slot}'s person looks like, or remove its looks like line.")
descriptions[slot] = description
for slot, worn in clothes.items():
# Clothes typed on their own line join the description; with none typed, the picture still gives the hair.
descriptions[slot] = f"{descriptions.get(slot, 'the same hair')}, wearing {' and '.join(worn)}"
return ("\n".join(kept), descriptions) if descriptions else (text, {})
@@ -204,23 +271,24 @@ CLOTHES_STAY = (
"attribute_transfer - apply only the face and hair to the original performance; the clothes of {who} in <Video 1> "
"stay as they are; the background of {picture} is not transferred."
)
KEEP_IS = (
"<Video 1> is the video being continued, and the target video starts from its last moment.\n"
"{main} is the main subject in <Video 1>, with the same look."
)
KEEP_KEPT = (
"<Video 1> (continuation point): fully_preserved - the place, the light, the colours and the camera carry on from its last moment.\n"
"{main} (appears in {shots}): fully_preserved - the look is retained."
)
KEEP_IS = "<Video 1> is the video being continued, and the target video starts from its last moment."
KEEP_MAIN = "{main} is the main subject in <Video 1>, with the same look."
KEEP_KEPT = "<Video 1> (continuation point): fully_preserved - the place, the light, the colours and the camera carry on from its last moment."
KEEP_KEPT_PLACE = "<Video 1> (continuation point): fully_preserved - the light, the colours and the camera carry on from its last moment."
KEEP_MAIN_KEPT = "{main} (appears in {shots}): fully_preserved - the look is retained."
SOUND_GOES_ON = "<Audio 1> is the soundtrack of <Video 1>, whose sound carries on in the target video."
SOUND_GOES_ON_KEPT = "<Audio 1>: reference - the sound continues without copying the source signal."
EDIT_IS = (
"<Video 1> supplies the place, the person, the action, the timing, the camera movement, the look and the sound.\n"
"{main} is the person in <Video 1>, kept as they are: the same face, hair, body and movements, with only what the script names changed."
)
EDIT_KEPT = (
"<Video 1>: partially_preserved - keep the place, the person, the action, the timing, the camera movement, the look and the sound; change only what the script names.\n"
"{main} (appears in {shots}): fully_preserved - the face, hair and every movement are retained; only what the script names changes."
EDIT_VIDEO = "<Video 1> supplies {supplies}."
EDIT_IS = "{main} is the person in <Video 1>, kept as they are: the same face, hair, body and movements, with only what the script names changed."
EDIT_VIDEO_KEPT = "<Video 1>: partially_preserved - keep {supplies}; change only what the script names."
EDIT_KEPT = "{main} (appears in {shots}): fully_preserved - the face, hair and every movement are retained; only what the script names changes."
# What a source video gives an edit, less what a connected picture takes over.
EDIT_SUPPLIES = ("the place", "the person", "the action", "the timing", "the camera movement", "the look", "the sound")
# A line that is about someone. An edit or a move copy of a clip with nobody in it (an empty hallway) names nobody.
NAMES_SOMEONE = re.compile(
r"@0|\b(?:he|she|him|her|his|hers|they|them|their|someone|somebody|anyone|everyone|person|people|man|men|woman|women|"
r"guy|girl|boy|kid|child|baby|dancer|singer|actor|actress)\b",
re.IGNORECASE,
)
REVOICE_IS = "<Video 1> is the source video for the target video edit.\n{main} is the person speaking in <Video 1>, with the same face, hair and clothing."
REVOICE_KEPT = (
@@ -229,6 +297,15 @@ REVOICE_KEPT = (
)
# A line only names who goes when it is a noun phrase like "the child in the seat", not an action or a pronoun.
NOUN_PHRASE = re.compile(r"^(?:the|a|an|this|that|these|those|his|her|their|everyone|someone|somebody|both|each|all)\b", re.I)
ACTION_WORD = re.compile(
r"\b(?:dances|walks|runs|talks|says|sits|stands|smiles|waves|jumps|enters|leaves|laughs|sings|eats|drinks|waits|"
r"is\s+\w+ing|are\s+\w+ing)\b",
re.I,
)
def who_goes_in(text):
"""Who a typed swap line says goes, without the rest of the line: "Elon is @1, he replaces the man at the
counter" is the man at the counter, and so is "Replace the man at the counter with @1."."""
@@ -244,7 +321,10 @@ def who_goes_in(text):
text = re.split(r"[.;!?]", text.strip(" .;!?"), maxsplit=1)[0]
text = NAMES_NEXT.sub("", text)
text = SAYS_WHO.sub("", TOKEN.sub("", text).strip(" .,;")).strip(" .,;")
return re.sub(r"\s+and$", "", text).strip(" .,;")
text = re.sub(r"\s+and$", "", text).strip(" .,;")
if not (replaces or plain) and not (NOUN_PHRASE.match(text) and not ACTION_WORD.search(text)):
return "" # "@1 dances" or "He dances" says what happens, not who goes.
return text
def lower_first(text):
@@ -274,7 +354,30 @@ class Picture:
def swapped_in(jobs):
"""How many people a swap puts in: one for each person or sheet picture."""
return max(1, sum(job in (PERSON, SHEET) for job in jobs.values()))
return max(1, sum(job in ACTORS for job in jobs.values()))
# A thing a line holds, wears or uses stays a prop; any other thing named in a line is the one doing the action.
HELD = re.compile(
r"\b(?:holds?|holding|carr(?:y|ies|ying)|wears?|wearing|puts? on|picks? up|uses?|using|grabs?|throws?|"
r"eats?|drinks?|with)\s+(?:\w+\s+){0,2}@(\d)\b",
re.IGNORECASE,
)
def things_that_perform(script, jobs, video):
"""A move copy or a swap with no person picture: a thing picture the lines make do the action (a cartoon hand
waving, a toy dancing) takes the moves, or comes in for the one in the video. With nothing typed, a swap's thing
comes in. A thing that is held or worn stays a thing."""
if video not in (MOVES, SWAP) or any(job in (PERSON, SHEET) for job in (jobs or {}).values()):
return jobs
held = {int(slot) for slot in HELD.findall(script or "")}
named = {int(slot) for slot in TOKEN.findall(script or "")}
jobs = dict(jobs)
for slot, job in jobs.items():
if job == THING and slot not in held and (slot in named or (video == SWAP and not named)):
jobs[slot] = PERFORMER
return jobs
def number_pictures(jobs, video=""):
@@ -295,15 +398,20 @@ class Cast:
self.pictures = pictures
self.video = video
last = max((picture.subject for picture in pictures), default=0)
self.people = [picture for picture in pictures if picture.job in (*ACTORS, START)]
self.moves = subject_label(last + 1) if video == MOVES else ""
# Nobody to give the moves to: the person in the video keeps them and is the main person.
self.own_moves = video == MOVES and not self.people
self.video_person = True # The video's own person is in the result; notice_people can say there is none.
# In a swap each person or sheet picture takes one person's place in the video, in picture order. The script
# can name who goes: "the child in the seat", or "@1 the man on the left. @2 the woman in red".
self.swappers = [picture for picture in pictures if picture.job in (PERSON, SHEET)] if video == SWAP else []
self.swappers = [picture for picture in pictures if picture.job in ACTORS] if video == SWAP else []
goes = len(self.swappers)
self.whos = [f"the person on the {spot}" for spot in SPOTS[goes]] if goes > 1 else [ONE_GOES]
self.replaced = subject_label(1) if video == SWAP else ""
self.in_video = subject_label(last + 1) if video in (KEEP, REVOICE, EDIT) else ""
self.people = [picture for picture in pictures if picture.job in (PERSON, SHEET, START)]
self.in_video = subject_label(last + 1) if video in (KEEP, REVOICE, EDIT) or self.own_moves else ""
if video == KEEP and self.people: # A person picture is the main person; the video adds no second subject.
self.in_video = ""
self.subjects = {picture.slot: subject_label(picture.subject) for picture in pictures if picture.subject}
self.clip_clothes = False # A swap that keeps the clothes of whoever goes.
self.appearances = {} # Explicit looks-like lines, by the visible replacement picture slot.
@@ -311,6 +419,29 @@ class Cast:
self.speaks_as_video = False # With that sound and no words typed: the new person says what the video says.
self.typed_lines = False # The script typed words in quotes for someone to say.
def notice_people(self, text):
"""An edit or a move copy with no person picture keeps the video's person only when the lines are about
someone, or something is put on them. A clip of an empty hallway gets no made-up person."""
if self.video == KEEP:
if not self.people and (text or "").strip():
self.video_person = bool(NAMES_SOMEONE.search(text))
elif self.video == EDIT or self.own_moves:
self.video_person = bool(self.of(OUTFIT) or NAMES_SOMEONE.search(text or ""))
@property
def supplies(self):
"""What the source video of an edit still gives: a place picture brings the place and its look, a style
picture the look."""
gone = set()
if self.of(PLACE):
gone |= {"the place", "the look"}
if self.of(STYLE):
gone.add("the look")
if not self.video_person:
gone.add("the person")
items = [item for item in EDIT_SUPPLIES if item not in gone]
return ", ".join(items[:-1]) + " and " + items[-1]
def of(self, *jobs):
return [picture for picture in self.pictures if picture.job in jobs]
@@ -356,12 +487,32 @@ class Cast:
@property
def main(self):
"""Who a line is about when it names nobody."""
if self.in_video:
if self.in_video and self.video_person:
return self.in_video
if self.people:
return subject_label(self.people[0].subject)
return next(iter(self.subjects.values()), subject_label(1))
@property
def main_in_shot(self):
"""Whether main is a person or thing the clip defines, so "<Subject N> is in the shot" can name it."""
if self.in_video and self.video_person and self.main == self.in_video:
return True
defined = {subject_label(picture.subject) for picture in self.of(*ACTORS, THING, START)}
return self.main in defined
def unclear_speaker(self, moments):
"""A refusal when two or more people are connected and a spoken line does not say which one speaks."""
if self.video not in ("", MOVES, KEEP) or len(self.people) < 2:
return ""
people = {picture.slot for picture in self.people}
for moment in moments:
if moment.speech and not moment.voice and not moment.voiceover:
if not any(int(slot) in people for slot in TOKEN.findall(moment.text)):
count = "two people" if len(self.people) == 2 else "more than one person"
return f'With {count}, name who speaks: @{self.people[1].slot} says "hello".'
return ""
@property
def opens(self):
return next(iter(self.of(START)), None)
@@ -378,9 +529,15 @@ class Cast:
if not self.pictures and not self.video:
return NOTHING_IN
if self.video in NEEDS_A_PERSON and not self.people:
if self.of(OUTFIT, THING):
if self.of(OUTFIT):
return DRESS_THE_VIDEO_PERSON
if self.of(THING):
return SWAP_NEEDS_PERSON_THING
if self.of(PLACE):
return SWAP_NEEDS_PERSON_PLACE
return NEEDS_A_PERSON[self.video]
if self.video == REVOICE and self.of(PERSON, SHEET):
return REVOICE_KEEPS_PERSON
typed = sorted({int(number) for number in TOKEN.findall(text)} - {0})
slots = {picture.slot: picture for picture in self.pictures}
for slot in typed:
@@ -389,16 +546,23 @@ class Cast:
if slots[slot].job == END:
return f"Picture {slot} is where the clip ends, so @{slot} can't be in a line. Say what happens on the way there."
if typed:
for picture in self.of(PERSON, SHEET, THING, OUTFIT):
if picture.slot not in typed:
return f"Picture {picture.slot} is on, but no line names @{picture.slot}."
for picture in self.of(*ACTORS, THING, OUTFIT):
if picture.slot in typed:
continue
# The only person picture is who "He" or "She" means.
if picture.job in (PERSON, SHEET) and len(self.of(PERSON, SHEET)) == 1 and HE_SHE.search(text):
continue
hint = f' Type who wears it, like "He wears @{picture.slot}."' if picture.job == OUTFIT else ""
return f"Picture {picture.slot} is on, but no line names @{picture.slot}.{hint}"
return ""
def wearers(self, moments):
"""Who wears each outfit: the person named just before it, or else the main person."""
found = {}
outfits = {subject_label(picture.subject) for picture in self.of(OUTFIT)}
default = THE_PERSON if self.main in outfits else self.main # An outfit is never worn by itself.
for picture in self.of(OUTFIT):
found[picture.slot] = self.main
found[picture.slot] = default
token = f"@{picture.slot}"
for moment in moments:
before = moment.text.partition(token)[0]
@@ -414,7 +578,9 @@ class Cast:
ends = self.ends
lines = []
if self.video == EDIT:
lines.append(EDIT_IS.format(main=self.in_video))
lines.append(EDIT_VIDEO.format(supplies=self.supplies))
if self.video_person:
lines.append(EDIT_IS.format(main=self.in_video))
if self.video == SWAP:
lines.append(SWAP_VIDEO)
lines += [SWAP_IS.format(replaced=gone, who=who) for gone, who, _ in self.swaps]
@@ -445,10 +611,17 @@ class Cast:
lines.append(FIRST_FRAME.format(picture=picture_label(self.opens.picture)))
if ends:
lines.append(LAST_FRAME.format(picture=picture_label(ends.picture), last=last))
if self.moves:
if self.own_moves and not self.video_person:
lines.append("<Video 1> provides the camera movement.")
elif self.own_moves:
clothes = "" if self.of(OUTFIT) else " and clothes,"
lines.append(OWN_MOVES_ARE.format(main=self.in_video, clothes=clothes or ","))
elif self.moves:
lines.append(MOVES_ARE.format(moves=self.moves))
if self.video == KEEP:
lines.append(KEEP_IS.format(main=self.in_video))
lines.append(KEEP_IS)
if self.in_video and self.video_person:
lines.append(KEEP_MAIN.format(main=self.in_video))
if self.video == REVOICE:
lines.append(REVOICE_IS.format(main=self.in_video))
return "\n".join(lines)
@@ -458,7 +631,7 @@ class Cast:
subject = subject_label(picture.subject)
label = picture_label(picture.picture)
wearing = [slot for slot, wearer in wearers.items() if wearer == subject]
if self.video == SWAP and picture.job in (PERSON, SHEET):
if self.video == SWAP and picture.job in ACTORS:
if self.clip_clothes:
return CLOTHES_STAY.format(who=self.goes_for(picture), picture=label)
return SWAPPED.format(picture=label)
@@ -467,9 +640,9 @@ class Cast:
elif picture.job == PERSON and wearing:
words = DRESSED[1].format(outfit=self.subjects[wearing[0]])
else:
wearer = wearers.get(picture.slot, self.main)
wearer = wearers.get(picture.slot, THE_PERSON if picture.job == OUTFIT else self.main)
words = JOB_WORDS[picture.job][1].format(wearer=wearer)
if picture.job in (PERSON, SHEET, THING):
if picture.job in (*ACTORS, THING):
words += " " + BACKGROUND.format(picture=label)
return words
@@ -482,7 +655,9 @@ class Cast:
lines = []
if self.video == EDIT:
lines.append(EDIT_KEPT.format(main=self.in_video, shots=shot_list(seen(self.in_video))))
lines.append(EDIT_VIDEO_KEPT.format(supplies=self.supplies))
if self.video_person:
lines.append(EDIT_KEPT.format(main=self.in_video, shots=shot_list(seen(self.in_video))))
if self.video == SWAP:
lines.append(SWAP_VIDEO_KEPT.format(people="people" if len(self.swaps) > 1 else "person"))
lines += [SWAP_KEPT.format(replaced=gone, who=who, main=new) for gone, who, new in self.swaps]
@@ -496,10 +671,25 @@ class Cast:
lines.append(FIRST_KEPT.format(picture=picture_label(self.opens.picture)))
if self.ends:
lines.append(LAST_KEPT.format(picture=picture_label(self.ends.picture), last=len(shots)))
if self.moves:
if self.own_moves and not self.video_person:
places = [self.subjects[picture.slot] for picture in self.of(PLACE)]
place = OWN_PLACE_FROM.format(place=places[0]) if places else OWN_PLACE_KEPT
lines.append(f"<Video 1>: attribute_transfer - apply only its camera movement to the target scene; {place}")
elif self.own_moves:
outfits = [self.subjects[picture.slot] for picture in self.of(OUTFIT)]
kept = (
f"partially_preserved - the face, hair, body, moves and timing are retained, and the clothes change to {outfits[0]}."
if outfits else "fully_preserved - the face, hair, body, clothes, moves and timing are retained."
)
places = [self.subjects[picture.slot] for picture in self.of(PLACE)]
place = OWN_PLACE_FROM.format(place=places[0]) if places else OWN_PLACE_KEPT
lines.append(OWN_MOVES_KEPT.format(main=self.in_video, shots=shot_list(seen(self.in_video)), kept=kept, place=place))
elif self.moves:
lines.append(MOVES_KEPT.format(moves=self.moves, shots=shot_list(seen(self.main)), main=self.main))
if self.video == KEEP:
lines.append(KEEP_KEPT.format(main=self.in_video, shots=shot_list(seen(self.in_video))))
lines.append(KEEP_KEPT_PLACE if self.of(PLACE) else KEEP_KEPT)
if self.in_video and self.video_person:
lines.append(KEEP_MAIN_KEPT.format(main=self.in_video, shots=shot_list(seen(self.in_video))))
if self.video == REVOICE:
lines.append(REVOICE_KEPT.format(main=self.in_video, shots=shot_list(seen(self.in_video))))
return "\n".join(lines)
+11 -4
View File
@@ -13,7 +13,7 @@ import re
import numpy as np
from ._h3_cast_helpers import EDIT, KEEP, NEEDS_NO_WORDS, ONE_GOES, REVOICE, SWAP, Cast, number_pictures, swap_appearances
from ._h3_cast_helpers import TOKEN
from ._h3_cast_helpers import TOKEN, things_that_perform
from ._h3_script_helpers import (
ACTION_GOES_ON,
PRONOUN,
@@ -78,9 +78,10 @@ def one_line(text):
def clean_words(text):
"""Spoken words: one line, no tags, ending the way H3 wants a line to end."""
text = one_line(text).replace("<", "").replace(">", "")
if text and text[-1] not in ".?!":
text += "."
# '"Hi," she says' is "Hi.", not "Hi,.". Chinese and Japanese lines end in their own stops: "。", not "。.".
text = one_line(text).replace("<", "").replace(">", "").rstrip(" ,;:,、;:")
if text and text[-1] not in ".?!。?!…":
text += "。" if re.search(r"[\u3040-\u30ff\u4e00-\u9fff]", text) else "."
return text
@@ -312,6 +313,7 @@ def write_prompt(script, seconds=15.0, camera="", look="", sound="", language="E
longest) puts a question to a small model, if one is connected: it fills in
a one-line idea and the sound of the place."""
parts = split_sections(script)
written = parts is None # Words someone typed in six parts go through as they are.
audio = next_label(script, "Audio")
speaker = None
@@ -319,10 +321,13 @@ def write_prompt(script, seconds=15.0, camera="", look="", sound="", language="E
jobs = jobs if jobs is not None else {1: "person"}
if video == EDIT:
script, jobs = put_on_from_pictures(script, jobs)
jobs = things_that_perform(script, jobs, video)
cast = Cast(number_pictures(jobs, video), video)
script, cast.appearances = swap_appearances(script, jobs, video)
scene = read_script(script)
cast.notice_people(" ".join(moment.text for moment in scene.moments))
problem = cast.problem(" ".join(moment.text for moment in scene.moments))
problem = problem or cast.unclear_speaker(scene.moments)
if problem:
raise ValueError(problem)
if not scene.moments and video == EDIT:
@@ -370,6 +375,8 @@ def write_prompt(script, seconds=15.0, camera="", look="", sound="", language="E
scene, seconds, camera=camera, look=look, sound=sound, say=say, cast=cast, sounds=not keeps_song, soundtrack=soundtrack
)
if written and (video == EDIT or (video == SWAP and clip_sound)): # The clip's own sound stays in the result.
parts["summary"] = add_task(parts["summary"], "audio reuse")
if voice:
add_voice(parts, voice_label, speaker)
if song_beats is not None and voice:
+69 -21
View File
@@ -17,15 +17,19 @@ from ._h3_cast_helpers import (
MAIN,
OUTFIT,
PERSON,
PERFORMER,
PLACE,
REVOICE,
SHEET,
START as START_JOB,
END as END_JOB,
STYLE,
SWAP,
SOUND_GOES_ON,
SOUND_GOES_ON_KEPT,
THING,
TOKEN,
things_that_perform,
ONE_GOES,
SPOTS,
Cast,
@@ -43,7 +47,9 @@ THEN = r"(?:,?\s*(?:and\s+)?then\b|,?\s*and\s+after\s+that\b|,?\s*after\s+that\b
# A word that starts a new moment and stays in it.
TURN = r"(?=,?\s*\b(?:suddenly|all\s+of\s+a\s+sudden|out\s+of\s+nowhere|finally|at\s+last|(?:hard\s+)?cut\s+to|(?:it\s+|and\s+|(?<!\bit\s))ends?\s+(?:with|on|in|as)|ending\s+(?:with|on|in))\b)"
# Where a line breaks into sentences: a full stop that is not a title, the end of a quote, or a semicolon.
SENTENCE = r"(?<!\bMr\.)(?<!\bMs\.)(?<!\bDr\.)(?<!\bSt\.)(?<!\bMrs\.)(?<=[.!?])\s+(?=\S)|(?<=\x00)\s+(?=[A-Z])|\s*;\s*"
# After a quote, a new sentence starts with a capital or an @: in '"Get a job." @1 looks up' the @1 is a new moment,
# or its own words are lost behind the first quote's. So is '"Hi" and @2 says "Bye"': one moment holds one quote.
SENTENCE = r"(?<!\bMr\.)(?<!\bMs\.)(?<!\bDr\.)(?<!\bSt\.)(?<!\bMrs\.)(?<=[.!?])\s+(?=\S)|(?<=\x00)\s+(?=[A-Z@])|(?<=\x00),?\s+(?:and|but|while)\s+(?=@\d)|\s*;\s*"
CUT_WORDS = re.compile(r"^(?:hard\s+)?(?:cut|cuts|smash\s+cut|jump\s+cut)\s+to\b[:,]?\s*", re.I)
NEW_SHOT = re.compile(r"^(?:new\s+shot|next\s+shot|shot\s+\d+)\b[:,.\-]?\s*", re.I)
START = re.compile(r"^(?:it\s+|the\s+(?:clip|video|scene|shot)\s+)?(?:starts?|begins?|opens?)(?:\s+(?:with|on|in|at|as)\b[:,]?|\s*:)\s*", re.I)
@@ -110,6 +116,30 @@ SOUND_WORDS = 22
NAMED = {PLACE: "the place", OUTFIT: "the outfit", THING: "the thing"} # What @2 reads as to the small model.
WORDS_A_SECOND = 3 # How fast H3 speaks.
# Words that trail off ("I never thought...") keep going: across the next cut, or past the end of the clip.
TRAILS_OFF = re.compile(r"(?:\.\.\.|\u2026|\u2014|--)\s*$")
LINE_CARRIES = "<scenetrans> The line from the previous shot continues seamlessly across the cut, and the words are not repeated."
CUT_OFF = "The line is cut off by the end of the video. <cutoff>"
def speech_runs_on(script, seconds):
"""(carried, cut_off): the moments whose words go on across the next cut, and the last moment's words if the
clip ends mid-line. Words carry on when they trail off with "..." or need more time than their shot has."""
starts = timeline(script, seconds)
ends = [*starts[1:], seconds]
carried, cut_off = set(), None
for index, moment in enumerate(script.moments):
if not moment.speech:
continue
trails = bool(TRAILS_OFF.search(moment.speech))
long = len(moment.speech.split()) / WORDS_A_SECOND > ends[index] - starts[index] + 0.5
following = script.moments[index + 1] if index + 1 < len(script.moments) else None
if following is not None and following.cut and not script.one_take and (trails or long):
carried.add(index)
elif following is None and trails:
cut_off = index
return carried, cut_off
HOLD = f"{MAIN} holds still" # What fills the time before a first moment set later.
KEEP_LOOK = "The target video keeps the look, the light and the colours of {picture}."
KEEP_COLOURS = "The target video keeps the colours and the film grain of {picture}."
@@ -130,6 +160,7 @@ OPENS_ON = "The shot begins from {picture}."
ENDS_ON = "The shot ends on {picture}."
ON_SHEET = "{subject} appears once, without the panels, labels or other views of {picture}."
THE_MOVES = "{main} performs the same moves as {moves}, at the same timing."
OWN_MOVES = "{main} moves exactly as in <Video 1>, at the same timing."
IN_THE_PLACE = "The shot takes place in {place}."
WEARS = "{wearer} wears {outfit}."
IN_THE_SHOT = "{main} is in the shot."
@@ -142,10 +173,10 @@ SAYS_NOTHING = "{main} keeps the lips closed and says nothing the whole time."
SPEAKS_AS_VIDEO = "{main} speaks as in <Video 1>, each word landing exactly on the lip movement of <Video 1>."
CLIP_SOUND = "The original sound of <Video 1> continues throughout."
FOLLOWS_CAMERA = "The camera follows the movement of <Video 1>."
REST_AS_VIDEO = "Everything else stays as it is in <Video 1>."
SAME_AS_VIDEO = "{main} has the same words, mouth movements and moves as in <Video 1>. Everything else stays as it is in <Video 1>."
CARRIES_ON = "The shot carries straight on from the end of <Video 1>."
ACTION_GOES_ON = "The action keeps going the way it was heading, and the camera keeps moving the same way."
FACES_US = "{main} faces the camera as in <Video 1>."
VIDEO_LOOKS = {
SWAP: "Retain the look of <Video 1>.",
KEEP: "The target video keeps the look, colours and camera of <Video 1>.",
@@ -557,12 +588,13 @@ def script_warning(script, seconds, cast=None):
if any((moment.at or 0.0) >= seconds for moment in script.moments):
return f"A moment starts after the clip ends, at {seconds:g} seconds."
starts = timeline(script, seconds)
for moment, start, end in zip(script.moments, starts, [*starts[1:], seconds]):
carried, cut_off = speech_runs_on(script, seconds)
for index, (moment, start, end) in enumerate(zip(script.moments, starts, [*starts[1:], seconds])):
unseen = UNSEEN.search(without_speech(moment))
if unseen:
return f'A camera can\'t see "{unseen.group(0).lower()}". Say what we would see, like "she smiles".'
takes = len(moment.speech.split()) / WORDS_A_SECOND
if takes > end - start + 0.5:
if takes > end - start + 0.5 and index not in carried and index != cut_off:
return f"A spoken line takes about {takes:.0f} seconds to say, and its moment has {end - start:.0f}. Give it more room."
return ""
@@ -585,6 +617,7 @@ def script_report(text, seconds, jobs=None, video=""):
}
for moment, start, end in zip(script.moments, starts, ends)
]
jobs = things_that_perform(text, jobs, video) if jobs is not None else None
cast = Cast(number_pictures(jobs, video), video) if jobs is not None else None
return {"moments": moments, "seconds": seconds, "warning": script_warning(script, seconds, cast)}
@@ -732,6 +765,8 @@ def before_the_action(number, text, cast, wearers):
# or for the whole clip at Fast preview; with it the new
# person is there from the first frame. An @1 looks like line only adds its own words.
looks = (f"has the defined appearance from {picture_label(picture.picture)}: {appearance}" if appearance
else f"has the shape, colours and drawing style of the character in {picture_label(picture.picture)}"
if picture.job == PERFORMER
else f"has the face, hair and clothes of the person in {picture_label(picture.picture)}")
notes.append(
f"{new} occupies the starting position of {who} and follows the same route, movements, timing and pace. "
@@ -749,8 +784,6 @@ def before_the_action(number, text, cast, wearers):
notes.append((OWN_LINES_ONLY if f"{new} (S" in text else SAYS_NOTHING).format(main=new))
if number == 1 and cast.video == KEEP:
notes += [CARRIES_ON]
if number == 1 and cast.video == REVOICE:
notes += [FACES_US.format(main=cast.main)]
places = [subject_label(picture.subject) for picture in cast.of(PLACE)]
if places and not any(place in text for place in places):
notes.append(IN_THE_PLACE.format(place=places[0]))
@@ -760,7 +793,8 @@ def before_the_action(number, text, cast, wearers):
notes.append(sentence(", ".join(spots[:-1]) + f" and {spots[-1]} of the frame"))
for slot, wearer in wearers.items():
outfit = cast.subjects[slot]
if outfit not in text and (wearer in people or wearer in text):
# An edit has no person picture: the person in the video wears an outfit that no line names.
if outfit not in text and (wearer in people or wearer in text or (cast.video == EDIT and wearer == cast.in_video)):
notes.append(WEARS.format(wearer=wearer, outfit=outfit))
return notes
@@ -768,10 +802,10 @@ def before_the_action(number, text, cast, wearers):
def after_the_action(text, cast):
"""What H3 needs to hear about a shot once its action has been said."""
notes = []
if cast.moves and cast.main in text:
notes.append(THE_MOVES.format(main=cast.main, moves=cast.moves))
if cast.moves and cast.video_person and cast.main in text:
notes.append(OWN_MOVES.format(main=cast.main) if cast.own_moves else THE_MOVES.format(main=cast.main, moves=cast.moves))
if cast.video == EDIT:
notes.append(SAME_AS_VIDEO.format(main=cast.main))
notes.append(SAME_AS_VIDEO.format(main=cast.main) if cast.video_person else REST_AS_VIDEO)
if cast.video in (SWAP, EDIT):
notes.append(FOLLOWS_CAMERA)
for picture in cast.of(SHEET):
@@ -799,6 +833,7 @@ def shot_lines(script, seconds, say, cast, wearers, move="", hold="", sounds=Tru
talking = speakers(script.moments, cast)
quiet = " ".join(QUIET.format(speaker=speaker) for speaker in talking if speaker.startswith("<"))
kept = still_true(script.moments)
carried, cut_off = speech_runs_on(script, seconds)
lines = []
for number, shot in enumerate(shots_of(script), 1):
shot_camera = script.moments[shot[0]].camera
@@ -841,8 +876,17 @@ def shot_lines(script, seconds, say, cast, wearers, move="", hold="", sounds=Tru
*([hold] if number > 1 else []),
capital(script.moments[first].sound) if script.moments[first].sound and not script.silent else "",
]
lines.append(f"[Shot {number}] " + " ".join(part for part in body if part))
if not any(cast.main in line for line in lines):
line = " ".join(part for part in body if part)
if shot[0] - 1 in carried:
# The speaker is mid-line as the shot opens, so the mouth is not closed here.
line = f"{LINE_CARRIES} " + re.sub(r" ?<Subject \d+> stays silent with the lips closed\.", "", line, count=1)
if shot[-1] in carried:
# The speaker is still talking at the cut, so the mouth does not close here.
line = re.sub(r" <Subject \d+> closes the lips\.", "", line) + " <scenetrans>"
if shot[-1] == cut_off:
line = re.sub(r" <Subject \d+> closes the lips\.", "", line) + f" {CUT_OFF}"
lines.append(f"[Shot {number}] " + line)
if cast.video_person and cast.main_in_shot and not any(cast.main in line for line in lines):
lines[0] = lines[0].replace("[Shot 1] ", f"[Shot 1] {IN_THE_SHOT.format(main=cast.main)} ", 1)
return lines
@@ -881,16 +925,19 @@ def summary_of(script, cast, new_places, soundtrack):
return f"[{task}] {changes} Everything else in <Video 1> is kept."
if cast.video == KEEP:
tag = f"{task} + audio reference" if soundtrack else task
return f"[{tag}] The target video continues directly from the end of <Video 1> in the same place."
opening = with_labels(without_speech(script.moments[0]), cast) or f"{cast.main} speaks"
where = "" if cast.of(PLACE) else " in the same place"
return f"[{tag}] The target video continues directly from the end of <Video 1>{where}."
talking = [who for who in speakers(script.moments, cast) if who.startswith("<")]
who_speaks = f"{' and '.join(talking)} speak" if len(talking) > 1 else f"{cast.main} speaks"
opening = with_labels(without_speech(script.moments[0]), cast) or who_speaks
later = [with_labels(without_speech(script.moments[shot[0]]), cast) for shot in shots_of(script)[1:]]
if cast.opens and cast.ends:
moving = f"moving from {picture_label(cast.opens.picture)} to {picture_label(cast.ends.picture)}"
return f"[{task}] In the target video, {lower_first(opening.rstrip('.!? '))}, {moving}."
summary = f"[{task}] In the target video, {lower_first(sentence(opening))}"
summary += "".join(f" {AND_THEN.format(line=lower_first(sentence(line)))}" for line in later if line)
if cast.moves:
summary += " " + THE_MOVES.format(main=cast.main, moves=cast.moves)
if cast.moves and cast.video_person:
summary += " " + (OWN_MOVES.format(main=cast.main) if cast.own_moves else THE_MOVES.format(main=cast.main, moves=cast.moves))
return f"{summary} {EVERY_PLACE}" if new_places else summary
@@ -916,14 +963,15 @@ def script_parts(script, seconds, camera="", look="", sound="", say=None, cast=N
cuts = [script.moments[shot[0]] for shot in shots_of(script)[1:]]
moved = any(not FRAME_WORDS.match(without_speech(moment)) for moment in cuts)
new_places = last > 1 and not cast.of(PLACE) and moved and all(not FRAME_WORDS.match(without_speech(moment)) for moment in cuts)
first = next(iter(cast.of(PLACE) or cast.pictures), None)
if not style and cast.video == EDIT:
# Only a place, a start frame or a person sets the look; an outfit, a thing or a style never does.
first = next(iter(cast.of(PLACE) or cast.of(START_JOB) or cast.of(PERSON, SHEET, PERFORMER, END_JOB)), None)
if not style and cast.video == EDIT and not cast.of(PLACE):
style = VIDEO_LOOKS[EDIT]
if not style and len(cast.of(PLACE)) > 1:
style = OWN_COLOURS
elif not style and not (first and first.job == THING):
elif not style and (first or cast.video in VIDEO_LOOKS):
words = KEEP_LOOK if cast.opens else KEEP_COLOURS
style = VIDEO_LOOKS.get(cast.video) or words.format(picture=picture_label(first.picture if first else 1))
style = (cast.video != EDIT and VIDEO_LOOKS.get(cast.video)) or words.format(picture=picture_label(first.picture if first else 1))
takes = [EVERY_PLACE] if new_places else []
if last == 1 and (len(script.moments) > 1 or cast.moves or script.one_take):
takes = [ONE_SHOT]
@@ -947,7 +995,7 @@ def script_parts(script, seconds, camera="", look="", sound="", say=None, cast=N
"subject_definitions": subjects,
"summary": summary_of(script, cast, new_places, soundtrack),
"retention_analysis": kept,
"detailed_description": "\n".join([" ".join(part for part in (style, move, *takes) if part), *lines]),
"detailed_description": "\n".join([*[" ".join(part for part in (style, move, *takes) if part)] * bool(style or move or takes), *lines]),
"overall_soundscape": ambience,
"non_diegetic_music": tune,
}
+25 -6
View File
@@ -40,6 +40,9 @@ OUTSIDE = (
"Image Folder reads only folders inside ComfyUI's input or output folder. "
"Drop your folder on the node, or press Add, and its pictures are copied in."
)
# A drive ("D:") in any part of a folder name, and control characters.
_DRIVE = re.compile(r"^[A-Za-z]:")
_CONTROL = re.compile(r"[\x00-\x1f\x7f]")
NO_FOLDER = 'Image Folder: there is no folder "{folder}" in ComfyUI\'s {source} folder.'
NO_PICTURES = 'Image Folder: no pictures in "{folder}". Add some, or choose another folder.'
NONE_LEFT = "Image Folder: none of the picked pictures are in the folder anymore. Pick again on the node."
@@ -64,7 +67,9 @@ def clean_folder(folder) -> str:
if text.startswith("/") or text.startswith("~") or re.match(r"^[A-Za-z]:", text):
raise ValueError(OUTSIDE)
parts = [part for part in text.split("/") if part not in ("", ".")]
if any(part == ".." for part in parts):
# ".." climbs out; a drive in any part ("a/D:/x") jumps to another drive
# on Windows; a control character is never part of a folder name.
if any(part == ".." or _DRIVE.match(part) for part in parts) or _CONTROL.search(text):
raise ValueError(OUTSIDE)
return "/".join(parts)
@@ -82,9 +87,10 @@ def place_inside(folder, roots: dict) -> tuple[str, str] | None:
This compares text only. A path that is outside those folders is never
looked up on disk, and one on another machine is refused from its text."""
text = str(folder or "").strip().strip('"').replace("\\", "/")
if not looks_full(text) or text.startswith("//"):
# A "~" path is not expanded: only a path written out in full can match.
if not looks_full(text) or text.startswith("//") or text.startswith("~"):
return None
full = os.path.normpath(os.path.expanduser(text))
full = os.path.normpath(text)
for source, root in roots.items():
for base in {os.path.normpath(str(root)), os.path.realpath(str(root))}:
if full == base:
@@ -94,14 +100,27 @@ def place_inside(folder, roots: dict) -> tuple[str, str] | None:
return None
def inside_root(top: Path, relative: str) -> Path:
"""`relative` below the resolved root `top`, as a resolved path. It is
checked as text before the disk is asked to resolve it, and again after,
so a link that leads out of the root is refused too."""
if not relative:
return top
lexical = top.joinpath(*relative.split("/"))
if top not in lexical.parents:
raise ValueError(OUTSIDE)
target = lexical.resolve()
if target != top and top not in target.parents:
raise ValueError(OUTSIDE)
return target
def safe_folder(root, folder, source: str = "input") -> Path:
"""The folder as a real path below `root`. A link that leads out of the
root is refused like any other way out."""
relative = clean_folder(folder)
top = Path(root).resolve()
target = top.joinpath(*relative.split("/")).resolve() if relative else top
if target != top and top not in target.parents:
raise ValueError(OUTSIDE)
target = inside_root(top, relative)
if not target.is_dir():
raise ValueError(NO_FOLDER.format(folder=relative, source=source))
return target
+45 -12
View File
@@ -6,18 +6,26 @@ that are wanted: they are copied into the output folder under the names the
node would have given them. Everything here works from names this module
made itself; the only thing a caller sends is the run's token and which
pictures to keep.
What a run holds (its settings, its count, what was kept) stays in this
process's memory, never in a file. ComfyUI's temp folder takes uploads, so a
list read back from there could be anyone's. The held pictures themselves
are named from the token, their number and one of the node's own formats,
and must still be in the held folder when they are copied.
"""
from __future__ import annotations
from collections import OrderedDict
from datetime import datetime
import json
from pathlib import Path
import re
import secrets
import shutil
import threading
from ._image_save_helpers import (
FORMAT_EXTENSIONS,
IMAGE_SAVE_LOCK,
existing_action,
name_stem,
@@ -34,6 +42,14 @@ from ._image_save_helpers import (
HELD_FOLDER = "ausboss_held"
_TOKEN = re.compile(r"^[0-9a-f]{16}$")
GONE = "These pictures are no longer held. Run the workflow again."
# The held pictures' formats: the extensions Save Image writes, nothing else.
HELD_EXTENSIONS = frozenset(FORMAT_EXTENSIONS.values())
# A run holds at most this many pictures, and the server remembers this many
# runs; the oldest is forgotten first and then says GONE.
MAX_HELD_PICTURES = 10000
MAX_HELD_RUNS = 256
_RUNS: "OrderedDict[str, dict]" = OrderedDict()
_RUNS_LOCK = threading.Lock()
def plan_destinations(settings: dict, count: int, now: datetime, root: Path, output_root: Path, picks=None):
@@ -88,15 +104,31 @@ def settle_destinations(planned, has_caption: bool, output_root: Path) -> list[s
def _held_name(token: str, index: int, extension: str) -> str:
if not _TOKEN.match(token) or extension not in HELD_EXTENSIONS or not 0 <= index < MAX_HELD_PICTURES:
raise ValueError("Save Image: that is not a picture it is holding.")
return f"{token}_{index:03d}.{extension}"
def _held_source(folder: Path, token: str, index: int, extension: str) -> Path:
"""A held picture's file, which must still sit directly in the held folder."""
source = folder / _held_name(token, index, extension)
if not source.is_file() or source.is_symlink() or source.resolve().parent != folder.resolve():
raise LookupError(GONE)
return source
def hold_pictures(temp_root, frames, settings: dict, encode) -> tuple[str, list[dict]]:
"""Write a run's pictures to the temp folder and remember how to name them.
`encode(path, frame)` writes one picture in the run's format. Returns
the run's token and the entries the node shows them from.
"""
frames = list(frames)
if len(frames) > MAX_HELD_PICTURES:
raise ValueError(
f"Save Image: {len(frames)} pictures are too many to hold (at most {MAX_HELD_PICTURES}). "
"Turn Auto save on to save them straight away."
)
folder = Path(temp_root) / HELD_FOLDER
folder.mkdir(parents=True, exist_ok=True)
token = secrets.token_hex(8)
@@ -105,8 +137,10 @@ def hold_pictures(temp_root, frames, settings: dict, encode) -> tuple[str, list[
name = _held_name(token, index, settings["extension"])
encode(folder / name, frame)
previews.append({"filename": name, "subfolder": HELD_FOLDER, "type": "temp"})
manifest = dict(settings, count=len(previews), kept={})
(folder / f"{token}.json").write_text(json.dumps(manifest), encoding="utf-8")
with _RUNS_LOCK:
_RUNS[token] = dict(settings, count=len(previews), kept={})
while len(_RUNS) > MAX_HELD_RUNS:
_RUNS.popitem(last=False)
return token, previews
@@ -119,16 +153,18 @@ def keep_pictures(temp_root, output_root, token, picks=None, now: datetime | Non
if not isinstance(token, str) or not _TOKEN.match(token):
raise ValueError("Save Image: that is not a run it is holding.")
folder = Path(temp_root) / HELD_FOLDER
manifest_path = folder / f"{token}.json"
if not manifest_path.is_file():
with _RUNS_LOCK:
manifest = _RUNS.get(token)
if manifest is None:
raise LookupError(GONE)
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
count = int(manifest["count"])
kept = {int(index): str(path) for index, path in dict(manifest.get("kept") or {}).items()}
kept = dict(manifest["kept"])
if picks is None:
wanted = list(range(count))
else:
if len(picks) > MAX_HELD_PICTURES:
raise ValueError("Save Image: that picture is not in this run.")
wanted = []
for pick in picks:
if isinstance(pick, bool) or not isinstance(pick, int) or not 0 <= pick < count:
@@ -151,17 +187,14 @@ def keep_pictures(temp_root, output_root, token, picks=None, now: datetime | Non
if action == "skip":
skipped.append(index)
continue
source = folder / _held_name(token, index, manifest["extension"])
if not source.is_file():
raise LookupError(GONE)
source = _held_source(folder, token, index, manifest["extension"])
path.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(source, path)
if has_caption:
sidecar_path(path).write_text(caption, encoding="utf-8")
kept[index] = path.resolve().relative_to(resolved_root).as_posix()
saved.append(index)
manifest["kept"] = {str(index): path for index, path in kept.items()}
manifest_path.write_text(json.dumps(manifest), encoding="utf-8")
manifest["kept"] = kept
return {
"count": count,
"saved": [{"index": index, "path": kept[index]} for index in saved],
+180 -5
View File
@@ -653,10 +653,13 @@ def apply_stitch(
exact with the toggle off, since the spread deliberately rewrites the
feathered band.
``color_match`` (0..1) shifts the patch's tone by the offset measured
in the feathered band (:func:`estimate_tone_offset`) before blending,
so an outpaint whose new bands came out a touch lighter or warmer than
the picture lands on the picture's own tone. 0 leaves the patch alone.
``color_match`` (0..1) shifts the patch's tone by the measured drift
before blending, so a new area that came out a touch lighter or warmer
than the picture lands on the picture's own tone. An outpaint is read
across its seams (:func:`tone_offset_field`); an inpaint, which has no
source rectangle, inside its painted area (:func:`inner_tone_offset`),
or in the feathered band (:func:`estimate_tone_offset`) when the
painted area holds new content. 0 leaves the patch alone.
``seam`` "classic" is everything above. "blend in" replaces it on a
stitcher that knows where the picture's edge is (Load Image + Pad and
@@ -788,7 +791,13 @@ def apply_stitch(
# Trimmed like the blend when fewer frames came back.
generated = generated[:frames] if generated.shape[0] > frames else generated
generated = generated[:, cy : cy + ch, cx : cx + cw].to(out.device)
field = tone_offset_field(patch, out[:, cy : cy + ch, cx : cx + cw, :], alpha, bbox, generated)
region = out[:, cy : cy + ch, cx : cx + cw, :]
field = tone_offset_field(patch, region, alpha, bbox, generated)
if bbox is None:
# An inpaint has no source rectangle to read a seam across. Its
# drift is read just inside the painted area, where it holds.
inner, held = inner_tone_offset(patch, region, alpha, came_back)
field = torch.where(held.view(-1, 1, 1, 1), inner.view(-1, 1, 1, 3).expand_as(field), field)
# Weighted by the blend: a fully generated pixel drifted by the whole
# field, a band pixel the sampler mixed at alpha drifted by alpha of
# it, and the blend below scales the correction by alpha once more.
@@ -841,6 +850,172 @@ def estimate_tone_offset(
return torch.where(measured, offset, torch.zeros_like(offset))
# An inpaint's drift is read in the painted area's own rim: this many
# pixels in from where the paste becomes whole. The rim is where the new
# part most often still shows what was there before (skin beside skin).
INNER_RIM_PX = 32
# Rim pixels within this many LAB units of the rim's median change count as
# the same content, drifted. The reading is only used when at least
# INNER_MIN_SHARE of the rim agrees and there are INNER_MIN_PIXELS of it.
INNER_SAME_CONTENT = 8.0
INNER_MIN_SHARE = 0.5
INNER_MIN_PIXELS = 64
# A larger change than this is new content (a jacket over skin), not a
# drift: matching it would pull the new thing toward the old colour.
INNER_MAX_SHIFT = 20.0
# New content has no "before" in its own place (skin where a shirt was), so
# it is read against the untouched picture beside it instead: the painted
# area and the picture, each averaged within this many pixels of a point.
NEIGHBOUR_REACH_PX = 48
# A point counts as on the seam when each side fills this much of its reach.
NEIGHBOUR_MIN_SIDE = 0.1
# Seam points within INNER_MAX_SHIFT of each other show the same thing on
# both sides (skin beside skin). Fewer than this share of the seam and the
# new part is something else all round, so nothing is matched.
NEIGHBOUR_MIN_SHARE = 0.25
def _neighbour_offset(
new: torch.Tensor, old: torch.Tensor, whole: torch.Tensor, outside: torch.Tensor
) -> torch.Tensor | None:
"""LAB offset of new content against the untouched picture beside it.
``new`` and ``old`` are one frame in LAB [H, W, 3]; ``whole`` marks the
fully pasted pixels and ``outside`` the untouched ones. Along the seam
the painted side's local mean is compared with the picture's. Where the
two are alike the model drew more of what is already there, and the gap
between them is its drift. None when too little of the seam is alike or
the alike part does not agree on one gap.
"""
size = 2 * NEIGHBOUR_REACH_PX + 1
def local(values: torch.Tensor, mask: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
weight = mask.to(values.dtype).unsqueeze(-1)
stack = torch.cat([values * weight, weight], dim=-1).movedim(-1, 0).unsqueeze(0)
stack = functional.avg_pool2d(stack, (1, size), stride=1, padding=(0, NEIGHBOUR_REACH_PX))
stack = functional.avg_pool2d(stack, (size, 1), stride=1, padding=(NEIGHBOUR_REACH_PX, 0))[0]
return (stack[:3] / stack[3:].clamp_min(1e-6)).movedim(0, -1), stack[3]
painted, painted_share = local(new, whole)
picture, picture_share = local(old, outside)
seam = (painted_share >= NEIGHBOUR_MIN_SIDE) & (picture_share >= NEIGHBOUR_MIN_SIDE)
gaps = (painted - picture)[seam]
if gaps.shape[0] < INNER_MIN_PIXELS:
return None
alike = gaps.norm(dim=-1) <= INNER_MAX_SHIFT
if int(alike.sum()) < INNER_MIN_PIXELS or float(alike.float().mean()) < NEIGHBOUR_MIN_SHARE:
return None
gaps = gaps[alike]
agree = (gaps - gaps.median(dim=0).values).norm(dim=-1) < INNER_SAME_CONTENT
if float(agree.float().mean()) < INNER_MIN_SHARE:
return None
return gaps[agree].median(dim=0).values
def _area_resize(image: torch.Tensor, width: int, height: int) -> torch.Tensor:
"""Shrink [B, H, W, C] by averaging the pixels each new one covers."""
return functional.interpolate(image.movedim(-1, 1), size=(height, width), mode="area").movedim(1, -1)
def inner_tone_offset(
inpainted: torch.Tensor,
canvas: torch.Tensor,
blend: torch.Tensor,
sampled: tuple[int, int] | None = None,
) -> tuple[torch.Tensor, torch.Tensor]:
"""Per-frame LAB drift of an inpaint, read inside the painted area.
:func:`estimate_tone_offset` reads the feathered band and assumes the
sampler mixed original and generated there by ``blend``. A workflow that
samples with its own, wider or softer noise mask breaks that: the model
leaves the band close to the original and drifts further in, so the band
reads a fraction of the drift (issue #361: 0.8 of 2.5 LAB units).
This reads the same pixels before and after in the rim of the fully
pasted area (``blend`` > 0.999, INNER_RIM_PX deep): the median change,
then the median again over the pixels that agree with it. Returns the
offsets [B, 3] and which frames hold [B]. A frame whose rim mostly
disagrees, or changed by more than INNER_MAX_SHIFT, is new content
rather than drift. That frame is read against the untouched picture
beside it (:func:`_neighbour_offset`), and holds at zero, left as
painted, when the picture beside it shows something else. Only a rim too
small to judge does not hold, and the caller keeps the band reading for it.
``sampled`` is the (width, height) the model worked at. A crop from a
large picture is pasted back several times that size, and a rim measured
in pasted pixels would be a sliver at the very edge of what the model
painted, where it drifts least. The reading is taken at the model's
size instead, which also keeps its cost the same for any picture.
"""
from ._color_helpers import rgb_to_lab
if sampled is not None:
width, height = int(sampled[0]), int(sampled[1])
if 0 < width < inpainted.shape[2] and 0 < height < inpainted.shape[1]:
inpainted = _area_resize(inpainted, width, height)
canvas = _area_resize(canvas, width, height)
blend = _area_resize(blend.unsqueeze(-1), width, height).squeeze(-1)
new = rgb_to_lab(inpainted[..., :3])
old = rgb_to_lab(canvas[..., :3])
diff = new - old
frames = diff.shape[0]
whole = (blend > 0.999).to(diff.dtype)
# A pixel is deeper than the rim when nothing within INNER_RIM_PX of it
# is outside the whole paste. The crop's own border does not count as
# outside: the painted area simply runs off the crop there.
# One pass along each axis: the same square reach at a fraction of the cost.
outside = grow_shrink_mask(1.0 - whole, INNER_RIM_PX)
deep = 1.0 - outside
rim = (whole > 0) & (deep < 0.5)
rim = torch.where(rim.flatten(1).any(dim=1).view(-1, 1, 1), rim, whole > 0)
pasted = whole > 0
untouched = blend < 0.001
if rim.shape[0] != frames:
rim = rim.expand(frames, -1, -1)
pasted = pasted.expand(frames, -1, -1)
untouched = untouched.expand(frames, -1, -1)
# See-through pixels hold whatever colour sits under the clear part.
if inpainted.shape[-1] > 3:
rim = rim & (inpainted[..., 3] >= 0.999)
pasted = pasted & (inpainted[..., 3] >= 0.999)
if canvas.shape[-1] > 3:
rim = rim & (canvas[..., 3] >= 0.999)
untouched = untouched & (canvas[..., 3] >= 0.999)
def beside(index: int) -> torch.Tensor:
gap = _neighbour_offset(new[index], old[index], pasted[index], untouched[index])
return offsets[index] if gap is None else gap
offsets = torch.zeros((frames, 3), dtype=diff.dtype, device=diff.device)
held = torch.zeros((frames,), dtype=torch.bool, device=diff.device)
for index in range(frames):
changes = diff[index][rim[index]]
if changes.shape[0] < INNER_MIN_PIXELS:
continue
# From here the rim is large enough to judge, so this reading stands
# and the band is not asked. New content keeps a zero shift: the band
# of a repainted edge reads the new colour itself as drift (a yellow
# swimsuit over skin turned the whole patch blue).
held[index] = True
middle = changes.median(dim=0).values
agree = (changes - middle).norm(dim=-1) < INNER_SAME_CONTENT
if float(agree.float().mean()) < INNER_MIN_SHARE:
offsets[index] = beside(index)
continue
offset = changes[agree].median(dim=0).values
if float(offset.norm()) > INNER_MAX_SHIFT:
offsets[index] = beside(index)
continue
offsets[index] = offset
return offsets, held
def _band_weights(blend: torch.Tensor) -> torch.Tensor:
return torch.where((blend > 0.001) & (blend < 0.999), blend, torch.zeros_like(blend))
+2 -5
View File
@@ -61,11 +61,8 @@ def list_lama_models() -> list[str]:
def resolve_lama_model(model_name: str) -> Path:
register_lama_model_folder()
if folder_paths is None:
path = Path(model_name).expanduser().resolve()
if path.is_file():
return path
else:
# Only a name from ComfyUI's lama model folder: a typed path is never opened.
if folder_paths is not None:
resolved = folder_paths.get_full_path(MODEL_FOLDER, model_name)
if resolved:
return Path(resolved).resolve()
+194
View File
@@ -0,0 +1,194 @@
"""Layout Boxes' `h3_prompt` output: the boxes as a MiniMax H3 Image prompt.
H3 Image places things from words, and it reads its pictures as
<Picture 1>, <Picture 2>, ... in the order they are wired. So every box
becomes one sentence that says where it is in plain words: left or right,
high or low, how much of the frame it takes, and who stands beside it. An
object box with no description stands for the person in the next reference
picture, with their face, hair and clothes.
The prompt never holds coordinates. Written as numbers they come back drawn
on the picture as text (tried on H3 Image: 6 renders of 6), so places and
sizes are said in words only, and nothing in the prompt talks about boxes,
lines or frames either.
With a picture on `background`, that picture is the scene: <Picture 1>, the
one H3 Image changes, and the subjects start at <Picture 2>. Without one the
subjects start at <Picture 1>.
"""
from __future__ import annotations
from ._layout_boxes_helpers import _turned_extent, angle_of, element_desc
# Fractions of the frame, said as words.
SHARES = (
(0.15, "a tenth"),
(0.29, "a quarter"),
(0.42, "a third"),
(0.58, "half"),
(0.71, "two thirds"),
(0.88, "three quarters"),
)
# A name for the box beside it, from its description: at most this many words.
NAME_WORDS = 8
def _extent(region: dict, shape: tuple[float, float]) -> tuple[float, float, float, float]:
"""(left, top, right, bottom) as fractions of the frame, cut to it."""
if angle_of(region):
left, top, right, bottom = _turned_extent(region, shape)
else:
x, y = float(region.get("x", 0.0)), float(region.get("y", 0.0))
w, h = float(region.get("w", 0.0)), float(region.get("h", 0.0))
left, right = sorted((x, x + w))
top, bottom = sorted((y, y + h))
return tuple(min(1.0, max(0.0, value)) for value in (left, top, right, bottom))
def share_words(part: float) -> str:
"""0.5 -> "half", 0.34 -> "a third", 0.95 -> "all"."""
for upto, words in SHARES:
if part < upto:
return words
return "all"
def across_words(middle: float) -> str:
if middle < 0.2:
return "at the far left of the frame"
if middle < 0.4:
return "on the left of the frame"
if middle <= 0.6:
return "in the middle of the frame"
if middle <= 0.8:
return "on the right of the frame"
return "at the far right of the frame"
def high_or_low(top: float, bottom: float) -> str:
""" "high " or "low " in front of the place across, when it says something."""
middle = (top + bottom) / 2
if bottom - top >= 0.6:
return ""
if middle < 0.34:
return "high "
if middle > 0.66:
return "low "
return ""
def size_words(left: float, top: float, right: float, bottom: float) -> str:
tall, wide = share_words(bottom - top), share_words(right - left)
of_height = "the frame's full height" if tall == "all" else f"{tall} of the frame's height"
of_width = "all of its width" if wide == "all" else f"{wide} of its width"
return f"taking up about {of_height} and {of_width}"
def _short_name(desc: str) -> str:
"""A box's description cut to a name to place another box by."""
first = desc.strip().split(",")[0].split(".")[0].strip()
words = first.split()
if not words:
return ""
name = " ".join(words[:NAME_WORDS])
return name[:1].lower() + name[1:] if not name[:2].isupper() else name
def _beside_words(gap: float, name: str, in_front: bool) -> str:
"""Where a box is against its neighbour on the left."""
if gap < 0:
return f"partly {'in front of' if in_front else 'behind'} {name}"
if gap < 0.05:
return f"right beside {name}, on its right"
if gap < 0.15:
return f"a little to the right of {name}"
return f"well to the right of {name}"
def _overlap_down(one: dict, other: dict) -> bool:
return one["extent"][1] < other["extent"][3] and other["extent"][1] < one["extent"][3]
def _subjects(regions: list[dict], shape: tuple[float, float], first_picture: int) -> list[dict]:
"""One entry per box worth a sentence, in the boxes' order."""
items = []
picture = first_picture
for order, region in enumerate(regions):
if not isinstance(region, dict):
continue
desc = element_desc(region).strip()
kind = "text" if region.get("type") == "text" else "obj"
item = {"order": order, "kind": kind, "desc": desc, "extent": _extent(region, shape), "picture": 0}
if kind == "text":
item["text"] = str(region.get("text", "") or "").strip()
if not item["text"] and not desc:
continue
item["name"] = f'the words "{item["text"]}"' if item["text"] else _short_name(desc)
elif desc:
item["name"] = _short_name(desc)
else:
item["picture"] = picture
item["name"] = f"the person from <Picture {picture}>"
picture += 1
items.append(item)
return items
def _place(item: dict, beside: str) -> str:
left, top, right, bottom = item["extent"]
parts = [high_or_low(top, bottom) + across_words((left + right) / 2)]
if beside:
parts.append(beside)
parts.append(size_words(left, top, right, bottom))
return ", ".join(parts)
def _sentence(item: dict, beside: str) -> str:
place = _place(item, beside)
if item["kind"] == "text":
words = f'The words "{item["text"]}" are written' if item["text"] else "Writing is"
look = f" The lettering: {item['desc'].rstrip('.')}." if item["desc"] else ""
return f"{words} {place}.{look}"
if item["picture"]:
n = item["picture"]
# "Exactly as in <Picture N>" made H3 Image copy that whole picture,
# backdrop and all, over the scene: name only what to keep.
return f"The person from <Picture {n}>, with the same face, hair and clothes as in <Picture {n}>. Placed {place}."
desc = item["desc"].rstrip(".")
return f"{desc[:1].upper()}{desc[1:]}. Placed {place}."
def h3_prompt(regions: list[dict], shape: tuple[float, float] | None = None, scene: bool = False) -> str:
"""The `h3_prompt` output. `shape` is the (width, height) of the canvas
the boxes were drawn on; `scene` is True when a picture is on
`background`, which is then <Picture 1>. No boxes give an empty text."""
shape = shape or (1.0, 1.0)
items = _subjects(regions, shape, 2 if scene else 1)
if not items:
return ""
# Each object is placed against the object on its left, when the two
# share some height; words in the picture are placed by the frame only.
beside = {}
things = [item for item in items if item["kind"] == "obj"]
by_across = sorted(things, key=lambda item: (item["extent"][0] + item["extent"][2]) / 2)
for before, item in zip(by_across, by_across[1:]):
if not _overlap_down(before, item):
continue
gap = item["extent"][0] - before["extent"][2]
beside[item["order"]] = _beside_words(gap, before["name"], item["order"] > before["order"])
if scene:
opening = (
"One photograph of the scene in <Picture 1>, kept as it is: the same place, the same "
"background and the same light, seen from the same camera."
)
else:
opening = "One photograph, seen from one camera, in one light."
opening += " Everything below is together in this one picture, not in separate pictures side by side."
lines = [opening]
lines += [_sentence(item, beside.get(item["order"], "")) for item in items]
lines.append(
"Everyone and everything in the picture shares the same ground and the same light, with "
"matching shadows. It is a plain photograph: only the scene, what is in it, and the light."
)
return "\n\n".join([lines[0], "\n".join(lines[1:-1]), lines[-1]])
+61 -19
View File
@@ -9,10 +9,13 @@ from __future__ import annotations
import json
import os
import re
from collections import OrderedDict
from pathlib import Path
from typing import Any
from ._route_errors import error_detail
try:
import folder_paths
except ImportError: # pragma: no cover - only outside ComfyUI
@@ -62,6 +65,7 @@ def parse_lora_stack(raw: str | None) -> list[dict[str, Any]]:
enabled = bool(entry.get("enabled", True)) and entry.get("group_off") is not True
rows.append(
{
"id": str(entry.get("id") or ""),
"name": name,
"strength": strength,
"strength_clip": clamp_strength(entry.get("strength_clip", strength), strength),
@@ -72,6 +76,42 @@ def parse_lora_stack(raw: str | None) -> list[dict[str, Any]]:
return rows
# A row's strength can come in on a link: the node then has an input named
# strength_<row id>, made by the frontend when a value is dropped on the row.
ROW_STRENGTH_PREFIX = "strength_"
_ROW_INPUT = re.compile(r"^strength_[A-Za-z0-9_-]{1,64}$")
def is_row_strength_input(name: Any) -> bool:
return isinstance(name, str) and bool(_ROW_INPUT.match(name))
def apply_linked_strengths(rows: list[dict[str, Any]], linked: dict[str, Any]) -> list[dict[str, Any]]:
"""Rows with each linked value as the model strength.
The CLIP strength keeps the ratio the row had to its model strength, so
one slider moves the whole LoRA. A row at model strength 0 has no ratio
to keep; its CLIP strength then follows the slider one for one.
"""
values = {
name[len(ROW_STRENGTH_PREFIX):]: value
for name, value in linked.items()
if is_row_strength_input(name) and value is not None
}
if not values:
return rows
out = []
for row in rows:
row_id = row.get("id")
if not row_id or row_id not in values:
out.append(row)
continue
strength = clamp_strength(values[row_id], row["strength"])
ratio = row["strength_clip"] / row["strength"] if row["strength"] else 1.0
out.append({**row, "strength": strength, "strength_clip": clamp_strength(strength * ratio, strength)})
return out
def collect_trigger_words(rows: list[dict[str, Any]], separator: str = ", ") -> str:
"""Join enabled rows' trigger words, deduplicated, order preserved."""
seen: set[str] = set()
@@ -136,27 +176,29 @@ _remap_noted: set[str] = set()
def resolve_lora_path(name: str) -> Path:
if folder_paths is None:
raise ValueError("folder_paths is unavailable outside ComfyUI.")
full = folder_paths.get_full_path("loras", name)
if not full:
# Only a name on ComfyUI's own LoRA list reaches the disk. A route's
# name or a widget value is never joined to a folder as given: it is
# matched against the list first, and anything else is refused here.
candidate, status = match_lora_name(str(name), list_loras())
if status == "remapped":
# The saved path is stale; a moved file should just keep working.
candidate, status = match_lora_name(str(name), list_loras())
if status == "remapped":
if name not in _remap_noted:
_remap_noted.add(name)
print(
f"[AusBoss] LoRA Loader: '{name}' is not at its saved "
f"path; using '{candidate}'."
)
full = folder_paths.get_full_path("loras", candidate)
elif status == "ambiguous":
raise ValueError(
f"LoRA name matches several files in models/loras: {name}"
if name not in _remap_noted:
_remap_noted.add(name)
print(
f"[AusBoss] LoRA Loader: '{name}' is not at its saved "
f"path; using '{candidate}'."
)
elif status == "ambiguous":
raise ValueError(
f"LoRA name matches several files in models/loras: {name}"
)
elif status != "exact":
raise ValueError(f"LoRA file not found in models/loras: {name}")
full = folder_paths.get_full_path("loras", candidate)
if not full:
raise ValueError(f"LoRA file not found in models/loras: {name}")
# Containment is checked on the path as written, with ".." folded but
# links not followed: a LoRA kept on another drive and linked into
# models/loras is the user's own choice, and ComfyUI loads it too.
# The listed file must also sit below one of the loras folders, read
# from the path as ComfyUI built it, with ".." folded.
path = Path(os.path.abspath(full))
roots = [Path(os.path.abspath(root)) for root in folder_paths.get_folder_paths("loras")]
if not any(root in path.parents for root in roots):
@@ -388,8 +430,8 @@ def apply_lora_stack(
except MemoryError:
raise
except Exception as exc:
# ComfyUI's own message here is PyTorch's and never names the file.
detail = f"{type(exc).__name__}: {' '.join(str(exc).split())}"
# ComfyUI can add the file's path; error_detail drops words that name one.
detail = error_detail(exc)
raise ValueError(
unreadable_lora_message(row["name"], unreadable_lora_reason(path), detail)
) from exc
+73 -11
View File
@@ -63,6 +63,41 @@ def _as_bhw(mask: torch.Tensor) -> torch.Tensor:
MASK_CHUNK = 8
def _within_support(mask: torch.Tensor, reach: int, run) -> torch.Tensor:
"""Run a neighbourhood filter only where it can change anything.
``run`` is a grow, shrink or blur whose output pixel reads the input no
further than ``reach`` pixels away, and gives exactly 0 where all it
reads is 0. Outside the nonzero pixels grown by ``reach`` the result is
therefore 0, so the filter runs on a window around them, grown by twice
the reach: every pixel kept from it reads only what it would read on the
whole frame, and at the frame's own edge the window ends there too, so
edge padding behaves the same. A box drawn on a big photo then costs the
box, not the photo; an empty mask costs one scan.
"""
if mask.ndim != 3 or mask.numel() == 0:
return run(mask)
height, width = int(mask.shape[1]), int(mask.shape[2])
nonzero = (mask != 0).any(dim=0)
rows = torch.nonzero(nonzero.any(dim=1)).flatten()
if rows.numel() == 0:
return torch.zeros_like(mask)
cols = torch.nonzero(nonzero.any(dim=0)).flatten()
top, bottom = int(rows[0]), int(rows[-1]) + 1
left, right = int(cols[0]), int(cols[-1]) + 1
wy0, wy1 = max(0, top - 2 * reach), min(height, bottom + 2 * reach)
wx0, wx1 = max(0, left - 2 * reach), min(width, right + 2 * reach)
# Most of the frame anyway: the copies would cost more than they save.
if (wy1 - wy0) * (wx1 - wx0) * 2 > height * width:
return run(mask)
window = run(mask[:, wy0:wy1, wx0:wx1].contiguous())
oy0, oy1 = max(0, top - reach), min(height, bottom + reach)
ox0, ox1 = max(0, left - reach), min(width, right + reach)
result = torch.zeros_like(mask)
result[:, oy0:oy1, ox0:ox1] = window[:, oy0 - wy0 : oy1 - wy0, ox0 - wx0 : ox1 - wx0]
return result
def grow_shrink_mask(mask: torch.Tensor, pixels: int) -> torch.Tensor:
"""Dilate (positive) or erode (negative) by whole pixels; soft values survive.
@@ -77,17 +112,40 @@ def grow_shrink_mask(mask: torch.Tensor, pixels: int) -> torch.Tensor:
steps = abs(int(pixels))
if steps == 0:
return mask
return _within_support(mask, steps, lambda part: _grow_shrink_full(part, pixels, steps))
def _grow_shrink_full(mask: torch.Tensor, pixels: int, steps: int) -> torch.Tensor:
if mask.shape[0] > MASK_CHUNK:
return torch.cat([grow_shrink_mask(part, pixels) for part in mask.split(MASK_CHUNK)])
size = 2 * steps + 1
grown = mask.unsqueeze(1)
return torch.cat([_grow_shrink_full(part, pixels, steps) for part in mask.split(MASK_CHUNK)])
if pixels > 0:
grown = functional.max_pool2d(grown, kernel_size=(1, size), stride=1, padding=(0, steps))
grown = functional.max_pool2d(grown, kernel_size=(size, 1), stride=1, padding=(steps, 0))
else:
grown = -functional.max_pool2d(-grown, kernel_size=(1, size), stride=1, padding=(0, steps))
grown = -functional.max_pool2d(-grown, kernel_size=(size, 1), stride=1, padding=(steps, 0))
return grown.squeeze(1)
return _running_max(_running_max(mask, steps, 2), steps, 1)
return -_running_max(_running_max(-mask, steps, 2), steps, 1)
def _running_max(values: torch.Tensor, steps: int, dim: int) -> torch.Tensor:
"""Max over the ``2 * steps + 1`` pixels centred on each pixel along ``dim``.
The same numbers as a max pool with that kernel and ``steps`` of -inf
padding, but by doubling: after k passes each pixel holds the max of the
2**k pixels from it on, and two such overlapping runs cover the whole
window. Max is exact in any order, so this matches the pool to the bit,
in about log2 of the window passes instead of one read per window pixel.
"""
size = 2 * steps + 1
length = values.shape[dim]
pad_shape = list(values.shape)
pad_shape[dim] = steps
edge = values.new_full(pad_shape, float("-inf"))
run = torch.cat((edge, values, edge), dim=dim)
width = 1
while width * 2 <= size:
count = run.shape[dim] - width
run = torch.maximum(run.narrow(dim, 0, count), run.narrow(dim, width, count))
width *= 2
if width == size:
return run.narrow(dim, 0, length).contiguous()
return torch.maximum(run.narrow(dim, 0, length), run.narrow(dim, size - width, length))
def _torch_fill_holes(solid: torch.Tensor) -> torch.Tensor:
@@ -194,9 +252,13 @@ def fill_mask_holes(mask: torch.Tensor, max_hole_size: float = 0.0) -> torch.Ten
def blur_mask(mask: torch.Tensor, sigma: float) -> torch.Tensor:
if sigma <= 0.0:
return mask
if mask.shape[0] > MASK_CHUNK:
return torch.cat([blur_mask(part, sigma) for part in mask.split(MASK_CHUNK)])
radius = max(1, int(math.ceil(float(sigma) * 3.0)))
return _within_support(mask, radius, lambda part: _blur_full(part, sigma, radius))
def _blur_full(mask: torch.Tensor, sigma: float, radius: int) -> torch.Tensor:
if mask.shape[0] > MASK_CHUNK:
return torch.cat([_blur_full(part, sigma, radius) for part in mask.split(MASK_CHUNK)])
coords = torch.arange(-radius, radius + 1, dtype=torch.float32, device=mask.device)
kernel = torch.exp(-(coords**2) / (2.0 * float(sigma) ** 2))
kernel = kernel / kernel.sum()
+8 -1
View File
@@ -242,13 +242,20 @@ def _locate_comfy_file(text: str, rule: str) -> tuple[str, str, Path]:
if (
parts[0] == "~"
or any(part in ("", ".", "..") for part in parts)
or any(re.match(r"[A-Za-z]:", part) for part in parts)
or (os.name == "nt" and ":" in inside)
or re.search(r"[\x00-\x1f\x7f]", inside)
):
raise ValueError(rule)
root = _server_folders().get(folder)
if root is None:
raise ValueError(rule)
path = root.joinpath(*parts).resolve()
# Checked as text before the disk resolves it, and again after, so a
# link that leads out of the folder is refused too.
lexical = root.joinpath(*parts)
if root not in lexical.parents:
raise ValueError(rule)
path = lexical.resolve()
if root not in path.parents:
raise ValueError(rule)
return folder, inside, path
+6
View File
@@ -7,6 +7,8 @@ from pathlib import Path
import av
MAX_VIDEO_UPLOAD_BYTES = 4 * 1024 ** 3
def upload_name(filename: str, extensions: set[str]) -> str:
name = str(filename or "")
@@ -44,8 +46,12 @@ async def stream_video_upload(request, root: Path, extensions: set[str]) -> dict
name = upload_name(part.filename, extensions)
path, handle = reserve_upload(root.resolve(), name)
complete = False
written = 0
try:
while chunk := await part.read_chunk(size=1024 * 1024):
written += len(chunk)
if written > MAX_VIDEO_UPLOAD_BYTES:
raise ValueError("That video is too large to upload (4 GB limit).")
await asyncio.to_thread(handle.write, chunk)
handle.close()
await asyncio.to_thread(validate_video, path)
+62
View File
@@ -0,0 +1,62 @@
"""Read the [project] table of a pyproject.toml.
``tomllib`` is in the standard library only from Python 3.11. Some ComfyUI
installs still run 3.10 (Stability Matrix, older portable builds), and there
a bare ``import tomllib`` stopped the whole pack from loading. So this uses
``tomllib`` when it is there, the ``tomli`` backport when that is installed,
and otherwise a small reader that takes the plain ``key = "value"`` lines of
[project], which is all the pack reads (its name and version).
"""
from __future__ import annotations
import re
try:
import tomllib as _toml
except ModuleNotFoundError: # Python 3.10
try:
import tomli as _toml
except ModuleNotFoundError:
_toml = None
_SECTION = re.compile(r"^\s*\[([^\[\]]+)\]\s*(?:#.*)?$")
_STRING_KEY = re.compile(r"""^\s*([A-Za-z0-9_-]+)\s*=\s*(?:"([^"]*)"|'([^']*)')\s*(?:#.*)?$""")
def _plain_project(text: str) -> dict:
"""The top-level string keys of [project], without a TOML library."""
project: dict = {}
inside = False
for line in text.splitlines():
section = _SECTION.match(line)
if section:
inside = section.group(1).strip() == "project"
continue
if not inside:
continue
match = _STRING_KEY.match(line)
if match and match.group(1) not in project:
value = match.group(2) if match.group(2) is not None else match.group(3)
project[match.group(1)] = value
return project
def project_from_text(text: str) -> dict:
"""The [project] table of pyproject text, or {} when it has none."""
if _toml is not None:
project = _toml.loads(text).get("project", {})
return project if isinstance(project, dict) else {}
return _plain_project(text)
def read_project(path: str) -> dict:
"""The [project] table of the pyproject.toml at ``path``.
Raises OSError or a parse error like ``tomllib.load`` does, so callers
keep their own fallbacks.
"""
with open(path, "rb") as f:
raw = f.read()
# utf-8-sig drops a BOM, which tomllib itself would reject.
return project_from_text(raw.decode("utf-8-sig"))
+15 -3
View File
@@ -1,11 +1,12 @@
"""What a route says back when a request fails."""
"""What a route or a node says back when something fails."""
from __future__ import annotations
import re
# A whole path: a word that opens with "/", "\" or a drive letter.
_SERVER_PATH = re.compile(r"""(?:^|[\s'"(\[=:,;])(?:[A-Za-z]:[\\/]|[\\/])[^\s'"]""")
# A whole path: a word that opens with "/", "\", "~/" or a drive letter,
# after anything but a letter, digit, "_" or "." ("and/or" and "3/4" stay).
_SERVER_PATH = re.compile(r"""(?:^|[^\w.])(?:[A-Za-z]:[\\/]|~[\\/]|[\\/])[^\s'"]""")
def safe_route_error(exc: Exception, fallback: str = "The request failed.") -> str:
@@ -16,3 +17,14 @@ def safe_route_error(exc: Exception, fallback: str = "The request failed.") -> s
if not text or _SERVER_PATH.search(text):
return fallback
return text
def error_detail(exc: BaseException) -> str:
"""A library's error for a node's message: its kind and its words, or
its kind alone when the words name a place on the server's disk. Node
errors reach the browser that queued the run and stay in the history."""
kind = type(exc).__name__
text = " ".join(str(exc).split())
if not text or _SERVER_PATH.search(text):
return kind
return f"{kind}: {text}"
+104
View File
@@ -0,0 +1,104 @@
"""Split a sheet of side-by-side pictures at the gaps between them.
A generated sheet (a character turnaround, a row of close-ups) rarely puts
each picture exactly on its share of the width. Cutting into equal parts then
lands a neighbour's sleeve in one piece and cuts another's off. Here each cut
moves to the cleanest column near its equal-share line: the column where the
fewest pixels differ from the sheet's backdrop.
Every piece is then placed on a backdrop-coloured canvas as wide as the widest
piece, so the pieces form one batch. The outer pieces keep the sheet's own
left and right edges at the canvas edge; the inner ones are centred.
"""
from __future__ import annotations
import torch
# How far a cut may move from its equal-share line, as a part of one share.
SEARCH = 0.4
# A pixel this far from the backdrop colour (0-1, any channel) counts as content.
CONTENT_STEP = 0.1
# Border strip, in pixels, that the backdrop colour is read from.
BORDER = 8
def backdrop_color(image: torch.Tensor) -> torch.Tensor:
"""The median colour of the picture's border: the sheet's backdrop."""
height, width, channels = image.shape
strip = max(1, min(BORDER, height // 4, width // 4))
border = torch.cat([
image[:strip].reshape(-1, channels),
image[-strip:].reshape(-1, channels),
image[:, :strip].reshape(-1, channels),
image[:, -strip:].reshape(-1, channels),
])
return border.median(dim=0).values
def column_content(image: torch.Tensor, backdrop: torch.Tensor) -> torch.Tensor:
"""For each column, how many pixels are not backdrop."""
return ((image - backdrop).abs().amax(dim=-1) > CONTENT_STEP).sum(dim=0)
def cut_columns(image: torch.Tensor, pieces: int) -> list[int]:
"""Cut positions for one HWC picture: 0, the inner cuts, then the width."""
width = int(image.shape[1])
pieces = max(1, min(int(pieces), width))
if pieces == 1:
return [0, width]
content = column_content(image, backdrop_color(image))
share = width / pieces
reach = int(share * SEARCH)
cuts = [0]
for index in range(1, pieces):
centre = round(index * share)
low = max(cuts[-1] + 1, centre - reach)
high = min(width - (pieces - index), centre + reach + 1)
if high <= low:
cuts.append(min(max(centre, cuts[-1] + 1), width - (pieces - index)))
continue
window = content[low:high]
cleanest = torch.nonzero(window == window.min()).flatten()
# The middle of the longest run of cleanest columns; on a tie the run
# nearest the equal-share line.
breaks = torch.nonzero(cleanest[1:] - cleanest[:-1] > 1).flatten() + 1
runs = torch.tensor_split(cleanest, breaks.tolist())
best = max(runs, key=lambda run: (len(run), -abs(int(run.float().mean()) + low - centre)))
cuts.append(low + int(round(float(best.float().mean()))))
cuts.append(width)
return cuts
def split_sheet(images: torch.Tensor, pieces: int) -> torch.Tensor:
"""Split every picture of a BHWC batch into ``pieces`` side by side.
Returns one batch: the first picture's pieces from left to right, then the
next picture's. All pieces share the widest piece's width.
"""
if not isinstance(images, torch.Tensor) or images.ndim != 4:
raise ValueError("Image Toolbox expected a BHWC IMAGE batch.")
pieces = int(pieces)
if pieces < 1:
raise ValueError("Pieces must be 1 or more.")
if pieces == 1:
return images
cut_sets = [cut_columns(image, pieces) for image in images]
backdrops = [backdrop_color(image) for image in images]
widest = max(b - a for cuts in cut_sets for a, b in zip(cuts, cuts[1:]))
out = []
for image, cuts, backdrop in zip(images, cut_sets, backdrops):
height = int(image.shape[0])
spans = list(zip(cuts, cuts[1:]))
for index, (start, end) in enumerate(spans):
span = end - start
canvas = backdrop.to(image.dtype).expand(height, widest, image.shape[-1]).clone()
if index == 0:
offset = 0
elif index == len(spans) - 1:
offset = widest - span
else:
offset = (widest - span) // 2
canvas[:, offset:offset + span] = image[:, start:end]
out.append(canvas)
return torch.stack(out)
+69 -3
View File
@@ -14,7 +14,8 @@ loads.
from __future__ import annotations
import os
import tomllib
from ._pyproject import read_project
PACK_NAME = "ausboss-nodes"
# A copy that has this file knows how to step aside.
@@ -24,8 +25,7 @@ _GUARD_FILE = os.path.join("nodes", "_single_copy.py")
def _read_pack(folder: str) -> dict | None:
"""Name the pack copy in ``folder``, or None when it is another pack."""
try:
with open(os.path.join(folder, "pyproject.toml"), "rb") as f:
project = tomllib.load(f).get("project", {})
project = read_project(os.path.join(folder, "pyproject.toml"))
except Exception:
return None
if project.get("name") != PACK_NAME:
@@ -95,3 +95,69 @@ def other_copy_that_loads(own_folder: str, roots: list[str] | None = None) -> di
return None
chosen = pick_copy(copies)
return None if chosen["folder"] == os.path.realpath(own_folder) else chosen
def is_older(version: str, than: str) -> bool:
return _version_key(version) < _version_key(than)
def second_copy_notice(own_folder: str, own_version: str, other: dict) -> dict:
"""What the browser tells someone whose pack is installed twice.
The usual case is an old git clone beside a newer Manager install: the
old clone cannot step aside, so it loads, and every node added since
shows as missing however often the Manager updates the other folder.
"""
own = os.path.basename(os.path.realpath(own_folder))
used = os.path.basename(other["folder"])
if is_older(other["version"], own_version):
summary = "AusBoss: an old copy is loading"
detail = (
f"ComfyUI is loading the old AusBoss v{other['version']} in "
f"custom_nodes/{used}, not v{own_version} in custom_nodes/{own}. "
f"Nodes added after v{other['version']} show as missing, and "
f"updating does not fix it. Delete the custom_nodes/{used} "
"folder, then restart ComfyUI."
)
else:
summary = "AusBoss is installed twice"
detail = (
f"AusBoss is in custom_nodes/{used} (v{other['version']}) and "
f"custom_nodes/{own} (v{own_version}). Only custom_nodes/{used} "
f"loads. Delete custom_nodes/{own}, then restart ComfyUI."
)
return {"summary": summary, "detail": detail, "older": is_older(other["version"], own_version)}
NOTICE_ROUTE = "/ausboss/second_copy"
def register_second_copy_notice(notice: dict, prompt_server=None) -> bool:
"""Serve ``notice`` to the browser at NOTICE_ROUTE.
Only copies that step aside call this, and the copy that loads never
adds this route, so nothing is added twice. Two copies that both step
aside share one route: the first adds it, the rest add their notice to
its list.
"""
if prompt_server is None:
try:
from server import PromptServer
prompt_server = PromptServer.instance
except Exception:
return False
notices = getattr(prompt_server, "_ausboss_second_copy_notices", None)
if notices is not None:
notices.append(notice)
return True
notices = [notice]
prompt_server._ausboss_second_copy_notices = notices
from aiohttp import web
@prompt_server.routes.get(NOTICE_ROUTE)
async def _second_copy_notices(_request):
return web.json_response(notices)
return True
+32 -14
View File
@@ -393,8 +393,9 @@ def transform_pil_batch(
)
image_array = np.asarray(output, dtype=np.float32) / 255.0
mask_array = np.asarray(mask, dtype=np.float32) / 255.0
frames.append(torch.from_numpy(image_array.copy()))
masks.append(torch.from_numpy(mask_array.copy()))
# The division already made fresh arrays, so no copy is needed.
frames.append(torch.from_numpy(image_array))
masks.append(torch.from_numpy(mask_array))
views.append(prompt_view)
if not frames or first_geometry is None:
@@ -480,17 +481,25 @@ def transform_tensor_batch_chunked(
return output, mask, geometry
def stable_file_fingerprint(path: str | os.PathLike[str], inputs: dict[str, object]) -> str:
normalized_path = str(Path(path).resolve()).casefold()
try:
stat = os.stat(path)
file_state: dict[str, object] = {
"path": normalized_path,
"mtime_ns": stat.st_mtime_ns,
"size": stat.st_size,
}
except OSError:
file_state = {"path": normalized_path, "missing": True}
def stable_file_fingerprint(path: Path | None, inputs: dict[str, object]) -> str:
"""A key that changes when the inputs or the file do.
`path` is what resolve_input_path or resolve_video_path returned, or
None when they refused the value. Only such a path is ever looked at on
disk: a refused value is a string, and a string is only hashed, so a
whole path or a network share typed into a widget is never opened."""
if isinstance(path, Path):
try:
stat = os.stat(path)
file_state: dict[str, object] = {
"path": str(path).casefold(),
"mtime_ns": stat.st_mtime_ns,
"size": stat.st_size,
}
except OSError:
file_state = {"path": str(path).casefold(), "missing": True}
else:
file_state = {"unresolved": True}
payload = {"file": file_state, "inputs": inputs}
encoded = json.dumps(payload, sort_keys=True, separators=(",", ":"), ensure_ascii=True)
return hashlib.sha256(encoded.encode("utf-8")).hexdigest()
@@ -567,6 +576,15 @@ def resize_then_pad(output, mask, geometry, fill_color, megapixels, method, step
return place(output), resized, None if view is None else place(view)
def has_see_through(images: Iterable[Image.Image]) -> bool:
"""True when any frame has see-through parts (:func:`see_through_kept`),
so :func:`original_image_batch` would differ with ``keep_see_through``."""
return any(
see_through_kept(image if image.mode == "RGBA" else image.convert("RGBA")) is not None
for image in images
)
def original_image_batch(images: Iterable[Image.Image], keep_see_through: bool = False) -> torch.Tensor:
"""Untransformed, EXIF-oriented RGB source frames for reference outputs.
@@ -578,7 +596,7 @@ def original_image_batch(images: Iterable[Image.Image], keep_see_through: bool =
"""
frames = []
for image in images:
array = np.asarray(image.convert("RGB"), dtype=np.float32).copy()
array = np.array(image.convert("RGB"), dtype=np.float32)
kept = None if keep_see_through else see_through_kept(image if image.mode == "RGBA" else image.convert("RGBA"))
if kept is not None:
array[~kept] = SEE_THROUGH_BACKDROP
+3 -2
View File
@@ -13,6 +13,7 @@ import numpy as np
import torch
from av.video.reformatter import ColorRange, Colorspace
from ._route_errors import error_detail
from ._execution_helpers import advance_progress, frame_progress, raise_if_interrupted
AAC_FRAME_SIZE = 1024
@@ -363,9 +364,9 @@ def _encoder_start_error(codec: str, exc: Exception) -> RuntimeError:
return RuntimeError(
"Save Video: the nvenc formats need an NVIDIA GPU with a working "
"driver. Pick a software format such as 'mp4 h264' instead. "
f"(The '{codec}' encoder said: {exc})"
f"(The '{codec}' encoder said: {error_detail(exc)})"
)
return RuntimeError(f"Save Video could not start the '{codec}' encoder: {exc}.")
return RuntimeError(f"Save Video could not start the '{codec}' encoder: {error_detail(exc)}.")
def _add_video_stream(container, spec: VideoFormat, rate, width: int, height: int, crf: int):
+30 -6
View File
@@ -164,7 +164,7 @@ class AusBossH3PromptWriter:
"INT",
{
"default": 8,
"min": 5,
"min": 4,
"max": 15,
"step": 1,
"tooltip": "How long the clip is. Plan on about one moment a second at most.",
@@ -203,7 +203,7 @@ class AusBossH3PromptWriter:
[AS_TYPED, *CAMERAS],
{
"default": AS_TYPED,
"tooltip": "How the camera moves the whole way through. As typed leaves it to your words.",
"tooltip": "How the camera moves the whole way through. As typed leaves it to your words; with a video wired it shows as from the video and keeps the video's own camera.",
},
),
"look": (
@@ -254,8 +254,8 @@ class AusBossH3PromptWriter:
"default": VIDEO_JOBS[0],
"tooltip": (
"What the video is for: copy its moves, swap the person in it, keep it going, give it "
"a new voice, or change something in it and keep the person (a hat, a shirt). Swap, "
"new voice and change something ignore Seconds and keep the video's length."
"a new voice, or change something in it and keep the person (a hat, a shirt). Copy its "
"moves, swap, new voice and change something ignore Seconds and keep the video's length."
),
},
),
@@ -285,6 +285,19 @@ class AusBossH3PromptWriter:
),
},
),
"full_prompt": (
"STRING",
{
"default": "",
"multiline": True,
"dynamicPrompts": False,
"tooltip": (
"Your own edit of the finished prompt, from the Full prompt tab. When it holds "
"text, H3 gets exactly this text instead of the prompt the node writes. Empty "
"means the node's own prompt."
),
},
),
},
}
@@ -321,7 +334,7 @@ class AusBossH3PromptWriter:
"The height of your video, or else of your first picture. Wire it into H3's height.",
"On when the finished clip should keep your video's own sound: with clip_sound on, or always for change something.",
)
FUNCTION = "write"
FUNCTION = "run"
def write(self, script, seconds, clip=None, picture_1=None, picture_2=None, picture_3=None, picture_4=None, video=None,
video_sound=None, voice=None, song=None, camera=AS_TYPED, look=FROM_PICTURE, song_start=0.0, cut_on_beat=True,
@@ -378,6 +391,17 @@ class AusBossH3PromptWriter:
ordered = [*given.values(), None, None, None, None][: len(PICTURES)]
return (text, *ordered, video, video_sound, voice, song, song_under, frames, *clip_shape(video, ordered[0]), keeps_clip_sound)
def run(self, script, seconds, full_prompt="", **inputs):
# The Full prompt tab shows what the node wrote; an edit typed there is sent in its place.
written, *rest = self.write(script, seconds, **inputs)
return {"ui": {"written_prompt": [written]}, "result": (sent_prompt(written, full_prompt), *rest)}
def sent_prompt(written, edited):
"""The prompt H3 gets: the edit from the Full prompt tab when it holds any text, else the written one."""
edited = str(edited or "")
return edited if edited.strip() else written
def _register_routes():
try:
@@ -393,7 +417,7 @@ def _register_routes():
async def read(request):
try:
body = await request.json()
seconds = min(max(int(body.get("seconds", 8)), 5), LONGEST_SECONDS)
seconds = min(max(int(body.get("seconds", 8)), 4), LONGEST_SECONDS)
jobs = {int(slot): job for slot, job in dict(body.get("jobs") or {}).items() if job in JOBS and int(slot) in PICTURES}
video = body.get("video") if body.get("video") in VIDEO_JOBS else ""
return web.json_response(script_report(str(body.get("script", ""))[:LONGEST_SCRIPT], seconds, jobs, video))
+11 -3
View File
@@ -6,6 +6,7 @@ from ._execution_helpers import ignore_extra_inputs
from ._media_helpers import list_input_images, load_image_frames, resolve_input_path
from ._inpaint_crop_helpers import build_transform_stitcher, remember_original
from ._transform_engine import (
has_see_through,
original_image_batch,
resize_then_pad,
stable_file_fingerprint,
@@ -138,13 +139,20 @@ class AusBossImageCropRotatePad:
source="Image Crop + Rotate + Pad",
)
# The picture as stored: a MaskEditor stroke keeps what is under it.
remember_original(stitcher, original_image_batch(frames, True), geometry, spec.normalized().rotation_degrees)
stored = original_image_batch(frames, True)
remember_original(stitcher, stored, geometry, spec.normalized().rotation_degrees)
# With nothing see-through both copies hold the same pixels: copy
# the one already made instead of converting the picture again.
if keep_picture or not has_see_through(frames):
original = stored.clone()
else:
original = original_image_batch(frames, False)
# Nothing see-through: the prompt view is the image itself, as a copy
# so no consumer can change one through the other.
if prompt_image is None:
prompt_image = output.clone()
return (
output, mask, stitcher, original_image_batch(frames, keep_picture),
output, mask, stitcher, original,
int(output.shape[2]), int(output.shape[1]), prompt_image,
)
@@ -168,7 +176,7 @@ class AusBossImageCropRotatePad:
try:
path = resolve_input_path(image)
except Exception:
path = image or ""
path = None # refused: hashed by its text only, never opened
spec = spec_from_values(**values)
# Every widget value is already part of ComfyUI's cache key, so a
# changed transform or budget re-runs the node without this; the
+15 -3
View File
@@ -2,6 +2,8 @@
from __future__ import annotations
import hashlib
from pathlib import Path
from ._execution_helpers import ignore_extra_inputs
@@ -18,6 +20,7 @@ from ._image_folder_helpers import (
choose,
clean_folder,
fingerprint,
inside_root,
list_folders,
list_pictures,
load_picture,
@@ -69,6 +72,13 @@ def _picked(source, folder, subfolders, sort, pictures) -> list[dict]:
return choose(listed, parse_picked(pictures))
def _version_tag(item: dict) -> str:
"""A short tag that changes when the picture does, for the browser's
thumbnail cache. It carries no file size or time."""
seen = f"{item['mtime_ns']}-{item['size']}".encode()
return hashlib.sha1(seen, usedforsecurity=False).hexdigest()[:12]
def _register_routes() -> None:
"""The gallery's three questions: which folders, which pictures, and a
small copy of one. Every path is attacker-controlled; each is resolved
@@ -117,7 +127,7 @@ def _register_routes() -> None:
"source": source,
"folder": shown,
"full": len(listed) >= MAX_PICTURES,
"pictures": [{"name": item["name"], "v": f"{item['mtime_ns']}-{item['size']}"} for item in listed],
"pictures": [{"name": item["name"], "v": _version_tag(item)} for item in listed],
})
@routes.get("/ausboss/image_folder/thumb")
@@ -129,8 +139,10 @@ def _register_routes() -> None:
base = clean_folder(query(request, "folder"))
# The name is a path below the folder; it goes through the same door.
relative = clean_folder(f"{base}/{name}" if base else name)
path = root.joinpath(*relative.split("/")).resolve()
if root not in path.parents or not path.is_file() or not path.name.lower().endswith(IMAGE_EXTENSIONS):
if not relative or not relative.lower().endswith(IMAGE_EXTENSIONS):
return web.json_response({"error": "no such picture"}, status=404)
path = inside_root(root, relative)
if not path.is_file() or not path.name.lower().endswith(IMAGE_EXTENSIONS):
return web.json_response({"error": "no such picture"}, status=404)
try:
edge = int(query(request, "size") or 160)
+81
View File
@@ -0,0 +1,81 @@
"""Image Toolbox 🆎: small picture jobs behind one node.
Each job is a choice in the ``job`` list, so a new job is a new choice, not a
new node. The first job splits a sheet of side-by-side pictures at the gaps
between them (``_sheet_split_helpers``).
"""
from __future__ import annotations
from ._sheet_split_helpers import split_sheet
SPLIT_SHEET = "split sheet at gaps"
JOBS = [SPLIT_SHEET]
class AusBossImageToolbox:
CATEGORY = "🆎 AusBoss/Image"
DESCRIPTION = (
"Small picture jobs in one node: pick the job from the list. "
"split sheet at gaps cuts a row of pictures, such as a character "
"sheet's views, into separate pictures. Each cut goes to the gap "
"between two pictures, not to an equal share of the width, so no "
"piece gets part of its neighbour. The pieces come out as one batch, "
"all the same size, padded with the sheet's backdrop colour."
)
SEARCH_ALIASES = [
"toolbox",
"split sheet",
"character sheet",
"turnaround",
"split views",
"cut into pieces",
"slice image",
"ausboss",
]
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"image": (
"IMAGE",
{"tooltip": "The picture to work on. A batch is worked on picture by picture."},
),
"job": (
JOBS,
{
"default": SPLIT_SHEET,
"tooltip": "What to do with the picture. split sheet at gaps: cut a row of pictures apart at the gaps between them.",
},
),
"pieces": (
"INT",
{
"default": 4,
"min": 1,
"max": 16,
"step": 1,
"tooltip": "How many pictures sit side by side on the sheet. 4 for a four-view character sheet.",
},
),
},
}
RETURN_TYPES = ("IMAGE",)
RETURN_NAMES = ("images",)
OUTPUT_TOOLTIPS = (
"The result. For split sheet at gaps: the pieces from left to right, one batch, all the same size.",
)
FUNCTION = "run"
def run(self, image, job, pieces):
if job == SPLIT_SHEET:
return (split_sheet(image, pieces),)
raise ValueError(f"Image Toolbox has no job named {job!r}.")
NODE_CLASS_MAPPINGS = {"AUSBOSS_NODES_ImageToolbox": AusBossImageToolbox}
NODE_DISPLAY_NAME_MAPPINGS = {"AUSBOSS_NODES_ImageToolbox": "Image Toolbox 🆎"}
__all__ = ["NODE_CLASS_MAPPINGS", "NODE_DISPLAY_NAME_MAPPINGS"]
+29 -2
View File
@@ -10,11 +10,13 @@ from ._inpaint_crop_helpers import (
RESIZE_ALGORITHMS,
SEAM_CLASSIC,
SEAM_MODES,
_resize_image,
apply_stitch,
build_crop,
paste_on_original,
stitch_blend_mask,
)
from ._follow_changes_helpers import follow_changes as _follow_changes
from ._unpainted_helpers import unpainted_notice, unpainted_share
# A workflow saved before Seam existed can hold the card's empty value in
@@ -367,7 +369,11 @@ class AusBossStitchInpaint:
"rim. The blend_mask output marks what the stitch changed, in the "
"stitched image's own coordinates, ready for a downstream color match. "
"After a hand crop in Image Crop + Rotate + Pad 🆎, set Paste onto "
"to original to get your whole picture back with the edit in place."
"to original to get your whole picture back with the edit in place. "
"Turn on Follow changes when the model draws past the box (a boot or "
"a plate rim cut off at its edge): the paste then grows to every "
"change that touches the box, after lining the model's crop up with "
"your picture."
)
SEARCH_ALIASES = [
"stitch inpaint",
@@ -455,6 +461,19 @@ class AusBossStitchInpaint:
),
},
),
"follow_changes": (
"BOOLEAN",
{
"default": False,
"tooltip": (
"Paste what the model changed next to the box too, "
"so feet, rims and collars that reach past the box "
"are not cut off. It also undoes a small zoom or "
"shift the model drew. Turn it on for edit models "
"that redraw the whole crop."
),
},
),
},
}
@@ -474,12 +493,20 @@ class AusBossStitchInpaint:
FUNCTION = "stitch"
def stitch(
self, stitcher, inpainted, fix_edge_halo=False, color_match=0.0, seam=SEAM_CLASSIC, paste_onto=PASTE_ONTO_CROP
self, stitcher, inpainted, fix_edge_halo=False, color_match=0.0, seam=SEAM_CLASSIC, paste_onto=PASTE_ONTO_CROP,
follow_changes=False,
):
if seam in _UNSET_SEAM:
seam = SEAM_CLASSIC
if seam not in SEAM_MODES:
raise ValueError(f"Stitch Inpaint: seam must be 'classic' or 'blend in', not {seam!r}.")
if follow_changes is True and seam == SEAM_CLASSIC and isinstance(stitcher, dict) \
and "canvas" in stitcher and stitcher.get("source_bbox") is None:
# An inpaint crop only: an outpaint's new area has no picture
# under it to compare against.
inpainted, stitcher, lines = _follow_changes(stitcher, inpainted, _resize_image)
for line in lines:
print(f"[AusBoss] Stitch Inpaint: {line}")
image = apply_stitch(stitcher, inpainted, bool(fix_edge_halo), float(color_match), seam)
if paste_onto not in _UNSET_PASTE_ONTO and paste_onto not in PASTE_ONTO_MODES:
raise ValueError(f"Stitch Inpaint: paste_onto must be 'crop' or 'original', not {paste_onto!r}.")
+14 -5
View File
@@ -6,7 +6,8 @@ at the place you drew it. Wire `elements` to MOSS-Image Layout Prompt.
It gives what ComfyUI's own Create Bounding Boxes gives, in the same order
and worked out the same way (preview, bboxes, elements), so it can stand in
for that node. A fourth output, `mask`, is white inside every box, to change
only those places of a picture. A box can be turned, for words at a slant:
only those places of a picture. A fifth, `h3_prompt`, says the same boxes in
words for MiniMax H3 Image (_layout_boxes_h3.py). A box can be turned, for words at a slant:
the mask is the turned box itself. Its canvas is a panel of the pack's own
(js/layout_boxes/index.js), so it draws in the classic look as well as in
Nodes 2.0. The panel drives ordinary hidden widgets, so saving, loading,
@@ -38,6 +39,7 @@ from ._layout_boxes_helpers import (
render_preview,
turned_mask_rows,
)
from ._layout_boxes_h3 import h3_prompt
from ._preview_helpers import first_frame_to_pil, temp_prefix
try:
@@ -116,11 +118,14 @@ class AusBossLayoutBoxes:
"ComfyUI's own Create Bounding Boxes gives, so it can take that node's "
"place. A picture on background shows under the boxes and sets the "
"canvas size. The mask output is white inside every box: use it to "
"change only those places of a picture, such as the words on a sign."
"change only those places of a picture, such as the words on a sign. "
"h3_prompt says the boxes in words for MiniMax H3 Image: describe each "
"person as \"the man from <Picture 2>, sitting on the couch\"."
)
SEARCH_ALIASES = [
"bounding boxes", "create bounding boxes", "bbox", "boxes", "layout",
"regions", "ideogram", "moss", "moss-image", "ausboss",
"regions", "ideogram", "moss", "moss-image", "h3", "h3 image", "minimax",
"placement", "ausboss",
]
@classmethod
@@ -161,8 +166,8 @@ class AusBossLayoutBoxes:
},
}
RETURN_TYPES = ("IMAGE", "BOUNDING_BOX", "ARRAY", "MASK")
RETURN_NAMES = ("preview", "bboxes", "elements", "mask")
RETURN_TYPES = ("IMAGE", "BOUNDING_BOX", "ARRAY", "MASK", "STRING")
RETURN_NAMES = ("preview", "bboxes", "elements", "mask", "h3_prompt")
OUTPUT_TOOLTIPS = (
"A picture of the boxes with their numbers and words, to check the layout. "
"Wire it to Preview Image.",
@@ -172,6 +177,9 @@ class AusBossLayoutBoxes:
"MOSS-Image Layout Prompt. A turned text box says its slant in its description.",
"The boxes as a mask: white inside every box, turned boxes as they are turned. "
"Use it to change only those places of a picture, such as the words on a sign.",
"The boxes as a prompt for MiniMax H3 Image: where each thing goes, in words. "
"Describe each person by their picture and what they do, such as "
"\"the man from <Picture 2>, sitting on the couch\". The background is <Picture 1>.",
)
OUTPUT_NODE = True
FUNCTION = "draw"
@@ -205,6 +213,7 @@ class AusBossLayoutBoxes:
bounding_boxes(regions, width, height, shape),
prompt_elements(regions, shape),
_boxes_mask(regions, width, height, picture),
h3_prompt(regions, shape, scene=picture is not None),
),
}
+5 -7
View File
@@ -15,9 +15,8 @@ class AusBossLoadAudio:
"Loads a sound file and hands on only the part you pick. The node shows the "
"sound as a wave, so you can see where the loud parts are. Drag the two "
"handles to set where it starts and stops, and press play to hear just that "
"part. Set Max length to the longest sound the next step takes: anything "
"longer shows in red as cut off, so you see exactly what comes out before "
"you run anything."
"part. Type a Duration to get a sound of an exact length, such as the "
"length of the video you are making."
)
SEARCH_ALIASES = [
"load audio",
@@ -49,7 +48,7 @@ class AusBossLoadAudio:
"min": 0.0,
"max": 86400.0,
"step": 0.01,
"tooltip": "Where the sound starts. Drag the wave's IN handle or type a time.",
"tooltip": "Where the sound starts. Drag the wave's left handle or type a Start.",
},
),
"end_seconds": (
@@ -59,7 +58,7 @@ class AusBossLoadAudio:
"min": 0.0,
"max": 86400.0,
"step": 0.01,
"tooltip": "Where the sound stops. 0 plays to the end. Drag the OUT handle or type a time.",
"tooltip": "Where the sound stops. 0 plays to the end. The face sets a Duration instead.",
},
),
},
@@ -72,8 +71,7 @@ class AusBossLoadAudio:
"max": 86400.0,
"step": 0.1,
"tooltip": (
"The longest the sound may be. Anything past it is cut off and shows "
"in red. 0 means no limit."
"How long the sound is: the Duration box. 0 runs to the end of the file."
),
},
),
+1 -1
View File
@@ -253,7 +253,7 @@ class AusBossLoadImage:
try:
path = resolve_input_path(image)
except Exception:
path = image or ""
path = None # refused: hashed by its text only, never opened
return stable_file_fingerprint(path, {"image": image, **values})
+1 -1
View File
@@ -403,7 +403,7 @@ class AusBossLoadImagePad:
try:
path = resolve_input_path(image)
except Exception:
path = image or ""
path = None # refused: hashed by its text only, never opened
return stable_file_fingerprint(path, {"image": image, **values})
+8 -10
View File
@@ -18,12 +18,12 @@ class AusBossLoadVideo:
CATEGORY = "🆎 AusBoss/Video"
DESCRIPTION = (
"Loads a video as a BHWC frame batch plus its audio, trimmed to an "
"optional start/end window selected on the preview timeline, with frame count, "
"optional window set with Start, Duration and Ends at under the player, with frame count, "
"fps, size, and duration outputs ready for downstream wiring, plus a lazy "
"core VIDEO output for nodes that consume whole videos. every_nth thins "
"the batch and max_frames caps it, so long clips load without filling "
"memory. single_frame flips the loader into a frame picker that "
"returns just the frame at the IN time as a one-image batch."
"returns just the frame at the start time as a one-image batch."
)
SEARCH_ALIASES = [
"load video",
@@ -53,8 +53,7 @@ class AusBossLoadVideo:
"max": 86400.0,
"step": 0.01,
"tooltip": (
"Skip everything before this time. Drag the preview's IN "
"handle or type an exact value below the player."
"Skip everything before this time. It is the Start box under the player."
),
},
),
@@ -66,8 +65,7 @@ class AusBossLoadVideo:
"max": 86400.0,
"step": 0.01,
"tooltip": (
"Stop at this time; 0 plays to the end. Drag the preview's "
"OUT handle or type an exact value below the player."
"Stop at this time; 0 plays to the end. The face sets a Duration instead."
),
},
),
@@ -115,8 +113,8 @@ class AusBossLoadVideo:
"max": 100000,
"step": 1,
"tooltip": (
"Stop after this many kept frames; 0 loads the "
"whole trim window. Caps memory on long clips — "
"Stop after this many kept frames: the Duration box. 0 loads the "
"whole window. Caps memory on long clips — "
"the decode ends early instead of loading and "
"discarding."
),
@@ -127,8 +125,8 @@ class AusBossLoadVideo:
{
"default": False,
"tooltip": (
"Load only the frame at the IN time as a "
"one-image batch. The preview's trim strip "
"Load only the frame at the start time as a "
"one-image batch. The timing card "
"becomes a frame picker (the FRAME button "
"toggles this), and end_seconds, every_nth, "
"and max_frames are ignored."
+29 -4
View File
@@ -5,7 +5,9 @@ from __future__ import annotations
from ._execution_helpers import ignore_extra_inputs
from ._lora_helpers import (
MISSING_MODES,
apply_linked_strengths,
apply_lora_stack,
is_row_strength_input,
collect_trigger_words,
missing_lora_rows,
parse_lora_stack,
@@ -16,6 +18,29 @@ from ._lora_helpers import (
)
class _OptionalWithRowStrengths(dict):
"""The node's optional inputs, plus strength_<row id> for any row.
ComfyUI passes a node only the inputs it declares. A row's strength input
exists only while something is linked to that row, so its name is not
known ahead: this dict answers for any such name.
"""
def __contains__(self, key):
return super().__contains__(key) or is_row_strength_input(key)
def __getitem__(self, key):
if not super().__contains__(key) and is_row_strength_input(key):
return ("FLOAT", {
"forceInput": True,
"tooltip": "A linked strength for one row. The CLIP strength keeps its ratio.",
})
return super().__getitem__(key)
def get(self, key, default=None):
return self[key] if key in self else default
class AusBossLoraLoader:
CATEGORY = "🆎 AusBoss/Loaders"
DESCRIPTION = (
@@ -53,7 +78,7 @@ class AusBossLoraLoader:
},
),
},
"optional": {
"optional": _OptionalWithRowStrengths({
"clip": ("CLIP", {"tooltip": "Optional CLIP to patch; without it, CLIP strengths are ignored."}),
"trigger_separator": (
"STRING",
@@ -81,7 +106,7 @@ class AusBossLoraLoader:
),
},
),
},
}),
}
RETURN_TYPES = ("MODEL", "CLIP", "STRING")
@@ -98,8 +123,8 @@ class AusBossLoraLoader:
)
FUNCTION = "load_loras"
def load_loras(self, model, loras: str, clip=None, trigger_separator=", ", on_missing="error"):
rows = parse_lora_stack(loras)
def load_loras(self, model, loras: str, clip=None, trigger_separator=", ", on_missing="error", **linked):
rows = apply_linked_strengths(parse_lora_stack(loras), linked)
missing: list[dict] = []
model, clip = apply_lora_stack(model, clip, rows, on_missing=on_missing, missing=missing)
# A row skipped for a missing file loaded nothing, so its words stay
+2 -1
View File
@@ -6,6 +6,7 @@ import sys
import torch
from ._route_errors import error_detail
from ._mask_by_name_helpers import (
IF_NOTHING,
NEEDS_SAM3,
@@ -238,7 +239,7 @@ class AusBossMaskByName:
raise
# A model or text reader that is not SAM 3's fails somewhere
# inside; say what to wire instead of showing that.
raise RuntimeError(f"{NOT_SAM3} ({type(error).__name__}: {error})") from error
raise RuntimeError(f"{NOT_SAM3} ({error_detail(error)})") from error
masks, boxes = output.result
counts = [len(frame) for frame in boxes]
# How sure SAM 3 was of each match in the first picture, best first.
+6 -5
View File
@@ -15,6 +15,7 @@ import torch
import torch.nn.functional as F
from PIL import Image
from ._route_errors import error_detail, safe_route_error
from ._execution_helpers import advance_progress, progress_bar, raise_if_interrupted, warn_once
from ._fine_edge_helpers import OFF as FINE_OFF
from ._fine_edge_helpers import (
@@ -485,7 +486,7 @@ class _Session:
except Exception as error: # noqa: BLE001 - told apart just below
if _stopped_by_user(error) or _out_of_memory(error):
raise
raise RuntimeError(f"{NOT_SAM3} ({type(error).__name__}: {error})") from error
raise RuntimeError(f"{NOT_SAM3} ({error_detail(error)})") from error
_WORDS[key] = held
while len(_WORDS) > WORDS_KEPT:
_WORDS.popitem(last=False)
@@ -561,14 +562,14 @@ class _Session:
if self._open is None:
# A model or a text reader that is not SAM 3's fails
# somewhere inside; say what to wire instead of showing that.
raise RuntimeError(f"{NOT_SAM3} ({type(error).__name__}: {error})") from error
raise RuntimeError(f"{NOT_SAM3} ({error_detail(error)})") from error
self.close()
try:
answer = self._call(kind, frame, what)
except Exception as error: # noqa: BLE001
if _stopped_by_user(error) or _out_of_memory(error):
raise
raise RuntimeError(f"{NOT_SAM3} ({type(error).__name__}: {error})") from error
raise RuntimeError(f"{NOT_SAM3} ({error_detail(error)})") from error
# The plain way answers where the quick way failed.
self._distrust("a question failed with it")
return answer
@@ -1288,7 +1289,7 @@ class AusBossMaskByTouch:
if item.kind not in ("subject", "background") or not asked or _stopped_by_user(error):
raise
area, used, which = None, "none", ()
subject_trouble = str(error)
subject_trouble = safe_route_error(error, type(error).__name__)
if index == 0:
share = 0.0 if area is None else round(float(area.sum()) / (height * width), 5)
item_notes.append({"ok": used != "none", "share": share, "as": used})
@@ -1348,7 +1349,7 @@ class AusBossMaskByTouch:
# and the picture says why.
if not asked or _stopped_by_user(error):
raise
fine, fine_trouble = False, str(error)
fine, fine_trouble = False, safe_route_error(error, type(error).__name__)
if fine and soft:
# Where a soft brush had the last word its fade stays as painted.
fade = torch.stack(painted) & (raw > 0) & (raw < 1)
+3 -2
View File
@@ -43,7 +43,7 @@ class AusBossVideoCropRotatePad:
required = {
"video": (
list_input_videos(),
{"tooltip": "Choose a video in ComfyUI's input folder or use the upload button."},
{"video_upload": True, "tooltip": "Choose a video in ComfyUI's input folder or use the upload button."},
),
"source_mode": (
["input folder", "local path"],
@@ -152,7 +152,7 @@ class AusBossVideoCropRotatePad:
try:
path = resolve_video_path(source_mode, video, local_path)
except Exception:
path = local_path if source_mode == "local path" else video
path = None # refused: hashed by its text only, never opened
spec = spec_from_values(**values)
resize = {name: values.get(name) for name in resize_inputs()}
return stable_file_fingerprint(
@@ -160,6 +160,7 @@ class AusBossVideoCropRotatePad:
{
"video": video,
"source_mode": source_mode,
"local_path": local_path,
"seek_mode": seek_mode,
"frame_index": int(frame_index),
"frame_time": round(float(frame_time), 6),

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