Compare commits

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

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

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

Fixes #387
2026-11-21 09:23:56 -06:00
ausboss 9ab4365245 Merge pull request #385 from ausboss/fix/latent-size-chips-keep-default
Latent Size: ratio chips keep the current megapixels by default
2026-11-20 22:33:46 -06:00
ausboss 5dfbcdd99c Merge remote-tracking branch 'origin/main' into fix/latent-size-chips-keep-default
# Conflicts:
#	CHANGELOG.md
2026-11-20 22:33:13 -06:00
ausboss 20f860d5ff Merge pull request #382 from ausboss/feat/h3-full-prompt-tab
H3 Prompt Writer: a Full prompt tab to see and change the written prompt
2026-11-20 22:32:59 -06:00
ausboss 44edcc633c Latent Size: ratio chips keep the current megapixels by default
Fixes #377. The gear setting lived only in browser storage, so private
windows lost it every time. It now starts on; turning it off still brings
back the ~1MP jump.
2026-11-20 21:29:18 -06:00
ausboss c99425cef1 Merge branch 'main' of https://github.com/ausboss/ComfyUI-AusBoss into feat/h3-full-prompt-tab
# Conflicts:
#	CHANGELOG.md
2026-11-20 21:26:03 -06:00
ausboss 743126d86f H3 Prompt Writer help: drop the reset-and-edit-again line 2026-11-20 15:42:37 -06:00
ausboss fb430afca1 Merge branch 'main' of https://github.com/ausboss/ComfyUI-AusBoss into feat/h3-full-prompt-tab
# Conflicts:
#	CHANGELOG.md
2026-11-20 15:39:03 -06:00
ausboss a606d34b97 H3 Prompt Writer: a Full prompt tab to see and change the written prompt
The node gets two tabs. Simple is the card as before and stays the
default. Full prompt shows the prompt the node wrote on its last run, in a
box you can edit; when it holds an edit, that text is sent to H3 instead.
An amber dot on the tab, a note under the box and a line on the Simple tab
say an edit is being sent. Reset to written clears it.

- New optional `full_prompt` input, appended last, with a "" fallback for
  older saves. The node now returns the written prompt as ui output
  (`written_prompt`); `write` is unchanged and `run` wraps it.
- Widget card: `when` gets the node as well as the values, a panel row can
  grow, and `refreshByHand` lets a panel redraw the card.
- Fix: a hidden textarea or panel row stayed visible, because the later
  `display:block` rules for those rows beat `.hidden`.
