Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f6d01458a8 | ||
|
|
60dca17f4a | ||
|
|
94b1ab1def | ||
|
|
f7fe1ceac8 | ||
|
|
07bb4d792b | ||
|
|
34995f9fdb | ||
|
|
8e00fd07fc | ||
|
|
3213c6a4c1 | ||
|
|
b6266d1f13 | ||
|
|
fbabc5de42 | ||
|
|
6f2a39502e | ||
|
|
c33fc9a968 | ||
|
|
eb1be4f36c | ||
|
|
0a16f4da32 | ||
|
|
89a8e2d05d | ||
|
|
0d1f6cf246 | ||
|
|
f9b142bb76 | ||
|
|
d0ce322d7c | ||
|
|
9a52cd8a04 | ||
|
|
20f5ea273d | ||
|
|
f4c123cffb | ||
|
|
148edbd741 | ||
|
|
d31377a939 | ||
|
|
3942e7d9dc | ||
|
|
28936dbe7e | ||
|
|
f75f7456b0 | ||
|
|
52e1e81838 | ||
|
|
6c41677b36 | ||
|
|
33555abf0f | ||
|
|
6a891d185c | ||
|
|
199a618a94 | ||
|
|
62a3fcbacc | ||
|
|
09bf3e9908 | ||
|
|
2e713a4f10 | ||
|
|
0b84c467c7 |
@@ -2,6 +2,92 @@
|
||||
|
||||
All notable changes to ComfyUI-AusBoss are documented here.
|
||||
|
||||
## Unreleased
|
||||
|
||||
- **Edit Lock 🆎 says what is wrong when the VAE and model don't match.**
|
||||
The readout used to blame the VAE alone. It now says either file can be
|
||||
the wrong one, gives the two channel counts it compared, and points to
|
||||
the model and VAE in the workflow's notes. A GGUF or other converted
|
||||
model is a common cause.
|
||||
|
||||
## 2.28.1 - 2026-11-25
|
||||
|
||||
- **Image Resize 🆎 shows Fit only when it is used.** Fit, and Fill under
|
||||
pad, now show only for a Width × height target. The other targets take
|
||||
their shape from the picture and always fit it, so those rows did
|
||||
nothing there.
|
||||
- **Photo Camera 🆎's More fold opens.** Crop margin and 360 width sat in
|
||||
a fold with no header, so nothing could open them. The card now has a
|
||||
More row that shows them.
|
||||
|
||||
## 2.28.0 - 2026-11-24
|
||||
|
||||
- **New node: Photo Camera 🆎.** It works out the camera your photo was
|
||||
taken with, so a 3D model of the person lines up with the photo. Wire in
|
||||
the photo, the person's mask and the photo's lens width (MoGe measures
|
||||
it). It hands Pixal3D the crop's lens, the 3D viewer your photo's own
|
||||
view, and where the photo goes on a 360 canvas so the 360 lines up
|
||||
behind the model.
|
||||
- **The 3D viewer can cut the front or back off a model.** Cut front and
|
||||
Cut back on the 360 strip's Model tab take away part of the model as the
|
||||
camera sees it, such as the inside of a hat that should sit behind the
|
||||
head. Pause for Shot 🆎 gets an optional `mesh` input and output that cut
|
||||
the run's model the same way, so the shot matches the viewer.
|
||||
- **Pause for Shot 🆎 keeps the viewer's 360 settings on runs that don't
|
||||
pause.** With Pause on *run through*, the backdrop now uses the Turn,
|
||||
Tilt, Shadow and the rest saved on the viewer, as a paused run does.
|
||||
Before, such a run used the 360 unturned.
|
||||
|
||||
- **Layout Boxes 🆎 says the boxes as sentences for any prompt.** A new
|
||||
`placement` output writes each box as a plain sentence: what goes there
|
||||
and where, such as `The words "FRESH" in bold black letters, placed top
|
||||
left, from 6% to 52% across and 6% to 25% down.` Add it to the prompt of
|
||||
a model that has no box input, and the things land where you drew them.
|
||||
|
||||
- **Color Match 🆎 can fix an edit that looks pasted on.** A new method,
|
||||
`kept`, takes the picture from before the edit as reference. It learns how
|
||||
the model shifted the parts it was meant to keep (darker, more contrast,
|
||||
more colour) and undoes that, so a new word or object sits in the same
|
||||
tone as the rest. New things keep their own colours.
|
||||
|
||||
- **Save Image 🆎 can write Civitai info.** Pick **Civitai** in the Embed
|
||||
switch (Off | On | Civitai) and a saved picture also carries its prompt,
|
||||
settings and the fingerprints of its model and LoRAs in the form
|
||||
civitai.com reads first.
|
||||
An upload then shows its prompt, lists its resources and gets the ComfyUI
|
||||
tool and txt2img or img2img technique tags, including for
|
||||
Krea 2, Qwen Image 2.1 and prompts inside subgraphs, where Civitai found no
|
||||
prompt and flagged the upload "Unable to Verify AI Generation". It is off
|
||||
by default, because Civitai then shows those settings in place of the
|
||||
ComfyUI workflow; the workflow stays in the file and still drags back into
|
||||
ComfyUI. The first save with a new model takes a moment while its file is
|
||||
fingerprinted.
|
||||
- **WebP pictures from Save Image 🆎 and Save Video 🆎 carry the workflow the
|
||||
way ComfyUI's own WebP does.** ComfyUI could not read the workflow back
|
||||
out of Save Image's WebP files, and civitai.com did not see them as
|
||||
ComfyUI pictures at all. They now use core ComfyUI's layout, so a WebP
|
||||
drags back into ComfyUI with its full graph and Civitai reads its prompt.
|
||||
Save Video's animated `webp` now embeds the workflow too, as core's
|
||||
animated WebP does; its Embed workflow row shows for `webp`.
|
||||
|
||||
- **LoRA Loader 🆎 can fetch Civitai info for every LoRA at once.** A new
|
||||
**Fetch all LoRAs** button in a LoRA's info card (also in the gear menu) looks
|
||||
up each LoRA in the stack that has no Civitai info yet, one at a time
|
||||
with a short pause, and saves its info and picture the same way the
|
||||
one-LoRA button does. The bottom of the node shows how far it is
|
||||
(`Civitai 12 / 44 · Stop`); click it to stop. It follows the Civitai
|
||||
picture setting, never replaces a picture, and slows down or stops when
|
||||
Civitai asks it to.
|
||||
|
||||
- **Image Toolbox can cut a piece of your own size.** Pick the new job
|
||||
**cut a piece**, set the width and height in pixels, pick where it sits
|
||||
(a corner, an edge or the centre) and move it right or down from there.
|
||||
The piece comes out of the first output, and the rest of the picture out
|
||||
of a new second output, `rest`. A piece as tall as the picture, against
|
||||
its left or right edge, leaves the strip beside it, so one node splits a
|
||||
picture into two parts of different sizes. Width or height 0 takes the
|
||||
picture's full width or height.
|
||||
|
||||
## 2.27.0 - 2026-11-23
|
||||
|
||||
- **Video Crop + Rotate + Pad → Clip 🆎 can put a clip window in an App-mode
|
||||
|
||||
@@ -138,7 +138,7 @@ Reads a picture's `width`, `height`, `longest_edge`, `shortest_edge` and batch `
|
||||
|
||||
### Image Toolbox
|
||||
|
||||
Small picture jobs in one node, picked from a list. **split sheet at gaps** cuts a row of pictures, such as a character sheet's views, into separate pictures, cutting at the gaps between them so no piece gets part of its neighbour.
|
||||
Small picture jobs in one node, picked from a list. **split sheet at gaps** cuts a row of pictures, such as a character sheet's views, into separate pictures, cutting at the gaps between them so no piece gets part of its neighbour. **cut a piece** cuts out one piece of the width and height you set, at the place you pick, and gives back the rest of the picture too.
|
||||
|
||||
### Color Match
|
||||
|
||||
@@ -347,6 +347,10 @@ The patch relies on ComfyUI's internal attention code. Its [help page](js/docs/A
|
||||
|
||||
Stops a run right after a **Preview 3D (Advanced)** viewer, so you can frame your shot on the model that run just made. Turn the camera, zoom, move the model, then press **Continue**: the run goes on with the shot exactly as the viewer shows it, and nothing before the pause runs again. **Stop** ends the run there. Wire a 360 picture into `panorama` and it shows behind the model while you frame, and `backdrop` hands on the part of it the camera sees, with an optional floor shadow. Set **Pause** to *run through* for runs nobody is watching.
|
||||
|
||||
### Photo Camera
|
||||
|
||||
Works out the camera your photo was taken with, so a 3D model of the person lines up with the photo. Made for **Pixal3D**, the TRELLIS 2 model that builds the model lined up with the photo. Wire in the photo, the person's mask and the photo's lens width (**Get FoV from MoGe** measures it). It hands Pixal3D the crop's lens, the 3D viewer your photo's own view (so the viewer opens where the photo was taken), and where the photo goes on a 360 canvas so the 360 lines up behind the model.
|
||||
|
||||
### Extras in ComfyUI's 3D viewers
|
||||
|
||||
The pack also adds to ComfyUI's own 3D viewers, with no new node:
|
||||
@@ -354,7 +358,7 @@ The pack also adds to ComfyUI's own 3D viewers, with no new node:
|
||||
- **Shape chips** above the width and height of Preview 3D (Advanced) and Save 3D (Advanced): pick a shape and the frame follows.
|
||||
- **Blender keys** with the mouse over a viewer: G move, R rotate, S scale, X / Y / Z to lock an axis, a typed number for an exact amount, the number keys for front, side and top views, and Home to frame the model.
|
||||
- **Viewport tools** in the top-right corner: drag the axis gizmo to orbit, the magnifier to zoom, the hand to pan, and a grid switch.
|
||||
- **A 360 strip** (press N, or the small 360 tab): spin and tip the model, turn, tilt and roll the 360 background, its brightness and blur, the light and the model's colours. The settings save with the workflow.
|
||||
- **A 360 strip** (press N, or the small 360 tab): spin and tip the model, cut its front or back away, turn, tilt and roll the 360 background, its brightness and blur, the light and the model's colours. The settings save with the workflow.
|
||||
|
||||
## Workflow utilities
|
||||
|
||||
@@ -376,6 +380,8 @@ Drag to draw a box, drag it to move it and its handles to size it; under the can
|
||||
|
||||
The `mask` output is white inside every box: load a picture, draw a box over the words on a sign, and an inpaint chain can write new words there while the rest of the picture stays as it was. For words at a slant, drag the round handle over a box to turn it: the mask turns with it, and a turned text box tells the model its slant.
|
||||
|
||||
For a model that reads only a prompt and has no box input, the `placement` output says the boxes as plain sentences, what goes in each box and where, to add to your prompt.
|
||||
|
||||

