Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
852af46786 | ||
|
|
63790c2e10 | ||
|
|
2289ef77aa | ||
|
|
7d09daeb39 | ||
|
|
7c61ae226d | ||
|
|
52cb5d8493 | ||
|
|
bfa7c35a64 | ||
|
|
916197fb28 | ||
|
|
286866fa0f | ||
|
|
a9fe941b03 | ||
|
|
f684af1273 | ||
|
|
734e88af1f | ||
|
|
a3a5cf2826 | ||
|
|
2fa296fe89 | ||
|
|
07461b5972 | ||
|
|
952f72bedf | ||
|
|
3792649ae5 | ||
|
|
5b00d85094 | ||
|
|
09b8c499e7 | ||
|
|
d2782a2a90 | ||
|
|
3ef50e0262 | ||
|
|
f9cd259a3e | ||
|
|
9ab4365245 | ||
|
|
5dfbcdd99c | ||
|
|
20f860d5ff | ||
|
|
44edcc633c | ||
|
|
c99425cef1 | ||
|
|
dcb9be2bdc | ||
|
|
9304be69a8 | ||
|
|
743126d86f | ||
|
|
fb430afca1 | ||
|
|
c636d73223 | ||
|
|
6db92cdd28 | ||
|
|
3c6cbd3a41 | ||
|
|
a606d34b97 | ||
|
|
aaf3ae6ae6 | ||
|
|
d62d263725 | ||
|
|
ffd4e66654 | ||
|
|
7f97d84a88 | ||
|
|
acfe587691 | ||
|
|
f87d710d14 | ||
|
|
85da4a4d0e | ||
|
|
4832789b48 | ||
|
|
9e9121accb | ||
|
|
905ee4033f | ||
|
|
3ef9e5f51d | ||
|
|
05628b7834 | ||
|
|
c1c1a5e054 | ||
|
|
a3eb72a30c | ||
|
|
cacadcf3b1 | ||
|
|
467505748d | ||
|
|
c100ef82c4 | ||
|
|
fa695038ce | ||
|
|
30cc27b985 | ||
|
|
081379ae97 | ||
|
|
21f97580e9 | ||
|
|
8c6599d2d4 | ||
|
|
78312c7bf5 | ||
|
|
16796566c4 | ||
|
|
3f36952095 | ||
|
|
0f4bd5b135 | ||
|
|
8a5fbfe1fb | ||
|
|
f6503cc7af | ||
|
|
51993c0a2c | ||
|
|
b043f6f1a7 | ||
|
|
29c986cfdc | ||
|
|
171ad422b9 | ||
|
|
f4061f4255 | ||
|
|
9d7bcfbfb6 | ||
|
|
8d139cdfc5 | ||
|
|
fae68ecb77 | ||
|
|
661c33a926 | ||
|
|
9b27bc9c4c | ||
|
|
de530e2eac | ||
|
|
7d81a43133 | ||
|
|
0067575b0c | ||
|
|
8cc90794d8 | ||
|
|
d82ed510b9 | ||
|
|
3f06362f9c | ||
|
|
d37e0cd026 | ||
|
|
38bdddded8 | ||
|
|
f0f6ca9f0c | ||
|
|
d47a6743e3 | ||
|
|
ab8389d598 | ||
|
|
5b10b3a23f | ||
|
|
f2d966afd1 | ||
|
|
182abca56f | ||
|
|
c1c9831378 | ||
|
|
6418940761 | ||
|
|
72af858975 | ||
|
|
80e5221403 | ||
|
|
f658ac58b0 | ||
|
|
adb1eaacc4 | ||
|
|
b0f8b5ec55 | ||
|
|
a3984bf656 | ||
|
|
232e1dcdb7 | ||
|
|
ab67a1f77f | ||
|
|
2af3fd9c83 | ||
|
|
9986ded109 | ||
|
|
197ac04a8c | ||
|
|
be2a2a1444 | ||
|
|
76eb4fc7e7 | ||
|
|
057f2bd05a | ||
|
|
172252ab02 | ||
|
|
ebc81ea57e | ||
|
|
bc235e96e5 | ||
|
|
6572b49386 |
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"attribution": {
|
||||
"commit": "",
|
||||
"pr": ""
|
||||
}
|
||||
}
|
||||
@@ -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/
|
||||
|
||||
@@ -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() }}
|
||||
|
||||
+266
@@ -2,6 +2,272 @@
|
||||
|
||||
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
|
||||
|
||||
+11
-2
@@ -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
|
||||
@@ -330,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
|
||||
@@ -341,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
|
||||
|
||||
@@ -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.
|
||||
|
||||
+16
-5
@@ -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
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="105" height="20" role="img" aria-label="release: v2.26.0">
|
||||
<title>release: v2.26.0</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.26.0</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 |
@@ -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 |
|
||||
|
||||
|
||||
+20
-1
@@ -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
@@ -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 () {
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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.
|
||||
@@ -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.
|
||||
|
||||
@@ -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.
|
||||
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -68,6 +68,12 @@ answered on the same line as the button.
|
||||
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.
|
||||
|
||||
@@ -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);
|
||||
},
|
||||
});
|
||||
+156
-17
@@ -9,6 +9,10 @@ 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";
|
||||
@@ -47,6 +51,8 @@ import {
|
||||
collectUpstreamLoaders,
|
||||
collectDownstreamLoaders,
|
||||
absorbChainIssue,
|
||||
anyFolderOpen,
|
||||
parentFolder,
|
||||
mergeImportedRows,
|
||||
moveGroup,
|
||||
moveHighlight,
|
||||
@@ -65,6 +71,7 @@ import {
|
||||
scrubValue,
|
||||
serializeRows,
|
||||
setGroupEnabled,
|
||||
setFolderFolds,
|
||||
setGroupOff,
|
||||
setStrength,
|
||||
shortLoraName,
|
||||
@@ -139,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,
|
||||
@@ -219,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; }
|
||||
@@ -394,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}; }
|
||||
@@ -909,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);
|
||||
|
||||
@@ -923,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();
|
||||
@@ -994,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,
|
||||
@@ -1006,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);
|
||||
@@ -1040,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();
|
||||
@@ -1065,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;
|
||||
@@ -1073,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");
|
||||
}
|
||||
@@ -1098,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);
|
||||
};
|
||||
@@ -1329,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();
|
||||
@@ -1356,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);
|
||||
@@ -1365,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;
|
||||
@@ -1396,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);
|
||||
@@ -1804,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)),
|
||||
@@ -2330,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];
|
||||
@@ -2341,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 = "";
|
||||
@@ -2387,6 +2506,7 @@ function updateRowValues(state) {
|
||||
master.classList.toggle("mixed", overall === "mixed");
|
||||
}
|
||||
decorateRows(state);
|
||||
decorateStrengthLinks(state);
|
||||
}
|
||||
|
||||
// ---------- absorb the loader chain ----------
|
||||
@@ -2868,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);
|
||||
@@ -2960,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,
|
||||
@@ -3091,6 +3212,7 @@ function ensureRedrawHook() {
|
||||
if (state.node.graph !== shown) continue;
|
||||
syncRows(state);
|
||||
refreshLocks(state);
|
||||
decorateStrengthLinks(state);
|
||||
}
|
||||
}, 250);
|
||||
});
|
||||
@@ -3196,6 +3318,7 @@ function watchBox(box) {
|
||||
function unmountCard(state, { resize = true } = {}) {
|
||||
liveCards.delete(state);
|
||||
state.disposed = true;
|
||||
state.unlinkStrengthWatch?.();
|
||||
state.nameObserver?.disconnect();
|
||||
closePopup();
|
||||
try {
|
||||
@@ -3289,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]);
|
||||
@@ -3351,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();
|
||||
|
||||
@@ -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;}
|
||||
`;
|
||||
@@ -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",
|
||||
|
||||
+42
-6
@@ -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
@@ -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 };
|
||||
}
|
||||
|
||||
@@ -48,8 +48,21 @@ export function clipLengthWords(timing) {
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
@@ -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
@@ -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.26.0";
|
||||
export const AUSBOSS_JS_VERSION = "2.26.7";
|
||||
|
||||
export const BRAND = "#00b4aa"; // AusBoss teal — keep node accents consistent.
|
||||
export const BRAND_DARK = "#007f78";
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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));
|
||||
};
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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("\\", "/");
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -11,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";
|
||||
@@ -82,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",
|
||||
@@ -107,7 +109,7 @@ const RESIZE_METHODS = ["lanczos", "area", "bicubic", "bilinear", "nearest-exact
|
||||
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() {
|
||||
@@ -1049,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) {
|
||||
@@ -2861,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));
|
||||
@@ -2888,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) {
|
||||
@@ -3106,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 });
|
||||
@@ -3343,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.
|
||||
|
||||
@@ -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 })]);
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
|
||||
@@ -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) {
|
||||
@@ -245,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
|
||||
|
||||
+28
-10
@@ -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" },
|
||||
|
||||
@@ -30,19 +30,25 @@ 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";
|
||||
@@ -94,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);
|
||||
@@ -124,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]);
|
||||
}
|
||||
@@ -132,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
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -214,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;}
|
||||
@@ -475,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");
|
||||
@@ -525,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"));
|
||||
@@ -612,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);
|
||||
@@ -639,11 +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;
|
||||
@@ -669,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`);
|
||||
@@ -695,7 +787,7 @@ async function checkModels(state, fresh) {
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -1002,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");
|
||||
@@ -1018,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);
|
||||
|
||||
+195
-3
@@ -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 视频放大 🆎",
|
||||
|
||||
@@ -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
|
||||
@@ -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
@@ -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)
|
||||
|
||||
@@ -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
@@ -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,
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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],
|
||||
|
||||
@@ -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))
|
||||
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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
@@ -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
@@ -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()
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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
@@ -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}"
|
||||
|
||||
@@ -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
@@ -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
@@ -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
|
||||
|
||||
@@ -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):
|
||||
|
||||
@@ -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))
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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"]
|
||||
@@ -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}.")
|
||||
|
||||
@@ -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),
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
@@ -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})
|
||||
|
||||
|
||||
|
||||
@@ -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})
|
||||
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -395,7 +395,7 @@ class AusBossVideoCropRotatePadClip:
|
||||
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(
|
||||
@@ -403,6 +403,7 @@ class AusBossVideoCropRotatePadClip:
|
||||
{
|
||||
"video": video,
|
||||
"source_mode": source_mode,
|
||||
"local_path": local_path,
|
||||
"start_seconds": round(float(start_seconds), 6),
|
||||
"end_seconds": round(float(end_seconds), 6),
|
||||
"every_nth": max(1, int(every_nth)),
|
||||
|
||||
+3
-2
@@ -2,8 +2,8 @@
|
||||
name = "ausboss-nodes"
|
||||
# Manager/registry search matches against this text, so it names the actual
|
||||
# nodes instead of describing the collection abstractly.
|
||||
description = "ComfyUI-AusBoss (AusBoss nodes): image and video nodes with compact controls: Image and Video Crop + Rotate + Pad (frame or clip), Load Image, Load Image + Pad, Image Folder, Image Resize, Align Image, Image Size, Color Match, Image Compare A/B, Realign to Source (experimental), Save Image (PNG, WebP/JXL, captions), Load Video, Load Audio, Save Video, Select Frame, Frame Interpolate, Mask Refine, Mask by Name and Mask by Touch, LaMa Inpaint, Crop For Inpaint, Stitch Inpaint, Tiled Upscale and Tiled Upscale Stitch, FlashVSR Upscale, Edit Lock and Edit Lock Restore, LoRA Loader, Krea 2 Encode and Outpaint Model Patch, Latent Size, Layout Boxes, Seed, Select Every Nth, Split Batch, Merge Batches, Text, Text Lines, Prompt Variations, H3 Prompt Writer, Integer, Float, Math Expression, Show Text, Free Memory, Workflow Note, Workflow Note Tile, Callout, Callout Tile, Workflow Switches, Run Timer, and Step Preview. Example workflows for Qwen Image 2.1, Krea 2, Klein 9B and LTX 2.3."
|
||||
version = "2.26.0"
|
||||
description = "ComfyUI-AusBoss (AusBoss nodes): image and video nodes with compact controls: Image and Video Crop + Rotate + Pad (frame or clip), Load Image, Load Image + Pad, Image Folder, Image Resize, Align Image, Image Size, Color Match, Image Compare A/B, Image Toolbox, Realign to Source (experimental), Save Image (PNG, WebP/JXL, captions), Load Video, Load Audio, Save Video, Select Frame, Frame Interpolate, Mask Refine, Mask by Name and Mask by Touch, LaMa Inpaint, Crop For Inpaint, Stitch Inpaint, Tiled Upscale and Tiled Upscale Stitch, FlashVSR Upscale, Edit Lock and Edit Lock Restore, LoRA Loader, Krea 2 Encode and Outpaint Model Patch, Latent Size, Layout Boxes, Seed, Select Every Nth, Split Batch, Merge Batches, Text, Text Lines, Prompt Variations, H3 Prompt Writer, Integer, Float, Math Expression, Show Text, Free Memory, Workflow Note, Workflow Note Tile, Callout, Callout Tile, Workflow Switches, Run Timer, and Step Preview. Examples for Qwen Image 2.1, Krea 2, Klein 9B and LTX 2.3."
|
||||
version = "2.26.7"
|
||||
# comfy-cli serializes this to JSON verbatim, so `file` publishes the literal
|
||||
# string {"file": "LICENSE"} to the registry listing. `text` puts a readable
|
||||
# name there instead. Both forms are supported; the LICENSE file is unchanged.
|
||||
@@ -22,6 +22,7 @@ keywords = [
|
||||
"tiled upscale", "upscale", "tiles", "restore", "layout boxes", "bounding boxes", "moss image", "replace text", "rotate box",
|
||||
"step preview", "live preview", "stop run",
|
||||
"text lines", "prompt list", "prompt variations", "wildcards", "flashvsr", "video upscale", "edit lock", "load image",
|
||||
"image toolbox", "split sheet", "character sheet",
|
||||
]
|
||||
|
||||
# Read by comfy-cli into the registry's supported_os field. Nothing in the pack
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// face_smoke.mjs <port> [--vue] [--only=Type,Type]
|
||||
// face_smoke.mjs <port> [--vue] [--blocked-reads] [--only=Type,Type]
|
||||
// Puts one of each of the pack's nodes on an empty graph and checks that its
|
||||
// face comes up. Run it against a ComfyUI tab on the headless Chrome at
|
||||
// <port> (COMFY_URL picks the server). No model is needed and nothing is
|
||||
@@ -14,6 +14,12 @@
|
||||
// often says things of its own.
|
||||
//
|
||||
// --vue Nodes 2.0 instead of the classic renderer
|
||||
// --blocked-reads
|
||||
// acts like a privacy browser (Firefox's fingerprint protection,
|
||||
// canvas blockers) that hands back blank pixels when a page reads
|
||||
// a canvas. Every node that loads a picture gets a sample picture,
|
||||
// and fails when its face then draws no picture: the bug that
|
||||
// left Image Crop + Rotate + Pad's stage empty in those browsers.
|
||||
// --only= a comma-separated list of node types
|
||||
//
|
||||
// Exits 1 when a node fails, 2 when the pack registered no node at all.
|
||||
@@ -22,8 +28,9 @@ const args = process.argv.slice(2);
|
||||
const port = args.find((arg) => !arg.startsWith("--"));
|
||||
const flag = (name) => args.find((arg) => arg.startsWith(`--${name}=`))?.slice(name.length + 3) ?? null;
|
||||
const vue = args.includes("--vue");
|
||||
const blockedReads = args.includes("--blocked-reads");
|
||||
const only = flag("only")?.split(",").filter(Boolean) ?? null;
|
||||
if (!port) { console.error("usage: face_smoke.mjs <port> [--vue] [--only=Type,Type]"); process.exit(2); }
|
||||
if (!port) { console.error("usage: face_smoke.mjs <port> [--vue] [--blocked-reads] [--only=Type,Type]"); process.exit(2); }
|
||||
|
||||
const COMFY = new URL(process.env.COMFY_URL || "http://127.0.0.1:8188/").href;
|
||||
const page = await (await fetch(`http://127.0.0.1:${port}/json/new?about:blank`, { method: "PUT" })).json();
|
||||
@@ -67,6 +74,17 @@ const ofThePack = (entry) => OF_THE_PACK.test(entry.text) || OF_THE_PACK.test(en
|
||||
await send("Page.enable"); await send("Runtime.enable");
|
||||
await send("Emulation.setDeviceMetricsOverride", { width: 1800, height: 1100, deviceScaleFactor: 1, mobile: false });
|
||||
await send("Network.enable"); await send("Network.setCacheDisabled", { cacheDisabled: true });
|
||||
// Blank every pixel read the page makes, before any of its code runs. The
|
||||
// smoke test keeps the real read for itself, to see what a face drew.
|
||||
if (blockedReads) {
|
||||
await send("Page.addScriptToEvaluateOnNewDocument", { source: `(() => {
|
||||
const real = CanvasRenderingContext2D.prototype.getImageData;
|
||||
Object.defineProperty(window, "__faceSmokeRealRead", { value: real });
|
||||
CanvasRenderingContext2D.prototype.getImageData = function (...args) {
|
||||
const data = real.apply(this, args); data.data.fill(0); return data;
|
||||
};
|
||||
})();` });
|
||||
}
|
||||
await send("Page.navigate", { url: COMFY });
|
||||
let ready = false;
|
||||
for (let i = 0; i < 240 && !ready; i++) { await sleep(500); ready = await evalJs("Boolean(window.app?.graph && window.app?.canvas && window.LiteGraph?.registered_node_types)").catch(() => false); }
|
||||
@@ -85,6 +103,26 @@ if (only) {
|
||||
if (!types.length) { console.error(`None of ${only.join(", ")} is a node of the pack on this page.`); ws.close(); process.exit(2); }
|
||||
}
|
||||
|
||||
// The sample picture for --blocked-reads, put in ComfyUI's input folder.
|
||||
const SAMPLE = "ausboss_face_smoke.png";
|
||||
if (blockedReads) {
|
||||
const { readFileSync } = await import("node:fs");
|
||||
const bytes = readFileSync(new URL("../../example_workflows/inputs/ausboss_pier_sunrise.png", import.meta.url)).toString("base64");
|
||||
const uploaded = await evalJs(`(async () => {
|
||||
const bytes = Uint8Array.from(atob(${JSON.stringify(bytes)}), (c) => c.charCodeAt(0));
|
||||
const body = new FormData();
|
||||
body.append("image", new Blob([bytes], { type: "image/png" }), ${JSON.stringify(SAMPLE)});
|
||||
body.append("overwrite", "true");
|
||||
const response = await window.comfyAPI.api.api.fetchApi("/upload/image", { method: "POST", body });
|
||||
return response.ok;
|
||||
})()`).catch((error) => String(error.message ?? error));
|
||||
if (uploaded !== true) { console.error(`Could not upload the sample picture: ${uploaded}`); ws.close(); process.exit(2); }
|
||||
}
|
||||
// How many different colours a face's canvases show, read with the real
|
||||
// pixel read. With the sample picture a face that drew it shows 350 or more;
|
||||
// the empty crop stage of the bug, with its handles and tint, showed 100.
|
||||
const PICTURE_COLOURS = 200;
|
||||
|
||||
const loading = said.splice(0).filter(ofThePack);
|
||||
let failed = 0;
|
||||
for (const entry of loading) { failed += 1; console.log(`FAIL while the page loaded: ${entry.text}`); }
|
||||
@@ -115,7 +153,28 @@ for (const type of types) {
|
||||
shown: widget.element.isConnected && getComputedStyle(widget.element).display !== "none",
|
||||
size: widget.element.isConnected ? box(widget.element) : [0, 0],
|
||||
}));
|
||||
return { size: [Math.round(node.size[0]), Math.round(node.size[1])], drawn: host ? box(host) : null, widgets: (node.widgets ?? []).length, panels };
|
||||
let colours = null;
|
||||
const source = ${blockedReads} ? (node.widgets ?? []).find((widget) => widget.name === "image" && Array.isArray(widget.options?.values)) : null;
|
||||
if (source) {
|
||||
if (!source.options.values.includes(${JSON.stringify(SAMPLE)})) source.options.values.push(${JSON.stringify(SAMPLE)});
|
||||
source.value = ${JSON.stringify(SAMPLE)}; source.callback?.(source.value);
|
||||
app.canvas.setDirty(true, true);
|
||||
await new Promise((resolve) => setTimeout(resolve, 2500));
|
||||
await new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)));
|
||||
const canvases = (node.widgets ?? []).filter((widget) => widget.element instanceof Element)
|
||||
.flatMap((widget) => [widget.element, ...widget.element.querySelectorAll("canvas")])
|
||||
.filter((el) => el instanceof HTMLCanvasElement && el.width > 0 && el.height > 0);
|
||||
if (canvases.length) {
|
||||
colours = 0;
|
||||
for (const canvas of canvases) {
|
||||
const data = window.__faceSmokeRealRead.call(canvas.getContext("2d"), 0, 0, canvas.width, canvas.height).data;
|
||||
const seen = new Set();
|
||||
for (let i = 0; i < data.length; i += 4 * 7) seen.add((data[i] >> 3) << 10 | (data[i + 1] >> 3) << 5 | data[i + 2] >> 3);
|
||||
colours = Math.max(colours, seen.size);
|
||||
}
|
||||
}
|
||||
}
|
||||
return { size: [Math.round(node.size[0]), Math.round(node.size[1])], drawn: host ? box(host) : null, widgets: (node.widgets ?? []).length, panels, colours };
|
||||
})()`).catch((error) => ({ error: String(error.message ?? error).slice(0, 400) }));
|
||||
await sleep(150);
|
||||
const problems = [];
|
||||
@@ -127,6 +186,9 @@ for (const type of types) {
|
||||
}
|
||||
if (vue && !seen.drawn) problems.push("Nodes 2.0 drew no element for the node");
|
||||
if (seen.drawn && !(seen.drawn[0] > 20 && seen.drawn[1] > 20)) problems.push(`the node is drawn ${seen.drawn.join(" x ")}`);
|
||||
if (seen.colours != null && seen.colours < PICTURE_COLOURS) {
|
||||
problems.push(`with pixel reads blocked its face drew no picture (${seen.colours} colours on its canvas)`);
|
||||
}
|
||||
for (const panel of seen.panels) {
|
||||
if (!panel.onPage) problems.push(`its panel '${panel.name}' is not on the page`);
|
||||
else if (panel.shown && !(panel.size[0] > 4 && panel.size[1] > 4)) problems.push(`its panel '${panel.name}' is ${panel.size.join(" x ")}`);
|
||||
@@ -137,7 +199,7 @@ for (const type of types) {
|
||||
}
|
||||
const others = said.filter((entry) => !entry.thrown && !ofThePack(entry));
|
||||
failed += problems.length ? 1 : 0;
|
||||
const sizes = seen.error ? "" : ` ${seen.size.join(" x ")}${seen.panels.length ? `, ${seen.panels.length} panel${seen.panels.length > 1 ? "s" : ""}` : ""}`;
|
||||
const sizes = seen.error ? "" : ` ${seen.size.join(" x ")}${seen.panels.length ? `, ${seen.panels.length} panel${seen.panels.length > 1 ? "s" : ""}` : ""}${seen.colours != null ? `, ${seen.colours} colours` : ""}`;
|
||||
console.log(`${problems.length ? "FAIL" : "ok "} ${type}${sizes}`);
|
||||
for (const problem of problems) console.log(` ${problem}`);
|
||||
for (const entry of others) console.log(` (console, not counted) ${entry.text.slice(0, 200)}`);
|
||||
@@ -145,7 +207,7 @@ for (const type of types) {
|
||||
for (const file of lostFiles) { failed += 1; console.log(`FAIL a file of the pack did not load: ${file}`); }
|
||||
|
||||
await evalJs(`(async () => { window.app.graph.clear(); await window.app.extensionManager.setting.set("Comfy.VueNodes.Enabled", ${JSON.stringify(rendererBefore ?? false)}); return true; })()`).catch(() => {});
|
||||
console.log(`\n${vue ? "Nodes 2.0" : "classic"}: ${types.length} nodes, ${failed} failed`);
|
||||
console.log(`\n${vue ? "Nodes 2.0" : "classic"}${blockedReads ? ", pixel reads blocked" : ""}: ${types.length} nodes, ${failed} failed`);
|
||||
await fetch(`http://127.0.0.1:${port}/json/close/${page.id}`).catch(() => {});
|
||||
ws.close();
|
||||
process.exit(failed ? 1 : 0);
|
||||
|
||||
@@ -130,6 +130,7 @@ import fnmatch
|
||||
ARCHIVE_ALLOWLIST = (
|
||||
"__init__.py", "nodes/", "js/", "example_workflows/", "README.md",
|
||||
"LICENSE", "pyproject.toml", "ausboss_presets_example.json", "locales/",
|
||||
"web_second_copy/",
|
||||
)
|
||||
# Besides every allowlist entry these must ship too: the node help pages and
|
||||
# the sample media the example workflows load.
|
||||
@@ -298,6 +299,7 @@ NETWORK_PATTERNS = {
|
||||
NETWORK_IMPORTS = {"requests", "httpx", "socket", "urllib.request", "http.client", "aiohttp.ClientSession"}
|
||||
shipped_source = [ROOT / "__init__.py", *sorted((ROOT / "nodes").rglob("*.py"))]
|
||||
shipped_source += sorted(p for p in (ROOT / "js").rglob("*") if p.suffix in (".js", ".mjs"))
|
||||
shipped_source += sorted(p for p in (ROOT / "web_second_copy").rglob("*") if p.suffix in (".js", ".mjs"))
|
||||
for path in shipped_source:
|
||||
if "__pycache__" in path.parts or not path.is_file():
|
||||
continue
|
||||
|
||||
@@ -67,6 +67,7 @@ PUBLIC_NODE_IDS = {
|
||||
"AUSBOSS_NODES_ImageFolder",
|
||||
"AUSBOSS_NODES_ImageResize",
|
||||
"AUSBOSS_NODES_ImageSize",
|
||||
"AUSBOSS_NODES_ImageToolbox",
|
||||
"AUSBOSS_NODES_Integer",
|
||||
"AUSBOSS_NODES_Krea2Encode",
|
||||
"AUSBOSS_NODES_Krea2OutpaintModelPatch",
|
||||
|
||||
@@ -76,6 +76,10 @@ def pack_widget_names() -> dict[str, list[str]]:
|
||||
groups = {k.value: v for k, v in zip(returned[0].keys, returned[0].values) if isinstance(k, ast.Constant)}
|
||||
for group in ("required", "optional"):
|
||||
inputs = groups.get(group)
|
||||
# A group wrapped in a call, such as LoRA Loader's open
|
||||
# optional inputs, lists its fixed inputs in the one dict.
|
||||
if isinstance(inputs, ast.Call) and len(inputs.args) == 1:
|
||||
inputs = inputs.args[0]
|
||||
if not isinstance(inputs, ast.Dict):
|
||||
continue
|
||||
for name, spec in zip(inputs.keys, inputs.values):
|
||||
|
||||
@@ -0,0 +1,305 @@
|
||||
---
|
||||
name: ausboss-workflows
|
||||
description: Write the words for AusBoss ComfyUI video workflows (MiniMax H3 Pika Person Swap and Pika Remix, through the H3 Prompt Writer node), and set up and run those workflows on the person's own computer. Use when someone shares ausboss-examples.vercel.app, asks for a person swap, a video remix or an H3 prompt, or wants an AusBoss workflow installed or run for them.
|
||||
license: MIT
|
||||
compatibility: Writing the words needs nothing. Running needs ComfyUI 0.38 or newer on the person's computer, an 8 GB or larger graphics card, and a browser the agent can drive.
|
||||
metadata:
|
||||
author: AusBoss
|
||||
homepage: https://ausboss-examples.vercel.app/
|
||||
updated: "2026-11-16"
|
||||
---
|
||||
|
||||
# AusBoss workflows
|
||||
|
||||
AusBoss makes a pack of ComfyUI nodes and the workflows built on them. This
|
||||
page is for an AI agent helping someone use those workflows. It covers three
|
||||
jobs, from light to heavy:
|
||||
|
||||
1. **Write the words.** The person says what they want; you write what goes in
|
||||
the workflow's text box and say which settings to pick.
|
||||
2. **Set it up.** Install the node pack and the model files.
|
||||
3. **Run it for them.** Load the workflow in their ComfyUI, put in their files
|
||||
and your words, run it, and hand back the clip.
|
||||
|
||||
Offer the third job when you can run commands on the person's computer. Ask
|
||||
before you start it: it downloads large files (see "Model files") and uses
|
||||
their graphics card for several minutes a clip.
|
||||
|
||||
## Where everything is
|
||||
|
||||
| What | Where |
|
||||
|---|---|
|
||||
| Node pack (source, help pages, issues) | https://github.com/ausboss/ComfyUI-AusBoss |
|
||||
| The pack's own guide for agents (which node does which job) | https://github.com/ausboss/ComfyUI-AusBoss/blob/main/js/docs/agents/README.md |
|
||||
| Workflows | https://civitai.com/user/AusBoss |
|
||||
| Models and LoRAs | https://huggingface.co/ausboss |
|
||||
| Real example runs (this site) | https://ausboss-examples.vercel.app/ |
|
||||
| Help from people, and every workflow file | https://discord.gg/RwVxY9Fuaj |
|
||||
| Video guides | https://www.youtube.com/@ausbossdev |
|
||||
|
||||
The examples on this site are real runs. Each page has a plain-text copy with
|
||||
every script, setting, prompt and file link:
|
||||
|
||||
- Person Swap Examples (4 examples): https://ausboss-examples.vercel.app/person-swap/index.md
|
||||
- Pika Remix Examples (8 examples): https://ausboss-examples.vercel.app/pika-remix/index.md
|
||||
- Fix a Pika Remix or Person Swap Run (a guide): https://ausboss-examples.vercel.app/fix/index.md
|
||||
- Faster Video in ComfyUI (a guide): https://ausboss-examples.vercel.app/speed/index.md
|
||||
|
||||
Read the matching page before you write for a workflow. A real example close
|
||||
to the person's request is the best starting point.
|
||||
|
||||
## The workflows
|
||||
|
||||
| Workflow | What it does | Get it | Real runs |
|
||||
|---|---|---|---|
|
||||
| MiniMax H3 Pika Person Swap | Swaps the person in a clip for the person in one photo. The place, camera, moves and sound stay. | https://civitai.com/models/3040833 | https://ausboss-examples.vercel.app/person-swap/index.md |
|
||||
| MiniMax H3 Pika Remix | Changes, swaps or copies a video using up to four pictures. Also starts a clip from a picture, or goes from one picture to another. | https://civitai.com/models/3050155 | https://ausboss-examples.vercel.app/pika-remix/index.md |
|
||||
|
||||
Both make video with sound, up to 15 seconds, with the MiniMax H3 model and
|
||||
the Pika H3 Flex LoRA. Both have a High VRAM setting (24 GB or more) and a Low
|
||||
VRAM setting (8 to 24 GB; on 8 GB, clips up to 8 seconds and 32 GB of RAM).
|
||||
|
||||
## Write the words
|
||||
|
||||
Both workflows have one text box, on the node titled
|
||||
**H3 Prompt Writer - What happens**. The person types plain lines there and
|
||||
the node writes the model's long prompt itself. So you write short plain
|
||||
lines, never the long prompt. The full rules are on the node's help page:
|
||||
https://github.com/ausboss/ComfyUI-AusBoss/blob/main/js/docs/AUSBOSS_NODES_H3PromptWriter.md
|
||||
If that page and this one disagree, that page is right.
|
||||
|
||||
### The basics
|
||||
|
||||
- One line is one moment. Lines play in order. About one moment a second is
|
||||
the most the model can play.
|
||||
- A blank line cuts to a new place.
|
||||
- `@1` to `@4` name the pictures plugged in. Each picture has a job, picked
|
||||
under the text box.
|
||||
- Say what a camera would see. `She smiles` works; `She feels happy` does not.
|
||||
- Nothing moves or exists unless a line says so.
|
||||
- Say which way people face, and where they end up.
|
||||
- Spoken words go in quotes, with the speaker named: `@1 says "we are late."`
|
||||
- Put the spoken line last. With time left after it, the model keeps talking.
|
||||
|
||||
### Picture jobs
|
||||
|
||||
| Job | Use it for |
|
||||
|---|---|
|
||||
| person | This person goes where the lines say. A clear photo. |
|
||||
| character sheet | One character drawn from several sides. |
|
||||
| place | Where it happens. A picture with nobody in it. |
|
||||
| outfit | Clothes for the person. Best with no head in the picture. |
|
||||
| thing | An object, product, toy or mascot. |
|
||||
| style | Only the look is used, for the whole clip. |
|
||||
| start on it | The clip starts from this picture. |
|
||||
| end on it | The clip lands on this picture. It can't be named with `@`. |
|
||||
|
||||
### Video jobs
|
||||
|
||||
| Job | What happens | What to type |
|
||||
|---|---|---|
|
||||
| swap the person | The pictured person takes over from the one in the video. | Who goes, by what they look like: `Replace the man in the hat with @1.` |
|
||||
| copy its moves | The pictured person does the video's moves somewhere new. | `@1 dances on a rooftop at sunset.` |
|
||||
| change something | The video stays, with one change. | The change, exactly: `She wears a red raincoat.` |
|
||||
| keep going | More of the same clip, from where it ends. | What happens next, or nothing. |
|
||||
| new voice | The same clip with a new voice. | The words, in quotes. Needs a voice clip. |
|
||||
|
||||
For **swap the person**, **change something** and **new voice**, the clip's
|
||||
length comes from the video. To make it shorter, trim the video on its loader.
|
||||
|
||||
### Person swap: the lines that work
|
||||
|
||||
```
|
||||
Replace the man in the suit holding an ice cream with @1.
|
||||
@1 looks like a heavy-set man with round glasses, a white shirt and green trousers.
|
||||
```
|
||||
|
||||
- Line 1 says who goes. Describe them by what is seen in the clip (clothes,
|
||||
hair, position), so the others in the shot are left alone.
|
||||
- Line 2 is optional and describes the new person. Write it from their photo.
|
||||
It helps the look; it does not promise an exact likeness. The Person Swap
|
||||
workflow can write this line itself: the **Describe @1 for me** switch.
|
||||
- If the photo shows only a face, write the clothes too. What the photo does
|
||||
not show, the model makes up.
|
||||
- The face in the clip has to be clear. A small or turned-away face keeps the
|
||||
clip's own person.
|
||||
- **Keep the clip's sound** on: the clip's own voice and music stay and the
|
||||
new mouth follows them. Off, with words in quotes: the model makes a new
|
||||
voice.
|
||||
|
||||
### Other things a line can do
|
||||
|
||||
- A time: start a line with `3s:` and it happens at 3 seconds.
|
||||
- `sound: rain on a tin roof` and `music: slow sad piano`. With no music line
|
||||
there is no music.
|
||||
- `camera: slow push in` and `look: a 1970s film`.
|
||||
- `no cuts` makes blank lines stop being cuts.
|
||||
- `ends on her sitting by the window` sets the last moment.
|
||||
- A sign: `a neon sign reads "OPEN"`.
|
||||
|
||||
### What to hand the person
|
||||
|
||||
When you only write the words, give them:
|
||||
|
||||
1. The lines, in a code block they can paste into the text box.
|
||||
2. Which file goes in which loader (`@1` is Picture 1, and so on).
|
||||
3. The job for each picture and for the video.
|
||||
4. Any switch to change, such as **Keep the clip's sound**.
|
||||
|
||||
A voice clip should be the person's own voice, or one they have permission to
|
||||
use. Only swap a real person into a clip when the person asking has the right
|
||||
to use that photo.
|
||||
|
||||
## Set it up
|
||||
|
||||
Check before you install anything:
|
||||
|
||||
```bash
|
||||
curl -s http://127.0.0.1:8188/system_stats
|
||||
```
|
||||
|
||||
That answers when ComfyUI is running on its usual port, with its version and
|
||||
the graphics card's memory. If nothing answers, ask the person where their
|
||||
ComfyUI is and how they start it. If they have none, the official install
|
||||
guide is https://docs.comfy.org/installation and that choice is theirs.
|
||||
|
||||
### The node pack
|
||||
|
||||
Either of these, then restart ComfyUI:
|
||||
|
||||
```bash
|
||||
comfy node install ausboss-nodes
|
||||
```
|
||||
|
||||
```bash
|
||||
git clone https://github.com/ausboss/ComfyUI-AusBoss.git ausboss-nodes
|
||||
```
|
||||
|
||||
The first needs comfy-cli. The second runs inside ComfyUI's `custom_nodes`
|
||||
folder. In the ComfyUI window, the person can also open the Manager, search
|
||||
for **AusBoss** and install it there. After the restart this returns the
|
||||
node, which shows the pack loaded:
|
||||
|
||||
```bash
|
||||
curl -s http://127.0.0.1:8188/object_info/AUSBOSS_NODES_H3PromptWriter
|
||||
```
|
||||
|
||||
### Model files
|
||||
|
||||
The files go in ComfyUI's `models` folder, in the subfolder named below. They
|
||||
are large. Tell the person the total and get a yes before you download. Skip
|
||||
any file they already have.
|
||||
|
||||
| File | Folder in `models` | Size | Needed |
|
||||
|---|---|---|---|
|
||||
| [qwen3vl_32b_minimax_h3_nvfp4_awq.safetensors](https://huggingface.co/Comfy-Org/MiniMax-H3/resolve/main/text_encoders/qwen3vl_32b_minimax_h3_nvfp4_awq.safetensors) | `text_encoders` | 15.7 GB | always |
|
||||
| [minimax_h3_audio_vae_fp32.safetensors](https://huggingface.co/Comfy-Org/MiniMax-H3/resolve/main/vae/minimax_h3_audio_vae_fp32.safetensors) | `vae` | 0.6 GB | always |
|
||||
| [pika_h3_flex_ref2va_v1_bf16.safetensors](https://huggingface.co/Comfy-Org/MiniMax-H3/resolve/main/loras/pika_h3_flex_ref2va_v1_bf16.safetensors) | `loras` | 2.0 GB | always |
|
||||
| [minimax_h3_ref2va_pruned_int8_convrot.safetensors](https://huggingface.co/Comfy-Org/MiniMax-H3/resolve/main/diffusion_models/minimax_h3_ref2va_pruned_int8_convrot.safetensors) | `diffusion_models` | 21.0 GB | High VRAM |
|
||||
| [minimax_h3_video_vae_fp16.safetensors](https://huggingface.co/Comfy-Org/MiniMax-H3/resolve/main/vae/minimax_h3_video_vae_fp16.safetensors) | `vae` | 5.2 GB | High VRAM |
|
||||
| [minimax_h3_ref2va_pruned_w6a8.safetensors](https://huggingface.co/Comfy-Org/MiniMax-H3/resolve/main/diffusion_models/minimax_h3_ref2va_pruned_w6a8.safetensors) | `diffusion_models` | 16.0 GB | Low VRAM |
|
||||
| [minimax_h3_video_vae_int8_convrot.safetensors](https://huggingface.co/Comfy-Org/MiniMax-H3/resolve/main/vae/minimax_h3_video_vae_int8_convrot.safetensors) | `vae` | 2.8 GB | Low VRAM |
|
||||
| [flashvsr_v1.1_fp16.safetensors](https://huggingface.co/ausboss/FlashVSR-v1.1-ComfyUI/resolve/main/flashvsr_v1.1_fp16.safetensors) | `diffusion_models` | 3.5 GB | only for Finish: FlashVSR |
|
||||
|
||||
High VRAM needs about 44 GB of files, Low VRAM about 37 GB. The optional switches that write text for you (such as **Describe @1 for me**) use a small Qwen3-VL 8B text model; the workflow's Guide note names that file and where to get it.
|
||||
|
||||
Each workflow opens with a Guide note that lists its files. If the note and
|
||||
this table disagree, the note in the newest workflow is right.
|
||||
|
||||
### Faster runs
|
||||
|
||||
One node or one launch setting makes these workflows about twice as fast on
|
||||
most recent cards: https://ausboss-examples.vercel.app/speed/index.md
|
||||
|
||||
## Run it for them
|
||||
|
||||
### Get the workflow file
|
||||
|
||||
- The newest file is on the workflow's Civitai page (links above). Civitai may
|
||||
ask for a login. If it does, ask the person to download the file and tell
|
||||
you where it is. The same files are in the Discord.
|
||||
- Each Person Swap example on this site also has a zip with the workflow set
|
||||
up exactly as it ran, its input files and its result. Those can be older
|
||||
than the Civitai file. They are good for a first test run: the result is
|
||||
there to compare with.
|
||||
|
||||
### Put the person's files in place
|
||||
|
||||
Copy their clip and pictures into ComfyUI's `input` folder, or upload them:
|
||||
|
||||
```bash
|
||||
curl -s -F "image=@/path/to/photo.jpg" http://127.0.0.1:8188/upload/image
|
||||
```
|
||||
|
||||
The same address takes video and audio files.
|
||||
|
||||
### Load it in ComfyUI's own page and run
|
||||
|
||||
These workflows have switches and grouped parts that only ComfyUI's page
|
||||
turns into a run. So do not rewrite the file into an API prompt by hand:
|
||||
open the page, load the file there, and let the page queue it. Any browser
|
||||
you can drive works, headless or not (Chrome started with
|
||||
`--remote-debugging-port`, Playwright, or a browser tool).
|
||||
|
||||
On the page at `http://127.0.0.1:8188/`, once `window.app.graph` exists:
|
||||
|
||||
```js
|
||||
await app.loadGraphData(workflow); // the parsed workflow file
|
||||
const node = (title) => app.graph.nodes.find((n) => n.title === title);
|
||||
const set = (title, name, value) => {
|
||||
const w = node(title).widgets.find((w) => w.name === name);
|
||||
w.value = value;
|
||||
w.callback?.(value);
|
||||
};
|
||||
set("H3 Prompt Writer - What happens", "script", "Replace the man in the hat with @1.");
|
||||
set("Video - Your clip", "video", "their_clip.mp4");
|
||||
set("Picture 1 - @1", "image", "their_photo.jpg");
|
||||
set("Seed", "seed", 6202);
|
||||
await app.queuePrompt(0);
|
||||
```
|
||||
|
||||
Find a node by its title and a setting by its name. The titles above are the
|
||||
ones in Person Swap; read `app.graph.nodes.map((n) => n.title)` for any other
|
||||
workflow. `await app.graphToPrompt()` shows what would be sent without running
|
||||
anything, which is a cheap check before you queue.
|
||||
|
||||
**Switches** (VRAM, Keep the clip's sound, Describe @1 for me, Finish) are
|
||||
cards on the canvas. To flip one without clicking, change the workflow file
|
||||
before you load it, as the pack's guide describes:
|
||||
https://github.com/ausboss/ComfyUI-AusBoss/blob/main/js/docs/agents/workflow_switches.md
|
||||
With a browser tool that can click, clicking the switch on the card is
|
||||
simpler. Pick **Low VRAM** when the card has less than 24 GB.
|
||||
|
||||
### Wait, then hand back the clip
|
||||
|
||||
`queuePrompt` returns right away. Watch the run with:
|
||||
|
||||
```bash
|
||||
curl -s http://127.0.0.1:8188/queue
|
||||
```
|
||||
|
||||
```bash
|
||||
curl -s http://127.0.0.1:8188/history
|
||||
```
|
||||
|
||||
A clip takes a few minutes; the first run is longer because the models load.
|
||||
The finished clip is in ComfyUI's `output` folder, and the history entry
|
||||
names the file. Tell the person where it is, and show it if you can.
|
||||
|
||||
### If it fails
|
||||
|
||||
- A loader turns red or the run stops on a file name: that model file is
|
||||
missing or has another name. Pick the person's copy in that loader.
|
||||
- Out of memory: pick **Low VRAM**, use a shorter clip, or turn on
|
||||
**Fast preview**.
|
||||
- The swap kept the clip's own person: the face in the clip is too small or
|
||||
turned away, or line 1 did not describe who goes.
|
||||
- A clip came out wrong but ran: run again with a new seed.
|
||||
- Anything else: the pack's issues
|
||||
(https://github.com/ausboss/ComfyUI-AusBoss/issues) and the Discord.
|
||||
|
||||
## About this page
|
||||
|
||||
Everything here is public information from AusBoss about his own nodes and
|
||||
workflows. It gives no instruction to act without the person's say: installs,
|
||||
downloads and runs are theirs to approve.
|
||||
@@ -102,3 +102,39 @@ test("a server that does not answer keeps the page quiet", async (t) => {
|
||||
await page.serverComesBack("2.7.0");
|
||||
assert.equal(page.toasts.length, 1);
|
||||
});
|
||||
|
||||
// The Manager switches the pack's files on disk, and the server keeps running
|
||||
// the old version until ComfyUI restarts. A reload in between gives the page
|
||||
// the new files: the page is newer than the server, and "press F5" is wrong.
|
||||
test("a page newer than the server says nothing", async (t) => {
|
||||
const page = await openPage(t, { running: "2.26.2", installed: "2.25.2" });
|
||||
assert.deepEqual(page.toasts, []);
|
||||
assert.deepEqual(page.refreshed, []);
|
||||
await page.serverComesBack("2.26.2");
|
||||
assert.deepEqual(page.toasts, [], "after the restart the two match");
|
||||
});
|
||||
|
||||
test("versions compare as numbers, not as text", async (t) => {
|
||||
const older = await openPage(t, { running: "2.25.10", installed: "2.25.9" });
|
||||
assert.deepEqual(older.toasts, [], "2.25.9 is older than 2.25.10");
|
||||
const newer = await openPage(t, { running: "2.25.9", installed: "2.25.10" });
|
||||
assert.equal(newer.toasts.length, 1, "2.25.10 is newer than 2.25.9");
|
||||
assert.match(newer.toasts[0].detail, /v2\.25\.10 is installed/);
|
||||
});
|
||||
|
||||
test("an unknown or odd version says nothing", async (t) => {
|
||||
for (const [running, installed] of [
|
||||
["2.26.2", "unknown"],
|
||||
["2.26.2", "2.27"],
|
||||
["2.26.2", "2.27.0rc1"],
|
||||
["2.26.2", "v2.27.0"],
|
||||
["2.26.2", 3],
|
||||
["unknown", "2.27.0"],
|
||||
["dev", "2.27.0"],
|
||||
[null, "2.27.0"],
|
||||
]) {
|
||||
const page = await openPage(t, { running, installed });
|
||||
assert.deepEqual(page.toasts, [], `page ${running}, server ${installed}`);
|
||||
assert.deepEqual(page.refreshed, [], `page ${running}, server ${installed}`);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -142,6 +142,7 @@ test("only the listed parts of the pack listen for the wheel", () => {
|
||||
"image_folder/index.js root", // the copy question, a window over the page
|
||||
"image_folder/index.js root", // the folder list, a window over the page
|
||||
"shared/discard_prompt.mjs backdrop", // the keep or discard question
|
||||
"shared/h3_cast_chips.mjs window", // closes a chip's job list when the graph moves
|
||||
"shared/media_picker.mjs window", // closes its list when the graph moves
|
||||
"shared/transform_editor.mjs canvas", // the full-screen editor zooms its picture
|
||||
"shared/widget_card.mjs area", // a text box scrolls its own text first
|
||||
|
||||
+35
-2
@@ -7,6 +7,7 @@ import {
|
||||
slideFraction,
|
||||
compareClip,
|
||||
compareResultSide,
|
||||
savedRestSide,
|
||||
compareSizeLabel,
|
||||
findCompareImages,
|
||||
findComparePairs,
|
||||
@@ -167,13 +168,14 @@ test("A and B sit on either side of the split line and move with it", () => {
|
||||
// A graph as { node id: ids of the nodes wired into it }. A subgraph node
|
||||
// also lists, under `subgraphs`, the graph inside it and where each of its
|
||||
// outputs comes from in there.
|
||||
function view(feeds, subgraphs = {}) {
|
||||
function view(feeds, subgraphs = {}, switches = {}) {
|
||||
return {
|
||||
feeds: (id) => feeds[id] ?? [],
|
||||
branches: (id) => switches[id] ?? null,
|
||||
inside(id) {
|
||||
const inner = subgraphs[id];
|
||||
if (!inner) return null;
|
||||
return { ...view(inner.feeds, inner.subgraphs), output: (slot) => inner.outputs[slot] ?? null };
|
||||
return { ...view(inner.feeds, inner.subgraphs, inner.switches), output: (slot) => inner.outputs[slot] ?? null };
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -211,6 +213,37 @@ test("both pictures out of one subgraph are told apart inside it", () => {
|
||||
assert.equal(compareResultSide(from(12, 0), from(12, 1), open), "B");
|
||||
});
|
||||
|
||||
test("a before that a switch can fill with the result still rests on the result", () => {
|
||||
// An edit-or-generate subgraph: decode 213 is the picture, and "before" is
|
||||
// switch 460, your picture (-10) for an edit or the picture itself for a
|
||||
// new one. B feeds A only through one branch of the switch, so A is not
|
||||
// made from B and the panel rests on B, the result.
|
||||
const inner = {
|
||||
feeds: { 212: [-10], 213: [212], 480: [213], 460: [480, -10, -10] },
|
||||
switches: { 480: [213], 460: [480, -10] },
|
||||
outputs: [from(480), from(460)],
|
||||
};
|
||||
const graph = view({ 39: [6] }, { 39: inner });
|
||||
assert.equal(compareResultSide(from(39, 1), from(39, 0), graph), "B");
|
||||
assert.equal(compareResultSide(from(39, 0), from(39, 1), graph), "A");
|
||||
// The same at the top level: 4 hands on the result 3 or the loader 1.
|
||||
const picker = view({ 2: [1], 3: [2], 4: [3, 1, 9] }, {}, { 4: [3, 1] });
|
||||
assert.equal(compareResultSide(from(4), from(3), picker), "B");
|
||||
assert.equal(compareResultSide(from(3), from(4), picker), "A");
|
||||
// A switch between an edit of B and B itself, or a picture from elsewhere,
|
||||
// is still made from B.
|
||||
assert.equal(compareResultSide(from(4), from(1), view({ 2: [1], 4: [2, 1, 9] }, {}, { 4: [2, 1] })), "A");
|
||||
assert.equal(compareResultSide(from(4), from(1), view({ 2: [1], 4: [2, 7, 9] }, {}, { 4: [2, 7] })), "A");
|
||||
// A switch with no picture wired proves nothing.
|
||||
assert.equal(compareResultSide(from(4), from(1), view({ 4: [9] }, {}, { 4: [] })), "B");
|
||||
});
|
||||
|
||||
test("only A or B counts as a saved resting side", () => {
|
||||
assert.equal(savedRestSide("A"), "A");
|
||||
assert.equal(savedRestSide("B"), "B");
|
||||
for (const value of [undefined, null, "", "a", "b", "slide", 1, true]) assert.equal(savedRestSide(value), null);
|
||||
});
|
||||
|
||||
test("an input with nothing to compare against rests on B", () => {
|
||||
assert.equal(compareResultSide(null, from(1), view({})), "B");
|
||||
assert.equal(compareResultSide(from(1), null, view({})), "B");
|
||||
|
||||
Vendored
+22
-2
@@ -251,7 +251,8 @@
|
||||
"video_job",
|
||||
"sound",
|
||||
"music",
|
||||
"clip_sound"
|
||||
"clip_sound",
|
||||
"full_prompt"
|
||||
],
|
||||
"outputs": [
|
||||
[
|
||||
@@ -469,6 +470,20 @@
|
||||
]
|
||||
]
|
||||
},
|
||||
"AUSBOSS_NODES_ImageToolbox": {
|
||||
"required": [
|
||||
"image",
|
||||
"job",
|
||||
"pieces"
|
||||
],
|
||||
"optional": [],
|
||||
"outputs": [
|
||||
[
|
||||
"IMAGE",
|
||||
"images"
|
||||
]
|
||||
]
|
||||
},
|
||||
"AUSBOSS_NODES_Integer": {
|
||||
"required": [
|
||||
"value"
|
||||
@@ -562,6 +577,10 @@
|
||||
[
|
||||
"MASK",
|
||||
"mask"
|
||||
],
|
||||
[
|
||||
"STRING",
|
||||
"h3_prompt"
|
||||
]
|
||||
]
|
||||
},
|
||||
@@ -1091,7 +1110,8 @@
|
||||
"fix_edge_halo",
|
||||
"color_match",
|
||||
"seam",
|
||||
"paste_onto"
|
||||
"paste_onto",
|
||||
"follow_changes"
|
||||
],
|
||||
"outputs": [
|
||||
[
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { readFileSync } from "node:fs";
|
||||
|
||||
const source = readFileSync(new URL("../js/shared/h3_cast_chips.mjs", import.meta.url), "utf-8");
|
||||
|
||||
test("a chip's job list stays open while an item is pressed", () => {
|
||||
// Pressing an item takes focus off the chip's button. A capturing blur
|
||||
// listener heard that and closed the list before the click could pick.
|
||||
const blur = source.match(/addEventListener\("blur",[^\n]*/)?.[0] ?? "";
|
||||
assert.match(blur, /event\.target === window/, "only the window losing focus closes the list");
|
||||
assert.doesNotMatch(blur, /\bon\)/, "the blur listener is not the capturing set");
|
||||
assert.match(source, /menu\.addEventListener\("mousedown", \(event\) => event\.preventDefault\(\)\)/, "a press keeps focus on the button");
|
||||
});
|
||||
@@ -1,7 +1,8 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { clipSetsDuration, linkSource } from '../js/shared/h3_duration.mjs';
|
||||
import { cameraChoiceLabel, clipSetsDuration, linkSource } from '../js/shared/h3_duration.mjs';
|
||||
import { choiceLabel } from '../js/shared/widget_card_math.mjs';
|
||||
|
||||
const graphWith = (mode = 0, useMap = false) => {
|
||||
const source = { id: 150, mode };
|
||||
@@ -11,10 +12,27 @@ const graphWith = (mode = 0, useMap = false) => {
|
||||
getNodeById:id=>id===150?source:null,
|
||||
} } };
|
||||
};
|
||||
test('only the three backend duration overrides use the clip', () => {
|
||||
test('only the four backend duration overrides use the clip', () => {
|
||||
const {node}=graphWith();
|
||||
for(const job of ['swap the person','new voice','change something']) assert.equal(clipSetsDuration(node,{video_job:job}),true);
|
||||
for(const job of ['copy its moves','keep going','',undefined]) assert.equal(clipSetsDuration(node,{video_job:job}),false);
|
||||
for(const job of ['copy its moves','swap the person','new voice','change something']) assert.equal(clipSetsDuration(node,{video_job:job}),true);
|
||||
for(const job of ['keep going','',undefined]) assert.equal(clipSetsDuration(node,{video_job:job}),false);
|
||||
});
|
||||
test('Camera\'s first choice reads "from the video" while a live clip gives H3 its camera', () => {
|
||||
const {node,source}=graphWith();
|
||||
const row={labels:cameraChoiceLabel};
|
||||
const job=(value)=>{node.widgets=[{name:'video_job',value}];};
|
||||
for(const value of ['copy its moves','swap the person','new voice','change something']) {
|
||||
job(value);assert.equal(choiceLabel(row,'as typed',[],node),'from the video',value);
|
||||
}
|
||||
// Keep going makes new footage, so the camera is still the user's words.
|
||||
job('keep going');assert.equal(choiceLabel(row,'as typed',[],node),'as typed');
|
||||
job('swap the person');
|
||||
// Only the first choice changes; a picked move keeps its own name.
|
||||
assert.equal(choiceLabel(row,'slow push in',[],node),'slow push in');
|
||||
// A muted clip, no clip, or no node: the plain name.
|
||||
source.mode=4;assert.equal(choiceLabel(row,'as typed',[],node),'as typed');
|
||||
source.mode=0;node.inputs[0].link=null;assert.equal(choiceLabel(row,'as typed',[],node),'as typed');
|
||||
assert.equal(choiceLabel(row,'as typed',[]),'as typed');
|
||||
});
|
||||
test('Full Video OFF/bypassed/missing/disconnected restore seconds; both link stores work', () => {
|
||||
for(const map of [false,true]) {
|
||||
@@ -73,7 +91,7 @@ test('timeline omits guessed duration/retiming and rejects an old async report;
|
||||
const {momentStrip}=await import('data:text/javascript;base64,'+Buffer.from(source).toString('base64'));
|
||||
const {node,source:video}=graphWith();let refreshes=0;node.__ausbossCard={refresh(){refreshes++;}};
|
||||
const panel=momentStrip(node), [ruler,track,note]=panel.element.children;
|
||||
const values={seconds:12,script:'She walks.',video_job:'copy its moves'};
|
||||
const values={seconds:12,script:'She walks.',video_job:'keep going'};
|
||||
panel.sync(values);assert.equal(timers.length,1);timers.shift()();await Promise.resolve();
|
||||
assert.equal(requests[0].seconds,12);
|
||||
panel.sync({...values,video_job:'swap the person'});
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { FULL, SIMPLE, TAB_PROPERTY, boxText, editValue, isEdited, promptTab, writtenFromOutput } from "../js/shared/h3_full_prompt_math.mjs";
|
||||
import { visibleRows } from "../js/shared/widget_card_math.mjs";
|
||||
|
||||
const WRITTEN = "summary:\nA slow push in. One continuous shot with no cuts.";
|
||||
|
||||
test("an edit is kept only when it differs from what the node wrote", () => {
|
||||
assert.equal(editValue("summary:\nOne continuous shot with no cuts.", WRITTEN), "summary:\nOne continuous shot with no cuts.");
|
||||
assert.equal(editValue(WRITTEN, WRITTEN), "");
|
||||
assert.equal(editValue(` ${WRITTEN}\n`, WRITTEN), "");
|
||||
assert.equal(editValue(" \n", WRITTEN), "");
|
||||
// Before any run there is nothing written: whatever is typed is the edit.
|
||||
assert.equal(editValue("my own prompt", ""), "my own prompt");
|
||||
});
|
||||
|
||||
test("the box shows the edit, else the last written prompt", () => {
|
||||
assert.equal(boxText({ full_prompt: "" }, WRITTEN), WRITTEN);
|
||||
assert.equal(boxText({ full_prompt: "mine" }, WRITTEN), "mine");
|
||||
assert.equal(boxText({}, ""), "");
|
||||
assert.equal(isEdited({ full_prompt: " \n" }), false);
|
||||
assert.equal(isEdited({ full_prompt: "mine" }), true);
|
||||
});
|
||||
|
||||
test("the tab is Simple unless the node says Full", () => {
|
||||
assert.equal(promptTab({}), SIMPLE);
|
||||
assert.equal(promptTab({ properties: { [TAB_PROPERTY]: "nonsense" } }), SIMPLE);
|
||||
assert.equal(promptTab({ properties: { [TAB_PROPERTY]: FULL } }), FULL);
|
||||
});
|
||||
|
||||
test("the written prompt is read from a run's ui output", () => {
|
||||
assert.equal(writtenFromOutput({ written_prompt: [WRITTEN] }), WRITTEN);
|
||||
assert.equal(writtenFromOutput({ written_prompt: WRITTEN }), WRITTEN);
|
||||
assert.equal(writtenFromOutput({ text: ["other"] }), null);
|
||||
assert.equal(writtenFromOutput(null), null);
|
||||
});
|
||||
|
||||
test("a row's when can follow a choice kept on the node", () => {
|
||||
const simple = { widget: "script", when: (values, node) => promptTab(node) !== FULL };
|
||||
const full = { panel: () => ({}), when: (values, node) => promptTab(node) === FULL };
|
||||
const node = { properties: {} };
|
||||
assert.deepEqual(visibleRows([simple, full], {}, {}, node), [simple]);
|
||||
node.properties[TAB_PROPERTY] = FULL;
|
||||
assert.deepEqual(visibleRows([simple, full], {}, {}, node), [full]);
|
||||
});
|
||||
@@ -0,0 +1,72 @@
|
||||
// The Chinese on the pack's own node faces (js/shared/i18n.mjs).
|
||||
//
|
||||
// - a string with no Chinese entry stays English,
|
||||
// - every word a widget card shows has a Chinese entry, or is on the short
|
||||
// list of things that deliberately stay English,
|
||||
// - only displayed text is translated: nothing in a card config that names a
|
||||
// widget or a value is a key of the table by accident of spelling.
|
||||
|
||||
import assert from "node:assert/strict";
|
||||
import fs from "node:fs";
|
||||
import test from "node:test";
|
||||
|
||||
import { PATTERNS, STAYS_ENGLISH, ZH } from "../js/shared/i18n_zh.mjs";
|
||||
import { isChineseLocale, translateText } from "../js/shared/i18n.mjs";
|
||||
import { PANEL_LABELS } from "../js/shared/panel_controls.mjs";
|
||||
|
||||
const cards = fs.readFileSync(new URL("../js/widget_cards/index.js", import.meta.url), "utf8");
|
||||
|
||||
// Every string a card shows: row labels, group headers, pill texts, the
|
||||
// words of a choice (`labels`), tooltips (`title`, `titles`), placeholders,
|
||||
// button captions.
|
||||
function displayedStrings(source) {
|
||||
const found = new Set();
|
||||
const literal = (raw) => JSON.parse(`"${raw}"`);
|
||||
for (const match of source.matchAll(/\b(?:label|onText|offText|placeholder|title|muteTitle|readOnlyTitle|section|text|readOnlyText)\s*:\s*"((?:[^"\\]|\\.)*)"/g)) found.add(literal(match[1]));
|
||||
for (const block of source.matchAll(/\b(?:labels|titles)\s*:\s*\{([^}]*)\}/g)) {
|
||||
for (const match of block[1].matchAll(/:\s*"((?:[^"\\]|\\.)*)"/g)) found.add(literal(match[1]));
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
test("an unknown string stays English", () => {
|
||||
assert.equal(translateText("A sentence no table has ever heard of"), "A sentence no table has ever heard of");
|
||||
assert.equal(translateText(""), "");
|
||||
assert.equal(translateText(" "), " ");
|
||||
assert.equal(translateText("constructor"), "constructor");
|
||||
assert.equal(translateText("toString"), "toString");
|
||||
assert.equal(translateText("Preview", {}, []), "Preview");
|
||||
});
|
||||
|
||||
test("a known string is translated and keeps the spaces around it", () => {
|
||||
assert.equal(translateText("Feather"), ZH.Feather);
|
||||
assert.equal(translateText(" Feather\n"), ` ${ZH.Feather}\n`);
|
||||
assert.notEqual(ZH.Feather, "Feather");
|
||||
});
|
||||
|
||||
test("the scrub hint is translated around a tooltip", () => {
|
||||
const out = translateText("Feather. Drag to scrub, click to type a number or a sum (1024*1.5), arrows to step; Shift = fine.");
|
||||
assert.match(out, /拖动调节/);
|
||||
assert.ok(out.startsWith("Feather."));
|
||||
const known = translateText("Do nothing Drag to scrub, click to type a number or a sum (1024*1.5), arrows to step; Shift = fine.");
|
||||
assert.ok(known.startsWith(ZH["Do nothing"]) && /拖动调节/.test(known));
|
||||
});
|
||||
|
||||
test("every Chinese language code takes the Chinese table", () => {
|
||||
for (const code of ["zh", "zh-CN", "zh-TW", "zh_CN", "ZH"]) assert.equal(isChineseLocale(code), true, code);
|
||||
for (const code of ["en", "ja", "ko", "", undefined, null, "zhx"]) assert.equal(isChineseLocale(code), false, String(code));
|
||||
});
|
||||
|
||||
test("no entry is empty or the same as its key without being listed as English", () => {
|
||||
for (const [english, chinese] of Object.entries(ZH)) {
|
||||
assert.ok(typeof chinese === "string" && chinese.length > 0, `empty entry for ${english}`);
|
||||
}
|
||||
for (const [pattern] of PATTERNS) assert.ok(pattern instanceof RegExp);
|
||||
});
|
||||
|
||||
test("every word a widget card shows has a Chinese entry or stays English on purpose", () => {
|
||||
const strings = new Set([...displayedStrings(cards), ...Object.values(PANEL_LABELS).flatMap((value) => (typeof value === "string" ? [value] : Object.values(value)))]);
|
||||
assert.ok(strings.size > 150, `only ${strings.size} strings found: the extraction broke`);
|
||||
const missing = [...strings].filter((text) => !(text in ZH) && !STAYS_ENGLISH.has(text) && !/^[^A-Za-z]*$/.test(text));
|
||||
assert.deepEqual(missing, []);
|
||||
});
|
||||
@@ -27,6 +27,9 @@ import {
|
||||
loaderLoraEntries,
|
||||
loraFolders,
|
||||
loraPickerEntries,
|
||||
setFolderFolds,
|
||||
parentFolder,
|
||||
anyFolderOpen,
|
||||
loraStackKeyAction,
|
||||
mergeImportedRows,
|
||||
middleEllipsis,
|
||||
@@ -1177,3 +1180,48 @@ test("the master switch turns groups back on, and its memory brings them back of
|
||||
const third = cycleMasterToggle(second.rows, second.snapshot);
|
||||
assert.deepEqual(third.rows.map((row) => [row.enabled, Boolean(row.group_off)]), [[true, false], [true, true], [false, true]]);
|
||||
});
|
||||
|
||||
test("fold all folds every folder and open all opens them, keeping unrelated folds", () => {
|
||||
const names = ["styles/ink/a.safetensors", "styles/ink/deep/b.safetensors",
|
||||
"styles/ink-old/c.safetensors", "faces/d.safetensors", "root.safetensors"];
|
||||
const folders = loraFolders(names).map(({ folder }) => folder);
|
||||
const before = new Set(["gone/folder"]);
|
||||
const folded = setFolderFolds(before, folders, true);
|
||||
assert.deepEqual(loraPickerEntries(names, "", folded).map(({ name }) => name),
|
||||
["styles", "faces", "root.safetensors"], "only top folders and root files stay in view");
|
||||
assert.equal(anyFolderOpen(loraPickerEntries(names, "", folded), folded), false);
|
||||
assert.ok(folded.has("gone/folder"), "a remembered fold for a folder not listed now is kept");
|
||||
assert.deepEqual([...before], ["gone/folder"], "the caller's Set is not changed");
|
||||
const opened = setFolderFolds(folded, folders, false);
|
||||
assert.deepEqual([...opened], ["gone/folder"]);
|
||||
assert.equal(anyFolderOpen(loraPickerEntries(names, "", opened), opened), true);
|
||||
});
|
||||
|
||||
test("folding a folder with its subtree leaves similarly named siblings alone", () => {
|
||||
const names = ["styles/ink/a.safetensors", "styles/ink/deep/b.safetensors",
|
||||
"styles/ink-old/c.safetensors", "styles/paint/d.safetensors"];
|
||||
const folders = loraFolders(names).map(({ folder }) => folder);
|
||||
const folded = setFolderFolds(new Set(), folders, true, "styles/ink");
|
||||
assert.deepEqual([...folded].sort(), ["styles/ink", "styles/ink/deep"]);
|
||||
const reopened = setFolderFolds(new Set([...folded, "styles/paint"]), folders, false, "styles\\ink");
|
||||
assert.deepEqual([...reopened], ["styles/paint"], "Windows separators name the same folder");
|
||||
});
|
||||
|
||||
test("fold-all label follows the folders in view, so a search view decides for itself", () => {
|
||||
const names = ["styles/ink/hit.safetensors", "faces/other.safetensors"];
|
||||
const searched = loraPickerEntries(names, "hit");
|
||||
assert.equal(anyFolderOpen(searched, new Set()), true);
|
||||
const folds = new Set(["styles"]);
|
||||
assert.equal(anyFolderOpen(loraPickerEntries(names, "hit", folds), folds), false,
|
||||
"with the only top folder in view folded, the control offers Open all");
|
||||
assert.equal(anyFolderOpen(loraPickerEntries(["root.safetensors"]), new Set()), false);
|
||||
});
|
||||
|
||||
test("Left moves up to the folder a file or folder sits in", () => {
|
||||
assert.equal(parentFolder("Krea2/Body/curvy.safetensors"), "Krea2/Body");
|
||||
assert.equal(parentFolder("Krea2\\Body\\curvy.safetensors"), "Krea2/Body", "Windows paths name the same folder");
|
||||
assert.equal(parentFolder("Krea2/Body"), "Krea2");
|
||||
assert.equal(parentFolder("Krea2"), null);
|
||||
assert.equal(parentFolder("root.safetensors"), null);
|
||||
assert.equal(parentFolder(undefined), null);
|
||||
});
|
||||
|
||||
@@ -12,6 +12,20 @@ test("mediaViewQuery names the file, its subfolder and its folder type", () => {
|
||||
assert.equal(mediaViewQuery(null), "");
|
||||
});
|
||||
|
||||
test("mediaViewQuery preserves leading spaces in the requested filename", () => {
|
||||
const filename = " 00_25.083 frame=377.png";
|
||||
for (const type of ["input", "output", "temp"]) {
|
||||
const suffix = type === "input" ? "" : ` [${type}]`;
|
||||
for (const subfolder of ["", "pasted"]) {
|
||||
const prefix = subfolder ? `${subfolder}/` : "";
|
||||
const query = new URLSearchParams(mediaViewQuery(`${prefix}${filename}${suffix}`));
|
||||
assert.equal(query.get("filename"), filename);
|
||||
assert.equal(query.get("subfolder"), subfolder);
|
||||
assert.equal(query.get("type"), type);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("filterMedia keeps values holding every term, ignoring case", () => {
|
||||
const values = ["pasted/ausboss_night_bridge.png", "ausboss_day_sky_square.mp4", "Night_Alley.PNG"];
|
||||
assert.deepEqual(filterMedia(values, ""), values);
|
||||
|
||||
@@ -24,15 +24,15 @@ test("cuts and speech are marked", () => {
|
||||
|
||||
test("no report and an empty script draw nothing and say what to do", () => {
|
||||
assert.deepEqual(stripRows(null), []);
|
||||
assert.deepEqual(stripCaption(null), { text: "Each line becomes a moment.", warn: false });
|
||||
assert.deepEqual(stripCaption({ moments: [] }), { text: "Each line becomes a moment.", warn: false });
|
||||
assert.deepEqual(stripCaption(null), { text: "Each line becomes a moment. A blank line between lines is a cut.", warn: false });
|
||||
assert.deepEqual(stripCaption({ moments: [] }), { text: "Each line becomes a moment. A blank line between lines is a cut.", warn: false });
|
||||
});
|
||||
|
||||
test("the caption adds the script up", () => {
|
||||
assert.equal(stripCaption({ moments: [row(0, 2.5), row(2.5, 5)] }).text, "2 moments, 2.5 s each, one take.");
|
||||
assert.equal(stripCaption({ moments: [row(0, 8)] }).text, "1 moment, 8 s, one take.");
|
||||
assert.equal(stripCaption({ moments: [row(0, 3), row(3, 8)] }).text, "2 moments, one take.");
|
||||
assert.equal(stripCaption({ moments: [row(0, 3), row(3, 8, { cut: true })] }).text, "2 moments, 1 cut.");
|
||||
assert.equal(stripCaption({ moments: [row(0, 2.5), row(2.5, 5)] }).text, "2 moments, 2.5 s each, one take. Click between two moments to cut there.");
|
||||
assert.equal(stripCaption({ moments: [row(0, 8)] }).text, "1 moment, 8 s, one take. Add a line for the next moment, a blank line to cut.");
|
||||
assert.equal(stripCaption({ moments: [row(0, 3), row(3, 8)] }).text, "2 moments, one take. Click between two moments to cut there.");
|
||||
assert.equal(stripCaption({ moments: [row(0, 3), row(3, 8, { cut: true })] }).text, "2 moments, 1 cut. Click a cut on the bar to join the shots.");
|
||||
});
|
||||
|
||||
test("only connected pictures send their job", () => {
|
||||
|
||||
@@ -58,6 +58,18 @@ test("both padded sides keep the multiple remainder on the far side", () => {
|
||||
});
|
||||
});
|
||||
|
||||
test("image references preserve filename whitespace around folder annotations", () => {
|
||||
for (const suffix of ["", " [input]", " [output]", " [temp]"]) {
|
||||
const type = suffix ? suffix.slice(2, -1) : "input";
|
||||
for (const filename of [" 00_25.083 frame=377.png", " photo.png "]) {
|
||||
assert.deepEqual(parseImageReference(filename + suffix), { filename, subfolder: "", type });
|
||||
assert.deepEqual(parseImageReference(` sub\\dir\\${filename}${suffix}`), {
|
||||
filename, subfolder: " sub/dir", type,
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("one padded side takes the whole remainder", () => {
|
||||
// Pinned in tests/test_pad_helpers.py too.
|
||||
assert.deepEqual(padGeometry(100, 64, pads(20, 0, 0, 0, 16)), {
|
||||
|
||||
@@ -209,6 +209,7 @@ test("deferred configuration cannot recreate removed or replaced panels", () =>
|
||||
hideInputsInDef() {}, livePanels: new Set(), unwatchSource() {}, clearMedia() {},
|
||||
buildPanel() { rebuilt += 1; return { eraser: {}, alive: true }; },
|
||||
syncErase() {}, syncAdvanced() {}, scheduleRefresh() {}, getMode: () => "slide", updateModeButtons() {},
|
||||
REST_PROPERTY: "ausboss_compare_rest", savedRestSide: () => null,
|
||||
});
|
||||
const file = kind === "compare" ? COMPARE : PREVIEW;
|
||||
vm.runInContext('const NODE_NAME="Compare"; const REST_SETTING="test"; const NODE_CONFIG={Preview:{}}; const INPUT_SIDE=1;'
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user