2026-11-20 14:03:47 -06:00
38 changed files with 2029 additions and 56 deletions
+38
View File
@@ -2,6 +2,44 @@
All notable changes to ComfyUI-AusBoss are documented here.
## Unreleased
- **LoRA Loader: set a LoRA's strength with a wire.** Drag a number wire,
from a slider or a Float node, onto any row and that row's strength follows
it. The row's box turns dashed teal and shows the number coming in; click
it to find the source, or right-click the row to unlink. The CLIP strength
keeps its ratio to the model strength (#388).
- **Node faces show Chinese when ComfyUI's language is Chinese.** The
labels, buttons, choices and tooltips the pack draws on its nodes, such as
the cards on FlashVSR and Image Resize, H3 Prompt Writer, Workflow Switches
and the video and image crop faces, now follow Settings > Language
(Chinese, in Simplified characters). Reload the page after changing the language. Nothing
saved in a workflow changes, and text with no Chinese yet stays English.
H3 Prompt Writer's socket names are translated too.
- **H3 Prompt Writer: see and change the full prompt.** A new **Full
prompt** tab at the top of the node shows the prompt it wrote on its last
run. Edit it there, for example to take out one camera move, and H3 gets
your text as it is. An amber dot shows an edit is being sent, and **Reset
to written** goes back to the node's own prompt. The **Simple** tab works
as before and stays the default.
- **Latent Size's ratio chips keep your megapixels.** Clicking a ratio chip
now changes the shape at the size you set, instead of jumping back to about
one megapixel. The old jump is still in the gear: turn off **Chips keep
current budget**. The setting is kept in the browser, so a private window
forgot it every time; it now starts on.
- **The pack loads on Python 3.10 again.** On a 3.10 install, such as some
Stability Matrix setups, the whole pack failed to load with
`No module named 'tomllib'`. It now loads there with nothing extra to
install (#387).
- **Workflow Note finds models in Stability Matrix's shared folders.**
A row whose folder uses an old name, `clip` or `unet`, was never checked
("This install has no model folder") even with the file in place. Those
rows are now checked like `text_encoders` and `diffusion_models`, the
names ComfyUI files them under. When the install also reads a kind of
model from a folder with a different name, such as Stability Matrix's
`Data/Models/Lora`, the card names that folder under the usual one, so
you know where your files are found and where a new one can go (#386).
## 2.26.6 - 2026-11-20
- **Image Toolbox's help page says what happens with too many pieces.**
+7
View File
@@ -150,6 +150,13 @@ example_workflows/ # example workflows (regular workflow JSON, not API JSON)
- Category: `🆎 AusBoss/<Group>`. The emoji is safe here — categories reach
the frontend as JSON and are never printed to the console at import time.
- Every node gets `DESCRIPTION`, input `tooltip`s, and `OUTPUT_TOOLTIPS`.
- Words a node face draws itself (card labels, buttons, choices, tooltips)
are translated for a Chinese ComfyUI by `js/i18n/index.js`: add the English
text and its Chinese to `js/shared/i18n_zh.mjs`, or to `STAYS_ENGLISH` there
when it should not change. Text with no entry stays English, and a widget's
name and value are never translated. Never read a label back from the DOM
to decide something; keep that in state (the translator changes the text).
`tests/i18n.test.mjs` fails on a card word with no entry.
- IMAGE tensors are BHWC float batches; MASK is BHW. Return tuples always,
even for one output: `(value,)`.
- Console output at import time must stay ASCII — ComfyUI on Windows often
+3 -3
View File
@@ -11,7 +11,6 @@ of taking the whole pack down, so one broken node never hides the rest.
import importlib
import os
import tomllib
import traceback
# One entry per file in nodes/, kept alphabetical. The order has no
@@ -102,9 +101,10 @@ __all__ = ["NODE_CLASS_MAPPINGS", "NODE_DISPLAY_NAME_MAPPINGS", "WEB_DIRECTORY"]
def _read_version():
"""Version straight from pyproject.toml so it is never duplicated."""
try:
from .nodes._pyproject import read_project
pyproject = os.path.join(os.path.dirname(__file__), "pyproject.toml")
with open(pyproject, "rb") as f:
version = tomllib.load(f).get("project", {}).get("version")
version = read_project(pyproject).get("version")
return version if isinstance(version, str) and version.strip() else "unknown"
except Exception:
return "unknown"
+19
View File
@@ -164,6 +164,17 @@ own, with blank lines around it, it is for the whole clip.
Already wrote H3's six parts yourself? Paste them in and they go through as
they are.
## See and change the full prompt
The **Full prompt** tab at the top of the node shows the prompt the node wrote
on its last run. To change one thing, such as taking out "A slow push in.",
edit it there and run again: H3 gets your text exactly as it is in the box. An
amber dot on the tab shows that an edit is being sent. **Reset to written**
throws the edit away and goes back to what the **Simple** tab writes.
While an edit is in place, changes on the Simple tab do nothing, because your
text is sent instead.
## What you can plug in
- **picture_1** to **picture_4**: your pictures.
@@ -224,6 +235,8 @@ as not plugged in.
- **Moments on the beat** (`cut_on_beat`, under **More**): moves each moment onto
the nearest beat of the song. Off keeps your own seconds.
- **Language** (`language`, under **More**): the language of the words in quotes.
- **Full prompt** (`full_prompt`, on the Full prompt tab): your own edit of the
finished prompt. Empty means the node's own prompt is sent.
## Tips
@@ -280,5 +293,11 @@ that sentence the picture's street came back halfway through on 2 of 2. With no
place in your lines H3 has nothing else to use, so it stayed in the picture's
place on 2 of 2.
The Full prompt tab is filled from the node's run, so it shows nothing until
the workflow has run once. The node still writes its own prompt on every run, a
model on `clip` included, so the tab can show it next to your edit and Reset can
go back to it. The last written prompt is kept with the node in a saved
workflow.
H3's own rewriter runs only on paid services, and the open model reads a prompt as
it is. This node does that job on your machine, with no model needed.
+24
View File
@@ -134,6 +134,30 @@ A group that a switch turns on and off shows the lock on its header
instead. The LoRAs in it keep plain grips, so each one is still yours to
turn on or off. Click the header's lock to take the group over.
## A strength set by a wire
To set one LoRA's strength from somewhere else, such as a slider, a Float
node or a sweep, drag that number's wire onto the row and let go. The row
under the pointer lights up teal while you aim; anywhere across the row
works. The wire runs to that row and its strength box turns dashed teal,
showing the number coming in. The bar behind the name follows it.
- **Click the dashed box** to jump to the node the number comes from.
- **Right-click the row → Unlink strength** to take the wire off. The row
goes back to the strength it had.
- The wire sets the model strength. The CLIP strength keeps the same ratio
to it, so a row at 1.0 / 0.5 fed 0.6 runs at 0.6 / 0.3.
- Gear menu → **Linked strength wires** shows the wire (the default), shows
it only while the pointer is on the loader or the number's node, or hides
it.
### Technical details
Each linked row has its own input, `strength_<row id>`, which exists only
while something is linked to that row. It takes FLOAT or INT. In an API
prompt, give a row's input the row's `id` from the `loras` text, for example
`"strength_ra1": 0.6`. A name that matches no row is ignored.
## Strength bars
Every named row paints a center-zero bar behind its name: teal grows right
+1 -1
View File
@@ -2,7 +2,7 @@
Pick a picture size by shape and megapixels, or by dragging. Use it in place of an Empty Latent node: it gives you the width, the height and a blank latent of that size.
- **Shape:** the left button selects landscape or portrait. Ratio chips follow that choice; square retains it for the next selection. Clicking a chip uses its generated size near one megapixel. Enable **Chips keep current budget** in the gear to retain the current area.
- **Shape:** the left button selects landscape or portrait. Ratio chips follow that choice; square retains it for the next selection. Clicking a chip changes the shape and keeps your current megapixels. To have a chip jump to its size near one megapixel instead, turn off **Chips keep current budget** in the gear.
- **Canvas:** drag a side to change one dimension; drag the corner to scale both. Shift frees the corner ratio, Alt removes snapping, and Escape cancels the drag. The bright readout shows the size, megapixels and ratio; an amber dot means the size is off the snap grid, which a typed size can be. Arrow keys nudge the focused canvas by the snap step, or by 8 px with Shift.
- **Size & budget:** scrub or type W, H, or MP. Typed dimensions are preserved exactly. The swap button exchanges dimensions. The **Sizes** chips are ready-made sizes for the current ratio, small to large. They show while the shape is one of the ratio chips; any other shape shows one greyed-out "custom" chip.
- **Gear:** set the **Snap step**, edit the **Ratio rail**, choose the **Latent family** (`latent`) and **Batch size** (`batch_size`), and hide the **Dot grid** or **MP cost curves**. **Snap step** (8, 16, 32 or 64; starts at 32) is the grid that drags, arrow keys and chips land on. The **Ratio rail** is the list of ratio chips, typed as `1:1, 21:9`. The display options apply to every Latent Size node in this browser; latent family and batch size (1 to 64) belong to this node.
+6
View File
@@ -68,6 +68,12 @@ answered on the same line as the button.
the ComfyUI server for its own model lists.
- **↻ check files** re-runs the check after you move files in. ComfyUI's own
**R** refresh triggers it as well.
- Launchers such as Stability Matrix keep models in shared folders of their
own, for example `Data/Models/Lora`. Files there count, and the card names
such a folder under the usual heading ("also read from ..."), so you can
see where your files are found and put new ones there. The old folder
names `clip` and `unet` are checked as `text_encoders` and
`diffusion_models`, the names ComfyUI uses for them.
- Folder `input` is for a sample image or clip shipped with the workflow: it
is looked for in `ComfyUI/input`.
- Clicking a file name copies it — handy for searching a loader's picker.
+14
View File
@@ -0,0 +1,14 @@
// On a Chinese ComfyUI (Settings > Language), the pack's own node faces show
// Chinese. js/shared/i18n.mjs holds the rules, js/shared/i18n_zh.mjs the words.
// The language is read when the page loads, so a change in Settings shows
// after a reload.
import { app } from "../../../scripts/app.js";
import { chineseActive, followFaces, useLocaleSource } from "../shared/i18n.mjs";
app.registerExtension({
name: "ausboss.i18n",
async setup() {
useLocaleSource(() => app.ui?.settings?.getSettingValue?.("Comfy.Locale"));
if (chineseActive()) followFaces(document.body);
},
});
+81 -7
View File
@@ -10,6 +10,9 @@ import {
openSettingsMenu,
} from "../shared/settings_menu.mjs";
import { compactAction } from "../shared/panel_controls.mjs";
import {
STRENGTH_LINK_STYLES, WIRE_LOOKS, installStrengthLinks, sourceTitle, sourceValue, syncStrengthLinks, unlinkRow,
} from "./strength_links.mjs";
import { makeScrubInput } from "../shared/scrub_input.mjs";
import { isAppShortcut, keepKeyInField } from "../shared/canvas_passthrough.mjs";
import { resetUnknownValues } from "../shared/widget_card_math.mjs";
@@ -143,6 +146,14 @@ const SETTINGS_SCHEMA = [
hint: "Two strength boxes per row on this node. New nodes always start "
+ "unified.",
},
{
key: "strength_wires", label: "Linked strength wires", type: "choice",
options: WIRE_LOOKS, default: "shown",
hint: "A number wire dropped on a row sets that row's strength. shown: "
+ "the wire runs to the row. on hover: it shows while the pointer is on "
+ "this node or its source. hidden: never drawn; the row still says "
+ "what sets it.",
},
{
key: "strength_bars", label: "Strength bars", type: "toggle",
default: true,
@@ -223,7 +234,7 @@ function installStyles() {
if (document.getElementById("ausboss-lora-styles")) return;
const style = document.createElement("style");
style.id = "ausboss-lora-styles";
style.textContent = `
style.textContent = STRENGTH_LINK_STYLES + `
.ausboss-lora-panel, .ausboss-lora-panel *,
.ausboss-lora-pop, .ausboss-lora-pop *,
.ausboss-lora-hoverthumb { box-sizing: border-box; }
@@ -917,7 +928,11 @@ function strengthBox(state, index, key) {
input.dataset.ausbossStrength = key;
// A short name; the tooltip above stays as the longer description.
input.setAttribute("aria-label", key === "strength" ? "Model strength" : "CLIP strength");
input.__ausbossRead = () => state.rows[index]?.[key].toFixed(2) ?? "1.00";
input.__ausbossRead = () => {
const entry = linkedEntry(state, index);
if (entry) return sourceValue(entry)?.toFixed(2) ?? "link";
return state.rows[index]?.[key].toFixed(2) ?? "1.00";
};
input.__ausbossTint = () => state.rows[index] && applyRangeTint(input, state.rows[index], key);
ensureRange(state, state.rows[index].name);
@@ -931,6 +946,16 @@ function strengthBox(state, index, key) {
let drag = null;
input.addEventListener("pointerdown", (event) => {
if (event.button !== 0 || !input.readOnly) return;
// A linked strength is set by its wire: a click shows where it comes from.
const entry = linkedEntry(state, index);
if (entry) {
event.preventDefault();
if (entry.source) {
app.canvas?.selectNode?.(entry.source);
app.canvas?.centerOnNode?.(entry.source);
}
return;
}
drag = { x: event.clientX, y: event.clientY, start: state.rows[index][key], scrubbed: false };
input.setPointerCapture(event.pointerId);
event.preventDefault();
@@ -1002,6 +1027,34 @@ function strengthBox(state, index, key) {
return box;
}
function linkedEntry(state, index) {
const row = state.rows[index];
return row ? state.linkedStrengths?.get(row.id) ?? null : null;
}
// Mark the rows a wire sets: the strength box shows the incoming number,
// and its tooltip names where it comes from.
function decorateStrengthLinks(state) {
if (state.disposed || state.box) return;
state.linkedStrengths = syncStrengthLinks(state);
for (const box of state.panel.querySelectorAll(".ausboss-lora-strengthbox")) {
const rowId = box.closest(".ausboss-lora-row")?.dataset.rowId;
const entry = rowId ? state.linkedStrengths.get(rowId) : null;
box.classList.toggle("linked", Boolean(entry));
const input = box.querySelector(".ausboss-lora-strength");
if (!input) continue;
input.title = entry
? `Set by "${sourceTitle(entry)}". Click to show it. Right-click the row to unlink.`
: input.dataset.baseTitle ?? "";
if (input.readOnly && input.__ausbossRead) input.value = input.__ausbossRead();
}
const signature = [...state.linkedStrengths].map(([id, entry]) => `${id}:${sourceValue(entry)}`).join("|");
if (signature !== state.linkSignature) {
state.linkSignature = signature;
decorateRows(state);
}
}
// ---------- picker ----------
// Width of the longest label in the picker's font. Remembered across opens,
@@ -1362,6 +1415,7 @@ function openPicker(state, index, anchor, { keyboard = false } = {}) {
const open = anyFolderOpen(entries, currentFolds());
foldAll.hidden = !entries.some((entry) => entry.kind === "folder");
foldAll.textContent = open ? "Fold all" : "Open all";
foldAll.dataset.folds = open ? "1" : "";
foldAll.title = open ? "Fold every folder in this list" : "Open every folder in this list";
if (highlight >= 0) highlight = clampHighlight(highlight, options.length);
list.textContent = "";
@@ -1391,7 +1445,7 @@ function openPicker(state, index, anchor, { keyboard = false } = {}) {
};
foldAll.addEventListener("click", () => {
toggleFolder(null, foldAll.textContent === "Fold all", "search");
toggleFolder(null, foldAll.dataset.folds === "1", "search");
});
search.addEventListener("input", () => { highlight = -1; searchCollapsed = new Set(); renderList(); });
search.addEventListener("keydown", (event) => {
@@ -1857,6 +1911,13 @@ function openRowMenu(state, index, event) {
commitRows(state, rows, { structural: true });
fitNode(state);
};
if (state.linkedStrengths?.has(row.id)) {
item("Unlink strength", () => {
unlinkRow(state, row.id);
decorateStrengthLinks(state);
});
menu.append(el("div", "ausboss-lora-menu-rule"));
}
item("Insert empty LoRA above", () => insertEmpty(index));
item("Insert empty LoRA below", () => insertEmpty(index + 1));
item("Move up", () => commitGroups(state, moveRowInStack(state.rows, index, -1)),
@@ -2383,7 +2444,12 @@ function renameOwnedGroup(state, from, to) {
// value update - the bar scale can change whenever any row's strength does.
function decorateRows(state) {
const showBars = state.settings?.strength_bars !== false;
const scale = strengthBarScale(state.rows);
// A linked row's bar shows the number coming in on its wire.
const shown = state.rows.map((row, index) => {
const value = sourceValue(linkedEntry(state, index));
return value === null ? row : { ...row, strength: value };
});
const scale = strengthBarScale(shown);
const dups = duplicateLoraKeys(state.rows);
state.panel.querySelectorAll(".ausboss-lora-name").forEach((button, index) => {
const row = state.rows[index];
@@ -2394,8 +2460,8 @@ function decorateRows(state) {
}
const notes = [row.name];
if (showBars) {
button.style.background = strengthBarBackground(row.strength, scale);
notes.push(`Model strength ${row.strength.toFixed(2)}; `
button.style.background = strengthBarBackground(shown[index].strength, scale);
notes.push(`Model strength ${shown[index].strength.toFixed(2)}; `
+ `bar edges are ±${scale.toFixed(2)}`);
} else {
button.style.background = "";
@@ -2440,6 +2506,7 @@ function updateRowValues(state) {
master.classList.toggle("mixed", overall === "mixed");
}
decorateRows(state);
decorateStrengthLinks(state);
}
// ---------- absorb the loader chain ----------
@@ -2921,7 +2988,7 @@ function renderRows(state) {
let nameDrag = null;
name.addEventListener("pointerdown", (event) => {
if (event.button !== 0 || !row.name
|| state.settings?.name_scrub === false) return;
|| state.settings?.name_scrub === false || linkedEntry(state, index)) return;
nameDrag = { x: event.clientX, y: event.clientY,
start: state.rows[index].strength, scrubbed: false };
name.setPointerCapture(event.pointerId);
@@ -3013,6 +3080,7 @@ function renderRows(state) {
stack.append(actions);
body.append(stack);
decorateRows(state);
decorateStrengthLinks(state);
state.lockSignature = null;
refreshLocks(state);
// Names refit whenever the stack's box changes - the node was resized,
@@ -3144,6 +3212,7 @@ function ensureRedrawHook() {
if (state.node.graph !== shown) continue;
syncRows(state);
refreshLocks(state);
decorateStrengthLinks(state);
}
}, 250);
});
@@ -3249,6 +3318,7 @@ function watchBox(box) {
function unmountCard(state, { resize = true } = {}) {
liveCards.delete(state);
state.disposed = true;
state.unlinkStrengthWatch?.();
state.nameObserver?.disconnect();
closePopup();
try {
@@ -3342,6 +3412,10 @@ function mountCard(node, { box = null, separatorWidget = null, onMissingWidget =
panel.style.height = `calc(100% + ${reclaim}px)`;
}
if (!box) {
state.unlinkStrengthWatch = installStrengthLinks(state, app);
state.onStrengthLinks = () => decorateStrengthLinks(state);
}
renderRows(state);
refreshAvailable(state);
node.setSize?.([Math.max(336, node.size?.[0] || 336), node.computeSize?.()[1] || 220]);
+303
View File
@@ -0,0 +1,303 @@
// A row's strength can come in on a link: drag a number wire onto a row and
// let go. The link lands on a hidden input named strength_<row id> that sits
// on the node's left edge at that row's height. Nothing marks the spot until
// a number wire is dragged over the node: then the row under the pointer
// lights up. Once linked, the row's strength box shows the incoming value,
// and the wire is shown, shown on hover, or hidden (gear menu).
//
// How the input stays out of sight: the frontend treats an input that names
// a widget as a widget's socket. It leaves such a socket out of the node's
// height, draws it only while a link is dragged or hovered or once it is
// connected, and keeps the position it is given when no widget by that name
// exists. The socket is also drawn in a clear colour, so a linked row shows
// no dot. The frontend does not hit-test such a socket either, so the
// loader's getInputOnPos finds the row under a drop itself.
//
// The frontend also removes, when a workflow loads, every widget socket
// whose widget it cannot find. So the input is saved as a plain input and
// becomes a widget socket again once the workflow has loaded.
import { chainCallback } from "../shared/index.mjs";
const NAME = /^strength_[A-Za-z0-9_-]{1,64}$/;
const CLEAR = "rgba(0,0,0,0)";
// Where the hidden socket sits from the node's left edge, as the frontend
// places a widget's socket.
const SOCKET_X = 10;
const NUMBER_TYPES = new Set(["FLOAT", "INT"]);
export const WIRE_LOOKS = ["shown", "on hover", "hidden"];
// The canvas skips drawing a wire it is told is being dragged, shadow and
// all, so a hidden wire carries that mark. The mark is not saved.
export const rowInputName = (rowId) => `strength_${rowId}`;
export const isRowInput = (input) => typeof input?.name === "string" && NAME.test(input.name);
const rowIdOf = (input) => input.name.slice("strength_".length);
const states = new Set();
let watching = false;
let hoverTarget = null;
function canvasOf(app) {
return app?.canvas ?? null;
}
function clientPoint(app, x, y) {
const canvas = canvasOf(app);
const rect = canvas.canvas.getBoundingClientRect();
const scale = canvas.ds.scale || 1;
const [ox, oy] = canvas.ds.offset;
return [rect.left + (x + ox) * scale, rect.top + (y + oy) * scale];
}
function graphPoint(app, clientX, clientY) {
const canvas = canvasOf(app);
const rect = canvas.canvas.getBoundingClientRect();
const scale = canvas.ds.scale || 1;
const [ox, oy] = canvas.ds.offset;
return [(clientX - rect.left) / scale - ox, (clientY - rect.top) / scale - oy];
}
function linkOf(graph, id) {
if (id === null || id === undefined || !graph) return null;
return graph.links?.get?.(id) ?? graph.links?.[id] ?? graph._links?.get?.(id) ?? null;
}
function rowElements(state) {
return [...state.panel.querySelectorAll(".ausboss-lora-row")]
.filter((element) => !element.classList.contains("folded-away"));
}
function rowElement(state, rowId) {
return rowElements(state).find((element) => element.dataset.rowId === rowId) ?? null;
}
// The row under a point in client pixels: anywhere across the node's width,
// so a drop does not have to hit the strength box itself.
function rowAtClient(state, clientX, clientY) {
const node = state.node;
const app = state.app;
const [left] = clientPoint(app, node.pos[0], node.pos[1]);
const [right] = clientPoint(app, node.pos[0] + node.size[0], node.pos[1]);
if (clientX < left - 4 || clientX > right + 4) return null;
for (const element of rowElements(state)) {
const rect = element.getBoundingClientRect();
if (clientY >= rect.top - 3 && clientY <= rect.bottom + 3) return element;
}
return null;
}
function isNumberDrag(app) {
const connector = canvasOf(app)?.linkConnector;
if (!connector?.isConnecting) return false;
if (connector.state?.connectingTo && connector.state.connectingTo !== "input") return false;
const types = (connector.renderLinks ?? []).map((link) => String(link?.fromSlot?.type ?? ""));
return types.length > 0 && types.every((type) => type.split(",").some((part) => NUMBER_TYPES.has(part.trim())));
}
export function rowInputs(node) {
return (node.inputs ?? []).filter(isRowInput);
}
// {row id: {input, link, source}} for every row a link sets now.
export function linkedRows(node) {
const found = new Map();
for (const input of rowInputs(node)) {
const link = linkOf(node.graph, input.link);
if (!link) continue;
const source = node.graph?.getNodeById?.(link.origin_id) ?? null;
found.set(rowIdOf(input), { input, link, source });
}
return found;
}
// What a linked row shows: the source's own number when it has one in
// sight (a Float or Int node, a slider), else just that it is linked.
export function sourceValue(entry) {
const widgets = entry?.source?.widgets ?? [];
const widget = widgets.find((item) => item.name === "value") ?? widgets.find((item) => typeof item.value === "number");
return typeof widget?.value === "number" ? widget.value : null;
}
export function sourceTitle(entry) {
return String(entry?.source?.title || entry?.source?.type || "another node");
}
function placeInput(state, input) {
const element = rowElement(state, rowIdOf(input));
if (!element) return;
const rect = element.getBoundingClientRect();
const [, y] = graphPoint(state.app, 0, rect.top + rect.height / 2);
const pos = [SOCKET_X, Math.round((y - state.node.pos[1]) * 10) / 10];
if (input.pos?.[0] !== pos[0] || input.pos?.[1] !== pos[1]) input.pos = pos;
}
const HIDDEN = () => ({ label: " ", localized_name: " ", color_on: CLEAR, color_off: CLEAR });
function hideInput(input) {
Object.assign(input, HIDDEN());
if (!input.widget) input.widget = { name: input.name };
}
function ensureRowInput(state, rowId) {
const node = state.node;
const name = rowInputName(rowId);
let input = node.inputs?.find((item) => item.name === name);
if (!input) input = node.addInput(name, "FLOAT,INT", { ...HIDDEN(), widget: { name } });
placeInput(state, input);
return input;
}
export function unlinkRow(state, rowId) {
const node = state.node;
const index = (node.inputs ?? []).findIndex((input) => input.name === rowInputName(rowId));
if (index < 0) return;
node.removeInput(index);
node.setDirtyCanvas?.(true, true);
}
function wireHidden(state, entry) {
const look = state.settings?.strength_wires ?? "shown";
if (look === "hidden") return true;
return look === "on hover" && hoverTarget !== state.node && hoverTarget !== entry.source;
}
function setWireHidden(entry, hidden) {
const link = entry.link;
if (hidden === Boolean(link._dragging)) return false;
// A wire the user is moving keeps the mark the canvas gave it.
if (!hidden && link.__ausbossHidden !== true) return false;
link._dragging = hidden;
link.__ausbossHidden = hidden;
return true;
}
// Keep the hidden inputs in step with the rows: drop the ones nothing is
// linked to or whose row is gone, move each to its row, colour its wire.
// Returns the linked rows.
export function syncStrengthLinks(state) {
const node = state.node;
const connecting = canvasOf(state.app)?.linkConnector?.isConnecting;
// Rows not yet read from a workflow that is loading say nothing about
// which inputs are stale.
const rowsCurrent = state.widget && state.renderedValue === state.widget.value;
if (!connecting && rowsCurrent) {
const ids = new Set(state.rows.map((row) => row.id));
for (let index = (node.inputs?.length ?? 0) - 1; index >= 0; index -= 1) {
const input = node.inputs[index];
if (!isRowInput(input)) continue;
if (!ids.has(rowIdOf(input)) || !linkOf(node.graph, input.link)) node.removeInput(index);
}
}
for (const input of rowInputs(node)) placeInput(state, input);
const linked = linkedRows(node);
let changed = false;
for (const entry of linked.values()) {
if (setWireHidden(entry, wireHidden(state, entry))) changed = true;
}
if (changed) node.setDirtyCanvas?.(true, true);
return linked;
}
function paintTarget(element) {
for (const state of states) {
for (const row of state.panel.querySelectorAll(".ausboss-lora-row.link-target")) {
if (row !== element) row.classList.remove("link-target");
}
}
element?.classList.add("link-target");
}
function watchPointer(app) {
if (watching) return;
watching = true;
window.addEventListener("pointermove", (event) => {
let target = null;
let over = null;
for (const state of states) {
if (state.disposed) continue;
const node = state.node;
const [x, y] = graphPoint(app, event.clientX, event.clientY);
if (x >= node.pos[0] && x <= node.pos[0] + node.size[0] && y >= node.pos[1] - 30 && y <= node.pos[1] + node.size[1]) over = node;
if (!target && !state.box && !state.readOnly && isNumberDrag(app)) target = rowAtClient(state, event.clientX, event.clientY);
}
paintTarget(target);
if (!over) {
const [x, y] = graphPoint(app, event.clientX, event.clientY);
over = canvasOf(app)?.graph?.getNodeOnPos?.(x, y) ?? null;
}
if (over !== hoverTarget) {
hoverTarget = over;
for (const state of states) if (!state.disposed) syncStrengthLinks(state);
}
}, true);
// Nodes 2.0 finishes a link drag in its own pointerup handler and never asks
// the node which input is under the pointer. So there the drop on a row is
// made here, before that handler runs; it then finds the link made.
window.addEventListener("pointerup", (event) => {
if (globalThis.LiteGraph?.vueNodesMode && isNumberDrag(app)) {
for (const state of states) {
if (state.disposed || state.box || state.readOnly) continue;
const element = rowAtClient(state, event.clientX, event.clientY);
if (element?.dataset.rowId) {
dropOnRow(state, element.dataset.rowId, canvasOf(app).linkConnector);
break;
}
}
}
requestAnimationFrame(() => {
paintTarget(null);
for (const state of states) if (!state.disposed) state.onStrengthLinks?.();
});
}, true);
}
function dropOnRow(state, rowId, connector) {
const input = ensureRowInput(state, rowId);
for (const link of connector.renderLinks ?? []) {
if (link.node === state.node) continue;
link.connectToInput?.(state.node, input, connector.events);
}
}
export function installStrengthLinks(state, app) {
state.app = app;
states.add(state);
watchPointer(app);
const node = state.node;
// Saved as plain inputs (see the top of this file), hidden again on load.
chainCallback(node, "onSerialize", (data) => {
if (!Array.isArray(data?.inputs)) return;
data.inputs = data.inputs.map((input) => {
if (!isRowInput(input)) return input;
const { widget, ...plain } = input;
return plain;
});
});
const rehide = () => {
for (const input of rowInputs(node)) hideInput(input);
requestAnimationFrame(() => { if (!state.disposed) state.onStrengthLinks?.(); });
};
chainCallback(node, "onGraphConfigured", rehide);
chainCallback(node, "onConfigure", () => requestAnimationFrame(rehide));
const original = node.getInputOnPos;
node.getInputOnPos = function (pos) {
const found = typeof original === "function" ? original.call(this, pos) : undefined;
if (found && !isRowInput(found)) return found;
if (state.disposed || state.box || state.readOnly || !isNumberDrag(app)) return found;
const [clientX, clientY] = clientPoint(app, pos[0], pos[1]);
const element = rowAtClient(state, clientX, clientY);
if (!element?.dataset.rowId) return found;
return ensureRowInput(state, element.dataset.rowId);
};
return () => {
states.delete(state);
if (node.getInputOnPos !== original) delete node.getInputOnPos;
};
}
export const STRENGTH_LINK_STYLES = `
.ausboss-lora-row.link-target{outline:2px solid #00b4aa;outline-offset:-1px;background:rgba(0,180,170,.14);}
.ausboss-lora-strengthbox.linked{border-color:transparent;outline:2px dashed rgba(0,180,170,.7);outline-offset:-2px;}
.ausboss-lora-strengthbox.linked .ausboss-lora-strength{color:#5fe3d9;cursor:pointer;}
.ausboss-lora-strengthbox.linked .ausboss-lora-step{display:none;}
`;
+3 -3
View File
@@ -97,9 +97,9 @@ const SETTINGS_SCHEMA = [
},
{
key: "chips_keep_budget", label: "Chips keep current budget", type: "toggle",
default: false,
hint: "Ratio chips reshape at your current megapixels instead of jumping "
+ "to that ratio's ~1MP default size.",
default: true,
hint: "On: ratio chips keep your current megapixels. Off: a chip jumps "
+ "to that ratio's ~1MP size.",
},
{
key: "rail", label: "Ratio rail", type: "text",
+156
View File
@@ -0,0 +1,156 @@
// H3 Prompt Writer's two tabs. Simple is the card as it always was: your
// lines, the chips and the menus. Full prompt shows the prompt the node wrote
// on its last run, in a box you can change; whatever you type there is what
// H3 gets, until Reset to written. The `full_prompt` widget underneath holds
// the edit (empty when there is none), so it saves and loads like any value.
import { app } from "../../../scripts/app.js";
import { chainCallback, notifyAusbossChange } from "./index.mjs";
import { keepKeyInField } from "./canvas_passthrough.mjs";
import { compactAction } from "./panel_controls.mjs";
import { THEME as T } from "./theme.mjs";
import { commitWidgetValue } from "./widget_card_math.mjs";
import { FULL, SIMPLE, TAB_PROPERTY, WRITTEN_PROPERTY, boxText, editValue, isEdited, promptTab, writtenFromOutput } from "./h3_full_prompt_math.mjs";
export { FULL, SIMPLE, isEdited, promptTab };
const CSS_ID = "ausboss-h3-full-prompt-css";
const EDITED_NOTE = "Edited by you. This text is sent as it is; the Simple tab is not used until you reset.";
function ensureCss() {
if (document.getElementById(CSS_ID)) return;
const style = document.createElement("style");
style.id = CSS_ID;
style.textContent = `
.ausboss-prompt-tabs .dot{display:inline-block;width:6px;height:6px;margin-left:6px;border-radius:3px;background:${T.warn};vertical-align:1px}
.ausboss-prompt-tabs .dot[hidden]{display:none}
.ausboss-full-prompt{display:flex;flex-direction:column;gap:6px;height:100%;min-height:0}
.ausboss-full-prompt-area{display:block;flex:1 1 auto;width:100%;min-width:0;min-height:0;padding:5px 8px;box-sizing:border-box;border:1px solid transparent;border-radius:6px;background:${T.fill};color:${T.ink};font:11.5px/1.45 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;resize:none;overflow:auto}
.ausboss-full-prompt-area:focus{outline:none;border-color:${T.brand}}
.ausboss-full-prompt-area::placeholder{color:${T.faint}}
.ausboss-full-prompt-note{flex:none;padding:5px 8px;border-radius:5px;background:${T.warnSoft};color:${T.warnInk};font-size:11px;line-height:1.35}
.ausboss-full-prompt-note[hidden]{display:none}
.ausboss-full-prompt-foot{flex:none;display:flex;align-items:center;gap:8px;min-height:24px}
.ausboss-full-prompt-foot span{flex:1 1 auto;min-width:0;color:${T.faint};font-size:11px;overflow:hidden;white-space:nowrap;text-overflow:ellipsis}
.ausboss-simple-edited{display:flex;align-items:center;height:100%;padding:0 8px;box-sizing:border-box;border-radius:5px;background:${T.warnSoft};color:${T.warnInk};font-size:11px;line-height:1.3}
`;
document.head.append(style);
}
const widgetOf = (node, name) => node.widgets?.find((widget) => widget.name === name) ?? null;
const redraw = (node) => (node.__ausbossCard?.refreshByHand ?? node.__ausbossCard?.refresh)?.();
const writtenOf = (node) => String(node.properties?.[WRITTEN_PROPERTY] ?? "");
function setEdit(node, value) {
const widget = widgetOf(node, "full_prompt");
if (!widget || widget.value === value) return;
commitWidgetValue(node, widget, value, app?.canvas);
node.graph?.setDirtyCanvas?.(true, true);
}
// The tab switch at the top of the card. The open tab is a display choice
// kept on the node, not a value: it changes nothing that is sent.
export function promptTabs(node) {
ensureCss();
const element = document.createElement("div");
element.className = "ausboss-card-seg ausboss-prompt-tabs";
const make = (tab, label, title) => {
const button = document.createElement("button");
button.type = "button";
button.textContent = label;
button.title = title;
button.addEventListener("click", () => {
if (promptTab(node) === tab) return;
node.properties ??= {};
node.properties[TAB_PROPERTY] = tab;
redraw(node);
});
element.append(button);
return button;
};
const simple = make(SIMPLE, "Simple", "Your lines, the pictures and the menus. The node writes the full prompt from them.");
const full = make(FULL, "Full prompt", "The prompt the node wrote on its last run. Change it here to send your own.");
const dot = document.createElement("span");
dot.className = "dot";
dot.title = "Edited: this text is sent instead of the Simple tab.";
full.append(dot);
return {
element,
sync(values) {
const tab = promptTab(node);
simple.classList.toggle("on", tab === SIMPLE);
full.classList.toggle("on", tab === FULL);
dot.hidden = !isEdited(values);
},
};
}
// One line on the Simple tab while an edit is being sent instead.
export function simpleEditedNote() {
ensureCss();
const element = document.createElement("div");
element.className = "ausboss-simple-edited";
element.textContent = "Full prompt is edited, so these lines are not used until you reset it there.";
return { element };
}
// The Full prompt tab: the box, a note while it holds an edit, and Reset.
export function fullPromptBox(node) {
ensureCss();
const element = document.createElement("div");
element.className = "ausboss-full-prompt";
const area = document.createElement("textarea");
// Not the card's own textarea class: the script's colouring takes the
// first box with that class, and it belongs to the script.
area.className = "ausboss-full-prompt-area";
area.spellcheck = false;
area.placeholder = "Run the workflow once and the prompt the node writes shows here. Change it to send your own.";
area.title = "What H3 gets. Type here to send your own text instead of the node's.";
const note = document.createElement("div");
note.className = "ausboss-full-prompt-note";
note.textContent = EDITED_NOTE;
const foot = document.createElement("div");
foot.className = "ausboss-full-prompt-foot";
const hint = document.createElement("span");
hint.textContent = "Filled in after each run.";
const reset = compactAction("Reset to written", "Throw your edit away and send what the Simple tab writes again.");
foot.append(hint, reset);
element.append(area, note, foot);
area.addEventListener("input", () => {
setEdit(node, editValue(area.value, writtenOf(node)));
redraw(node);
});
area.addEventListener("change", () => notifyAusbossChange());
area.addEventListener("keydown", (event) => {
keepKeyInField(event, { weights: true });
if (event.key === "Escape") area.blur();
});
// Leaving the box shows what is sent: emptied, it is the written prompt again.
area.addEventListener("blur", () => redraw(node));
reset.addEventListener("click", () => {
setEdit(node, "");
area.value = writtenOf(node);
notifyAusbossChange();
redraw(node);
});
// Each run hands back the prompt the node wrote. It is kept on the node, so
// a saved workflow opens with it.
chainCallback(node, "onExecuted", (output) => {
const written = writtenFromOutput(output);
if (written === null) return;
node.properties ??= {};
node.properties[WRITTEN_PROPERTY] = written;
redraw(node);
});
return {
element,
sync(values) {
const edited = isEdited(values);
if (document.activeElement !== area) area.value = boxText(values, writtenOf(node));
note.hidden = !edited;
reset.disabled = !edited;
},
};
}
+39
View File
@@ -0,0 +1,39 @@
// What H3 Prompt Writer's Full prompt tab decides, kept apart from the DOM so
// it can be tested. The node writes the prompt; the tab shows what it wrote
// after a run, and text typed there is sent in its place until Reset.
export const SIMPLE = "simple";
export const FULL = "full";
// Display choices kept on the node: the open tab, and the last prompt the
// node wrote (so a saved workflow opens the tab with it).
export const TAB_PROPERTY = "ausboss_prompt_tab";
export const WRITTEN_PROPERTY = "ausboss_written_prompt";
export function promptTab(node) {
return node?.properties?.[TAB_PROPERTY] === FULL ? FULL : SIMPLE;
}
// The widget holds an edit only when there is one: empty text, or the
// written prompt typed back unchanged, means "send what the node writes".
export function editValue(text, written = "") {
const typed = String(text ?? "");
if (!typed.trim()) return "";
if (written && typed.trim() === String(written).trim()) return "";
return typed;
}
export function isEdited(values) {
return String(values?.full_prompt ?? "").trim() !== "";
}
// What the box shows: the edit, else the last prompt the node wrote.
export function boxText(values, written = "") {
return isEdited(values) ? String(values.full_prompt) : String(written ?? "");
}
// The prompt the node wrote on its last run, from the run's ui output.
export function writtenFromOutput(output) {
const text = output?.written_prompt;
if (Array.isArray(text)) return typeof text[0] === "string" ? text[0] : null;
return typeof text === "string" ? text : null;
}
+117
View File
@@ -0,0 +1,117 @@
// Language for the pack's own node faces. ComfyUI translates node names and
// socket names from locales/<language>/nodeDefs.json; the controls the pack
// draws itself (widget cards, panels, bars, menus) are translated here.
//
// t("Preview") the Chinese text on a Chinese ComfyUI, else the same text
// translateText(text) the lookup alone, no locale check
//
// The Chinese table is js/shared/i18n_zh.mjs, keyed by the English text, so a
// string with no entry stays English. Only what is displayed changes; widget
// names, widget values and saved workflows never go through this.
import { PATTERNS, SCRUB_HINT_EN, SCRUB_HINT_ZH, ZH } from "./i18n_zh.mjs";
// "zh", "zh-CN", "zh-TW" ... all take the Chinese table.
export function isChineseLocale(code) {
return typeof code === "string" && /^zh(?:[-_]|$)/i.test(code.trim());
}
// ComfyUI's language setting, read each time so a changed setting is seen on
// the next call.
let localeSource = null;
// js/i18n/index.js hands over ComfyUI's own `app`, which is there before
// `window.app` is.
export function useLocaleSource(read) { localeSource = typeof read === "function" ? read : null; }
export function currentLocale() {
try {
const value = localeSource ? localeSource() : globalThis.app?.ui?.settings?.getSettingValue?.("Comfy.Locale");
return typeof value === "string" ? value : "";
} catch {
return "";
}
}
export const chineseActive = () => isChineseLocale(currentLocale());
// Look `text` up in the Chinese table, keeping any spaces around it. Returns
// the text itself when there is no entry.
export function translateText(text, table = ZH, patterns = PATTERNS) {
if (typeof text !== "string" || text === "") return text;
const trimmed = text.trim();
if (trimmed === "") return text;
// A number box's tooltip is "<its own tooltip> <the scrub hint>".
if (table === ZH && trimmed.endsWith(` ${SCRUB_HINT_EN}`)) {
const own = trimmed.slice(0, -SCRUB_HINT_EN.length - 1);
return text.replace(trimmed, () => `${translateText(own, table, patterns)} ${SCRUB_HINT_ZH}`);
}
const hit = Object.hasOwn(table, trimmed) ? table[trimmed] : undefined;
let result = typeof hit === "string" && hit !== "" ? hit : null;
if (result === null) {
for (const [pattern, build] of patterns) {
const match = pattern.exec(trimmed);
if (match) { result = build(...match); break; }
}
}
if (result === null) return text;
return text.replace(trimmed, () => result);
}
export function t(text) {
return chineseActive() ? translateText(text) : text;
}
// ---------- translating a face that is already built ----------
const ATTRIBUTES = ["title", "placeholder", "aria-label"];
// Text that belongs to the user or the graph, or that code reads back.
const SKIP = "[data-no-i18n],[class*='ausboss-callout'],[class*='ausboss-note'],.ausboss-show-text-body,.ausboss-lora-label";
// Text inside these is a value (what is typed, or the page's own scripts), not a label.
const VALUE_HOLDERS = "textarea,input,script,style,[contenteditable]";
const SCOPE = "[class*='ausboss']";
function inScope(element, text = false) {
if (!element?.closest?.(SCOPE) || element.closest(SKIP)) return false;
return !(text && element.closest(VALUE_HOLDERS));
}
function translateNode(node) {
if (node.nodeType === 3) {
const parent = node.parentElement;
// An <option>'s text is what the list shows; its value is its own attribute.
if (!parent || !inScope(parent, true)) return;
const next = translateText(node.nodeValue);
if (next !== node.nodeValue) node.nodeValue = next;
return;
}
if (node.nodeType !== 1 || !(node.matches?.(SCOPE) || node.querySelector?.(SCOPE) || node.closest?.(SCOPE))) return;
const walker = node.ownerDocument.createTreeWalker(node, 1 | 4);
const visit = (current) => {
if (current.nodeType === 3) translateNode(current);
else if (current.nodeType === 1 && inScope(current)) {
for (const name of ATTRIBUTES) {
const value = current.getAttribute(name);
if (!value) continue;
const next = translateText(value);
if (next !== value) current.setAttribute(name, next);
}
}
};
visit(node);
for (let current = walker.nextNode(); current; current = walker.nextNode()) visit(current);
}
// Keep every pack face in `root` translated, including text a face writes
// later. Returns a function that stops it.
export function followFaces(root = document.body) {
translateNode(root);
const observer = new MutationObserver((records) => {
for (const record of records) {
if (record.type === "characterData") translateNode(record.target);
else if (record.type === "attributes") translateNode(record.target);
else for (const added of record.addedNodes) translateNode(added);
}
});
observer.observe(root, { subtree: true, childList: true, characterData: true, attributes: true, attributeFilter: ATTRIBUTES });
return () => observer.disconnect();
}
+339
View File
@@ -0,0 +1,339 @@
// Simplified Chinese for the text the pack draws on its own node faces
// (widget cards, panels, bars and menus). The key is the English text as the
// code writes it; a string with no entry here simply stays English.
// Only what is DISPLAYED changes: widget names, values, saved workflows and
// the API prompt never see these strings.
//
// Product and model names (H3, Pika, Qwen, FlashVSR, LoRA, VRAM, SAM 3) and
// file names, codec names and algorithm names stay as they are.
export const ZH = {
// ---- card rows and group headers
"Target": "目标", "Size": "尺寸", "Edge": "边缘", "Budget": "像素预算", "Scale": "缩放", "Fit": "适应",
"Fill": "填充", "Multiple": "倍数", "Filter": "滤镜", "Job": "任务", "Pieces": "分块数",
"Lock": "锁定", "Tolerance": "容差", "Feather": "羽化", "Remove tint": "去除偏色", "Strength": "强度",
"Method": "方法", "Reference": "参考", "Invert mask": "反转遮罩", "Megapixels": "百万像素",
"More": "更多", "MORE": "更多", "Tile size": "分块大小", "Overlap": "重叠", "Redraw limit": "重绘上限",
"Keep colors": "保持颜色", "Tone match": "色调匹配", "Fix edge halo": "修复边缘光晕", "Follow changes": "跟随变化",
"Context": "上下文", "Stay in picture": "不出画面", "Blend": "混合", "Grow": "扩大", "Blur": "模糊",
"Target size, extend": "目标尺寸与外扩", "Extra context": "额外上下文", "Target width": "目标宽度", "Target height": "目标高度",
"Rescale": "重新缩放", "Extend left": "向左外扩", "Extend right": "向右外扩", "Extend up": "向上外扩", "Extend down": "向下外扩",
"Expand": "扩张", "Fill holes": "填补孔洞", "Max hole size": "最大孔洞", "Smooth": "平滑", "Black point": "黑场", "White point": "白场",
"From": "来源", "Folder": "文件夹", "Subfolders": "子文件夹", "Order": "排序", "Run": "运行", "Picture": "图片",
"After a run": "运行之后", "At the end": "到末尾时", "Soften": "柔化", "Fine edges": "精细边缘", "Fill small holes": "填补小孔",
"Invert": "反转", "If nothing": "没选中时", "New picture": "换新图时", "Free VRAM": "释放显存", "Canvas": "画布",
"Find": "查找", "If several": "有多个时", "Sureness": "把握度", "FPS": "帧率", "Scene cut": "场景切换", "Batch": "批量",
"Model": "模型", "Mode": "模式", "Anchor": "对齐位置", "Pad fill": "扩边填充", "Pad color": "扩边颜色", "Color": "颜色",
"Empty fill": "空白填充", "Max zoom": "最大缩放", "Every nth": "每隔几帧", "Offset": "偏移", "Split after": "在此之后拆分",
"Mismatch": "尺寸不一致", "Value": "数值", "Split at": "拆分方式", "Numbering": "编号", "Limit": "数量上限",
"Length": "长度", "Camera": "镜头", "Look": "风格", "Song starts at": "歌曲起点", "Moments on the beat": "时刻对齐节拍",
"Language": "语言", "Clip's own sound": "素材自带声音", "Sound": "声音", "Music": "音乐", "Frame": "帧",
"KV cache": "KV 缓存", "VLM reference": "VLM 参考", "Source": "素材", "Width": "宽度", "Height": "高度",
"Longest side": "最长边", "Ratio": "比例", "Keep": "保留", "Round to": "取整到", "Enlarge": "放大小图",
"Backdrop": "背景虚化", "Exact padding": "精确扩边", "Left": "左", "Top": "上", "Right": "右", "Bottom": "下",
"Prefix": "文件名前缀", "Format": "格式", "FPS · CRF": "帧率 · CRF", "Ping-pong": "往返播放", "Embed workflow": "嵌入工作流",
"Pictures and settings": "图片与设置", "What H3 gets": "H3 收到的内容", "What happens": "发生了什么",
"Align": "对齐", "Aspect ratio": "画面比例", "Crop, pad & resize": "裁剪、扩边与缩放", "Duration": "时长", "Ends at": "结束于",
"Frames for": "帧数用于", "Start": "起点", "Whole video": "整段视频", "Clip IN": "片段入点", "Clip OUT": "片段出点",
"Colors": "颜色", "Preview steps": "预览步骤", "Show picture": "显示图片", "Preview": "预览",
"Settings": "设置", "Show as": "显示为", "When off": "关闭时", "Group order": "分组顺序", "Groups": "分组", "Inputs": "输入", "Outputs": "输出",
"Fit to ratio": "适应比例", "Hold the shape": "保持形状", "Box 1 is": "框 1 是",
// ---- on / off pills and short states
"on": "开", "off": "关", "On": "开", "Off": "关", "keep": "保留", "remove": "移除", "once per run": "每次运行一次", "every step": "每一步",
"forward, back": "正放、倒放", "not used": "未使用", "by blend in": "(融合模式下)", "blend in": "融合", "blend": "混合",
// ---- choice labels
"Width × height": "宽 × 高", "Longest edge": "最长边", "Shortest edge": "最短边", "Scale factor": "缩放倍数",
"cover": "填满", "fit": "适应", "fit inside": "放入框内", "crop to fill": "裁剪填满", "crop to ratio": "按比例裁剪", "crop": "裁剪",
"pad": "扩边", "resize": "缩放", "stretch": "拉伸", "megapixels": "百万像素", "longest side": "最长边", "scale": "缩放",
"hist": "直方图", "histogram": "直方图", "first frame": "首帧", "reference": "参考图", "guided": "引导", "matting": "抠图",
"optical flow (RAFT)": "光流 (RAFT)", "match a": "匹配 a", "match b": "匹配 b", "error": "报错", "source rect": "源矩形",
"whole canvas": "整个画布", "all in one run": "一次全部", "one per run": "每次一张", "all of them": "全部", "none": "无", "None": "无",
"any": "任意", "always": "始终", "auto": "自动", "stay": "保持", "start over": "重新开始", "keep picks": "保留选择",
"stop the run": "停止运行", "empty mask": "空遮罩", "newest first": "最新在前", "oldest first": "最旧在前", "random": "随机", "Random": "随机",
"next": "下一张", "name": "名称", "title": "标题", "canvas": "画布", "each line": "每行一次", "blank line": "空行分隔",
"rows": "逐行", "one pill": "单选", "bypass": "绕过", "mute": "静音", "mirror": "镜像", "follow": "跟随", "linked": "已连接",
"gray": "灰色", "edge": "边缘", "edge pixel": "边缘像素", "color": "纯色", "pillarbox blur": "两侧虚化", "replicate": "复制边缘",
"source": "原图", "as typed": "照输入", "from the picture": "取自图片", "text": "文字", "object": "物体", "still": "静止", "handheld": "手持",
"shaky": "抖动", "push in": "推近", "pull back": "拉远", "orbit": "环绕", "walking pov": "步行视角", "anime": "动漫", "comic book": "漫画",
"pencil sketch": "铅笔素描", "watercolor": "水彩", "split sheet at gaps": "按空隙拆分拼图", "Pad": "扩边", "Crop": "裁剪",
"Resize": "缩放", "Center": "居中", "Soft": "柔和", "Simple": "简易", "Full prompt": "完整提示词", "Text": "文字", "Fixed": "固定",
"LTX (8n+1)": "LTX (8n+1)", "Wan (4n+1)": "Wan (4n+1)", "Every group": "每个分组", "Numbered groups": "编号分组",
"Titles matching…": "按标题匹配…", "No groups": "没有分组", "All": "全部", "Background": "背景", "Subject": "主体",
// ---- buttons, bars, captions
"Add": "添加", "Browse": "浏览", "Clear": "清除", "Done": "完成", "Erase": "擦除", "Paint": "绘制", "Pick": "选取", "Load": "加载",
"Open editor": "打开编辑器", "Reset": "重置", "Reset crop": "重置裁剪", "Reset padding": "重置扩边", "Reset to written": "恢复为所写内容",
"Undo": "撤销", "Use as start": "设为起点", "Use last run": "用上次的", "New seed": "新种子", "Step +1": "步进 +1", "STOP": "停止",
"FIND": "查找", "FRAME": "帧", "LOOP": "循环", "AUTO": "自动", "Turn": "旋转", "Step": "步进", "Match": "匹配",
"+ Choice": "+ 选项", "+ LoRA": "+ LoRA", "+ new": "+ 新建", "+ video": "+ 视频", "Layouts ▾": "布局 ▾",
"Select nodes, then add a switch": "先选中节点,再添加开关", "Description": "说明",
"Choose a file…": "选择文件…", "Choose a sound file": "选择声音文件", "Choose an input video…": "选择输入视频…",
"Choose an uploaded image…": "选择已上传的图片…", "Choose an uploaded video…": "选择已上传的视频…",
"Choose or upload a video": "选择或上传视频", "Choose an input image": "选择输入图片", "Choose an input video": "选择输入视频",
"Copy a folder from your computer": "从电脑复制一个文件夹", "Load image": "加载图片", "Load video": "加载视频",
"Connect a mask to see it here": "连接遮罩即可在此查看", "Connect an image to see it here": "连接图像即可在此查看",
"Connect frames to see it here": "连接帧即可在此查看",
"Connect a picture or a video. H3 needs one to start from.": "请连接一张图片或一段视频,H3 需要一个起点。",
"Drag on the canvas to draw a box": "在画布上拖动来画一个框",
"Each box you draw gets its words here: a thing to show, or text to write in the picture.": "你画的每个框都在这里写描述:要显示的东西,或要写在图里的文字。",
"Edited by you. This text is sent as it is; the Simple tab is not used until you reset.": "已由你修改。这段文字将原样发送,重置之前不会使用“简易”标签页。",
"Edited: this text is sent instead of the Simple tab.": "已修改:发送的是这段文字,而不是“简易”标签页。",
"Full prompt is edited, so these lines are not used until you reset it there.": "完整提示词已被修改,所以这些行在那边重置之前不会使用。",
"Filled in after each run.": "每次运行后自动填入。",
"No LoRAs yet": "还没有 LoRA", "no LoRAs": "没有 LoRA", "No pictures here yet. Drop a folder or pictures on the node, or bring a folder in:": "这里还没有图片。把文件夹或图片拖到节点上,或导入一个文件夹:",
"no pictures": "没有图片", "Working on the fine details…": "正在处理细节…", "Run to preview the saved video": "运行后预览保存的视频",
"run the graph to see the text that arrives here": "运行工作流即可在此看到传入的文字",
"rolls a new seed each queue": "每次排队都会换新种子", "Source · feather 24 px": "素材 · 羽化 24 px",
"Select the nodes of one part, such as a box and its Save, then press + Switch.": "选中某个部分的节点(例如一个框和它的保存节点),然后点“+ 开关”。",
"Choose an uploaded image or drop one onto this node.": "选择已上传的图片,或把图片拖到此节点上。",
"Choose an uploaded video or add one to ComfyUI's input folder.": "选择已上传的视频,或把视频放进 ComfyUI 的 input 文件夹。",
"Choose a file from ComfyUI's input folder or load a new image.": "从 ComfyUI 的 input 文件夹选择文件,或加载新图片。",
"Choose a file from ComfyUI's input folder or load a new video.": "从 ComfyUI 的 input 文件夹选择文件,或加载新视频。",
"Choose a rendered image from ComfyUI's output folder.": "从 ComfyUI 的 output 文件夹选择已生成的图片。",
"Choose a rendered video from ComfyUI's output folder.": "从 ComfyUI 的 output 文件夹选择已生成的视频。",
"Choose a picture or video to center.": "选择要居中的图片或视频。",
"Upload a picture into ComfyUI's input folder": "把图片上传到 ComfyUI 的 input 文件夹",
"Upload an image into ComfyUI's input folder": "把图片上传到 ComfyUI 的 input 文件夹",
"Upload a video into ComfyUI's input folder": "把视频上传到 ComfyUI 的 input 文件夹",
"Upload a sound file into ComfyUI's input folder": "把声音文件上传到 ComfyUI 的 input 文件夹",
// ---- tooltips written in the pack's own code
"Add a LoRA": "添加 LoRA", "Pick one LoRA, or click a folder name to add all its LoRAs.": "选一个 LoRA,或点文件夹名把里面的 LoRA 全部加入。",
"Re-check LoRA files: refresh the list and reconnect rows whose files moved or came back": "重新检查 LoRA 文件:刷新列表,并重新连接文件被移动或重新出现的行",
"LoRA templates: save this stack, or apply a saved one": "LoRA 模板:保存当前这组,或套用已保存的",
"Toggle every LoRA: mixed saves your setup and turns all on; on turns all off; off brings your saved setup back": "切换所有 LoRA:混合时保存当前设置并全部开启;全开时全部关闭;全关时恢复你保存的设置",
"Serialized LoRA stack managed by the node's row editor; edit the rows, not this value.": "由节点的行编辑器管理的 LoRA 列表;请编辑各行,不要改这个值。",
"LoRA Loader settings": "LoRA 加载器设置",
"Click to type a seed": "点击输入种子", "Copy the seed": "复制种子", "Copy the text": "复制文字", "Earlier seeds this node ran with": "此节点用过的历史种子",
"Increment the seed after each queue (click again for decrement)": "每次排队后种子加 1(再点一次改为减 1)",
"Keep this seed for every queue": "每次排队都用这个种子",
"Put the last run's seed back and pin it (Fixed)": "恢复上次运行的种子并固定",
"Roll a fresh seed and pin it (Fixed)": "随机一个新种子并固定",
"Roll a new seed after every queue": "每次排队后随机新种子",
"Rolls a new seed after each run. Tap for Fixed.": "每次运行后随机新种子。点一下切换为固定。",
"Seed settings: full or compact look": "种子设置:完整或紧凑外观", "Number settings": "数字设置", "Text settings": "文字设置",
"Image Crop + Rotate + Pad settings": "图像裁剪 + 旋转 + 扩边设置", "Stitch Inpaint settings": "拼回重绘设置",
"Step down; Shift = fine.": "减小;按住 Shift 精细调节。", "Step up; Shift = fine.": "增大;按住 Shift 精细调节。",
"Arithmetic over a, b and c: numbers, + - * / // % **, parentheses, and min/max/abs/round/floor/ceil/sqrt.": "对 a、b、c 做运算:数字、+ - * / // % **、括号,以及 min/max/abs/round/floor/ceil/sqrt。",
"Center side to side": "左右居中", "Center top to bottom": "上下居中",
"Choose how to reach the next ratio. Crop trims the picture and Pad adds fill.": "选择如何达到下一个比例:裁剪会切掉画面,扩边会补上填充。",
"Comma-separated text; a group is listed when its title contains any of it": "用逗号分隔的文字;分组标题包含其中任意一项就会列出",
"Drag a handle to set where the sound starts or stops. Drag the middle to slide it.": "拖动手柄设置声音的起点或终点,拖动中间可整体滑动。",
"Drag to change the Duration; the start stays.": "拖动来改变时长,起点不变。",
"Drag to move the clip; its Duration stays. Shift + arrow moves one frame.": "拖动来移动片段,时长不变。Shift + 方向键每次移动一帧。",
"Drag to slide the clip; its Duration stays.": "拖动来滑动片段,时长不变。",
"Fill #000000": "填充 #000000", "Fill #808080": "填充 #808080",
"Fill colour of the padding and rotation corners. Now #808080.": "扩边和旋转后空角的填充颜色。当前为 #808080。",
"Keep the canvas size.": "保持画布尺寸。", "Keep the whole picture and add fill to reach the selected ratio.": "保留整张图片,并补上填充以达到所选比例。",
"Trim the picture to the selected ratio.": "把图片裁剪到所选比例。",
"Pad to 16:9: keep every pixel and add fill around it.": "扩边到 16:9:保留每个像素,四周补上填充。",
"Pad to 1:1: keep every pixel and add fill around it.": "扩边到 1:1:保留每个像素,四周补上填充。",
"Pad to 21:9: keep every pixel and add fill around it.": "扩边到 21:9:保留每个像素,四周补上填充。",
"Pad to 3:2: keep every pixel and add fill around it.": "扩边到 3:2:保留每个像素,四周补上填充。",
"Pad to 4:3: keep every pixel and add fill around it.": "扩边到 4:3:保留每个像素,四周补上填充。",
"Tap a ratio to pad the picture to it (or crop it, with Fit on crop). Tap the lit one to go back to the whole picture.": "点一个比例,把图片扩边到该比例(“适应”选裁剪时则是裁剪)。再点亮着的那个可回到完整图片。",
"Show the portrait ratios": "显示竖版比例", "Show ratio, fit, align, fill, feather, center and resize settings": "显示比例、适应、对齐、填充、羽化、居中和缩放设置",
"Reset rotation, crop and padding, and turn the padlock off. Fill, feather, Align and the timeline stay.": "重置旋转、裁剪和扩边,并解除锁定。填充、羽化、对齐和时间线保持不变。",
"Show the whole picture again; rotation, padding and the timeline stay. With the padlock on, the bands it added to keep the shape go too.": "重新显示整张图片;旋转、扩边和时间线保持不变。锁定时,为保持形状而补的边也会去掉。",
"The diamonds and crop squares drag freely; the orange corners always keep the shape. Tap to hold this shape whatever you drag.": "菱形和裁剪方块可自由拖动;橙色角点始终保持形状。点一下,无论怎么拖都保持当前形状。",
"Make the canvas width and height multiples of this number before resizing. Padding grows or unpadded edges are trimmed. Use 1 to turn alignment off.": "缩放前先让画布宽高成为此数的倍数。扩边会加大,没扩边的边缘会被裁掉。填 1 表示不对齐。",
"Rounds each resized side to a multiple of this (32 for LTX and Wan, 8 or 64 for image models). Each side rounds on its own, so a large step can stretch the picture slightly; the readout warns above 1%.": "把缩放后的每条边取整为此数的倍数(LTX 和 Wan 用 32,图像模型用 8 或 64)。每条边各自取整,步长大时画面可能略有拉伸;超过 1% 时读数会提醒。",
"Output budget in megapixels (x 1024x1024). The size readout under the picture shows where it lands.": "输出像素预算,单位百万像素(x 1024x1024)。图片下方的尺寸读数会显示最终大小。",
"Resize the output to a megapixel budget, each side rounded to the step (32 for LTX and Wan).": "把输出缩放到像素预算,每条边取整到步长(LTX 和 Wan 用 32)。",
"Resize to the megapixel budget and round each side to the step.": "缩放到像素预算,每条边取整到步长。",
"Feather of the mask into the kept pixels; the image keeps a hard edge against the fill.": "遮罩向保留像素内的羽化;图片与填充之间保持硬边。",
"Feather of the mask into the kept frames, in pixels. The frames keep a hard edge against the fill whatever the feather, so a black-band outpaint still sees its bars.": "遮罩向保留画面内的羽化,单位像素。无论羽化多少,画面与填充之间都保持硬边,所以黑边外扩仍能看到黑条。",
"Where the clip starts in the source video.": "片段在源视频中的起点。", "Where the clip ends in the source video. Typing it changes the Duration.": "片段在源视频中的终点。输入它会改变时长。",
"Start the clip at the frame on the stage. The Duration stays.": "让片段从舞台上当前这一帧开始,时长不变。",
"How long the clip is. Counted in clip frames at the output rate.": "片段有多长,按输出帧率的片段帧数计算。",
"How long the sound is. Clear it, or type 0, to run to the end of the file.": "声音有多长。清空或输入 0 表示播到文件末尾。",
"Where the sound starts in the file, of 0:00.": "声音在文件中的起点,从 0:00 起算。", "Where the sound stops in the file. Typing it changes the Duration.": "声音在文件中的终点。输入它会改变时长。",
"Keep a frame count the video model takes: LTX wants 8n+1 (49, 97, 121), Wan 4n+1. The Duration steps to those counts. Any keeps every frame.": "保留视频模型能接受的帧数:LTX 需要 8n+1(49、97、121),Wan 需要 4n+1。时长会按这些帧数步进。选“任意”则保留每一帧。",
"Keep one frame in this many. Output fps is adjusted to keep real-time playback; the Duration counts the frames kept.": "每隔这么多帧保留一帧。输出帧率会随之调整以保持实时播放;时长按保留的帧数计算。",
"Use the whole video: start at 0 with no Duration limit. Keeps Every nth and Frames for.": "使用整段视频:从 0 开始,不限制时长。“每隔几帧”和“帧数用于”仍然有效。",
"Play it again and again": "循环播放", "Play the clip from its start": "从头播放片段", "Play the part that comes out": "播放最终输出的部分",
"Show times in frames: source frames for Start and Ends at, clip frames for Duration.": "以帧显示时间:起点和终点用源视频帧,时长用片段帧。", "Show times in seconds.": "以秒显示时间。",
"Playback frame rate; wire Load Video's fps output to match the source. A connected video input brings its own rate and overrides this widget. Fractional rates like 23.976 and 29.97 can be typed in.": "播放帧率;把加载视频的 fps 输出连过来可与源视频一致。连接了视频输入时会使用它自带的帧率,并覆盖这个控件。可以输入 23.976、29.97 这类小数帧率。",
"Play the clip forward then backward so it loops seamlessly. Roughly doubles the frame count and the encode time; the first and last frames are not repeated at the turnaround.": "先正放再倒放,让片段无缝循环。帧数和编码时间大约翻倍;转折处首尾帧不会重复。",
"On embeds the workflow in the video file, so dropping the file back on the canvas restores the graph that made it.": "开启后会把工作流嵌入视频文件,把文件拖回画布即可还原生成它的工作流。",
"Container and codec. mp4 h264 plays everywhere; mp4 h265 halves the size at the same quality where supported; the nvenc pair encodes on an NVIDIA GPU instead of the CPU (much faster, slightly larger); webm vp9 and webm av1 suit the web and mux Opus; mov prores": "封装格式和编码。mp4 h264 到处都能播放;mp4 h265 在支持的设备上同画质体积减半;两个 nvenc 选项用 NVIDIA 显卡而不是 CPU 编码(快得多,体积略大);webm vp9 和 webm av1 适合网页并封装 Opus;mov prores",
"Encode quality: lower is better and larger. 19 is visually lossless for h264; h265 and vp9 read the same scale (vp9 tolerates a few points higher).": "编码质量:数值越小画质越好、文件越大。h264 用 19 在视觉上无损;h265 和 vp9 用同样的刻度(vp9 可以高几个点)。",
"Show the clip's first frame here while it is being made, one step at a time, with a Stop button. Off by default.": "生成过程中在这里逐步显示片段的首帧,并带一个停止按钮。默认关闭。",
"Stop this run now. The next run in the queue still starts.": "立即停止这次运行。队列里的下一次运行仍会开始。",
"Moves each moment onto the nearest beat of the song. Pick off to keep your own seconds.": "把每个时刻移到歌曲最近的节拍上。选“关”则保留你自己写的秒数。",
"The second of the song to start from, so the clip gets the good part.": "从歌曲的第几秒开始,让片段用上最精彩的部分。",
"This video job uses the incoming clip, so Length is not used.": "这个视频任务使用传入的片段,所以不使用“长度”。", "From the clip": "取自片段",
"Plug a picture into picture_1 to name it @1 in your lines.": "把图片接到 picture_1,就能在文字里用 @1 称呼它。",
"Plug a picture into picture_2 to name it @2 in your lines.": "把图片接到 picture_2,就能在文字里用 @2 称呼它。",
"Plug a picture into picture_3 to name it @3 in your lines.": "把图片接到 picture_3,就能在文字里用 @3 称呼它。",
"Plug a picture into picture_4 to name it @4 in your lines.": "把图片接到 picture_4,就能在文字里用 @4 称呼它。",
"Plug a video into video to copy its moves, swap the person, keep it going or give it a new voice.": "把视频接到 video,可以复制它的动作、换人、接着往下拍,或换一个新声音。",
"Turn on when a swap keeps the video's own sound. Each line is timed from that sound, and words from anyone else are left out so only the new person's mouth moves.": "换人并保留视频原声时开启。每一行按原声计时,其他人的台词会被去掉,只有新人物的嘴在动。",
"Run the workflow once and the prompt the node writes shows here. Change it to send your own.": "运行一次工作流后,节点写出的提示词会显示在这里。修改它就会发送你自己的版本。",
"The prompt the node wrote on its last run. Change it here to send your own.": "节点上次运行写出的提示词。在这里修改即可发送你自己的版本。",
"Throw your edit away and send what the Simple tab writes again.": "放弃你的修改,重新发送“简易”标签页写出的内容。",
"What H3 gets. Type here to send your own text instead of the node's.": "H3 收到的内容。在这里输入即可用你自己的文字代替节点写的。",
"What happens, one line for each moment. A blank line cuts to a new place. @1 is Picture 1. Start a line with 3s: to put it on that second.": "发生了什么,每个时刻写一行。空行表示切到新的地点。@1 是图片 1。行首写 3s: 可把它放在第 3 秒。",
"Type what happens, one line for each thing. Picture 1 is @1. A blank line cuts to a new place.\n\nSwap: leave empty, or name who goes. Optional new look on its own line: @1 looks like a woman with blonde hair and a black hoodie.": "输入发生了什么,每件事一行。图片 1 是 @1。空行表示切到新的地点。\n\n换人:留空,或写明换掉谁。新造型可单独写一行:@1 是一位金发、穿黑色连帽衫的女士。",
"Your lines, the pictures and the menus. The node writes the full prompt from them.": "你写的文字、图片和各个菜单。节点会据此写出完整提示词。",
"What you can type in the words": "文字里可以怎么写", "rain on a window": "窗上的雨声", "slow piano: music makes it louder": "舒缓钢琴:加了音乐会更响",
"upscale, face": "放大, 人脸",
"Switching a row on switches the other rows off - for alternatives such as two upscalers.": "打开一行会关掉其他行,适合在两个放大器这类互斥方案之间切换。",
"Rows gives each switch a row with its own off | on. One pill makes the switches choices in a single pill, where one is always picked.": "“逐行”让每个开关各占一行,各自有关 | 开。“单选”把这些开关合成一个选项条,始终选中其中一个。",
"Show only the labels and their switches. Double-click a label, or right-click the node, to edit again.": "只显示名称和开关。双击名称或右键节点可重新编辑。",
"Select the nodes of one part on the canvas, then press this: they get one switch": "在画布上选中某一部分的节点再按这里,它们会得到一个开关",
"Set the nodes the way this choice should be, then press this and give it a name. Do it again for each choice: the card becomes one pill, and picking one sets the nodes that way.": "先把节点调成这个选项该有的样子,再按这里并起个名字。每个选项都这样做一遍:卡片会变成一个选项条,选中某项就会把节点设成对应状态。",
"What a switched-off part does. Bypass: its nodes hand their inputs straight through, so the rest of the workflow still runs. Mute: its nodes do not run, and nor does anything that needs their output.": "关闭的部分怎么处理。绕过:节点把输入直接传出去,工作流其余部分照常运行。静音:节点不运行,依赖它们输出的节点也不运行。",
"What off means, which groups get a switch of their own, and their order": "“关”是什么意思、哪些分组有各自的开关,以及它们的顺序",
"Which groups get a switch of their own, listed under the switches you made: none, every group, the numbered ones (titles starting with a digit, like 1 · Load), or titles matching text.": "哪些分组有各自的开关,列在你创建的开关下面:无、每个分组、编号分组(标题以数字开头,如 1 · Load),或标题匹配某段文字。",
"The order of the group rows. Canvas: the way the workflow reads, column by column from the left and top to bottom within a column. Title: by title, with numbers in numeric order.": "分组行的顺序。画布:按工作流的阅读顺序,从左到右逐列,每列从上到下。标题:按标题排序,数字按数值大小排。",
"Toggle looping for this saved preview": "切换此预览的循环播放",
// ---- tooltips of the nodes the Person Swap and Pika Remix workflows use
"A sound file in ComfyUI's input folder. Use Upload to add one.": "ComfyUI input 文件夹里的声音文件。用“上传”添加新的。",
"Fill colour of the padding and rotation corners. Video outpaint models key on it: the LTX IC-LoRA paints pure black (#000000) and leaves other colours alone. Now #000000.": "扩边和旋转后空角的填充颜色。视频外扩模型会以它为依据:LTX IC-LoRA 画纯黑(#000000),其他颜色保持不动。当前为 #000000。",
"Container and codec.": "封装格式和编码。mp4 h264 到处都能播放;mp4 h265 在支持的设备上同画质体积减半;两个 nvenc 选项用 NVIDIA 显卡而不是 CPU 编码(快得多,体积略大);webm vp9 和 webm av1 适合网页并封装 Opus;mov prores 是 ProRes HQ 剪辑母版;mkv ffv1 是逐位无损,文件非常大;gif 和 webp 没有声音、无限循环,并把每一帧都放进内存,只适合短片段。",
"Feather of the mask into the kept frames, in pixels. The frames keep a hard edge against the fill whatever the feather, so a black-band outpaint still sees its bars.": "遮罩向保留画面内的羽化,单位像素。无论羽化多少,画面与填充之间都保持硬边,所以黑边外扩仍能看到黑条。",
"From the picture keeps your photo's look. The others redraw it in that style.": "“取自图片”保留你照片原本的样子,其他选项会把它重绘成对应风格。",
"How long the clip is. Plan on about one moment a second at most.": "片段有多长。大约每秒最多安排一个时刻。",
"How many times larger each side gets. 1 keeps the size and only sharpens.": "每条边放大多少倍。1 表示尺寸不变,只做锐化。",
"How the camera moves the whole way through. As typed leaves it to your words; with a video wired it shows as from the video and keeps the video's own camera.": "镜头从头到尾怎么运动。“照输入”交给你写的文字;连了视频时显示为“取自视频”,沿用视频自带的镜头。",
"Keeps each frame's colours the same as your video. Leave it on.": "让每一帧的颜色与你的视频保持一致。建议保持开启。",
"Saved under the output folder; subfolders are created automatically.": "保存在 output 文件夹下;子文件夹会自动创建。",
"The FlashVSR model file, from ComfyUI/models/diffusion_models.": "FlashVSR 模型文件,位于 ComfyUI/models/diffusion_models。",
"The integer to output.": "要输出的整数。",
"The language of the words in quotes.": "引号里台词所用的语言。",
"The music, like a slow lo-fi beat. A clip with music comes out louder. Empty means no music.": "音乐,比如舒缓的 lo-fi 节奏。带音乐的片段声音会更响。留空表示没有音乐。",
"What you hear the whole way through, like rain on a window. Leave it empty for none.": "从头到尾都能听到的声音,比如窗上的雨声。留空表示没有。",
"Play": "播放",
"Load image": "加载图片",
"Load video": "加载视频",
"One at a time": "一次一个",
"applies to the next ratio": "应用于下一个比例",
"rain on a window": "窗上的雨声",
// ---- card tooltips and placeholders
"Size of the finished picture. 0 keeps the picture's own size.": "成品图片的大小。0 表示保持图片原有大小。",
"Used only while Fill holes is on.": "仅在“填补孔洞”开启时使用。",
"the folder itself": "文件夹本身",
"Choose a folder inside ComfyUI's input or output folder.": "选择 ComfyUI 的 input 或 output 文件夹里的一个文件夹。",
"Prompt, caption, or shared text": "提示词、字幕或共用文字",
"type here": "在此输入",
"One line for each run": "每次运行写一行",
"A woman in a {red|blue|green} {sweater|jacket}. One choice is picked from each set.": "一位穿着{红色|蓝色|绿色}{毛衣|夹克}的女士。每组花括号里会随机选一项。",
"Prompt - describe the whole finished canvas": "提示词:描述整个成品画面",
"Negative prompt (ignored at CFG 1)": "负面提示词(CFG 为 1 时忽略)",
"On, the vision tower also sees the reference images. Use on for AnyPaint with a whole-canvas reference; use off for Registered Outpaint with a source-rectangle reference. Match the adapter's conditioning contract.": "开启时,视觉模块也会看到参考图。AnyPaint 配整张画布的参考图时开启;Registered Outpaint 配源矩形参考图时关闭。要与适配器的条件约定保持一致。",
"0 keeps the source width; set one side only to keep the aspect.": "0 表示保持源宽度;只设一边即可保持宽高比。",
"0 keeps the source height; set one side only to keep the aspect.": "0 表示保持源高度;只设一边即可保持宽高比。",
"Lock the untouched parts; step aside when the whole picture changes": "锁住没改动的部分;整张图都变了就不介入",
"Lock even when the whole picture changes": "即使整张图都变了也锁定",
"Do nothing": "什么都不做",
"A separate horizontal and vertical zoom plus a shift: how Qwen edits drift": "水平和垂直方向各自缩放,再加平移:Qwen 编辑后画面通常就是这样偏移的",
"Also a slight rotation or shear": "另外还修正轻微的旋转或倾斜",
"Stretch the nearest edge pixels": "拉伸最近的边缘像素",
"The original's pixels": "使用原图的像素",
"Flat #808080, for an inpaint pass": "纯 #808080,用于重绘",
"resize b to a's size": "把 b 缩放到 a 的尺寸",
"resize a to b's size": "把 a 缩放到 b 的尺寸",
// ---- panels, menus and lists of the same nodes
"Absorb chain LoRAs": "并入串联的 LoRA",
"Add your own trigger word...": "添加自己的触发词…",
"Adds 1 after each run. Tap for -1.": "每次运行后加 1。点一下改为减 1。",
"Advisory range for this LoRA; out-of-range strengths tint orange on the row.": "这个 LoRA 的建议范围;超出范围的强度会让该行显示为橙色。",
"Asks civitai.com about this one file, from this browser.": "由此浏览器向 civitai.com 查询这一个文件。",
"Audio preview unavailable ⓘ": "无法预览音频 ⓘ",
"Audio preview unavailable. Show details.": "无法预览音频。查看详情。",
"Back to defaults for this node type": "恢复此节点类型的默认值",
"Changed from the suggested value": "与建议值不同",
"Choice": "选项",
"Choose a source to set the clip": "先选择素材,再设置片段",
"Choose a source to begin": "选择素材后开始",
"Civitai lookup button": "Civitai 查询按钮",
"Civitai lookup failed": "Civitai 查询失败",
"Civitai picture": "Civitai 图片",
"Close without saving: puts back everything as it was when the editor opened (Esc)": "不保存关闭:恢复为打开编辑器时的样子(Esc)",
"Crop image — right-click to copy": "裁剪后的图片,右键可复制",
"Default strength": "默认强度",
"Drag to move the whole group": "拖动可移动整个分组",
"Drag to reorder": "拖动可调整顺序",
"Each line becomes a moment. A blank line between lines is a cut.": "每一行是一个时刻,两行之间的空行表示切换场景。",
"Enable or disable this LoRA": "启用或停用这个 LoRA",
"Fetching...": "获取中…",
"Group name": "分组名称",
"Held": "已锁定",
"Hide file extension": "隐藏文件扩展名",
"Hide folder names": "隐藏文件夹名",
"Keeps this seed for every run. Tap for +1.": "每次运行都用这个种子。点一下改为加 1。",
"Loading…": "加载中…",
"Long names": "长名称",
"Mask feather in pixels.": "遮罩羽化,单位像素。",
"More ratios": "更多比例",
"Name this stack; saving over an existing name replaces it": "给这组 LoRA 起个名字;用已有名字保存会覆盖它",
"Not found on Civitai": "Civitai 上没有找到",
"Output budget in megapixels (x 1024x1024).": "输出像素预算,单位百万像素(x 1024x1024)。",
"Playhead frame / last frame": "当前帧 / 最后一帧",
"Preview thumbnails": "预览缩略图",
"Preview, base model, and trigger words": "预览图、基础模型和触发词",
"Put this seed back and pin it": "恢复这个种子并固定",
"Remove all padding.": "清除所有扩边。",
"Rotation in degrees: 1° per step, Shift for 0.1°. The crop stays over the same part of the picture.": "旋转角度:每步 1°,按住 Shift 为 0.1°。裁剪框保持在画面的同一部分上。",
"Rounds each resized side to a multiple of this (32 for LTX and Wan).": "把缩放后的每条边取整为此数的倍数(LTX 和 Wan 用 32)。",
"Rows on the box": "框上的行",
"Save current as...": "另存当前为…",
"Scrub strength on the name": "在名称上拖动调节强度",
"Search LoRAs": "搜索 LoRA",
"Search LoRAs...": "搜索 LoRA…",
"Seed settings": "种子设置",
"Select every node this switch turns off and on": "选中此开关控制的所有节点",
"Select nodes or groups on the canvas first, then add them to this switch": "先在画布上选中节点或分组,再把它们加入这个开关",
"Select nodes that run only while this is off, then take them off that side. They stay as they are.": "选中只在此项关闭时才运行的节点,再把它们放到“关”的一侧。节点本身保持原样。",
"Select nodes this switch holds first, then take them out of it": "先选中此开关管理的节点,再把它们移出",
"Select the nodes only this choice needs. They are switched off while another choice is picked.": "选中只有这个选项才需要的节点。选了其他选项时,它们会被关闭。",
"Separate model / CLIP strength": "分开设置模型 / CLIP 强度",
"Set the nodes the way this choice should be, then pick this": "先把节点调成这个选项该有的样子,再选中它",
"Show the mask on the picture": "在图片上显示遮罩",
"Stop on missing LoRA": "缺少 LoRA 时停止",
"Strength bars": "强度条",
"Strength step": "强度步长",
"Linked strength wires": "强度连线显示", "shown": "显示", "on hover": "悬停时显示", "hidden": "隐藏",
"Unlink strength": "断开强度连线", "link": "连线",
"Takes 1 off after each run. Tap for Random.": "每次运行后减 1。点一下改为随机。",
"The words come from the wire.": "文字来自连线。",
"Tick to add with others": "勾选后与其他一起添加",
"Toggle this trigger word into the row's output": "把这个触发词加入或移出该行的输出",
"Trigger word separator": "触发词分隔符",
"Turn this group on or off. Each LoRA in it keeps its own switch.": "开启或关闭这个分组。组里的每个 LoRA 仍有各自的开关。",
"Untick every file": "取消勾选所有文件",
"seeds this node ran with": "此节点用过的历史种子",
"the last run delivered an empty string": "上次运行传来的是空字符串",
"Start and Ends at are places in the source video. Duration counts the frames the clip sends on, at the output rate.": "起点和终点是源视频里的位置。时长是片段送出的帧数,按输出帧率计算。",
"The frame this node outputs (frame_index).": "此节点输出的帧(frame_index)。",
"Pick a color": "选择颜色",
"Show the advanced mask controls": "显示高级遮罩控制",
"Reset rotation, crop, padding, fill, feather and Align. Keep the source, current frame, trim window, fixed length and picture.": "重置旋转、裁剪、扩边、填充、羽化和对齐。素材、当前帧、截取范围、固定长度和图片保持不变。",
"Up/Down chooses a row, Space toggles it, and Left/Right changes strength.": "上下键选择一行,空格切换开关,左右键调整强度。",
"Tint the paste mask the stitcher will use - the same mask math as the backend, at preview resolution.": "给拼回时使用的贴回遮罩上色,计算方式与后端一致,只是分辨率为预览分辨率。",
"Ramp where generated pixels fade over the source, in pixels of the output. Separate from the padding feather.": "生成的像素渐隐到原图上的过渡宽度,单位为输出像素。与扩边羽化相互独立。",
"Your own ratios from ausboss_presets.json. Picking one works like a ratio button.": "来自 ausboss_presets.json 的自定义比例。选中它的效果和点比例按钮一样。",
"Choose or upload an image": "选择或上传图片",
"Preview could not load this image": "预览无法加载这张图片",
};
// Strings that deliberately stay English on a Chinese face: names, symbols
// and technical terms with no everyday Chinese form.
export const STAYS_ENGLISH = new Set([
"W", "H", "FPS", "CFG", "LoRA", "VRAM", "Seed", "H3",
"lab", "rgb", "mkl", "bicubic", "bilinear", "lanczos", "nearest", "area",
"gif", "webp", "mp4 h264", "mp4 h265", "mp4 h264 nvenc", "mp4 h265 nvenc", "mov prores", "mkv ffv1", "webm vp9", "webm av1",
"big-lama.pt", "loras", "script", "video", "flashvsr_v1.1_fp16.safetensors", "f(a, b, c)", "a + b",
]);
// The hint js/shared/scrub_input.mjs adds to every number box's tooltip.
export const SCRUB_HINT_EN = "Drag to scrub, click to type a number or a sum (1024*1.5), arrows to step; Shift = fine.";
export const SCRUB_HINT_ZH = "拖动调节,点击输入数字或算式(如 1024*1.5),方向键步进;按住 Shift 精细调节。";
// A few strings carry a number or a name; the number stays and the words around it change.
export const PATTERNS = [
[/^The limits of what this is wired to: (.*)\.$/, (m, names) => `它所连接对象的取值范围:${names}。`],
[/^Set by "(.*)"\. Click to show it\. Right-click the row to unlink\.$/, (m, name) => `由“${name}”设置。点击可定位到它。右键该行可断开连线。`],
[/^Source · feather (\d+) px · Fill (#[0-9a-fA-F]{6})$/, (m, f, c) => `素材 · 羽化 ${f} px · 填充 ${c}`],
[/^Source · Fill (#[0-9a-fA-F]{6})$/, (m, c) => `素材 · 填充 ${c}`],
[/^(\d+):(\d+): reshape to this ratio\. The flip button on the left sets the orientation\.$/, (m, a, b) => `${a}:${b}:重塑为此比例。左侧的翻转按钮用来切换横竖方向。`],
];
+4 -3
View File
@@ -10,6 +10,7 @@
// writePad(side, value) write one raw pad widget (with callbacks)
// onGestureEnd() called once per completed drag
import { t } from "./i18n.mjs";
import { canvasLocalPoint } from "./transform_geometry.mjs";
import {
edgeCursor,
@@ -86,7 +87,7 @@ function drawPill(ctx, text, cx, cy, accent = false) {
ctx.fillStyle = accent ? "#8de0da" : "#e7f4f2";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(text, cx, cy + 0.5);
ctx.fillText(t(text), cx, cy + 0.5);
ctx.restore();
return width;
}
@@ -99,7 +100,7 @@ function drawBandText(ctx, text, cx, cy) {
ctx.shadowColor = "rgba(0,0,0,0.9)";
ctx.shadowBlur = 3;
ctx.fillStyle = "#ffe2c2";
ctx.fillText(text, cx, cy);
ctx.fillText(t(text), cx, cy);
ctx.restore();
}
@@ -247,7 +248,7 @@ export function createPadStage(canvas, options) {
ctx.shadowColor = "rgba(0,0,0,0.85)";
ctx.shadowBlur = 4;
ctx.fillStyle = "#78908e";
ctx.fillText(source.emptyText, w / 2, h / 2);
ctx.fillText(t(source.emptyText), w / 2, h / 2);
ctx.restore();
}
+3 -2
View File
@@ -11,6 +11,7 @@ import { mediaViewQuery, unlistedMedia } from "./media_list.mjs";
import { createMediaPicker } from "./media_picker.mjs";
import { normalizeFillColor } from "./fill_color.mjs";
import { makeSlideSwitch } from "./slide_switch.mjs";
import { t } from "./i18n.mjs";
import { makeScrubInput } from "./scrub_input.mjs";
import { confirmDiscard } from "./discard_prompt.mjs";
import { PIXEL_PROBE, featherGeneratedMask, generatedAreaMask, overlayPlan, pixelReadTrusted, seeThroughMap, stitchBlendFromMask } from "./stitch_preview.mjs";
@@ -1051,7 +1052,7 @@ function buildAspectChipRow(state) {
caption.textContent = untouched ? "Source" : "Custom";
caption.title = `${untouched ? "The picture's own shape" : "No ratio button has this shape"}: ${canvas.width}×${canvas.height} (${ratioLabel(canvas.width, canvas.height)}). Tap a ratio to use one.`;
}
caption.classList.toggle("generic", caption.textContent === "Ratio");
caption.classList.toggle("generic", !held && Boolean(request || !picture));
caption.classList.toggle("custom", Boolean(picture && !request && !untouched && !held));
caption.classList.toggle("held", held);
for (const { chip, aspect } of chips) {
@@ -3426,7 +3427,7 @@ function sizeLines(state) {
return lines;
}
function drawEmpty(state, text) { state.render = null; state.panelRender = null; syncReadout(state); for (const canvas of [state.canvas, state.previewCanvas]) { if (!canvas) continue; const prepared = prepareCanvas(canvas); drawEmptyCanvas(prepared.context, prepared.width, prepared.height, text); } }
function drawEmptyCanvas(context, width, height, text) { context.fillStyle = "#111"; context.fillRect(0, 0, width, height); context.fillStyle = "#9ba2aa"; context.font = "13px system-ui"; context.textAlign = "center"; context.fillText(text, width / 2, height / 2); context.textAlign = "left"; }
function drawEmptyCanvas(context, width, height, text) { context.fillStyle = "#111"; context.fillRect(0, 0, width, height); context.fillStyle = "#9ba2aa"; context.font = "13px system-ui"; context.textAlign = "center"; context.fillText(t(text), width / 2, height / 2); context.textAlign = "left"; }
// True when the node is an AusBoss transform node whose editor can open
// (installed by installTransformNode). Used by the pack-wide command.
+10 -5
View File
@@ -81,7 +81,7 @@ export function ensureCardCss() {
style.textContent = `
.ausboss-card{position:relative;box-sizing:border-box;width:100%;height:100%;display:flex;flex-direction:column;gap:${ROW_GAP}px;padding:${CARD_PADDING}px 8px;overflow:hidden;border:1px solid transparent;border-radius:${RADIUS_CARD}px;background:${T.card};font:12px/1.3 ${FONT};color:${T.inkSoft};pointer-events:none}
.ausboss-card-row{display:grid;grid-template-columns:minmax(56px,30%) 1fr;align-items:center;gap:8px;height:${ROW_HEIGHT}px;flex:none;pointer-events:auto}
.ausboss-card-row.hidden{display:none}
.ausboss-card .ausboss-card-row.hidden{display:none}
.ausboss-card-row.linked{opacity:.5}
.ausboss-card-row.linked .ausboss-card-control{pointer-events:none}
.ausboss-card-row.muted .ausboss-card-control{opacity:.35;pointer-events:none}
@@ -97,6 +97,7 @@ export function ensureCardCss() {
.ausboss-card-row.area{display:block}
.ausboss-card-row.panel{display:block}
.ausboss-card-row.area.grow{flex:1 1 auto;height:auto}
.ausboss-card-row.panel.grow{flex:1 1 auto;height:auto}
.ausboss-card-label{overflow:hidden;white-space:nowrap;text-overflow:ellipsis;color:${T.label};font-size:11px;user-select:none}
.ausboss-card-control{display:flex;align-items:center;gap:6px;min-width:0;height:100%}
.ausboss-card-field{display:flex;align-items:center;gap:6px;flex:1 1 0;min-width:0;height:100%}
@@ -215,9 +216,10 @@ function isFloatWidget(widget) {
// - `top` lifts the widgets' sockets
// into the node's slot column
// { section: "Caption" }
// { panel: (node) => ({ element, sync(values) }), height }
// { panel: (node) => ({ element, sync(values) }), height, grow?, when? }
// - the node's own display, on a row
// of the card
// of the card; `grow` takes the
// node's spare height
// { group: "advanced", label: "More" } - a disclosure; later rows with
// group: "advanced" sit under it
// A numeric row may have readOnlyText(node, values): nonempty text replaces
@@ -538,7 +540,8 @@ export function mountWidgetCard(node, { rows, minWidth = 300, first = false, hid
}
if (row.panel) {
const line = el("div", "ausboss-card-row panel");
line.style.height = `${rowHeight(row)}px`;
if (row.grow) { line.classList.add("grow"); line.style.minHeight = `${rowHeight(row)}px`; }
else line.style.height = `${rowHeight(row)}px`;
const panel = row.panel(node);
line.append(panel.element);
state.rows.push({ row, element: line, syncs: panel.sync ? [panel.sync] : [] });
@@ -762,7 +765,7 @@ export function mountWidgetCard(node, { rows, minWidth = 300, first = false, hid
}
const groups = {};
for (const entry of state.rows) if (entry.header) groups[entry.row.group] = groupOpen(entry.row.group);
const visible = visibleRows(state.rows.map((entry) => entry.row), vals, groups);
const visible = visibleRows(state.rows.map((entry) => entry.row), vals, groups, node);
const visibleSet = new Set(visible);
const tops = rowTops(visible, look);
state.rowTop = new Map();
@@ -863,5 +866,7 @@ export function mountWidgetCard(node, { rows, minWidth = 300, first = false, hid
refresh();
state.refresh = refresh; state.setGroupOpen = setGroupOpen; state.groupOpen = groupOpen;
// A panel that changes the card's rows itself (a tab) redraws it as a change by hand.
state.refreshByHand = () => byHand(refresh);
return state;
}
+4 -2
View File
@@ -18,12 +18,14 @@ const SEGMENT_MAX_CHARS = 26;
// Which rows the current values leave visible. `groups` maps a group name to
// its open state; a row inside a closed group is out, a row whose `when`
// says no is out, a group header stays as long as any row under it exists.
export function visibleRows(rows, values, groups = {}) {
// `when(values, node)` gets the node too, for a row that follows a display
// choice kept on the node rather than a widget value (a tab).
export function visibleRows(rows, values, groups = {}, node = null) {
return rows.filter((row) => {
if (row.group !== undefined && row.widget === undefined && row.pair === undefined && row.section === undefined) {
return true; // the disclosure header itself
}
if (row.when && row.when(values) === false) return false;
if (row.when && row.when(values, node) === false) return false;
if (row.inGroup && !groups[row.inGroup]) return false;
return true;
});
+37
View File
@@ -181,6 +181,43 @@ export function folderPath(dir) {
return `ComfyUI/models/${dir}`;
}
// ComfyUI still accepts two old folder names everywhere except in its
// /models/<folder> list, which answers 404 for them. Stability Matrix and
// older notes use them, so a row naming one is checked under the new name.
const LEGACY_FOLDERS = { clip: "text_encoders", unet: "diffusion_models" };
export function modelFolderKey(dir) {
const key = str(dir, 200).trim();
return Object.hasOwn(LEGACY_FOLDERS, key) ? LEGACY_FOLDERS[key] : key;
}
// Every folder this install reads for `dir`, from ComfyUI's
// /experiment/models list ([{ name, folders: [path, ...] }]). Launchers
// such as Stability Matrix add their own shared folders through
// extra_model_paths.yaml, so a file may live outside ComfyUI/models.
export function installFolders(dir, folderList) {
if (!dir || dir === INPUT_FOLDER || !Array.isArray(folderList)) return [];
const key = modelFolderKey(dir);
const entry = folderList.find((item) => item && item.name === key);
if (!entry || !Array.isArray(entry.folders)) return [];
return [...new Set(entry.folders.map((folder) => str(folder, 1000)).filter(Boolean))];
}
// The folders from `installFolders` with a name of their own, such as
// Stability Matrix's Data/Models/Lora: the ones worth showing, since a
// person would not guess them. A folder named like the kind itself
// (models/loras, output/loras, a shared .../loras) reads the way the card
// already says, so it is left out.
export function sharedFolders(dir, folderList) {
const key = modelFolderKey(dir);
const usual = new Set([key, ...Object.keys(LEGACY_FOLDERS).filter((name) => LEGACY_FOLDERS[name] === key)]
.map((name) => name.toLowerCase()));
return installFolders(dir, folderList).filter((folder) => {
const last = folder.replace(/\\/g, "/").replace(/\/+$/, "").split("/").pop().toLowerCase();
return !usual.has(last);
});
}
// Rows grouped by folder in first-seen order, so the card reads like the
// install tree: one heading per folder, its files beneath.
export function groupModels(models) {
+15 -7
View File
@@ -11,6 +11,7 @@ import { chainCallback, notifyAusbossChange } from "../shared/index.mjs";
import { formatWidgetVisibility } from "../shared/save_video_formats.mjs";
import { hideInputsInDef } from "../shared/widget_visibility.mjs";
import { castChips } from "../shared/h3_cast_chips.mjs";
import { FULL, fullPromptBox, isEdited, promptTab, promptTabs, simpleEditedNote } from "../shared/h3_full_prompt.mjs";
import { cameraChoiceLabel, clipSetsDuration } from "../shared/h3_duration.mjs";
import { loadImagePreview, loadImageStrip } from "../shared/load_image_strip.mjs";
import { momentStrip } from "../shared/moment_strip.mjs";
@@ -390,18 +391,25 @@ const CARDS = {
// sockets, and each picture's job sits under the words.
AUSBOSS_NODES_H3PromptWriter: {
minWidth: 420,
hide: ["job_1", "job_2", "job_3", "job_4", "video_job"],
socketless: ["job_1", "job_2", "job_3", "job_4", "video_job"],
resetUnknown: { sound: "", music: "", clip_sound: false },
hide: ["job_1", "job_2", "job_3", "job_4", "video_job", "full_prompt"],
socketless: ["job_1", "job_2", "job_3", "job_4", "video_job", "full_prompt"],
resetUnknown: { sound: "", music: "", clip_sound: false, full_prompt: "" },
rows: [
{ section: "What happens" },
// Simple is the card as it always was; Full prompt shows the prompt the
// node wrote and sends an edit made there instead (js/shared/h3_full_prompt.mjs).
{ panel: promptTabs, height: 30 },
{ panel: simpleEditedNote, height: 30, when: (values, node) => promptTab(node) !== FULL && isEdited(values) },
{ section: "What H3 gets", when: (values, node) => promptTab(node) === FULL },
{ panel: fullPromptBox, height: 210, grow: true, when: (values, node) => promptTab(node) === FULL },
{ section: "What happens", when: (values, node) => promptTab(node) !== FULL },
{
when: (values, node) => promptTab(node) !== FULL,
widget: "script", kind: "textarea", height: 118, grow: true,
placeholder: "Type what happens, one line for each thing. Picture 1 is @1. A blank line cuts to a new place.\n\nSwap: leave empty, or name who goes. Optional new look on its own line: @1 looks like a woman with blonde hair and a black hoodie.",
},
{ panel: momentStrip, height: 76 },
{ widget: "sound", label: "Sound", placeholder: "rain on a window" },
{ widget: "music", label: "Music", placeholder: "slow piano: music makes it louder" },
{ panel: momentStrip, height: 76, when: (values, node) => promptTab(node) !== FULL },
{ widget: "sound", label: "Sound", placeholder: "rain on a window", when: (values, node) => promptTab(node) !== FULL },
{ widget: "music", label: "Music", placeholder: "slow piano: music makes it louder", when: (values, node) => promptTab(node) !== FULL },
{ section: "Pictures and settings" },
{ panel: castChips, height: 30 },
{ widget: "seconds", label: "Length", suffix: "s", readOnlyText: (node, values) => clipSetsDuration(node, values) ? "From the clip" : "", readOnlyTitle: "This video job uses the incoming clip, so Length is not used." },
+50 -3
View File
@@ -30,10 +30,12 @@ import {
MODEL_COLUMNS,
groupModels,
hostLabel,
installFolders,
listedSpelling,
loadersNeeding,
loraRowsNeeding,
matchInstalled,
modelFolderKey,
noteFit,
noteIsEmpty,
noteShowsTileFace,
@@ -43,6 +45,7 @@ import {
parseMarkdown,
rowFromCells,
serializeNote,
sharedFolders,
subfolderOf,
} from "../shared/workflow_note.mjs";
import { comboValues, commitWidgetValue } from "../shared/widget_card_math.mjs";
@@ -94,12 +97,13 @@ const PANEL_TOP = 2;
const folderLists = new Map(); // dir -> { at, promise }
let modelFolders = null; // Promise<string[]> from GET /models
let folderInfo = null; // { at, promise } of GET /experiment/models
function listFolder(dir, fresh = false) {
const cached = folderLists.get(dir);
if (!fresh && cached && performance.now() - cached.at < FOLDER_CACHE_MS) return cached.promise;
const promise = api
.fetchApi(`/models/${encodeURIComponent(dir)}`)
.fetchApi(`/models/${encodeURIComponent(modelFolderKey(dir))}`)
.then((response) => (response.ok ? response.json() : null))
.then((files) => (Array.isArray(files) ? files : null))
.catch(() => null);
@@ -124,6 +128,22 @@ function knownFolders() {
return modelFolders;
}
// Where this install looks for each kind of model: [{ name, folders }].
// Launchers such as Stability Matrix add shared folders outside
// ComfyUI/models through extra_model_paths.yaml. [] when the endpoint is
// missing (an older or newer ComfyUI): the card then just names the usual
// folder, as before.
function installFolderList(fresh = false) {
if (!fresh && folderInfo && performance.now() - folderInfo.at < FOLDER_CACHE_MS) return folderInfo.promise;
const promise = api
.fetchApi("/experiment/models")
.then((response) => (response.ok ? response.json() : []))
.then((list) => (Array.isArray(list) ? list : []))
.catch(() => []);
folderInfo = { at: performance.now(), promise };
return promise;
}
function nodeTypeRegistered(type) {
return Boolean(type && globalThis.LiteGraph?.registered_node_types?.[type]);
}
@@ -214,6 +234,8 @@ ${TILE_FACE_CSS}
.ausboss-note-body a:hover,.ausboss-note-link:hover{text-decoration:underline;}
.ausboss-note-folder{margin:8px 0 4px;color:#a9c4c2;font:11px ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;}
.ausboss-note-folder:first-child{margin-top:0;}
.ausboss-note-folder-also{margin:-2px 0 4px 18px;color:#7f9896;font:10.5px ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;overflow-wrap:anywhere;}
.ausboss-note-folder-also[hidden]{display:none;}
.ausboss-note-row{display:flex;align-items:center;gap:8px;min-height:30px;padding:3px 0;}
.ausboss-note-dot{flex:none;width:8px;height:8px;border-radius:50%;background:#4b5a5a;}
.ausboss-note-dot.checking{background:#4b5a5a;animation:ausboss-note-pulse 1s ease-in-out infinite;}
@@ -525,6 +547,7 @@ function render(state) {
const scroll = state.scroll;
scroll.textContent = "";
state.rows = [];
state.folderHints = new Map();
const head = el("div", "ausboss-note-head");
head.append(el("h1", "ausboss-note-title", note.title || "Untitled workflow"));
@@ -612,6 +635,10 @@ function renderSections(state, scroll) {
section.append(heading);
for (const group of groupModels(note.models)) {
section.append(el("div", "ausboss-note-folder", `📂 ${group.path}`));
const also = el("div", "ausboss-note-folder-also");
also.hidden = true;
section.append(also);
(state.folderHints ??= new Map()).set(group.dir, also);
for (const row of group.rows) section.append(modelRow(state, row));
}
scroll.append(section);
@@ -639,11 +666,26 @@ function renderSections(state, scroll) {
checkModels(state, false);
}
// A launcher's shared model folder (Stability Matrix keeps LoRAs in
// Data/Models/Lora) under the usual ComfyUI/models/<dir> line, so the card
// says where this install also finds the files and where to put new ones.
function showSharedFolders(state, dir, list) {
const also = state.folderHints?.get(dir);
if (!also) return;
const shared = sharedFolders(dir, list);
also.hidden = !shared.length;
also.textContent = shared.length ? `also read from ${shared.join(", ")}` : "";
also.title = shared.length
? "This install also reads this kind of model from here (set in extra_model_paths.yaml, for example by Stability Matrix). A file in either place counts."
: "";
}
async function checkModels(state, fresh) {
const generation = (state.checkGeneration = (state.checkGeneration || 0) + 1);
const rows = state.rows;
const picked = [];
for (const entry of rows) setDot(entry.dot, "checking", "checking…");
const folderList = installFolderList(fresh);
const byDir = new Map();
for (const entry of rows) {
const dir = entry.row.dir;
@@ -669,8 +711,13 @@ async function checkModels(state, fresh) {
}));
return;
}
const files = await listFolder(dir, fresh);
const [files, list] = await Promise.all([listFolder(dir, fresh), folderList]);
if (generation !== state.checkGeneration) return;
showSharedFolders(state, dir, list);
const searched = installFolders(dir, list);
const notFound = searched.length
? `Not found in the ${searched.length === 1 ? "folder" : "folders"} this install reads for ${dir}: ${searched.join(", ")}`
: `Not found in ComfyUI/models/${dir}`;
for (const entry of entries) {
if (files === null) {
setDot(entry.dot, "unknown", `This install has no "${dir}" model folder, so the file is not checked`);
@@ -695,7 +742,7 @@ async function checkModels(state, fresh) {
setDot(entry.dot, "ok", `Found: ${match.path}`);
entry.showInstalled(match.path);
} else {
setDot(entry.dot, "missing", `Not found in ComfyUI/models/${dir}`);
setDot(entry.dot, "missing", notFound);
entry.showDownload();
}
}
+172 -3
View File
@@ -216,6 +216,9 @@
},
"feather": {
"name": "羽化"
},
"remove_tint": {
"name": "去除偏色"
}
},
"outputs": {
@@ -292,7 +295,128 @@
},
"AUSBOSS_NODES_H3PromptWriter": {
"display_name": "H3 提示词写手 🆎",
"description": "每发生一件事写一行,给每张图片和视频分配一个任务,它就会写出 MiniMax H3 需要的提示词,并给出匹配的宽度和高度。视频里有两个人时,写明要换谁,就只替换那个人。"
"description": "每发生一件事写一行,给每张图片和视频分配一个任务,它就会写出 MiniMax H3 需要的提示词,并给出匹配的宽度和高度。视频里有两个人时,写明要换谁,就只替换那个人。",
"inputs": {
"script": {
"name": "脚本"
},
"seconds": {
"name": "长度"
},
"clip": {
"name": "片段"
},
"picture_1": {
"name": "图片 1"
},
"picture_2": {
"name": "图片 2"
},
"picture_3": {
"name": "图片 3"
},
"picture_4": {
"name": "图片 4"
},
"video": {
"name": "视频"
},
"video_sound": {
"name": "视频声音"
},
"voice": {
"name": "人声"
},
"song": {
"name": "歌曲"
},
"camera": {
"name": "镜头"
},
"look": {
"name": "风格"
},
"song_start": {
"name": "歌曲起点"
},
"cut_on_beat": {
"name": "按节拍切换"
},
"language": {
"name": "语言"
},
"job_1": {
"name": "图片 1 任务"
},
"job_2": {
"name": "图片 2 任务"
},
"job_3": {
"name": "图片 3 任务"
},
"job_4": {
"name": "图片 4 任务"
},
"video_job": {
"name": "视频任务"
},
"sound": {
"name": "声音"
},
"music": {
"name": "音乐"
},
"clip_sound": {
"name": "片段自带声音"
},
"full_prompt": {
"name": "完整提示词"
}
},
"outputs": {
"0": {
"name": "提示词"
},
"1": {
"name": "图片 1"
},
"2": {
"name": "图片 2"
},
"3": {
"name": "图片 3"
},
"4": {
"name": "图片 4"
},
"5": {
"name": "视频"
},
"6": {
"name": "视频声音"
},
"7": {
"name": "人声"
},
"8": {
"name": "歌曲"
},
"9": {
"name": "垫底歌曲"
},
"10": {
"name": "帧数"
},
"11": {
"name": "宽度"
},
"12": {
"name": "高度"
},
"13": {
"name": "保留片段声音"
}
}
},
"AUSBOSS_NODES_ImageCropRotatePad": {
"display_name": "图像裁剪 + 旋转 + 扩边 🆎",
@@ -984,6 +1108,9 @@
},
"fine_edges": {
"name": "精细边缘"
},
"new_picture": {
"name": "换新图时"
}
},
"outputs": {
@@ -1004,6 +1131,15 @@
"inputs": {
"expression": {
"name": "表达式"
},
"a": {
"name": "a"
},
"b": {
"name": "b"
},
"c": {
"name": "c"
}
},
"outputs": {
@@ -1021,6 +1157,12 @@
"inputs": {
"on_mismatch": {
"name": "不匹配时"
},
"a": {
"name": "a"
},
"b": {
"name": "b"
}
},
"outputs": {
@@ -1126,6 +1268,9 @@
},
"batch_size": {
"name": "批次大小"
},
"workflow_sizes": {
"name": "工作流尺寸"
}
},
"outputs": {
@@ -1337,6 +1482,14 @@
"index": {
"name": "索引"
}
},
"outputs": {
"0": {
"name": "a"
},
"1": {
"name": "b"
}
}
},
"AUSBOSS_NODES_StepPreview": {
@@ -1364,6 +1517,9 @@
},
"paste_onto": {
"name": "贴到"
},
"follow_changes": {
"name": "跟随变化"
}
},
"outputs": {
@@ -1688,6 +1844,9 @@
},
"fixed_frames": {
"name": "固定帧数"
},
"last_seconds": {
"name": "最后几秒"
}
},
"outputs": {
@@ -1764,11 +1923,21 @@
},
"AUSBOSS_NODES_CalloutTile": {
"display_name": "标注卡片 🆎",
"description": "紧凑的标题或彩色链接按钮。双击编辑,拖动角落调整大小。旧版节点包会将它显示为缺失节点,请更新 ComfyUI-AusBoss。"
"description": "紧凑的标题或彩色链接按钮。双击编辑,拖动角落调整大小。旧版节点包会将它显示为缺失节点,请更新 ComfyUI-AusBoss。",
"inputs": {
"text": {
"name": "文字"
}
}
},
"AUSBOSS_NODES_WorkflowNoteTile": {
"display_name": "工作流说明卡片 🆎",
"description": "点击打开完整说明的小按钮。点击铅笔编辑,拖动角落调整大小。旧版节点包会将它显示为缺失节点,请更新 ComfyUI-AusBoss。"
"description": "点击打开完整说明的小按钮。点击铅笔编辑,拖动角落调整大小。旧版节点包会将它显示为缺失节点,请更新 ComfyUI-AusBoss。",
"inputs": {
"note": {
"name": "备注"
}
}
},
"AUSBOSS_NODES_FlashVSRUpscale": {
"display_name": "FlashVSR 视频放大 🆎",
+38
View File
@@ -9,6 +9,7 @@ from __future__ import annotations
import json
import os
import re
from collections import OrderedDict
from pathlib import Path
from typing import Any
@@ -64,6 +65,7 @@ def parse_lora_stack(raw: str | None) -> list[dict[str, Any]]:
enabled = bool(entry.get("enabled", True)) and entry.get("group_off") is not True
rows.append(
{
"id": str(entry.get("id") or ""),
"name": name,
"strength": strength,
"strength_clip": clamp_strength(entry.get("strength_clip", strength), strength),
@@ -74,6 +76,42 @@ def parse_lora_stack(raw: str | None) -> list[dict[str, Any]]:
return rows
# A row's strength can come in on a link: the node then has an input named
# strength_<row id>, made by the frontend when a value is dropped on the row.
ROW_STRENGTH_PREFIX = "strength_"
_ROW_INPUT = re.compile(r"^strength_[A-Za-z0-9_-]{1,64}$")
def is_row_strength_input(name: Any) -> bool:
return isinstance(name, str) and bool(_ROW_INPUT.match(name))
def apply_linked_strengths(rows: list[dict[str, Any]], linked: dict[str, Any]) -> list[dict[str, Any]]:
"""Rows with each linked value as the model strength.
The CLIP strength keeps the ratio the row had to its model strength, so
one slider moves the whole LoRA. A row at model strength 0 has no ratio
to keep; its CLIP strength then follows the slider one for one.
"""
values = {
name[len(ROW_STRENGTH_PREFIX):]: value
for name, value in linked.items()
if is_row_strength_input(name) and value is not None
}
if not values:
return rows
out = []
for row in rows:
row_id = row.get("id")
if not row_id or row_id not in values:
out.append(row)
continue
strength = clamp_strength(values[row_id], row["strength"])
ratio = row["strength_clip"] / row["strength"] if row["strength"] else 1.0
out.append({**row, "strength": strength, "strength_clip": clamp_strength(strength * ratio, strength)})
return out
def collect_trigger_words(rows: list[dict[str, Any]], separator: str = ", ") -> str:
"""Join enabled rows' trigger words, deduplicated, order preserved."""
seen: set[str] = set()
+62
View File
@@ -0,0 +1,62 @@
"""Read the [project] table of a pyproject.toml.
``tomllib`` is in the standard library only from Python 3.11. Some ComfyUI
installs still run 3.10 (Stability Matrix, older portable builds), and there
a bare ``import tomllib`` stopped the whole pack from loading. So this uses
``tomllib`` when it is there, the ``tomli`` backport when that is installed,
and otherwise a small reader that takes the plain ``key = "value"`` lines of
[project], which is all the pack reads (its name and version).
"""
from __future__ import annotations
import re
try:
import tomllib as _toml
except ModuleNotFoundError: # Python 3.10
try:
import tomli as _toml
except ModuleNotFoundError:
_toml = None
_SECTION = re.compile(r"^\s*\[([^\[\]]+)\]\s*(?:#.*)?$")
_STRING_KEY = re.compile(r"""^\s*([A-Za-z0-9_-]+)\s*=\s*(?:"([^"]*)"|'([^']*)')\s*(?:#.*)?$""")
def _plain_project(text: str) -> dict:
"""The top-level string keys of [project], without a TOML library."""
project: dict = {}
inside = False
for line in text.splitlines():
section = _SECTION.match(line)
if section:
inside = section.group(1).strip() == "project"
continue
if not inside:
continue
match = _STRING_KEY.match(line)
if match and match.group(1) not in project:
value = match.group(2) if match.group(2) is not None else match.group(3)
project[match.group(1)] = value
return project
def project_from_text(text: str) -> dict:
"""The [project] table of pyproject text, or {} when it has none."""
if _toml is not None:
project = _toml.loads(text).get("project", {})
return project if isinstance(project, dict) else {}
return _plain_project(text)
def read_project(path: str) -> dict:
"""The [project] table of the pyproject.toml at ``path``.
Raises OSError or a parse error like ``tomllib.load`` does, so callers
keep their own fallbacks.
"""
with open(path, "rb") as f:
raw = f.read()
# utf-8-sig drops a BOM, which tomllib itself would reject.
return project_from_text(raw.decode("utf-8-sig"))
+3 -3
View File
@@ -14,7 +14,8 @@ loads.
from __future__ import annotations
import os
import tomllib
from ._pyproject import read_project
PACK_NAME = "ausboss-nodes"
# A copy that has this file knows how to step aside.
@@ -24,8 +25,7 @@ _GUARD_FILE = os.path.join("nodes", "_single_copy.py")
def _read_pack(folder: str) -> dict | None:
"""Name the pack copy in ``folder``, or None when it is another pack."""
try:
with open(os.path.join(folder, "pyproject.toml"), "rb") as f:
project = tomllib.load(f).get("project", {})
project = read_project(os.path.join(folder, "pyproject.toml"))
except Exception:
return None
if project.get("name") != PACK_NAME:
+25 -1
View File
@@ -285,6 +285,19 @@ class AusBossH3PromptWriter:
),
},
),
"full_prompt": (
"STRING",
{
"default": "",
"multiline": True,
"dynamicPrompts": False,
"tooltip": (
"Your own edit of the finished prompt, from the Full prompt tab. When it holds "
"text, H3 gets exactly this text instead of the prompt the node writes. Empty "
"means the node's own prompt."
),
},
),
},
}
@@ -321,7 +334,7 @@ class AusBossH3PromptWriter:
"The height of your video, or else of your first picture. Wire it into H3's height.",
"On when the finished clip should keep your video's own sound: with clip_sound on, or always for change something.",
)
FUNCTION = "write"
FUNCTION = "run"
def write(self, script, seconds, clip=None, picture_1=None, picture_2=None, picture_3=None, picture_4=None, video=None,
video_sound=None, voice=None, song=None, camera=AS_TYPED, look=FROM_PICTURE, song_start=0.0, cut_on_beat=True,
@@ -378,6 +391,17 @@ class AusBossH3PromptWriter:
ordered = [*given.values(), None, None, None, None][: len(PICTURES)]
return (text, *ordered, video, video_sound, voice, song, song_under, frames, *clip_shape(video, ordered[0]), keeps_clip_sound)
def run(self, script, seconds, full_prompt="", **inputs):
# The Full prompt tab shows what the node wrote; an edit typed there is sent in its place.
written, *rest = self.write(script, seconds, **inputs)
return {"ui": {"written_prompt": [written]}, "result": (sent_prompt(written, full_prompt), *rest)}
def sent_prompt(written, edited):
"""The prompt H3 gets: the edit from the Full prompt tab when it holds any text, else the written one."""
edited = str(edited or "")
return edited if edited.strip() else written
def _register_routes():
try:
+29 -4
View File
@@ -5,7 +5,9 @@ from __future__ import annotations
from ._execution_helpers import ignore_extra_inputs
from ._lora_helpers import (
MISSING_MODES,
apply_linked_strengths,
apply_lora_stack,
is_row_strength_input,
collect_trigger_words,
missing_lora_rows,
parse_lora_stack,
@@ -16,6 +18,29 @@ from ._lora_helpers import (
)
class _OptionalWithRowStrengths(dict):
"""The node's optional inputs, plus strength_<row id> for any row.
ComfyUI passes a node only the inputs it declares. A row's strength input
exists only while something is linked to that row, so its name is not
known ahead: this dict answers for any such name.
"""
def __contains__(self, key):
return super().__contains__(key) or is_row_strength_input(key)
def __getitem__(self, key):
if not super().__contains__(key) and is_row_strength_input(key):
return ("FLOAT", {
"forceInput": True,
"tooltip": "A linked strength for one row. The CLIP strength keeps its ratio.",
})
return super().__getitem__(key)
def get(self, key, default=None):
return self[key] if key in self else default
class AusBossLoraLoader:
CATEGORY = "🆎 AusBoss/Loaders"
DESCRIPTION = (
@@ -53,7 +78,7 @@ class AusBossLoraLoader:
},
),
},
"optional": {
"optional": _OptionalWithRowStrengths({
"clip": ("CLIP", {"tooltip": "Optional CLIP to patch; without it, CLIP strengths are ignored."}),
"trigger_separator": (
"STRING",
@@ -81,7 +106,7 @@ class AusBossLoraLoader:
),
},
),
},
}),
}
RETURN_TYPES = ("MODEL", "CLIP", "STRING")
@@ -98,8 +123,8 @@ class AusBossLoraLoader:
)
FUNCTION = "load_loras"
def load_loras(self, model, loras: str, clip=None, trigger_separator=", ", on_missing="error"):
rows = parse_lora_stack(loras)
def load_loras(self, model, loras: str, clip=None, trigger_separator=", ", on_missing="error", **linked):
rows = apply_linked_strengths(parse_lora_stack(loras), linked)
missing: list[dict] = []
model, clip = apply_lora_stack(model, clip, rows, on_missing=on_missing, missing=missing)
# A row skipped for a missing file loaded nothing, so its words stay
+4
View File
@@ -76,6 +76,10 @@ def pack_widget_names() -> dict[str, list[str]]:
groups = {k.value: v for k, v in zip(returned[0].keys, returned[0].values) if isinstance(k, ast.Constant)}
for group in ("required", "optional"):
inputs = groups.get(group)
# A group wrapped in a call, such as LoRA Loader's open
# optional inputs, lists its fixed inputs in the one dict.
if isinstance(inputs, ast.Call) and len(inputs.args) == 1:
inputs = inputs.args[0]
if not isinstance(inputs, ast.Dict):
continue
for name, spec in zip(inputs.keys, inputs.values):
+2 -1
View File
@@ -251,7 +251,8 @@
"video_job",
"sound",
"music",
"clip_sound"
"clip_sound",
"full_prompt"
],
"outputs": [
[
+45
View File
@@ -0,0 +1,45 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { FULL, SIMPLE, TAB_PROPERTY, boxText, editValue, isEdited, promptTab, writtenFromOutput } from "../js/shared/h3_full_prompt_math.mjs";
import { visibleRows } from "../js/shared/widget_card_math.mjs";
const WRITTEN = "summary:\nA slow push in. One continuous shot with no cuts.";
test("an edit is kept only when it differs from what the node wrote", () => {
assert.equal(editValue("summary:\nOne continuous shot with no cuts.", WRITTEN), "summary:\nOne continuous shot with no cuts.");
assert.equal(editValue(WRITTEN, WRITTEN), "");
assert.equal(editValue(` ${WRITTEN}\n`, WRITTEN), "");
assert.equal(editValue(" \n", WRITTEN), "");
// Before any run there is nothing written: whatever is typed is the edit.
assert.equal(editValue("my own prompt", ""), "my own prompt");
});
test("the box shows the edit, else the last written prompt", () => {
assert.equal(boxText({ full_prompt: "" }, WRITTEN), WRITTEN);
assert.equal(boxText({ full_prompt: "mine" }, WRITTEN), "mine");
assert.equal(boxText({}, ""), "");
assert.equal(isEdited({ full_prompt: " \n" }), false);
assert.equal(isEdited({ full_prompt: "mine" }), true);
});
test("the tab is Simple unless the node says Full", () => {
assert.equal(promptTab({}), SIMPLE);
assert.equal(promptTab({ properties: { [TAB_PROPERTY]: "nonsense" } }), SIMPLE);
assert.equal(promptTab({ properties: { [TAB_PROPERTY]: FULL } }), FULL);
});
test("the written prompt is read from a run's ui output", () => {
assert.equal(writtenFromOutput({ written_prompt: [WRITTEN] }), WRITTEN);
assert.equal(writtenFromOutput({ written_prompt: WRITTEN }), WRITTEN);
assert.equal(writtenFromOutput({ text: ["other"] }), null);
assert.equal(writtenFromOutput(null), null);
});
test("a row's when can follow a choice kept on the node", () => {
const simple = { widget: "script", when: (values, node) => promptTab(node) !== FULL };
const full = { panel: () => ({}), when: (values, node) => promptTab(node) === FULL };
const node = { properties: {} };
assert.deepEqual(visibleRows([simple, full], {}, {}, node), [simple]);
node.properties[TAB_PROPERTY] = FULL;
assert.deepEqual(visibleRows([simple, full], {}, {}, node), [full]);
});
+72
View File
@@ -0,0 +1,72 @@
// The Chinese on the pack's own node faces (js/shared/i18n.mjs).
//
// - a string with no Chinese entry stays English,
// - every word a widget card shows has a Chinese entry, or is on the short
// list of things that deliberately stay English,
// - only displayed text is translated: nothing in a card config that names a
// widget or a value is a key of the table by accident of spelling.
import assert from "node:assert/strict";
import fs from "node:fs";
import test from "node:test";
import { PATTERNS, STAYS_ENGLISH, ZH } from "../js/shared/i18n_zh.mjs";
import { isChineseLocale, translateText } from "../js/shared/i18n.mjs";
import { PANEL_LABELS } from "../js/shared/panel_controls.mjs";
const cards = fs.readFileSync(new URL("../js/widget_cards/index.js", import.meta.url), "utf8");
// Every string a card shows: row labels, group headers, pill texts, the
// words of a choice (`labels`), tooltips (`title`, `titles`), placeholders,
// button captions.
function displayedStrings(source) {
const found = new Set();
const literal = (raw) => JSON.parse(`"${raw}"`);
for (const match of source.matchAll(/\b(?:label|onText|offText|placeholder|title|muteTitle|readOnlyTitle|section|text|readOnlyText)\s*:\s*"((?:[^"\\]|\\.)*)"/g)) found.add(literal(match[1]));
for (const block of source.matchAll(/\b(?:labels|titles)\s*:\s*\{([^}]*)\}/g)) {
for (const match of block[1].matchAll(/:\s*"((?:[^"\\]|\\.)*)"/g)) found.add(literal(match[1]));
}
return found;
}
test("an unknown string stays English", () => {
assert.equal(translateText("A sentence no table has ever heard of"), "A sentence no table has ever heard of");
assert.equal(translateText(""), "");
assert.equal(translateText(" "), " ");
assert.equal(translateText("constructor"), "constructor");
assert.equal(translateText("toString"), "toString");
assert.equal(translateText("Preview", {}, []), "Preview");
});
test("a known string is translated and keeps the spaces around it", () => {
assert.equal(translateText("Feather"), ZH.Feather);
assert.equal(translateText(" Feather\n"), ` ${ZH.Feather}\n`);
assert.notEqual(ZH.Feather, "Feather");
});
test("the scrub hint is translated around a tooltip", () => {
const out = translateText("Feather. Drag to scrub, click to type a number or a sum (1024*1.5), arrows to step; Shift = fine.");
assert.match(out, /拖动调节/);
assert.ok(out.startsWith("Feather."));
const known = translateText("Do nothing Drag to scrub, click to type a number or a sum (1024*1.5), arrows to step; Shift = fine.");
assert.ok(known.startsWith(ZH["Do nothing"]) && /拖动调节/.test(known));
});
test("every Chinese language code takes the Chinese table", () => {
for (const code of ["zh", "zh-CN", "zh-TW", "zh_CN", "ZH"]) assert.equal(isChineseLocale(code), true, code);
for (const code of ["en", "ja", "ko", "", undefined, null, "zhx"]) assert.equal(isChineseLocale(code), false, String(code));
});
test("no entry is empty or the same as its key without being listed as English", () => {
for (const [english, chinese] of Object.entries(ZH)) {
assert.ok(typeof chinese === "string" && chinese.length > 0, `empty entry for ${english}`);
}
for (const [pattern] of PATTERNS) assert.ok(pattern instanceof RegExp);
});
test("every word a widget card shows has a Chinese entry or stays English on purpose", () => {
const strings = new Set([...displayedStrings(cards), ...Object.values(PANEL_LABELS).flatMap((value) => (typeof value === "string" ? [value] : Object.values(value)))]);
assert.ok(strings.size > 150, `only ${strings.size} strings found: the extraction broke`);
const missing = [...strings].filter((text) => !(text in ZH) && !STAYS_ENGLISH.has(text) && !/^[^A-Za-z]*$/.test(text));
assert.deepEqual(missing, []);
});
+11 -4
View File
@@ -2,6 +2,7 @@
import ast
import copy
import importlib.util
import json
import os
from pathlib import Path
@@ -229,11 +230,17 @@ class CommandTests(unittest.TestCase):
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
with patch.object(changelog_notes, "ROOT", self.root):
self.assertEqual(changelog_notes.pyproject_version(), version)
# The banner's _read_version and the single-copy guard both read
# through nodes/_pyproject.py: check it with a TOML library and with
# the plain reader that Python 3.10 without tomli falls back to.
spec = importlib.util.spec_from_file_location("ausboss_pyproject", ROOT / "nodes" / "_pyproject.py")
reader_module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(reader_module)
self.assertEqual(reader_module.read_project(str(path)).get("version"), version)
self.assertEqual(reader_module._plain_project(path.read_text()).get("version"), version)
tree = ast.parse((ROOT / "__init__.py").read_text())
body = [n for n in tree.body if isinstance(n, (ast.Import, ast.ImportFrom)) or isinstance(n, ast.FunctionDef) and n.name == "_read_version"]
scope = {"__file__": str(self.root / "__init__.py")}
exec(compile(ast.Module(body=body, type_ignores=[]), "version_reader", "exec"), scope)
self.assertEqual(scope["_read_version"](), version)
reader = next(n for n in tree.body if isinstance(n, ast.FunctionDef) and n.name == "_read_version")
self.assertIn("read_project", ast.unparse(reader))
if __name__ == "__main__":
+14 -1
View File
@@ -1294,6 +1294,19 @@ class NodeTests(unittest.TestCase):
self.assertEqual(frames, 141)
self.assertIn("<Audio 1>", node.write(SAYS, 6, picture_1=PICTURE, voice=self.audio())[0])
def test_an_edited_full_prompt_is_sent_and_the_written_one_shown(self):
node = AusBossH3PromptWriter()
written = node.write(LINES, 6, picture_1=PICTURE)
plain = node.run(LINES, 6, picture_1=PICTURE)
self.assertEqual(plain["ui"]["written_prompt"], [written[0]])
self.assertEqual(plain["result"][0], written[0])
self.assertEqual(plain["result"][1:11], written[1:11])
edited = node.run(LINES, 6, picture_1=PICTURE, full_prompt="my own prompt\nno push in")
self.assertEqual(edited["result"][0], "my own prompt\nno push in")
self.assertEqual(edited["ui"]["written_prompt"], [written[0]])
self.assertEqual(edited["result"][11], written[11])
self.assertEqual(node.run(LINES, 6, picture_1=PICTURE, full_prompt=" \n")["result"][0], written[0])
def test_the_picks_that_change_nothing_add_nothing(self):
node = AusBossH3PromptWriter()
self.assertEqual(node.write(LINES, 6, picture_1=PICTURE)[0], node.write(LINES, 6, picture_1=PICTURE, camera="as typed", look="from the picture")[0])
@@ -1457,7 +1470,7 @@ class SoundAndMusicBoxTests(unittest.TestCase):
def test_the_boxes_are_appended_after_every_older_input(self):
names = list(AusBossH3PromptWriter.INPUT_TYPES()["optional"])
self.assertEqual(names[-3:], ["sound", "music", "clip_sound"])
self.assertEqual(names[-4:], ["sound", "music", "clip_sound", "full_prompt"])
def spoken(stretches, seconds, rate=16000, noise=0.002, seed=3):
+72
View File
@@ -625,5 +625,77 @@ class ResolveLoraPathTests(unittest.TestCase):
self.assertEqual(asked, [])
class LinkedRowStrengthTests(unittest.TestCase):
"""A number wire dropped on a row arrives as strength_<row id> (issue #388)."""
ROW = {"name": "a.safetensors", "strength": 0.8, "strength_clip": 0.4,
"enabled": True, "triggers": ""}
def rows(self):
return [{**self.ROW, "id": "ra1"}, {**self.ROW, "id": "rb2", "name": "b.safetensors"}]
def test_the_linked_value_sets_the_model_strength_and_clip_keeps_its_ratio(self):
out = _lora_helpers.apply_linked_strengths(self.rows(), {"strength_rb2": 0.3})
self.assertEqual((out[0]["strength"], out[0]["strength_clip"]), (0.8, 0.4))
self.assertAlmostEqual(out[1]["strength"], 0.3)
self.assertAlmostEqual(out[1]["strength_clip"], 0.15)
def test_a_row_at_zero_follows_the_link_one_for_one(self):
rows = [{**self.ROW, "id": "r0", "strength": 0.0, "strength_clip": 0.0}]
out = _lora_helpers.apply_linked_strengths(rows, {"strength_r0": 0.5})
self.assertEqual((out[0]["strength"], out[0]["strength_clip"]), (0.5, 0.5))
def test_unknown_rows_and_other_names_change_nothing(self):
rows = self.rows()
out = _lora_helpers.apply_linked_strengths(rows, {"strength_gone": 0.1, "trigger_separator": ", "})
self.assertEqual(out, rows)
def test_row_input_names(self):
self.assertTrue(_lora_helpers.is_row_strength_input("strength_rb2"))
for name in ("strength_", "strength_a b", "strength_" + "x" * 65, "loras", 3, None):
self.assertFalse(_lora_helpers.is_row_strength_input(name), name)
def test_the_node_declares_any_row_input_as_an_optional_float(self):
try:
from nodes.node_lora_loader import AusBossLoraLoader
except Exception as exc: # pragma: no cover - needs the package importable
self.skipTest(f"node module not importable offline: {exc}")
optional = AusBossLoraLoader.INPUT_TYPES()["optional"]
self.assertIn("strength_rb2", optional)
self.assertEqual(optional["strength_rb2"][0], "FLOAT")
self.assertNotIn("strength_", optional)
self.assertNotIn("bogus", optional)
# The listed inputs are unchanged: saved workflows keep their slots.
self.assertEqual(list(optional), ["clip", "trigger_separator", "on_missing"])
def test_comfyui_hands_a_row_input_to_the_node(self):
# ComfyUI passes a node only inputs it can look up; this is its own lookup.
try:
from comfy_execution.graph import get_input_info
from nodes.node_lora_loader import AusBossLoraLoader
except Exception as exc: # pragma: no cover - needs ComfyUI on the path
self.skipTest(f"ComfyUI not importable: {exc}")
kind, category, _info = get_input_info(AusBossLoraLoader, "strength_rb2")
self.assertEqual((kind, category), ("FLOAT", "optional"))
self.assertEqual(get_input_info(AusBossLoraLoader, "bogus"), (None, None, None))
def test_load_loras_applies_the_linked_strength(self):
try:
from nodes.node_lora_loader import AusBossLoraLoader
import nodes.node_lora_loader as node_module
except Exception as exc: # pragma: no cover - needs the package importable
self.skipTest(f"node module not importable offline: {exc}")
seen = []
def apply(model, clip, rows, **_kwargs):
seen.extend(rows)
return model, clip
with patch.object(node_module, "apply_lora_stack", side_effect=apply):
AusBossLoraLoader().load_loras("model", json.dumps(self.rows()), strength_rb2=1.2)
self.assertEqual([round(row["strength"], 3) for row in seen], [0.8, 1.2])
self.assertEqual([round(row["strength_clip"], 3) for row in seen], [0.4, 0.6])
if __name__ == "__main__":
unittest.main()
+124
View File
@@ -0,0 +1,124 @@
"""The pack loads on Python 3.10, where tomllib does not exist (issue #387).
Each check runs in a child interpreter with tomllib (and tomli) hidden, the
way a Python 3.10 install without the backport sees the world.
"""
from __future__ import annotations
from pathlib import Path
import subprocess
import sys
import tempfile
import textwrap
import unittest
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._pyproject import _plain_project, project_from_text
# Run in a child interpreter: make tomllib and tomli look absent.
HIDE_TOML = textwrap.dedent(
"""
import sys
class _NoToml:
def find_spec(self, name, path=None, target=None):
if name in ("tomllib", "tomli"):
raise ModuleNotFoundError(f"No module named {name!r}", name=name)
return None
sys.meta_path.insert(0, _NoToml())
sys.modules.pop("tomllib", None)
sys.modules.pop("tomli", None)
"""
)
def run_without_toml(body: str) -> subprocess.CompletedProcess:
code = HIDE_TOML + textwrap.dedent(body)
return subprocess.run(
[sys.executable, "-c", code], cwd=ROOT, capture_output=True, text=True, timeout=60
)
class PlainReaderTests(unittest.TestCase):
def test_matches_tomllib_on_the_real_pyproject(self):
text = (ROOT / "pyproject.toml").read_text(encoding="utf-8")
real = project_from_text(text)
plain = _plain_project(text)
self.assertEqual(plain["name"], real["name"])
self.assertEqual(plain["version"], real["version"])
def test_reads_only_the_project_table(self):
text = textwrap.dedent(
"""
[tool.other]
name = "not-this"
[project]
name = 'ausboss-nodes' # single quotes and a comment
version = "1.2.3"
license = { text = "MIT License" }
[project.urls]
name = "not-this-either"
"""
)
self.assertEqual(_plain_project(text), {"name": "ausboss-nodes", "version": "1.2.3"})
def test_no_project_table(self):
self.assertEqual(_plain_project('[tool.x]\nversion = "9"\n'), {})
class NoTomllibTests(unittest.TestCase):
def test_reader_works_without_tomllib(self):
result = run_without_toml(
"""
from nodes import _pyproject
assert _pyproject._toml is None, _pyproject._toml
project = _pyproject.read_project("pyproject.toml")
print(project["name"], project["version"])
"""
)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertTrue(result.stdout.startswith("ausboss-nodes "), result.stdout)
def test_single_copy_guard_works_without_tomllib(self):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp).resolve()
for name, version in (("ComfyUI-AusBoss", "2.0.0"), ("ausboss-nodes", "3.0.0")):
folder = root / name
(folder / "nodes").mkdir(parents=True)
(folder / "__init__.py").write_text("")
(folder / "nodes" / "_single_copy.py").write_text("")
(folder / "pyproject.toml").write_text(
f'[project]\nname = "ausboss-nodes"\nversion = "{version}"\n'
)
result = run_without_toml(
f"""
from nodes._single_copy import other_copy_that_loads
older = {str(root / "ComfyUI-AusBoss")!r}
winner = other_copy_that_loads(older, [{str(root)!r}])
print(winner)
"""
)
self.assertEqual(result.returncode, 0, result.stderr)
# The newer copy is found, so its version was read without tomllib.
self.assertIn("ausboss-nodes", result.stdout)
def test_shipped_python_never_imports_tomllib_directly(self):
offenders = []
for path in [ROOT / "__init__.py", *sorted((ROOT / "nodes").rglob("*.py"))]:
if path.name == "_pyproject.py":
continue
for number, line in enumerate(path.read_text(encoding="utf-8").splitlines(), 1):
stripped = line.strip()
if stripped.startswith(("import tomllib", "from tomllib")):
offenders.append(f"{path.relative_to(ROOT)}:{number}")
self.assertEqual(offenders, [], "use nodes/_pyproject.py so Python 3.10 still loads")
if __name__ == "__main__":
unittest.main()
+35 -3
View File
@@ -56,6 +56,24 @@ def input_default(cls, name):
return kind[0] if isinstance(kind, (list, tuple)) else None
def run_parameter(cls, name):
"""The parameter an API prompt without `name` runs with, or None.
A node function that takes **inputs and hands them on in one call,
such as H3 Prompt Writer's run() to write(), is followed that one step.
"""
function = getattr(cls, cls.FUNCTION)
parameters = inspect.signature(function).parameters
if name in parameters:
return parameters[name]
if any(p.kind is p.VAR_KEYWORD for p in parameters.values()):
for target in re.findall(r"self\.(\w+)\([^()]*\*\*\w+\)", inspect.getsource(function)):
handed_on = inspect.signature(getattr(cls, target)).parameters
if name in handed_on:
return handed_on[name]
return None
@unittest.skipUnless(COMFY_ROOT, "set AUSBOSS_COMFY_ROOT to a ComfyUI checkout")
class SavedFallbackTests(unittest.TestCase):
@classmethod
@@ -74,16 +92,30 @@ class SavedFallbackTests(unittest.TestCase):
def test_each_fallback_is_the_new_node_default_and_the_api_default(self):
for node_id, fallbacks in self.fallbacks.items():
cls = self.pack.NODE_CLASS_MAPPINGS[node_id]
parameters = inspect.signature(getattr(cls, cls.FUNCTION)).parameters
for name, fallback in fallbacks.items():
with self.subTest(node=node_id, input=name):
self.assertEqual(fallback, input_default(cls, name), "a new node's default")
self.assertIn(name, parameters, f"{cls.FUNCTION}() does not take {name}")
parameter = run_parameter(cls, name)
self.assertIsNotNone(parameter, f"{cls.FUNCTION}() does not take {name}")
self.assertEqual(
fallback, parameters[name].default,
fallback, parameter.default,
"what an API prompt without the input runs with",
)
def test_a_function_that_hands_on_its_inputs_is_followed(self):
class Wrapper:
FUNCTION = "run"
def run(self, script, **inputs):
return self.write(script, **inputs)
def write(self, script, sound=""):
return script, sound
self.assertEqual(run_parameter(Wrapper, "sound").default, "")
self.assertIsNone(run_parameter(Wrapper, "music"))
self.assertEqual(run_parameter(Wrapper, "script").name, "script")
if __name__ == "__main__":
unittest.main()
+48
View File
@@ -12,7 +12,9 @@ import {
folderPath,
groupModels,
hostLabel,
installFolders,
matchInstalled,
modelFolderKey,
onlyCopy,
noteFit,
noteIsEmpty,
@@ -23,6 +25,7 @@ import {
parseMarkdown,
rowFromCells,
safeUrl,
sharedFolders,
serializeNote,
} from "../js/shared/workflow_note.mjs";
import { collectGraphNodes } from "../js/shared/appearance.mjs";
@@ -127,6 +130,51 @@ test("folderPath and groupModels read like the install tree", () => {
assert.deepEqual(groups.map((g) => [g.dir, g.rows.map((r) => r.name)]), [["vae", ["a", "c"]], ["loras", ["b"]]]);
});
// Stability Matrix's extra_model_paths.yaml, as ComfyUI's
// /experiment/models reports it on Windows (issue #386).
const STABILITY_MATRIX = [
{ name: "loras", folders: ["C:\\SM\\Packages\\ComfyUI\\models\\loras", "C:\\SM\\Data\\Models\\Lora", "C:\\SM\\Data\\Models\\LyCORIS"] },
{ name: "text_encoders", folders: ["C:\\SM\\Packages\\ComfyUI\\models\\text_encoders", "C:\\SM\\Packages\\ComfyUI\\models\\clip", "C:\\SM\\Data\\Models\\TextEncoders"] },
{ name: "diffusion_models", folders: ["/opt/ComfyUI/models/unet", "/opt/ComfyUI/models/diffusion_models/", "/mnt/shared/DiffusionModels"] },
{ name: "vae", folders: ["/opt/ComfyUI/models/vae"] },
];
test("old folder names are checked under the names ComfyUI lists them by", () => {
// GET /models/clip and /models/unet answer 404; ComfyUI files them as these.
assert.equal(modelFolderKey("clip"), "text_encoders");
assert.equal(modelFolderKey("unet"), "diffusion_models");
assert.equal(modelFolderKey("loras"), "loras");
assert.equal(modelFolderKey("clip_vision"), "clip_vision");
assert.equal(modelFolderKey("input"), "input");
});
test("installFolders lists every folder the install reads, shared ones included", () => {
assert.deepEqual(installFolders("loras", STABILITY_MATRIX), STABILITY_MATRIX[0].folders);
assert.deepEqual(installFolders("clip", STABILITY_MATRIX), STABILITY_MATRIX[1].folders);
assert.deepEqual(installFolders("input", STABILITY_MATRIX), []);
assert.deepEqual(installFolders("checkpoints", STABILITY_MATRIX), []);
assert.deepEqual(installFolders("loras", null), []);
assert.deepEqual(installFolders("loras", [null, { name: "loras" }]), []);
});
test("sharedFolders names only the folders outside ComfyUI/models", () => {
assert.deepEqual(sharedFolders("loras", STABILITY_MATRIX), ["C:\\SM\\Data\\Models\\Lora", "C:\\SM\\Data\\Models\\LyCORIS"]);
// models/clip is ComfyUI's own old text-encoder folder, not a shared one.
assert.deepEqual(sharedFolders("text_encoders", STABILITY_MATRIX), ["C:\\SM\\Data\\Models\\TextEncoders"]);
assert.deepEqual(sharedFolders("clip", STABILITY_MATRIX), ["C:\\SM\\Data\\Models\\TextEncoders"]);
assert.deepEqual(sharedFolders("unet", STABILITY_MATRIX), ["/mnt/shared/DiffusionModels"]);
// A plain install has nothing extra to show, and neither do folders
// named like the kind (ComfyUI's own output/loras, a shared .../loras).
assert.deepEqual(sharedFolders("vae", STABILITY_MATRIX), []);
assert.deepEqual(sharedFolders("loras", [{ name: "loras", folders: ["/c/ComfyUI/models/loras", "/c/ComfyUI/output/loras", "D:\\shared\\LoRAs\\"] }]), []);
assert.deepEqual(sharedFolders("loras", []), []);
});
test("the note asks ComfyUI for a folder by the name it lists it under", () => {
const source = readFileSync(new URL("../js/workflow_note/index.js", import.meta.url), "utf8");
assert.match(source, /fetchApi\(`\/models\/\$\{encodeURIComponent\(modelFolderKey\(dir\)\)\}`\)/);
});
test("matchInstalled finds exact paths first, then basenames in any subfolder", () => {
const files = ["Krea 2/krea2_turbo_fp8.safetensors", "other/thing.safetensors", "top.safetensors"];
assert.deepEqual(matchInstalled("krea2_turbo_fp8.safetensors", files), { found: true, path: "Krea 2/krea2_turbo_fp8.safetensors" });