|
||||
|
||||
### Seed
|
||||
|
||||
@@ -46,6 +46,7 @@ NODE_MODULES = [
|
||||
"node_mask_by_touch",
|
||||
"node_math",
|
||||
"node_pause_shot",
|
||||
"node_photo_camera",
|
||||
"node_prompt_variations",
|
||||
"node_realign_to_source",
|
||||
"node_refine_mask",
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="105" height="20" role="img" aria-label="release: v2.27.0">
|
||||
<title>release: v2.27.0</title>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="105" height="20" role="img" aria-label="release: v2.28.1">
|
||||
<title>release: v2.28.1</title>
|
||||
<path fill="#555" d="M0 0h48v20H0z"/>
|
||||
<path fill="#00b4aa" d="M48 0h57v20H48z"/>
|
||||
<g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" font-size="11">
|
||||
<text x="24" y="14">release</text>
|
||||
<text x="76.5" y="14">v2.27.0</text>
|
||||
<text x="76.5" y="14">v2.28.1</text>
|
||||
</g>
|
||||
</svg>
|
||||
|
||||
|
Before Width: | Height: | Size: 425 B After Width: | Height: | Size: 425 B |
@@ -2,8 +2,9 @@
|
||||
|
||||
Makes one picture's colors match another's. Use it when an inpainted or
|
||||
stitched area comes back a little too warm, cool, dark or bright next to the
|
||||
original. Four methods go from a gentle fix to an exact match, and a
|
||||
first-frame mode matches every frame of a video to its first, which can
|
||||
original. Four methods go from a gentle fix to an exact match. A fifth,
|
||||
**kept**, is for edits whose new part looks too crisp and colourful next to
|
||||
the rest of the picture. A first-frame mode matches every frame of a video to its first, which can
|
||||
reduce color drift between frames.
|
||||
|
||||
## Controls
|
||||
@@ -15,7 +16,7 @@ reduce color drift between frames.
|
||||
inpaint, feed the original image here. A single reference broadcasts
|
||||
across a batch; a matched batch pairs frame to frame. Required unless
|
||||
**Reference** (`reference_mode`) is **first frame**.
|
||||
- **Method** (`method`): How the colors move.
|
||||
- **Method** (`method`): How the colors move. A line under it says what the picked one does.
|
||||
- **lab** — per-channel mean/std shift in LAB. Perceptual and the safe
|
||||
default: corrects overall casts and contrast without shifting
|
||||
individual hues around.
|
||||
@@ -24,6 +25,13 @@ reduce color drift between frames.
|
||||
not just shifted.
|
||||
- **hist** (`histogram`) — matches each channel's distribution exactly.
|
||||
The strongest and least subtle.
|
||||
- **kept** — for an edit, with the picture from before the edit as
|
||||
**reference**. Edit models often hand back the parts they were asked
|
||||
to keep a little darker, with more contrast and colour, so a new sign or
|
||||
word looks pasted on. This method learns that shift from the parts the
|
||||
model kept and undoes it everywhere. New things keep their own colours:
|
||||
green apples that replaced oranges stay green. The reference must be the
|
||||
same size as the image.
|
||||
- **mask** (optional): Restricts the match to the white area — both the
|
||||
statistics measured on the image and where the correction lands. Black
|
||||
pixels pass through **bit-identical**. Reference statistics always come
|
||||
@@ -43,6 +51,11 @@ reduce color drift between frames.
|
||||
|
||||
## Notes
|
||||
|
||||
- For an edit in a box, put **kept** between the model and **Stitch Inpaint
|
||||
🆎**: the model's crop into **image**, Crop For Inpaint's crop into
|
||||
**reference**, its mask into **mask**. The fix is learned and applied
|
||||
inside the box only.
|
||||
|
||||
- The node takes a mask but outputs none on purpose: the mask only scopes
|
||||
the fix and passes through your graph unchanged — wire your original
|
||||
mask onward.
|
||||
|
||||
@@ -28,6 +28,37 @@ own file.
|
||||
A batch of sheets is cut sheet by sheet: the first sheet's pieces, then the
|
||||
next sheet's.
|
||||
|
||||
### cut a piece
|
||||
|
||||
Cuts one piece out of the picture, at the size and place you set. Use it when
|
||||
the parts you need are not the same size, or when you know exactly where a
|
||||
part is.
|
||||
|
||||
- **Width** and **Height** (`width`, `height`): the piece's size in pixels.
|
||||
0 takes the picture's full width or height.
|
||||
- **Position** (`position`): where the piece sits, from **top left** to
|
||||
**bottom right**. **center** puts it in the middle.
|
||||
- **Move right** and **Move down** (`move_right`, `move_down`): move the
|
||||
piece from that position by this many pixels. Below 0 moves it left or up.
|
||||
|
||||
The piece never leaves the picture. A size larger than the picture is cut to
|
||||
the picture's size, and a move that would push the piece past an edge stops
|
||||
at that edge.
|
||||
|
||||
The piece comes out of **images**. The second output, **rest**, is what is
|
||||
left of the picture:
|
||||
|
||||
- When the piece is as tall as the picture and sits against its left or
|
||||
right edge, **rest** is the strip beside it. The same goes for a piece as
|
||||
wide as the picture at the top or bottom. So to split a picture into two
|
||||
parts of different sizes, set the first part's width, Height 0, and
|
||||
Position **left**: **images** is the first part and **rest** the second.
|
||||
- Any other piece leaves a hole, and **rest** is the whole picture with the
|
||||
hole filled with the picture's backdrop colour.
|
||||
|
||||
A batch is cut at the same place in every picture. Other jobs pass the
|
||||
picture through **rest** unchanged.
|
||||
|
||||
## Technical details
|
||||
|
||||
- The backdrop colour is the median colour of the picture's border.
|
||||
@@ -39,6 +70,7 @@ next sheet's.
|
||||
- When two pictures overlap on the sheet, no column is clean. The cut then
|
||||
goes where the least of them is lost, and a small part of one can remain
|
||||
in the other's piece.
|
||||
- cut a piece fills its hole with the same backdrop colour.
|
||||
- Pieces set to 1 returns the picture unchanged.
|
||||
- Pieces higher than the picture's width in pixels gives one piece per
|
||||
pixel column, so fewer pieces than asked for.
|
||||
|
||||
@@ -60,6 +60,26 @@ of 6 and the woman 4 of 6, and the room stayed as it was; with empty boxes,
|
||||
2 of 12. Keep `preview` out of H3
|
||||
Image's pictures too, or the boxes' lines can stay in the picture.
|
||||
|
||||
## Words for a prompt
|
||||
|
||||
Some models make a picture from a prompt alone and have no input for boxes.
|
||||
The `placement` output says your boxes as plain sentences: what goes in each
|
||||
box and where it is in the picture. Add it to your prompt, for example with
|
||||
ComfyUI's Concatenate Text node, and the model puts each thing where you drew
|
||||
it.
|
||||
|
||||
For a text box with the word FRESH in the top left and an orange on the right,
|
||||
it gives:
|
||||
|
||||
> The words "FRESH" in huge bold black sans-serif letters, placed top left,
|
||||
> from 6% to 52% across and 6% to 25% down. One ripe orange with a green
|
||||
> leaf, placed middle right, from 52% to 94% across and 35% to 85% down.
|
||||
|
||||
Write the **Description** of each box the way you would in a prompt. Tried on
|
||||
SenseNova U1.6, which has no box input: these sentences put all the boxes in
|
||||
place on two seeds of two, where `elements` as text put the words in the wrong
|
||||
places.
|
||||
|
||||
## Change the words in a picture
|
||||
|
||||
The `mask` output is white inside every box. Use it to change only one part
|
||||
@@ -184,11 +204,12 @@ removes it. The first color also colors the box on the canvas.
|
||||
| `elements` | The boxes as prompt elements. Wire it to MOSS-Image Layout Prompt. A turned box gives the straight box around it, and a turned text box says its slant in its description. |
|
||||
| `mask` | White inside every box, black elsewhere, to change only those places of a picture. A turned box is white inside its turned shape only. |
|
||||
| `h3_prompt` | The boxes as a prompt for MiniMax H3 Image, in words: where each thing goes and how big it is. Name each person's picture and what they do in the box's description. See **Place people with MiniMax H3 Image**. |
|
||||
| `placement` | The boxes as sentences for a prompt: what goes in each box and where, as parts of the picture. Add it to your prompt for a model that has no box input. See **Words for a prompt**. |
|
||||
|
||||
## In place of Create Bounding Boxes
|
||||
|
||||
Layout Boxes has the same inputs and the same outputs in the same order (and
|
||||
`mask` and `h3_prompt` after them), so the wires move straight over. For the same boxes it
|
||||
`mask`, `h3_prompt` and `placement` after them), so the wires move straight over. For the same boxes it
|
||||
gives the same `bboxes` and `elements`, and MOSS-Image Layout Prompt makes the
|
||||
same prompt from them.
|
||||
|
||||
@@ -257,5 +278,19 @@ run once: they fill the canvas. Then remove the old node.
|
||||
overlap (the later box is in front). Text boxes are placed by the frame
|
||||
only. A turned box is placed by the straight box around it. A text box with
|
||||
no text and no description is left out. No boxes give an empty text.
|
||||
- `placement` has one sentence per box, in box order, joined by spaces. A
|
||||
text box with words gives `The words "TEXT" in DESCRIPTION, placed WHERE.`
|
||||
(`The words "TEXT", placed WHERE.` without a description); any other box
|
||||
gives its description, first letter in upper case, then `, placed WHERE.`
|
||||
A box with no words and no description is left out. The description is
|
||||
the one `elements` carries, so a turned text box says its slant. WHERE is
|
||||
a rough place and then the box's edges in whole percents of the canvas,
|
||||
cut to it: `top left, from 6% to 52% across and 6% to 25% down`. The box
|
||||
is "top" when its bottom edge is above 40%, "bottom" when its top edge is
|
||||
below 60%, else "middle"; "left" when its right edge is left of 55%,
|
||||
"right" when its left edge is right of 45%, else "center"; and the middle
|
||||
of both is said as "center" alone. A turned box is placed by the straight
|
||||
box around it. A box with colors gets ` Colors: #FF3399, #00AABB.` after
|
||||
its sentence. No boxes give an empty text.
|
||||
- The background is saved, shrunk, in ComfyUI's temp folder for the node's
|
||||
face. Nothing else is written.
|
||||
|
||||
@@ -347,6 +347,16 @@ show it right away. Gear menu → **Civitai picture** picks which pictures:
|
||||
takes the first picture whatever its rating, and **off** saves none. It never
|
||||
replaces a picture you already have.
|
||||
|
||||
**All of them at once:** click **Fetch all LoRAs** beside that button (or gear
|
||||
menu → **Civitai info for every LoRA**). It looks up every LoRA in the stack that
|
||||
has no Civitai info yet, one after another with a short pause, so Civitai
|
||||
is not asked too fast. The bottom of the node shows how far it is
|
||||
(`Civitai 12 / 44 · Stop`); click it to stop after the LoRA being fetched.
|
||||
A message at the end says how many were found, how many Civitai does not
|
||||
know, and how many already had their info. LoRAs with info are skipped, so
|
||||
running it again only fetches the new ones. It follows the same
|
||||
**Civitai picture** setting and never replaces a picture.
|
||||
|
||||
## Trigger words
|
||||
|
||||
The info card gathers words from three places: the LoRA file's own metadata,
|
||||
@@ -367,10 +377,17 @@ switched on for the old one.
|
||||
(see "Get the pictures from Civitai" above). After that the button reads **Refresh Civitai
|
||||
info** and the card gets a **View on Civitai** link. A LoRA Civitai does
|
||||
not know (unpublished or hidden) reads **Not found on Civitai**. Gear
|
||||
menu → **Civitai lookup button** removes the button. When a lookup fails,
|
||||
menu → **Civitai lookup button** removes the button, and **Fetch all LoRAs**
|
||||
with it. When a lookup fails,
|
||||
a message says why. If it always says it could not reach civitai.com,
|
||||
check whether ComfyUI was started with `--disable-api-nodes`: that setting
|
||||
stops the browser from reaching any other site, Civitai included.
|
||||
- **Fetch all LoRAs** runs that same lookup for each LoRA in the stack that has no
|
||||
Civitai info yet, one at a time, about one and a half seconds apart. If
|
||||
Civitai answers "too many requests", it waits 20 seconds and tries that
|
||||
LoRA once more; a second time, it stops and says so. It also stops when
|
||||
civitai.com cannot be reached, or after three failures in a row. Only one
|
||||
Fetch all LoRAs runs at a time on the page.
|
||||
- **Suggested strength**: a lowest and a highest value at the bottom of the
|
||||
card (leave one empty for "any"). It is only a reminder: a row set outside
|
||||
it shows its number in orange, and the tooltip gives the range. Saved per
|
||||
|
||||
@@ -28,11 +28,24 @@ Take the 360 out of the viewer while the run waits, and `backdrop` comes out
|
||||
plain grey, the same as with no 360 wired in. What you see in the viewer is
|
||||
what you get.
|
||||
|
||||
## Cut the front or back off the model
|
||||
|
||||
**Cut front** and **Cut back** on the viewer's Model tab take away part of
|
||||
the model as the camera sees it: Back the far side, Front the near side, each
|
||||
as a share of the model's depth. Use Back to hide what should sit behind
|
||||
something in the picture, such as the inside of a hat behind the head. The
|
||||
viewer shows the cut as you drag.
|
||||
|
||||
For the shot to be cut too, wire the model's mesh into `mesh` and take `mesh`
|
||||
from this node to Render Mesh. A run that goes straight through uses the cut
|
||||
saved on the viewer.
|
||||
|
||||
## Settings
|
||||
|
||||
- **Pause**: *wait for me* stops every run here. *run through* lets runs go
|
||||
straight on with the camera as it was when you pressed Run, for runs nobody
|
||||
is watching.
|
||||
is watching. The viewer's 360 settings and Cut go along as they were then
|
||||
too, and changing one makes the next run redo the shot.
|
||||
|
||||
## Technical details
|
||||
|
||||
@@ -41,6 +54,12 @@ what you get.
|
||||
Run a second time.
|
||||
- Continue sends the viewer's camera, the model's turn and the size as
|
||||
numbers to the pack's own route. Only a node that is waiting accepts it.
|
||||
- A run that goes straight through takes the viewer's 360 settings and Cut
|
||||
from the hidden `view` input, which the page fills from the viewer as Run
|
||||
is pressed. ComfyUI only runs a node again when one of its inputs changes,
|
||||
so they ride in an input rather than in the saved workflow. A prompt sent
|
||||
without the page can fill `view` with the same JSON (`{"sky": {...},
|
||||
"cut": {...}}`) or leave it empty for the defaults.
|
||||
- Cancel in ComfyUI's queue ends a pause too. A page reloaded during a pause
|
||||
shows the Continue bar again.
|
||||
- Every open page gets the model to frame, not only the one that pressed Run:
|
||||
@@ -51,3 +70,9 @@ what you get.
|
||||
tenth of the model. Continue sends that patch with
|
||||
the camera, and the backdrop is darkened along the same rays Render Mesh
|
||||
casts, so the shadow lands where the model's feet are drawn.
|
||||
- The cut planes face the camera. The model's depth is how far the box around
|
||||
its own points reaches along the view, measured the same way in the viewer
|
||||
and on the run's mesh. The viewer cuts at the exact plane; the mesh keeps
|
||||
the triangles whose middle lies between the planes, so the edges agree to
|
||||
within a triangle. While a cut is on, the viewer draws both sides of the
|
||||
model, so through the cut you see its inside, the way Render Mesh draws it.
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
# Photo Camera 🆎
|
||||
|
||||
Works out the camera your photo was taken with, so a 3D model of the person
|
||||
lines up with the photo. With it, the 3D viewer opens on your photo's own
|
||||
view: same height, same lens, the person where they stand in the photo. Move
|
||||
the camera from there and the shot starts from something real instead of a
|
||||
guess.
|
||||
|
||||
It is made for **Pixal3D**, the TRELLIS 2 model in ComfyUI that builds the
|
||||
model lined up with the photo.
|
||||
|
||||
## How to wire it
|
||||
|
||||
- `image`: your photo, the one **Crop to Mask** cuts the person from.
|
||||
- `mask`: the person's mask, the same one Crop to Mask uses.
|
||||
- `fov`: how wide the photo is, in degrees. Wire **Get FoV from MoGe**
|
||||
(horizontal, degrees) here, run on the same photo. Without MoGe, 55 suits
|
||||
most phone photos.
|
||||
|
||||
Then:
|
||||
|
||||
- `crop_fov` goes into **Pixal3D Conditioning**'s `fov`.
|
||||
- `camera_info` goes into the 3D viewer's `camera_info`
|
||||
(**Preview 3D (Advanced)**). The viewer opens on the photo's view.
|
||||
- `strip_width`, `strip_x` and `strip_y` say where the photo goes on the 360
|
||||
canvas: its width (into an Image Scale) and its left and top edges (into
|
||||
the Image Composite that lays it on the canvas). The 360 then lines up
|
||||
with the camera. Turn the 360 by 90 on the viewer's Angle tab so its middle
|
||||
sits behind the model.
|
||||
|
||||
## Settings
|
||||
|
||||
- **Lens**: the photo's field of view across, in degrees.
|
||||
- **Crop margin** (under **More**): the margin Crop to Mask adds around the person.
|
||||
Keep it the same as Crop to Mask's `pad_factor`.
|
||||
- **360 width** (under **More**): the width of the 360 canvas.
|
||||
|
||||
## Technical details
|
||||
|
||||
- Pixal3D builds from a square crop around the person and the crop's field of
|
||||
view. Its model comes out with +Y up, and with the crop's camera on +Z
|
||||
looking at the middle from 0.5 / tan(crop_fov / 2) away.
|
||||
- The whole photo was taken from the same point. Its centre is off the crop's
|
||||
middle, so the photo's camera is the crop's camera turned towards the
|
||||
photo's centre, with no roll. Render Mesh and the viewer can show a turn
|
||||
but not a shifted sensor, which is what a crop really is. A person near the
|
||||
middle lands to the pixel. A fifth of the frame off centre, the model's far
|
||||
edges move by up to 3% of the frame's width; up in a corner with a wide
|
||||
lens, up to 8%.
|
||||
- The crop box is the one Crop to Mask cuts: the node asks ComfyUI's own crop
|
||||
helper for it, and measures it the same way itself on a ComfyUI without
|
||||
that helper.
|
||||
- The photo is laid on the 360 canvas flat, at its own width in degrees, with
|
||||
its centre where the camera's axis meets the canvas.
|
||||
@@ -41,10 +41,18 @@ file's name. A caption on the `caption_text` input writes the paired `.txt`.
|
||||
workflow in EXIF. **JXL** (`jxl lossless`, lossless JPEG XL) is the most
|
||||
compact; it needs the optional `pillow-jxl-plugin` in ComfyUI's python
|
||||
(also the pack's `jxl` extra) and few browsers preview it.
|
||||
- **Embed workflow** (`save_metadata`): **On** stores the prompt and
|
||||
- **Embed** (`save_metadata`, `civitai_info`): **On** stores the prompt and
|
||||
workflow in the file (PNG text chunks, EXIF in webp and jxl) so it drags
|
||||
back into ComfyUI; **Off** writes a clean file for sharing or datasets.
|
||||
`--disable-metadata` on the server wins.
|
||||
- **Civitai** (the Embed switch's third choice, `civitai_info` on): stores
|
||||
the workflow and also the prompt, the sampler settings and the
|
||||
fingerprints of the model and LoRAs in the form civitai.com reads, so an
|
||||
upload shows its prompt and lists its resources. Not the default: Civitai
|
||||
then shows these settings instead of the ComfyUI workflow, though the
|
||||
workflow stays in the file and still drags back into ComfyUI. The first save with a new model
|
||||
takes a moment while its file is fingerprinted; after that it is
|
||||
remembered. See "Uploading to Civitai" below.
|
||||
- **Preview** (`preview`): the small switch under the card shows the saved
|
||||
image on the node. Off, the picture's box goes away and the node is
|
||||
shorter; on again, the node returns to its height with the last saved
|
||||
@@ -115,6 +123,44 @@ be, apart from the size, which only a run knows.
|
||||
and is not read for tokens.
|
||||
- Other text between percent signs stays as typed.
|
||||
|
||||
## Uploading to Civitai
|
||||
|
||||
civitai.com reads a ComfyUI picture's prompt from the embedded graph, but
|
||||
only from nodes it knows. A prompt typed into Krea 2 Encode 🆎, core's Qwen
|
||||
Image 2.1 encoder or a node inside a subgraph reads as no prompt, and the
|
||||
upload is flagged "Unable to Verify AI Generation". Civitai also finds a
|
||||
picture's models only by their file fingerprints, which a ComfyUI graph does
|
||||
not hold, so a plain ComfyUI picture always says no resources were found.
|
||||
Pick **Civitai** in the Embed switch before saving pictures you mean to
|
||||
upload.
|
||||
|
||||
### Technical details
|
||||
|
||||
- The line is the one A1111 writes (`parameters` text in PNG, EXIF
|
||||
UserComment in WebP and JPEG XL): prompt, `Negative prompt:`, then
|
||||
`Steps`, `Sampler`, `Schedule type`, `CFG scale`, `Seed`, `Size`,
|
||||
`Model hash`, `Model`, `Lora hashes` and a `Hashes` JSON block. Civitai
|
||||
reads it before the ComfyUI graph.
|
||||
- It ends with `engine: ComfyUI`, which tags the post with the ComfyUI tool,
|
||||
and `process: txt2img` or `img2img`, which picks its technique. A sampler
|
||||
that starts from an encoded picture, an inpaint node, or a denoise under 1
|
||||
counts as img2img.
|
||||
- Civitai does not keep the ComfyUI graph from a picture that carries this
|
||||
line, so its page shows no workflow to copy. The workflow is still in the
|
||||
file for anyone who downloads it.
|
||||
- It is built from the run's own graph, walking up from this node to the
|
||||
nearest sampler (KSampler, KSamplerAdvanced, SamplerCustom and
|
||||
SamplerCustomAdvanced), its prompt encoder, and the checkpoint or
|
||||
diffusion model and LoRAs on its model input. LoRA Loader 🆎 rows that are
|
||||
off or at strength 0 are left out. A graph with no sampler gets no line.
|
||||
- Fingerprints are AutoV2 hashes (the first ten hex digits of the file's
|
||||
SHA256), cached in `user/ausboss/` by file size and date. Text encoders and
|
||||
VAEs are not listed; Civitai does not credit a picture to them.
|
||||
- A prompt made while the graph runs (Prompt Variations 🆎) is written as
|
||||
the text typed into its node.
|
||||
- Videos cannot carry it: Civitai reads only the `prompt` and `workflow`
|
||||
tags of an mp4 or webm.
|
||||
|
||||
## Outputs
|
||||
|
||||
- **file_path**: absolute path of the first file saved this run (empty when
|
||||
|
||||
@@ -78,13 +78,14 @@ a software format to use instead rather than failing with a driver stack
|
||||
trace.
|
||||
|
||||
`gif` and `webp` have no streaming encoder, so every frame is held in memory
|
||||
before the first byte is written — keep those to short clips. Neither carries
|
||||
metadata, so an embedded workflow is not available for them.
|
||||
before the first byte is written — keep those to short clips. `webp` carries
|
||||
the embedded workflow the same way ComfyUI's own animated WebP does; `gif` has
|
||||
no place for it.
|
||||
|
||||
The node's face follows the table: widgets the chosen format ignores are
|
||||
hidden rather than left to look meaningful. The CRF field leaves the
|
||||
**FPS · CRF** row for `mov prores`, `mkv ffv1` and `gif` (their rows read
|
||||
*ignored* above), and the **Embed workflow** row disappears for `gif` and `webp`,
|
||||
*ignored* above), and the **Embed workflow** row disappears for `gif`,
|
||||
which cannot carry it. Hidden is not removed:
|
||||
the widget keeps its position and its value, saved workflows store and restore
|
||||
it exactly as before, and switching the format back brings it back with the
|
||||
|
||||
@@ -47,6 +47,7 @@ help panel.
|
||||
| Do maths on numbers | Math Expression (`AUSBOSS_NODES_MathExpression`) |
|
||||
| Show text on the node, or the picture while it is made | Show Text (`AUSBOSS_NODES_ShowText`), Step Preview (`AUSBOSS_NODES_StepPreview`) |
|
||||
| Stop a run after the 3D viewer to frame the shot on the new model, with a 360 behind it | Pause for Shot (`AUSBOSS_NODES_PauseShot`): [node help](../AUSBOSS_NODES_PauseShot.md) |
|
||||
| Line a 3D model (Pixal3D) up with the photo: the photo's camera for the viewer, the crop's lens, the photo's place on a 360 | Photo Camera (`AUSBOSS_NODES_PhotoCamera`): [node help](../AUSBOSS_NODES_PhotoCamera.md) |
|
||||
| Free graphics memory between steps | Free Memory (`AUSBOSS_NODES_FreeMemory`) |
|
||||
| Time the whole run | Run Timer (`AUSBOSS_NODES_RunTimer`) |
|
||||
| Turn parts of a workflow off and on | Workflow Switches (`AUSBOSS_NODES_WorkflowSwitches`): [its own agent guide](workflow_switches.md) |
|
||||
|
||||
+123
-16
@@ -90,8 +90,9 @@ import {
|
||||
upsertTemplate,
|
||||
} from "../shared/lora_stack.mjs";
|
||||
import {
|
||||
MAX_PICTURE_BYTES, civitaiButtonLabel, civitaiByHashUrl, civitaiFailureText, isCivitaiAddress,
|
||||
parseCivitaiBody, pickCivitaiPicture, smallPictureUrl,
|
||||
MAX_PICTURE_BYTES, civitaiButtonLabel, civitaiByHashUrl, civitaiFailureText, civitaiQueueLabel,
|
||||
civitaiQueueSummary, isCivitaiAddress, parseCivitaiBody, pickCivitaiPicture, runCivitaiQueue,
|
||||
smallPictureUrl,
|
||||
} from "../shared/civitai_lookup.mjs";
|
||||
|
||||
const NODE_CLASS = "AUSBOSS_NODES_LoraLoader";
|
||||
@@ -496,6 +497,10 @@ function installStyles() {
|
||||
color: inherit; cursor: pointer; padding: 2px 8px; font-size: 11px; }
|
||||
.ausboss-lora-chip.active { border-color: ${BRAND}; color: ${BRAND}; }
|
||||
.ausboss-lora-fetch { align-self: flex-start; }
|
||||
.ausboss-lora-fetchrow { display: flex; gap: 6px; align-items: center; }
|
||||
.ausboss-lora-fetchrow .ausboss-lora-fetch { align-self: auto; }
|
||||
.ausboss-lora-fetchrow .ausboss-lora-fetch-all { height: ${ACTIONS_HEIGHT}px; }
|
||||
.ausboss-lora-actions .ausboss-lora-civitai-run { align-self: center; margin-left: 6px; }
|
||||
.ausboss-lora-custom { display: flex; gap: 6px; align-items: center; }
|
||||
.ausboss-lora-custom input { flex: 1 1 auto; min-width: 0; height: ${ACTIONS_HEIGHT}px;
|
||||
border: 1px solid #3a4047; box-sizing: border-box;
|
||||
@@ -1524,8 +1529,10 @@ function openPicker(state, index, anchor, { keyboard = false } = {}) {
|
||||
// about that hash, and the server saves the answer beside the LoRA after
|
||||
// checking it describes the same file. Returns false when Civitai does not
|
||||
// know the file (unpublished or hidden models answer 404). `picture` is the
|
||||
// Civitai picture gear option ("off", "PG-13" or "any").
|
||||
async function lookUpOnCivitai(serverName, picture = "PG-13") {
|
||||
// Civitai picture gear option ("off", "PG-13" or "any"). Otherwise it returns
|
||||
// `{ picture }`: "saved", "none" (Civitai has none to save), "failed" or
|
||||
// "off". `quiet` keeps the picture's own messages back for Fetch all.
|
||||
async function lookUpOnCivitai(serverName, picture = "PG-13", { quiet = false } = {}) {
|
||||
const hashed = await (await api.fetchApi(
|
||||
`/ausboss/lora/hash?name=${encodeURIComponent(serverName)}`
|
||||
)).json();
|
||||
@@ -1534,7 +1541,9 @@ async function lookUpOnCivitai(serverName, picture = "PG-13") {
|
||||
credentials: "omit", redirect: "error", referrerPolicy: "no-referrer", cache: "no-store",
|
||||
});
|
||||
if (response.status === 404) return false;
|
||||
if (!response.ok) throw new Error(`Civitai answered ${response.status}.`);
|
||||
if (!response.ok) {
|
||||
throw Object.assign(new Error(`Civitai answered ${response.status}.`), { status: response.status });
|
||||
}
|
||||
const info = parseCivitaiBody(await response.text());
|
||||
const saved = await (await api.fetchApi("/ausboss/lora/civitai", {
|
||||
method: "POST",
|
||||
@@ -1542,24 +1551,28 @@ async function lookUpOnCivitai(serverName, picture = "PG-13") {
|
||||
body: JSON.stringify({ name: serverName, info }),
|
||||
})).json();
|
||||
if (!saved.ok) throw new Error(saved.error || "Could not save the Civitai info.");
|
||||
if (picture !== "off") {
|
||||
await saveCivitaiPicture(serverName, info, picture === "any").catch((error) =>
|
||||
loraToast(`Saved the Civitai info, but not its picture: ${civitaiFailureText(error)}`));
|
||||
if (picture === "off") return { picture: "off" };
|
||||
try {
|
||||
if (await saveCivitaiPicture(serverName, info, picture === "any")) return { picture: "saved" };
|
||||
if (!quiet) {
|
||||
loraToast(picture === "any"
|
||||
? "Civitai has no picture of this LoRA to save."
|
||||
: "Civitai has no picture of this LoRA rated PG-13 or milder.");
|
||||
}
|
||||
return { picture: "none" };
|
||||
} catch (error) {
|
||||
if (!quiet) loraToast(`Saved the Civitai info, but not its picture: ${civitaiFailureText(error)}`);
|
||||
return { picture: "failed" };
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// The LoRA's first picture on Civitai, saved beside it as its preview. The
|
||||
// browser downloads a 450-pixel copy from Civitai's picture server without
|
||||
// cookies; the server checks it is a picture and never replaces one.
|
||||
// Returns false when Civitai has no picture the setting allows.
|
||||
async function saveCivitaiPicture(serverName, info, anyRating) {
|
||||
const picture = pickCivitaiPicture(info, anyRating);
|
||||
if (!picture) {
|
||||
loraToast(anyRating
|
||||
? "Civitai has no picture of this LoRA to save."
|
||||
: "Civitai has no picture of this LoRA rated PG-13 or milder.");
|
||||
return;
|
||||
}
|
||||
if (!picture) return false;
|
||||
const response = await fetch(smallPictureUrl(picture.url), {
|
||||
credentials: "omit", referrerPolicy: "no-referrer", cache: "no-store",
|
||||
});
|
||||
@@ -1577,6 +1590,76 @@ async function saveCivitaiPicture(serverName, info, anyRating) {
|
||||
})).json();
|
||||
if (!saved.ok) throw new Error(saved.error || "Could not save the picture.");
|
||||
pictureSaved();
|
||||
return true;
|
||||
}
|
||||
|
||||
// ---------- Fetch all ----------
|
||||
|
||||
// The same one-file lookup for every LoRA in the stack that has no Civitai
|
||||
// info yet, one file at a time (runCivitaiQueue). One run for the whole
|
||||
// page: Civitai counts requests per browser, not per node.
|
||||
let civitaiRun = null;
|
||||
|
||||
function fetchAllFromCivitai(state) {
|
||||
if (state.settings?.civitai_lookup === false) return;
|
||||
if (civitaiRun) {
|
||||
if (civitaiRun.state !== state) loraToast("Another LoRA Loader is fetching Civitai info. Wait for it, or stop it there.");
|
||||
return;
|
||||
}
|
||||
const names = state.rows.map((row) => row.name).filter(Boolean)
|
||||
.map((name) => effectiveLoraName(state, name));
|
||||
const hasPicture = new Map();
|
||||
const run = { state, done: 0, total: null, stopping: false, wake: null, button: null };
|
||||
civitaiRun = run;
|
||||
renderRows(state);
|
||||
runCivitaiQueue(names, {
|
||||
needsLookup: async (name) => {
|
||||
const data = await (await api.fetchApi(`/ausboss/lora/info?name=${encodeURIComponent(name)}`)).json();
|
||||
if (!data.ok) throw new Error(data.error || "No such LoRA.");
|
||||
hasPicture.set(name, Boolean(data.info.has_preview));
|
||||
return !data.info.has_civitai;
|
||||
},
|
||||
// The picture setting is read per file, so a change mid-run counts.
|
||||
lookUp: (name) => lookUpOnCivitai(name,
|
||||
hasPicture.get(name) ? "off" : (state.settings?.civitai_picture ?? "PG-13"), { quiet: true }),
|
||||
wait: (ms) => new Promise((resolve) => {
|
||||
const timer = setTimeout(resolve, ms);
|
||||
run.wake = () => { clearTimeout(timer); resolve(); };
|
||||
}),
|
||||
shouldStop: () => run.stopping,
|
||||
onProgress: ({ done, total }) => {
|
||||
run.done = done;
|
||||
run.total = total;
|
||||
showCivitaiRun(run);
|
||||
},
|
||||
}).then((result) => loraToast(civitaiQueueSummary(result)))
|
||||
.catch((error) => loraToast(civitaiFailureText(error)))
|
||||
.finally(() => {
|
||||
civitaiRun = null;
|
||||
if (state.panel?.isConnected) renderRows(state);
|
||||
});
|
||||
}
|
||||
|
||||
// While a run works, its node's footer holds one button: how far it is, and
|
||||
// a click stops it after the file being fetched.
|
||||
function civitaiRunButton(run) {
|
||||
const button = compactAction("", "Fetching Civitai info for every LoRA in this stack "
|
||||
+ "that has none yet, one at a time. Click to stop after the current one.");
|
||||
button.classList.add("ausboss-lora-civitai-run");
|
||||
button.addEventListener("click", () => {
|
||||
run.stopping = true;
|
||||
run.wake?.();
|
||||
showCivitaiRun(run);
|
||||
});
|
||||
run.button = button;
|
||||
showCivitaiRun(run);
|
||||
return button;
|
||||
}
|
||||
|
||||
function showCivitaiRun(run) {
|
||||
if (!run.button) return;
|
||||
run.button.disabled = run.stopping;
|
||||
run.button.textContent = run.stopping ? "Stopping..." : civitaiQueueLabel(run.done, run.total);
|
||||
}
|
||||
|
||||
// ---------- info card ----------
|
||||
@@ -1675,7 +1758,17 @@ function openInfo(state, index, anchor) {
|
||||
loraToast(fetchButton.title);
|
||||
}
|
||||
});
|
||||
card.append(fetchButton);
|
||||
const fetchAll = compactAction("Fetch all LoRAs",
|
||||
"Fetch Civitai info for every LoRA in this stack that has none yet, one at a time.");
|
||||
fetchAll.classList.add("ausboss-lora-fetch-all");
|
||||
fetchAll.disabled = Boolean(civitaiRun);
|
||||
fetchAll.addEventListener("click", () => {
|
||||
closePopup();
|
||||
fetchAllFromCivitai(state);
|
||||
});
|
||||
const fetchRow = el("div", "ausboss-lora-fetchrow");
|
||||
fetchRow.append(fetchButton, fetchAll);
|
||||
card.append(fetchRow);
|
||||
}
|
||||
|
||||
const range = el("div", "ausboss-lora-range");
|
||||
@@ -2680,6 +2773,19 @@ function openSettings(state, anchor) {
|
||||
runImportChain(state);
|
||||
},
|
||||
},
|
||||
...(state.settings?.civitai_lookup === false ? [] : [{
|
||||
key: "_civitai_all",
|
||||
label: "Civitai info for every LoRA",
|
||||
type: "action",
|
||||
button: "Fetch all LoRAs",
|
||||
hint: "Look up every LoRA in this stack that has no Civitai info yet, "
|
||||
+ "one at a time, the same way the info card's button does. The "
|
||||
+ "bottom of the node shows how far it is; click there to stop.",
|
||||
onAction: () => {
|
||||
closeSettingsMenu();
|
||||
fetchAllFromCivitai(state);
|
||||
},
|
||||
}]),
|
||||
];
|
||||
// Inside a subgraph the rows can show on the box's face instead; first in
|
||||
// the menu there, since it is what a loader in a box is usually set up for.
|
||||
@@ -3077,6 +3183,7 @@ function renderRows(state) {
|
||||
add.addEventListener("click", addRowAndPick);
|
||||
add.title = "Pick one LoRA, or click a folder name to add all its LoRAs.";
|
||||
actions.append(add);
|
||||
if (civitaiRun?.state === state) actions.append(civitaiRunButton(civitaiRun));
|
||||
stack.append(actions);
|
||||
body.append(stack);
|
||||
decorateRows(state);
|
||||
|
||||
@@ -16,6 +16,7 @@ import { compactAction, HINT_TYPE } from "../shared/panel_controls.mjs";
|
||||
import { holdNodeMinWidth, pinVuePanelHeight } from "../shared/panel_layout.mjs";
|
||||
import { FONT_UI, RADIUS_CONTROL, THEME as T } from "../shared/theme.mjs";
|
||||
import { bottomButtons } from "../shared/viewer3d_layout.mjs";
|
||||
import { viewValue } from "../shared/viewer_view.mjs";
|
||||
|
||||
const NODE_CLASS = "AUSBOSS_NODES_PauseShot";
|
||||
const PANEL = "ausboss_pause_shot_panel";
|
||||
@@ -58,6 +59,9 @@ async function readShot(viewer) {
|
||||
}
|
||||
const sky = viewer?.properties?.["AusBoss View"]?.sky;
|
||||
if (sky && typeof sky === "object") shot.sky = sky;
|
||||
// The viewer's Cut, so the run's mesh is cut the way the viewer shows it.
|
||||
const cut = viewer?.properties?.["AusBoss View"]?.cut;
|
||||
if (cut && typeof cut === "object") shot.cut = cut;
|
||||
// The 360 taken out of the viewer (its background image removed) leaves
|
||||
// the backdrop grey, as with no 360 wired in.
|
||||
const scene = viewerGizmo(viewer)?.__ausbossScene;
|
||||
@@ -278,6 +282,15 @@ app.registerExtension({
|
||||
holdNodeMinWidth(widget, MIN_WIDTH);
|
||||
widget.options.minNodeSize = [MIN_WIDTH, 60];
|
||||
this.__ausbossPauseShot = panel;
|
||||
// The viewer's 360 settings and Cut go into the hidden `view` input as
|
||||
// the prompt is built, so a run that goes straight through runs again
|
||||
// when one of them changed (js/shared/viewer_view.mjs). The widget
|
||||
// itself holds nothing, so a saved workflow carries no copy.
|
||||
const view = this.widgets?.find((item) => item.name === "view");
|
||||
if (view) {
|
||||
view.value = "";
|
||||
view.serializeValue = () => viewValue(viewerOf(this)?.properties?.["AusBoss View"]);
|
||||
}
|
||||
});
|
||||
chainCallback(nodeType.prototype, "onRemoved", function () {
|
||||
this.__ausbossPauseShot?.clear();
|
||||
|
||||
+25
-13
@@ -33,7 +33,7 @@ const CARD_HEIGHT = 288;
|
||||
const WRAPPER_INSET = 16;
|
||||
const HIDDEN = [
|
||||
"filename_prefix", "format", "save_metadata", "exact_name", "on_existing",
|
||||
"output_dir", "caption", "name_counter", "name_date", "name_time", "name_size", "name_batch", "autosave",
|
||||
"output_dir", "caption", "name_counter", "name_date", "name_time", "name_size", "name_batch", "autosave", "civitai_info",
|
||||
];
|
||||
const FONT = `-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif`;
|
||||
const MONO = `ui-monospace,SFMono-Regular,Menlo,Consolas,monospace`;
|
||||
@@ -64,6 +64,7 @@ function ensureCss() {
|
||||
.ausboss-save-half{display:flex;align-items:center;gap:6px;flex:1 1 auto;min-width:0}
|
||||
.ausboss-save-half .ausboss-card-seg{flex:1 1 0;min-width:0}
|
||||
.ausboss-save-switches{gap:12px}
|
||||
.ausboss-save-half.embed{flex-grow:1.5}
|
||||
.ausboss-save-browse{position:fixed;z-index:10000;width:260px;max-height:320px;overflow:auto;padding:4px;border:1px solid #3a4047;border-radius:7px;background:#1c1f23;box-shadow:0 8px 28px rgba(0,0,0,.5);font:12px/1.3 ${FONT};color:#d8ecea}
|
||||
.ausboss-save-browse-head{padding:5px 8px 6px;border-bottom:1px solid #2c3238;color:#78908e;font:10px/1 ${FONT};letter-spacing:.08em;text-transform:uppercase;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||||
.ausboss-save-browse button{display:block;width:100%;padding:6px 8px;border:none;border-radius:5px;background:transparent;color:inherit;font:inherit;text-align:left;cursor:pointer}
|
||||
@@ -273,20 +274,31 @@ function buildCard(node) {
|
||||
}
|
||||
root.append(seg);
|
||||
|
||||
// Embed workflow: a no | yes pill, the pack's boolean.
|
||||
// Embed: what goes in the file, in one pill. Off is a clean picture; On
|
||||
// stores the prompt and workflow for drag-back; Civitai stores them too and
|
||||
// adds the settings line civitai.com reads (save_metadata + civitai_info).
|
||||
const embedRow = el("div", "ausboss-save-row");
|
||||
const embedSeg = el("div", "ausboss-card-seg ausboss-card-bool");
|
||||
embedSeg.setAttribute("role", "radiogroup");
|
||||
const embedButtons = new Map();
|
||||
const embedTitle = "Embed stores the prompt and workflow in the image for drag-back. Off writes a clean image for sharing or datasets.";
|
||||
for (const [on, text] of [[false, PANEL_LABELS.off], [true, PANEL_LABELS.on]]) {
|
||||
const embedChoices = [
|
||||
["off", PANEL_LABELS.off, false, false, "Off writes a clean image, with no prompt or workflow inside - for sharing or datasets."],
|
||||
["on", PANEL_LABELS.on, true, false, "On stores the prompt and workflow in the image, so it drags back into ComfyUI."],
|
||||
["civitai", "Civitai", true, true, "Civitai stores the workflow and also the prompt, settings and model and LoRA fingerprints the way civitai.com reads them, so an upload lists its prompt and resources."],
|
||||
];
|
||||
for (const [key, text, embed, civitai, title] of embedChoices) {
|
||||
const button = el("button", "", text);
|
||||
button.type = "button"; button.title = embedTitle;
|
||||
button.addEventListener("click", () => { if (setValue(node, "save_metadata", on)) notifyAusbossChange(); state.refresh(); });
|
||||
embedSeg.append(button); embedButtons.set(on, button);
|
||||
button.type = "button"; button.title = title;
|
||||
button.addEventListener("click", () => {
|
||||
const changedEmbed = setValue(node, "save_metadata", embed);
|
||||
const changedCivitai = setValue(node, "civitai_info", civitai);
|
||||
if (changedEmbed || changedCivitai) notifyAusbossChange();
|
||||
state.refresh();
|
||||
});
|
||||
embedSeg.append(button); embedButtons.set(key, button);
|
||||
}
|
||||
const embedHalf = el("div", "ausboss-save-half");
|
||||
embedHalf.append(el("span", "ausboss-save-embed-label", PANEL_LABELS.embed), embedSeg);
|
||||
const embedHalf = el("div", "ausboss-save-half embed");
|
||||
embedHalf.append(el("span", "ausboss-save-embed-label", "Embed"), embedSeg);
|
||||
embedRow.classList.add("ausboss-save-switches");
|
||||
embedRow.append(embedHalf);
|
||||
root.append(embedRow);
|
||||
@@ -348,10 +360,10 @@ function buildCard(node) {
|
||||
chips.classList.toggle("off", !tagsEnabled(values));
|
||||
for (const [key, chip] of chipButtons) chip.classList.toggle("on", Boolean(values[key]));
|
||||
for (const [key, button] of formatButtons) button.classList.toggle("on", values.format === key);
|
||||
const embed = Boolean(values.save_metadata);
|
||||
for (const [on, button] of embedButtons) {
|
||||
button.classList.toggle("on", on === embed);
|
||||
button.setAttribute("aria-checked", String(on === embed));
|
||||
const embed = !values.save_metadata ? "off" : values.civitai_info ? "civitai" : "on";
|
||||
for (const [key, button] of embedButtons) {
|
||||
button.classList.toggle("on", key === embed);
|
||||
button.setAttribute("aria-checked", String(key === embed));
|
||||
}
|
||||
const auto = values.autosave !== false;
|
||||
for (const [on, button] of autoButtons) {
|
||||
|
||||
@@ -104,3 +104,119 @@ export function isCivitaiAddress(url) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- fetch all ----------
|
||||
// One button runs the same one-file lookup for every LoRA in a stack that has
|
||||
// no Civitai info yet: one file at a time, with a pause between files so
|
||||
// Civitai is not asked too fast. Nothing here talks to the network itself;
|
||||
// the caller hands in the lookup.
|
||||
|
||||
// The pause between two lookups, and the longer one after Civitai answers
|
||||
// 429 ("too many requests"). A second 429 ends the run.
|
||||
export const QUEUE_PAUSE_MS = 1500;
|
||||
export const SLOW_DOWN_PAUSE_MS = 20000;
|
||||
// This many failures in a row ends the run: something is wrong for all files.
|
||||
export const MAX_FAILURES_IN_A_ROW = 3;
|
||||
|
||||
// `names`: the stack's LoRA names (repeats and blanks are dropped).
|
||||
// `needsLookup(name)`: true when the file has no Civitai info yet; an error
|
||||
// means the file is missing, and it is left out.
|
||||
// `lookUp(name)`: false when Civitai does not know the file, else
|
||||
// `{ picture }` ("saved" when a picture was saved). An error with
|
||||
// `status: 429` means slow down; a TypeError means Civitai cannot be reached.
|
||||
// `wait(ms)`: a pause; it may end early once `shouldStop()` is true.
|
||||
// `onProgress({ done, total, name })`: total is null while files are checked.
|
||||
export async function runCivitaiQueue(names, {
|
||||
needsLookup, lookUp, wait, shouldStop = () => false, onProgress = () => {},
|
||||
pauseMs = QUEUE_PAUSE_MS, slowDownMs = SLOW_DOWN_PAUSE_MS,
|
||||
}) {
|
||||
const result = {
|
||||
total: 0, done: 0, found: 0, pictures: 0, notFound: 0, failed: 0,
|
||||
alreadyHad: 0, missing: 0, stopped: null, error: null,
|
||||
};
|
||||
const unique = [...new Set((names ?? []).filter((name) => typeof name === "string" && name))];
|
||||
const todo = [];
|
||||
onProgress({ done: 0, total: null, name: null });
|
||||
for (const name of unique) {
|
||||
if (shouldStop()) { result.stopped = "you"; return result; }
|
||||
try {
|
||||
if (await needsLookup(name)) todo.push(name);
|
||||
else result.alreadyHad += 1;
|
||||
} catch {
|
||||
result.missing += 1;
|
||||
}
|
||||
}
|
||||
result.total = todo.length;
|
||||
onProgress({ done: 0, total: result.total, name: null });
|
||||
let failuresInRow = 0;
|
||||
for (const name of todo) {
|
||||
if (result.done > 0) await wait(pauseMs);
|
||||
if (shouldStop()) { result.stopped = "you"; return result; }
|
||||
let slowedDown = false;
|
||||
for (;;) {
|
||||
try {
|
||||
const answer = await lookUp(name);
|
||||
if (answer) {
|
||||
result.found += 1;
|
||||
if (answer.picture === "saved") result.pictures += 1;
|
||||
} else {
|
||||
result.notFound += 1;
|
||||
}
|
||||
failuresInRow = 0;
|
||||
break;
|
||||
} catch (error) {
|
||||
if (error?.status === 429 && !slowedDown) {
|
||||
slowedDown = true;
|
||||
await wait(slowDownMs);
|
||||
if (shouldStop()) { result.stopped = "you"; return result; }
|
||||
continue;
|
||||
}
|
||||
result.error = error;
|
||||
if (error?.status === 429) { result.stopped = "slow down"; return result; }
|
||||
if (error instanceof TypeError) { result.stopped = "unreachable"; return result; }
|
||||
result.failed += 1;
|
||||
failuresInRow += 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
result.done += 1;
|
||||
onProgress({ done: result.done, total: result.total, name });
|
||||
if (failuresInRow >= MAX_FAILURES_IN_A_ROW) { result.stopped = "failures"; return result; }
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
// The run's button while it works: where it is, and that a click stops it.
|
||||
export function civitaiQueueLabel(done, total) {
|
||||
return total == null ? "Civitai: checking · Stop" : `Civitai ${done} / ${total} · Stop`;
|
||||
}
|
||||
|
||||
const plural = (count, word) => `${count} ${word}${count === 1 ? "" : "s"}`;
|
||||
|
||||
// What the run did, in one or two plain sentences for the closing message.
|
||||
export function civitaiQueueSummary(result) {
|
||||
if (!result.total && !result.stopped) {
|
||||
if (result.alreadyHad && !result.missing) return "Every LoRA in this stack already has its Civitai info.";
|
||||
if (!result.alreadyHad && !result.missing) return "This stack has no LoRAs to look up.";
|
||||
}
|
||||
const parts = [];
|
||||
if (result.found) {
|
||||
parts.push(`found ${plural(result.found, "LoRA")}`
|
||||
+ (result.pictures ? ` (${plural(result.pictures, "new picture")})` : ""));
|
||||
}
|
||||
if (result.notFound) parts.push(`${result.notFound} not on Civitai`);
|
||||
if (result.failed) parts.push(`${result.failed} failed`);
|
||||
if (result.alreadyHad) parts.push(`${result.alreadyHad} already had info`);
|
||||
if (result.missing) parts.push(`${plural(result.missing, "file")} not found on disk`);
|
||||
let text = parts.length ? `Civitai: ${parts.join(", ")}.` : "Civitai: nothing fetched.";
|
||||
const left = result.total - result.done;
|
||||
if (result.stopped === "you") text += ` Stopped with ${left} left.`;
|
||||
else if (result.stopped === "slow down") {
|
||||
text += ` Civitai asked us to slow down, so it stopped with ${left} left. Try again in a few minutes.`;
|
||||
} else if (result.stopped === "unreachable") text += ` ${civitaiFailureText(result.error)}`;
|
||||
else if (result.failed && !result.stopped) text += ` Last failure: ${civitaiFailureText(result.error)}`;
|
||||
else if (result.stopped === "failures") {
|
||||
text += ` Stopped after ${MAX_FAILURES_IN_A_ROW} failures in a row: ${civitaiFailureText(result.error)}`;
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
+15
-3
@@ -9,6 +9,8 @@
|
||||
|
||||
export const ZH = {
|
||||
// ---- card rows and group headers
|
||||
"Lens": "镜头视角", "Crop margin": "裁剪边距", "360 width": "360 宽度",
|
||||
"How wide the photo is, in degrees across. Wire Get FoV from MoGe here.": "照片横向有多宽,单位为度。把 MoGe 的“获取视角”接到这里。",
|
||||
"Target": "目标", "Size": "尺寸", "Edge": "边缘", "Budget": "像素预算", "Scale": "缩放", "Fit": "适应",
|
||||
"Fill": "填充", "Multiple": "倍数", "Filter": "滤镜", "Job": "任务", "Pieces": "分块数",
|
||||
"Lock": "锁定", "Tolerance": "容差", "Feather": "羽化", "Remove tint": "去除偏色", "Strength": "强度",
|
||||
@@ -31,7 +33,7 @@ export const ZH = {
|
||||
"KV cache": "KV 缓存", "VLM reference": "VLM 参考", "Source": "素材", "Width": "宽度", "Height": "高度",
|
||||
"Longest side": "最长边", "Ratio": "比例", "Keep": "保留", "Round to": "取整到", "Enlarge": "放大小图",
|
||||
"Backdrop": "背景虚化", "Exact padding": "精确扩边", "Left": "左", "Top": "上", "Right": "右", "Bottom": "下",
|
||||
"Prefix": "文件名前缀", "Format": "格式", "FPS · CRF": "帧率 · CRF", "Ping-pong": "往返播放", "Embed workflow": "嵌入工作流",
|
||||
"Prefix": "文件名前缀", "Format": "格式", "FPS · CRF": "帧率 · CRF", "Ping-pong": "往返播放", "Embed workflow": "嵌入工作流", "Embed": "嵌入",
|
||||
"Pictures and settings": "图片与设置", "What H3 gets": "H3 收到的内容", "What happens": "发生了什么",
|
||||
"Align": "对齐", "Aspect ratio": "画面比例", "Crop, pad & resize": "裁剪、扩边与缩放", "Duration": "时长", "Ends at": "结束于",
|
||||
"Frames for": "帧数用于", "Start": "起点", "Whole video": "整段视频", "Clip IN": "片段入点", "Clip OUT": "片段出点",
|
||||
@@ -56,7 +58,7 @@ export const ZH = {
|
||||
"gray": "灰色", "edge": "边缘", "edge pixel": "边缘像素", "color": "纯色", "pillarbox blur": "两侧虚化", "replicate": "复制边缘",
|
||||
"source": "原图", "as typed": "照输入", "from the picture": "取自图片", "text": "文字", "object": "物体", "still": "静止", "handheld": "手持",
|
||||
"shaky": "抖动", "push in": "推近", "pull back": "拉远", "orbit": "环绕", "walking pov": "步行视角", "anime": "动漫", "comic book": "漫画",
|
||||
"pencil sketch": "铅笔素描", "watercolor": "水彩", "split sheet at gaps": "按空隙拆分拼图", "Pad": "扩边", "Crop": "裁剪",
|
||||
"pencil sketch": "铅笔素描", "watercolor": "水彩", "split sheet at gaps": "按空隙拆分拼图", "cut a piece": "裁出一块", "Move right": "右移", "Move down": "下移", "Position": "位置", "Pad": "扩边", "Crop": "裁剪",
|
||||
"Resize": "缩放", "Center": "居中", "Soft": "柔和", "Simple": "简易", "Full prompt": "完整提示词", "Text": "文字", "Fixed": "固定",
|
||||
"LTX (8n+1)": "LTX (8n+1)", "Wan (4n+1)": "Wan (4n+1)", "Every group": "每个分组", "Numbered groups": "编号分组",
|
||||
"Titles matching…": "按标题匹配…", "No groups": "没有分组", "All": "全部", "Background": "背景", "Subject": "主体",
|
||||
@@ -257,6 +259,13 @@ export const ZH = {
|
||||
"Each line becomes a moment. A blank line between lines is a cut.": "每一行是一个时刻,两行之间的空行表示切换场景。",
|
||||
"Enable or disable this LoRA": "启用或停用这个 LoRA",
|
||||
"Fetching...": "获取中…",
|
||||
"Fetch all LoRAs": "获取全部 LoRA",
|
||||
"Fetch Civitai info for every LoRA in this stack that has none yet, one at a time.": "逐个为这组中还没有 Civitai 信息的每个 LoRA 获取信息。",
|
||||
"Fetching Civitai info for every LoRA in this stack that has none yet, one at a time. Click to stop after the current one.": "正在逐个为这组中还没有 Civitai 信息的每个 LoRA 获取信息。点击可在当前这个完成后停止。",
|
||||
"Civitai info for every LoRA": "为全部 LoRA 获取 Civitai 信息",
|
||||
"Look up every LoRA in this stack that has no Civitai info yet, one at a time, the same way the info card's button does. The bottom of the node shows how far it is; click there to stop.": "逐个查询这组中还没有 Civitai 信息的每个 LoRA,方式与信息卡里的按钮相同。节点底部会显示进度;点击那里可停止。",
|
||||
"Stopping...": "正在停止…",
|
||||
"Civitai: checking · Stop": "Civitai:检查中 · 停止",
|
||||
"Group name": "分组名称",
|
||||
"Held": "已锁定",
|
||||
"Hide file extension": "隐藏文件扩展名",
|
||||
@@ -297,6 +306,8 @@ export const ZH = {
|
||||
"Unlink strength": "断开强度连线", "link": "连线",
|
||||
"Takes 1 off after each run. Tap for Random.": "每次运行后减 1。点一下改为随机。",
|
||||
"The words come from the wire.": "文字来自连线。",
|
||||
"from a link": "来自连线",
|
||||
"Set by a link into this input. Remove the link to type a value here.": "由连到这个输入的连线设置。断开连线后可在此输入数值。",
|
||||
"Tick to add with others": "勾选后与其他一起添加",
|
||||
"Toggle this trigger word into the row's output": "把这个触发词加入或移出该行的输出",
|
||||
"Trigger word separator": "触发词分隔符",
|
||||
@@ -320,7 +331,7 @@ export const ZH = {
|
||||
// Strings that deliberately stay English on a Chinese face: names, symbols
|
||||
// and technical terms with no everyday Chinese form.
|
||||
export const STAYS_ENGLISH = new Set([
|
||||
"W", "H", "FPS", "CFG", "LoRA", "VRAM", "Seed", "H3",
|
||||
"W", "H", "FPS", "CFG", "LoRA", "VRAM", "Seed", "H3", "Civitai",
|
||||
"lab", "rgb", "mkl", "bicubic", "bilinear", "lanczos", "nearest", "area",
|
||||
"gif", "webp", "mp4 h264", "mp4 h265", "mp4 h264 nvenc", "mp4 h265 nvenc", "mov prores", "mkv ffv1", "webm vp9", "webm av1",
|
||||
"big-lama.pt", "loras", "script", "video", "flashvsr_v1.1_fp16.safetensors", "f(a, b, c)", "a + b",
|
||||
@@ -332,6 +343,7 @@ export const SCRUB_HINT_ZH = "拖动调节,点击输入数字或算式(如 1
|
||||
|
||||
// A few strings carry a number or a name; the number stays and the words around it change.
|
||||
export const PATTERNS = [
|
||||
[/^Civitai (\d+) \/ (\d+) · Stop$/, (m, done, total) => `Civitai ${done} / ${total} · 停止`],
|
||||
[/^The limits of what this is wired to: (.*)\.$/, (m, names) => `它所连接对象的取值范围:${names}。`],
|
||||
[/^Set by "(.*)"\. Click to show it\. Right-click the row to unlink\.$/, (m, name) => `由“${name}”设置。点击可定位到它。右键该行可断开连线。`],
|
||||
[/^Source · feather (\d+) px · Fill (#[0-9a-fA-F]{6})$/, (m, f, c) => `素材 · 羽化 ${f} px · 填充 ${c}`],
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
// Image Resize 🆎: which card rows the node reads for the values set. No DOM
|
||||
// and no ComfyUI imports, so node:test covers it.
|
||||
|
||||
// Only a width × height box can disagree with the picture's shape; every other
|
||||
// target takes its shape from the picture, and the node always fits it
|
||||
// (nodes/_resize_helpers.py). So Fit is only read in width × height.
|
||||
export function readsFit(values) {
|
||||
return values?.target_mode === "width+height";
|
||||
}
|
||||
|
||||
// The fill colour paints pad's bars, so it is read only where pad is.
|
||||
export function readsFill(values) {
|
||||
return readsFit(values) && values?.keep_proportion === "pad";
|
||||
}
|
||||
+1
-1
@@ -9,7 +9,7 @@ import { app } from "../../../scripts/app.js";
|
||||
// Must match `version` in pyproject.toml — scripts/release_preflight.py
|
||||
// enforces it. The backend serves its copy at /ausboss/pack_version; a
|
||||
// mismatch means the browser cached JavaScript from an older install.
|
||||
export const AUSBOSS_JS_VERSION = "2.27.0";
|
||||
export const AUSBOSS_JS_VERSION = "2.28.1";
|
||||
|
||||
export const BRAND = "#00b4aa"; // AusBoss teal — keep node accents consistent.
|
||||
export const BRAND_DARK = "#007f78";
|
||||
|
||||
@@ -8,8 +8,8 @@
|
||||
// quality dial of the software and NVENC encoders and maps onto webp's
|
||||
// quality scale, while prores rides its own profile ladder, ffv1 is lossless
|
||||
// by definition, and Pillow's gif path quantizes per frame with no quality
|
||||
// dial at all. gif and webp are written frame by frame through Pillow and
|
||||
// never carry the workflow metadata the video containers embed.
|
||||
// dial at all. gif and webp are written frame by frame through Pillow; webp
|
||||
// carries the workflow in EXIF as core's animated WebP does, gif never does.
|
||||
export const FORMAT_WIDGET_SETS = {
|
||||
"mp4 h264": ["crf", "save_metadata"],
|
||||
"mp4 h265": ["crf", "save_metadata"],
|
||||
@@ -20,7 +20,7 @@ export const FORMAT_WIDGET_SETS = {
|
||||
"mov prores": ["save_metadata"],
|
||||
"mkv ffv1": ["save_metadata"],
|
||||
"gif": [],
|
||||
"webp": ["crf"],
|
||||
"webp": ["crf", "save_metadata"],
|
||||
};
|
||||
|
||||
// The only widgets the format ever toggles. Everything else on the node —
|
||||
|
||||
@@ -6,6 +6,7 @@ import { hideInputsInDef, hideWidget } from "./widget_visibility.mjs";
|
||||
import { mountTransformTrim } from "./transform_trim.mjs";
|
||||
import { mountClipWindow } from "./clip_window.mjs";
|
||||
import { clipOutputRate, inputNumber } from "./clip_rate.mjs";
|
||||
import { wiredFieldText, wiredNumber, wiredResize, wiredSummaryParts, wiredSwitch } from "./transform_wired.mjs";
|
||||
import { BRAND, chainCallback, keepDomWidgetWidthAuto, notifyAusbossChange, showToast } from "./index.mjs";
|
||||
import { WIDGET_FRAME, fillNodeHeight, holdVueNodeMinWidth, holdVuePanelMinHeight } from "./panel_layout.mjs";
|
||||
import { mediaViewQuery, unlistedMedia } from "./media_list.mjs";
|
||||
@@ -191,6 +192,7 @@ function installStyles() {
|
||||
.ausboss-transform-group-title{display:inline-flex;align-items:center;gap:6px;letter-spacing:.05em;text-transform:uppercase;white-space:nowrap}
|
||||
.ausboss-transform-group-caret{display:inline-block;color:${BRAND};font-size:11px;transition:transform .14s ease}
|
||||
.ausboss-transform-group.open .ausboss-transform-group-caret{transform:rotate(90deg)}
|
||||
.ausboss-transform-wired{display:inline-flex;align-items:center;justify-content:flex-end;min-height:24px;padding:0 6px;border:1px dashed #3a5352;border-radius:5px;color:#8ca8a5;font:500 11px system-ui;font-variant-numeric:tabular-nums;white-space:nowrap;cursor:default}
|
||||
.ausboss-transform-group-summary{display:inline-flex;align-items:center;gap:6px;min-width:0;color:#8ca8a5;font:500 11px system-ui;font-variant-numeric:tabular-nums;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||||
.ausboss-transform-group-swatch{flex:none;width:10px;height:10px;border:1px solid #555b63;border-radius:3px;box-sizing:border-box}
|
||||
.ausboss-transform-group-meta{min-width:0;overflow:hidden;text-overflow:ellipsis}
|
||||
@@ -632,16 +634,9 @@ export function transformGroupSummary(state) {
|
||||
parts.push(`Custom ${ratioLabel(canvas.width, canvas.height)}`);
|
||||
}
|
||||
if (lockActive(state)) parts.push("held");
|
||||
const feather = Math.round(Number(value(node, "feather", 0)) || 0);
|
||||
if (feather > 0) parts.push(`feather ${feather} px`);
|
||||
const multiple = Math.round(Number(value(node, "canvas_multiple", 1)) || 1);
|
||||
if (multiple > 1) parts.push(`÷${multiple}`);
|
||||
if (widget(node, "resize_to_megapixels") && value(node, "resize_to_megapixels", false)) {
|
||||
const mp = Number(value(node, "megapixels", 1)) || 1;
|
||||
const steps = Math.round(Number(value(node, "resolution_steps", 1)) || 1);
|
||||
parts.push(`${mp.toFixed(2)} MP`);
|
||||
if (steps > 1 && multiple <= 1) parts.push(`÷${steps}`);
|
||||
}
|
||||
// Feather, Align and the resize as the run uses them: a linked input runs
|
||||
// with the wired value, not the widget's own (js/shared/transform_wired.mjs).
|
||||
parts.push(...wiredSummaryParts(node));
|
||||
return parts.join(" · ");
|
||||
}
|
||||
|
||||
@@ -933,6 +928,13 @@ export function installTransformNode(node, kind, mountPanel = null) {
|
||||
for (const trim of state.trimViews) trim.sync();
|
||||
}
|
||||
}
|
||||
// A wired value changed upstream (a Float typed to 24): the summary,
|
||||
// the face fields and the size readout follow it.
|
||||
if (!state.disposed) {
|
||||
const wired = JSON.stringify([wiredSummaryParts(node), wiredResize(node)]);
|
||||
if (state.wiredKey !== undefined && wired !== state.wiredKey) queueMicrotask(() => { if (!state.disposed) draw(state); });
|
||||
state.wiredKey = wired;
|
||||
}
|
||||
if (state.disposed || state.zoomRedraw || !panelBackingStale(state)) return;
|
||||
state.zoomRedraw = requestAnimationFrame(() => { state.zoomRedraw = null; if (!state.disposed) draw(state); });
|
||||
});
|
||||
@@ -956,6 +958,7 @@ export function installTransformNode(node, kind, mountPanel = null) {
|
||||
}
|
||||
chainCallback(node, "onConnectionsChange", () => queueMicrotask(() => {
|
||||
for (const trim of state.trimViews) trim.sync();
|
||||
if (!state.disposed) draw(state);
|
||||
}));
|
||||
chainCallback(node, "onConfigure", () => queueMicrotask(() => {
|
||||
if (state.disposed) return;
|
||||
@@ -1514,6 +1517,12 @@ function buildCanvasRow(state) {
|
||||
stepLabel.append(createElement("span", "", "Step"), steps.root);
|
||||
const hasResize = Boolean(widget(node, "resize_to_megapixels"));
|
||||
resizeRow.append(resizeLabel, budgetLabel, stepLabel);
|
||||
const wired = [
|
||||
wiredStandIn(node, "feather", feather, 0, (amount) => `${Math.round(amount)} px`),
|
||||
wiredStandIn(node, "canvas_multiple", multiple, 1, (amount) => `${Math.round(amount)} px`),
|
||||
wiredStandIn(node, "megapixels", budget, 1, (amount) => `${Number(amount).toFixed(2)} MP`),
|
||||
wiredStandIn(node, "resolution_steps", steps, 1, (amount) => `${Math.round(amount)} px`),
|
||||
];
|
||||
const sync = () => {
|
||||
fill.value = normalizeColor(value(node, "fill_color", "#808080"));
|
||||
fill.title = `${fill.title.split(" Now ")[0]} Now ${fill.value}.`;
|
||||
@@ -1523,7 +1532,9 @@ function buildCanvasRow(state) {
|
||||
resize.sync();
|
||||
budget.set(value(node, "megapixels", 1));
|
||||
steps.set(value(node, "resolution_steps", 1));
|
||||
const resizeOn = hasResize && Boolean(value(node, "resize_to_megapixels", false));
|
||||
for (const standIn of wired) standIn();
|
||||
const switched = wiredSwitch(node, "resize_to_megapixels", false);
|
||||
const resizeOn = hasResize && (!switched.known || Boolean(switched.value));
|
||||
resizeRow.style.display = hasResize ? "" : "none";
|
||||
budgetLabel.style.display = resizeOn ? "" : "none";
|
||||
stepLabel.style.display = resizeOn ? "" : "none";
|
||||
@@ -1537,6 +1548,22 @@ function buildCanvasRow(state) {
|
||||
return [alignRow, row, resizeRow];
|
||||
}
|
||||
|
||||
// A linked setting runs with the wired value, so its number box gives way to
|
||||
// that value (or "from a link" when only the run knows it). The box stays the
|
||||
// way to set the widget's own value once the link is gone. Returns the sync.
|
||||
function wiredStandIn(node, name, control, fallback, format) {
|
||||
const text = createElement("span", "ausboss-transform-wired");
|
||||
text.title = t("Set by a link into this input. Remove the link to type a value here.");
|
||||
text.style.display = "none";
|
||||
control.root.after(text);
|
||||
return () => {
|
||||
const shown = wiredFieldText(wiredNumber(node, name, fallback), format);
|
||||
control.root.style.display = shown === null ? "" : "none";
|
||||
text.style.display = shown === null ? "none" : "";
|
||||
if (shown !== null) text.textContent = shown === "from a link" ? t("from a link") : shown;
|
||||
};
|
||||
}
|
||||
|
||||
// Resize as an off | on pill, on the node face and in the editor.
|
||||
function resizeSwitch(state) {
|
||||
const node = state.node;
|
||||
@@ -1577,7 +1604,7 @@ function syncReadout(state) {
|
||||
const source = rotatedSize(state.sourceWidth, state.sourceHeight, current.rotation_degrees);
|
||||
const resize = resizeRequest(state.node);
|
||||
const chain = sizeChain(current, source, resize);
|
||||
const { tokens, warnings } = litTokens(state, sizeChainTokens(chain));
|
||||
const { tokens, warnings } = readoutTokens(state, chain);
|
||||
const prefix = createElement("span", "ausboss-transform-ellipsis");
|
||||
tokens.forEach((token, index) => {
|
||||
if (index) prefix.append(" → ");
|
||||
@@ -2334,6 +2361,12 @@ function buildControls(state, sidebar) {
|
||||
previewSection.append(finalPreview);
|
||||
state.finalPreviewCanvas = finalPreview;
|
||||
|
||||
const editorWired = [
|
||||
wiredStandIn(node, "feather", featherNumber, 24, (amount) => `${Math.round(amount)} px`),
|
||||
wiredStandIn(node, "canvas_multiple", multiple, 1, (amount) => `${Math.round(amount)} px`),
|
||||
...(budget ? [wiredStandIn(node, "megapixels", budget, 1, (amount) => `${Number(amount).toFixed(2)} MP`)] : []),
|
||||
...(steps ? [wiredStandIn(node, "resolution_steps", steps, 1, (amount) => `${Math.round(amount)} px`)] : []),
|
||||
];
|
||||
sidebar.append(cropSection, rotateSection, padSection);
|
||||
if (resizeSection) sidebar.append(resizeSection);
|
||||
sidebar.append(actions, previewSection);
|
||||
@@ -2343,6 +2376,7 @@ function buildControls(state, sidebar) {
|
||||
featherNumber.set(value(node, "feather", 24));
|
||||
multiple.set(value(node, "canvas_multiple", 1)); color.value = normalizeColor(value(node, "fill_color", "#808080"));
|
||||
resize?.sync(); budget?.set(value(node, "megapixels", 1)); steps?.set(value(node, "resolution_steps", 1));
|
||||
for (const standIn of editorWired) standIn();
|
||||
if (more) more.value = extra.includes(liveRequest(state) ?? "") ? liveRequest(state) : "";
|
||||
};
|
||||
}
|
||||
@@ -2891,10 +2925,23 @@ function drawScene(context, state, render, compact, interactive) {
|
||||
context.restore();
|
||||
}
|
||||
|
||||
// The resize the run makes, wired values included; null when it is off or a
|
||||
// link decides a part of it that only the run knows (resizeFromLink).
|
||||
function resizeRequest(node) {
|
||||
return value(node, "resize_to_megapixels", false)
|
||||
? { megapixels: value(node, "megapixels", 1), steps: value(node, "resolution_steps", 1) }
|
||||
: null;
|
||||
const resize = wiredResize(node);
|
||||
return resize && !resize.unknown ? resize : null;
|
||||
}
|
||||
|
||||
function resizeFromLink(node) {
|
||||
return Boolean(wiredResize(node)?.unknown);
|
||||
}
|
||||
|
||||
// The size chain's steps, ending on a resize a link decides when it does:
|
||||
// the size it lands on is only known at run time.
|
||||
function readoutTokens(state, chain) {
|
||||
const result = litTokens(state, sizeChainTokens(chain));
|
||||
if (resizeFromLink(state.node)) result.tokens = [...result.tokens, { label: "resize", text: "from a link" }];
|
||||
return result;
|
||||
}
|
||||
|
||||
// The size readout, drawn OUTSIDE the image: under the output rect, above
|
||||
@@ -2905,7 +2952,7 @@ function resizeRequest(node) {
|
||||
// amber line when the steps stretch the picture or the resize undoes Align.
|
||||
const READOUT_LINE = 15;
|
||||
function drawOutputSize(context, state, render) {
|
||||
const { tokens } = litTokens(state, sizeChainTokens(sizeChain(values(state.node), render.source, resizeRequest(state.node))));
|
||||
const { tokens } = readoutTokens(state, sizeChain(values(state.node), render.source, resizeRequest(state.node)));
|
||||
// The amber line is the settled note, as on the face: it waits for the hand.
|
||||
const warnings = shownNote(state).warnings;
|
||||
const { outputRect } = render;
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
// What the Crop + Rotate + Pad nodes will really use for a setting that can
|
||||
// be wired: a linked input runs with the wired value, not the widget's own.
|
||||
// A wired value also skips the input's range (ComfyUI only range-checks typed
|
||||
// values), so a Float of 24 wired into Megapixels resizes to 24 MP while the
|
||||
// widget still holds 16.
|
||||
//
|
||||
// Only typed numbers are read across the wire (clip_rate.mjs inputNumber):
|
||||
// a calculated value (Math Expression) stays unknown until the run, and the
|
||||
// face says the value comes from a link instead of showing a wrong one.
|
||||
//
|
||||
// Pure: reads `inputs`, `widgets` and `graph`, so tests run it on plain
|
||||
// objects.
|
||||
|
||||
import { inputNumber, linkOrigin } from "./clip_rate.mjs";
|
||||
|
||||
function widgetValue(node, name, fallback) {
|
||||
return node?.widgets?.find((item) => item.name === name)?.value ?? fallback;
|
||||
}
|
||||
|
||||
export function inputLinked(node, name) {
|
||||
const slot = node?.inputs?.find((input) => input?.name === name || input?.widget?.name === name);
|
||||
return slot?.link !== null && slot?.link !== undefined;
|
||||
}
|
||||
|
||||
// { value, linked, known } for a number setting. Unlinked: the widget's
|
||||
// value. Linked to a typed number: that number. Linked to anything else:
|
||||
// value null, known false.
|
||||
export function wiredNumber(node, name, fallback) {
|
||||
const own = widgetValue(node, name, fallback);
|
||||
if (!inputLinked(node, name)) return { value: own, linked: false, known: true };
|
||||
const read = inputNumber(node, name, own);
|
||||
return read === null ? { value: null, linked: true, known: false } : { value: read, linked: true, known: true };
|
||||
}
|
||||
|
||||
const SWITCHES = ["PrimitiveBoolean"];
|
||||
|
||||
// The same for an on/off setting.
|
||||
export function wiredSwitch(node, name, fallback) {
|
||||
const own = Boolean(widgetValue(node, name, fallback));
|
||||
if (!inputLinked(node, name)) return { value: own, linked: false, known: true };
|
||||
const origin = linkOrigin(node, name);
|
||||
const unknown = { value: null, linked: true, known: false };
|
||||
if (!origin) return unknown;
|
||||
const { node: source, slot } = origin;
|
||||
let read;
|
||||
if ((source.comfyClass ?? source.type) === "PrimitiveNode") read = source.widgets?.[0]?.value;
|
||||
else if (SWITCHES.includes(source.type) && slot === 0
|
||||
&& !source.inputs?.some((input) => input.name === "value" && input.link != null)) {
|
||||
read = source.widgets?.find((item) => item.name === "value")?.value;
|
||||
}
|
||||
return typeof read === "boolean" ? { value: read, linked: true, known: true } : unknown;
|
||||
}
|
||||
|
||||
// The resize the run makes: null when it is off, { megapixels, steps } when
|
||||
// every part is known, { unknown: true } when a link decides a part of it.
|
||||
export function wiredResize(node) {
|
||||
if (!node?.widgets?.some((item) => item.name === "resize_to_megapixels")) return null;
|
||||
const on = wiredSwitch(node, "resize_to_megapixels", false);
|
||||
if (on.known && !on.value) return null;
|
||||
const megapixels = wiredNumber(node, "megapixels", 1);
|
||||
const steps = wiredNumber(node, "resolution_steps", 1);
|
||||
if (!on.known || !megapixels.known || !steps.known) return { unknown: true };
|
||||
return { megapixels: Number(megapixels.value) || 1, steps: Number(steps.value) || 1 };
|
||||
}
|
||||
|
||||
// The end of the "Crop, pad & resize" summary: feather, Align, and the
|
||||
// resize, each as the run will use it.
|
||||
export function wiredSummaryParts(node) {
|
||||
const parts = [];
|
||||
const feather = wiredNumber(node, "feather", 0);
|
||||
if (!feather.known) parts.push("feather from a link");
|
||||
else if (Math.round(Number(feather.value) || 0) > 0) parts.push(`feather ${Math.round(Number(feather.value))} px`);
|
||||
const multiple = wiredNumber(node, "canvas_multiple", 1);
|
||||
const align = multiple.known ? Math.round(Number(multiple.value) || 1) : null;
|
||||
if (align === null) parts.push("align from a link");
|
||||
else if (align > 1) parts.push(`÷${align}`);
|
||||
if (!node?.widgets?.some((item) => item.name === "resize_to_megapixels")) return parts;
|
||||
const on = wiredSwitch(node, "resize_to_megapixels", false);
|
||||
if (on.known && !on.value) return parts;
|
||||
if (!on.known) parts.push("resize from a link");
|
||||
const megapixels = wiredNumber(node, "megapixels", 1);
|
||||
parts.push(megapixels.known ? `${(Number(megapixels.value) || 1).toFixed(2)} MP` : "MP from a link");
|
||||
const steps = wiredNumber(node, "resolution_steps", 1);
|
||||
if (!steps.known) parts.push("step from a link");
|
||||
else if (Math.round(Number(steps.value) || 1) > 1 && align !== null && align <= 1) parts.push(`÷${Math.round(Number(steps.value))}`);
|
||||
return parts;
|
||||
}
|
||||
|
||||
// What a face field shows for a linked setting in place of its number box:
|
||||
// the wired number, or that a link sets it.
|
||||
export function wiredFieldText(reading, format) {
|
||||
if (!reading.linked) return null;
|
||||
return reading.known ? format(reading.value) : "from a link";
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
// The viewer's 360 settings and Cut (its "AusBoss View" property,
|
||||
// js/viewer_pano) as one string, for Pause for Shot's hidden `view` input.
|
||||
// ComfyUI runs a node again only when one of its inputs changes, and a
|
||||
// node's properties in the saved workflow are not inputs: read from there, a
|
||||
// changed Turn handed back the old backdrop. So the page writes them into
|
||||
// the input as the prompt is built (js/pause_shot). The keys are sorted, so
|
||||
// the same settings always give the same string and a run with nothing
|
||||
// changed still comes from the cache.
|
||||
|
||||
const KEYS = ["sky", "cut"];
|
||||
|
||||
function sorted(value) {
|
||||
if (Array.isArray(value)) return value.map(sorted);
|
||||
if (!value || typeof value !== "object") return value;
|
||||
const out = {};
|
||||
for (const key of Object.keys(value).sort()) out[key] = sorted(value[key]);
|
||||
return out;
|
||||
}
|
||||
|
||||
export function viewValue(view) {
|
||||
if (!view || typeof view !== "object") return "";
|
||||
const out = {};
|
||||
for (const key of KEYS) {
|
||||
const part = view[key];
|
||||
if (part && typeof part === "object" && !Array.isArray(part)) out[key] = sorted(part);
|
||||
}
|
||||
return Object.keys(out).length ? JSON.stringify(out) : "";
|
||||
}
|
||||
+122
-7
@@ -3,7 +3,9 @@
|
||||
// end (the bar itself is full at a normal node width), so it never covers
|
||||
// the frame. Its tabs:
|
||||
// - Model: spin, tip and lean the model itself (saved with the shot, so
|
||||
// the run's 3D shot follows).
|
||||
// the run's 3D shot follows), and Cut: take away the front or back of
|
||||
// the model, a share of its depth as the camera sees it (Pause for
|
||||
// Shot cuts the run's mesh the same way, nodes/_mesh_cut_helpers.py).
|
||||
// - Angle: turn, tilt and roll the 360 background, and its own field of
|
||||
// view, and whether the 360 moves as the camera orbits (as the viewer
|
||||
// draws it) or stays fixed in the frame like a photo backdrop.
|
||||
@@ -37,6 +39,7 @@ export const SKY_DEFAULTS = Object.freeze({ turn: 0, tilt: 0, roll: 0, fov: null
|
||||
export const ORBITS = Object.freeze(["moves", "fixed"]);
|
||||
export const LIGHTS = Object.freeze(["studio", "photo", "360"]);
|
||||
export const LOOK_DEFAULTS = Object.freeze({ light: "studio", strength: 100, bright: 100, contrast: 100, saturation: 100, warmth: 0 });
|
||||
export const CUT_DEFAULTS = Object.freeze({ front: 0, back: 0 });
|
||||
|
||||
const ICONS = {
|
||||
sky: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round"><circle cx="12" cy="12" r="8.5"/><ellipse cx="12" cy="12" rx="3.6" ry="8.5"/><path d="M3.5 12h17"/></svg>',
|
||||
@@ -367,13 +370,112 @@ function applyLook(manager, state) {
|
||||
state.dirty = false;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ cut
|
||||
// Two clipping planes square to the camera keep a band of the model's
|
||||
// depth: Front takes that share off the near side, Back off the far side.
|
||||
// The depth is how far the box around the model's own points reaches along
|
||||
// the view, the same box Pause for Shot measures on the run's mesh.
|
||||
|
||||
const cutBoxes = new WeakMap();
|
||||
function modelBox(model) {
|
||||
if (cutBoxes.has(model)) return cutBoxes.get(model);
|
||||
const Matrix = model.matrixWorld.constructor;
|
||||
model.updateMatrixWorld(true);
|
||||
const toModel = new Matrix().copy(model.matrixWorld).invert();
|
||||
const lo = [Infinity, Infinity, Infinity];
|
||||
const hi = [-Infinity, -Infinity, -Infinity];
|
||||
model.traverse((part) => {
|
||||
if (!part.isMesh || !part.geometry) return;
|
||||
if (!part.geometry.boundingBox) part.geometry.computeBoundingBox?.();
|
||||
const box = part.geometry.boundingBox;
|
||||
if (!box) return;
|
||||
const into = new Matrix().multiplyMatrices(toModel, part.matrixWorld);
|
||||
const point = box.min.clone();
|
||||
for (const x of [box.min.x, box.max.x]) for (const y of [box.min.y, box.max.y]) for (const z of [box.min.z, box.max.z]) {
|
||||
point.set(x, y, z).applyMatrix4(into);
|
||||
["x", "y", "z"].forEach((axis, i) => { lo[i] = Math.min(lo[i], point[axis]); hi[i] = Math.max(hi[i], point[axis]); });
|
||||
}
|
||||
});
|
||||
const box = Number.isFinite(lo[0]) ? { lo, hi } : null;
|
||||
if (box) cutBoxes.set(model, box);
|
||||
return box;
|
||||
}
|
||||
|
||||
const materialsOf = (part) => (Array.isArray(part.material) ? part.material : [part.material]).filter(Boolean);
|
||||
function clearCut(state) {
|
||||
state.cutModel?.traverse?.((part) => {
|
||||
if (!part.isMesh) return;
|
||||
for (const material of materialsOf(part)) {
|
||||
if (material.clippingPlanes !== state.cutPlanes) continue;
|
||||
material.clippingPlanes = null;
|
||||
if ("ausbossCutSide" in material.userData) {
|
||||
material.side = material.userData.ausbossCutSide;
|
||||
delete material.userData.ausbossCutSide;
|
||||
}
|
||||
material.needsUpdate = true;
|
||||
}
|
||||
});
|
||||
state.cutModel = null;
|
||||
}
|
||||
|
||||
function applyCut(manager, state) {
|
||||
const cut = state.values.cut;
|
||||
const model = modelOf(manager);
|
||||
if (!(cut.front > 0 || cut.back > 0) || !model) { if (state.cutModel) clearCut(state); return; }
|
||||
const camera = manager.getActiveCamera?.();
|
||||
const box = modelBox(model);
|
||||
if (!camera || !box) return;
|
||||
if (state.cutModel && state.cutModel !== model) clearCut(state);
|
||||
model.updateMatrixWorld(true);
|
||||
camera.updateMatrixWorld();
|
||||
const Vector = camera.position.constructor;
|
||||
const eye = new Vector().setFromMatrixPosition(camera.matrixWorld);
|
||||
const forward = camera.getWorldDirection(new Vector());
|
||||
const point = new Vector();
|
||||
let lo = Infinity;
|
||||
let hi = -Infinity;
|
||||
for (const x of [box.lo[0], box.hi[0]]) for (const y of [box.lo[1], box.hi[1]]) for (const z of [box.lo[2], box.hi[2]]) {
|
||||
const depth = point.set(x, y, z).applyMatrix4(model.matrixWorld).sub(eye).dot(forward);
|
||||
lo = Math.min(lo, depth);
|
||||
hi = Math.max(hi, depth);
|
||||
}
|
||||
const front = Math.min(99, Math.max(0, cut.front));
|
||||
const back = Math.min(99 - front, Math.max(0, cut.back));
|
||||
const near = lo + (hi - lo) * front / 100;
|
||||
const far = hi - (hi - lo) * back / 100;
|
||||
// three keeps the side where normal . p + constant >= 0.
|
||||
state.cutPlanes ??= [{ normal: new Vector(), constant: 0 }, { normal: new Vector(), constant: 0 }];
|
||||
const [nearPlane, farPlane] = state.cutPlanes;
|
||||
const along = eye.dot(forward);
|
||||
nearPlane.normal.copy(forward);
|
||||
nearPlane.constant = -(along + near);
|
||||
farPlane.normal.copy(forward).negate();
|
||||
farPlane.constant = along + far;
|
||||
manager.renderer.localClippingEnabled = true;
|
||||
// The viewer swaps materials for its own modes, so check them each frame.
|
||||
model.traverse((part) => {
|
||||
if (!part.isMesh) return;
|
||||
for (const material of materialsOf(part)) {
|
||||
if (material.clippingPlanes === state.cutPlanes) continue;
|
||||
material.clippingPlanes = state.cutPlanes;
|
||||
material.clipShadows = true;
|
||||
// Through the cut you see the model's inside, as Render Mesh draws
|
||||
// it, not a hole: both sides while cut (three's DoubleSide is 2).
|
||||
if (!("ausbossCutSide" in material.userData)) material.userData.ausbossCutSide = material.side;
|
||||
material.side = 2;
|
||||
material.needsUpdate = true;
|
||||
}
|
||||
});
|
||||
state.cutModel = model;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------- viewer registry
|
||||
|
||||
const managers = new Set();
|
||||
|
||||
function stateOf(manager) {
|
||||
return (manager.__ausbossViewState ??= {
|
||||
values: { sky: { ...SKY_DEFAULTS }, look: { ...LOOK_DEFAULTS } },
|
||||
values: { sky: { ...SKY_DEFAULTS }, look: { ...LOOK_DEFAULTS }, cut: { ...CUT_DEFAULTS } },
|
||||
sky: null, skyWasOn: false, envTexture: null, lookUsed: false, frame: 0, dirty: true,
|
||||
node: null, panorama: false, restored: false, lastMode: null,
|
||||
});
|
||||
@@ -418,6 +520,7 @@ function patchSceneManager() {
|
||||
const state = stateOf(this);
|
||||
keepPanorama(this, state);
|
||||
applyLook(this, state);
|
||||
applyCut(this, state);
|
||||
if (skyActive(this, state.values.sky)) {
|
||||
if (drawSky(this, state)) { state.skyWasOn = true; drawShadow(this, state); return undefined; }
|
||||
} else if (state.skyWasOn) {
|
||||
@@ -583,10 +686,15 @@ const COLOUR = { title: "Colour", group: "look", fields: [
|
||||
// The model's own turn. These read and write the loaded model's rotation
|
||||
// directly, which the viewer saves with the shot and hands to the run (its
|
||||
// model_3d_info), so the 3D shot follows. Nothing extra is saved here.
|
||||
// Front and Back cut are saved with the viewer ("cut" in its properties).
|
||||
const MODEL = { title: "Model", group: "model", fields: [
|
||||
{ key: "spin", label: "Spin", min: -180, max: 180, step: 1, fineStep: 0.1, decimals: 1, unit: "°", title: "Turn the model around, left or right." },
|
||||
{ key: "tip", label: "Tip", min: -90, max: 90, step: 1, fineStep: 0.1, decimals: 1, unit: "°", title: "Tip the model forward or back." },
|
||||
{ key: "lean", label: "Lean", min: -90, max: 90, step: 1, fineStep: 0.1, decimals: 1, unit: "°", title: "Lean the model left or right." },
|
||||
{ key: "front", store: "cut", label: "Cut front", min: 0, max: 99, step: 1, fineStep: 0.1, decimals: 1, unit: "%",
|
||||
title: "Cut away the part of the model nearest the camera, as a share of its depth." },
|
||||
{ key: "back", store: "cut", label: "Cut back", min: 0, max: 99, step: 1, fineStep: 0.1, decimals: 1, unit: "%",
|
||||
title: "Cut away the far side of the model, as a share of its depth: the inside of a hat behind the head, a hood, a back you don't want seen. Pause for Shot cuts the run's model the same way." },
|
||||
] };
|
||||
const TABS = [MODEL, ANGLE, BACKDROP, LIGHT, COLOUR];
|
||||
|
||||
@@ -615,7 +723,7 @@ function readSaved(node, state) {
|
||||
if (node?.properties?.["Scene Config"]?.backgroundRenderMode === "panorama") state.panorama = true;
|
||||
if (!saved || typeof saved !== "object") return;
|
||||
if (saved.panorama === true) state.panorama = true;
|
||||
for (const [group, defaults] of [["sky", SKY_DEFAULTS], ["look", LOOK_DEFAULTS]]) {
|
||||
for (const [group, defaults] of [["sky", SKY_DEFAULTS], ["look", LOOK_DEFAULTS], ["cut", CUT_DEFAULTS]]) {
|
||||
const from = saved[group] ?? {};
|
||||
for (const key of Object.keys(defaults)) {
|
||||
const value = from[key];
|
||||
@@ -636,8 +744,12 @@ function writeSaved(node, state) {
|
||||
node.properties ??= {};
|
||||
const skyDefault = isDefault(state.values.sky, SKY_DEFAULTS);
|
||||
const lookDefault = isDefault(state.values.look, LOOK_DEFAULTS);
|
||||
if (skyDefault && lookDefault && !state.panorama) delete node.properties[PROP];
|
||||
else node.properties[PROP] = { panorama: state.panorama, sky: { ...state.values.sky }, look: { ...state.values.look } };
|
||||
const cutDefault = isDefault(state.values.cut, CUT_DEFAULTS);
|
||||
if (skyDefault && lookDefault && cutDefault && !state.panorama) delete node.properties[PROP];
|
||||
else {
|
||||
node.properties[PROP] = { panorama: state.panorama, sky: { ...state.values.sky }, look: { ...state.values.look } };
|
||||
if (!cutDefault) node.properties[PROP].cut = { ...state.values.cut };
|
||||
}
|
||||
app.graph?.setDirtyCanvas?.(true, false);
|
||||
}
|
||||
|
||||
@@ -791,7 +903,8 @@ function buildStrip(box, root, manager) {
|
||||
});
|
||||
}
|
||||
for (const field of spec.fields) {
|
||||
const row = field.pill ? pillField(field, values) : scrubField(field, values);
|
||||
const own = field.store ? state.values[field.store] : values;
|
||||
const row = field.pill ? pillField(field, own) : scrubField(field, own);
|
||||
rows.push({ row, spec: field });
|
||||
fields.append(row);
|
||||
}
|
||||
@@ -810,7 +923,9 @@ function buildStrip(box, root, manager) {
|
||||
reset.addEventListener("click", () => {
|
||||
if (tab.group === "model") {
|
||||
const model = modelOf(manager);
|
||||
if (model) { writeModelTurn(model, { spin: 0, tip: 0, lean: 0 }); redraw(manager); }
|
||||
if (model) writeModelTurn(model, { spin: 0, tip: 0, lean: 0 });
|
||||
state.values.cut = { ...CUT_DEFAULTS };
|
||||
changed();
|
||||
show(tab);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -19,6 +19,7 @@ import { mountWidgetCard } from "../shared/widget_card.mjs";
|
||||
import { FONT_UI, THEME } from "../shared/theme.mjs";
|
||||
import { SOCKETLESS_CHOICE, SOCKETLESS_TEXT, commitWidgetValue, markSocketless, resetUnknownValues } from "../shared/widget_card_math.mjs";
|
||||
import { mediaViewQuery } from "../shared/media_list.mjs";
|
||||
import { readsFill, readsFit } from "../shared/image_resize_rows.mjs";
|
||||
import { gearIconSvg, openSettingsMenu } from "../shared/settings_menu.mjs";
|
||||
import { SEAM_MENU, SEAM_MUTE_TITLES, isBlendIn, seamCornerReserve } from "../shared/stitch_seam.mjs";
|
||||
import { NUMBER_LOOK_MENU, TEXT_LOOK_MENU, setTextLook, textLook, textLookCornerReserve } from "../shared/text_look.mjs";
|
||||
@@ -77,6 +78,24 @@ function seamCorner(node, card) {
|
||||
},
|
||||
};
|
||||
}
|
||||
// Color Match: one line under Method that says what the picked method does,
|
||||
// so the short pill names need no trip to the tooltip.
|
||||
const COLOR_MATCH_METHOD_HINTS = {
|
||||
lab: "Moves the colours to match. The safe default.",
|
||||
rgb: "The same as lab, in plain red, green and blue.",
|
||||
mkl: "For colours that are turned, not just shifted.",
|
||||
histogram: "An exact match. The strongest, least subtle.",
|
||||
kept: "For an edit: wire the picture from before the edit as reference.",
|
||||
};
|
||||
function colorMatchMethodHint() {
|
||||
const element = document.createElement("div");
|
||||
element.style.cssText = "display:flex;align-items:center;height:100%;padding:0 2px;box-sizing:border-box;"
|
||||
+ `color:${THEME.faint};font:11px/14px ${FONT_UI};`;
|
||||
return {
|
||||
element,
|
||||
sync: (values) => { element.textContent = COLOR_MATCH_METHOD_HINTS[values.method] ?? ""; },
|
||||
};
|
||||
}
|
||||
// Text, Integer and Float: the gear in the card's corner picks the node's
|
||||
// look, the usual box or big and centred (shared/text_look.mjs). The look is
|
||||
// kept on the node, not in a widget, so the node's inputs and saved values
|
||||
@@ -120,8 +139,8 @@ const CARDS = {
|
||||
{ widget: "edge_length", label: "Edge", suffix: "px", when: isMode("target_mode", "longest_edge", "shortest_edge") },
|
||||
{ widget: "megapixels", label: "Budget", suffix: "MP", when: isMode("target_mode", "megapixels") },
|
||||
{ widget: "scale_factor", label: "Scale", suffix: "×", when: isMode("target_mode", "scale_factor") },
|
||||
{ widget: "keep_proportion", label: "Fit", kind: "segment", labels: { cover_crop: "cover" } },
|
||||
{ widget: "fill_color", label: "Fill", kind: "color", when: isMode("keep_proportion", "pad") },
|
||||
{ widget: "keep_proportion", label: "Fit", kind: "segment", labels: { cover_crop: "cover" }, when: readsFit },
|
||||
{ widget: "fill_color", label: "Fill", kind: "color", when: readsFill },
|
||||
{ widget: "divisible_by", label: "Multiple" },
|
||||
{ widget: "interpolation", label: "Filter", kind: "select" },
|
||||
],
|
||||
@@ -130,12 +149,29 @@ const CARDS = {
|
||||
// its own rows show only while it is picked.
|
||||
AUSBOSS_NODES_ImageToolbox: {
|
||||
minWidth: 280,
|
||||
resetUnknown: { width: 512, height: 512, position: "top left", move_right: 0, move_down: 0 },
|
||||
rows: [
|
||||
{ widget: "job", label: "Job", kind: "select" },
|
||||
{ widget: "pieces", label: "Pieces", when: isMode("job", "split sheet at gaps") },
|
||||
{ widget: "width", label: "Width", suffix: "px", when: isMode("job", "cut a piece") },
|
||||
{ widget: "height", label: "Height", suffix: "px", when: isMode("job", "cut a piece") },
|
||||
{ widget: "position", label: "Position", kind: "select", when: isMode("job", "cut a piece") },
|
||||
{ widget: "move_right", label: "Move right", suffix: "px", when: isMode("job", "cut a piece") },
|
||||
{ widget: "move_down", label: "Move down", suffix: "px", when: isMode("job", "cut a piece") },
|
||||
],
|
||||
},
|
||||
AUSBOSS_NODES_PauseShot: { minWidth: 260, first: true, hide: ["view"], socketless: ["view"], rows: [
|
||||
{ widget: "pause", label: "Pause", onText: "wait for me", offText: "run through" },
|
||||
] },
|
||||
AUSBOSS_NODES_PhotoCamera: {
|
||||
minWidth: 260,
|
||||
rows: [
|
||||
{ widget: "fov", label: "Lens", suffix: "°", step: 1, decimals: 1, title: "How wide the photo is, in degrees across. Wire Get FoV from MoGe here." },
|
||||
{ group: "advanced", label: "More" },
|
||||
{ widget: "pad_factor", label: "Crop margin", suffix: "×", step: 0.05, decimals: 2, group: "advanced" },
|
||||
{ widget: "canvas_width", label: "360 width", suffix: "px", step: 256, snap: true, group: "advanced" },
|
||||
],
|
||||
},
|
||||
AUSBOSS_NODES_PauseShot: { minWidth: 260, first: true, rows: [{ widget: "pause", label: "Pause", onText: "wait for me", offText: "run through" }] },
|
||||
AUSBOSS_NODES_EditLock: {
|
||||
minWidth: 300,
|
||||
rows: [
|
||||
@@ -156,6 +192,7 @@ const CARDS = {
|
||||
rows: [
|
||||
{ widget: "strength", label: "Strength" },
|
||||
{ widget: "method", label: "Method", kind: "segment", labels: { histogram: "hist" }, titles: { histogram: "histogram" } },
|
||||
{ panel: colorMatchMethodHint, height: 28 },
|
||||
{ widget: "reference_mode", label: "Reference", kind: "segment", labels: { reference: "reference", first_frame: "first frame" } },
|
||||
{ widget: "invert_mask", label: "Invert mask" },
|
||||
],
|
||||
|
||||
@@ -48,7 +48,7 @@
|
||||
},
|
||||
"AUSBOSS_NODES_ColorMatch": {
|
||||
"display_name": "颜色匹配 🆎",
|
||||
"description": "把参考图的颜色统计转移到输入图上,用来修正局部重绘或拼回区域的色差。四种方法:lab 和 rgb 按通道调整均值和标准差,mkl 映射完整的颜色协方差,histogram 让每个通道的分布完全一致。可选的 mask 把测量和校正都限制在白色区域(invert_mask 反转),所以节点接收遮罩但不输出遮罩:遮罩只决定修正范围,在你的图中原样通过。strength 在原图和完全匹配的结果之间混合。视频用 reference_mode:first_frame 让每一帧都匹配批次自己的第一帧,不需要参考图也能减少帧间色彩漂移;它不会稳定画面运动。",
|
||||
"description": "把参考图的颜色统计转移到输入图上,用来修正局部重绘或拼回区域的色差。五种方法:lab 和 rgb 按通道调整均值和标准差,mkl 映射完整的颜色协方差,histogram 让每个通道的分布完全一致,kept 用于编辑:从模型本该保留的部分学出它带来的偏移并整体撤销,新内容保留自己的颜色。可选的 mask 把测量和校正都限制在白色区域(invert_mask 反转),所以节点接收遮罩但不输出遮罩:遮罩只决定修正范围,在你的图中原样通过。strength 在原图和完全匹配的结果之间混合。视频用 reference_mode:first_frame 让每一帧都匹配批次自己的第一帧,不需要参考图也能减少帧间色彩漂移;它不会稳定画面运动。",
|
||||
"inputs": {
|
||||
"image": {
|
||||
"name": "图像"
|
||||
@@ -644,7 +644,7 @@
|
||||
},
|
||||
"AUSBOSS_NODES_ImageToolbox": {
|
||||
"display_name": "图像工具箱 🆎",
|
||||
"description": "把几个小的图像任务放在一个节点里:从列表里选任务。split sheet at gaps 会把一排并列的图(比如角色设定图的四个视角)切成单独的图。每一刀都切在两张图之间的空隙,而不是按宽度平均切,所以不会有哪一张带上邻图的一部分。切好的图作为一个批次输出,尺寸相同,用设定图的背景色补齐。",
|
||||
"description": "把几个小的图像任务放在一个节点里:从列表里选任务。split sheet at gaps 会把一排并列的图(比如角色设定图的四个视角)切成单独的图。每一刀都切在两张图之间的空隙,而不是按宽度平均切,所以不会有哪一张带上邻图的一部分。切好的图作为一个批次输出,尺寸相同,用设定图的背景色补齐。cut a piece 按你设定的宽度和高度,在你选的位置裁出一块,同时给出图的其余部分。",
|
||||
"inputs": {
|
||||
"image": {
|
||||
"name": "图像"
|
||||
@@ -654,11 +654,29 @@
|
||||
},
|
||||
"pieces": {
|
||||
"name": "份数"
|
||||
},
|
||||
"width": {
|
||||
"name": "宽度"
|
||||
},
|
||||
"height": {
|
||||
"name": "高度"
|
||||
},
|
||||
"position": {
|
||||
"name": "位置"
|
||||
},
|
||||
"move_right": {
|
||||
"name": "右移"
|
||||
},
|
||||
"move_down": {
|
||||
"name": "下移"
|
||||
}
|
||||
},
|
||||
"outputs": {
|
||||
"0": {
|
||||
"name": "图像"
|
||||
},
|
||||
"1": {
|
||||
"name": "其余部分"
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -795,6 +813,9 @@
|
||||
},
|
||||
"4": {
|
||||
"name": "H3 提示词"
|
||||
},
|
||||
"5": {
|
||||
"name": "位置描述"
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -2003,6 +2024,12 @@
|
||||
},
|
||||
"panorama": {
|
||||
"name": "360 全景"
|
||||
},
|
||||
"mesh": {
|
||||
"name": "网格"
|
||||
},
|
||||
"view": {
|
||||
"name": "查看器设置"
|
||||
}
|
||||
},
|
||||
"outputs": {
|
||||
@@ -2020,6 +2047,47 @@
|
||||
},
|
||||
"4": {
|
||||
"name": "背景"
|
||||
},
|
||||
"5": {
|
||||
"name": "网格"
|
||||
}
|
||||
}
|
||||
},
|
||||
"AUSBOSS_NODES_PhotoCamera": {
|
||||
"display_name": "照片相机 🆎",
|
||||
"description": "算出拍这张照片的相机,让人物的 3D 模型和照片对齐。接入照片、人物遮罩和照片的视角宽度(MoGe 的“获取视角”可测出)。crop_fov 接到 Pixal3D 条件,camera_info 接到 3D 查看器,查看器就会从照片本身的视角打开;三个位置数字决定照片放在 360 画布的哪里,让 360 在模型后面对齐。",
|
||||
"inputs": {
|
||||
"image": {
|
||||
"name": "照片"
|
||||
},
|
||||
"mask": {
|
||||
"name": "遮罩"
|
||||
},
|
||||
"fov": {
|
||||
"name": "视角"
|
||||
},
|
||||
"pad_factor": {
|
||||
"name": "裁剪边距"
|
||||
},
|
||||
"canvas_width": {
|
||||
"name": "360 宽度"
|
||||
}
|
||||
},
|
||||
"outputs": {
|
||||
"0": {
|
||||
"name": "裁剪视角"
|
||||
},
|
||||
"1": {
|
||||
"name": "相机"
|
||||
},
|
||||
"2": {
|
||||
"name": "照片宽度"
|
||||
},
|
||||
"3": {
|
||||
"name": "照片左边"
|
||||
},
|
||||
"4": {
|
||||
"name": "照片上边"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,327 @@
|
||||
"""The Civitai line: an A1111-style ``parameters`` text for Save Image 🆎.
|
||||
|
||||
civitai.com reads a ComfyUI picture's prompt out of the embedded graph, and
|
||||
only for the nodes it knows: a prompt typed into a node it does not know
|
||||
(Krea 2 Encode 🆎, core's Qwen Image 2.1 encoder, a prompt inside a
|
||||
subgraph) reads as no prompt at all, and the upload is flagged "Unable to
|
||||
Verify AI Generation". It also never matches a ComfyUI picture's models,
|
||||
because it matches models by file hash and the graph holds only file names.
|
||||
|
||||
This module writes the line A1111 puts in its pictures, which Civitai reads
|
||||
first: the prompt, the sampler settings, and the model and LoRA hashes
|
||||
(AutoV2, the first ten hex digits of the file's SHA256). It is built from the
|
||||
run's own graph (the hidden PROMPT input), walking up from the save node, so
|
||||
a second sampler on another branch is not mistaken for this picture's.
|
||||
|
||||
Everything here is best effort and never raises into a save: a graph it
|
||||
cannot read gives no line, and the file saves as it always did.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Any, Callable
|
||||
|
||||
# How far a walk follows links before it gives up (cycles, odd graphs).
|
||||
MAX_DEPTH = 40
|
||||
|
||||
# Inputs that hold a prompt's words, in the order they are tried.
|
||||
TEXT_KEYS = ("text", "prompt", "populated_text", "text_g", "string", "value")
|
||||
# Inputs that pass conditioning through from an earlier node.
|
||||
CONDITIONING_KEYS = ("conditioning", "conditioning_1", "conditioning_to", "cond", "positive")
|
||||
|
||||
# Which model folder each loader input names a file in. Text encoders, VAEs
|
||||
# and the like are left out: Civitai never credits a picture to one.
|
||||
MODEL_KEYS = {
|
||||
"ckpt_name": ("checkpoints",),
|
||||
"unet_name": ("diffusion_models", "unet_gguf"),
|
||||
}
|
||||
LORA_FOLDERS = ("loras",)
|
||||
|
||||
LORA_LOADER = "AUSBOSS_NODES_LoraLoader"
|
||||
|
||||
|
||||
def _is_link(value: Any) -> bool:
|
||||
return (
|
||||
isinstance(value, list) and len(value) == 2
|
||||
and isinstance(value[0], (str, int)) and isinstance(value[1], int)
|
||||
)
|
||||
|
||||
|
||||
class _Graph:
|
||||
def __init__(self, prompt: dict):
|
||||
self.nodes = {str(key): node for key, node in prompt.items() if isinstance(node, dict)}
|
||||
|
||||
def node(self, link) -> dict | None:
|
||||
return self.nodes.get(str(link[0])) if _is_link(link) else None
|
||||
|
||||
@staticmethod
|
||||
def inputs(node: dict | None) -> dict:
|
||||
values = (node or {}).get("inputs")
|
||||
return values if isinstance(values, dict) else {}
|
||||
|
||||
def upstream(self, start: str | None) -> list[str]:
|
||||
"""Node ids feeding ``start``, nearest first (breadth first)."""
|
||||
if start is None or str(start) not in self.nodes:
|
||||
return list(self.nodes)
|
||||
order: list[str] = []
|
||||
seen = {str(start)}
|
||||
queue = [str(start)]
|
||||
while queue:
|
||||
current = queue.pop(0)
|
||||
for value in self.inputs(self.nodes.get(current)).values():
|
||||
if _is_link(value) and str(value[0]) in self.nodes and str(value[0]) not in seen:
|
||||
seen.add(str(value[0]))
|
||||
order.append(str(value[0]))
|
||||
queue.append(str(value[0]))
|
||||
return order
|
||||
|
||||
def literal(self, value: Any, keys: tuple[str, ...], depth: int = 0):
|
||||
"""A typed value, or the value a linked primitive node holds."""
|
||||
if not _is_link(value):
|
||||
return value
|
||||
if depth > MAX_DEPTH:
|
||||
return None
|
||||
inputs = self.inputs(self.node(value))
|
||||
for key in keys:
|
||||
if key in inputs:
|
||||
return self.literal(inputs[key], keys, depth + 1)
|
||||
return None
|
||||
|
||||
def words(self, value: Any, depth: int = 0) -> str | None:
|
||||
"""The text a STRING input carries: typed, or from a text node."""
|
||||
if isinstance(value, str):
|
||||
return value
|
||||
if not _is_link(value) or depth > MAX_DEPTH:
|
||||
return None
|
||||
inputs = self.inputs(self.node(value))
|
||||
for key in TEXT_KEYS:
|
||||
if key in inputs:
|
||||
found = self.words(inputs[key], depth + 1)
|
||||
if found is not None:
|
||||
return found
|
||||
if "string_a" in inputs or "string_b" in inputs:
|
||||
parts = [self.words(inputs.get(key), depth + 1) for key in ("string_a", "string_b")]
|
||||
delimiter = inputs.get("delimiter") if isinstance(inputs.get("delimiter"), str) else ""
|
||||
return delimiter.join(part for part in parts if part)
|
||||
return None
|
||||
|
||||
def conditioning_text(self, link: Any, depth: int = 0) -> str | None:
|
||||
"""The prompt behind a CONDITIONING link, through encoders and the
|
||||
nodes that pass conditioning on (ControlNet, guidance, inpaint)."""
|
||||
node = self.node(link)
|
||||
if node is None or depth > MAX_DEPTH:
|
||||
return None
|
||||
inputs = self.inputs(node)
|
||||
slot = link[1]
|
||||
# An encoder with both prompts (Krea 2 Encode 🆎, Qwen Image 2.1):
|
||||
# its second output is the negative.
|
||||
if "negative_prompt" in inputs and slot == 1:
|
||||
return self.words(inputs["negative_prompt"])
|
||||
for key in TEXT_KEYS[:4]:
|
||||
if key in inputs:
|
||||
found = self.words(inputs[key])
|
||||
if found is not None:
|
||||
return found
|
||||
# A node that takes and returns a positive/negative pair.
|
||||
if _is_link(inputs.get("positive")) and _is_link(inputs.get("negative")):
|
||||
return self.conditioning_text(inputs["negative" if slot == 1 else "positive"], depth + 1)
|
||||
for key in CONDITIONING_KEYS:
|
||||
if _is_link(inputs.get(key)):
|
||||
return self.conditioning_text(inputs[key], depth + 1)
|
||||
return None
|
||||
|
||||
|
||||
def _sampler(graph: _Graph, order: list[str]) -> dict | None:
|
||||
"""The settings of the nearest sampler upstream of the save node."""
|
||||
for node_id in order:
|
||||
node = graph.nodes[node_id]
|
||||
inputs = graph.inputs(node)
|
||||
settings: dict[str, Any] = {}
|
||||
if "positive" in inputs and "negative" in inputs and ("steps" in inputs or "sigmas" in inputs):
|
||||
# KSampler, KSamplerAdvanced, SamplerCustom and look-alikes.
|
||||
positive, negative = inputs["positive"], inputs["negative"]
|
||||
settings["seed"] = graph.literal(inputs.get("seed", inputs.get("noise_seed")), ("seed", "noise_seed", "value", "int"))
|
||||
settings["cfg"] = graph.literal(inputs.get("cfg"), ("cfg", "value", "float"))
|
||||
settings["sampler"] = graph.literal(inputs.get("sampler_name"), ("sampler_name", "value"))
|
||||
settings["scheduler"] = graph.literal(inputs.get("scheduler"), ("scheduler", "value"))
|
||||
settings["steps"] = graph.literal(inputs.get("steps"), ("steps", "value", "int"))
|
||||
settings["denoise"] = graph.literal(inputs.get("denoise"), ("denoise", "value", "float"))
|
||||
sampler_link, sigmas_link = inputs.get("sampler"), inputs.get("sigmas")
|
||||
model_link = inputs.get("model")
|
||||
elif "guider" in inputs and ("sigmas" in inputs or "noise" in inputs):
|
||||
# SamplerCustomAdvanced: the settings sit on the nodes it takes.
|
||||
guider = graph.inputs(graph.node(inputs["guider"]))
|
||||
if "positive" in guider:
|
||||
positive, negative = guider.get("positive"), guider.get("negative")
|
||||
else:
|
||||
positive, negative = guider.get("conditioning"), None
|
||||
settings["cfg"] = graph.literal(guider.get("cfg"), ("cfg", "value", "float"))
|
||||
noise = graph.inputs(graph.node(inputs.get("noise")))
|
||||
settings["seed"] = graph.literal(noise.get("noise_seed", noise.get("seed")), ("noise_seed", "seed", "value", "int"))
|
||||
sampler_link, sigmas_link = inputs.get("sampler"), inputs.get("sigmas")
|
||||
model_link = guider.get("model")
|
||||
else:
|
||||
continue
|
||||
sampler_inputs = graph.inputs(graph.node(sampler_link))
|
||||
if settings.get("sampler") is None and "sampler_name" in sampler_inputs:
|
||||
settings["sampler"] = graph.literal(sampler_inputs["sampler_name"], ("sampler_name", "value"))
|
||||
sigmas = graph.inputs(graph.node(sigmas_link))
|
||||
for key in ("steps", "scheduler", "denoise"):
|
||||
if settings.get(key) is None and key in sigmas:
|
||||
settings[key] = graph.literal(sigmas[key], (key, "value"))
|
||||
settings["positive"] = graph.conditioning_text(positive) or ""
|
||||
settings["negative"] = graph.conditioning_text(negative) or ""
|
||||
settings["model_link"] = model_link
|
||||
settings["latent_link"] = inputs.get("latent_image")
|
||||
return settings
|
||||
return None
|
||||
|
||||
|
||||
def _lora_rows(graph: _Graph, node: dict) -> list[tuple[str, Any]]:
|
||||
"""(file name, strength) of every LoRA a loader node applies."""
|
||||
inputs = graph.inputs(node)
|
||||
rows: list[tuple[str, Any]] = []
|
||||
if node.get("class_type") == LORA_LOADER and isinstance(inputs.get("loras"), str):
|
||||
try:
|
||||
from ._lora_helpers import parse_lora_stack
|
||||
|
||||
for row in parse_lora_stack(inputs["loras"]):
|
||||
if row["enabled"] and row["strength"]:
|
||||
rows.append((row["name"], row["strength"]))
|
||||
except Exception:
|
||||
pass
|
||||
return rows
|
||||
if isinstance(inputs.get("lora_name"), str):
|
||||
strength = graph.literal(inputs.get("strength_model", inputs.get("strength", 1.0)), ("value", "float"))
|
||||
if strength != 0:
|
||||
rows.append((inputs["lora_name"], strength))
|
||||
# Stack loaders that keep one entry per row: {"on", "lora", "strength"}.
|
||||
for value in inputs.values():
|
||||
if isinstance(value, dict) and isinstance(value.get("lora"), str) and value.get("on", True):
|
||||
if value.get("strength", 1.0) != 0:
|
||||
rows.append((value["lora"], value.get("strength", 1.0)))
|
||||
return [(name, strength) for name, strength in rows if name and name.lower() != "none"]
|
||||
|
||||
|
||||
def _starts_from_a_picture(graph: _Graph, latent_link: Any, denoise: Any) -> bool:
|
||||
"""True when the sampler reworks an existing picture rather than noise."""
|
||||
if isinstance(denoise, (int, float)) and denoise < 1:
|
||||
return True
|
||||
start = graph.node(latent_link)
|
||||
if start is None:
|
||||
return False
|
||||
first = str(latent_link[0])
|
||||
for node_id in [first] + graph.upstream(first):
|
||||
kind = str(graph.nodes[node_id].get("class_type", ""))
|
||||
if "VAEEncode" in kind or "Inpaint" in kind:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _short_name(name: str) -> str:
|
||||
return Path(str(name).replace("\\", "/")).stem
|
||||
|
||||
|
||||
def _quote(value: str) -> str:
|
||||
"""An A1111 value: quoted when a comma, colon or quote would split it."""
|
||||
return json.dumps(value) if any(mark in value for mark in ',:"\n') else value
|
||||
|
||||
|
||||
def civitai_parameters(
|
||||
prompt: dict | None,
|
||||
save_node_id: str | None,
|
||||
width: int,
|
||||
height: int,
|
||||
find_file: Callable[[tuple[str, ...], str], Path | None],
|
||||
file_hash: Callable[[Path], str],
|
||||
) -> str | None:
|
||||
"""The A1111-style line for one save, or None when the graph holds no
|
||||
sampler to describe. ``find_file(folders, name)`` resolves a model file;
|
||||
``file_hash(path)`` returns its SHA256 (cached by the caller)."""
|
||||
if not isinstance(prompt, dict):
|
||||
return None
|
||||
try:
|
||||
graph = _Graph(prompt)
|
||||
order = graph.upstream(save_node_id)
|
||||
settings = _sampler(graph, order)
|
||||
if settings is None or settings.get("steps") is None:
|
||||
return None
|
||||
|
||||
def autov2(folders, name) -> str | None:
|
||||
try:
|
||||
path = find_file(folders, name)
|
||||
return file_hash(path)[:10] if path is not None else None
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
# Models and LoRAs are looked for up the sampler's model input, so a
|
||||
# loader that only feeds another branch (a mask model, an upscaler
|
||||
# pass) is not credited; a graph without that link falls back to
|
||||
# everything upstream of the save.
|
||||
model_node = graph.node(settings["model_link"])
|
||||
model_order = order
|
||||
if model_node is not None:
|
||||
start = str(settings["model_link"][0])
|
||||
model_order = [start] + graph.upstream(start)
|
||||
model_name = model_hash = None
|
||||
loras: list[tuple[str, Any, str]] = []
|
||||
seen_loras: set[str] = set()
|
||||
for node_id in model_order:
|
||||
node = graph.nodes[node_id]
|
||||
inputs = graph.inputs(node)
|
||||
if model_name is None:
|
||||
for key, folders in MODEL_KEYS.items():
|
||||
name = inputs.get(key)
|
||||
if isinstance(name, str) and name:
|
||||
model_name, model_hash = name, autov2(folders, name)
|
||||
break
|
||||
for name, strength in _lora_rows(graph, node):
|
||||
if name in seen_loras:
|
||||
continue
|
||||
seen_loras.add(name)
|
||||
found = autov2(LORA_FOLDERS, name)
|
||||
if found:
|
||||
loras.append((name, strength, found))
|
||||
|
||||
if not settings["positive"].strip() and not model_hash and not loras:
|
||||
return None
|
||||
lines = [settings["positive"].strip()]
|
||||
if settings["negative"].strip():
|
||||
lines.append("Negative prompt: " + settings["negative"].strip())
|
||||
details = [f"Steps: {settings['steps']}"]
|
||||
for label, key in (("Sampler", "sampler"), ("Schedule type", "scheduler"), ("CFG scale", "cfg"), ("Seed", "seed")):
|
||||
value = settings.get(key)
|
||||
if value is not None and not _is_link(value):
|
||||
details.append(f"{label}: {_quote(str(value))}")
|
||||
details.append(f"Size: {int(width)}x{int(height)}")
|
||||
hashes: dict[str, str] = {}
|
||||
if model_name:
|
||||
if model_hash:
|
||||
details.append(f"Model hash: {model_hash}")
|
||||
hashes["model"] = model_hash
|
||||
details.append(f"Model: {_quote(_short_name(model_name))}")
|
||||
denoise = settings.get("denoise")
|
||||
if isinstance(denoise, (int, float)) and denoise < 1:
|
||||
details.append(f"Denoising strength: {denoise}")
|
||||
if loras:
|
||||
listed = ", ".join(f"{_short_name(name)}: {digest}" for name, _strength, digest in loras)
|
||||
details.append(f"Lora hashes: {json.dumps(listed)}")
|
||||
for name, _strength, digest in loras:
|
||||
hashes[f"lora:{_short_name(name)}"] = digest
|
||||
if hashes:
|
||||
details.append("Hashes: " + json.dumps(hashes, separators=(",", ":")))
|
||||
details.append("Version: ComfyUI")
|
||||
# Lower-case keys Civitai keeps as they are: "engine" tags the post
|
||||
# with the ComfyUI tool, "process" picks its technique.
|
||||
details.append("engine: ComfyUI")
|
||||
img2img = _starts_from_a_picture(graph, settings.get("latent_link"), denoise)
|
||||
details.append("process: " + ("img2img" if img2img else "txt2img"))
|
||||
lines.append(", ".join(details))
|
||||
return "\n".join(lines)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
__all__ = ["civitai_parameters"]
|
||||
+96
-4
@@ -154,8 +154,9 @@ def lab_to_rgb(lab: torch.Tensor) -> torch.Tensor:
|
||||
# Method names are the node's combo values. All are textbook constructions
|
||||
# implemented here from the math: per-channel mean/std transfer in LAB or RGB,
|
||||
# the closed-form Monge-Kantorovich linear covariance mapping, and per-channel
|
||||
# histogram (quantile) matching.
|
||||
COLOR_MATCH_METHODS = ("lab", "rgb", "mkl", "histogram")
|
||||
# histogram (quantile) matching. "kept" is the pack's own: a robust fit on
|
||||
# the pixels an edit left alone (see _kept_matched).
|
||||
COLOR_MATCH_METHODS = ("lab", "rgb", "mkl", "histogram", "kept")
|
||||
|
||||
|
||||
def _weighted_lab_stats(
|
||||
@@ -294,6 +295,94 @@ def _histogram_matched(
|
||||
return torch.stack(frames, dim=0).clamp(0.0, 1.0)
|
||||
|
||||
|
||||
# A kept-pixel fit never moves contrast or saturation further than this; a
|
||||
# larger number means the fit read new content as kept, not a real drift.
|
||||
_KEPT_GAIN = {"lightness": (0.7, 1.3), "chroma": (0.6, 1.3)}
|
||||
_KEPT_SAMPLES = 200_000
|
||||
|
||||
|
||||
def _kept_fit(source: torch.Tensor, target: torch.Tensor, keep: float = 0.6, rounds: int = 4):
|
||||
"""Robust tone fit, N x 3 LAB source onto N x 3 LAB target.
|
||||
|
||||
Fits lightness gain and offset, one chroma gain about the source's mean
|
||||
colour, and an a/b offset. Each round keeps the best-fitting share
|
||||
(``keep``) of the pixels and fits again, so content the edit changed
|
||||
falls out as outliers and only the pixels it kept decide the fit.
|
||||
"""
|
||||
chosen = torch.ones(source.shape[0], dtype=torch.bool, device=source.device)
|
||||
params = (1.0, 0.0, 1.0, torch.zeros(2, dtype=source.dtype, device=source.device),
|
||||
source[:, 1:].mean(0))
|
||||
for _ in range(rounds):
|
||||
s, t = source[chosen], target[chosen]
|
||||
if s.shape[0] < 16:
|
||||
break
|
||||
sl, tl = s[:, 0], t[:, 0]
|
||||
sl_mean, tl_mean = sl.mean(), tl.mean()
|
||||
var = ((sl - sl_mean) ** 2).sum()
|
||||
gain_l = float(((sl - sl_mean) * (tl - tl_mean)).sum() / var) if var > 1e-6 else 1.0
|
||||
gain_l = min(max(gain_l, _KEPT_GAIN["lightness"][0]), _KEPT_GAIN["lightness"][1])
|
||||
offset_l = float(tl_mean - gain_l * sl_mean)
|
||||
centre = s[:, 1:].mean(0)
|
||||
sc, tc = s[:, 1:] - centre, t[:, 1:] - t[:, 1:].mean(0)
|
||||
cvar = (sc * sc).sum()
|
||||
gain_c = float((sc * tc).sum() / cvar) if cvar > 1e-6 else 1.0
|
||||
gain_c = min(max(gain_c, _KEPT_GAIN["chroma"][0]), _KEPT_GAIN["chroma"][1])
|
||||
tint = (t[:, 1:] - s[:, 1:]).mean(0)
|
||||
params = (gain_l, offset_l, gain_c, tint, centre)
|
||||
residual = (_kept_apply(source, params) - target).norm(dim=-1)
|
||||
limit = torch.quantile(residual[chosen], keep)
|
||||
chosen = chosen & (residual <= limit)
|
||||
return params
|
||||
|
||||
|
||||
def _kept_apply(lab: torch.Tensor, params) -> torch.Tensor:
|
||||
gain_l, offset_l, gain_c, tint, centre = params
|
||||
lightness = lab[..., :1] * gain_l + offset_l
|
||||
colour = (lab[..., 1:] - centre) * gain_c + centre + tint
|
||||
return torch.cat([lightness, colour], dim=-1)
|
||||
|
||||
|
||||
def _kept_matched(
|
||||
rgb: torch.Tensor, reference: torch.Tensor, mask: torch.Tensor | None
|
||||
) -> torch.Tensor:
|
||||
"""Undo an edit's tone drift, learned from the pixels the edit kept.
|
||||
|
||||
The reference is the same picture before the edit, pixel for pixel. An
|
||||
edit model often hands back the parts it was asked to keep a little
|
||||
darker, with more contrast and colour. Measured on those kept parts
|
||||
(inside the mask, if one is given), the drift is a lightness gain and
|
||||
offset, a saturation gain and a tint; undoing it everywhere brings the
|
||||
new content into the same tone without pulling its own colours toward
|
||||
what used to be there.
|
||||
"""
|
||||
if reference.shape[1:3] != rgb.shape[1:3]:
|
||||
raise ValueError(
|
||||
"Color Match kept needs the picture from before the edit, at the same "
|
||||
f"size: the image is {rgb.shape[2]}x{rgb.shape[1]}, the reference "
|
||||
f"{reference.shape[2]}x{reference.shape[1]}."
|
||||
)
|
||||
frames = []
|
||||
for index in range(rgb.shape[0]):
|
||||
lab = rgb_to_lab(rgb[index : index + 1])[0]
|
||||
pick = index if reference.shape[0] > 1 else 0
|
||||
ref = rgb_to_lab(reference[pick : pick + 1])[0]
|
||||
source, target = lab.reshape(-1, 3), ref.reshape(-1, 3)
|
||||
if mask is not None:
|
||||
region = mask[index if mask.shape[0] > 1 else 0].reshape(-1) > 0.5
|
||||
source, target = source[region], target[region]
|
||||
if source.shape[0] < 64:
|
||||
frames.append(rgb[index])
|
||||
continue
|
||||
if source.shape[0] > _KEPT_SAMPLES:
|
||||
# An even spread of pixels: the same answer every run.
|
||||
step = source.shape[0] // _KEPT_SAMPLES + 1
|
||||
source, target = source[::step], target[::step]
|
||||
params = _kept_fit(source.double(), target.double())
|
||||
params = tuple(p.to(lab.dtype) if isinstance(p, torch.Tensor) else p for p in params)
|
||||
frames.append(lab_to_rgb(_kept_apply(lab, params).unsqueeze(0))[0])
|
||||
return torch.stack(frames, dim=0)
|
||||
|
||||
|
||||
def match_colors(
|
||||
image: torch.Tensor,
|
||||
reference: torch.Tensor,
|
||||
@@ -307,8 +396,9 @@ def match_colors(
|
||||
``method`` picks the construction: "lab" and "rgb" move per-channel
|
||||
mean/std in that space, "mkl" maps the full RGB covariance through the
|
||||
Monge-Kantorovich linear transform, "histogram" matches each channel's
|
||||
quantiles exactly. With a mask, both the measured statistics and the
|
||||
applied correction are restricted to the white region (``invert_mask``
|
||||
quantiles exactly, "kept" undoes an edit's tone drift learned from the
|
||||
pixels it kept (the reference is the picture before the edit). With a
|
||||
mask, both the measured statistics and the applied correction are restricted to the white region (``invert_mask``
|
||||
flips which side that is); pixels where the mask is zero are returned
|
||||
bit-identical. ``strength`` lerps between the original (0) and the
|
||||
fully matched image (1). A batch-1 reference broadcasts across an
|
||||
@@ -360,6 +450,8 @@ def match_colors(
|
||||
matched = _mkl_matched(rgb, ref_rgb, mask)
|
||||
elif method == "histogram":
|
||||
matched = _histogram_matched(rgb, ref_rgb, mask)
|
||||
elif method == "kept":
|
||||
matched = _kept_matched(rgb, ref_rgb, mask)
|
||||
else:
|
||||
matched = _stats_matched(rgb, ref_rgb, mask, in_lab=method == "lab")
|
||||
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
"""Cut a piece of a chosen size out of a picture.
|
||||
|
||||
The piece's place is a position on the picture (a corner, an edge's middle
|
||||
or the centre) moved by an offset in pixels. The piece always stays inside
|
||||
the picture: a size larger than the picture is cut to the picture's size,
|
||||
and an offset that would push it past an edge stops at that edge.
|
||||
|
||||
Besides the piece, the job gives back the rest of the picture. When the
|
||||
piece takes a whole side (the full height against the left or right edge,
|
||||
or the full width against the top or bottom), the rest is the strip beside
|
||||
it, so one cut splits a picture into two parts of different sizes. Any
|
||||
other piece leaves a hole, and the rest is the whole picture with that
|
||||
hole filled with the picture's backdrop colour.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import torch
|
||||
|
||||
from ._sheet_split_helpers import backdrop_color
|
||||
|
||||
# Reading order, so the list reads like the picture: top row, middle, bottom.
|
||||
POSITIONS = (
|
||||
"top left",
|
||||
"top",
|
||||
"top right",
|
||||
"left",
|
||||
"center",
|
||||
"right",
|
||||
"bottom left",
|
||||
"bottom",
|
||||
"bottom right",
|
||||
)
|
||||
|
||||
|
||||
def piece_box(
|
||||
height: int,
|
||||
width: int,
|
||||
piece_width: int,
|
||||
piece_height: int,
|
||||
position: str = "top left",
|
||||
move_right: int = 0,
|
||||
move_down: int = 0,
|
||||
) -> tuple[int, int, int, int]:
|
||||
"""(top, left, bottom, right) of the piece, inside a height x width picture.
|
||||
|
||||
A piece width or height of 0 (or less) means the picture's full width or
|
||||
height; a larger one is cut to the picture.
|
||||
"""
|
||||
if position not in POSITIONS:
|
||||
raise ValueError(f"Cut a piece has no position named {position!r}.")
|
||||
piece_width = width if piece_width <= 0 else min(int(piece_width), width)
|
||||
piece_height = height if piece_height <= 0 else min(int(piece_height), height)
|
||||
if "left" in position:
|
||||
left = 0
|
||||
elif "right" in position:
|
||||
left = width - piece_width
|
||||
else:
|
||||
left = (width - piece_width) // 2
|
||||
if position.startswith("top"):
|
||||
top = 0
|
||||
elif position.startswith("bottom"):
|
||||
top = height - piece_height
|
||||
else:
|
||||
top = (height - piece_height) // 2
|
||||
left = max(0, min(width - piece_width, left + int(move_right)))
|
||||
top = max(0, min(height - piece_height, top + int(move_down)))
|
||||
return top, left, top + piece_height, left + piece_width
|
||||
|
||||
|
||||
def rest_of(image: torch.Tensor, box: tuple[int, int, int, int]) -> torch.Tensor:
|
||||
"""What is left of a BHWC batch once the piece in ``box`` is cut out."""
|
||||
top, left, bottom, right = box
|
||||
height, width = image.shape[1], image.shape[2]
|
||||
full_height = top == 0 and bottom == height
|
||||
full_width = left == 0 and right == width
|
||||
if full_height and not full_width:
|
||||
if left == 0:
|
||||
return image[:, :, right:].clone()
|
||||
if right == width:
|
||||
return image[:, :, :left].clone()
|
||||
if full_width and not full_height:
|
||||
if top == 0:
|
||||
return image[:, bottom:].clone()
|
||||
if bottom == height:
|
||||
return image[:, :top].clone()
|
||||
rest = image.clone()
|
||||
for index in range(rest.shape[0]):
|
||||
rest[index, top:bottom, left:right] = backdrop_color(image[index])
|
||||
return rest
|
||||
|
||||
|
||||
def cut_piece(
|
||||
image: torch.Tensor,
|
||||
piece_width: int,
|
||||
piece_height: int,
|
||||
position: str = "top left",
|
||||
move_right: int = 0,
|
||||
move_down: int = 0,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
"""The piece and the rest, for every picture of a BHWC batch at the same place."""
|
||||
box = piece_box(image.shape[1], image.shape[2], piece_width, piece_height, position, move_right, move_down)
|
||||
top, left, bottom, right = box
|
||||
return image[:, top:bottom, left:right].clone(), rest_of(image, box)
|
||||
@@ -285,6 +285,8 @@ class EditLock:
|
||||
self.wide: float | None = None # share of the picture the lock would free, at the decision
|
||||
self.top: float | None = None # the strongest spot then, in units of the quiet level
|
||||
self.peak: float | None = None # and the strongest hundredth
|
||||
self.vae_channels: int | None = None # when the VAE and model disagree: the picture's channels
|
||||
self.model_channels: int | None = None # and the channels the model predicts
|
||||
self._sigma: float | None = None
|
||||
self._first = True
|
||||
self._first_sigma = 1.0
|
||||
@@ -328,6 +330,7 @@ class EditLock:
|
||||
latent = self.latent[:, :, 0] if self.latent.ndim == 5 else self.latent
|
||||
if latent.shape[1] != flat.shape[1]:
|
||||
self.status = "vae"
|
||||
self.vae_channels, self.model_channels = int(latent.shape[1]), int(flat.shape[1])
|
||||
return pred
|
||||
source = fit_latent(latent.to(device=flat.device, dtype=torch.float32), *flat.shape[-2:])
|
||||
if source is None:
|
||||
@@ -451,5 +454,11 @@ def describe(lock: EditLock) -> str:
|
||||
if lock.status == "video":
|
||||
return "Edit Lock did nothing: it works on single pictures, not video."
|
||||
if lock.status == "vae":
|
||||
return "Edit Lock did nothing: this VAE does not belong to this model."
|
||||
counts = ""
|
||||
if lock.vae_channels is not None and lock.model_channels is not None:
|
||||
counts = (f" (your VAE makes {lock.vae_channels}-channel pictures, "
|
||||
f"the model expects {lock.model_channels})")
|
||||
return ("Edit Lock did nothing: the VAE and the diffusion model don't match"
|
||||
f"{counts}. Either file can be the wrong one. Use the model and VAE listed "
|
||||
"in the workflow's notes. A GGUF or other converted model is a common cause.")
|
||||
return "Edit Lock has not run yet: plug its model output into the sampler."
|
||||
|
||||
@@ -8,7 +8,6 @@ bottom and are the only functions that touch PIL.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
import secrets
|
||||
import threading
|
||||
@@ -313,19 +312,36 @@ def _png_info(metadata: dict | None):
|
||||
return info
|
||||
|
||||
|
||||
def _exif_bytes(metadata: dict | None) -> bytes | None:
|
||||
"""Workflow JSON in EXIF, mirroring core's animated-webp convention
|
||||
(prompt in Make, workflow and friends in ImageDescription). Shared by
|
||||
the WebP and JPEG XL encoders."""
|
||||
# EXIF tags of core ComfyUI's WebP layout: the prompt in Model, then the
|
||||
# workflow and any other key in Make, ImageDescription and on downwards.
|
||||
EXIF_MODEL = 0x0110
|
||||
EXIF_MAKE = 0x010F
|
||||
EXIF_IFD = 0x8769
|
||||
EXIF_USER_COMMENT = 0x9286
|
||||
|
||||
|
||||
def exif_bytes(metadata: dict | None) -> bytes | None:
|
||||
"""The workflow in EXIF, laid out exactly as core ComfyUI writes WebP:
|
||||
``prompt:<json>`` in Model, then ``workflow:<json>`` (and any other key)
|
||||
in Make, ImageDescription and downwards. ComfyUI's canvas reads each
|
||||
entry back as ``key:value``, and civitai.com finds a ComfyUI picture by
|
||||
the ``prompt:`` in Model. A ``parameters`` entry (the Civitai line) goes
|
||||
in UserComment instead, where A1111-style readers look for it.
|
||||
|
||||
Shared by Save Image's WebP and JPEG XL encoders and Save Video's
|
||||
animated WebP. Values arrive as the JSON text workflow_metadata made."""
|
||||
if not metadata:
|
||||
return None
|
||||
exif = Image.Exif()
|
||||
prompt = metadata.get("prompt")
|
||||
rest = dict(metadata)
|
||||
prompt = rest.pop("prompt", None)
|
||||
parameters = rest.pop("parameters", None)
|
||||
if prompt is not None:
|
||||
exif[0x010F] = "prompt:" + prompt
|
||||
rest = {key: value for key, value in metadata.items() if key != "prompt"}
|
||||
if rest:
|
||||
exif[0x010E] = json.dumps({key: json.loads(value) for key, value in rest.items()})
|
||||
exif[EXIF_MODEL] = "prompt:" + prompt
|
||||
for tag, (key, value) in zip(range(EXIF_MAKE, 0, -1), rest.items()):
|
||||
exif[tag] = f"{key}:{value}"
|
||||
if parameters:
|
||||
exif.get_ifd(EXIF_IFD)[EXIF_USER_COMMENT] = b"UNICODE\0" + str(parameters).encode("utf-16-be")
|
||||
return exif.tobytes()
|
||||
|
||||
|
||||
@@ -337,7 +353,7 @@ def encode_image(path: Path, frame: torch.Tensor, format_name: str, metadata: di
|
||||
return
|
||||
if format_name == "webp lossless":
|
||||
kwargs = {"format": "WEBP", "lossless": True, "quality": 100, "method": 4}
|
||||
exif = _exif_bytes(metadata)
|
||||
exif = exif_bytes(metadata)
|
||||
if exif is not None:
|
||||
kwargs["exif"] = exif
|
||||
image.save(path, **kwargs)
|
||||
@@ -349,7 +365,7 @@ def encode_image(path: Path, frame: torch.Tensor, format_name: str, metadata: di
|
||||
"(add the pillow-jxl-plugin package to ComfyUI's python)."
|
||||
)
|
||||
kwargs = {"format": "JXL", "lossless": True}
|
||||
exif = _exif_bytes(metadata)
|
||||
exif = exif_bytes(metadata)
|
||||
if exif is not None:
|
||||
kwargs["exif"] = exif
|
||||
try:
|
||||
@@ -375,6 +391,7 @@ __all__ = [
|
||||
"PREVIEW_FOLDER",
|
||||
"counter_pattern",
|
||||
"encode_image",
|
||||
"exif_bytes",
|
||||
"existing_action",
|
||||
"fill_name_tokens",
|
||||
"frame_to_pil",
|
||||
|
||||
@@ -496,6 +496,59 @@ def prompt_elements(regions: list[dict], shape: tuple[float, float] | None = Non
|
||||
return elements
|
||||
|
||||
|
||||
def _percent_extent(region: dict, shape: tuple[float, float]) -> tuple[int, int, int, int]:
|
||||
"""(left, top, right, bottom) of a box as whole percents of the canvas,
|
||||
cut to it. A turned box gives the straight box around it, as in
|
||||
`elements`."""
|
||||
if angle_of(region):
|
||||
left, top, right, bottom = _turned_extent(region, shape)
|
||||
else:
|
||||
x, y = region.get("x", 0.0), region.get("y", 0.0)
|
||||
w, h = region.get("w", 0.0), region.get("h", 0.0)
|
||||
left, right = sorted((x, x + w))
|
||||
top, bottom = sorted((y, y + h))
|
||||
return tuple(round(min(1.0, max(0.0, value)) * 100) for value in (left, top, right, bottom))
|
||||
|
||||
|
||||
def placement_words(left: int, top: int, right: int, bottom: int) -> str:
|
||||
"""Where a box is, from whole percents of the canvas: "top left, from 6%
|
||||
to 52% across and 6% to 25% down". Plain "center" for the middle."""
|
||||
vertical = "top" if bottom < 40 else "bottom" if top > 60 else "middle"
|
||||
horizontal = "left" if right < 55 else "right" if left > 45 else "center"
|
||||
where = "center" if (vertical, horizontal) == ("middle", "center") else f"{vertical} {horizontal}"
|
||||
return f"{where}, from {left}% to {right}% across and {top}% to {bottom}% down"
|
||||
|
||||
|
||||
def placement_prompt(regions: list[dict], shape: tuple[float, float] | None = None) -> str:
|
||||
"""The `placement` output: one sentence per box, in the boxes' order, that
|
||||
says what goes there and where, for a model that reads only a prompt.
|
||||
`shape` is the (width, height) of the canvas a turned box was turned on.
|
||||
A text box with words: 'The words "FRESH" in bold letters, placed top
|
||||
left, from ...'. Any other box: its description, placed where it is; a
|
||||
box with no words and no description is left out. No boxes give ""."""
|
||||
shape = shape or (1.0, 1.0)
|
||||
sentences = []
|
||||
for region in regions:
|
||||
if not isinstance(region, dict):
|
||||
continue
|
||||
desc = element_desc(region)
|
||||
desc = desc.strip().rstrip(".,;:").rstrip() if isinstance(desc, str) else ""
|
||||
text = region.get("text", "") if region.get("type") == "text" else ""
|
||||
text = text.strip() if isinstance(text, str) else ""
|
||||
where = placement_words(*_percent_extent(region, shape))
|
||||
if text:
|
||||
sentence = f'The words "{text}" in {desc}, placed {where}.' if desc else f'The words "{text}", placed {where}.'
|
||||
elif desc:
|
||||
sentence = f"{desc[:1].upper()}{desc[1:]}, placed {where}."
|
||||
else:
|
||||
continue
|
||||
colors = element_colors(region.get("palette", []))[:MAX_COLORS]
|
||||
if colors:
|
||||
sentence += f" Colors: {', '.join(colors)}."
|
||||
sentences.append(sentence)
|
||||
return " ".join(sentences)
|
||||
|
||||
|
||||
def canvas_boxes(regions: list[dict]) -> list[dict]:
|
||||
"""Boxes in the form the canvas keeps them, for the node's face."""
|
||||
keys = ("x", "y", "w", "h", "type", "text", "desc", "palette")
|
||||
@@ -745,6 +798,8 @@ __all__ = [
|
||||
"input_fingerprint",
|
||||
"mask_rects",
|
||||
"parse_layout",
|
||||
"placement_prompt",
|
||||
"placement_words",
|
||||
"prompt_elements",
|
||||
"read_angle",
|
||||
"regions_from_pixel_boxes",
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
"""Cut a model to a band of its own depth, as the camera sees it: the 3D
|
||||
viewer's Cut (js/viewer_pano, Cut tab) and Pause for Shot's mesh output.
|
||||
|
||||
Two planes face the camera. Front takes away that share of the model's
|
||||
depth from the side nearest the camera, Back from the far side, both in
|
||||
percent. "The model's depth" is how far its box reaches along the camera's
|
||||
view: the eight corners of the box around the model's own points (before the
|
||||
viewer moves, turns or sizes it), placed where the viewer shows the model.
|
||||
The viewer measures the same box, so its cut and this one meet at the same
|
||||
planes. This keeps the triangles whose middle lies between the planes; the
|
||||
viewer cuts at the exact plane, so the two edges agree to within a triangle.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
|
||||
import numpy as np
|
||||
|
||||
CUT_KEYS = ("front", "back")
|
||||
# At least this much of the model's depth stays, so a cut never empties it.
|
||||
MIN_KEEP = 1.0
|
||||
|
||||
|
||||
def clean_cut(value) -> dict | None:
|
||||
"""{"front": %, "back": %} from an answer or a saved viewer, or None when
|
||||
nothing is cut."""
|
||||
if not isinstance(value, dict):
|
||||
return None
|
||||
out = {}
|
||||
for key in CUT_KEYS:
|
||||
number = value.get(key)
|
||||
ok = isinstance(number, (int, float)) and not isinstance(number, bool) and math.isfinite(number)
|
||||
out[key] = min(100.0 - MIN_KEEP, max(0.0, float(number))) if ok else 0.0
|
||||
out["back"] = min(out["back"], 100.0 - MIN_KEEP - out["front"])
|
||||
return out if out["front"] > 0 or out["back"] > 0 else None
|
||||
|
||||
|
||||
def _vec(data, default=(0.0, 0.0, 0.0)) -> np.ndarray:
|
||||
out = list(default)
|
||||
if isinstance(data, dict):
|
||||
for i, key in enumerate("xyz"):
|
||||
value = data.get(key)
|
||||
if isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value):
|
||||
out[i] = float(value)
|
||||
return np.array(out, dtype=np.float64)
|
||||
|
||||
|
||||
def model_transform(model_3d_info):
|
||||
"""(scale, rotation, position) of the viewer's model, the way Render Mesh
|
||||
places it; None without one."""
|
||||
transform = model_3d_info[0] if isinstance(model_3d_info, list) and model_3d_info else model_3d_info
|
||||
if not isinstance(transform, dict) or not isinstance(transform.get("quaternion"), dict):
|
||||
return None
|
||||
q = transform["quaternion"]
|
||||
x, y, z, w = (float(q.get(k, 0.0) or 0.0) for k in "xyzw")
|
||||
rotation = np.array([
|
||||
[1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w)],
|
||||
[2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w)],
|
||||
[2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)],
|
||||
])
|
||||
return _vec(transform.get("scale"), (1.0, 1.0, 1.0)), rotation, _vec(transform.get("position"))
|
||||
|
||||
|
||||
def place(points: np.ndarray, transform) -> np.ndarray:
|
||||
if transform is None:
|
||||
return points
|
||||
scale, rotation, position = transform
|
||||
return (points * scale) @ rotation.T + position
|
||||
|
||||
|
||||
def camera_view(camera_info):
|
||||
"""(eye, forward) of a viewer camera; None without a usable one."""
|
||||
if not isinstance(camera_info, dict) or not isinstance(camera_info.get("position"), dict):
|
||||
return None
|
||||
eye = _vec(camera_info["position"])
|
||||
if isinstance(camera_info.get("target"), dict):
|
||||
forward = _vec(camera_info["target"]) - eye
|
||||
elif isinstance(camera_info.get("quaternion"), dict):
|
||||
_, rotation, _ = model_transform([{"quaternion": camera_info["quaternion"]}])
|
||||
forward = rotation @ np.array([0.0, 0.0, -1.0])
|
||||
else:
|
||||
return None
|
||||
norm = float(np.linalg.norm(forward))
|
||||
if norm < 1e-9:
|
||||
return None
|
||||
return eye, forward / norm
|
||||
|
||||
|
||||
def box_corners(points: np.ndarray) -> np.ndarray:
|
||||
lo, hi = points.min(0), points.max(0)
|
||||
return np.array([[(lo, hi)[i][0], (lo, hi)[j][1], (lo, hi)[k][2]] for i in (0, 1) for j in (0, 1) for k in (0, 1)])
|
||||
|
||||
|
||||
def cut_planes(points: np.ndarray, transform, view, cut: dict) -> tuple[float, float]:
|
||||
"""(near, far): the kept band, as distances along the camera's view."""
|
||||
eye, forward = view
|
||||
depth = (place(box_corners(points), transform) - eye) @ forward
|
||||
lo, hi = float(depth.min()), float(depth.max())
|
||||
span = hi - lo
|
||||
return lo + span * cut["front"] / 100.0, hi - span * cut["back"] / 100.0
|
||||
|
||||
|
||||
def kept_faces(points: np.ndarray, faces: np.ndarray, transform, view, cut: dict) -> np.ndarray:
|
||||
"""True for each triangle whose middle lies between the cut planes."""
|
||||
near, far = cut_planes(points, transform, view, cut)
|
||||
eye, forward = view
|
||||
depth = (place(points, transform) - eye) @ forward
|
||||
middle = depth[faces].mean(1)
|
||||
return (middle >= near) & (middle <= far)
|
||||
|
||||
|
||||
def cut_mesh(mesh, model_3d_info, camera_info, cut):
|
||||
"""The mesh with the cut-away triangles dropped (its points, colours and
|
||||
pictures kept). Unchanged when nothing is cut or the cut needs a camera."""
|
||||
cut = clean_cut(cut)
|
||||
view = camera_view(camera_info)
|
||||
if mesh is None or cut is None or view is None:
|
||||
return mesh
|
||||
import copy
|
||||
|
||||
import torch
|
||||
|
||||
vertices, faces = mesh.vertices, mesh.faces
|
||||
if vertices.ndim != 3 or faces.ndim != 3 or vertices.shape[0] != 1:
|
||||
return mesh # one model at a time, as Render Mesh draws
|
||||
n = int(mesh.vertex_counts[0]) if getattr(mesh, "vertex_counts", None) is not None else vertices.shape[1]
|
||||
m = int(mesh.face_counts[0]) if getattr(mesh, "face_counts", None) is not None else faces.shape[1]
|
||||
points = vertices[0, :n].detach().float().cpu().numpy().astype(np.float64)
|
||||
tris = faces[0, :m].detach().cpu().numpy().astype(np.int64)
|
||||
if points.size == 0 or tris.size == 0:
|
||||
return mesh
|
||||
keep = kept_faces(points, tris, model_transform(model_3d_info), view, cut)
|
||||
if keep.all() or not keep.any():
|
||||
return mesh
|
||||
out = copy.copy(mesh)
|
||||
kept = faces[0, :m][torch.from_numpy(keep).to(faces.device)]
|
||||
out.faces = kept.unsqueeze(0)
|
||||
if getattr(mesh, "face_counts", None) is not None:
|
||||
out.face_counts = torch.tensor([kept.shape[0]], dtype=mesh.face_counts.dtype, device=mesh.face_counts.device)
|
||||
return out
|
||||
@@ -0,0 +1,119 @@
|
||||
"""The camera a photo was taken with, in the frame a pixel-aligned 3D build
|
||||
(Pixal3D) puts its model in, and where the photo sits on a 360 canvas.
|
||||
|
||||
Pixal3D builds the model from a square crop around the subject (Crop to Mask)
|
||||
and a horizontal field of view for that crop. Its model comes out Y-up, the
|
||||
crop's camera on +Z looking down -Z at the origin, and the crop's frame
|
||||
spanning x and y from -0.5 to 0.5 on the z = 0 plane. So the crop's camera
|
||||
stands at distance 0.5 / tan(crop_fov / 2).
|
||||
|
||||
The whole photo was taken from the same point. Its centre lies off the crop's
|
||||
axis by the crop's offset in the photo, so the photo's camera is the crop's
|
||||
camera turned towards the photo's centre (no roll), with the photo's own
|
||||
field of view. A sensor shift is what really happened; a turn is what the
|
||||
3D viewer and Render Mesh can show, and for the few degrees a subject sits
|
||||
off centre the two agree to within a few pixels.
|
||||
|
||||
The 360 canvas is an equirectangular picture in which the photo is laid flat
|
||||
at its own width in degrees. Its centre column faces the way the viewer's
|
||||
front camera looks once the 360 is turned 90 degrees (BACKDROP_TURN), so the
|
||||
photo goes where the camera's axis meets the canvas.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
|
||||
# The 360's Turn that puts the canvas's centre column behind the model as the
|
||||
# viewer's front camera sees it (three.js samples a background at
|
||||
# u = atan2(z, x) / 2pi + 0.5, so the centre faces +X until turned).
|
||||
BACKDROP_TURN = 90.0
|
||||
|
||||
|
||||
def subject_box(mask, pad_factor: float = 1.1, max_side: int = 1024) -> tuple[tuple[float, float, float, float], tuple[int, int]]:
|
||||
"""The square Crop to Mask cuts around the subject, in the photo's pixels.
|
||||
|
||||
mask: H x W numbers from 0 to 1 (the subject white). Returns
|
||||
((x1, y1, x2, y2), (W, H)) at the size Crop to Mask measures at, which is
|
||||
the photo scaled down so its longest side is at most max_side.
|
||||
"""
|
||||
import numpy as np
|
||||
|
||||
m = np.asarray(mask, dtype=np.float64)
|
||||
h, w = m.shape
|
||||
border = np.concatenate([m[0, :], m[-1, :], m[:, 0], m[:, -1]])
|
||||
centre = m[h // 4:h - h // 4, w // 4:w - w // 4]
|
||||
if border.mean() > 0.5 and centre.mean() < 0.5:
|
||||
m = 1.0 - m
|
||||
scale = 1.0
|
||||
if max(h, w) > max_side:
|
||||
scale = max_side / max(h, w)
|
||||
W, H = (int(w * scale), int(h * scale)) if scale != 1.0 else (w, h)
|
||||
ys, xs = np.nonzero(m > 0.8)
|
||||
if xs.size == 0:
|
||||
return (0.0, 0.0, float(W), float(H)), (W, H)
|
||||
# Measured on the full-size mask and scaled, which agrees with a box
|
||||
# measured on the scaled mask to about a pixel.
|
||||
x0, x1 = xs.min() * scale, (xs.max() + 1) * scale - 1
|
||||
y0, y1 = ys.min() * scale, (ys.max() + 1) * scale - 1
|
||||
cx, cy = (x0 + x1) / 2.0, (y0 + y1) / 2.0
|
||||
side = int(max(x1 - x0 + 1, y1 - y0 + 1) * pad_factor)
|
||||
half = math.ceil(side / 2)
|
||||
left, top = int(cx - half), int(cy - half)
|
||||
return (float(left), float(top), float(left + 2 * half), float(top + 2 * half)), (W, H)
|
||||
|
||||
|
||||
def look_quaternion(eye, target) -> dict:
|
||||
"""three.js camera quaternion (x, y, z, w) looking from eye to target,
|
||||
+Y up, no roll: a turn about Y, then a tip about X."""
|
||||
dx, dy, dz = (e - t for e, t in zip(eye, target))
|
||||
yaw = math.atan2(dx, dz)
|
||||
pitch = -math.atan2(dy, math.hypot(dx, dz))
|
||||
cy, sy, cp, sp = math.cos(yaw / 2), math.sin(yaw / 2), math.cos(pitch / 2), math.sin(pitch / 2)
|
||||
return {"x": cy * sp, "y": sy * cp, "z": -sy * sp, "w": cy * cp}
|
||||
|
||||
|
||||
def photo_camera(box, size, fov: float, canvas_width: int = 2048) -> dict:
|
||||
"""Everything that follows from the crop and the photo's horizontal field
|
||||
of view (degrees): the crop's field of view for Pixal3D, the photo's
|
||||
camera for the viewer, and the photo's place on the 360 canvas."""
|
||||
x1, y1, x2, y2 = (float(v) for v in box)
|
||||
W, H = int(size[0]), int(size[1])
|
||||
fov = min(170.0, max(1.0, float(fov)))
|
||||
focal = (W / 2.0) / math.tan(math.radians(fov) / 2.0)
|
||||
side = max(1.0, x2 - x1)
|
||||
crop_fov = math.degrees(2.0 * math.atan((side / 2.0) / focal))
|
||||
distance = 0.5 / math.tan(math.radians(crop_fov) / 2.0)
|
||||
|
||||
# The photo's centre, seen from the crop's camera (x right, y up, -z ahead).
|
||||
cx, cy = (x1 + x2) / 2.0, (y1 + y2) / 2.0
|
||||
dx = (W / 2.0 - cx) / focal
|
||||
dy = (cy - H / 2.0) / focal
|
||||
norm = math.sqrt(dx * dx + dy * dy + 1.0)
|
||||
eye = (0.0, 0.0, distance)
|
||||
target = (dx / norm * distance, dy / norm * distance, distance - distance / norm)
|
||||
vfov = math.degrees(2.0 * math.atan((H / 2.0) / focal))
|
||||
xyz = lambda v: {"x": float(v[0]), "y": float(v[1]), "z": float(v[2])}
|
||||
camera = {
|
||||
"position": xyz(eye), "target": xyz(target), "quaternion": look_quaternion(eye, target),
|
||||
"fov": vfov, "aspect": W / max(1, H), "zoom": 1, "cameraType": "perspective",
|
||||
"near": 0.01, "far": 10000, "frustum": {"left": -5, "right": 5, "top": 5, "bottom": -5},
|
||||
}
|
||||
|
||||
# The photo on the 360 canvas: its centre where the camera's axis meets it.
|
||||
canvas_width = max(8, int(canvas_width))
|
||||
canvas_height = canvas_width // 2
|
||||
yaw = math.atan2(dx, 1.0)
|
||||
pitch = math.atan2(dy, math.hypot(dx, 1.0))
|
||||
strip_width = max(1, round(canvas_width * fov / 360.0))
|
||||
strip_height = max(1, round(strip_width * H / max(1, W)))
|
||||
centre_x = (0.5 + yaw / (2 * math.pi)) * canvas_width
|
||||
centre_y = (0.5 - pitch / math.pi) * canvas_height
|
||||
return {
|
||||
"crop_fov": crop_fov,
|
||||
"camera_info": camera,
|
||||
"strip_width": int(strip_width),
|
||||
"strip_x": int(round(centre_x - strip_width / 2.0)),
|
||||
"strip_y": int(round(centre_y - strip_height / 2.0)),
|
||||
"distance": distance,
|
||||
}
|
||||
@@ -238,7 +238,8 @@ def _rgb_uint8(frame: torch.Tensor) -> np.ndarray:
|
||||
|
||||
|
||||
def _encode_animation(
|
||||
path: Path, batch: torch.Tensor, fps: float, crf: int, extension: str
|
||||
path: Path, batch: torch.Tensor, fps: float, crf: int, extension: str,
|
||||
metadata: dict | None = None,
|
||||
) -> None:
|
||||
"""Write an animated gif or webp through Pillow.
|
||||
|
||||
@@ -246,7 +247,8 @@ def _encode_animation(
|
||||
streaming encoder, so every frame has to be resident before the first byte
|
||||
is written - which is why the node's tooltip points them at short clips.
|
||||
GIF frames are quantized individually so each carries its own adaptive
|
||||
palette rather than sharing one flattened web palette.
|
||||
palette rather than sharing one flattened web palette. webp carries the
|
||||
workflow in EXIF the way core's animated WebP does; gif has no place for it.
|
||||
"""
|
||||
from PIL import Image
|
||||
|
||||
@@ -277,7 +279,11 @@ def _encode_animation(
|
||||
else:
|
||||
# webp's quality runs the opposite way to crf: 0 is worst, 100 best.
|
||||
quality = max(0, min(100, int(round(100.0 - int(crf) * 100.0 / 51.0))))
|
||||
head.save(path, **shared, quality=quality, method=4)
|
||||
from ._image_save_helpers import exif_bytes
|
||||
|
||||
exif = exif_bytes(metadata)
|
||||
extra = {} if exif is None else {"exif": exif}
|
||||
head.save(path, **shared, quality=quality, method=4, **extra)
|
||||
|
||||
|
||||
def encode_video(
|
||||
@@ -303,7 +309,7 @@ def encode_video(
|
||||
frame_count = int(batch.shape[0])
|
||||
rate = _fps_fraction(fps)
|
||||
if not spec.video_codec:
|
||||
_encode_animation(path, batch, fps, crf, spec.extension)
|
||||
_encode_animation(path, batch, fps, crf, spec.extension, metadata)
|
||||
return width, height, frame_count
|
||||
prepared_audio = _prepare_audio(audio)
|
||||
if prepared_audio is not None and spec.audio_codec == "libopus":
|
||||
|
||||
@@ -9,10 +9,12 @@ class AusBossColorMatch:
|
||||
CATEGORY = "🆎 AusBoss/Image"
|
||||
DESCRIPTION = (
|
||||
"Transfers the reference image's color statistics onto the input — "
|
||||
"fixes the color shift on inpainted or stitched regions. Four "
|
||||
"fixes the color shift on inpainted or stitched regions. Five "
|
||||
"methods: lab and rgb move per-channel mean/std, mkl maps the full "
|
||||
"color covariance, histogram matches each channel's distribution "
|
||||
"exactly. An optional mask restricts both the measurement and the "
|
||||
"exactly, and kept is for edits: it learns how the model shifted "
|
||||
"the parts it was meant to keep and undoes that everywhere, so new "
|
||||
"things keep their own colours. An optional mask restricts both the measurement and the "
|
||||
"correction to its white area (invert_mask flips that), which is "
|
||||
"why the node takes a mask but outputs none: the mask only scopes "
|
||||
"the fix, and passes through your graph unchanged. Strength blends "
|
||||
@@ -74,7 +76,11 @@ class AusBossColorMatch:
|
||||
"channels. mkl: full covariance mapping, best "
|
||||
"when hues are rotated, not just shifted. "
|
||||
"histogram: exact per-channel distribution "
|
||||
"match, the strongest and least subtle."
|
||||
"match, the strongest and least subtle. kept: "
|
||||
"for an edit, with the picture from before the "
|
||||
"edit as reference. Fixes the brightness, "
|
||||
"contrast and colour the model shifted, and "
|
||||
"leaves new things their own colours."
|
||||
),
|
||||
},
|
||||
),
|
||||
|
||||
+72
-10
@@ -1,16 +1,21 @@
|
||||
"""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``).
|
||||
new node. split sheet at gaps cuts a sheet of side-by-side pictures at the
|
||||
gaps between them (``_sheet_split_helpers``); cut a piece cuts one piece of a
|
||||
chosen size and place (``_cut_piece_helpers``).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from ._cut_piece_helpers import POSITIONS, cut_piece
|
||||
from ._sheet_split_helpers import split_sheet
|
||||
|
||||
SPLIT_SHEET = "split sheet at gaps"
|
||||
JOBS = [SPLIT_SHEET]
|
||||
CUT_PIECE = "cut a piece"
|
||||
JOBS = [SPLIT_SHEET, CUT_PIECE]
|
||||
# Largest piece size and offset, in pixels.
|
||||
MAX_SIDE = 16384
|
||||
|
||||
|
||||
class AusBossImageToolbox:
|
||||
@@ -21,7 +26,9 @@ class AusBossImageToolbox:
|
||||
"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."
|
||||
"all the same size, padded with the sheet's backdrop colour. "
|
||||
"cut a piece cuts one piece of the width and height you set, at the "
|
||||
"position you pick, and gives back the rest of the picture too."
|
||||
)
|
||||
SEARCH_ALIASES = [
|
||||
"toolbox",
|
||||
@@ -31,6 +38,9 @@ class AusBossImageToolbox:
|
||||
"split views",
|
||||
"cut into pieces",
|
||||
"slice image",
|
||||
"crop",
|
||||
"cut a piece",
|
||||
"crop with offset",
|
||||
"ausboss",
|
||||
]
|
||||
|
||||
@@ -46,7 +56,7 @@ class AusBossImageToolbox:
|
||||
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.",
|
||||
"tooltip": "What to do with the picture. split sheet at gaps: cut a row of pictures apart at the gaps between them. cut a piece: cut out one piece of the size you set.",
|
||||
},
|
||||
),
|
||||
"pieces": (
|
||||
@@ -60,18 +70,70 @@ class AusBossImageToolbox:
|
||||
},
|
||||
),
|
||||
},
|
||||
"optional": {
|
||||
"width": (
|
||||
"INT",
|
||||
{
|
||||
"default": 512,
|
||||
"min": 0,
|
||||
"max": MAX_SIDE,
|
||||
"step": 1,
|
||||
"tooltip": "For cut a piece: how wide the piece is, in pixels. 0 takes the picture's full width.",
|
||||
},
|
||||
),
|
||||
"height": (
|
||||
"INT",
|
||||
{
|
||||
"default": 512,
|
||||
"min": 0,
|
||||
"max": MAX_SIDE,
|
||||
"step": 1,
|
||||
"tooltip": "For cut a piece: how tall the piece is, in pixels. 0 takes the picture's full height.",
|
||||
},
|
||||
),
|
||||
"position": (
|
||||
list(POSITIONS),
|
||||
{
|
||||
"default": "top left",
|
||||
"tooltip": "For cut a piece: where on the picture the piece sits before it is moved. top left starts at the top left corner.",
|
||||
},
|
||||
),
|
||||
"move_right": (
|
||||
"INT",
|
||||
{
|
||||
"default": 0,
|
||||
"min": -MAX_SIDE,
|
||||
"max": MAX_SIDE,
|
||||
"step": 1,
|
||||
"tooltip": "For cut a piece: moves the piece right by this many pixels; below 0 moves it left. It stops at the picture's edge.",
|
||||
},
|
||||
),
|
||||
"move_down": (
|
||||
"INT",
|
||||
{
|
||||
"default": 0,
|
||||
"min": -MAX_SIDE,
|
||||
"max": MAX_SIDE,
|
||||
"step": 1,
|
||||
"tooltip": "For cut a piece: moves the piece down by this many pixels; below 0 moves it up. It stops at the picture's edge.",
|
||||
},
|
||||
),
|
||||
},
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("IMAGE",)
|
||||
RETURN_NAMES = ("images",)
|
||||
RETURN_TYPES = ("IMAGE", "IMAGE")
|
||||
RETURN_NAMES = ("images", "rest")
|
||||
OUTPUT_TOOLTIPS = (
|
||||
"The result. For split sheet at gaps: the pieces from left to right, one batch, all the same size.",
|
||||
"The result. For split sheet at gaps: the pieces from left to right, one batch, all the same size. For cut a piece: the piece.",
|
||||
"For cut a piece: the rest of the picture. A piece that takes a whole side leaves the strip beside it; any other piece leaves the picture with its hole filled with the backdrop colour. Other jobs pass the picture through.",
|
||||
)
|
||||
FUNCTION = "run"
|
||||
|
||||
def run(self, image, job, pieces):
|
||||
def run(self, image, job, pieces, width=512, height=512, position="top left", move_right=0, move_down=0):
|
||||
if job == SPLIT_SHEET:
|
||||
return (split_sheet(image, pieces),)
|
||||
return (split_sheet(image, pieces), image)
|
||||
if job == CUT_PIECE:
|
||||
return cut_piece(image, width, height, position, move_right, move_down)
|
||||
raise ValueError(f"Image Toolbox has no job named {job!r}.")
|
||||
|
||||
|
||||
|
||||
@@ -7,7 +7,9 @@ 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 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:
|
||||
words for MiniMax H3 Image (_layout_boxes_h3.py), and a sixth, `placement`,
|
||||
says each box as a plain sentence for any model that reads only a prompt
|
||||
(placement_prompt). 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,
|
||||
@@ -34,6 +36,7 @@ from ._layout_boxes_helpers import (
|
||||
input_fingerprint,
|
||||
mask_rects,
|
||||
parse_layout,
|
||||
placement_prompt,
|
||||
prompt_elements,
|
||||
regions_from_pixel_boxes,
|
||||
render_preview,
|
||||
@@ -120,7 +123,8 @@ class AusBossLayoutBoxes:
|
||||
"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. "
|
||||
"h3_prompt says the boxes in words for MiniMax H3 Image: describe each "
|
||||
"person as \"the man from <Picture 2>, sitting on the couch\"."
|
||||
"person as \"the man from <Picture 2>, sitting on the couch\". "
|
||||
"placement says each box as a sentence, for models that read only a prompt."
|
||||
)
|
||||
SEARCH_ALIASES = [
|
||||
"bounding boxes", "create bounding boxes", "bbox", "boxes", "layout",
|
||||
@@ -166,8 +170,8 @@ class AusBossLayoutBoxes:
|
||||
},
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("IMAGE", "BOUNDING_BOX", "ARRAY", "MASK", "STRING")
|
||||
RETURN_NAMES = ("preview", "bboxes", "elements", "mask", "h3_prompt")
|
||||
RETURN_TYPES = ("IMAGE", "BOUNDING_BOX", "ARRAY", "MASK", "STRING", "STRING")
|
||||
RETURN_NAMES = ("preview", "bboxes", "elements", "mask", "h3_prompt", "placement")
|
||||
OUTPUT_TOOLTIPS = (
|
||||
"A picture of the boxes with their numbers and words, to check the layout. "
|
||||
"Wire it to Preview Image.",
|
||||
@@ -180,6 +184,8 @@ class AusBossLayoutBoxes:
|
||||
"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>.",
|
||||
"The boxes as sentences for a prompt: what goes where, as parts of the picture. "
|
||||
"Add it to your prompt for a model that has no box input.",
|
||||
)
|
||||
OUTPUT_NODE = True
|
||||
FUNCTION = "draw"
|
||||
@@ -214,6 +220,7 @@ class AusBossLayoutBoxes:
|
||||
prompt_elements(regions, shape),
|
||||
_boxes_mask(regions, width, height, picture),
|
||||
h3_prompt(regions, shape, scene=picture is not None),
|
||||
placement_prompt(regions, shape),
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
@@ -21,12 +21,14 @@ ComfyUI's queue ends a pause as well.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import random
|
||||
import threading
|
||||
|
||||
from ._backdrop_helpers import clean_ground, shadow_alpha, view_backdrop
|
||||
from ._mesh_cut_helpers import clean_cut, cut_mesh
|
||||
|
||||
EVENT_WAIT = "ausboss-pause-shot"
|
||||
EVENT_DONE = "ausboss-pause-shot-done"
|
||||
@@ -157,6 +159,9 @@ def clean_shot(shot) -> dict:
|
||||
ground = clean_ground(shot.get("ground"))
|
||||
if ground:
|
||||
out["ground"] = ground
|
||||
cut = clean_cut(shot.get("cut"))
|
||||
if cut:
|
||||
out["cut"] = cut
|
||||
# False when the 360 was taken out of the viewer: the backdrop goes grey.
|
||||
if shot.get("panorama") is False:
|
||||
out["panorama"] = False
|
||||
@@ -278,18 +283,23 @@ class AusBossPauseShot:
|
||||
},
|
||||
"optional": {
|
||||
"panorama": ("IMAGE", {"tooltip": "A 360 picture (twice as wide as tall) to show behind the model and hand on as backdrop."}),
|
||||
"mesh": ("MESH", {"tooltip": "The model as a mesh, the one Render Mesh draws. Wire it here and take mesh from this node to Render Mesh, so the viewer's Cut reaches the shot."}),
|
||||
"view": ("STRING", {"default": "", "multiline": False, "tooltip": "The viewer's 360 settings and Cut, filled in by the page when you press Run. Leave it empty."}),
|
||||
},
|
||||
# Only what is in the prompt: ComfyUI runs a node again only when
|
||||
# an input changes, and the saved workflow is not an input.
|
||||
"hidden": {"unique_id": "UNIQUE_ID", "prompt": "PROMPT"},
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("LOAD3D_MODEL_INFO", "LOAD3D_CAMERA", "INT", "INT", "IMAGE")
|
||||
RETURN_NAMES = ("model_3d_info", "camera_info", "width", "height", "backdrop")
|
||||
RETURN_TYPES = ("LOAD3D_MODEL_INFO", "LOAD3D_CAMERA", "INT", "INT", "IMAGE", "MESH")
|
||||
RETURN_NAMES = ("model_3d_info", "camera_info", "width", "height", "backdrop", "mesh")
|
||||
OUTPUT_TOOLTIPS = (
|
||||
"The model's placement as the viewer shows it when you press Continue.",
|
||||
"The camera as the viewer shows it when you press Continue.",
|
||||
"The shot's width.",
|
||||
"The shot's height.",
|
||||
"The part of the 360 the camera sees, at the shot's size, with the viewer's ground shadow. Grey when no 360 is wired in.",
|
||||
"The mesh wired in, cut the way the viewer's Cut shows it. Nothing when no mesh is wired in.",
|
||||
)
|
||||
FUNCTION = "wait"
|
||||
|
||||
@@ -298,7 +308,8 @@ class AusBossPauseShot:
|
||||
# A pause asks on every run, even when nothing above it changed.
|
||||
return float("nan") if pause else 0
|
||||
|
||||
def wait(self, model_3d_info, camera_info, width, height, pause, panorama=None, unique_id=None, prompt=None):
|
||||
def wait(self, model_3d_info, camera_info, width, height, pause, panorama=None, mesh=None, view="",
|
||||
unique_id=None, prompt=None):
|
||||
shot = {}
|
||||
if pause and unique_id is not None:
|
||||
extra = {}
|
||||
@@ -318,8 +329,45 @@ class AusBossPauseShot:
|
||||
height = shot.get("height", height)
|
||||
if shot.get("panorama") is False:
|
||||
panorama = None
|
||||
backdrop = _backdrop(panorama, camera_info, shot.get("sky"), shot.get("ground"), width, height)
|
||||
return (model_3d_info, camera_info, width, height, backdrop)
|
||||
sky, cut = shot.get("sky"), shot.get("cut")
|
||||
if sky is None:
|
||||
# A run that went straight through: no Continue carried the 360's
|
||||
# settings or the Cut, so take the viewer's as the page put them
|
||||
# in `view` when Run was pressed.
|
||||
saved = view_settings(view)
|
||||
sky, cut = saved.get("sky"), saved.get("cut")
|
||||
backdrop = _backdrop(panorama, camera_info, sky, shot.get("ground"), width, height)
|
||||
mesh = cut_mesh(mesh, model_3d_info, camera_info, cut)
|
||||
return (model_3d_info, camera_info, width, height, backdrop, mesh)
|
||||
|
||||
|
||||
MAX_VIEW = 20000
|
||||
|
||||
|
||||
def view_settings(view) -> dict:
|
||||
"""The viewer's 360 settings (Turn, Tilt, Shadow...) and its Cut, from the
|
||||
`view` input: the page writes the viewer's "AusBoss View" property
|
||||
(js/viewer_pano) there as JSON when Run is pressed (js/pause_shot),
|
||||
checked like an answer's. They ride in an input, not in the saved
|
||||
workflow, because ComfyUI runs a node again only when an input changes:
|
||||
read from the workflow, a changed Turn handed back the old backdrop."""
|
||||
if isinstance(view, str):
|
||||
if not view.strip() or len(view) > MAX_VIEW:
|
||||
return {}
|
||||
try:
|
||||
view = json.loads(view)
|
||||
except ValueError:
|
||||
return {}
|
||||
if not isinstance(view, dict):
|
||||
return {}
|
||||
out = {}
|
||||
sky = clean_value(view.get("sky"))
|
||||
if isinstance(sky, dict):
|
||||
out["sky"] = sky
|
||||
cut = clean_cut(view.get("cut"))
|
||||
if cut:
|
||||
out["cut"] = cut
|
||||
return out
|
||||
|
||||
|
||||
def _backdrop(panorama, camera_info, sky, ground, width, height):
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
"""Photo Camera 🆎: the camera your photo was taken with, for a 3D model
|
||||
built to line up with the photo (Pixal3D).
|
||||
|
||||
Give it the photo, the subject's mask and the photo's field of view (MoGe's
|
||||
Get FoV measures it). It hands on the crop's field of view for Pixal3D
|
||||
Conditioning, the photo's camera for the 3D viewer (so the viewer opens on
|
||||
your photo's own view), and where the photo goes on the 360 canvas so the
|
||||
360 lines up with the camera. The maths is in _photo_camera_helpers.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
|
||||
from ._photo_camera_helpers import photo_camera, subject_box
|
||||
|
||||
|
||||
def _crop_box(image, mask, pad_factor: float, max_side: int):
|
||||
"""The square Crop to Mask cuts. Core's own helper when it is there, so
|
||||
the two agree to the pixel; the same rule of ours otherwise."""
|
||||
try:
|
||||
from comfy_extras.nodes_images import _crop_image_with_mask
|
||||
|
||||
_, box, size = _crop_image_with_mask(image[0, :, :, :3], mask[0], max_image_size=max_side,
|
||||
pad_factor=pad_factor, aspect_ratio=1.0)
|
||||
return tuple(float(v) for v in box), (int(size[0]), int(size[1]))
|
||||
except Exception as error: # an older or newer ComfyUI: fall back to ours
|
||||
logging.info("Photo Camera: using its own crop box (%s)", type(error).__name__)
|
||||
return subject_box(mask[0].float().cpu().numpy(), pad_factor, max_side)
|
||||
|
||||
|
||||
class AusBossPhotoCamera:
|
||||
CATEGORY = "🆎 AusBoss/Utility"
|
||||
DESCRIPTION = (
|
||||
"Works out the camera your photo was taken with, so a 3D model of the "
|
||||
"person lines up with the photo. Wire in the photo, the person's mask "
|
||||
"and the photo's field of view (Get FoV from MoGe measures it). Send "
|
||||
"crop_fov to Pixal3D Conditioning, camera_info to the 3D viewer, and "
|
||||
"the strip numbers to where the photo is laid on the 360. The viewer "
|
||||
"then opens on your photo's own view, with the 360 behind it lined up."
|
||||
)
|
||||
SEARCH_ALIASES = ["photo camera", "camera", "match camera", "pixal3d", "line up", "3d", "fov", "360", "ausboss"]
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {
|
||||
"image": ("IMAGE", {"tooltip": "Your photo, the same one Crop to Mask cuts the person from."}),
|
||||
"mask": ("MASK", {"tooltip": "The person, white on black: the same mask Crop to Mask uses."}),
|
||||
"fov": ("FLOAT", {"default": 55.0, "min": 1.0, "max": 170.0, "step": 0.1,
|
||||
"tooltip": "How wide the photo is, in degrees across. Wire Get FoV from MoGe here; 55 suits most phone photos."}),
|
||||
"pad_factor": ("FLOAT", {"default": 1.1, "min": 1.0, "max": 2.0, "step": 0.01,
|
||||
"tooltip": "The margin Crop to Mask adds around the person. Keep the two the same."}),
|
||||
"canvas_width": ("INT", {"default": 2048, "min": 8, "max": 16384, "step": 8,
|
||||
"tooltip": "Width of the 360 canvas the photo is laid on."}),
|
||||
},
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("FLOAT", "LOAD3D_CAMERA", "INT", "INT", "INT")
|
||||
RETURN_NAMES = ("crop_fov", "camera_info", "strip_width", "strip_x", "strip_y")
|
||||
OUTPUT_TOOLTIPS = (
|
||||
"The crop's field of view, for Pixal3D Conditioning.",
|
||||
"Your photo's camera, for the 3D viewer's camera_info: it opens on the photo's own view.",
|
||||
"How wide the photo is on the 360 canvas, in pixels.",
|
||||
"Where the photo's left edge goes on the 360 canvas.",
|
||||
"Where the photo's top edge goes on the 360 canvas.",
|
||||
)
|
||||
FUNCTION = "solve"
|
||||
|
||||
def solve(self, image, mask, fov, pad_factor, canvas_width):
|
||||
if mask.ndim == 2:
|
||||
mask = mask.unsqueeze(0)
|
||||
if tuple(mask.shape[-2:]) != tuple(image.shape[1:3]):
|
||||
import comfy.utils
|
||||
|
||||
mask = comfy.utils.common_upscale(mask.unsqueeze(1).float(), image.shape[2], image.shape[1],
|
||||
"bilinear", "disabled").squeeze(1)
|
||||
box, size = _crop_box(image, mask, float(pad_factor), 1024)
|
||||
out = photo_camera(box, size, float(fov), int(canvas_width))
|
||||
shown = [round(float(fov), 1), round(out["crop_fov"], 1), out["strip_width"], out["strip_x"], out["strip_y"]]
|
||||
return {"ui": {"ausboss_photo_camera": shown},
|
||||
"result": (out["crop_fov"], out["camera_info"], out["strip_width"], out["strip_x"], out["strip_y"])}
|
||||
|
||||
|
||||
NODE_CLASS_MAPPINGS = {"AUSBOSS_NODES_PhotoCamera": AusBossPhotoCamera}
|
||||
NODE_DISPLAY_NAME_MAPPINGS = {"AUSBOSS_NODES_PhotoCamera": "Photo Camera 🆎"}
|
||||
|
||||
__all__ = ["NODE_CLASS_MAPPINGS", "NODE_DISPLAY_NAME_MAPPINGS"]
|
||||
@@ -22,6 +22,8 @@ from ._image_save_helpers import (
|
||||
)
|
||||
from ._route_errors import safe_route_error
|
||||
from ._step_preview_helpers import STEP_PREVIEW_DEFAULT, register_step_preview_handler
|
||||
from ._civitai_info import civitai_parameters
|
||||
from ._lora_helpers import file_sha256
|
||||
from ._video_save_helpers import workflow_metadata
|
||||
|
||||
try:
|
||||
@@ -30,6 +32,18 @@ except ImportError: # offline tests
|
||||
folder_paths = None
|
||||
|
||||
|
||||
def _find_model_file(folders: tuple[str, ...], name: str) -> Path | None:
|
||||
"""A model file by its list name, from ComfyUI's registered folders."""
|
||||
for folder in folders:
|
||||
try:
|
||||
found = folder_paths.get_full_path(folder, name)
|
||||
except Exception:
|
||||
found = None
|
||||
if found:
|
||||
return Path(found)
|
||||
return None
|
||||
|
||||
|
||||
def _register_folder_route() -> None:
|
||||
"""GET /ausboss/save_image/folders?path=<relative> lists the subfolders
|
||||
under ComfyUI's output folder, for the node's Browse button. Paths are
|
||||
@@ -310,8 +324,21 @@ class AusBossSaveImage:
|
||||
),
|
||||
},
|
||||
),
|
||||
"civitai_info": (
|
||||
"BOOLEAN",
|
||||
{
|
||||
"default": False,
|
||||
"tooltip": (
|
||||
"On: also writes the prompt, settings and model "
|
||||
"and LoRA fingerprints the way civitai.com reads "
|
||||
"them, so an upload lists its prompt and resources. "
|
||||
"Needs Embed on. The first save with a new model "
|
||||
"takes a moment while its file is fingerprinted."
|
||||
),
|
||||
},
|
||||
),
|
||||
},
|
||||
"hidden": {"prompt": "PROMPT", "extra_pnginfo": "EXTRA_PNGINFO"},
|
||||
"hidden": {"prompt": "PROMPT", "extra_pnginfo": "EXTRA_PNGINFO", "unique_id": "UNIQUE_ID"},
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("STRING", "IMAGE")
|
||||
@@ -344,8 +371,10 @@ class AusBossSaveImage:
|
||||
preview=True,
|
||||
step_preview=STEP_PREVIEW_DEFAULT,
|
||||
autosave=True,
|
||||
civitai_info=False,
|
||||
prompt=None,
|
||||
extra_pnginfo=None,
|
||||
unique_id=None,
|
||||
):
|
||||
if folder_paths is None:
|
||||
raise RuntimeError("Save Image requires ComfyUI's folder_paths at runtime.")
|
||||
@@ -359,6 +388,12 @@ class AusBossSaveImage:
|
||||
root = resolve_output_root(output_dir, output_root)
|
||||
count = int(images.shape[0])
|
||||
height, width = int(images.shape[1]), int(images.shape[2])
|
||||
if metadata is not None and civitai_info:
|
||||
parameters = civitai_parameters(
|
||||
prompt, unique_id, width, height, _find_model_file, file_sha256,
|
||||
)
|
||||
if parameters:
|
||||
metadata["parameters"] = parameters
|
||||
# Name tokens typed on the node (%width%, %year%...). A linked
|
||||
# filename is another node's exact name and is left as it is.
|
||||
now = datetime.now()
|
||||
|
||||
@@ -158,7 +158,7 @@ class AusBossSaveVideo:
|
||||
"Embed the prompt and workflow in the file, so an mp4 "
|
||||
"dragged back onto the canvas restores its graph. Turn off "
|
||||
"to share a file without your prompts and node graph inside "
|
||||
"it. gif and webp never carry metadata."
|
||||
"it. gif never carries metadata."
|
||||
),
|
||||
},
|
||||
),
|
||||
|
||||
+2
-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, Load Image, Load Image + Pad, Image Folder, Image Resize, Align Image, Image Size, Color Match, Image Compare A/B, Image Toolbox, Realign to Source (experimental), Save Image (PNG, WebP/JXL, captions), Load Video, Load Audio, Save Video, Select Frame, Frame Interpolate, Mask Refine, Mask by Name and Mask by Touch, LaMa Inpaint, Crop For Inpaint, Stitch Inpaint, Tiled Upscale and Tiled Upscale Stitch, FlashVSR Upscale, Edit Lock and Edit Lock Restore, LoRA Loader, Krea 2 Encode and Outpaint Model Patch, Latent Size, Layout Boxes, Seed, Select Every Nth, Split Batch, Merge Batches, Text, Text Lines, Prompt Variations, H3 Prompt Writer, Integer, Float, Math Expression, Show Text, Free Memory, Workflow Note, Workflow Note Tile, Callout, Callout Tile, Workflow Switches, Run Timer, Step Preview, and Pause for Shot. Examples for Qwen Image 2.1, Krea 2, Klein 9B and LTX 2.3."
|
||||
version = "2.27.0"
|
||||
description = "ComfyUI-AusBoss (AusBoss nodes): image and video nodes: Image and Video Crop + Rotate + Pad, Load Image, Load Image + Pad, Image Folder, Image Resize, Align Image, Image Size, Color Match, Image Compare A/B, Image Toolbox, Realign to Source (experimental), Save Image (PNG, WebP/JXL, captions), Load Video, Load Audio, Save Video, Select Frame, Frame Interpolate, Mask Refine, Mask by Name and Mask by Touch, LaMa Inpaint, Crop For Inpaint, Stitch Inpaint, Tiled Upscale and Tiled Upscale Stitch, FlashVSR Upscale, Edit Lock and Edit Lock Restore, LoRA Loader, Krea 2 Encode and Outpaint Model Patch, Latent Size, Layout Boxes, Seed, Select Every Nth, Split Batch, Merge Batches, Text, Text Lines, Prompt Variations, H3 Prompt Writer, Integer, Float, Math Expression, Show Text, Free Memory, Workflow Note, Workflow Note Tile, Callout, Callout Tile, Workflow Switches, Run Timer, Step Preview, Pause for Shot, and Photo Camera. Examples for Qwen Image 2.1, Krea 2, Klein 9B and LTX 2.3."
|
||||
version = "2.28.1"
|
||||
# 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.
|
||||
|
||||
@@ -59,6 +59,7 @@ PUBLIC_NODE_IDS = {
|
||||
"AUSBOSS_NODES_EditLock",
|
||||
"AUSBOSS_NODES_EditLockRestore",
|
||||
"AUSBOSS_NODES_PauseShot",
|
||||
"AUSBOSS_NODES_PhotoCamera",
|
||||
"AUSBOSS_NODES_FlashVSRUpscale",
|
||||
"AUSBOSS_NODES_Float",
|
||||
"AUSBOSS_NODES_FrameInterpolate",
|
||||
|
||||
@@ -7,10 +7,13 @@ import {
|
||||
civitaiButtonLabel,
|
||||
civitaiByHashUrl,
|
||||
civitaiFailureText,
|
||||
civitaiQueueLabel,
|
||||
civitaiQueueSummary,
|
||||
isCivitaiAddress,
|
||||
isMildPicture,
|
||||
parseCivitaiBody,
|
||||
pickCivitaiPicture,
|
||||
runCivitaiQueue,
|
||||
smallPictureUrl,
|
||||
} from "../js/shared/civitai_lookup.mjs";
|
||||
|
||||
@@ -89,3 +92,123 @@ test("a failed lookup says why in plain words", () => {
|
||||
assert.equal(civitaiFailureText(new Error("Civitai answered 500.")), "Civitai answered 500.");
|
||||
assert.equal(civitaiFailureText(null), "The Civitai lookup failed.");
|
||||
});
|
||||
|
||||
// ---------- fetch all ----------
|
||||
|
||||
// A fake Civitai: `answers` maps a name to what lookUp returns or throws.
|
||||
function fakeQueue({ have = [], missing = [], answers = {}, stopAfter = Infinity } = {}) {
|
||||
const asked = [];
|
||||
const pauses = [];
|
||||
const progress = [];
|
||||
let stop = false;
|
||||
const options = {
|
||||
needsLookup: async (name) => {
|
||||
if (missing.includes(name)) throw new Error("No such LoRA.");
|
||||
return !have.includes(name);
|
||||
},
|
||||
lookUp: async (name) => {
|
||||
asked.push(name);
|
||||
if (asked.length >= stopAfter) stop = true;
|
||||
const answer = typeof answers[name] === "function" ? answers[name](asked) : answers[name];
|
||||
if (answer instanceof Error) throw answer;
|
||||
return answer ?? { picture: "saved" };
|
||||
},
|
||||
wait: async (ms) => { pauses.push(ms); },
|
||||
shouldStop: () => stop,
|
||||
onProgress: (step) => progress.push({ ...step }),
|
||||
};
|
||||
return { asked, pauses, progress, options, stopNow: () => { stop = true; } };
|
||||
}
|
||||
|
||||
const statusError = (status) => Object.assign(new Error(`Civitai answered ${status}.`), { status });
|
||||
|
||||
test("fetch all asks only about LoRAs with no info, once each, with a pause between", async () => {
|
||||
const fake = fakeQueue({ have: ["b"], missing: ["gone"], answers: { c: false, d: { picture: "none" } } });
|
||||
const result = await runCivitaiQueue(["a", "b", "", "a", "gone", "c", "d", null], fake.options);
|
||||
assert.deepEqual(fake.asked, ["a", "c", "d"]);
|
||||
assert.deepEqual(fake.pauses, [1500, 1500]);
|
||||
assert.equal(result.total, 3);
|
||||
assert.equal(result.done, 3);
|
||||
assert.equal(result.found, 2);
|
||||
assert.equal(result.pictures, 1);
|
||||
assert.equal(result.notFound, 1);
|
||||
assert.equal(result.alreadyHad, 1);
|
||||
assert.equal(result.missing, 1);
|
||||
assert.equal(result.stopped, null);
|
||||
assert.deepEqual(fake.progress.map(({ done, total }) => [done, total]), [[0, null], [0, 3], [1, 3], [2, 3], [3, 3]]);
|
||||
assert.equal(civitaiQueueSummary(result),
|
||||
"Civitai: found 2 LoRAs (1 new picture), 1 not on Civitai, 1 already had info, 1 file not found on disk.");
|
||||
});
|
||||
|
||||
test("stop ends the run after the file being fetched", async () => {
|
||||
const fake = fakeQueue({ stopAfter: 2 });
|
||||
const result = await runCivitaiQueue(["a", "b", "c", "d"], fake.options);
|
||||
assert.deepEqual(fake.asked, ["a", "b"]);
|
||||
assert.equal(result.stopped, "you");
|
||||
assert.equal(result.done, 2);
|
||||
assert.match(civitaiQueueSummary(result), /Stopped with 2 left\.$/);
|
||||
});
|
||||
|
||||
test("stop while the files are checked asks Civitai nothing", async () => {
|
||||
const fake = fakeQueue();
|
||||
fake.stopNow();
|
||||
const result = await runCivitaiQueue(["a", "b"], fake.options);
|
||||
assert.deepEqual(fake.asked, []);
|
||||
assert.equal(result.stopped, "you");
|
||||
});
|
||||
|
||||
test("one failure is counted and the run goes on", async () => {
|
||||
const fake = fakeQueue({ answers: { b: new Error("Could not save the Civitai info.") } });
|
||||
const result = await runCivitaiQueue(["a", "b", "c"], fake.options);
|
||||
assert.deepEqual(fake.asked, ["a", "b", "c"]);
|
||||
assert.equal(result.failed, 1);
|
||||
assert.equal(result.found, 2);
|
||||
assert.equal(result.stopped, null);
|
||||
assert.match(civitaiQueueSummary(result), /1 failed\. Last failure: Could not save the Civitai info\.$/);
|
||||
});
|
||||
|
||||
test("three failures in a row end the run", async () => {
|
||||
const broken = new Error("Civitai answered 500.");
|
||||
const fake = fakeQueue({ answers: { a: broken, b: broken, c: broken } });
|
||||
const result = await runCivitaiQueue(["a", "b", "c", "d", "e"], fake.options);
|
||||
assert.deepEqual(fake.asked, ["a", "b", "c"]);
|
||||
assert.equal(result.stopped, "failures");
|
||||
assert.match(civitaiQueueSummary(result), /Stopped after 3 failures in a row: Civitai answered 500\./);
|
||||
});
|
||||
|
||||
test("a site that cannot be reached ends the run at once", async () => {
|
||||
const fake = fakeQueue({ answers: { a: new TypeError("Failed to fetch") } });
|
||||
const result = await runCivitaiQueue(["a", "b"], fake.options);
|
||||
assert.deepEqual(fake.asked, ["a"]);
|
||||
assert.equal(result.stopped, "unreachable");
|
||||
assert.match(civitaiQueueSummary(result), /Could not reach civitai\.com/);
|
||||
});
|
||||
|
||||
test("Civitai's slow down waits longer and tries the file again once", async () => {
|
||||
const fake = fakeQueue({ answers: { b: (asked) => (asked.length === 2 ? statusError(429) : { picture: "saved" }) } });
|
||||
const result = await runCivitaiQueue(["a", "b", "c"], fake.options);
|
||||
assert.deepEqual(fake.asked, ["a", "b", "b", "c"]);
|
||||
assert.deepEqual(fake.pauses, [1500, 20000, 1500]);
|
||||
assert.equal(result.found, 3);
|
||||
assert.equal(result.stopped, null);
|
||||
});
|
||||
|
||||
test("a second slow down in a row ends the run", async () => {
|
||||
const fake = fakeQueue({ answers: { b: statusError(429) } });
|
||||
const result = await runCivitaiQueue(["a", "b", "c"], fake.options);
|
||||
assert.deepEqual(fake.asked, ["a", "b", "b"]);
|
||||
assert.equal(result.stopped, "slow down");
|
||||
assert.match(civitaiQueueSummary(result), /asked us to slow down, so it stopped with 2 left/);
|
||||
});
|
||||
|
||||
test("nothing to do says so plainly", async () => {
|
||||
const all = await runCivitaiQueue(["a"], fakeQueue({ have: ["a"] }).options);
|
||||
assert.equal(civitaiQueueSummary(all), "Every LoRA in this stack already has its Civitai info.");
|
||||
const none = await runCivitaiQueue([], fakeQueue().options);
|
||||
assert.equal(civitaiQueueSummary(none), "This stack has no LoRAs to look up.");
|
||||
});
|
||||
|
||||
test("the run's button shows where it is and that a click stops it", () => {
|
||||
assert.equal(civitaiQueueLabel(0, null), "Civitai: checking · Stop");
|
||||
assert.equal(civitaiQueueLabel(12, 44), "Civitai 12 / 44 · Stop");
|
||||
});
|
||||
|
||||
Vendored
+56
-3
@@ -476,11 +476,21 @@
|
||||
"job",
|
||||
"pieces"
|
||||
],
|
||||
"optional": [],
|
||||
"optional": [
|
||||
"width",
|
||||
"height",
|
||||
"position",
|
||||
"move_right",
|
||||
"move_down"
|
||||
],
|
||||
"outputs": [
|
||||
[
|
||||
"IMAGE",
|
||||
"images"
|
||||
],
|
||||
[
|
||||
"IMAGE",
|
||||
"rest"
|
||||
]
|
||||
]
|
||||
},
|
||||
@@ -581,6 +591,10 @@
|
||||
[
|
||||
"STRING",
|
||||
"h3_prompt"
|
||||
],
|
||||
[
|
||||
"STRING",
|
||||
"placement"
|
||||
]
|
||||
]
|
||||
},
|
||||
@@ -877,7 +891,9 @@
|
||||
"pause"
|
||||
],
|
||||
"optional": [
|
||||
"panorama"
|
||||
"panorama",
|
||||
"mesh",
|
||||
"view"
|
||||
],
|
||||
"outputs": [
|
||||
[
|
||||
@@ -899,6 +915,42 @@
|
||||
[
|
||||
"IMAGE",
|
||||
"backdrop"
|
||||
],
|
||||
[
|
||||
"MESH",
|
||||
"mesh"
|
||||
]
|
||||
]
|
||||
},
|
||||
"AUSBOSS_NODES_PhotoCamera": {
|
||||
"required": [
|
||||
"image",
|
||||
"mask",
|
||||
"fov",
|
||||
"pad_factor",
|
||||
"canvas_width"
|
||||
],
|
||||
"optional": [],
|
||||
"outputs": [
|
||||
[
|
||||
"FLOAT",
|
||||
"crop_fov"
|
||||
],
|
||||
[
|
||||
"LOAD3D_CAMERA",
|
||||
"camera_info"
|
||||
],
|
||||
[
|
||||
"INT",
|
||||
"strip_width"
|
||||
],
|
||||
[
|
||||
"INT",
|
||||
"strip_x"
|
||||
],
|
||||
[
|
||||
"INT",
|
||||
"strip_y"
|
||||
]
|
||||
]
|
||||
},
|
||||
@@ -1019,7 +1071,8 @@
|
||||
"name_batch",
|
||||
"preview",
|
||||
"step_preview",
|
||||
"autosave"
|
||||
"autosave",
|
||||
"civitai_info"
|
||||
],
|
||||
"outputs": [
|
||||
[
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
// Image Resize's card shows Fit and Fill only where the node reads them.
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { readsFill, readsFit } from "../js/shared/image_resize_rows.mjs";
|
||||
|
||||
const MODES = ["width+height", "longest_edge", "shortest_edge", "megapixels", "scale_factor"];
|
||||
const FITS = ["stretch", "fit", "cover_crop", "pad"];
|
||||
|
||||
test("Fit shows only for a width × height box, the one target the node fits", () => {
|
||||
for (const mode of MODES) {
|
||||
assert.equal(readsFit({ target_mode: mode }), mode === "width+height", mode);
|
||||
}
|
||||
});
|
||||
|
||||
test("Fill shows only where pad is read", () => {
|
||||
for (const mode of MODES) {
|
||||
for (const fit of FITS) {
|
||||
const expected = mode === "width+height" && fit === "pad";
|
||||
assert.equal(readsFill({ target_mode: mode, keep_proportion: fit }), expected, `${mode} ${fit}`);
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -45,12 +45,12 @@ test("crf shows only where the encoder reads a quality number", () => {
|
||||
}
|
||||
});
|
||||
|
||||
test("save_metadata hides only for the Pillow formats that cannot carry it", () => {
|
||||
test("save_metadata hides only for gif, the one format that cannot carry it", () => {
|
||||
const wantsMetadata = (format) => formatWidgetVisibility(format).save_metadata;
|
||||
for (const format of BACKEND_FORMATS) {
|
||||
assert.equal(
|
||||
wantsMetadata(format),
|
||||
format !== "gif" && format !== "webp",
|
||||
format !== "gif",
|
||||
`save_metadata visibility wrong for ${format}`,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,220 @@
|
||||
"""Save Image's Civitai line: the A1111-style ``parameters`` text built from
|
||||
the run's graph, and where each format stores it."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
import torch
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
sys.path.insert(0, str(ROOT))
|
||||
if "nodes" in sys.modules and not hasattr(sys.modules["nodes"], "__path__"):
|
||||
del sys.modules["nodes"]
|
||||
|
||||
from PIL import Image
|
||||
|
||||
from nodes import _lora_helpers, node_save_image
|
||||
from nodes._civitai_info import civitai_parameters
|
||||
|
||||
|
||||
def stack(*rows):
|
||||
return json.dumps([{"name": name, "strength": strength, "enabled": on} for name, strength, on in rows])
|
||||
|
||||
|
||||
def sd15_graph():
|
||||
return {
|
||||
"4": {"class_type": "CheckpointLoaderSimple", "inputs": {"ckpt_name": "sd/dreamshaper_8.safetensors"}},
|
||||
"10": {"class_type": "AUSBOSS_NODES_LoraLoader", "inputs": {
|
||||
"model": ["4", 0], "clip": ["4", 1],
|
||||
"loras": stack(("detail.safetensors", 0.8, True), ("off.safetensors", 1.0, False), ("zero.safetensors", 0.0, True)),
|
||||
}},
|
||||
"5": {"class_type": "EmptyLatentImage", "inputs": {"width": 512, "height": 768, "batch_size": 1}},
|
||||
"6": {"class_type": "CLIPTextEncode", "inputs": {"text": "a lighthouse at dusk, oil paint", "clip": ["10", 1]}},
|
||||
"7": {"class_type": "CLIPTextEncode", "inputs": {"text": "blurry", "clip": ["10", 1]}},
|
||||
"3": {"class_type": "KSampler", "inputs": {
|
||||
"seed": 1234, "steps": 20, "cfg": 7, "sampler_name": "euler", "scheduler": "normal", "denoise": 1,
|
||||
"model": ["10", 0], "positive": ["6", 0], "negative": ["7", 0], "latent_image": ["5", 0],
|
||||
}},
|
||||
"8": {"class_type": "VAEDecode", "inputs": {"samples": ["3", 0], "vae": ["4", 2]}},
|
||||
"9": {"class_type": "AUSBOSS_NODES_SaveImage", "inputs": {"images": ["8", 0]}},
|
||||
}
|
||||
|
||||
|
||||
FILES = {
|
||||
("checkpoints", "sd/dreamshaper_8.safetensors"): "a" * 64,
|
||||
("loras", "detail.safetensors"): "b" * 64,
|
||||
("loras", "off.safetensors"): "c" * 64,
|
||||
("loras", "zero.safetensors"): "d" * 64,
|
||||
("diffusion_models", "krea2_dev.safetensors"): "e" * 64,
|
||||
}
|
||||
|
||||
|
||||
def find_file(folders, name):
|
||||
for folder in folders:
|
||||
if (folder, name) in FILES:
|
||||
return Path(folder) / name
|
||||
return None
|
||||
|
||||
|
||||
def file_hash(path: Path) -> str:
|
||||
return FILES[(path.parent.as_posix().split("/")[0], path.relative_to(path.parts[0]).as_posix())]
|
||||
|
||||
|
||||
def line(graph, save_id="9"):
|
||||
return civitai_parameters(graph, save_id, 512, 768, find_file, file_hash)
|
||||
|
||||
|
||||
class CivitaiLineTests(unittest.TestCase):
|
||||
def test_a_plain_graph_gives_prompt_settings_and_hashes(self):
|
||||
text = line(sd15_graph())
|
||||
prompt, negative, details = text.split("\n")
|
||||
self.assertEqual(prompt, "a lighthouse at dusk, oil paint")
|
||||
self.assertEqual(negative, "Negative prompt: blurry")
|
||||
self.assertTrue(details.startswith("Steps: 20, Sampler: euler, Schedule type: normal, CFG scale: 7, Seed: 1234, Size: 512x768"))
|
||||
self.assertIn("Model hash: aaaaaaaaaa, Model: dreamshaper_8", details)
|
||||
# Rows that are off or at 0 never ran, so they are not credited.
|
||||
self.assertIn('Lora hashes: "detail: bbbbbbbbbb"', details)
|
||||
self.assertIn('Hashes: {"model":"aaaaaaaaaa","lora:detail":"bbbbbbbbbb"}', details)
|
||||
self.assertNotIn("off", details.replace("offset", ""))
|
||||
self.assertNotIn("zero", details)
|
||||
# Lower-case keys Civitai keeps: the ComfyUI tool tag and the technique.
|
||||
self.assertTrue(details.endswith("Version: ComfyUI, engine: ComfyUI, process: txt2img"))
|
||||
|
||||
def test_a_sampler_that_starts_from_a_picture_is_img2img(self):
|
||||
graph = sd15_graph()
|
||||
graph["5"] = {"class_type": "VAEEncode", "inputs": {"pixels": ["11", 0], "vae": ["4", 2]}}
|
||||
graph["11"] = {"class_type": "LoadImage", "inputs": {"image": "x.png"}}
|
||||
self.assertTrue(line(graph).endswith("process: img2img"))
|
||||
graph = sd15_graph()
|
||||
graph["3"]["inputs"]["denoise"] = 0.5
|
||||
self.assertTrue(line(graph).endswith("process: img2img"))
|
||||
|
||||
def test_a_two_prompt_encoder_gives_its_negative_on_the_second_output(self):
|
||||
graph = {
|
||||
"1": {"class_type": "UNETLoader", "inputs": {"unet_name": "krea2_dev.safetensors"}},
|
||||
"20": {"class_type": "AUSBOSS_NODES_Seed", "inputs": {"seed": 777}},
|
||||
"21": {"class_type": "AUSBOSS_NODES_Text", "inputs": {"text": "a red fox in snow"}},
|
||||
"12": {"class_type": "AUSBOSS_NODES_Krea2Encode", "inputs": {"clip": ["2", 0], "prompt": ["21", 0], "negative_prompt": "low quality"}},
|
||||
"14": {"class_type": "KSampler", "inputs": {
|
||||
"seed": ["20", 0], "steps": 8, "cfg": 1, "sampler_name": "euler", "scheduler": "simple", "denoise": 1,
|
||||
"model": ["1", 0], "positive": ["12", 0], "negative": ["12", 1], "latent_image": ["13", 0],
|
||||
}},
|
||||
"15": {"class_type": "VAEDecode", "inputs": {"samples": ["14", 0]}},
|
||||
"9": {"class_type": "AUSBOSS_NODES_SaveImage", "inputs": {"images": ["15", 0]}},
|
||||
}
|
||||
text = line(graph)
|
||||
self.assertTrue(text.startswith("a red fox in snow\nNegative prompt: low quality\nSteps: 8,"))
|
||||
self.assertIn("Seed: 777", text)
|
||||
self.assertIn('Hashes: {"model":"eeeeeeeeee"}', text)
|
||||
|
||||
def test_a_custom_sampler_reads_its_settings_from_the_nodes_it_takes(self):
|
||||
graph = {
|
||||
"1": {"class_type": "UNETLoader", "inputs": {"unet_name": "krea2_dev.safetensors"}},
|
||||
"6": {"class_type": "CLIPTextEncode", "inputs": {"text": "a cabin at night"}},
|
||||
"7": {"class_type": "FluxGuidance", "inputs": {"conditioning": ["6", 0], "guidance": 3.5}},
|
||||
"g": {"class_type": "BasicGuider", "inputs": {"model": ["1", 0], "conditioning": ["7", 0]}},
|
||||
"n": {"class_type": "RandomNoise", "inputs": {"noise_seed": 99}},
|
||||
"s": {"class_type": "KSamplerSelect", "inputs": {"sampler_name": "euler"}},
|
||||
"c": {"class_type": "BasicScheduler", "inputs": {"model": ["1", 0], "steps": 28, "scheduler": "simple", "denoise": 1}},
|
||||
"x": {"class_type": "SamplerCustomAdvanced", "inputs": {"noise": ["n", 0], "guider": ["g", 0], "sampler": ["s", 0], "sigmas": ["c", 0], "latent_image": ["l", 0]}},
|
||||
"d": {"class_type": "VAEDecode", "inputs": {"samples": ["x", 0]}},
|
||||
"9": {"class_type": "AUSBOSS_NODES_SaveImage", "inputs": {"images": ["d", 0]}},
|
||||
}
|
||||
text = line(graph)
|
||||
self.assertTrue(text.startswith("a cabin at night\nSteps: 28, Sampler: euler, Schedule type: simple, Seed: 99,"))
|
||||
self.assertIn("Model: krea2_dev", text)
|
||||
|
||||
def test_only_the_sampler_upstream_of_this_save_is_described(self):
|
||||
graph = sd15_graph()
|
||||
other = {key: dict(node, inputs=dict(node["inputs"])) for key, node in sd15_graph().items()}
|
||||
graph.update({f"o{key}": node for key, node in other.items()})
|
||||
for node in other.values():
|
||||
node["inputs"] = {k: ([f"o{v[0]}", v[1]] if isinstance(v, list) else v) for k, v in node["inputs"].items()}
|
||||
graph["o6"]["inputs"]["text"] = "the other branch"
|
||||
self.assertTrue(line(graph, "o9").startswith("the other branch\n"))
|
||||
self.assertTrue(line(graph, "9").startswith("a lighthouse at dusk"))
|
||||
|
||||
def test_no_sampler_or_an_odd_graph_gives_no_line(self):
|
||||
self.assertIsNone(line({"1": {"class_type": "LoadImage", "inputs": {"image": "x.png"}}, "9": {"class_type": "AUSBOSS_NODES_SaveImage", "inputs": {"images": ["1", 0]}}}))
|
||||
self.assertIsNone(line(None))
|
||||
self.assertIsNone(line({"3": {"class_type": "KSampler", "inputs": {"positive": ["3", 0], "negative": ["3", 0], "steps": ["3", 0]}}}))
|
||||
|
||||
def test_a_missing_model_file_still_gives_the_prompt(self):
|
||||
graph = sd15_graph()
|
||||
graph["4"]["inputs"]["ckpt_name"] = "gone.safetensors"
|
||||
text = line(graph)
|
||||
self.assertIn("Model: gone", text)
|
||||
self.assertNotIn("Model hash", text)
|
||||
|
||||
|
||||
class SaveImageCivitaiTests(unittest.TestCase):
|
||||
def run_node(self, root, **overrides):
|
||||
models = Path(root) / "models"
|
||||
lora = models / "detail.safetensors"
|
||||
lora.parent.mkdir(parents=True, exist_ok=True)
|
||||
lora.write_bytes(b"lora bytes")
|
||||
ckpt = models / "dreamshaper_8.safetensors"
|
||||
ckpt.write_bytes(b"checkpoint bytes")
|
||||
paths = {("checkpoints", "sd/dreamshaper_8.safetensors"): ckpt, ("loras", "detail.safetensors"): lora}
|
||||
|
||||
class FakeFolderPaths:
|
||||
@staticmethod
|
||||
def get_output_directory():
|
||||
return str(root)
|
||||
|
||||
@staticmethod
|
||||
def get_full_path(folder, name):
|
||||
found = paths.get((folder, name))
|
||||
return str(found) if found else None
|
||||
|
||||
values = {
|
||||
"images": torch.rand(1, 8, 16, 3), "filename_prefix": "shot", "format": "png",
|
||||
"save_metadata": True, "civitai_info": True, "preview": False,
|
||||
"prompt": sd15_graph(), "extra_pnginfo": {"workflow": {"nodes": []}}, "unique_id": "9",
|
||||
}
|
||||
values.update(overrides)
|
||||
with patch.object(node_save_image, "folder_paths", FakeFolderPaths), \
|
||||
patch.object(_lora_helpers, "_hash_cache_path", lambda: None):
|
||||
path = Path(node_save_image.AusBossSaveImage().save(**values)["result"][0])
|
||||
return path, hashlib.sha256(b"checkpoint bytes").hexdigest()[:10]
|
||||
|
||||
def test_png_keeps_the_workflow_and_adds_parameters(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
path, model_hash = self.run_node(tmp)
|
||||
with Image.open(path) as image:
|
||||
text = dict(image.text)
|
||||
self.assertIn("workflow", text)
|
||||
self.assertIn("prompt", text)
|
||||
self.assertTrue(text["parameters"].startswith("a lighthouse at dusk, oil paint\n"))
|
||||
self.assertIn(f"Model hash: {model_hash}", text["parameters"])
|
||||
|
||||
def test_webp_puts_parameters_in_user_comment_beside_the_workflow(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
path, model_hash = self.run_node(tmp, format="webp lossless")
|
||||
with Image.open(path) as image:
|
||||
exif = image.getexif()
|
||||
self.assertTrue(exif.get(0x0110).startswith("prompt:"))
|
||||
self.assertTrue(exif.get(0x010F).startswith("workflow:"))
|
||||
comment = exif.get_ifd(0x8769)[0x9286]
|
||||
self.assertTrue(comment.startswith(b"UNICODE\0"))
|
||||
self.assertIn(f"Model hash: {model_hash}", comment[8:].decode("utf-16-be"))
|
||||
|
||||
def test_off_by_default_and_never_without_embed(self):
|
||||
for overrides in ({"civitai_info": False}, {"save_metadata": False}):
|
||||
with self.subTest(**overrides), tempfile.TemporaryDirectory() as tmp:
|
||||
path, _ = self.run_node(tmp, **overrides)
|
||||
with Image.open(path) as image:
|
||||
self.assertNotIn("parameters", image.text)
|
||||
defaults = node_save_image.AusBossSaveImage.INPUT_TYPES()["optional"]["civitai_info"][1]
|
||||
self.assertIs(defaults["default"], False)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -208,5 +208,56 @@ class ReferenceModeTests(unittest.TestCase):
|
||||
node.match(rand_image(2, 8, 8), 1.0)
|
||||
|
||||
|
||||
|
||||
def drifted_edit(seed: int = 30):
|
||||
"""A picture, and the same picture after an edit: the kept parts come back
|
||||
darker with more contrast and colour, and one block is new, bright green."""
|
||||
before = rand_image(1, 48, 48, seed) * 0.6 + 0.2
|
||||
lab = rgb_to_lab(before)
|
||||
lab = torch.cat([lab[..., :1] * 1.1 - 4.0, lab[..., 1:] * 1.25], dim=-1)
|
||||
after = lab_to_rgb(lab)
|
||||
after[:, 30:44, 30:44, :] = torch.tensor([0.25, 0.75, 0.2])
|
||||
new = torch.zeros((1, 48, 48), dtype=torch.bool)
|
||||
new[:, 30:44, 30:44] = True
|
||||
return before, after, new
|
||||
|
||||
|
||||
class KeptMethodTests(unittest.TestCase):
|
||||
def test_undoes_the_drift_on_the_kept_parts(self):
|
||||
before, after, new = drifted_edit()
|
||||
out = match_colors(after, before, 1.0, method="kept")
|
||||
kept = ~new
|
||||
drift = (rgb_to_lab(after) - rgb_to_lab(before)).norm(dim=-1)[kept].mean()
|
||||
left = (rgb_to_lab(out) - rgb_to_lab(before)).norm(dim=-1)[kept].mean()
|
||||
self.assertLess(float(left), float(drift) * 0.25)
|
||||
|
||||
def test_new_content_keeps_its_own_colour(self):
|
||||
before, after, new = drifted_edit()
|
||||
green = rgb_to_lab(after)[new].mean(0)
|
||||
kept = rgb_to_lab(match_colors(after, before, 1.0, method="kept"))[new].mean(0)
|
||||
lab = rgb_to_lab(match_colors(after, before, 1.0, method="lab"))[new].mean(0)
|
||||
# Still clearly green (negative a), close to its own hue...
|
||||
self.assertLess(float(kept[1]), -30.0)
|
||||
self.assertLess(float((kept[1:] - green[1:]).norm()), 20.0)
|
||||
# ...where a whole-picture statistics match drags it much further.
|
||||
self.assertGreater(float((lab[1:] - green[1:]).norm()), float((kept[1:] - green[1:]).norm()))
|
||||
|
||||
def test_unchanged_picture_stays_put(self):
|
||||
image = rand_image(1, 24, 24, seed=31)
|
||||
out = match_colors(image, image.clone(), 1.0, method="kept")
|
||||
self.assertTrue(torch.allclose(out, image, atol=3e-3))
|
||||
|
||||
def test_mask_limits_where_it_measures_and_fixes(self):
|
||||
before, after, _ = drifted_edit()
|
||||
mask = box_mask(48, 48, 0, 24, 0, 48)
|
||||
out = match_colors(after, before, 1.0, mask=mask, method="kept")
|
||||
self.assertTrue(torch.equal(out[:, 24:], after[:, 24:]))
|
||||
self.assertFalse(torch.allclose(out[:, :24], after[:, :24], atol=1e-3))
|
||||
|
||||
def test_needs_the_same_size_reference(self):
|
||||
with self.assertRaisesRegex(ValueError, "same size"):
|
||||
match_colors(rand_image(1, 16, 16), rand_image(1, 8, 8), 1.0, method="kept")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
import torch
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
sys.path.insert(0, str(ROOT))
|
||||
if "nodes" in sys.modules and not hasattr(sys.modules["nodes"], "__path__"):
|
||||
del sys.modules["nodes"]
|
||||
|
||||
from nodes._cut_piece_helpers import POSITIONS, cut_piece, piece_box
|
||||
|
||||
|
||||
def ramp(height: int = 60, width: int = 100) -> torch.Tensor:
|
||||
"""A one-picture BHWC batch whose red channel is the column and green the row, so a cut shows where it came from."""
|
||||
image = torch.ones((1, height, width, 3))
|
||||
image[0, :, :, 0] = torch.arange(width)[None, :] / 1000
|
||||
image[0, :, :, 1] = torch.arange(height)[:, None] / 1000
|
||||
return image
|
||||
|
||||
|
||||
def origin(piece: torch.Tensor) -> tuple[int, int]:
|
||||
"""(row, column) of a cut's top left pixel in the ramp."""
|
||||
return round(float(piece[0, 0, 0, 1]) * 1000), round(float(piece[0, 0, 0, 0]) * 1000)
|
||||
|
||||
|
||||
class PieceBoxTests(unittest.TestCase):
|
||||
def test_each_position_puts_the_piece_where_it_says(self):
|
||||
expected = {
|
||||
"top left": (0, 0), "top": (0, 30), "top right": (0, 60),
|
||||
"left": (10, 0), "center": (10, 30), "right": (10, 60),
|
||||
"bottom left": (20, 0), "bottom": (20, 30), "bottom right": (20, 60),
|
||||
}
|
||||
self.assertEqual(set(expected), set(POSITIONS))
|
||||
for position, (top, left) in expected.items():
|
||||
self.assertEqual(piece_box(60, 100, 40, 40, position), (top, left, top + 40, left + 40), position)
|
||||
|
||||
def test_moves_add_to_the_position_and_stop_at_the_edge(self):
|
||||
self.assertEqual(piece_box(60, 100, 40, 40, "top left", 25, 5), (5, 25, 45, 65))
|
||||
self.assertEqual(piece_box(60, 100, 40, 40, "center", -10, 0), (10, 20, 50, 60))
|
||||
self.assertEqual(piece_box(60, 100, 40, 40, "top left", 500, 500), (20, 60, 60, 100))
|
||||
self.assertEqual(piece_box(60, 100, 40, 40, "bottom right", -500, -500), (0, 0, 40, 40))
|
||||
|
||||
def test_zero_takes_the_full_side_and_too_large_is_cut_to_the_picture(self):
|
||||
self.assertEqual(piece_box(60, 100, 0, 0), (0, 0, 60, 100))
|
||||
self.assertEqual(piece_box(60, 100, 30, 0, "right"), (0, 70, 60, 100))
|
||||
self.assertEqual(piece_box(60, 100, 4000, 4000, "center"), (0, 0, 60, 100))
|
||||
|
||||
def test_an_unknown_position_is_an_error(self):
|
||||
with self.assertRaises(ValueError):
|
||||
piece_box(60, 100, 10, 10, "middle")
|
||||
|
||||
|
||||
class CutPieceTests(unittest.TestCase):
|
||||
def test_the_piece_has_the_size_asked_for_and_comes_from_its_place(self):
|
||||
piece, _rest = cut_piece(ramp(), 30, 20, "top left", 12, 7)
|
||||
self.assertEqual(tuple(piece.shape), (1, 20, 30, 3))
|
||||
self.assertEqual(origin(piece), (7, 12))
|
||||
|
||||
def test_a_full_height_piece_at_the_left_leaves_the_strip_on_its_right(self):
|
||||
# Two parts of different sizes from one picture: 35 px and the other 65 px.
|
||||
piece, rest = cut_piece(ramp(), 35, 0, "top left")
|
||||
self.assertEqual(tuple(piece.shape), (1, 60, 35, 3))
|
||||
self.assertEqual(tuple(rest.shape), (1, 60, 65, 3))
|
||||
self.assertEqual(origin(rest), (0, 35))
|
||||
|
||||
def test_a_full_height_piece_at_the_right_leaves_the_strip_on_its_left(self):
|
||||
_piece, rest = cut_piece(ramp(), 35, 0, "right")
|
||||
self.assertEqual(tuple(rest.shape), (1, 60, 65, 3))
|
||||
self.assertEqual(origin(rest), (0, 0))
|
||||
|
||||
def test_a_full_width_piece_leaves_the_strip_above_or_below(self):
|
||||
_piece, below = cut_piece(ramp(), 0, 25, "top")
|
||||
self.assertEqual(tuple(below.shape), (1, 35, 100, 3))
|
||||
self.assertEqual(origin(below), (25, 0))
|
||||
_piece, above = cut_piece(ramp(), 0, 25, "bottom")
|
||||
self.assertEqual(tuple(above.shape), (1, 35, 100, 3))
|
||||
self.assertEqual(origin(above), (0, 0))
|
||||
|
||||
def test_a_piece_inside_leaves_the_picture_with_its_hole_filled(self):
|
||||
image = torch.ones((1, 60, 100, 3))
|
||||
image[0, 20:40, 40:60] = 0.2
|
||||
_piece, rest = cut_piece(image, 20, 20, "center")
|
||||
self.assertEqual(tuple(rest.shape), tuple(image.shape))
|
||||
self.assertTrue(torch.all(rest == 1.0))
|
||||
self.assertTrue(torch.all(image[0, 20:40, 40:60] == 0.2), "the input is left alone")
|
||||
|
||||
def test_a_batch_is_cut_at_the_same_place_in_every_picture(self):
|
||||
batch = torch.cat([ramp(), ramp() * 0.5])
|
||||
piece, rest = cut_piece(batch, 10, 10, "bottom right")
|
||||
self.assertEqual(tuple(piece.shape), (2, 10, 10, 3))
|
||||
self.assertEqual(rest.shape[0], 2)
|
||||
self.assertTrue(torch.allclose(piece[1], piece[0] * 0.5))
|
||||
|
||||
|
||||
class ToolboxNodeTests(unittest.TestCase):
|
||||
def test_the_node_runs_both_jobs_and_old_calls_still_work(self):
|
||||
from nodes.node_image_toolbox import AusBossImageToolbox
|
||||
|
||||
node = AusBossImageToolbox()
|
||||
image = ramp()
|
||||
pieces, passed = node.run(image, "split sheet at gaps", 1)
|
||||
self.assertEqual(tuple(pieces.shape), tuple(image.shape))
|
||||
self.assertIs(passed, image)
|
||||
piece, rest = node.run(image, "cut a piece", 4, width=40, height=0, position="left")
|
||||
self.assertEqual(tuple(piece.shape), (1, 60, 40, 3))
|
||||
self.assertEqual(tuple(rest.shape), (1, 60, 60, 3))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -279,6 +279,18 @@ class EditLockTests(unittest.TestCase):
|
||||
lock.status = status
|
||||
self.assertIn("did nothing", describe(lock))
|
||||
|
||||
def test_a_vae_and_model_that_do_not_match_say_both_counts(self):
|
||||
source, other, redraw = latents()
|
||||
pred = local_prediction(source, other, redraw)
|
||||
lock = lock_for(source[:, :16].clone())
|
||||
self.assertTrue(torch.equal(run(lock, pred), pred))
|
||||
self.assertEqual(lock.status, "vae")
|
||||
text = describe(lock)
|
||||
self.assertIn("the VAE and the diffusion model don't match", text)
|
||||
self.assertIn(f"your VAE makes 16-channel pictures, the model expects {pred.shape[1]}", text)
|
||||
self.assertIn("workflow's notes", text)
|
||||
self.assertIn("GGUF", text)
|
||||
|
||||
def test_a_grid_one_cell_off_still_locks(self):
|
||||
source, other, redraw = latents(video=False)
|
||||
lock = lock_for(torch.nn.functional.interpolate(source, size=(H + 2, W + 1), mode="bilinear"))
|
||||
|
||||
@@ -455,7 +455,10 @@ class WebpEncodeTests(unittest.TestCase):
|
||||
exif = image.getexif()
|
||||
expected = (frame * 255).round().clamp(0, 255) / 255.0
|
||||
self.assertTrue(torch.allclose(back, expected, atol=1 / 255))
|
||||
self.assertTrue(str(exif.get(0x010F, "")).startswith("prompt:"))
|
||||
# Core ComfyUI's layout: prompt in Model, then "workflow:..." in
|
||||
# Make, which is what ComfyUI's canvas and civitai.com read.
|
||||
self.assertEqual(exif.get(0x0110), "prompt:{}")
|
||||
self.assertEqual(exif.get(0x010F), 'workflow:{"a": 1}')
|
||||
|
||||
|
||||
class SaveImageLocalModeTests(SaveImageNodeTests):
|
||||
|
||||
@@ -32,6 +32,8 @@ from nodes._layout_boxes_helpers import (
|
||||
input_fingerprint,
|
||||
mask_rects,
|
||||
parse_layout,
|
||||
placement_prompt,
|
||||
placement_words,
|
||||
prompt_elements,
|
||||
read_angle,
|
||||
regions_from_pixel_boxes,
|
||||
@@ -350,6 +352,67 @@ class TurnedBoxes(unittest.TestCase):
|
||||
self.assertEqual(element_desc(box(0, 0, 64, 32, "text", "OPEN", "chalk")), "chalk")
|
||||
|
||||
|
||||
def fraction_box(x, y, w, h, kind="obj", text="", desc="", palette=(), **more):
|
||||
"""A box in fractions of the canvas, as the `placement` tests read best."""
|
||||
return {"x": x, "y": y, "w": w, "h": h, "type": kind, "text": text, "desc": desc, "palette": list(palette), **more}
|
||||
|
||||
|
||||
class PlacementSentences(unittest.TestCase):
|
||||
def test_the_form_that_was_tried(self):
|
||||
regions = [
|
||||
fraction_box(0.06, 0.06, 0.46, 0.19, "text", "FRESH", "huge bold black sans-serif letters"),
|
||||
fraction_box(0.52, 0.35, 0.42, 0.50, desc="one ripe orange with a green leaf"),
|
||||
]
|
||||
self.assertEqual(
|
||||
placement_prompt(regions, (1024, 1024)),
|
||||
'The words "FRESH" in huge bold black sans-serif letters, placed top left, from 6% to 52% across and '
|
||||
"6% to 25% down. One ripe orange with a green leaf, placed middle right, from 52% to 94% across and "
|
||||
"35% to 85% down.",
|
||||
)
|
||||
|
||||
def test_no_boxes_no_words(self):
|
||||
self.assertEqual(placement_prompt([], None), "")
|
||||
self.assertEqual(placement_prompt([fraction_box(0.1, 0.1, 0.2, 0.2), fraction_box(0.1, 0.1, 0.2, 0.2, "text")]), "",
|
||||
"a box with no words and no description is left out")
|
||||
|
||||
def test_the_place_in_words(self):
|
||||
for extent, where in (
|
||||
((0, 0, 30, 39), "top left"), ((50, 61, 100, 100), "bottom right"), ((30, 30, 70, 70), "center"),
|
||||
((30, 0, 70, 20), "top center"), ((0, 30, 54, 70), "middle left"), ((46, 30, 100, 70), "middle right"),
|
||||
((0, 40, 40, 60), "middle left"), ((44, 60, 56, 90), "middle center"),
|
||||
):
|
||||
want = "center" if where == "middle center" else where
|
||||
self.assertTrue(placement_words(*extent).startswith(want + ", from "), (extent, placement_words(*extent)))
|
||||
self.assertEqual(placement_words(6, 6, 52, 25), "top left, from 6% to 52% across and 6% to 25% down")
|
||||
|
||||
def test_text_without_a_description_and_text_without_words(self):
|
||||
words = placement_prompt([fraction_box(0.0, 0.0, 0.5, 0.2, "text", " OPEN ", "")])
|
||||
self.assertEqual(words, 'The words "OPEN", placed top left, from 0% to 50% across and 0% to 20% down.')
|
||||
thing = placement_prompt([fraction_box(0.6, 0.7, 0.4, 0.3, "text", " ", "a neon sign.")])
|
||||
self.assertEqual(thing, "A neon sign, placed bottom right, from 60% to 100% across and 70% to 100% down.",
|
||||
"a text box with no words is placed as a thing")
|
||||
|
||||
def test_colors_follow_the_sentence(self):
|
||||
words = placement_prompt([fraction_box(0.25, 0.25, 0.5, 0.5, desc="a cat", palette=["#ff3399", "#00aabb"])])
|
||||
self.assertEqual(words, "A cat, placed center, from 25% to 75% across and 25% to 75% down. Colors: #FF3399, #00AABB.")
|
||||
|
||||
def test_a_turned_box_gives_the_straight_box_around_it_and_its_slant(self):
|
||||
sign = turned(448, 256, 448, 128, 25, "text", "SALE", "red letters")
|
||||
(element,) = prompt_elements([sign], (W, H))
|
||||
top, left, bottom, right = (round(value / 10) for value in element["bbox"])
|
||||
self.assertEqual(
|
||||
placement_prompt([sign], (W, H)),
|
||||
f'The words "SALE" in red letters, tilted about 25 degrees, running downhill to the right, placed center, '
|
||||
f"from {left}% to {right}% across and {top}% to {bottom}% down.",
|
||||
)
|
||||
level = placement_prompt([dict(sign, angle=0)], (W, H))
|
||||
self.assertIn("from 33% to 67% across and 33% to 50% down", level)
|
||||
|
||||
def test_boxes_past_the_edge_are_cut_to_the_canvas(self):
|
||||
words = placement_prompt([fraction_box(-0.2, 0.9, 0.5, 0.3, desc="a dog")])
|
||||
self.assertEqual(words, "A dog, placed bottom left, from 0% to 30% across and 90% to 100% down.")
|
||||
|
||||
|
||||
class ThePreviewWords(unittest.TestCase):
|
||||
def test_words(self):
|
||||
self.assertEqual(box_words({"type": "obj", "desc": "a cat", "text": "x"}), "a cat")
|
||||
|
||||
@@ -54,7 +54,7 @@ class LayoutBoxesNode(unittest.TestCase):
|
||||
|
||||
def test_the_canvas_boxes_make_all_four_outputs(self):
|
||||
out = self.node.draw(width=W, height=H, layout=layout(box(320, 96, 512, 640, desc="a cat"), box(0, 0, W, 64, "text", "OPEN", "neon")))
|
||||
preview, frames, elements, mask, _words = out["result"]
|
||||
preview, frames, elements, mask, _words, _placement = out["result"]
|
||||
self.assertEqual(tuple(preview.shape), (1, 585, 1024, 3), "the canvas's shape, 1024 on its long side")
|
||||
self.assertEqual(preview.dtype, torch.float32)
|
||||
self.assertTrue(0.0 <= float(preview.min()) and float(preview.max()) <= 1.0)
|
||||
@@ -69,7 +69,7 @@ class LayoutBoxesNode(unittest.TestCase):
|
||||
self.assertTrue(torch.equal(mask, expected), "1 inside every box, 0 elsewhere")
|
||||
|
||||
def test_no_boxes(self):
|
||||
preview, frames, elements, mask, _words = self.node.draw(width=512, height=1024)["result"]
|
||||
preview, frames, elements, mask, _words, _placement = self.node.draw(width=512, height=1024)["result"]
|
||||
self.assertEqual(tuple(preview.shape), (1, 1024, 512, 3))
|
||||
self.assertEqual((frames, elements), ([], []))
|
||||
self.assertEqual(tuple(mask.shape), (1, 1024, 512))
|
||||
@@ -116,7 +116,7 @@ class LayoutBoxesNode(unittest.TestCase):
|
||||
def test_a_turned_box_makes_a_turned_mask(self):
|
||||
# 25, -55 and 90 degrees, apart on a 1344 x 768 canvas; each white area is its turned rectangle.
|
||||
boxes = [dict(box(100, 300, 369, 103), angle=25), dict(box(560, 300, 300, 80), angle=-55), dict(box(1000, 250, 200, 100), angle=90)]
|
||||
_preview, frames, elements, mask, _words = self.node.draw(width=W, height=H, layout=layout(*boxes))["result"]
|
||||
_preview, frames, elements, mask, _words, _placement = self.node.draw(width=W, height=H, layout=layout(*boxes))["result"]
|
||||
self.assertEqual(tuple(mask.shape), (1, H, W))
|
||||
def area(x0, x1):
|
||||
return int(mask[0, :, x0:x1].sum())
|
||||
@@ -154,9 +154,16 @@ class LayoutBoxesNode(unittest.TestCase):
|
||||
self.assertIn("the scene in <Picture 1>", scene)
|
||||
self.assertIn("The person from <Picture 2>", scene)
|
||||
|
||||
def test_placement_says_each_box_as_a_sentence(self):
|
||||
boxes = layout(box(0, 0, 672, 192, "text", "OPEN", "neon letters"), box(672, 384, 672, 384, desc="a cat"))
|
||||
words = self.node.draw(width=W, height=H, layout=boxes)["result"][5]
|
||||
self.assertEqual(words, 'The words "OPEN" in neon letters, placed top left, from 0% to 50% across and 0% to 25% down. '
|
||||
"A cat, placed middle right, from 50% to 100% across and 50% to 100% down.")
|
||||
self.assertEqual(self.node.draw(width=W, height=H)["result"][5], "")
|
||||
|
||||
def test_a_turned_text_box_tells_the_model_its_slant(self):
|
||||
sign = dict(box(613, 300, 369, 102, "text", "No Phones", "bold black letters on a white sign"), angle=25.2)
|
||||
_preview, frames, elements, _mask, _words = self.node.draw(width=W, height=H, layout=layout(sign))["result"]
|
||||
_preview, frames, elements, _mask, _words, _placement = self.node.draw(width=W, height=H, layout=layout(sign))["result"]
|
||||
self.assertEqual(elements[0]["desc"], "bold black letters on a white sign, tilted about 25 degrees, running downhill to the right")
|
||||
self.assertEqual(elements[0]["text"], "No Phones")
|
||||
level = self.node.draw(width=W, height=H, layout=layout(dict(sign, angle=0)))["result"]
|
||||
@@ -168,7 +175,7 @@ class LayoutBoxesNode(unittest.TestCase):
|
||||
# shape, so the box is turned there and the mask is a true rectangle on the photo.
|
||||
picture = torch.rand(1, 750, 1000, 3)
|
||||
words = {"x": 0.4, "y": 0.4, "w": 0.3, "h": 0.08, "type": "text", "text": "SALE", "desc": "red letters", "angle": -30}
|
||||
_preview, frames, _elements, mask, _words = self.node.draw(background=picture, width=1024, height=1536, layout=layout(words))["result"]
|
||||
_preview, frames, _elements, mask, _words, _placement = self.node.draw(background=picture, width=1024, height=1536, layout=layout(words))["result"]
|
||||
self.assertEqual(tuple(mask.shape), (1, 750, 1000))
|
||||
self.assertLess(abs(int(mask.sum()) - 300 * 60), 2 * (300 + 60), "300 x 60 photo pixels, turned")
|
||||
cx, cy, a = 550, 330, math.radians(-30)
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
"""The viewer's Cut: the planes face the camera and split the model's depth
|
||||
by the shares asked, and Pause for Shot's mesh keeps what lies between."""
|
||||
|
||||
import math
|
||||
import os
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
import numpy as np
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
from nodes._mesh_cut_helpers import camera_view, clean_cut, cut_planes, kept_faces, model_transform # noqa: E402
|
||||
|
||||
CAMERA = {"position": {"x": 0, "y": 0, "z": 5}, "target": {"x": 0, "y": 0, "z": 0}}
|
||||
|
||||
|
||||
def slab():
|
||||
"""A row of small triangles from z = -1 (far) to z = 1 (near)."""
|
||||
points, faces = [], []
|
||||
for i, z in enumerate(np.linspace(-1, 1, 21)):
|
||||
points += [(-0.1, 0, z), (0.1, 0, z), (0, 0.1, z)]
|
||||
faces.append((3 * i, 3 * i + 1, 3 * i + 2))
|
||||
return np.array(points, dtype=float), np.array(faces)
|
||||
|
||||
|
||||
class MeshCutTests(unittest.TestCase):
|
||||
def test_nothing_cut_is_none(self):
|
||||
self.assertIsNone(clean_cut(None))
|
||||
self.assertIsNone(clean_cut({"front": 0, "back": 0}))
|
||||
self.assertIsNone(clean_cut({"front": "x", "back": True}))
|
||||
|
||||
def test_cut_always_leaves_some_model(self):
|
||||
cut = clean_cut({"front": 70, "back": 70})
|
||||
self.assertEqual(cut["front"], 70)
|
||||
self.assertLessEqual(cut["front"] + cut["back"], 99)
|
||||
|
||||
def test_back_half_comes_off(self):
|
||||
points, faces = slab()
|
||||
keep = kept_faces(points, faces, None, camera_view(CAMERA), {"front": 0, "back": 50})
|
||||
middles = points[faces].mean(1)[:, 2]
|
||||
self.assertTrue((middles[keep] >= -1e-9).all())
|
||||
self.assertTrue((middles[~keep] < 0).all())
|
||||
|
||||
def test_planes_follow_the_viewer_turn(self):
|
||||
points, faces = slab()
|
||||
# The model spun 90 degrees about Y: its depth now runs across the view.
|
||||
turn = [{"position": {"x": 0, "y": 0, "z": 0}, "scale": {"x": 1, "y": 1, "z": 1},
|
||||
"quaternion": {"x": 0, "y": math.sin(math.pi / 4), "z": 0, "w": math.cos(math.pi / 4)}}]
|
||||
near, far = cut_planes(points, model_transform(turn), camera_view(CAMERA), {"front": 0, "back": 50})
|
||||
# Seen from +Z the turned slab is only 0.2 deep (its triangles' width).
|
||||
self.assertAlmostEqual(far - near, 0.1, places=6)
|
||||
|
||||
def test_front_cut_keeps_the_far_part(self):
|
||||
points, faces = slab()
|
||||
keep = kept_faces(points, faces, None, camera_view(CAMERA), {"front": 25, "back": 0})
|
||||
middles = points[faces].mean(1)[:, 2]
|
||||
self.assertTrue((middles[keep] <= 0.5 + 1e-9).all())
|
||||
self.assertEqual(int(keep.sum()), 16)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import unittest
|
||||
@@ -70,5 +71,43 @@ class PanoramaOffTests(unittest.TestCase):
|
||||
self.assertNotIn("panorama", ps.clean_shot({}))
|
||||
|
||||
|
||||
class ViewInputTests(unittest.TestCase):
|
||||
"""A run that goes straight through has no Continue answer, so the 360's
|
||||
Turn and the Cut come from the hidden `view` input, which the page fills
|
||||
from the viewer as Run is pressed. An input, so that ComfyUI runs the
|
||||
node again when one of them changes."""
|
||||
|
||||
def test_settings_are_read_from_the_input(self):
|
||||
view = json.dumps({"sky": {"turn": 90, "tilt": 2}, "cut": {"back": 0.3}, "panorama": False})
|
||||
found = ps.view_settings(view)
|
||||
self.assertEqual(found["sky"], {"turn": 90, "tilt": 2})
|
||||
self.assertIn("cut", found)
|
||||
self.assertNotIn("panorama", found)
|
||||
|
||||
def test_empty_or_junk_gives_nothing(self):
|
||||
for junk in ("", " ", "{", "[1, 2]", '"text"', "x" * (ps.MAX_VIEW + 1), None, 3):
|
||||
self.assertEqual(ps.view_settings(junk), {})
|
||||
|
||||
def test_the_input_changes_the_backdrop(self):
|
||||
import torch
|
||||
|
||||
node = ps.AusBossPauseShot()
|
||||
pano = torch.zeros((1, 32, 64, 3))
|
||||
pano[:, :, :32, 0] = 1.0 # one half red, the other black
|
||||
camera = {"position": {"x": 0, "y": 0, "z": 2}, "target": {"x": 0, "y": 0, "z": 0}, "fov": 50}
|
||||
|
||||
def backdrop(view):
|
||||
return node.wait([], camera, 32, 32, False, panorama=pano, view=view)[4]
|
||||
|
||||
still = backdrop("")
|
||||
turned = backdrop(json.dumps({"sky": {"turn": 90}}))
|
||||
self.assertGreater(float((still - turned).abs().max()), 0.5)
|
||||
self.assertTrue(torch.equal(still, backdrop(json.dumps({"sky": {"turn": 0}}))))
|
||||
|
||||
def test_the_saved_workflow_is_not_read(self):
|
||||
# Everything the result depends on is an input ComfyUI compares.
|
||||
self.assertNotIn("extra_pnginfo", ps.AusBossPauseShot.INPUT_TYPES()["hidden"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
"""Photo Camera: the photo's camera puts the model where the crop's camera did.
|
||||
|
||||
A point on the model is seen by Pixal3D's crop camera at one pixel of the
|
||||
crop, which is one pixel of the photo. The camera the node hands the viewer
|
||||
must see that point at the same pixel of the whole photo.
|
||||
"""
|
||||
|
||||
import math
|
||||
import os
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
import numpy as np
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
from nodes._backdrop_helpers import euler_zxy_matrix, quaternion_matrix # noqa: E402
|
||||
from nodes._photo_camera_helpers import BACKDROP_TURN, photo_camera, subject_box # noqa: E402
|
||||
|
||||
|
||||
def project(camera, point, width, height):
|
||||
"""three.js perspective projection of a world point, in photo pixels."""
|
||||
pos = np.array([camera["position"][k] for k in "xyz"])
|
||||
rot = quaternion_matrix([camera["quaternion"][k] for k in "xyzw"])
|
||||
v = rot.T @ (np.asarray(point, dtype=float) - pos)
|
||||
tan_v = math.tan(math.radians(camera["fov"]) / 2)
|
||||
nx = v[0] / (-v[2] * tan_v * camera["aspect"])
|
||||
ny = v[1] / (-v[2] * tan_v)
|
||||
return (nx + 1) / 2 * width, (1 - ny) / 2 * height
|
||||
|
||||
|
||||
def crop_pixel(point, box, crop_fov):
|
||||
"""Where Pixal3D's crop camera sees a point, in photo pixels."""
|
||||
x1, y1, x2, _ = box
|
||||
side = x2 - x1
|
||||
d = 0.5 / math.tan(math.radians(crop_fov) / 2)
|
||||
depth = d - point[2]
|
||||
f = 0.5 / math.tan(math.radians(crop_fov) / 2) # crop widths per unit at depth 1
|
||||
u = 0.5 + f * point[0] / depth
|
||||
v = 0.5 - f * point[1] / depth
|
||||
return x1 + u * side, y1 + v * side
|
||||
|
||||
|
||||
class PhotoCameraTests(unittest.TestCase):
|
||||
def test_centred_subject_looks_straight_ahead(self):
|
||||
out = photo_camera((100, 300, 700, 900), (800, 1200), 55.0)
|
||||
cam = out["camera_info"]
|
||||
self.assertAlmostEqual(cam["target"]["x"], 0.0, places=9)
|
||||
self.assertGreater(out["crop_fov"], 0)
|
||||
self.assertLess(out["crop_fov"], 55.0)
|
||||
# Centred photo on a 2048 canvas: the same place the shipped workflow uses.
|
||||
self.assertEqual(out["strip_width"], round(2048 * 55 / 360))
|
||||
self.assertEqual(out["strip_x"], round(1024 - out["strip_width"] / 2))
|
||||
|
||||
def test_model_points_land_where_the_crop_put_them(self):
|
||||
width, height = 832, 1216
|
||||
# (box, fov, worst edge error, worst middle error) as shares of the width.
|
||||
# A turned camera, not a shifted sensor: the further the person stands
|
||||
# off centre and the wider the lens, the more the model's far edges move.
|
||||
cases = (
|
||||
((200, 400, 650, 850), 40.0, 0.002, 0.002), # centred
|
||||
((60, 500, 560, 1000), 50.0, 0.03, 0.003), # a fifth of the frame off centre
|
||||
((400, 200, 780, 580), 65.0, 0.08, 0.012), # far up in a corner, wide lens
|
||||
)
|
||||
for box, fov, edge, middle in cases:
|
||||
out = photo_camera(box, (width, height), fov)
|
||||
worst = 0.0
|
||||
for point in ((0, 0, 0), (0.3, 0.4, 0.1), (-0.4, -0.45, -0.2), (0.45, -0.3, 0.25)):
|
||||
a = np.array(project(out["camera_info"], point, width, height))
|
||||
b = np.array(crop_pixel(point, box, out["crop_fov"]))
|
||||
worst = max(worst, float(np.abs(a - b).max()))
|
||||
self.assertLess(worst, edge * width, (box, fov, worst))
|
||||
a = np.array(project(out["camera_info"], (0, 0, 0), width, height))
|
||||
b = np.array(crop_pixel((0, 0, 0), box, out["crop_fov"]))
|
||||
self.assertLess(float(np.abs(a - b).max()), middle * width, (box, fov))
|
||||
|
||||
def test_strip_sits_where_the_camera_axis_meets_the_360(self):
|
||||
width, height = 832, 1216
|
||||
out = photo_camera((60, 500, 560, 1000), (width, height), 50.0)
|
||||
cam = out["camera_info"]
|
||||
ahead = quaternion_matrix([cam["quaternion"][k] for k in "xyzw"]) @ np.array([0, 0, -1.0])
|
||||
turned = euler_zxy_matrix(0, math.radians(BACKDROP_TURN), 0).T @ ahead
|
||||
u = math.atan2(turned[2], turned[0]) / (2 * math.pi) + 0.5
|
||||
v = math.asin(max(-1, min(1, turned[1]))) / math.pi + 0.5
|
||||
centre_x = out["strip_x"] + out["strip_width"] / 2
|
||||
strip_height = round(out["strip_width"] * height / width)
|
||||
centre_y = out["strip_y"] + strip_height / 2
|
||||
self.assertAlmostEqual(centre_x, u * 2048, delta=1.0)
|
||||
self.assertAlmostEqual(centre_y, (1 - v) * 1024, delta=1.0)
|
||||
|
||||
def test_subject_box_is_a_padded_square(self):
|
||||
mask = np.zeros((1216, 832))
|
||||
mask[300:1000, 200:500] = 1.0
|
||||
(x1, y1, x2, y2), (w, h) = subject_box(mask, 1.1, 1024)
|
||||
self.assertEqual((w, h), (700, 1024))
|
||||
self.assertAlmostEqual(x2 - x1, y2 - y1)
|
||||
scale = 1024 / 1216
|
||||
self.assertAlmostEqual(x2 - x1, int(700 * scale * 1.1), delta=2)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -455,6 +455,27 @@ class FormatTests(unittest.TestCase):
|
||||
with av.open(str(path)) as container:
|
||||
self.assertEqual(container.metadata.get(key), "ausboss-test")
|
||||
|
||||
def test_animated_webp_carries_the_workflow_as_core_writes_it(self):
|
||||
# Core's animated WebP: prompt in EXIF Model, the workflow in Make,
|
||||
# each as "key:json". gif has no place for it and stays clean.
|
||||
from PIL import Image
|
||||
|
||||
metadata = {"prompt": '{"1": {}}', "workflow": '{"nodes": []}'}
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
path = Path(tmp) / "loop.webp"
|
||||
encode_video(path, gradient_batch(3, 32, 32), 8.0, None, 23, metadata, "webp")
|
||||
with Image.open(path) as image:
|
||||
exif = image.getexif()
|
||||
self.assertEqual(exif.get(0x0110), 'prompt:{"1": {}}')
|
||||
self.assertEqual(exif.get(0x010F), 'workflow:{"nodes": []}')
|
||||
clean = Path(tmp) / "clean.webp"
|
||||
encode_video(clean, gradient_batch(3, 32, 32), 8.0, None, 23, None, "webp")
|
||||
with Image.open(clean) as image:
|
||||
self.assertEqual(len(image.getexif()), 0)
|
||||
gif = Path(tmp) / "loop.gif"
|
||||
encode_video(gif, gradient_batch(3, 32, 32), 8.0, None, 23, metadata, "gif")
|
||||
self.assertNotIn(b"workflow", gif.read_bytes())
|
||||
|
||||
def test_stream_options_map_crf_onto_each_codecs_own_dial(self):
|
||||
options = _video_save_helpers.stream_options
|
||||
self.assertEqual(options("libx264", 19)["crf"], "19")
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
"""ComfyUI runs a node again only when one of its inputs changes. The saved
|
||||
workflow that rides along with a run (EXTRA_PNGINFO) is not one of them, so a
|
||||
node that took a setting from it would hand back an old result after that
|
||||
setting changed: Pause for Shot once read the viewer's 360 Turn that way. Only
|
||||
the save nodes read it, to write it into the files they save."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
import unittest
|
||||
|
||||
NODES = Path(__file__).resolve().parent.parent / "nodes"
|
||||
# Embedding the workflow in a saved file, as ComfyUI's own Save Image does.
|
||||
READ_TO_EMBED = {"node_save_image.py", "node_save_video.py"}
|
||||
|
||||
|
||||
class WorkflowIsNotAnInputTests(unittest.TestCase):
|
||||
def test_only_save_nodes_read_the_saved_workflow(self):
|
||||
readers = sorted(path.name for path in NODES.glob("*.py") if "EXTRA_PNGINFO" in path.read_text(encoding="utf-8"))
|
||||
self.assertEqual([name for name in readers if name not in READ_TO_EMBED], [],
|
||||
"A setting a node's result depends on must be one of its inputs, "
|
||||
"not read from the saved workflow: ComfyUI would not run the node again when it changes.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,113 @@
|
||||
// A linked setting on the Crop + Rotate + Pad nodes runs with the wired value
|
||||
// (js/shared/transform_wired.mjs). A Float of 24 wired into Megapixels
|
||||
// resized to 24 MP while the card summary, the MP field and the size readout
|
||||
// all said 16.00 MP, the widget's own value, and read as a 16 MP cap.
|
||||
|
||||
import assert from "node:assert/strict";
|
||||
import fs from "node:fs";
|
||||
import test from "node:test";
|
||||
|
||||
import { wiredFieldText, wiredNumber, wiredResize, wiredSummaryParts, wiredSwitch } from "../js/shared/transform_wired.mjs";
|
||||
|
||||
const WIDGETS = { feather: 24, canvas_multiple: 1, resize_to_megapixels: true, megapixels: 16, resolution_steps: 1 };
|
||||
|
||||
// A crop node whose inputs named in `wires` are linked to the given source
|
||||
// nodes, as plain objects.
|
||||
function cropNode(values = {}, wires = {}) {
|
||||
const nodes = new Map();
|
||||
const links = {};
|
||||
const graph = { links, getNodeById: (id) => nodes.get(id) ?? null };
|
||||
const merged = { ...WIDGETS, ...values };
|
||||
const node = {
|
||||
id: 1, graph,
|
||||
widgets: Object.entries(merged).map(([name, value]) => ({ name, value })),
|
||||
inputs: Object.keys(merged).map((name) => ({ name, widget: { name }, link: null })),
|
||||
};
|
||||
nodes.set(1, node);
|
||||
let next = 10;
|
||||
for (const [name, source] of Object.entries(wires)) {
|
||||
const id = next++;
|
||||
source.id = id;
|
||||
source.mode ??= 0;
|
||||
source.inputs ??= [];
|
||||
nodes.set(id, source);
|
||||
links[id] = { id, origin_id: id, origin_slot: 0, target_id: 1 };
|
||||
node.inputs.find((input) => input.name === name).link = id;
|
||||
}
|
||||
return node;
|
||||
}
|
||||
|
||||
const float = (value) => ({ type: "PrimitiveFloat", widgets: [{ name: "value", value }] });
|
||||
const int = (value) => ({ type: "PrimitiveInt", widgets: [{ name: "value", value }] });
|
||||
const math = () => ({ type: "AUSBOSS_NODES_MathExpression", widgets: [{ name: "expression", value: "a*2" }] });
|
||||
|
||||
test("unlinked settings read the widgets, as before", () => {
|
||||
const node = cropNode();
|
||||
assert.deepEqual(wiredNumber(node, "megapixels", 1), { value: 16, linked: false, known: true });
|
||||
assert.deepEqual(wiredSummaryParts(node), ["feather 24 px", "16.00 MP"]);
|
||||
assert.deepEqual(wiredResize(node), { megapixels: 16, steps: 1 });
|
||||
assert.equal(wiredFieldText(wiredNumber(node, "megapixels", 1), (v) => `${v} MP`), null);
|
||||
});
|
||||
|
||||
test("a typed number wired into Megapixels shows that number, past the 16 MP range", () => {
|
||||
const node = cropNode({}, { megapixels: float(24) });
|
||||
assert.deepEqual(wiredNumber(node, "megapixels", 1), { value: 24, linked: true, known: true });
|
||||
assert.deepEqual(wiredSummaryParts(node), ["feather 24 px", "24.00 MP"]);
|
||||
assert.deepEqual(wiredResize(node), { megapixels: 24, steps: 1 });
|
||||
assert.equal(wiredFieldText(wiredNumber(node, "megapixels", 1), (v) => `${v.toFixed(2)} MP`), "24.00 MP");
|
||||
});
|
||||
|
||||
test("a calculated value says it comes from a link instead of showing the widget's", () => {
|
||||
const node = cropNode({}, { megapixels: math() });
|
||||
assert.deepEqual(wiredNumber(node, "megapixels", 1), { value: null, linked: true, known: false });
|
||||
assert.deepEqual(wiredSummaryParts(node), ["feather 24 px", "MP from a link"]);
|
||||
assert.deepEqual(wiredResize(node), { unknown: true });
|
||||
assert.equal(wiredFieldText(wiredNumber(node, "megapixels", 1), String), "from a link");
|
||||
});
|
||||
|
||||
test("the other summary values follow their links too", () => {
|
||||
const node = cropNode({ resolution_steps: 1 }, { feather: int(8), canvas_multiple: math(), resolution_steps: int(32) });
|
||||
assert.deepEqual(wiredSummaryParts(node), ["feather 8 px", "align from a link", "16.00 MP"]);
|
||||
const steps = cropNode({}, { resolution_steps: int(32) });
|
||||
assert.deepEqual(wiredSummaryParts(steps), ["feather 24 px", "16.00 MP", "÷32"]);
|
||||
assert.deepEqual(wiredSummaryParts(cropNode({}, { feather: math() })), ["feather from a link", "16.00 MP"]);
|
||||
assert.deepEqual(wiredSummaryParts(cropNode({}, { resolution_steps: math() })), ["feather 24 px", "16.00 MP", "step from a link"]);
|
||||
});
|
||||
|
||||
test("a wired resize switch decides whether the resize shows", () => {
|
||||
const off = cropNode({}, { resize_to_megapixels: { type: "PrimitiveBoolean", widgets: [{ name: "value", value: false }] } });
|
||||
assert.deepEqual(wiredSwitch(off, "resize_to_megapixels", false), { value: false, linked: true, known: true });
|
||||
assert.deepEqual(wiredSummaryParts(off), ["feather 24 px"]);
|
||||
assert.equal(wiredResize(off), null);
|
||||
const typedOn = cropNode({ resize_to_megapixels: false }, { resize_to_megapixels: { type: "PrimitiveBoolean", widgets: [{ name: "value", value: true }] } });
|
||||
assert.deepEqual(wiredResize(typedOn), { megapixels: 16, steps: 1 });
|
||||
const unknown = cropNode({ resize_to_megapixels: false }, { resize_to_megapixels: math() });
|
||||
assert.deepEqual(wiredSummaryParts(unknown), ["feather 24 px", "resize from a link", "16.00 MP"]);
|
||||
assert.deepEqual(wiredResize(unknown), { unknown: true });
|
||||
});
|
||||
|
||||
test("a muted source is unknown, not the widget's value", () => {
|
||||
const source = float(24);
|
||||
source.mode = 2;
|
||||
const node = cropNode({}, { megapixels: source });
|
||||
assert.deepEqual(wiredSummaryParts(node), ["feather 24 px", "MP from a link"]);
|
||||
});
|
||||
|
||||
test("a node without the resize inputs (video) only gets feather and Align", () => {
|
||||
const node = cropNode();
|
||||
node.widgets = node.widgets.filter((item) => !["resize_to_megapixels", "megapixels", "resolution_steps"].includes(item.name));
|
||||
assert.deepEqual(wiredSummaryParts(node), ["feather 24 px"]);
|
||||
assert.equal(wiredResize(node), null);
|
||||
});
|
||||
|
||||
test("the transform face reads the summary, the fields and the size readout through the wire", () => {
|
||||
const source = fs.readFileSync(new URL("../js/shared/transform_editor.mjs", import.meta.url), "utf8");
|
||||
const summary = source.slice(source.indexOf("export function transformGroupSummary"), source.indexOf("function buildTransformGroup"));
|
||||
assert.match(summary, /wiredSummaryParts\(node\)/);
|
||||
assert.doesNotMatch(summary, /value\(node, "megapixels"/);
|
||||
const request = source.slice(source.indexOf("function resizeRequest"), source.indexOf("function resizeFromLink"));
|
||||
assert.match(request, /wiredResize\(node\)/);
|
||||
for (const name of ["feather", "canvas_multiple", "megapixels", "resolution_steps"]) {
|
||||
assert.match(source, new RegExp(`wiredStandIn\\(node, "${name}"`), `${name} has no stand-in on the face`);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,31 @@
|
||||
// Pause for Shot's hidden `view` input: the viewer's 360 settings and Cut as
|
||||
// one string, the same string for the same settings.
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { readFileSync } from "node:fs";
|
||||
|
||||
import { viewValue } from "../js/shared/viewer_view.mjs";
|
||||
|
||||
test("the same settings give the same string, whatever the key order", () => {
|
||||
const a = viewValue({ sky: { turn: 90, tilt: 2 }, cut: { back: 0.3, front: 0 } });
|
||||
const b = viewValue({ cut: { front: 0, back: 0.3 }, sky: { tilt: 2, turn: 90 } });
|
||||
assert.equal(a, b);
|
||||
assert.deepEqual(JSON.parse(a), { sky: { tilt: 2, turn: 90 }, cut: { back: 0.3, front: 0 } });
|
||||
});
|
||||
|
||||
test("a changed setting changes the string", () => {
|
||||
assert.notEqual(viewValue({ sky: { turn: 90 } }), viewValue({ sky: { turn: 0 } }));
|
||||
assert.notEqual(viewValue({ sky: { turn: 90 } }), viewValue({ sky: { turn: 90 }, cut: { back: 0.2 } }));
|
||||
});
|
||||
|
||||
test("only the 360 settings and the Cut ride along; nothing saved gives nothing", () => {
|
||||
assert.equal(viewValue({ sky: { turn: 45 }, panorama: false, other: 1 }), JSON.stringify({ sky: { turn: 45 } }));
|
||||
for (const junk of [undefined, null, "", "x", 3, [], { sky: "x", cut: [1] }]) assert.equal(viewValue(junk), "");
|
||||
});
|
||||
|
||||
test("the pause fills the input as the prompt is built, and the card hides it", () => {
|
||||
const pause = readFileSync(new URL("../js/pause_shot/index.js", import.meta.url), "utf8");
|
||||
assert.match(pause, /view\.serializeValue\s*=\s*\(\)\s*=>\s*viewValue\(/);
|
||||
const cards = readFileSync(new URL("../js/widget_cards/index.js", import.meta.url), "utf8");
|
||||
assert.match(cards, /AUSBOSS_NODES_PauseShot:[^\n]*hide: \["view"\], socketless: \["view"\]/);
|
||||
});
|
||||
@@ -441,3 +441,24 @@ test("a lifted socket loses the row position the frontend stamped on it", () =>
|
||||
assert.equal("pos" in loose, false);
|
||||
assert.equal(loose.widget, undefined);
|
||||
});
|
||||
|
||||
// A row folded into a group shows only while that group is open, and only a
|
||||
// header row ({ group, label }) opens it. A card that folds rows away without
|
||||
// one leaves them out of reach (Photo Camera's Crop margin and 360 width).
|
||||
test("every group a card folds rows into has a header that opens it", () => {
|
||||
const source = readFileSync(join(ROOT, "js", "widget_cards", "index.js"), "utf-8");
|
||||
const ids = [...source.matchAll(/\n {2}(AUSBOSS_NODES_\w+): \{/g)].map((match) => match[1]);
|
||||
assert.ok(ids.length > 10, "no card entries found");
|
||||
for (const id of ids) {
|
||||
const lines = cardEntry(id).split("\n");
|
||||
const headers = new Set();
|
||||
const folded = new Set();
|
||||
for (const line of lines) {
|
||||
const group = line.match(/\bgroup: "([^"]+)"/)?.[1];
|
||||
if (!group) continue;
|
||||
if (/\b(widget|pair): /.test(line)) folded.add(group);
|
||||
else headers.add(group);
|
||||
}
|
||||
for (const group of folded) assert.ok(headers.has(group), `${id} folds rows into "${group}" with no header row to open it`);
|
||||
}
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user