Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
67d372e481 | ||
|
|
7f432d921c | ||
|
|
c406ef10d9 | ||
|
|
02b3ce2662 | ||
|
|
f5883dce8a | ||
|
|
5283ac99d0 | ||
|
|
aae35150c4 | ||
|
|
38fd6813f7 | ||
|
|
07ce762159 | ||
|
|
b668e9ace0 | ||
|
|
53bebffb83 | ||
|
|
24be45d996 | ||
|
|
9f208f61d7 | ||
|
|
f1dbaf0fb0 | ||
|
|
3c225ea242 | ||
|
|
8f128f5417 | ||
|
|
f822bb3382 | ||
|
|
51e8a94f14 | ||
|
|
af3de6eafb | ||
|
|
9a38504ea7 | ||
|
|
a9e2b7c168 | ||
|
|
d5cb95d2e1 | ||
|
|
95b09ee484 | ||
|
|
75d42c44d1 | ||
|
|
5fcb150384 | ||
|
|
fdc70ede61 | ||
|
|
a6657bac72 | ||
|
|
977c352361 | ||
|
|
540f3c0c45 | ||
|
|
b2087ba565 | ||
|
|
fa644d9969 | ||
|
|
f31e15ec9f | ||
|
|
340fc54b49 | ||
|
|
3664cbf1d8 | ||
|
|
c132d1517b | ||
|
|
c49cae39e2 | ||
|
|
cf70590406 | ||
|
|
a84b897d76 |
@@ -32,3 +32,14 @@ jobs:
|
||||
for source in pathlib.Path('web').glob('*.js'):
|
||||
subprocess.run(['node', '--input-type=module', '--check'], input=source.read_bytes(), check=True)
|
||||
PY
|
||||
- name: Check exclusive routing behavior
|
||||
run: node --experimental-default-type=module tests/test_exclusive_routes.mjs
|
||||
- name: Check comparison result history
|
||||
run: node --experimental-default-type=module tests/test_compare_history.mjs
|
||||
|
||||
- name: Check crop geometry
|
||||
run: |
|
||||
node --experimental-default-type=module tests/test_crop_geometry.mjs
|
||||
node --experimental-default-type=module tests/test_crop_dimensions.mjs
|
||||
node --experimental-default-type=module tests/test_legacy_feedback.mjs
|
||||
node --experimental-default-type=module tests/test_draft_guard.mjs
|
||||
|
||||
+161
@@ -1,5 +1,166 @@
|
||||
# Changelog
|
||||
|
||||
## 0.6.9
|
||||
|
||||
- Place the Clear button directly after the swap width/height control in Crop & Blend; in Mask mode it is the only visible button of that bar and stays at the bottom left of the canvas.
|
||||
|
||||
## 0.6.8
|
||||
|
||||
- Add a Clear button to the bottom-left canvas bar: one click empties the mask of the active target, in both Mask and Crop & Blend modes, and it stays disabled until an image is loaded.
|
||||
- Move the selected-region painting help onto the repaint mask button, and remove hover text from the painting canvas entirely: hovering the image no longer shows any hint in any mode. The bottom controls and their button tooltips keep the instructions.
|
||||
- Remove the now-unused canvas and repaint mask hint entries from the locale dictionary.
|
||||
- Bump the inline crop module's asset version so the updated file is fetched instead of a cached copy.
|
||||
|
||||
## 0.6.7
|
||||
|
||||
- Before merging an adopted crop layer, hold the right mouse button to preview the original; release, pointer cancellation or window blur restores the workspace. Preview changes display only. After merge, right-click again releases the crop selection.
|
||||
- Add English/Chinese hover instructions for bottom controls and state-specific canvas gestures, including size/hardness shortcuts, masks, adoption, merging and Undo.
|
||||
|
||||
## 0.6.6
|
||||
|
||||
- Right-click releases a locked crop without painting; the next plain click selects a new region. Adopted layer effects are merged before reselection. Right-click no longer paints or erases in either mode; Alt remains the temporary eraser.
|
||||
- Remove the redundant reselect button. Move the existing mask Undo button from the inpaint controls to the inline toolbar, immediately after Merge, using a return-arrow icon. Undo also remains accessible in ordinary mask mode.
|
||||
|
||||
## 0.6.5
|
||||
|
||||
- Keep crop size presets, width/height swap and custom dimensions available after locking a region. Changing dimensions automatically unlocks it for a new selection.
|
||||
- Merge an adopted layer before changing the region, and retain the old selection if merging fails.
|
||||
|
||||
## 0.6.4
|
||||
|
||||
- Use a pure black dashed crop outline and automatically synchronize connected inpaint resolution when locking a crop. Linked resolution inputs remain under their upstream node's control.
|
||||
- Remove the Inline Mask result socket and obsolete feedback connections. Both modes now receive results exclusively through Image Compare adoption.
|
||||
- Crop adoption keeps the full source, crop location and repaint mask; the accepted patch remains a separate editable blend layer. Generation alone does not update it. Tag comparison previews with their originating crop to reject stale adoption.
|
||||
|
||||
## 0.6.3
|
||||
|
||||
- Check oversized embedded sources before workflow configuration, so the first autosave cannot disable browser draft storage before the mode-change guard runs. Upload exact source bytes before changing the file reference, including sources in subgraph definitions.
|
||||
- Keep the array and optional named widget snapshots synchronized when serializing Inline Mask; stale embedded copies no longer survive in the named snapshot. Keep repaint masks, fusion masks and layer references unchanged.
|
||||
- Apply the source-capacity check after uploading/replacing an embedded image too. Respect disabled browser persistence and retain embedded data if upload fails.
|
||||
- A page that already encountered the native draft quota error needs one reload to reset ComfyUI's disabled-storage flag: save the workflow with Ctrl+S first, then use Ctrl+F5. No browser drafts are cleared by the plugin.
|
||||
|
||||
## 0.6.2
|
||||
|
||||
- Remove magic wand and quick selection, including their toolbar menu and background workers.
|
||||
- Locking a crop dims the outside and starts an empty repaint mask, ready for manual painting. Brush, shape and mask actions stay inside the locked crop.
|
||||
- Reduce presets to six sizes with 64-aligned dimensions from 512 through 2048; retain the width/height swap button. Custom sizing steps by 64 pixels.
|
||||
|
||||
## 0.6.1
|
||||
|
||||
- Add a collapsed painting-tools/mask-settings section in WebUI Inpaint and Inpaint Prepare. Keep the complete Undo/Redo/Invert/Fill/Clear/Import/Export row visible, and save the fold state in the workflow.
|
||||
- Reproduce browser draft quota failures with a large embedded source. Before a mode change or enabling embedding, probe available draft capacity using a temporary plugin-owned key; credit the existing current draft and preserve all other browser storage.
|
||||
- If the embedded source does not fit, upload an exact PNG copy first, then use the input-file reference without reloading pixels or clearing repaint masks, fusion masks, layers or undo commands. A failed upload retains the original embedded data and mode. Small embeddings remain embedded.
|
||||
- Share in-flight recovery across embedding/mode changes, respect disabled ComfyUI browser persistence, and keep the recovery notice above the crop toolbar.
|
||||
|
||||
## 0.6.0
|
||||
|
||||
- Merge rectangular cropping and two-layer blending into Inline Mask, with a compact mode selector; ordinary mask mode ignores the result input.
|
||||
- Add 32-aligned crop presets, pointer-following selection, fixed-region repeat generation, exact full-image stitching and a third full_image output. Feedback wiring is split into an acyclic execution graph before validation.
|
||||
- Replace the proposed crop version history with original/result layers and a separate editable fusion mask. Brush reveals the new layer; Alt erases back to the original. Reselecting merges visible layers first.
|
||||
- Add a compact selection-tool menu: contiguous magic wand (W), brush-guided color quick selection (Q), tolerance and selection brush size. Alt subtracts, and both tools support undo/redo in either mode. Selection calculations run in a Web Worker.
|
||||
- Use arrow/fit/pin icons, Ctrl+wheel for size and Shift+wheel for hardness. Use source size follows the locked crop in crop mode.
|
||||
- Retain existing image/mask output indices, old workflows, comparison adoption and mask preservation. Restart ComfyUI and hard-refresh after updating.
|
||||
|
||||
## 0.5.13
|
||||
|
||||
- Restore a missing enabled execution input by resolving its saved workflow route through Get/Set, reroutes and subgraph output slots to an existing flattened execution node.
|
||||
- Fix the captured remote failure where the selected positive branch existed in a tag subgraph but its input link was absent from the submitted exclusive node. Never invent missing backend nodes or connect a different node type.
|
||||
- Include node ID, frontend/workflow flags and submitted-connection flags in selection errors to distinguish an ignored branch from lost execution wiring.
|
||||
- Validate three actual failed remote request snapshots locally and two lightweight CPU queue probes with the same missing-link/subgraph mapping. Restart ComfyUI after this backend update.
|
||||
|
||||
## 0.5.12
|
||||
|
||||
- Trace enabled Get nodes back through their named Set and encoder in saved workflow metadata; ignored Sets disable their branch even when both Gets remain enabled and both execution links survive.
|
||||
- Normalize exclusive branch flags and remove only ignored execution inputs before ComfyUI validation/cache lookup. Keep all original workflow wires and normal cache reuse.
|
||||
- Repeat the workflow check during lazy selection, support scoped subgraph IDs and both serialized link formats, and retain raw-API behavior without workflow metadata.
|
||||
- Validate the supplied remote workflow's routing states using lightweight real image queues, including reverse switching, cache reuse and strict invalid states. A full ComfyUI restart is required after updating.
|
||||
|
||||
## 0.5.11
|
||||
|
||||
- Resolve exclusive selection against the actual submitted prompt connections, overriding stale frontend flags when only one branch survives Get/Set, mute or bypass resolution.
|
||||
- Support dynamically expanded subgraph node IDs through ComfyUI's dynamic prompt, while retaining explicit branch flags for bypassed transforms that keep both physical connections.
|
||||
- Keep both-enabled/both-absent errors and include the received branch state in their diagnostic message. Restart ComfyUI after updating this backend change.
|
||||
|
||||
## 0.5.10
|
||||
|
||||
- Add a pin toggle beside Fit in Inline Mask: keep the image fitted, route plain wheel to the workflow, retain Ctrl+wheel brush sizing and save the toggle with the workflow.
|
||||
- Shorten the inline load button to Upload (上传).
|
||||
- Bound inline preview bitmap allocation to source detail and an 8 Mi-pixel budget; cache the source/mask composite during cursor movement. Full-resolution mask data remains unchanged.
|
||||
- Successful adoption resets comparison history to the accepted image as 1/1. The next generation starts a fresh result list; failed adoption preserves history.
|
||||
|
||||
## 0.5.9
|
||||
|
||||
- Bound comparison bitmap resolution to source detail, 8192 pixels per edge and a 16 Mi-pixel allocation budget, avoiding quadratic bitmap growth at large workflow zoom.
|
||||
- Redraw only the strip swept by the comparison divider during pointer movement; redraw fully after image, size or hover changes.
|
||||
- Draw the divider as a separate overlay so it remains one screen pixel wide even when magnifying the workflow.
|
||||
|
||||
## 0.5.8
|
||||
|
||||
- Count each comparison preview file once, even when cached execution notifications replay it; keep the selected result on replay.
|
||||
- Remove duplicate preview entries when reloading older saved comparison histories.
|
||||
|
||||
## 0.5.7
|
||||
|
||||
- Accumulate comparison results across runs, select the newest result and preserve each result's matching original, including after workflow reload.
|
||||
- Keep comparison images permanently fitted and centered in the canvas; remove independent wheel zoom and middle/Space image panning.
|
||||
- Route wheel events over the full comparison node, including the picture, to ComfyUI workflow navigation.
|
||||
- Preserve hover comparison, the full-result view on pointer leave, batch selection and adoption with mask/history retention.
|
||||
|
||||
## 0.5.6
|
||||
|
||||
- Follow KJNodes Get/Set routes and reroutes when deciding which exclusive input is enabled, including the setter's and real source node's bypass/mute states.
|
||||
- Support virtual routers using the current resolveVirtualOutput API, and safely reject routing cycles or missing setters.
|
||||
- Exclude inactive inputs from detached execution DTOs before frontend link resolution, avoiding missing-input errors when a virtual Get itself is bypassed; retain all editable/saved workflow wires.
|
||||
- Add dependency-free routing regression checks to CI and validate actual KJ Get/Set workflows with real CPU queue output pixels in both supported frontend versions/renderers.
|
||||
|
||||
## 0.5.5
|
||||
|
||||
- Bind the inline canvas, inpaint parameter panel and comparison widget width directly to the node's logical graph width. Cached screen-space measurements cannot shrink the widgets a second time at reduced graph zoom.
|
||||
- Keep native widget margins and vertical sizing; horizontal and vertical node resizing remain available.
|
||||
- Calculate source-image automatic canvas height from untransformed client dimensions rather than dividing screen measurements by graph zoom.
|
||||
- Verify stale-width fault injection, horizontal/vertical resize, zoom, Fit/mask preservation and workflow reload on frontend 1.42.11 and 1.52.7 in both renderers.
|
||||
|
||||
## 0.5.4
|
||||
|
||||
- Prevent the inline Fit button click from bubbling into ComfyUI node selection / bring-to-front handlers, which can remeasure a saved node's DOM editor.
|
||||
- Keep node and editor dimensions unchanged when fitting the image. Fit still resets only image zoom and pan.
|
||||
- Version the inline editor module and stylesheet URLs to refresh imported assets on upgrades; update an existing shared stylesheet link as well.
|
||||
- Verify actual clicks on saved workflow node geometry in frontend 1.42.11 and 1.52.7, with classic nodes and Nodes 2.0.
|
||||
|
||||
## 0.5.3
|
||||
|
||||
- Move the image Fit button from the inpaint painting controls to the inline mask, immediately after Load image.
|
||||
- Keep viewport reset and mask/history behavior unchanged. Includes the 0.5.2 single-frame 5D VAE compatibility fix.
|
||||
|
||||
## 0.5.2
|
||||
|
||||
- Support still-image inpainting with both 4D `[B,C,H,W]` and single-frame 5D `[B,C,1,H,W]` VAE latents, including the Wan-derived VAE used by Anima/Qwen-image pipelines.
|
||||
- Preserve the independent image/variant batch axis when a video-derived VAE would otherwise interpret the batch as frames.
|
||||
- Match noise/fill masks to latent rank and convert single-frame decoded images back to ordinary IMAGE batches before compositing.
|
||||
- Keep native inpaint conditioning and its batch/mask metadata compatible with single-frame 5D latents.
|
||||
- Add regression coverage and verify actual ComfyUI Wan VAE encode/decode and native mask preparation with tiny random test weights; no real Anima checkpoint was available locally.
|
||||
|
||||
## 0.5.1
|
||||
|
||||
- Add Auto Exclusive Switch: two generic lazy inputs, no manual switch control, and exactly one enabled branch required.
|
||||
- Respect muted/bypassed input branches, including bypassed transform nodes that normally pass through data; branch changes also invalidate execution caches.
|
||||
- Widen the group preset list from 32% to 40% of its panel.
|
||||
- Keep the new nodes English-only as well: backend error messages and the group preset node description no longer carry inline Chinese, and the two new example workflows use English note text and group names. The group preset node keeps no saved title override, so it shows its locale-aware name in any language.
|
||||
|
||||
## 0.5.0
|
||||
|
||||
- Preserve the painted mask, undo/redo history and viewport when adopting a comparison result as the source; an ordinary image upload still starts a new mask.
|
||||
- Add Group Bypass Presets: a connection-free controller with a preset list, per-group enabled/bypassed/unmanaged states, and a right-click preset menu.
|
||||
- Store presets in the workflow with stable group IDs, support renamed and nested groups, and leave newly added/unmanaged groups untouched.
|
||||
- Add a model-free example workflow for group presets.
|
||||
|
||||
## 0.4.2
|
||||
|
||||
- Make every user-facing string English by default: node display names, category, descriptions, tooltips and the canvas/panel labels.
|
||||
- Keep node class IDs, parameter identifiers and enum values unchanged, so existing workflows stay compatible.
|
||||
- Add `locales/en` and `locales/zh` and follow the ComfyUI language setting, so a Chinese ComfyUI shows Chinese labels while English stays the built-in default. Any missing translation falls back to English.
|
||||
- Document how this pack differs from ComfyUI's built-in modal mask editor and `Painter` node.
|
||||
|
||||
## 0.4.1
|
||||
|
||||
- Rename the public node pack to **Adachi-Inpaint-Workbench**; keep existing node class IDs compatible with saved workflows.
|
||||
|
||||
@@ -1,185 +1,262 @@
|
||||
<div align="center">
|
||||
|
||||
# Adachi-Inpaint-Workbench
|
||||
|
||||
直接在 ComfyUI 工作流节点里载入原图、涂抹蒙版、局部重绘,无需另开遮罩编辑器喵。
|
||||
**Paint. Inpaint. Compare. Keep going.**
|
||||
|
||||

|
||||
An inline inpainting workspace for ComfyUI, with WebUI-style controls and tools for switching workflow branches.
|
||||
|
||||
由 Adachi(安达)开发,MIT 开源喵。
|
||||
支持整图范围与蒙版范围重绘、Alt 临时橡皮擦、Ctrl+滚轮笔径、图像对比及一键采用重绘结果喵。
|
||||
**English** · [简体中文](README.zh-CN.md)
|
||||
|
||||
## ComfyUI Manager 与安装
|
||||
[](LICENSE)
|
||||
[](https://github.com/Comfy-Org/ComfyUI)
|
||||
[](pyproject.toml)
|
||||
[](https://github.com/adachi0130/Adachi-Inpaint-Workbench/actions/workflows/ci.yml)
|
||||
|
||||
Manager 的 Git URL 安装可使用 `https://github.com/adachi0130/Adachi-Inpaint-Workbench`;或在 `ComfyUI/custom_nodes` 中克隆喵。
|
||||
[Features](#features) · [Installation](#installation) · [Quick start](#quick-start) · [Node reference](#node-reference) · [Examples](#example-workflows)
|
||||
|
||||

|
||||
|
||||
*The original workbench preview. Earlier toolbar screenshots are retained below; v0.6 uses arrow / fit / pin icons.*
|
||||
|
||||
</div>
|
||||
|
||||
## Why this workbench?
|
||||
|
||||
Inpainting usually means moving between the workflow, a mask editor and the generated result. This pack keeps that loop on the graph: paint directly on a node, generate, compare, then adopt a result as your next source **without losing the painted mask**.
|
||||
|
||||
| Tool | What it adds |
|
||||
| --- | --- |
|
||||
| **Inline Mask** | Paint masks or crop, inpaint and blend two layers in the same node. |
|
||||
| **WebUI Inpaint** | Whole-image or masked-area sampling, familiar inpainting controls and compositing back at the source resolution. |
|
||||
| **Image Compare** | Hover comparison, result history and one-click adoption for another editing round. |
|
||||
| **Group Bypass Presets** | Save combinations of enabled/bypassed groups and apply them with one click. |
|
||||
| **Auto Exclusive Switch** | Route the only enabled branch to a shared output, without a manual switch widget. |
|
||||
|
||||
English and Simplified Chinese interfaces follow the ComfyUI language setting. The plugin uses the PyTorch, NumPy and Pillow already available in ComfyUI; no extra frontend build is required.
|
||||
|
||||
## Features
|
||||
|
||||
### Paint directly on the graph
|
||||
|
||||
Upload, drop or paste a source image and paint on **Inline Mask** itself. Mask strokes stay in the browser and are saved with the workflow; painting does not require a disk save/load round-trip for every stroke.
|
||||
|
||||
- Brush, soft edges, hardness, opacity, pen pressure, temporary erasing and shape tools.
|
||||
- A compact **↑ upload / ⛶ fit / pin** toolbar, with a mode selector at the upper right. Enable the pin (**Keep**) to keep the image fitted and centered; plain wheel then navigates the workflow, while `Ctrl` + wheel still changes brush size and `Shift` + wheel changes hardness.
|
||||
- Resize the editor horizontally or vertically. The pin state and node dimensions survive workflow reload.
|
||||
- The connected **WebUI Inpaint** node hosts the painting controls and sampling parameters, leaving more space for the picture. Its painting tools, mask mode and fill content fold behind an arrow; **Undo / Redo / Invert / Fill / Clear / Import / Export** remain visible. Fold state is saved with the workflow.
|
||||
- Bounded display buffers and cached image/mask compositing reduce redraw cost at large graph zoom; the saved mask retains its source resolution.
|
||||
|
||||
<details>
|
||||
<summary>View the compact toolbar</summary>
|
||||
|
||||
<p align="center">
|
||||
<img src="preview/inline-mask-toolbar.png" alt="Inline Mask with Upload, Fit and the active Keep pin" width="300">
|
||||
</p>
|
||||
|
||||
*Toolbar reference supplied by the author; the source preview is unloaded in this screenshot.*
|
||||
|
||||
</details>
|
||||
|
||||
### Crop and blend in the same node
|
||||
|
||||
Choose **Mask** or **Crop & Blend** at the upper right of Inline Mask. Both modes receive images through **Adopt this result** in Image Compare; Inline Mask has no result input socket.
|
||||
|
||||
In Crop & Blend mode, choose one of six 64-aligned presets spanning 512–2048 pixels per side, including 1024 × 1536 (or custom dimensions in multiples of 64). The dashed rectangle follows the pointer by its upper-left corner; left-click locks it. The outside is darkened. A new region starts with an empty repaint mask. Paint inside the rectangle; brush and shape operations stay within its bounds. Use **◌ repaint mask** to return to repaint-mask editing. The position stays fixed for repeated passes. Size presets remain editable while locked; changing the preset, orientation or custom dimensions cancels the current selection and returns to pointer placement, merging any adopted layer first. The outline is a pure black dashed rectangle, and locking it automatically fills the connected Inpaint node's width and height from the crop, using the same rules as Use source size.
|
||||
|
||||
| Connection | Purpose |
|
||||
| --- | --- |
|
||||
| `Inline Mask.image` + `mask` → `WebUI Inpaint.image` + `mask` | Send the selected crop and its repaint mask. |
|
||||
| `Inline Mask.image` → `Image Compare.original`; `WebUI Inpaint.image` → `Image Compare.result` | Compare the crop before adopting it. |
|
||||
| `Inline Mask.full_image` → `Save Image.images` | Save the current full image with the **adopted** layer stitched in. |
|
||||
|
||||
Generate, inspect the result in **Image Compare**, then click **Adopt this result** to return it. There is no feedback wire and generation does not automatically replace the editor image. Use the inpaint node's **image** output for comparison; its `crop` output is the sampling canvas and can have a different size. [Open the ready-wired example](examples/05-inline-crop-blend.json).
|
||||
|
||||
After adoption, **◐ blend layers** shows the original under the new result. Paint to keep new pixels, hold **Alt** to restore original pixels, and use soft brush edges to blend seams. This layer mask is independent of the repaint mask and is kept for another pass at the same coordinates. Before merging, **hold the right mouse button** to preview the original; release it to restore the workspace without changing either mask or the selection. **✓** merges the visible layers. Once merged, right-click releases the selection, then the next left-click locks a new region. The **↶ Undo** button sits to the right of ✓ and undoes mask strokes in the active mask or blend layer. Hover the bottom controls for instructions; canvas tooltips follow the current editing stage. There is no crop version timeline. For a generated batch, choose the desired result in Image Compare before adopting it. A result tagged with an older crop is rejected after selecting another region.
|
||||
|
||||
### Inpaint the whole image or just the masked region
|
||||
|
||||
| Sampling area | Behaviour |
|
||||
| --- | --- |
|
||||
| **Whole image** · `whole_image` | Resize the full source to the sampling canvas, generate, then composite through the mask. |
|
||||
| **Only masked** · `only_masked` | Crop the mask bounds with padding and aspect-ratio context, generate at the sampling size, then paste the region back into place. |
|
||||
|
||||
Both modes return a final `image` at the **source image's resolution**. Sampling `width` and `height` are independent controls; **Use source size** fills them from the uploaded image, rounded to the sampler's required multiple of 8.
|
||||
|
||||
The panel includes mask inside/outside, original/fill/noise/zero-latent content, denoise, sampler, scheduler, steps, CFG and seed. Advanced controls cover blur, growth, extra feathering, batch size and optional Refiner staging.
|
||||
|
||||
### Compare, adopt and refine
|
||||
|
||||
Move the pointer over **Image Compare**: **result on the left, original on the right**. Leave the picture to see the full result. The divider stays thin, the image stays fitted, and scrolling navigates the workflow background.
|
||||
|
||||
Results accumulate within an editing round, with the newest selected automatically. Each result retains its matching original; replayed preview notifications are not counted twice.
|
||||
|
||||
Click **Adopt this result** to replace the inline source while preserving its mask and current-session undo/redo history. The comparison list resets to **1/1**; the next generation starts a new round. Failed adoption leaves the list intact. Adoption never queues a generation automatically.
|
||||
|
||||
### Switch entire workflow setups with presets
|
||||
|
||||
Save group states for your own setups: text-to-image, inpainting, model variants, ControlNet, upscaling, or any other grouped branches.
|
||||
|
||||

|
||||
|
||||
Choose a preset on the left, configure **Enabled / Bypassed / Keep current** on the right, or apply it from the node's right-click menu. Presets are stored in the workflow and need no wires or third-party group controller. Missing groups are reported; overlapping groups give the smaller group's setting priority.
|
||||
|
||||
### Automatically use the remaining branch
|
||||
|
||||
Connect two alternatives to **Auto Exclusive Switch** and bypass one. The remaining enabled branch flows to the shared output, with no `switch` toggle to maintain.
|
||||
|
||||

|
||||
|
||||
Use it for conditioning, strings, images, masks, models or latents; the two alternatives must use the same data type. Both enabled, or neither available, is an error rather than a silent preference for A.
|
||||
|
||||
KJNodes Get/Set routes and reroutes are supported. **Both Gets may stay enabled**: bypassing a branch's corresponding Set or source disables that branch. Workflow-aware server checks also handle saved subgraph output routes when the source node exists in the submitted execution graph.
|
||||
|
||||
## Installation
|
||||
|
||||
### Git clone
|
||||
|
||||
Run from your `ComfyUI/custom_nodes` directory:
|
||||
|
||||
```bash
|
||||
git clone https://github.com/adachi0130/Adachi-Inpaint-Workbench.git
|
||||
```
|
||||
|
||||
Manager 搜索收录申请已提交:[ComfyUI-Manager PR #3378](https://github.com/Comfy-Org/ComfyUI-Manager/pull/3378),仍需维护者合并及索引更新,尚不能保证搜索可见喵。
|
||||
当前尚未配置 Comfy Registry 发布者,Registry 发布流程见 [发布说明](registry/README.md) 喵。
|
||||
**Restart ComfyUI completely, then hard-refresh the browser with `Ctrl+F5`** (`Cmd+Shift+R` on macOS). Search for `Inline Mask`, `WebUI Inpaint` or `Adachi` in the node menu.
|
||||
|
||||
## 安装
|
||||
### Other installation options
|
||||
|
||||
将整个 `Adachi-Inpaint-Workbench` 文件夹复制到 `ComfyUI/custom_nodes/`,保留其中的 `web/`、`backend.py`、`__init__.py` 喵。
|
||||
重启 ComfyUI,然后在浏览器按 `Ctrl+F5` 刷新前端缓存喵。
|
||||
在节点搜索中输入 `Inline Mask` 或 `WebUI Inpaint`,分类是 **安达工作台 / Adachi-Inpaint-Workbench** 喵。
|
||||
|
||||
Windows 也可以从解压后的插件文件夹运行安装脚本,将参数改为自己的、包含 `main.py` 的 ComfyUI 目录喵。
|
||||
- **ComfyUI Manager:** use its Git URL installation option, if available, with this repository's URL. Git URL installation and visibility in Manager's search index are separate; see the [publishing notes](registry/README.md).
|
||||
- **ZIP:** [download the repository](https://github.com/adachi0130/Adachi-Inpaint-Workbench/archive/refs/heads/main.zip), extract it, and place the plugin folder at `ComfyUI/custom_nodes/Adachi-Inpaint-Workbench/`. Keep `web/`, `backend.py` and `__init__.py` together.
|
||||
- **Windows installer:** from the extracted plugin folder, run the following, pointing to the ComfyUI directory containing `main.py`:
|
||||
|
||||
```powershell
|
||||
powershell -ExecutionPolicy Bypass -File .\install.ps1 -ComfyUIPath "D:\ComfyUI_windows_portable\ComfyUI"
|
||||
```
|
||||
|
||||
脚本只复制本插件;更新时会把旧插件压缩备份到所选 ComfyUI 的 `user/adachi-workbench-backups/`,不会自动重启服务喵。
|
||||
插件使用 ComfyUI 已有的 PyTorch、NumPy、Pillow,不需要额外 pip/npm 安装喵。
|
||||
卸载时关闭 ComfyUI,再删除 `custom_nodes/Adachi-Inpaint-Workbench` 即可喵。
|
||||
The installer backs up an existing installation to `user/adachi-workbench-backups/`. It does not restart ComfyUI.
|
||||
|
||||
## 最快上手
|
||||
For a Git installation, update with `git pull` inside the plugin folder, then restart ComfyUI and refresh the browser. Keep only one copy of this node pack in `custom_nodes`.
|
||||
|
||||
1. 将 `examples/01-inline-inpaint.json` 拖入 ComfyUI,选择自己的 checkpoint 喵。
|
||||
2. 在 **内联蒙版 / Inline Mask** 节点载入、拖放或粘贴图片,直接在画布上涂抹需要重绘的部分喵。
|
||||
3. 修改正负提示词,在 **WebUI 局部重绘** 节点中选择画笔工具、重绘范围、采样分辨率、采样器与重绘幅度,然后运行喵。
|
||||
4. `image` 输出回贴后的完整原图,`crop` 输出实际采样画布,`mask` 输出该采样画布对应的蒙版喵。
|
||||
## Quick start
|
||||
|
||||
**白色蒙版重绘,黑色保护;画布中橙色代表绘制区域** 喵。
|
||||
当 `mask_mode=outside` 时会反相,重绘橙色之外的部分喵。
|
||||
`mask_blur`、`mask_grow`、额外羽化会改变有效蒙版边界,边界内的混合像素也会变化;有效蒙版为零的像素逐值保留喵。
|
||||
1. Drag [01-inline-inpaint.json](examples/01-inline-inpaint.json) into ComfyUI and select a compatible checkpoint, or connect your existing model, VAE and conditioning nodes.
|
||||
2. In **Inline Mask**, upload a picture and paint the region to change. **White repaints; black preserves.** Orange is only the on-screen overlay.
|
||||
3. Edit the upstream positive/negative prompts. Set the sampling area, width, height and denoise in **WebUI Inpaint**, then queue the workflow.
|
||||
4. Compare the output. Adopt a result when you want it to become the next source, and continue editing with the mask intact.
|
||||
|
||||
## 两种重绘范围
|
||||
|
||||
| `area` | 对应操作 | 实际行为 |
|
||||
|---|---|---|
|
||||
| `whole_image` | 以原图范围重绘 | 将整张图缩放到 `width × height` 采样,再按照蒙版回贴原图 |
|
||||
| `only_masked` | 以蒙版范围重绘 | 取蒙版包围框,加 `padding` 上下文,尽量扩展到目标比例,将局部放大到采样尺寸,生成后贴回原位置 |
|
||||
|
||||
`width/height` 指采样画布尺寸,须为 8 的倍数;两种模式的最终 `image` 都保持上传原图的分辨率喵。
|
||||
这一点与 WebUI 整图模式常以目标宽高输出的行为有区别;需要目标尺寸的图时,可取 `crop`,或在完整输出后连接缩放节点喵。
|
||||
`padding`、`mask_blur`、`mask_grow` 的单位都是原图像素喵。
|
||||
蒙版贴近图像边缘时,局部模式用保比例填充保住整块蒙版,不会为匹配比例切掉蒙版喵。
|
||||
`resize_mode` 的拉伸、居中裁剪、保比例填充作用于 `whole_image`;局部模式自动采用保留全部蒙版的变换喵。
|
||||
|
||||
## 画布操作
|
||||
|
||||
| 操作 | 使用方式 |
|
||||
|---|---|
|
||||
| 画笔 / 橡皮 | 工具栏切换,`B` / `E`;按住 `Alt` 或鼠标右键临时擦除,松开恢复原工具;擦除时显示橡皮擦图标与淡粉色虚线范围 |
|
||||
| 矩形 / 自由套索 | `R` / `L`,拖动画出要重绘的区域 |
|
||||
| 笔径 / 硬度 / 笔触 | 分别控制原图像素笔径、边缘硬度、绘制不透明度 |
|
||||
| 橙色叠加 | 仅调节显示透明度,不改变真实蒙版 |
|
||||
| 撤销 / 重做 | `Ctrl+Z` / `Ctrl+Shift+Z`,或 `Ctrl+Y` |
|
||||
| 缩放 / 移动 | 滚轮缩放;空格拖动、鼠标中键或 `H` 移动;「适应」复位 |
|
||||
| 笔径快捷键 | `[` / `]` |
|
||||
| 快速调整笔径 | 鼠标放在画布上,按住 `Ctrl` 向上滚轮增大、向下滚轮减小;普通滚轮仍缩放图片 |
|
||||
| 编辑器高度 | 拖动编辑器底部 `↕` 条上下拉伸;尺寸随工作流保存 |
|
||||
| 反转 / 全选 / 清空 | 作用于当前绘制蒙版,可撤销 |
|
||||
| 导入 / 导出蒙版 | 原始分辨率 PNG;黑白图按亮度导入,带透明度的图按 alpha 导入 |
|
||||
| 原图 / 蒙版 / 叠加 | 切换预览,不改变输出 |
|
||||
|
||||
支持画笔压力和软笔刷;鼠标使用固定压力喵。
|
||||
内联蒙版仅保留图片编辑区与左上角的小型 **载入原图** 按钮,载入后按原图比例调整画布高度以减少空边喵。
|
||||
画笔、橡皮、矩形、套索、移动、四个笔刷滑条、撤销重做、蒙版操作、显示切换、适应与原图嵌入选项,均显示在连接的 **WebUI 局部重绘** 节点中,直接控制原来的内联画布喵。
|
||||
图片上传一次,之后每笔在浏览器内更新蒙版,并在工作流及运行参数中保存 PNG 数据,无需每画一笔都保存、重新加载磁盘文件喵。
|
||||
鼠标位于图片区域时滚轮缩放图片;位于工具栏、按钮、滑条或参数面板时,滚轮遵循 ComfyUI 的画布导航设置喵。
|
||||
从 ComfyUI 画布开始的连续滚轮手势移入图片时,继续导航外部画布;停下后再在图片里滚动才缩放图片喵。
|
||||
超大图仍会消耗浏览器内存,PNG 编码耗时取决于分辨率和设备,不能保证所有图像都瞬间完成喵。
|
||||
|
||||
## 画笔工具与重绘参数
|
||||
|
||||
内联蒙版连接 **WebUI 局部重绘** 的 `image` 输入后,原画笔控件自动显示在该重绘节点中;下方参数面板直接控制该节点的真实采样参数喵。
|
||||
宽度和高度各占一行,支持滑条及数值输入;重绘幅度也使用滑条,点击 **使用原图宽高** 可填入原图尺寸,按采样要求取最近的 8 的倍数喵。
|
||||
蒙版内外、填充、重绘范围、采样器、调度器、步数、CFG 和种子直接显示,蒙版处理、批量、Refiner 切换等位于 **蒙版、批量与高级设置** 中喵。
|
||||
如果一张内联原图连接多个重绘节点,画笔控件放在第一个 WebUI 重绘节点中,各节点保留自己的参数面板;断开或删除该节点后,工具自动迁移到下一个可用节点喵。
|
||||
外部连线控制的参数会禁用对应面板控件;模块化工作流将画笔工具放在 **重绘预处理 / Inpaint Prepare** 节点中,采样参数仍在独立采样节点中调整喵。
|
||||
|
||||
## 图像对比与连续重绘
|
||||
|
||||
添加 **图像对比 / Image Compare** 节点,将内联蒙版的 `image` 接到 `original`,最终完整重绘图 `image` 接到 `result`,运行后即可对比喵。
|
||||
鼠标移入图片时,细竖线左边显示重绘结果、右边显示原图;移出后隐藏分割线,完整显示重绘结果,普通滚轮缩放图片;批量结果选择、尺寸和适应按钮位于图片下方喵。
|
||||
满意后点击 **采用此结果**,插件会把当前选中的结果上传为新的原图,回填到上游内联蒙版,并清空旧蒙版,随后可以继续涂抹下一处喵。
|
||||
原图连接经过中间 IMAGE 节点时会向上寻找内联蒙版;若存在多个目标,可以在“回填到”中明确选择喵。
|
||||
回填只在点击按钮时发生,不会自动开始下一轮生成;`image` 输出仍传递整个结果批次,可接保存图像喵。
|
||||
对比预览保存在 ComfyUI 临时目录,清理或重启后可能需要重新运行;点击采用后的原图保存在 `input/adachi-inpaint/`,不依赖临时预览文件喵。
|
||||
|
||||
## 填充、批量与 Refiner
|
||||
|
||||
| `fill` | 行为 |
|
||||
|---|---|
|
||||
| `original` | 使用原图像素编码 latent |
|
||||
| `fill` | 按蒙版周围颜色进行多尺度填充,再编码 latent |
|
||||
| `latent_noise` | 在 masked latent 内填入与 seed 相关的噪声 |
|
||||
| `latent_nothing` | 将 masked latent 置零 |
|
||||
|
||||
后两种 latent 填充由 **WebUI 局部重绘** 一体节点实现;独立 **重绘预处理** 只处理像素与蒙版,使用标准节点组合时请选择 `original` 或 `fill` 喵。
|
||||
`denoise=0` 与空蒙版会直接返回原图,跳过 VAE 和采样;`batch_size` 为每张输入图的变体数,使用相同 seed 可重现同一批次喵。
|
||||
多次批量运行可使用 ComfyUI 的队列数量以及 seed 的生成后控制;`batch_size` 控制单次运行数量喵。
|
||||
普通 SD/SDXL checkpoint 保持 `inpaint_model=false`;专用 inpainting 模型才开启,届时调用 ComfyUI 原生 `InpaintModelConditioning` 喵。
|
||||
|
||||
可选接入兼容的 `refiner_model`,用 `refiner_switch` 指定 base 采样步骤占比;`0.8` 表示约前 80% 步骤由 base 执行喵。
|
||||
建议用 Refiner 自身的 CLIP 编码并接入 `refiner_positive/refiner_negative`,未接入则沿用原条件,VAE 仍使用 base 侧的 VAE 喵。
|
||||
`refiner_switch=1` 只用 base,`0` 只用 Refiner;已知 latent 格式不兼容时会报错喵。
|
||||
|
||||
## 使用标准采样工作流
|
||||
|
||||
`examples/02-modular-inpaint.json` 展示可自由更换采样器的连接方式喵。
|
||||
|
||||
```text
|
||||
Inline Mask ── image/mask ──> Inpaint Prepare
|
||||
pixels ──> VAE Encode ──> Set Latent Noise Mask ──> KSampler
|
||||
mask ──────────────────────────┘ │
|
||||
context ──────────────────────────────────────┐ │
|
||||
│ ▼
|
||||
Inpaint Composite <── VAE Decode
|
||||
│
|
||||
Save Image
|
||||
```mermaid
|
||||
flowchart LR
|
||||
Source[Inline Mask] -->|image + mask| Inpaint[WebUI Inpaint]
|
||||
Inputs[Model · VAE · Conditioning] --> Inpaint
|
||||
Source -->|original| Compare[Image Compare]
|
||||
Inpaint -->|result| Compare
|
||||
Inpaint --> Save[Save Image]
|
||||
Compare -. Adopt this result .-> Source
|
||||
```
|
||||
|
||||
务必将 `Prepare.context` 接回 **原图回贴 / Inpaint Composite**,这样局部结果会回到原图坐标和尺寸喵。
|
||||
标准示例针对普通 checkpoint;专用 inpainting checkpoint 应改用其需要的 conditioning 节点,或直接使用一体节点喵。
|
||||
多个输入图各生成多个变体时,Composite 需要变体按原图分组,例如 `A,A,B,B`;一体节点已按此排列,外部重复 latent 节点如果输出 `A,B,A,B`,需先调整批次顺序喵。
|
||||
### Essential connections
|
||||
|
||||
## 分享与兼容性
|
||||
| From | To |
|
||||
| --- | --- |
|
||||
| `Inline Mask.image` / `mask` | `WebUI Inpaint.image` / `mask` |
|
||||
| Your model / VAE / positive / negative conditioning | The matching inputs of `WebUI Inpaint` |
|
||||
| `Inline Mask.image` | `Image Compare.original` |
|
||||
| `WebUI Inpaint.image` | `Image Compare.result` and/or `Save Image.images` |
|
||||
|
||||
绘制蒙版自动写入工作流;默认原图只保存 ComfyUI `input/` 内的相对路径喵。
|
||||
要让别人直接打开同一张图,勾选画布下方 **原图嵌入工作流** 后再保存工作流 JSON;对方安装本插件并选择自己的模型即可继续编辑喵。
|
||||
不嵌入时,需要一并提供原图,并保持 `input/` 下的相对路径一致喵。
|
||||
嵌入会增大工作流文件,原图和蒙版也会随工作流分享,因此分享前请确认图片内容喵。
|
||||
The Refiner inputs are optional. Leave them disconnected unless you are using a compatible second-stage model.
|
||||
|
||||
这是原创实现的 WebUI 风格工作流,不承诺与 AUTOMATIC1111/Forge 的结果逐像素一致喵。
|
||||
`soft_edge` 是额外高斯羽化,`soft_strength` 控制额外半径,**并未复刻 WebUI 的 Soft Inpainting 原算法及其完整参数** 喵。
|
||||
采样器、调度器和 Refiner 使用当前 ComfyUI 的实现,填充算法也为本插件独立实现喵。
|
||||
目前支持静态图像与 4 维 latent;不支持视频 VAE、WebUI 脚本/扩展和自动读取 WebUI 插件配置喵。
|
||||
文件最大 64 MiB、图像最大 3200 万像素、单边最大 16384 像素;不附带模型或下载服务喵。
|
||||
已在本机 ComfyUI 的隔离 CPU 服务验证节点加载、画布编辑、工作流/运行参数保存与恢复,并用 mock VAE/采样器验证后端;尚未用实际 checkpoint 验证生成质量和各模型家族/Refiner 的兼容性喵。
|
||||
## Node reference
|
||||
|
||||
## English quick start
|
||||
All nodes live under **Adachi-Inpaint-Workbench**. The group preset controller is frontend-only; the other six are user-facing backend nodes.
|
||||
|
||||
**Adachi-Inpaint-Workbench** is an MIT-licensed ComfyUI custom node pack for direct mask painting, WebUI-style inpainting, result/original comparison, and adopting results for another edit pass喵.
|
||||
| Node | Purpose | Outputs |
|
||||
| --- | --- | --- |
|
||||
| **Inline Mask** | Mask painting or crop/inpaint/layer blending | `image`, `mask`, `full_image` |
|
||||
| **WebUI Inpaint** | Prepare, sample and composite in one node | `image` = full composite; `crop` = sampling canvas; `mask` = sampling mask |
|
||||
| **Image Compare** | Preview, compare and adopt results | `image` = unchanged result batch |
|
||||
| **Group Bypass Presets** | Apply saved group states | No connections needed |
|
||||
| **Auto Exclusive Switch** | Forward exactly one enabled alternative | `output` of the selected type |
|
||||
| **Inpaint Prepare** | Crop/resize pixels and mask for a custom sampler workflow | `pixels`, `mask`, `context` |
|
||||
| **Inpaint Composite** | Return a decoded local result to source coordinates | `image` |
|
||||
|
||||
Copy the entire `Adachi-Inpaint-Workbench` folder into `ComfyUI/custom_nodes`, restart ComfyUI, then hard-refresh your browser喵.
|
||||
Search for `Inline Mask` or `WebUI Inpaint` under **安达工作台 / Adachi-Inpaint-Workbench**喵.
|
||||
No extra pip or npm packages are required beyond ComfyUI's PyTorch, NumPy and Pillow喵.
|
||||
For modular sampling: `Prepare.pixels → VAE Encode → Set Latent Noise Mask → sampler → VAE Decode → Composite`. Connect `Prepare.mask` to the latent mask node and **always connect `Prepare.context` to `Composite.context`**. See the [modular example](examples/02-modular-inpaint.json).
|
||||
|
||||
Drag `examples/01-inline-inpaint.json` into ComfyUI, select a checkpoint, upload an image inside **Inline Mask**, paint, and run the workflow喵.
|
||||
White repaints and black preserves; orange is the visual mask overlay喵.
|
||||
Use `whole_image` to sample the full source extent, or `only_masked` to enlarge the padded mask bounding box for detailed local inpainting喵.
|
||||
Sampling uses `width × height`; the final `image` output is composited at the original image resolution in both modes, while `crop` exposes the generated sampling canvas喵.
|
||||
## Canvas shortcuts
|
||||
|
||||
The editor supports brush/eraser, rectangles, freehand lasso, undo/redo, invert, mask import/export, brush size/hardness/opacity, zoom, pan, drag-and-drop and clipboard images喵.
|
||||
Inline Mask shows only the image and a small upload button; its original live painting controls and the sampling parameter panel are hosted in the connected WebUI Inpaint node (or Inpaint Prepare for modular workflows)喵.
|
||||
Paint with the left button; hold Alt or use the right button to erase temporarily, use Ctrl+wheel for brush size, zoom with the plain wheel, and pan while holding Space喵.
|
||||
Enable **Embed source in workflow** before saving JSON to share the source image along with its mask喵.
|
||||
| Action | Shortcut / control |
|
||||
| --- | --- |
|
||||
| Brush / eraser / rectangle / lasso | `B` / `E` / `R` / `L` |
|
||||
| Temporary eraser | Hold `Alt`; release to return to the previous tool |
|
||||
| Brush size | `Ctrl` + wheel, or `[` / `]` |
|
||||
| Brush hardness | `Shift` + wheel |
|
||||
| Preview original before merging | Hold right mouse button; release to restore the workspace |
|
||||
| Release crop selection | After merging with ✓ (or with no adopted layer), right-click, then left-click to select a new region |
|
||||
| Undo / redo | `Ctrl+Z` / `Ctrl+Shift+Z`, or `Ctrl+Y` |
|
||||
| Image zoom / pan, when unpinned | Wheel / Space + drag, middle-button drag, or the pan tool (`H`) |
|
||||
| Keep the image fitted | Pin beside **Fit**; click again to unlock |
|
||||
| Adjust editor height | Drag the bottom `↕` handle |
|
||||
|
||||
The **Image Compare** node takes `original` from Inline Mask and `result` from the final full-size generated image; hover to compare result on the left and original on the right, and leave the picture to see the full result喵.
|
||||
Select a batch result if needed, then click **采用此结果 / Adopt this result** to upload it as the upstream editor's new source and clear the old mask for another pass喵.
|
||||
The painting panel also provides invert, fill, clear, PNG mask import/export, image/mask/overlay views and **Embed source in workflow**. Overlay opacity affects display only. Scrolling over buttons and parameter controls navigates the outer workflow; a gesture starting on the workflow keeps navigating it when the pointer crosses the picture.
|
||||
|
||||
The all-in-one node adds original/color-fill/noise/zero-latent modes, native ComfyUI sampling, per-image batch variants, dedicated inpaint conditioning and an optional compatible Refiner stage喵.
|
||||
`examples/02-modular-inpaint.json` demonstrates Prepare → standard VAE/KSampler nodes → Composite; use `original` or `fill` in that modular pipeline喵.
|
||||
`soft_edge` adds Gaussian feathering; it does not implement AUTOMATIC1111 Soft Inpainting or its complete parameter set喵.
|
||||
The plugin is an original MIT-licensed implementation and does not bundle WebUI/Forge source, models or extensions喵.
|
||||
Real-checkpoint image quality and every model/Refiner family have not been tested; browser integration and CPU/mock-sampler regression tests have been run喵.
|
||||
## Example workflows
|
||||
|
||||
Run the CPU tests from this plugin directory with your ComfyUI Python喵.
|
||||
Drag a JSON file into ComfyUI:
|
||||
|
||||
```powershell
|
||||
python tests/test_backend.py -v
|
||||
| Example | What to try |
|
||||
| --- | --- |
|
||||
| [01 · Inline inpainting](examples/01-inline-inpaint.json) | The complete painting and inpainting loop; select your own compatible checkpoint. |
|
||||
| [02 · Modular inpainting](examples/02-modular-inpaint.json) | Use standard encode/sample/decode nodes with Prepare and Composite. |
|
||||
| [03 · Group presets](examples/03-group-presets.json) | Model-free preset switching with image branches. |
|
||||
| [04 · Exclusive switch](examples/04-exclusive-switch.json) | Model-free A/B selection controlled by group presets. |
|
||||
| [05 · Inline crop and blend](examples/05-inline-crop-blend.json) | One editor, crop presets, comparison adoption and accepted full-image output; select your checkpoint and upload a source. |
|
||||
|
||||
## Compatibility and important behaviour
|
||||
|
||||
- **Static images:** ordinary 4D `[B,C,H,W]` latents and single-frame 5D `[B,C,1,H,W]` image latents are supported, including the Wan-derived VAE path used by Anima. Supply the model family's matching VAE and conditioning. This is not multi-frame video inpainting.
|
||||
- **Anima:** for ordinary masked img2img, leave **inpaint_model** disabled. That option is for dedicated inpainting architectures, not a requirement for painting a mask.
|
||||
- **Source size:** the final composite keeps the source resolution in both sampling areas. Use `crop` or a separate resize node for a target-size output.
|
||||
- **Crop layers:** the fusion mask and crop coordinates are saved in the workflow; the latest layer is a relative image reference under `input/adachi-inpaint-layers/`. Include that file when moving an unmerged edit between machines, or merge layers and embed the source first.
|
||||
- **Sharing:** masks are embedded in saved workflows. Source images use a relative `input/` path by default; enable **Embed source in workflow** to include the picture too. Embedded images increase JSON size. If an embedded source would exceed browser draft storage when loading a workflow, uploading an image, changing modes or enabling embedding, the plugin first uploads an exact source copy and switches to an input-file reference, preserving masks and layers. To intentionally keep a very large source embedded, disable ComfyUI browser workflow persistence before embedding; exported files are not subject to the browser draft quota. If the page already reports draft failures on every edit, save with **Ctrl+S**, then reload with **Ctrl+F5** to reset ComfyUI's disabled draft-storage state.
|
||||
- **Adoption:** source and result dimensions must match to preserve mask coordinates. Undo/redo commands survive adoption in the current session; saving/reloading retains the mask, not the command history.
|
||||
- **Temporary previews:** comparison history stores preview references. ComfyUI temp cleanup may expire them; adopted images are stored under `input/adachi-inpaint/`.
|
||||
- **Scope:** this is an original WebUI-style implementation. It does not promise identical WebUI pixels, scripts or extension behaviour. Extra soft-edge feathering is not WebUI's full Soft Inpainting algorithm.
|
||||
|
||||
<details>
|
||||
<summary>Sampling, fill and batch details</summary>
|
||||
|
||||
- Sampling dimensions use multiples of 8. Padding, blur and mask growth are measured in source pixels; effective mask edges can change after blur/growth, while pixels with zero effective mask remain unchanged.
|
||||
- `mask_mode=outside` inverts the painted region before mask processing.
|
||||
- `resize_mode` controls whole-image resizing. Masked-area mode uses an aspect-preserving transform that retains the full mask, including at source edges.
|
||||
- Fill modes: **original**, surrounding-colour **fill**, **latent noise**, and **zero latent**. The latent modes belong to WebUI Inpaint; the modular Prepare node handles pixels and masks.
|
||||
- An empty mask or `denoise=0` skips VAE/sampling. `batch_size` is variants per input image, not ComfyUI queue count.
|
||||
- For modular multi-source batches, group variants per source (`A,A,B,B`), rather than interleaving them (`A,B,A,B`).
|
||||
- Optional Refiner uses `refiner_model` and `refiner_switch`; `0.8` runs the last 20% with the Refiner. Compatible Refiner conditioning is recommended. A switch of `1` uses only the base model; `0` uses only the Refiner.
|
||||
- Input limits: 64 MiB per file, 32 megapixels and 16384 pixels per image edge. Large-image painting and PNG encoding still depend on browser memory and hardware.
|
||||
|
||||
</details>
|
||||
|
||||
## Troubleshooting and development
|
||||
|
||||
**Old UI after updating?** Fully restart ComfyUI and hard-refresh the browser. Backend Python changes need a server restart; refreshing the page alone is insufficient.
|
||||
|
||||
**Exclusive switch reports no enabled input?** Check the real source and corresponding Set, not only the visible Get nodes. Keep the selector outside the groups it controls. If an integration still drops a subgraph output, placing the CLIP encoder outside that subgraph is a practical workaround. For a report, include the workflow, plugin/frontend versions and full error text; current errors show frontend, workflow and submitted-input flags.
|
||||
|
||||
**An image is missing after opening someone else's workflow?** Supply the source at its relative input path, or have the sender save with source embedding enabled. Expired comparison previews require regeneration.
|
||||
|
||||
CPU regression tests:
|
||||
|
||||
```bash
|
||||
python -m unittest discover -s tests -v
|
||||
node --experimental-default-type=module tests/test_exclusive_routes.mjs
|
||||
node --experimental-default-type=module tests/test_compare_history.mjs
|
||||
```
|
||||
|
||||
See [verification notes](VERIFICATION.md) for tested configurations and limits, [changelog](CHANGELOG.md) for updates, and [rollback instructions](ROLLBACK.md) for returning to an earlier version. Model-family and image-quality coverage is not exhaustive.
|
||||
|
||||
## Credits and license
|
||||
|
||||
Created by **Adachi / 安达**. Licensed under [MIT](LICENSE).
|
||||
|
||||
Built for [ComfyUI](https://github.com/Comfy-Org/ComfyUI), with familiar inpainting controls inspired by WebUI and hover-comparison interaction inspired by [rgthree-comfy](https://github.com/rgthree/rgthree-comfy). This repository contains its own implementation; those projects are not bundled dependencies.
|
||||
|
||||
Bug reports and workflow examples are welcome in [Issues](https://github.com/adachi0130/Adachi-Inpaint-Workbench/issues).
|
||||
|
||||
+262
@@ -0,0 +1,262 @@
|
||||
<div align="center">
|
||||
|
||||
# Adachi-Inpaint-Workbench
|
||||
|
||||
**绘制蒙版,局部重绘,对比结果,继续精修。**
|
||||
|
||||
直接在 ComfyUI 工作流内操作的重绘工作台,提供 WebUI 风格参数,以及分组预设、自动分支选择工具。
|
||||
|
||||
[English](README.md) · **简体中文**
|
||||
|
||||
[](LICENSE)
|
||||
[](https://github.com/Comfy-Org/ComfyUI)
|
||||
[](pyproject.toml)
|
||||
[](https://github.com/adachi0130/Adachi-Inpaint-Workbench/actions/workflows/ci.yml)
|
||||
|
||||
[功能介绍](#功能介绍) · [安装](#安装) · [快速开始](#快速开始) · [节点一览](#节点一览) · [示例工作流](#示例工作流)
|
||||
|
||||

|
||||
|
||||
*保留工作台早期预览图;下方保留旧工具栏截图;v0.6 使用上传箭头、适应、图钉。*
|
||||
|
||||
</div>
|
||||
|
||||
## 为什么做这个工作台?
|
||||
|
||||
局部重绘时,常常需要在工作流、蒙版编辑器和生成结果之间来回切换。本插件把这段操作放回画布:直接在节点内涂蒙版,生成并对比结果,再把满意的图片作为下一轮原图,**保留已经画好的蒙版**继续精修。
|
||||
|
||||
| 工具 | 用途 |
|
||||
| --- | --- |
|
||||
| **内联蒙版 · Inline Mask** | 同一节点内涂蒙版,或裁切、重绘、双图层融合。 |
|
||||
| **WebUI 局部重绘 · WebUI Inpaint** | 整图或蒙版区域采样,使用熟悉的重绘参数,按原图尺寸回贴结果。 |
|
||||
| **图像对比 · Image Compare** | 鼠标划线对比、查看结果历史,一键采用后继续重绘。 |
|
||||
| **组忽略预设 · Group Bypass Presets** | 保存各组的打开/忽略组合,一键切换工作流配置。 |
|
||||
| **自动二选一 · Auto Exclusive Switch** | 自动输出唯一启用的分支,不用手动设置 switch。 |
|
||||
|
||||
界面支持英文和简体中文,跟随 ComfyUI 的语言设置。使用 ComfyUI 已有的 PyTorch、NumPy 和 Pillow,无需额外构建前端。
|
||||
|
||||
## 功能介绍
|
||||
|
||||
### 直接在工作流里画蒙版
|
||||
|
||||
在**内联蒙版**上传、拖入或粘贴原图,然后直接在节点画布上涂抹。蒙版在浏览器内更新,随工作流保存,不需要每画一笔都保存、加载磁盘文件。
|
||||
|
||||
- 支持画笔软边、硬度、不透明度、数位笔压感、临时擦除和形状工具。
|
||||
- 顶部使用**↑ 上传、⛶ 适应、图钉**,右上角切换模式。图钉的悬停提示为「保持」:开启后图片持续适应并居中,普通滚轮控制工作流背景,`Ctrl` + 滚轮调整笔径,`Shift` + 滚轮调整硬度。
|
||||
- 支持横向、纵向调整编辑区大小;图钉状态和节点尺寸都能随工作流保存。
|
||||
- 连到 **WebUI 局部重绘**后,画笔工具和采样参数显示在重绘节点内,让图片编辑区保持简洁。画笔工具、蒙版内外和填充内容收进箭头折叠区,**撤销、重做、反转、全选、清空、导入蒙版、导出**整行始终显示;折叠状态随工作流保存。
|
||||
- 放大工作流时限制显示画布的分配尺寸,并缓存原图/蒙版合成,减少反复重绘;实际保存的蒙版仍保持原图分辨率。
|
||||
|
||||
<details>
|
||||
<summary>查看简洁工具栏</summary>
|
||||
|
||||
<p align="center">
|
||||
<img src="preview/inline-mask-toolbar.png" alt="内联蒙版的上传、适应和已开启的保持图钉" width="300">
|
||||
</p>
|
||||
|
||||
*作者提供的工具栏示意图;截图中的原图预览尚未载入。*
|
||||
|
||||
</details>
|
||||
|
||||
### 一个节点内裁切、重绘和融合
|
||||
|
||||
在内联蒙版右上角选择**蒙版**或**裁切融合**。两种模式都通过图像对比节点的**采用此结果**回传图片;内联蒙版不再提供结果输入口。
|
||||
|
||||
裁切融合模式保留六组常用预设,宽高均为 64 的倍数,范围 512~2048(含两端);可用交换按钮切换横竖方向,自定义尺寸按 64 像素递增。虚线框的左上角跟随鼠标,左键点击锁定,框外压暗。新选区的蒙版为空,需要自己在框内涂抹;画笔和形状操作限制在选区内,点击 **◌ 重绘蒙版**可返回编辑重绘范围。选区框为纯黑虚线;点击锁定时,相连 Inpaint 节点会自动填写裁片宽高,等同于点一次「使用原图宽高」。选区位置固定,支持反复重绘同一处。选定后仍可切换预设、交换横竖或修改自定义宽高;修改会自动取消当前选区,重新跟随鼠标定位,已有采用图层会先合并保留。
|
||||
|
||||
| 连线 | 用途 |
|
||||
| --- | --- |
|
||||
| `内联蒙版.image`、`mask` → `WebUI 局部重绘.image`、`mask` | 把裁片和重绘蒙版送去生成。 |
|
||||
| `内联蒙版.image` → `图像对比.original`;`WebUI 局部重绘.image` → `图像对比.result` | 先对比裁片,再选择采用。 |
|
||||
| `内联蒙版.full_image` → `保存图像.images` | 保存包含**已采用图层**的完整图像。 |
|
||||
|
||||
先生成,在**图像对比**中查看,满意后点击**采用此结果**,才会嵌回当前裁切位置;没有回接输入线,也不会生成后自动替换。比较结果使用重绘节点的 **image** 输出;`crop` 是采样画布,尺寸可能不同。[已连好的示例](examples/05-inline-crop-blend.json)。
|
||||
|
||||
采用后自动进入 **◐ 图层融合**:底层原图、上层重绘结果,画笔保留新图,按住 **Alt** 擦回原图,软笔刷可融合接缝。融合蒙版与重绘蒙版相互独立,同一区域继续生成会保留融合蒙版。合并前**按住右键看原图,松开恢复工作区**,不改动蒙版或选区。**✓** 合并当前可见图层;合并后在图片内右键取消选定,再左键选择新区域。**↶ 撤销**位于 ✓ 右边,可撤销当前重绘蒙版或融合蒙版的涂抹。鼠标悬停底部控件可查看操作说明,画布提示也会跟随当前编辑阶段变化。没有裁切版本列表。批量生成时,在图像对比中选中想要的结果再采用;换到其他选区后,带有旧选区标记的结果会拒绝回贴,避免贴错位置。
|
||||
|
||||
### 整图重绘与蒙版区域重绘
|
||||
|
||||
| 采样区域 | 工作方式 |
|
||||
| --- | --- |
|
||||
| **整图范围** · `whole_image` | 将整张原图调整到采样尺寸,生成后通过蒙版合成回原图。 |
|
||||
| **仅蒙版区域** · `only_masked` | 按蒙版边界截取区域,加入 padding 和宽高比所需的上下文,采样后回贴到原位置。 |
|
||||
|
||||
两种模式最终输出的 `image` 都保持**原图尺寸**。采样宽、高独立设置;**使用原图宽高**按钮可一键填写,并按采样器要求对齐到 8 的倍数。
|
||||
|
||||
面板提供蒙版内/外、原图像素/填充/潜空间噪声/空白潜空间、重绘幅度、采样器、调度器、步数、CFG 和种子。高级设置包括蒙版模糊、扩张、额外羽化、批次数量和可选 Refiner。
|
||||
|
||||
### 对比结果,采用后继续精修
|
||||
|
||||
鼠标移入**图像对比**:**左边是重绘结果,右边是原图**;移开后显示完整结果。分隔线保持细线,图片持续适应编辑区,滚轮作用于工作流背景。
|
||||
|
||||
同一轮编辑中的结果会累计保存并默认选中最新一张,每张结果对应当时的原图;重复的预览通知不会重复计数。
|
||||
|
||||
点击**采用此结果**,把选中的图片回填为内联蒙版的新原图,同时保留蒙版和当前会话中的撤销/重做记录。结果列表立即回到 **1/1**,下一次生成开启新一轮。采用失败时保留原列表;采用操作不会自动开始生成。
|
||||
|
||||
### 一键切换整套分组配置
|
||||
|
||||
为自己的工作流保存多套组合,例如文生图、修图、不同模型、ControlNet、放大等分支的打开/忽略状态。
|
||||
|
||||

|
||||
|
||||
左侧点选预设,右侧配置各组**打开 / 忽略 / 保持当前**,也能通过节点右键菜单应用。预设随工作流保存,不需要连线,也不依赖第三方组控制节点。已删除的组会显示提示;分组重叠时,较小组的设置优先。
|
||||
|
||||
### 自动使用剩下的一路输入
|
||||
|
||||
将两路备选输入连接到**自动二选一**,忽略其中一路后,另一条有效分支自动流向共同输出,无需手动切换 `switch`。
|
||||
|
||||

|
||||
|
||||
可用于提示词条件、字符串、图像、蒙版、模型、潜空间等数据;两路输入应为同一类型。两路都启用或都不可用时会报错,不会擅自优先选择 A。
|
||||
|
||||
支持 KJNodes 的 Get/Set 和重路由节点。**两个 Get 可以一直开启**:忽略其中一路对应的 Set 或上游源节点,就会停用那条分支。请求带有工作流信息时,后端也会核对已保存的子图输出;执行请求中仍存在相应源节点时,可恢复丢失的有效连接。
|
||||
|
||||
## 安装
|
||||
|
||||
### Git 安装
|
||||
|
||||
在 `ComfyUI/custom_nodes` 目录运行:
|
||||
|
||||
```bash
|
||||
git clone https://github.com/adachi0130/Adachi-Inpaint-Workbench.git
|
||||
```
|
||||
|
||||
**完整重启 ComfyUI,再按 `Ctrl+F5` 强制刷新网页**,macOS 可用 `Cmd+Shift+R`。在节点菜单搜索 `Inline Mask`、`WebUI Inpaint` 或 `Adachi`。
|
||||
|
||||
### 其他安装方式
|
||||
|
||||
- **ComfyUI Manager:**如果当前版本提供 Git URL 安装,可以填入本仓库地址。Git URL 安装与能否在 Manager 搜索索引中找到是两回事,收录说明见[发布文档](registry/README.md)。
|
||||
- **ZIP:**[下载仓库压缩包](https://github.com/adachi0130/Adachi-Inpaint-Workbench/archive/refs/heads/main.zip),解压后放到 `ComfyUI/custom_nodes/Adachi-Inpaint-Workbench/`,保留完整的 `web/`、`backend.py` 和 `__init__.py`。
|
||||
- **Windows 安装脚本:**在解压后的插件目录运行以下命令,路径指向包含 `main.py` 的 ComfyUI 目录:
|
||||
|
||||
```powershell
|
||||
powershell -ExecutionPolicy Bypass -File .\install.ps1 -ComfyUIPath "D:\ComfyUI_windows_portable\ComfyUI"
|
||||
```
|
||||
|
||||
脚本会将已有安装备份到 `user/adachi-workbench-backups/`,不会自动重启 ComfyUI。
|
||||
|
||||
Git 安装用户可在插件目录运行 `git pull` 更新,然后重启 ComfyUI 并刷新网页。`custom_nodes` 中只保留一份本插件,避免重复加载。
|
||||
|
||||
## 快速开始
|
||||
|
||||
1. 将 [01-inline-inpaint.json](examples/01-inline-inpaint.json) 拖入 ComfyUI,选择兼容的 checkpoint;也可以连接现有工作流的模型、VAE 和文本条件。
|
||||
2. 在**内联蒙版**上传图片,涂出需要修改的部分。**白色重绘、黑色保留**,橙色只是界面叠加显示。
|
||||
3. 编辑上游节点的正面/负面提示词,在 **WebUI 局部重绘**里设置采样区域、宽高和重绘幅度,运行工作流。
|
||||
4. 查看对比结果,满意时点击采用,将它作为新原图,保留蒙版继续修改。
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
Source[内联蒙版] -->|image + mask| Inpaint[WebUI 局部重绘]
|
||||
Inputs[模型 · VAE · 文本条件] --> Inpaint
|
||||
Source -->|original| Compare[图像对比]
|
||||
Inpaint -->|result| Compare
|
||||
Inpaint --> Save[保存图像]
|
||||
Compare -. 采用此结果 .-> Source
|
||||
```
|
||||
|
||||
### 必要连线
|
||||
|
||||
| 从哪里 | 连到哪里 |
|
||||
| --- | --- |
|
||||
| `内联蒙版.image` / `mask` | `WebUI 局部重绘.image` / `mask` |
|
||||
| 模型 / VAE / 正面条件 / 负面条件 | `WebUI 局部重绘`对应输入 |
|
||||
| `内联蒙版.image` | `图像对比.original` |
|
||||
| `WebUI 局部重绘.image` | `图像对比.result`,以及需要时的 `保存图像.images` |
|
||||
|
||||
Refiner 输入是可选项。只有需要兼容的第二阶段模型时才连接,否则留空即可。
|
||||
|
||||
## 节点一览
|
||||
|
||||
分类为 **Adachi-Inpaint-Workbench**。组忽略预设是前端控制节点,其余六个为用户使用的后端节点;
|
||||
|
||||
| 节点 | 用途 | 输出 |
|
||||
| --- | --- | --- |
|
||||
| **内联蒙版 · Inline Mask** | 普通蒙版或裁切重绘、双图层融合 | `image`、`mask`、`full_image` |
|
||||
| **WebUI 局部重绘 · WebUI Inpaint** | 一体化准备、采样、合成 | `image`:完整合成图;`crop`:采样画布;`mask`:采样蒙版 |
|
||||
| **图像对比 · Image Compare** | 预览、对比、采用结果 | `image`:原样传递结果批次 |
|
||||
| **组忽略预设 · Group Bypass Presets** | 应用已保存的组状态 | 无需连线 |
|
||||
| **自动二选一 · Auto Exclusive Switch** | 传递唯一启用的输入 | `output`:被选中分支的数据类型 |
|
||||
| **重绘准备 · Inpaint Prepare** | 为自定义采样流程裁剪、调整图像和蒙版 | `pixels`、`mask`、`context` |
|
||||
| **重绘合成 · Inpaint Composite** | 将局部解码结果回贴到原图 | `image` |
|
||||
|
||||
模块化流程可使用 `Prepare.pixels → VAE 编码 → 设置潜空间噪声蒙版 → 采样器 → VAE 解码 → Composite`。`Prepare.mask` 连接噪声蒙版节点,**务必把 `Prepare.context` 连到 `Composite.context`**,详见[模块化示例](examples/02-modular-inpaint.json)。
|
||||
|
||||
## 画布快捷操作
|
||||
|
||||
| 操作 | 快捷键或控件 |
|
||||
| --- | --- |
|
||||
| 画笔 / 橡皮擦 / 矩形 / 套索 | `B` / `E` / `R` / `L` |
|
||||
| 临时橡皮擦 | 按住 `Alt`,松开后恢复之前的工具 |
|
||||
| 调整笔径 | `Ctrl` + 滚轮,或 `[` / `]` |
|
||||
| 调整硬度 | `Shift` + 滚轮 |
|
||||
| 合并前临时看原图 | 按住右键;松开恢复当前工作区 |
|
||||
| 取消裁切选定 | 点击 ✓ 合并后(或没有回贴图层时),图片内右键,再左键选择新区域 |
|
||||
| 撤销 / 重做 | `Ctrl+Z` / `Ctrl+Shift+Z`,或 `Ctrl+Y` |
|
||||
| 未固定时的图片缩放 / 移动 | 滚轮 / 空格拖动、中键拖动,或移动工具 `H` |
|
||||
| 保持图片适应 | 点击「适应」旁的图钉,再点一次解除 |
|
||||
| 调整编辑区高度 | 拖动底部 `↕` 手柄 |
|
||||
|
||||
画笔面板还提供反转、全选、清空、PNG 蒙版导入/导出、原图/蒙版/叠加视图和**原图嵌入工作流**。叠加不透明度只影响显示。鼠标在按钮、参数区滚动时控制外部工作流;从工作流背景开始的连续滚轮手势,移入图片后仍控制工作流。
|
||||
|
||||
## 示例工作流
|
||||
|
||||
将对应 JSON 拖入 ComfyUI:
|
||||
|
||||
| 示例 | 内容 |
|
||||
| --- | --- |
|
||||
| [01 · 内联局部重绘](examples/01-inline-inpaint.json) | 完整绘制与重绘流程,需要自行选择兼容模型。 |
|
||||
| [02 · 模块化重绘](examples/02-modular-inpaint.json) | Prepare / Composite 配合常规编解码与采样节点。 |
|
||||
| [03 · 分组预设](examples/03-group-presets.json) | 使用图像分支演示预设切换,不需要模型。 |
|
||||
| [04 · 自动二选一](examples/04-exclusive-switch.json) | 分组预设控制两路输入,不需要模型。 |
|
||||
| [05 · 内联裁切融合](examples/05-inline-crop-blend.json) | 同一编辑器裁切、接收结果和输出完整回贴图,需要选择模型并上传原图。 |
|
||||
|
||||
## 兼容性与重要行为
|
||||
|
||||
- **静态图片:**支持常规四维 `[B,C,H,W]` 和单帧五维 `[B,C,1,H,W]` 图像潜空间,包括 Anima 使用的 Wan 衍生 VAE 路径;需提供该模型配套的 VAE 和文本条件,不是多帧视频重绘。
|
||||
- **Anima:**普通带蒙版图生图请关闭 **inpaint_model / 专用重绘模型**。该选项用于专用 inpaint 架构,并非画了蒙版就需要开启。
|
||||
- **原图尺寸:**两种采样区域最终都按原图尺寸合成;如果要目标采样尺寸的图片,使用 `crop` 或另接调整尺寸节点。
|
||||
- **裁切图层:**选区和融合蒙版会保存到工作流,最新重绘图层引用 `input/adachi-inpaint-layers/` 中的图片。跨机器移动尚未合并的编辑时需带上这张图,或先合并图层再嵌入原图。
|
||||
- **分享工作流:**蒙版会写入 JSON。原图默认只存 `input/` 下的相对路径,开启**原图嵌入工作流**才会把图片也写进去,文件会变大。加载工作流、上传图片、切换模式或勾选嵌入时,如果浏览器草稿空间不足,插件先保存一份完全相同的原图到 input 图片目录,再改用文件引用,保留蒙版、图层和笔画记录。若确实要把大图嵌入 JSON,可先关闭 ComfyUI 的浏览器工作流持久化,再勾选嵌入;导出文件不受浏览器草稿限额影响。若当前页面已经每次操作都提示草稿失败,请先按 **Ctrl+S** 保存,再按 **Ctrl+F5** 刷新一次,重置 ComfyUI 本页已停用的草稿状态。
|
||||
- **采用结果:**结果尺寸必须与原图一致,才能保留蒙版坐标。撤销/重做记录在本次会话中保留;保存重开保留蒙版,不保存逐笔命令历史。
|
||||
- **临时预览:**对比历史保存的是预览引用,ComfyUI 清理临时文件后可能失效;已采用的原图保存在 `input/adachi-inpaint/`。
|
||||
- **功能范围:**这是独立实现的 WebUI 风格工具,不保证与 WebUI 像素、脚本和扩展行为完全一致;额外软边羽化并非 WebUI 的完整 Soft Inpainting 算法。
|
||||
|
||||
<details>
|
||||
<summary>采样、填充与批次细节</summary>
|
||||
|
||||
- 采样宽高使用 8 的倍数。padding、模糊和蒙版扩张以原图像素计量;模糊/扩张会改变有效蒙版边界,有效蒙版为零的像素保持不变。
|
||||
- `mask_mode=outside` 会先反转涂抹区域,再进行蒙版处理。
|
||||
- `resize_mode` 控制整图采样的调整方式;仅蒙版区域使用保留完整蒙版的比例变换,也适用于蒙版碰到图像边缘的情况。
|
||||
- 填充模式包括**原图像素、周边颜色填充、潜空间噪声、空白潜空间**。潜空间模式属于一体化重绘节点;模块化 Prepare 只处理图像和蒙版。
|
||||
- 空蒙版或 `denoise=0` 会跳过 VAE 和采样。`batch_size` 表示每张原图生成的变体数,不是 ComfyUI 队列次数。
|
||||
- 模块化多原图批次需按原图分组变体,例如 `A,A,B,B`,而非交错的 `A,B,A,B`。
|
||||
- 可选 Refiner 使用 `refiner_model` 与 `refiner_switch`;`0.8` 表示最后 20% 步骤使用 Refiner,建议提供兼容的专用文本条件。设为 `1` 只用基础模型,`0` 只用 Refiner。
|
||||
- 输入限制为单文件 64 MiB、单图 3200 万像素、单边 16384 像素。大图绘制与 PNG 编码速度仍取决于浏览器内存和硬件。
|
||||
|
||||
</details>
|
||||
|
||||
## 排错与开发
|
||||
|
||||
**更新后还是旧界面?** 完整重启 ComfyUI,再强制刷新网页。Python 后端修改不能仅靠刷新网页加载。
|
||||
|
||||
**自动二选一提示没有有效输入?** 检查真正的上游源节点和对应 Set,不能只看 Get。将二选一放在受控分组之外。若其他集成仍会丢掉子图输出,可以先把 CLIP 编码器放到子图外。反馈时请附上工作流、插件/前端版本和完整错误;当前错误会显示前端、工作流与执行输入的状态标记。
|
||||
|
||||
**打开别人的工作流后图片丢失?** 按相对路径补齐原图,或请对方开启原图嵌入后再保存。临时对比预览失效则需要重新生成。
|
||||
|
||||
运行 CPU 回归测试:
|
||||
|
||||
```bash
|
||||
python -m unittest discover -s tests -v
|
||||
node --experimental-default-type=module tests/test_exclusive_routes.mjs
|
||||
node --experimental-default-type=module tests/test_compare_history.mjs
|
||||
```
|
||||
|
||||
已测试配置和范围见[验证记录](VERIFICATION.md),版本变化见[更新日志](CHANGELOG.md),恢复旧版本见[回滚说明](ROLLBACK.md)。模型家族和实际画质测试并非全覆盖。
|
||||
|
||||
## 致谢与许可证
|
||||
|
||||
由 **Adachi / 安达** 制作,采用 [MIT 许可证](LICENSE)。
|
||||
|
||||
基于 [ComfyUI](https://github.com/Comfy-Org/ComfyUI) 构建,重绘交互参考 WebUI,鼠标划线对比体验参考 [rgthree-comfy](https://github.com/rgthree/rgthree-comfy)。代码由本仓库独立实现,这些项目不作为捆绑依赖。
|
||||
|
||||
欢迎通过 [Issues](https://github.com/adachi0130/Adachi-Inpaint-Workbench/issues) 反馈问题、分享工作流用法。
|
||||
+41
-9
@@ -1,20 +1,52 @@
|
||||
# Git 版本与回滚
|
||||
# Git versions and rollback
|
||||
|
||||
`v0.2.0` 是最早的界面回滚点,`v0.3.0` 包含内联参数面板、左右对比调整和滚轮路由修复;`v0.4.0` 将画笔与参数集中到 WebUI 重绘节点;`v0.4.1` 更新橡皮擦光标及公开名称喵。
|
||||
本机安装目录与源码目录均保留 Git 历史;普通发布 ZIP 不含 `.git`,可另用 Git bundle 恢复历史喵。
|
||||
The current version is **v0.6.7**. Git history lives in the source repository. The installed custom-node folder may be a ZIP/file copy without its own `.git`; do not run rollback commands in ComfyUI's parent repository.
|
||||
|
||||
在插件目录运行以下命令,先确认没有未保存改动,再切换版本喵。
|
||||
Before installing, the installer saves the previous plugin directory under `ComfyUI/user/adachi-workbench-backups/`. Restore that ZIP to roll back a copied installation. For a Git clone, use the tags below.
|
||||
|
||||
| Tag | Contents |
|
||||
|---|---|
|
||||
| `v0.6.7` | Hold right mouse to preview the original before merging; contextual hover help |
|
||||
| `local-before-v0.6.7` | Source before original-layer preview and expanded hover instructions |
|
||||
| `v0.6.6` | Right-click releases crops; move mask Undo beside Merge |
|
||||
| `local-before-v0.6.6` | Source before right-click reselection and inline Undo |
|
||||
| `v0.6.5` | Change crop dimensions while selected, automatically return to selection |
|
||||
| `local-before-v0.6.5` | Source before editable locked-crop dimensions |
|
||||
| `v0.6.4` | Black crop frame, automatic dimensions and comparison-only result adoption |
|
||||
| `local-before-v0.6.4` | Source before the comparison-adoption update, including v0.6.3 draft preflight fixes |
|
||||
| `v0.6.2` | Draft recovery, collapsible controls, retired selection tools and revised crop behavior |
|
||||
| `local-before-v0.6.2` | Exact baseline before the combined draft/fold and crop updates |
|
||||
| `v0.6.0` | Merged crop/blend editor, magic wand and quick selection |
|
||||
| `local-before-v0.6.0` | Exact source baseline before the merged editor (includes bilingual README) |
|
||||
| `v0.5.13` | Restore dropped enabled inputs through saved subgraph output routes |
|
||||
| `v0.5.12` / `local-before-v0.5.13` | Trace Get/Set source states server-side before prompt validation and caching |
|
||||
| `v0.5.11` / `local-before-v0.5.12` | Resolve exclusive selection from actual submitted connections despite stale frontend flags |
|
||||
| `v0.5.10` / `local-before-v0.5.11` | Pin inline fit, bound/cache inline previews, Upload label and restart comparison rounds after adoption |
|
||||
| `v0.5.9` / `local-before-v0.5.10` | Bound comparison bitmap allocations and redraw only the swept divider strip |
|
||||
| `v0.5.8` / `local-before-v0.5.9` | Deduplicate replayed comparison previews and repair duplicate saved history |
|
||||
| `v0.5.7` / `local-before-v0.5.8` | Fixed comparison images; wheel navigates the workflow; retain result history across runs |
|
||||
| `v0.5.6` / `local-before-v0.5.7` | Exclusive selector follows Get/Set and virtual routes correctly |
|
||||
| `v0.5.5` / `local-before-v0.5.6` | Bind canvas/panel widths to node geometry and retain vertical resizing |
|
||||
| `v0.5.4` / `local-before-v0.5.5` | Isolate Fit clicks and refresh editor assets on upgrade |
|
||||
| `v0.5.3` / `local-before-v0.5.4` | Fit beside Load image in the inline mask, plus the 5D VAE fix |
|
||||
| `v0.5.2` / `local-before-v0.5.3` | Single-frame 5D VAE support for image models, plus all previous features |
|
||||
| `local-before-v0.5.2` | Exact baseline before the VAE compatibility fix in each local repository |
|
||||
| `v0.5.1` | Auto Exclusive Switch, wider preset list, and all v0.5.0 features |
|
||||
| `v0.5.0` / `local-before-v0.5.1` | Preserve masks on adoption and group bypass presets |
|
||||
| `local-before-v0.5.0` | Exact baseline before mask adoption / group preset changes |
|
||||
|
||||
To undo only this update, run in the plugin folder:
|
||||
|
||||
```powershell
|
||||
git status --short
|
||||
git switch --detach v0.4.0
|
||||
git switch --detach local-before-v0.6.7
|
||||
```
|
||||
|
||||
恢复本版使用以下命令喵。
|
||||
Return to this version with:
|
||||
|
||||
```powershell
|
||||
git switch --detach v0.4.1
|
||||
git switch --detach v0.6.7
|
||||
```
|
||||
|
||||
切换后重启 ComfyUI 并在浏览器按 `Ctrl+F5` 刷新喵。
|
||||
已有本地修改时请先提交或备份,避免覆盖自己的改动喵。
|
||||
Restart ComfyUI and hard-refresh the browser (`Ctrl+F5`) after switching versions.
|
||||
Commit or back up any local modifications before switching. A release ZIP does not contain `.git`; use the installer backup for a copied installation.
|
||||
|
||||
+85
-29
@@ -1,35 +1,91 @@
|
||||
# 验证记录
|
||||
# Verification record
|
||||
|
||||
验证环境:Windows、本机 ComfyUI 0.19.3、ComfyUI frontend 1.42.11、PyTorch 2.8.0、Pillow 11.0.0、Chrome 155,使用独立的 8190 端口、CPU、测试输入输出目录和内存数据库喵。
|
||||
- 0.6.7: real Chrome mouse interactions on frontend 1.52.7 pass in classic nodes and Nodes 2.0. Display pixel checks verify hold-right original preview and release restoration, including release outside the picture, pointer cancellation and window blur. Preview overrides mask-only display temporarily, leaves serialized image/mask/crop state unchanged, and does not affect composite export pixels. After Merge, right-click still releases the selection; normal-mode right-click does not erase. Bottom controls have hover instructions and canvas help follows the editing stage. These checks use solid-color image fixtures, not model generation.
|
||||
|
||||
- 后端 16 项 CPU 测试通过,覆盖两种范围、边缘蒙版、反相、增长、羽化、周边颜色填充、批量映射、原像素保护、空蒙版、denoise=0、潜空间噪声/置零、专用 inpaint conditioning、不同 VAE 压缩比和 Refiner 分段喵。
|
||||
- 浏览器 12 组交互测试通过,覆盖真实鼠标绘画、右键擦除、矩形/套索、撤销重做、导入持久化、半压力硬笔刷、活动形状保存、缩放坐标、1600/768/390 像素窗口布局喵。
|
||||
- 经典节点与 Nodes 2.0 均完成真实画布拖画、工作流序列化、运行参数序列化与重新载入测试,蒙版像素一致且正确触发工作流修改状态,无插件 JavaScript 错误喵。
|
||||
- 实际 ComfyUI API 队列执行了两种范围的载入→预处理→回贴→保存图像工作流,输出尺寸正确,有效蒙版外 RGB 像素逐值相等喵。
|
||||
- 两份示例由真实节点生成、重新加载并构造执行参数,节点和连线有效,模型文件名为用户选择占位符喵。
|
||||
- 安装脚本在临时目录完成首次安装、再次安装及旧版备份测试喵。
|
||||
- 0.1.1 在经典节点和 Nodes 2.0 用真实鼠标拖动底部高度条,画布增高 160px、缩小 80px,保存并重开后尺寸和蒙版均保留喵。
|
||||
- 0.1.2 用真实浏览器 Ctrl+滚轮测试笔径增减、1–512px 上下限、滑条数值同步和普通滚轮缩放,确认四个滑条位于画布下方;浏览器共 14 组交互验证通过喵。
|
||||
- 0.2.0 新增 Alt 临时擦除和图像对比节点,后端 18 项测试通过;真实鼠标/键盘操作确认松开 Alt 恢复原工具喵。
|
||||
- 0.2.0 在经典节点与 Nodes 2.0 的实际 API 队列验证左右像素、鼠标分割线、滚轮缩放、Ctrl+滚轮笔径、批量结果选择、多编辑器上游定位、点击回填、旧蒙版清空和保存后重新打开,无插件脚本错误喵。
|
||||
- 两种节点模式中的图片滚轮事件均不会误触发整张工作流缩放,回填结果保存在 input 目录并可嵌入工作流喵。
|
||||
- 0.3.0 在经典节点与 Nodes 2.0 验证底部内联参数控制真实采样节点、宽高分行、原图尺寸填写、工作流重开不重复增高、断开连接恢复原参数,以及 Nodes 2.0 原节点参数行实际隐藏喵。
|
||||
- 0.3.0 验证工具栏和参数区域滚轮传递给外部画布,连续外部滚轮手势进入图片后不改变图片缩放,停下后的图片滚轮只缩放图片喵。
|
||||
- 0.3.0 对比节点实测左侧为结果、右侧为原图,移出后完整显示结果;分割线为一个物理像素,移除了圆形手柄、角标和底部说明,回填与批量选择仍通过喵。
|
||||
- 0.3.0 画笔浏览器交互 15 组通过,两种渲染模式的纵向拉伸和保存恢复通过,两个更新后的示例工作流连线及执行参数验证通过喵。
|
||||
- 0.4.0 在经典节点与 Nodes 2.0 验证内联画布只保留载入按钮,原画笔 DOM 控件迁移到 WebUI 节点;真实鼠标涂抹后可从重绘节点撤销,工具和滑条控制原画布,采样参数正确进入执行请求喵。
|
||||
- 0.4.0 验证按原图比例缩减画布空边、细高度条拉伸、保存重开保持尺寸、原图尺寸填写、断开重连、删除重建重绘节点,以及工具区域滚轮继续操作外部画布喵。
|
||||
- 0.4.0 图像对比顶部不再有工具栏,结果选择、尺寸和适应移到底部;真实 API 队列中的左右对比、移出显示完整结果、批量选择及结果回填通过喵。
|
||||
- 0.4.1 真实浏览器按住 Alt 后确认橡皮擦 SVG 光标及擦除状态生效,松开后恢复十字画笔光标;临时擦除、常规绘画和 18 项后端 CPU 回归通过喵。
|
||||
- 0.4.1 统一公开名称为 Adachi-Inpaint-Workbench,保留节点类 ID 以兼容已有工作流喵。
|
||||
- 0.6.6: real mouse checks in classic nodes and Nodes 2.0 on frontend 1.52.7 verify right-click release without erasing, right-click while unselected, left-click relocking, preserved adopted pixels after merge, Alt temporary erase in both modes, and a functional live Undo button directly after Merge. The old reselect button and inpaint-panel Undo are absent. Canvas context menus are stopped from bubbling to the outer node. Frontend syntax and diff whitespace checks pass.
|
||||
|
||||
采样路径还使用本机 ComfyUI 的真实 common_ksampler/KSampler 函数进行了噪声调度衔接检查;尚未加载实际 checkpoint 测试 GPU 生成质量或所有模型家族,不能将 CPU/接口测试视为模型效果验证喵。
|
||||
- 0.6.5: classic and Nodes 2.0 browser checks on frontend 1.52.7 verify changing a locked preset, pointer-following replacement selection, automatic inpaint dimensions after relocking, preservation of an adopted patch by merging, retention of the old selection/resolution after an upload failure, and reselection through swap/custom controls. Frontend syntax and diff whitespace checks pass.
|
||||
|
||||
实现参考资料:
|
||||
- 0.6.4 comparison-adoption update: 48 backend tests pass, including removal of the result socket, ignoring obsolete feedback links, and generating-region metadata on comparison previews. Resolution-sync checks cover multiple connected targets, linked-input protection and source-size bounds. Real CPU comparison queues and browser interactions on isolated port 8196 with frontend 1.52.7 pass in classic nodes and Nodes 2.0: black dashed frame, automatic inpaint dimensions, no automatic stitching, manual crop adoption with retained repaint mask, independent fusion editing, reload, stale-result rejection, normal-mode mask preservation, and migration of the old wired example. Existing draft preflight/storage, comparison history, geometry and frontend syntax checks also pass. No complete model generation is claimed by these lightweight image probes.
|
||||
|
||||
- [ComfyUI 前端扩展接口](https://docs.comfy.org/custom-nodes/js/javascript_overview)
|
||||
- [ComfyUI widget 序列化说明](https://github.com/Comfy-Org/ComfyUI_frontend/blob/main/docs/WIDGET_SERIALIZATION.md)
|
||||
- [WebUI 重绘预处理语义](https://github.com/AUTOMATIC1111/stable-diffusion-webui/blob/master/modules/processing.py)
|
||||
- [rgthree 图像对比交互参考](https://github.com/rgthree/rgthree-comfy/blob/main/py/image_comparer.py)
|
||||
- 0.6.3: reproduced the sticky native draft failure on real frontend builds 1.42.11 and 1.52.7: after a 12 Mi-character draft fails, even a two-character draft returns false until the page reloads. Isolated lightweight API fixtures (no model queues or production writes) verify oversized workflow loading before configuration, exact source byte hashes, repaint mask pixels, stale named-snapshot cleanup, repeated mode changes and subsequent successful native draft writes in classic nodes and Nodes 2.0 on both builds. Unit checks additionally cover nested subgraph sources, named-only snapshots, fitting/blocked storage, failed uploads and unchanged masks/layers. This does not claim inspection of the user's live browser console or a complete model generation.
|
||||
|
||||
插件代码为独立实现,发布许可见 LICENSE,未附带上述项目源码喵。
|
||||
- 0.6.1 fixes (included in 0.6.2): reproduced the exact browser “failed to save workflow draft” toast on frontend 1.42.11 with an approximately 10-million-character embedded source and a real QuotaExceededError. The capacity guard now converts only a source that does not fit, uploading it before clearing embedded data. SHA-256 checks confirm the input PNG bytes are identical; repaint/fusion masks, layers and undo commands survive. Failed uploads preserve both embedding and mode, existing browser storage is untouched, fitting sources remain embedded and disabled workflow persistence is respected.
|
||||
- Combined 0.6.2: the quota/fold browser regression passes in classic nodes and Nodes 2.0 on frontends 1.42.11 and 1.52.7 (1.52.7 also tested after the concurrent crop/tool changes). The collapsed tools hide painting controls and mask/fill options while all seven action buttons remain visible and operational. Heights update, open/closed states survive workflow reload, and 1440/768/390 layouts pass. Real CPU feedback queues use image inversion rather than model inference; no complete Anima generation is claimed. All 47 backend tests and JavaScript tests for draft guarding, crop geometry, exclusive routing and comparison history pass.
|
||||
|
||||
- 0.6.2: all 47 backend tests, crop geometry checks and existing draft-guard checks pass; all frontend modules pass syntax checks. Real browser checks on an isolated 8194 CPU service with frontend 1.52.7 pass in classic nodes and Nodes 2.0: locked crops start empty, manual strokes paint normally, fill/rectangle/brush stay within the crop, undo/redo and reload preserve the mask, a fresh region clears previous strokes, ordinary mode remains unrestricted, and the toolbar contains no automatic-selection tools. Six presets include both 512 and 2048 endpoints and use only 64-aligned dimensions.
|
||||
|
||||
- 0.6.0: 47 CPU backend tests pass, including exact crop/mask slicing, soft fusion masks, batch composites, untouched outside pixels, content-addressed layer files, invalid bounds/result sizes, normal-mode ignored results and acyclic feedback normalization. Geometry, magic-wand/quick-selection, exclusive routing and comparison-history JavaScript checks also pass. All frontend modules pass syntax checks; example/localization JSON and project metadata parse successfully.
|
||||
- 0.6.0: real Chrome interaction and real CPU queues on isolated port 8191 with ComfyUI 0.19.3 and frontend 1.52.7 pass in classic nodes and Nodes 2.0. Tests cover a visible Inline Mask → ImageInvert → Inline Mask loop with full-image saving, normal-mode result ignoring, magic-wand add/subtract, quick-selection drag/subtract, independent repaint/fusion masks, soft-brush undo/redo, fixed-region repeat generation, saved-workflow restoration, merge/reselect, stale-job rejection, Ctrl/Shift wheel gestures, pinned graph scrolling and 1440/768/390 viewport layouts. No plugin script errors were observed. These are image-processing probes, not a complete Anima generation.
|
||||
- 0.6.0: the connected WebUI panel mounts the existing live painting controls, source-size filling uses locked crop dimensions, Escape closes the selection menu without reselecting, and the internal layer sink is hidden from the classic node menu. The old example loads with existing image/mask wires intact; the new eight-node crop/blend example is generated and reloaded through ComfyUI.
|
||||
|
||||
- 0.5.13: the remote history was read without modifying its workflow or queue. Three actual failed request snapshots contained selector 532 with a selected flag but no data input; local normalization restores its saved tag-subgraph connection to `349:412`, leaving selector 533's `16` source intact. Two real local CPU queue probes reproduce the missing-input shape and subgraph mapping with lightweight image sources, verify both selector outputs and upstream changes, and avoid model generation. All 39 backend unit tests pass, including Get/Set recovery, flattened subgraph output slots and refusal to reconnect absent or mismatched source types. The remote's complete Anima generation was not executed by these tests.
|
||||
|
||||
- 0.5.12: all 37 CPU unit tests pass. The supplied remote workflow was used as request metadata with lightweight red/blue image probes replacing model generation: positive selector 532 chooses B, negative 533 chooses A, all four Gets remain enabled. Ten real queue cases cover reverse Set/source states, switching back, encoder-only and Set-only bypass, unchanged-workflow preservation, cache reuse, and both-enabled/both-ignored errors. No complete Anima model generation is claimed by these routing probes. Sixteen native KJ Get/Set browser queue cases pass on frontend 1.52.7 in both renderers, and all 15 metadata-free stale-state API queue cases still pass.
|
||||
|
||||
- 0.5.11: all 32 backend CPU tests pass, including stale branch flags with either single submitted input, strict empty/ambiguous input errors, both-connected passthrough selection and dynamic subgraph node lookup. Fifteen real CPU queue cases verify single-branch A/B output pixels for flags -1 through 3, both-connected A/B selection, and invalid cases. Sixteen real KJ Get/Set queue cases on frontend 1.52.7 cover both renderers, source/Set/Get ignore and mute states, reverse switching, both-invalid states and workflow reload.
|
||||
|
||||
Environment: Windows, local ComfyUI 0.19.3, ComfyUI frontend 1.42.11, PyTorch 2.8.0, Pillow 11.0.0, Chrome 155, using a separate port 8190 CPU service with its own input/output directories and an in-memory database.
|
||||
|
||||
- 16 backend CPU tests pass, covering both sampling areas, edge masks, inversion, growth, feathering, surrounding-colour fill, batch mapping, source-pixel protection, empty masks, `denoise=0`, latent noise/zero modes, dedicated inpaint conditioning, different VAE compression ratios and Refiner staging.
|
||||
- 12 browser interaction tests pass, covering real mouse painting, right-button erase, rectangle/lasso, undo/redo, import persistence, half-pressure hard brush, active-shape saving, zoom coordinates and 1600/768/390 pixel window layouts.
|
||||
- Painting on the real canvas, workflow serialization, executed-parameter serialization and reload were verified in both classic nodes and Nodes 2.0: mask pixels match and the workflow correctly enters the modified state, with no plugin JavaScript errors.
|
||||
- The real ComfyUI API queue ran load → prepare → composite → save-image workflows in both sampling areas, with correct output sizes and RGB pixels outside the effective mask equal value-by-value.
|
||||
- Both example workflows were generated by the real nodes, reloaded and used to build executed parameters; nodes and links are valid and model filenames are user-selectable placeholders.
|
||||
- The installer was tested in a temp directory for first install, repeat install and previous-version backup.
|
||||
- 0.1.1: in classic nodes and Nodes 2.0 the bottom height bar was dragged with a real mouse, growing the canvas by 160 px and shrinking it by 80 px; size and mask both survived save and reopen.
|
||||
- 0.1.2: real-browser Ctrl+wheel tests covered brush size growth and shrink, the 1–512 px limits, slider value sync and plain-wheel zoom, confirming the four sliders sit below the canvas; 14 browser interaction checks passed in total.
|
||||
- 0.2.0: added Alt temporary erase and the image comparison node; 18 backend tests pass. Real mouse/keyboard use confirms releasing Alt restores the previous tool.
|
||||
- 0.2.0: the real API queue in classic nodes and Nodes 2.0 verified left/right pixels, the mouse divider, wheel zoom, Ctrl+wheel brush size, batch result selection, upstream editor discovery with several candidates, click-to-adopt, old mask clearing and reopen after save, with no plugin script errors.
|
||||
- Picture wheel events in both node modes never trigger whole-workflow zoom by mistake, and adopted results are stored in the input directory and can be embedded in the workflow.
|
||||
- 0.3.0: in classic nodes and Nodes 2.0 the bottom inline parameters were verified to drive the real sampling node, width/height on separate rows, source-size filling, no repeated growth on workflow reopen, disconnect restoring the original parameters, and the original parameter rows actually hidden in Nodes 2.0.
|
||||
- 0.3.0: wheel events over the toolbar and parameter area pass through to the outer canvas, a continuous outer wheel gesture does not change image zoom when it enters the picture, and wheel events inside the picture after stopping zoom only the picture.
|
||||
- 0.3.0: the comparison node was measured with the result on the left and the original on the right, showing the full result on exit; the divider is a single physical pixel, the round handle, corner labels and bottom caption were removed, and adoption plus batch selection still pass.
|
||||
- 0.3.0: 15 brush browser interaction checks pass, vertical stretching and save/restore pass in both rendering modes, and the two updated example workflows pass link and executed-parameter validation.
|
||||
- 0.4.0: in classic nodes and Nodes 2.0 the inline canvas was verified to keep only the load button with the original painting DOM controls moved into the WebUI node; real mouse painting can then be undone from the inpaint node, the tools and sliders drive the original canvas and the sampling parameters correctly reach the execution request.
|
||||
- 0.4.0: canvas margins shrinking to the image ratio, thin height-bar stretching, size retention across save/reopen, source-size filling, disconnect/reconnect, deleting and recreating the inpaint node, and toolbar-area wheel events continuing to drive the outer canvas were all verified.
|
||||
- 0.4.0: the comparison node no longer has a top toolbar, with result selection, dimensions and fit moved to the bottom; left/right comparison in the real API queue, full result on exit, batch selection and result adoption all pass.
|
||||
- 0.4.1: a real browser confirms the eraser SVG cursor and erase state after holding Alt, restoring the cross brush cursor on release; temporary erase, regular painting and the 18 backend CPU regression tests pass.
|
||||
- 0.4.1: the public name was unified to Adachi-Inpaint-Workbench while node class IDs were kept so existing workflows stay compatible.
|
||||
- 0.4.2: node display names, descriptions, tooltips and frontend labels were converted to English so the nodes are usable for the general Manager audience; the same 18 backend CPU tests pass and every touched script parses.
|
||||
- 0.5.0: in classic nodes and Nodes 2.0, adopting a real queued comparison result preserves mask PNG pixels, base-mask pixels and the current undo/redo command arrays. Undo/redo still work, workflow reload retains the mask, a mismatched result leaves the source/mask unchanged, and ordinary image upload still clears the mask.
|
||||
- 0.5.0: group preset tests cover real preset-button clicks, enabled/bypassed modes in executed prompts, exclusion of the virtual controller from backend execution, saved workflow reload, renamed and duplicate-title groups, unmanaged new groups, nested group priority, missing groups and protection of the controller itself.
|
||||
- 0.5.0: the native right-click preset submenu was clicked successfully in both renderers. The example workflow was loaded and all three presets queued successfully without a model.
|
||||
|
||||
- 0.5.1: all 23 CPU unit tests pass, including exclusive input validation and identity-preserving forwarding of conditioning, image/mask tensors, latents and falsey values.
|
||||
- 0.5.1: 26 real CPU queue cases across classic nodes and Nodes 2.0 cover A/B selection, bypassed transform pass-through, mute, both-enabled/both-bypassed/both-disconnected errors, reroutes, one connected input, group presets, cache changes, workflow reload and switching reloaded presets. Output pixels match the selected image; the unused branch was not requested by the selector. A raw API prompt works without frontend metadata.
|
||||
- 0.5.1: the 40%-width preset list retains internal scrolling and has no horizontal overflow in a 360px node at a 390px viewport.
|
||||
|
||||
- 0.5.2: all 29 CPU tests pass. New cases cover single-frame 5D image latents, per-source/variant masks, both crop modes, noise/zero fill, third-party VAE wrappers, native inpaint conditioning, refiner continuation, and explicit rejection of real multi-frame output.
|
||||
- 0.5.2: actual ComfyUI `VAE` + `WanVAE` encode/decode and `prepare_mask` were exercised with a small randomly initialized Wan architecture (16 latent channels). Four cases cover whole-image/original, masked-area/noise, zero-latent fill, and native inpaint conditioning, with two independent sources and two variants each. Latents were `[4,16,1,8,8]`, masks `[4,1,1,8,8]`, decoded images `[4,64,64,3]`, and all protected source pixels remained exact.
|
||||
- Anima checkpoint image generation was not performed: this machine does not have the user's Anima/Qwen VAE checkpoint files. The workflow was inspected read-only, confirming node 501 uses VAE node 358 (`qwen_image_vae.safetensors`) and the Anima model branch.
|
||||
|
||||
- 0.5.3: in classic nodes and Nodes 2.0, the inline Fit button is on the same row immediately to the right of Load image, and is absent from the connected inpaint controls. Actual browser clicks reset zoom/pan and preserve the painted mask PNG exactly.
|
||||
|
||||
- 0.5.4: frontend 1.52.7 was downloaded as a wheel and extracted into an isolated test directory, leaving the installed frontend unchanged. With saved node dimensions from the user's workflow, the previous bubbling Fit click changed the classic editor viewport from 396x625 to 396x594. Stopping propagation keeps it at 396x625. Nodes 2.0 also retains its viewport and node dimensions.
|
||||
- 0.5.4: actual browser clicks pass with the saved workflow geometry on frontend 1.42.11 and 1.52.7 in both renderers. Fit resets zoom/pan, remains immediately after Load image, and the inpaint panel occupies over 94% of its node's logical width. The remote server and its installed extension set were not accessed, so the separate narrow-panel screenshot cannot be claimed reproduced/resolved remotely.
|
||||
|
||||
- 0.5.5: injecting a cached widget width equal to 35% of its node width reproduces the narrow-column shape on frontend 1.52.7 classic nodes. Before the fix, a 380px inline node had a 113px editor; afterwards its editor is 360px wide, with the remaining 20px reserved for native margins. Inpaint and comparison widgets recover their full widths as well.
|
||||
- 0.5.5: browser checks on frontend 1.42.11 and 1.52.7, classic nodes and Nodes 2.0, cover attempted stale width writes, resizing node widths to 800/450/1050px, independent height expansion, graph zoom at 0.3/0.6/1.15, Fit with mask preservation, and saved workflow reload. The simulated failure is covered; the remote server itself was not accessed.
|
||||
|
||||
- 0.5.6: inspected the supplied workflow read-only: selectors 532/533 are fed by KJ Get nodes p/p_0 and n/n_0, while the p_0/n_0 setters are bypassed. The previous direct-node check therefore incorrectly classified both branches as enabled.
|
||||
- 0.5.6: actual local KJNodes Set/Get frontend definitions were loaded only into isolated QA browsers (no KJ code is bundled). Across frontend 1.42.11/1.52.7 and classic/Nodes 2.0, 32 real CPU queue cases verify ignored setters, swapped states, ignored/muted real sources, ignored Get, explicit both/neither errors, and switching after workflow reload. Output image pixels match the selected branch; generating prompts does not change editable connections.
|
||||
- 0.5.6: dependency-free routing tests cover Get/Set, reroutes, current virtual-output APIs, mute/bypass, missing setters/inputs and cycles. All 29 backend CPU tests continue to pass.
|
||||
|
||||
- 0.5.7: actual browser wheel events over a real queued comparison image change workflow navigation while the comparison transform stays fitted and centered. Verified on frontends 1.42.11 and 1.52.7 in classic nodes and Nodes 2.0, with left-result/right-original pixels, hover/leave behavior, batch selection, adoption preserving mask/history, workflow reload, rejected mismatched adoption and ordinary-upload mask reset.
|
||||
- 0.5.7: three real queued two-image batches accumulate 2, 4 and 6 results and select the newest result. After adoption, old results retain their old original and new results use the adopted original; all six results survive workflow reload in both frontend versions/renderers. Dependency-free tests additionally cover legacy batch mapping, empty outputs and immutable appending.
|
||||
- 0.5.8: real single-image queues on frontend 1.52.7 in classic nodes and Nodes 2.0 show 1/1 then 2/2. Replaying the same execution output twice does not increase the count or reset a manually selected result. Reloading a workflow containing duplicate preview references removes duplicates. Unit checks distinguish filenames, subfolders and file types.
|
||||
- 0.5.9: on frontend 1.52.7 in classic nodes and Nodes 2.0, a 1024x1536 comparison was measured at workflow zoom 1x, 2x and 4x. At 4x, 24 synchronous paints with readback dropped from 483 to 36 ms (classic) and 453 to 35 ms (Nodes 2.0). These are isolated browser measurements, not end-to-end workflow FPS guarantees. The divider measured one screen pixel at every zoom. Dirty-strip redraws matched full-redraw pixels exactly across forward/reverse/unchanged divider movements and edge positions; pointer exit hides the divider.
|
||||
- 0.5.10: frontends 1.42.11 and 1.52.7, both classic nodes and Nodes 2.0, verify the Upload label and pin icon beside Fit, pin persistence across workflow reload, plain wheel navigating the workflow, Ctrl+wheel brush sizing while pinned, and restored image wheel zoom after unpinning. At 4x graph zoom the display allocation remains bounded, the original mask dimensions remain 320x200, and 20 cursor-only redraws never recomposite the mask overlay. All 15 standalone editor regression groups pass, including real painting, Alt/right-button erase, undo/redo, shapes, pressure, serialization and zoom/pan coordinate mapping.
|
||||
- 0.5.10: actual adoption reduces the comparison list to 1/1, preserves mask PNG and undo/redo identities, and saves the pending new-round state. Reloading before generating retains that state; the next two-image batches start at 2/2 and then accumulate to 4/4. Rejected adoption leaves history unchanged. These checks pass in both frontend versions/renderers.
|
||||
|
||||
The sampling path was also checked for noise-schedule continuity against the real `common_ksampler`/`KSampler` functions in the local ComfyUI; an actual checkpoint has not been loaded to test GPU image quality or every model family, so CPU/interface tests must not be treated as model-quality verification.
|
||||
|
||||
References used during implementation:
|
||||
|
||||
- [ComfyUI frontend extension APIs](https://docs.comfy.org/custom-nodes/js/javascript_overview)
|
||||
- [ComfyUI widget serialization notes](https://github.com/Comfy-Org/ComfyUI_frontend/blob/main/docs/WIDGET_SERIALIZATION.md)
|
||||
- [WebUI inpainting pre-processing semantics](https://github.com/AUTOMATIC1111/stable-diffusion-webui/blob/master/modules/processing.py)
|
||||
- [rgthree image comparison interaction reference](https://github.com/rgthree/rgthree-comfy/blob/main/py/image_comparer.py)
|
||||
|
||||
The plugin code is an independent implementation; see LICENSE for the release licence. No source from the projects above is bundled.
|
||||
|
||||
+6
-1
@@ -1,6 +1,11 @@
|
||||
"""Adachi-Inpaint-Workbench custom-node package for ComfyUI."""
|
||||
|
||||
from .backend import NODE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS
|
||||
from .backend import NODE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS, normalize_exclusive_prompt
|
||||
from server import PromptServer
|
||||
|
||||
if not getattr(PromptServer.instance, "_adachi_exclusive_normalizer", False):
|
||||
PromptServer.instance.add_on_prompt_handler(normalize_exclusive_prompt)
|
||||
PromptServer.instance._adachi_exclusive_normalizer = True
|
||||
|
||||
WEB_DIRECTORY = "./web"
|
||||
|
||||
|
||||
+516
-60
@@ -10,9 +10,11 @@ import base64
|
||||
import binascii
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import math
|
||||
from pathlib import Path
|
||||
import re
|
||||
import tempfile
|
||||
import warnings
|
||||
|
||||
import numpy as np
|
||||
@@ -21,7 +23,7 @@ import torch
|
||||
import torch.nn.functional as F
|
||||
|
||||
|
||||
CATEGORY = "安达工作台 / Adachi-Inpaint-Workbench"
|
||||
CATEGORY = "Adachi-Inpaint-Workbench"
|
||||
MAX_IMAGE_PIXELS = 32_000_000
|
||||
MAX_IMAGE_BYTES = 64 * 1024 * 1024
|
||||
MAX_DATA_URL_CHARS = 4 * ((MAX_IMAGE_BYTES + 2) // 3) + 128
|
||||
@@ -289,17 +291,17 @@ def _composite(generated, context):
|
||||
|
||||
def _prepare_inputs():
|
||||
return {
|
||||
"image": ("IMAGE", {"tooltip": "原图 / Original image; output is restored to this exact size."}),
|
||||
"mask": ("MASK", {"tooltip": "白色重绘,黑色保护 / White repaints; black preserves."}),
|
||||
"area": (["whole_image", "only_masked"], {"default": "only_masked", "tooltip": "whole_image:整张原图缩放采样;only_masked:蒙版包围框加边距放大采样,再贴回原图 / Whole image or mask bounding-box inpainting."}),
|
||||
"width": ("INT", {"default": 1024, "min": 64, "max": 8192, "step": 8, "tooltip": "采样画布宽度;最终输出仍为原图尺寸 / Sampling canvas width, independent of final image size."}),
|
||||
"height": ("INT", {"default": 1024, "min": 64, "max": 8192, "step": 8, "tooltip": "采样画布高度 / Sampling canvas height."}),
|
||||
"padding": ("INT", {"default": 32, "min": 0, "max": 2048, "step": 1, "tooltip": "仅蒙版区域:原图像素单位的上下文边距 / Mask-only context padding in original pixels."}),
|
||||
"mask_blur": ("FLOAT", {"default": 4.0, "min": 0.0, "max": 128.0, "step": 0.5, "tooltip": "原图像素单位的高斯羽化半径 / Gaussian mask feathering in original pixels."}),
|
||||
"mask_grow": ("INT", {"default": 0, "min": -128, "max": 128, "step": 1, "tooltip": "正数扩张,负数收缩 / Positive dilates; negative erodes the mask."}),
|
||||
"mask_mode": (["inside", "outside"], {"default": "inside", "tooltip": "inside:蒙版内;outside:蒙版外 / Repaint inside or invert the mask."}),
|
||||
"fill": (["original", "fill", "latent_noise", "latent_nothing"], {"default": "original", "tooltip": "原图像素、周围颜色填充、潜空间噪声、空白潜空间;后两项由一体采样节点在 latent 层实现 / Original, surrounding-color fill, latent noise, or zero latent. Latent modes require the all-in-one sampler."}),
|
||||
"resize_mode": (["stretch", "crop", "fill"], {"default": "stretch", "tooltip": "整图模式:拉伸、居中裁剪、保比例填充;仅蒙版模式自动保留完整蒙版 / Whole-image resize mode; mask-only mode always retains the entire mask."}),
|
||||
"image": ("IMAGE", {"tooltip": "Original image; output is restored to this exact size."}),
|
||||
"mask": ("MASK", {"tooltip": "White repaints; black preserves."}),
|
||||
"area": (["whole_image", "only_masked"], {"default": "only_masked", "tooltip": "Whole image or mask bounding-box inpainting."}),
|
||||
"width": ("INT", {"default": 1024, "min": 64, "max": 8192, "step": 8, "tooltip": "Sampling canvas width, independent of final image size."}),
|
||||
"height": ("INT", {"default": 1024, "min": 64, "max": 8192, "step": 8, "tooltip": "Sampling canvas height."}),
|
||||
"padding": ("INT", {"default": 32, "min": 0, "max": 2048, "step": 1, "tooltip": "Mask-only context padding in original pixels."}),
|
||||
"mask_blur": ("FLOAT", {"default": 4.0, "min": 0.0, "max": 128.0, "step": 0.5, "tooltip": "Gaussian mask feathering in original pixels."}),
|
||||
"mask_grow": ("INT", {"default": 0, "min": -128, "max": 128, "step": 1, "tooltip": "Positive dilates; negative erodes the mask."}),
|
||||
"mask_mode": (["inside", "outside"], {"default": "inside", "tooltip": "Repaint inside or invert the mask."}),
|
||||
"fill": (["original", "fill", "latent_noise", "latent_nothing"], {"default": "original", "tooltip": "Original, surrounding-color fill, latent noise, or zero latent. Latent modes require the all-in-one sampler."}),
|
||||
"resize_mode": (["stretch", "crop", "fill"], {"default": "stretch", "tooltip": "Whole-image resize mode; mask-only mode always retains the entire mask."}),
|
||||
}
|
||||
|
||||
|
||||
@@ -307,22 +309,27 @@ class AdachiInlineMask:
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {"required": {
|
||||
"image": ("STRING", {"default": "", "tooltip": "ComfyUI input 图片路径,由内联编辑器上传 / Input image path populated by inline upload."}),
|
||||
"mask_data": ("STRING", {"default": "", "multiline": False, "tooltip": "编辑器保存的白底重绘蒙版 PNG / Editor mask PNG data URL; white repaints."}),
|
||||
"source_data": ("STRING", {"default": "", "multiline": False, "tooltip": "嵌入原图以便工作流在其他机器使用 / Embedded source image for portable workflows."}),
|
||||
"image": ("STRING", {"default": "", "tooltip": "Input image path populated by inline upload."}),
|
||||
"mask_data": ("STRING", {"default": "", "multiline": False, "tooltip": "Editor mask PNG data URL; white repaints."}),
|
||||
"source_data": ("STRING", {"default": "", "multiline": False, "tooltip": "Embedded source image for portable workflows."}),
|
||||
}, "optional": {
|
||||
"edit_mode": (["mask", "crop"], {"default": "mask"}),
|
||||
"crop_state": ("STRING", {"default": "{}"}),
|
||||
"blend_data": ("STRING", {"default": ""}),
|
||||
"layer_image": ("STRING", {"default": ""}),
|
||||
}}
|
||||
|
||||
RETURN_TYPES = ("IMAGE", "MASK")
|
||||
RETURN_NAMES = ("image", "mask")
|
||||
RETURN_TYPES = ("IMAGE", "MASK", "IMAGE")
|
||||
RETURN_NAMES = ("image", "mask", "full_image")
|
||||
FUNCTION = "load"
|
||||
CATEGORY = CATEGORY
|
||||
DESCRIPTION = "直接在工作流节点内涂抹蒙版,无需打开独立编辑器 / Paint an inpaint mask directly in the workflow."
|
||||
DESCRIPTION = "Paint an inpaint mask directly in the workflow."
|
||||
SEARCH_ALIASES = ["inline mask", "webui inpaint", "局部重绘", "安达", "adachi"]
|
||||
|
||||
@classmethod
|
||||
def IS_CHANGED(cls, image="", mask_data="", source_data=""):
|
||||
def IS_CHANGED(cls, image="", mask_data="", source_data="", **kwargs):
|
||||
digest = hashlib.sha256()
|
||||
for value in (image, mask_data, source_data):
|
||||
for value in (image, mask_data, source_data, json.dumps(kwargs, sort_keys=True, default=str)):
|
||||
digest.update(str(value).encode("utf-8"))
|
||||
digest.update(b"\x00")
|
||||
if not source_data:
|
||||
@@ -334,7 +341,7 @@ class AdachiInlineMask:
|
||||
return float("nan")
|
||||
return digest.hexdigest()
|
||||
|
||||
def load(self, image="", mask_data="", source_data=""):
|
||||
def load(self, image="", mask_data="", source_data="", edit_mode="mask", crop_state="{}", blend_data="", layer_image="", result=None):
|
||||
raster = _data_image(source_data) if source_data else _read_raster(_input_path(image))
|
||||
rgba = raster.convert("RGBA")
|
||||
pixels = torch.from_numpy(np.asarray(rgba.convert("RGB"), dtype=np.float32).copy() / 255.0)[None]
|
||||
@@ -345,22 +352,29 @@ class AdachiInlineMask:
|
||||
mask = np.asarray(mask_image, dtype=np.float32).copy() / 255.0
|
||||
else:
|
||||
mask = 1.0 - np.asarray(rgba.getchannel("A"), dtype=np.float32).copy() / 255.0
|
||||
return pixels, torch.from_numpy(mask)[None]
|
||||
mask = torch.from_numpy(mask)[None]
|
||||
if edit_mode == "crop":
|
||||
state = _crop_state(crop_state)
|
||||
if state.get("locked"):
|
||||
x, y, width, height = _crop_box(state, pixels.shape[2], pixels.shape[1])
|
||||
composite = _blend_layer(pixels, _load_layer(layer_image), blend_data, state)
|
||||
return composite[:, y:y+height, x:x+width].clone(), mask[:, y:y+height, x:x+width].clone(), composite
|
||||
return pixels, mask, pixels
|
||||
|
||||
|
||||
class AdachiInpaintPrepare:
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {"required": _prepare_inputs(), "optional": {
|
||||
"soft_edge": ("BOOLEAN", {"default": False, "tooltip": "额外羽化;不是 A1111 Soft Inpainting 算法 / Extra feathering, not AUTOMATIC1111's Soft Inpainting algorithm."}),
|
||||
"soft_strength": ("FLOAT", {"default": 0.5, "min": 0.0, "max": 1.0, "step": 0.05, "tooltip": "额外增加 0–16 像素羽化 / Adds 0–16 pixels of Gaussian feathering."}),
|
||||
"soft_edge": ("BOOLEAN", {"default": False, "tooltip": "Extra feathering, not AUTOMATIC1111's Soft Inpainting algorithm."}),
|
||||
"soft_strength": ("FLOAT", {"default": 0.5, "min": 0.0, "max": 1.0, "step": 0.05, "tooltip": "Adds 0–16 pixels of Gaussian feathering."}),
|
||||
}}
|
||||
|
||||
RETURN_TYPES = ("IMAGE", "MASK", "ADACHI_INPAINT_CONTEXT")
|
||||
RETURN_NAMES = ("pixels", "mask", "context")
|
||||
FUNCTION = "prepare"
|
||||
CATEGORY = CATEGORY
|
||||
DESCRIPTION = "局部重绘裁剪、蒙版处理与精确回贴上下文;latent 填充请使用一体采样节点 / Crop and prepare masks with exact compositing context; use the all-in-one sampler for latent fill modes."
|
||||
DESCRIPTION = "Crop and prepare masks with exact compositing context; use the all-in-one sampler for latent fill modes."
|
||||
SEARCH_ALIASES = ["inpaint crop", "局部重绘预处理", "webui", "adachi"]
|
||||
|
||||
def prepare(self, image, mask, **kwargs):
|
||||
@@ -371,15 +385,15 @@ class AdachiInpaintComposite:
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {"required": {
|
||||
"generated": ("IMAGE", {"tooltip": "采样后的裁剪图 / Generated sampling canvas."}),
|
||||
"context": ("ADACHI_INPAINT_CONTEXT", {"tooltip": "预处理节点的裁剪和原图上下文 / Context from Adachi Inpaint Prepare."}),
|
||||
"generated": ("IMAGE", {"tooltip": "Generated sampling canvas."}),
|
||||
"context": ("ADACHI_INPAINT_CONTEXT", {"tooltip": "Context from Adachi Inpaint Prepare."}),
|
||||
}}
|
||||
|
||||
RETURN_TYPES = ("IMAGE",)
|
||||
RETURN_NAMES = ("image",)
|
||||
FUNCTION = "composite"
|
||||
CATEGORY = CATEGORY
|
||||
DESCRIPTION = "还原原图尺寸,软蒙版外保持原像素不变 / Restore original size and preserve pixels outside the effective mask exactly."
|
||||
DESCRIPTION = "Restore original size and preserve pixels outside the effective mask exactly."
|
||||
SEARCH_ALIASES = ["inpaint paste", "局部重绘回贴", "adachi"]
|
||||
|
||||
def composite(self, generated, context):
|
||||
@@ -396,6 +410,58 @@ def _vae_ratio(vae):
|
||||
return int(ratio) if isinstance(ratio, (int, float)) and ratio >= 1 else 8
|
||||
|
||||
|
||||
def _check_image_latents(samples, batch):
|
||||
if not isinstance(samples, torch.Tensor) or samples.ndim not in (4, 5) or min(samples.shape) < 1:
|
||||
raise ValueError("Image VAE must return [B,C,H,W] or [B,C,1,H,W] latents.")
|
||||
if samples.shape[0] != batch:
|
||||
raise ValueError("VAE latent batch must match the number of independent input images.")
|
||||
if samples.ndim == 5 and samples.shape[2] != 1:
|
||||
raise ValueError("Still-image inpainting requires one latent frame per image (T=1); multi-frame video is not supported.")
|
||||
return samples
|
||||
|
||||
|
||||
def _encode_still_images(vae, pixels):
|
||||
# Video-derived VAEs can interpret a 4D IMAGE batch as consecutive frames.
|
||||
# Encode those VAEs one image at a time so sources/variants remain independent.
|
||||
if getattr(vae, "latent_dim", None) == 3 and pixels.shape[0] > 1:
|
||||
samples = torch.cat([_check_image_latents(vae.encode(frame[None]), 1) for frame in pixels], dim=0)
|
||||
else:
|
||||
samples = vae.encode(pixels)
|
||||
# Also support third-party VAE wrappers without a latent_dim attribute.
|
||||
if isinstance(samples, torch.Tensor) and samples.ndim == 5 and pixels.shape[0] > 1:
|
||||
if samples.shape[0] != pixels.shape[0] or samples.shape[2] != 1:
|
||||
samples = torch.cat([_check_image_latents(vae.encode(frame[None]), 1) for frame in pixels], dim=0)
|
||||
return _check_image_latents(samples, pixels.shape[0])
|
||||
|
||||
|
||||
class _StillImageVAE:
|
||||
"""Keep native inpaint conditioning while making its VAE encodes batch-safe."""
|
||||
|
||||
def __init__(self, vae):
|
||||
self.vae = vae
|
||||
|
||||
def __getattr__(self, name):
|
||||
return getattr(self.vae, name)
|
||||
|
||||
def encode(self, pixels):
|
||||
return _encode_still_images(self.vae, pixels)
|
||||
|
||||
|
||||
def _decode_still_images(vae, samples, batch):
|
||||
_check_image_latents(samples, batch)
|
||||
decoded = vae.decode(samples)
|
||||
if isinstance(decoded, tuple):
|
||||
decoded = decoded[0]
|
||||
if isinstance(decoded, torch.Tensor) and decoded.ndim == 5:
|
||||
if decoded.shape[1] != 1:
|
||||
raise ValueError("VAE decoded multiple frames for a still image; expected [B,1,H,W,C].")
|
||||
decoded = decoded[:, 0]
|
||||
decoded = _image_tensor(decoded)
|
||||
if decoded.shape[0] != batch:
|
||||
raise ValueError("VAE decoded image batch does not match the input image batch.")
|
||||
return decoded
|
||||
|
||||
|
||||
def _check_refiner(model, refiner):
|
||||
"""Reject known incompatible latent formats while allowing SDXL base/refiner."""
|
||||
first = getattr(getattr(model, "model", None), "latent_format", None)
|
||||
@@ -430,29 +496,29 @@ class AdachiWebUIInpaint:
|
||||
required = {
|
||||
"model": ("MODEL",), "positive": ("CONDITIONING",), "negative": ("CONDITIONING",), "vae": ("VAE",),
|
||||
**_prepare_inputs(),
|
||||
"seed": ("INT", {"default": 0, "min": 0, "max": 0xFFFFFFFFFFFFFFFF, "control_after_generate": True, "tooltip": "可复现批量随机种子 / Seed for a reproducible batch of distinct samples."}),
|
||||
"seed": ("INT", {"default": 0, "min": 0, "max": 0xFFFFFFFFFFFFFFFF, "control_after_generate": True, "tooltip": "Seed for a reproducible batch of distinct samples."}),
|
||||
"steps": ("INT", {"default": 20, "min": 1, "max": 10000}),
|
||||
"cfg": ("FLOAT", {"default": 7.0, "min": 0.0, "max": 100.0, "step": 0.1}),
|
||||
"sampler_name": (comfy.samplers.KSampler.SAMPLERS,),
|
||||
"scheduler": (comfy.samplers.KSampler.SCHEDULERS,),
|
||||
"denoise": ("FLOAT", {"default": 0.75, "min": 0.0, "max": 1.0, "step": 0.01, "tooltip": "0 原样返回原图,1 完全重绘 / Zero returns the original exactly; one fully denoises."}),
|
||||
"batch_size": ("INT", {"default": 1, "min": 1, "max": 16, "tooltip": "每张输入图生成数量 / Number of generated variants per input image."}),
|
||||
"refiner_switch": ("FLOAT", {"default": 0.8, "min": 0.0, "max": 1.0, "step": 0.01, "tooltip": "接入 Refiner 时的采样切换比例;0全程refiner,1全程base / Fraction of steps on the base model when a refiner is connected."}),
|
||||
"denoise": ("FLOAT", {"default": 0.75, "min": 0.0, "max": 1.0, "step": 0.01, "tooltip": "Zero returns the original exactly; one fully denoises."}),
|
||||
"batch_size": ("INT", {"default": 1, "min": 1, "max": 16, "tooltip": "Number of generated variants per input image."}),
|
||||
"refiner_switch": ("FLOAT", {"default": 0.8, "min": 0.0, "max": 1.0, "step": 0.01, "tooltip": "Fraction of steps on the base model when a refiner is connected."}),
|
||||
}
|
||||
return {"required": required, "optional": {
|
||||
"inpaint_model": ("BOOLEAN", {"default": False, "tooltip": "仅专用 inpaint 模型开启,添加原生 inpaint conditioning / Enable only for dedicated inpainting models; uses ComfyUI's native InpaintModelConditioning."}),
|
||||
"soft_edge": ("BOOLEAN", {"default": False, "tooltip": "额外羽化,并非 A1111 Soft Inpainting 原算法 / Extra feathering, not A1111 Soft Inpainting."}),
|
||||
"inpaint_model": ("BOOLEAN", {"default": False, "tooltip": "Enable only for dedicated inpainting models; uses ComfyUI's native InpaintModelConditioning."}),
|
||||
"soft_edge": ("BOOLEAN", {"default": False, "tooltip": "Extra feathering, not A1111 Soft Inpainting."}),
|
||||
"soft_strength": ("FLOAT", {"default": 0.5, "min": 0.0, "max": 1.0, "step": 0.05}),
|
||||
"refiner_model": ("MODEL", {"tooltip": "可选的兼容 Refiner 模型(例如 SDXL refiner) / Optional compatible refiner model, e.g. SDXL refiner."}),
|
||||
"refiner_positive": ("CONDITIONING", {"tooltip": "用 Refiner 的 CLIP 编码;未连接则沿用原始正面条件 / Encode using the refiner CLIP; defaults to original positive conditioning."}),
|
||||
"refiner_negative": ("CONDITIONING", {"tooltip": "用 Refiner 的 CLIP 编码;未连接则沿用原始负面条件 / Encode using the refiner CLIP; defaults to original negative conditioning."}),
|
||||
"refiner_model": ("MODEL", {"tooltip": "Optional compatible refiner model, e.g. SDXL refiner."}),
|
||||
"refiner_positive": ("CONDITIONING", {"tooltip": "Encode using the refiner CLIP; defaults to original positive conditioning."}),
|
||||
"refiner_negative": ("CONDITIONING", {"tooltip": "Encode using the refiner CLIP; defaults to original negative conditioning."}),
|
||||
}}
|
||||
|
||||
RETURN_TYPES = ("IMAGE", "IMAGE", "MASK")
|
||||
RETURN_NAMES = ("image", "crop", "mask")
|
||||
FUNCTION = "sample"
|
||||
CATEGORY = CATEGORY
|
||||
DESCRIPTION = "WebUI 式局部重绘:整图/蒙版区域、填充、采样和原尺寸回贴 / WebUI-style inpainting, crop, latent fill, sampling and original-size compositing."
|
||||
DESCRIPTION = "WebUI-style inpainting, crop, latent fill, sampling and original-size compositing."
|
||||
SEARCH_ALIASES = ["webui", "img2img", "inpaint", "局部重绘", "安达", "adachi"]
|
||||
|
||||
def sample(self, model, positive, negative, vae, image, mask, seed=0, steps=20, cfg=7.0,
|
||||
@@ -478,13 +544,26 @@ class AdachiWebUIInpaint:
|
||||
masks = _resize_mask(masks, target_height, target_width)
|
||||
if inpaint_model:
|
||||
positive, negative, latent = nodes.InpaintModelConditioning().encode(
|
||||
positive=positive, negative=negative, pixels=pixels, vae=vae, mask=masks, noise_mask=True)
|
||||
positive=positive, negative=negative, pixels=pixels, vae=_StillImageVAE(vae), mask=masks, noise_mask=True)
|
||||
else:
|
||||
latent = {"samples": vae.encode(pixels)}
|
||||
samples = latent["samples"]
|
||||
if not isinstance(samples, torch.Tensor) or samples.ndim != 4:
|
||||
raise ValueError("This node supports still-image VAEs with 4D image latents.")
|
||||
latent = {"samples": _encode_still_images(vae, pixels)}
|
||||
samples = _check_image_latents(latent["samples"], pixels.shape[0])
|
||||
latent_mask = _resize_mask(masks.to(device=samples.device, dtype=samples.dtype), samples.shape[-2], samples.shape[-1])[:, None]
|
||||
if samples.ndim == 5:
|
||||
latent_mask = latent_mask.unsqueeze(2)
|
||||
if inpaint_model:
|
||||
# Native conditioning provides a pixel-space [B,1,H,W] mask;
|
||||
# retain the independent batch axis for volumetric model inputs.
|
||||
def volumetric_conditioning(conditioning):
|
||||
result = []
|
||||
for embedding, metadata in conditioning:
|
||||
metadata = metadata.copy()
|
||||
concat_mask = metadata.get("concat_mask")
|
||||
if isinstance(concat_mask, torch.Tensor) and concat_mask.ndim == 4:
|
||||
metadata["concat_mask"] = concat_mask.unsqueeze(2)
|
||||
result.append([embedding, metadata])
|
||||
return result
|
||||
positive, negative = volumetric_conditioning(positive), volumetric_conditioning(negative)
|
||||
latent["noise_mask"] = latent_mask
|
||||
fill = kwargs.get("fill", "original")
|
||||
if fill in {"latent_noise", "latent_nothing"}:
|
||||
@@ -512,10 +591,7 @@ class AdachiWebUIInpaint:
|
||||
else:
|
||||
sampled = nodes.common_ksampler(model, int(seed), int(steps), float(cfg), sampler_name, scheduler,
|
||||
positive, negative, latent, denoise=float(denoise))[0]
|
||||
decoded = vae.decode(sampled["samples"])
|
||||
if isinstance(decoded, tuple):
|
||||
decoded = decoded[0]
|
||||
decoded = _image_tensor(decoded)
|
||||
decoded = _decode_still_images(vae, sampled["samples"], pixels.shape[0])
|
||||
return _composite(decoded, context), decoded, masks
|
||||
|
||||
|
||||
@@ -525,32 +601,408 @@ class AdachiImageCompare:
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {"required": {
|
||||
"original": ("IMAGE", {"tooltip": "右侧原图,连接内联蒙版的 image / Original image shown on the right."}),
|
||||
"result": ("IMAGE", {"tooltip": "左侧完整重绘图,请连接最终 image 而非 crop / Full-size generated image shown on the left; use image, not crop."}),
|
||||
}}
|
||||
"original": ("IMAGE", {"tooltip": "Original image shown on the right."}),
|
||||
"result": ("IMAGE", {"tooltip": "Full-size generated image shown on the left; use image, not crop."}),
|
||||
}, "hidden": {"prompt": "PROMPT", "unique_id": "UNIQUE_ID", "dynprompt": "DYNPROMPT"}}
|
||||
|
||||
RETURN_TYPES = ("IMAGE",)
|
||||
RETURN_NAMES = ("image",)
|
||||
FUNCTION = "compare"
|
||||
OUTPUT_NODE = True
|
||||
CATEGORY = CATEGORY
|
||||
DESCRIPTION = "鼠标竖线左右对比原图与重绘结果;点击采用此结果可送回上游内联蒙版 / Hover to compare; adopt a result into the upstream inline editor."
|
||||
DESCRIPTION = "Hover to compare; adopt a result into the upstream inline editor."
|
||||
SEARCH_ALIASES = ["compare", "before after", "图像对比", "adachi", "安达工作台"]
|
||||
|
||||
def compare(self, original, result):
|
||||
def compare(self, original, result, prompt=None, unique_id=None, dynprompt=None):
|
||||
import nodes
|
||||
|
||||
original, result = _image_tensor(original), _image_tensor(result)
|
||||
if original.shape[1:3] != result.shape[1:3]:
|
||||
raise ValueError("原图与结果尺寸须一致,请连接最终 image 输出而非 crop / Image sizes must match. Connect the final image output, not crop.")
|
||||
raise ValueError("Image sizes must match. Connect the final image output, not crop.")
|
||||
if result.shape[0] % original.shape[0]:
|
||||
raise ValueError("结果批量须为原图批量的整数倍 / Result batch must be a multiple of the original batch.")
|
||||
raise ValueError("Result batch must be a multiple of the original batch.")
|
||||
if original.shape[1] * original.shape[2] > MAX_IMAGE_PIXELS or max(original.shape[1:3]) > 16384:
|
||||
raise ValueError("Comparison images exceed the inline editor's 32 megapixel / 16384px limit.")
|
||||
preview = nodes.PreviewImage()
|
||||
before = preview.save_images(original, filename_prefix="adachi_compare_original")["ui"]["images"]
|
||||
after = preview.save_images(result, filename_prefix="adachi_compare_result")["ui"]["images"]
|
||||
return {"ui": {"adachi_originals": before, "adachi_results": after}, "result": (result,)}
|
||||
origin = _comparison_origin(prompt, unique_id, dynprompt)
|
||||
return {"ui": {"adachi_originals": before, "adachi_results": after, "adachi_origin": [origin] if origin else []}, "result": (result,)}
|
||||
|
||||
|
||||
_MISSING_INPUT = object()
|
||||
|
||||
|
||||
def _workflow_exclusive_flags(extra_pnginfo, unique_id):
|
||||
"""Recover routing states from the editable graph, before virtual links vanish."""
|
||||
workflow = extra_pnginfo.get("workflow") if isinstance(extra_pnginfo, dict) else None
|
||||
if not isinstance(workflow, dict) or unique_id is None:
|
||||
return None
|
||||
definitions = {str(g.get("id")): g for g in workflow.get("definitions", {}).get("subgraphs", [])}
|
||||
graph = workflow
|
||||
parts = str(unique_id).split(":")
|
||||
for parent_id in parts[:-1]:
|
||||
parent = next((n for n in graph.get("nodes", []) if str(n.get("id")) == parent_id), None)
|
||||
graph = definitions.get(str(parent.get("type"))) if parent else None
|
||||
if graph is None:
|
||||
return None
|
||||
nodes = {str(n.get("id")): n for n in graph.get("nodes", [])}
|
||||
selector = nodes.get(parts[-1])
|
||||
if not selector or selector.get("type") != "AdachiExclusiveSwitch":
|
||||
return None
|
||||
links = {}
|
||||
for link in graph.get("links", []):
|
||||
if isinstance(link, dict):
|
||||
links[str(link["id"])] = (str(link["origin_id"]), link.get("origin_slot", 0))
|
||||
else:
|
||||
links[str(link[0])] = (str(link[1]), link[2])
|
||||
|
||||
def visit(node_id, slot, seen):
|
||||
if node_id in seen:
|
||||
return False
|
||||
node = nodes.get(node_id)
|
||||
if node is None:
|
||||
return None # e.g. a subgraph's external input placeholder
|
||||
if node.get("mode", 0) in (2, 4):
|
||||
return False
|
||||
seen = seen | {node_id}
|
||||
kind = node.get("type")
|
||||
if kind == "GetNode":
|
||||
values = node.get("widgets_values", [])
|
||||
name = values[0] if isinstance(values, list) and values else None
|
||||
setter = next((n for n in nodes.values() if n.get("type") == "SetNode"
|
||||
and isinstance(n.get("widgets_values"), list)
|
||||
and n["widgets_values"] and n["widgets_values"][0] == name), None) if name else None
|
||||
return visit(str(setter["id"]), slot, seen) if setter else False
|
||||
if kind in ("SetNode", "Reroute"):
|
||||
inputs = node.get("inputs", [])
|
||||
if not inputs:
|
||||
return False
|
||||
source = inputs[slot] if isinstance(slot, int) and 0 <= slot < len(inputs) else inputs[0]
|
||||
link = links.get(str(source.get("link")))
|
||||
return visit(*link, seen) if link else False
|
||||
return True
|
||||
|
||||
flags = 0
|
||||
for name, bit in (("input_a", 1), ("input_b", 2)):
|
||||
source = next((i for i in selector.get("inputs", []) if i.get("name") == name), {})
|
||||
link = links.get(str(source.get("link")))
|
||||
enabled = visit(*link, set()) if link else False
|
||||
if enabled is None:
|
||||
return None
|
||||
if enabled:
|
||||
flags |= bit
|
||||
return flags
|
||||
|
||||
|
||||
def _workflow_exclusive_sources(extra_pnginfo, unique_id, prompt):
|
||||
"""Resolve saved graph outputs to existing flattened execution nodes only."""
|
||||
workflow = extra_pnginfo.get("workflow") if isinstance(extra_pnginfo, dict) else None
|
||||
if not isinstance(workflow, dict):
|
||||
return {}
|
||||
definitions = {str(g.get("id")): g for g in workflow.get("definitions", {}).get("subgraphs", [])}
|
||||
|
||||
def index(graph):
|
||||
nodes = {str(n.get("id")): n for n in graph.get("nodes", [])}
|
||||
links = {}
|
||||
for link in graph.get("links", []):
|
||||
if isinstance(link, dict):
|
||||
links[str(link["id"])] = (str(link["origin_id"]), link.get("origin_slot", 0))
|
||||
else:
|
||||
links[str(link[0])] = (str(link[1]), link[2])
|
||||
return nodes, links
|
||||
|
||||
graph, path = workflow, []
|
||||
parts = str(unique_id).split(":")
|
||||
for parent_id in parts[:-1]:
|
||||
nodes, _ = index(graph)
|
||||
parent = nodes.get(parent_id)
|
||||
graph = definitions.get(str(parent.get("type"))) if parent else None
|
||||
if graph is None:
|
||||
return {}
|
||||
path.append(parent_id)
|
||||
nodes, links = index(graph)
|
||||
selector = nodes.get(parts[-1])
|
||||
if not selector or selector.get("type") != "AdachiExclusiveSwitch":
|
||||
return {}
|
||||
|
||||
def resolve(current, node_id, slot, prefix, seen):
|
||||
key = (id(current), node_id, slot)
|
||||
if key in seen or len(seen) > 64:
|
||||
return None
|
||||
seen = seen | {key}
|
||||
current_nodes, current_links = index(current)
|
||||
node = current_nodes.get(node_id)
|
||||
if not node or node.get("mode", 0) in (2, 4):
|
||||
return None
|
||||
kind = node.get("type")
|
||||
if kind == "GetNode":
|
||||
values = node.get("widgets_values", [])
|
||||
name = values[0] if isinstance(values, list) and values else None
|
||||
setter = next((n for n in current_nodes.values() if n.get("type") == "SetNode"
|
||||
and isinstance(n.get("widgets_values"), list)
|
||||
and n["widgets_values"] and n["widgets_values"][0] == name), None) if name else None
|
||||
return resolve(current, str(setter["id"]), slot, prefix, seen) if setter else None
|
||||
if kind in ("SetNode", "Reroute"):
|
||||
inputs = node.get("inputs", [])
|
||||
source = inputs[slot] if isinstance(slot, int) and 0 <= slot < len(inputs) else inputs[0] if inputs else {}
|
||||
link = current_links.get(str(source.get("link")))
|
||||
return resolve(current, *link, prefix, seen) if link else None
|
||||
if kind in definitions:
|
||||
child = definitions[kind]
|
||||
outputs = child.get("outputs", [])
|
||||
if not isinstance(slot, int) or not 0 <= slot < len(outputs):
|
||||
return None
|
||||
_, child_links = index(child)
|
||||
output_links = [child_links[str(i)] for i in outputs[slot].get("linkIds", []) if str(i) in child_links]
|
||||
if len(output_links) != 1:
|
||||
return None
|
||||
return resolve(child, *output_links[0], prefix + [node_id], seen)
|
||||
execution_id = ":".join(prefix + [node_id])
|
||||
execution_node = prompt.get(execution_id)
|
||||
if isinstance(execution_node, dict) and execution_node.get("class_type") == kind:
|
||||
return [execution_id, slot]
|
||||
return None
|
||||
|
||||
result = {}
|
||||
for source in selector.get("inputs", []):
|
||||
name = source.get("name")
|
||||
link = links.get(str(source.get("link")))
|
||||
if name in ("input_a", "input_b") and link:
|
||||
resolved = resolve(graph, *link, path, set())
|
||||
if resolved is not None:
|
||||
result[name] = resolved
|
||||
return result
|
||||
|
||||
|
||||
def normalize_exclusive_prompt(data):
|
||||
"""Resolve flags before validation/cache keys, without changing workflow wires."""
|
||||
prompt = data.get("prompt", {})
|
||||
extra = data.get("extra_data", {}).get("extra_pnginfo")
|
||||
if not isinstance(prompt, dict):
|
||||
return data
|
||||
for node_id, node in prompt.items():
|
||||
if not isinstance(node, dict) or node.get("class_type") != "AdachiExclusiveSwitch":
|
||||
continue
|
||||
flags = _workflow_exclusive_flags(extra, node_id)
|
||||
if flags is None:
|
||||
continue
|
||||
inputs = node.setdefault("inputs", {})
|
||||
inputs["active_inputs"] = flags
|
||||
sources = _workflow_exclusive_sources(extra, node_id, prompt) if flags in (1, 2) else {}
|
||||
for name, bit in (("input_a", 1), ("input_b", 2)):
|
||||
if not flags & bit:
|
||||
inputs.pop(name, None)
|
||||
elif name not in inputs and name in sources:
|
||||
inputs[name] = sources[name]
|
||||
return normalize_crop_prompt(data)
|
||||
|
||||
|
||||
class AdachiExclusiveSwitch:
|
||||
"""Forward exactly one enabled branch, without evaluating the ignored branch."""
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"optional": {
|
||||
"input_a": ("*", {"lazy": True, "tooltip": "First branch; bypass either this branch or input_b."}),
|
||||
"input_b": ("*", {"lazy": True, "tooltip": "Second branch; exactly one branch must remain enabled."}),
|
||||
# The frontend computes this from the graph on every serialization.
|
||||
# Keeping it in the prompt also makes branch changes invalidate caches,
|
||||
# including bypassed transform nodes whose links otherwise pass through.
|
||||
"active_inputs": ("INT", {"default": -1, "min": -1, "max": 3}),
|
||||
},
|
||||
"hidden": {"prompt": "PROMPT", "dynprompt": "DYNPROMPT", "unique_id": "UNIQUE_ID", "extra_pnginfo": "EXTRA_PNGINFO"},
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("*",)
|
||||
RETURN_NAMES = ("output",)
|
||||
FUNCTION = "select"
|
||||
CATEGORY = CATEGORY
|
||||
DESCRIPTION = "Automatically forwards the only enabled input. Bypass one branch; both enabled or both absent is an error."
|
||||
SEARCH_ALIASES = ["exclusive switch", "auto switch", "自动二选一", "互斥", "自动切换", "adachi"]
|
||||
|
||||
@staticmethod
|
||||
def _selected_input(input_a, input_b, active_inputs, prompt=None, dynprompt=None, unique_id=None, extra_pnginfo=None):
|
||||
frontend_flags, submitted_flags = active_inputs, None
|
||||
workflow_flags = _workflow_exclusive_flags(extra_pnginfo, unique_id)
|
||||
if workflow_flags is not None:
|
||||
active_inputs = workflow_flags
|
||||
execution_node = None
|
||||
if dynprompt is not None and unique_id is not None:
|
||||
try:
|
||||
execution_node = dynprompt.get_node(unique_id)
|
||||
except KeyError:
|
||||
pass
|
||||
if execution_node is None and isinstance(prompt, dict) and unique_id is not None:
|
||||
execution_node = prompt.get(str(unique_id), prompt.get(unique_id))
|
||||
if isinstance(execution_node, dict) and isinstance(execution_node.get("inputs"), dict):
|
||||
# Get/Set and mute/bypass resolution may remove a connection after
|
||||
# widgets serialize. Trust the actual submitted connections when
|
||||
# only one (or none) survives, regardless of stale frontend flags.
|
||||
connected = execution_node["inputs"]
|
||||
actual = int("input_a" in connected) | (int("input_b" in connected) << 1)
|
||||
submitted_flags = actual
|
||||
if actual != 3:
|
||||
active_inputs = actual if workflow_flags is None else actual & workflow_flags
|
||||
if active_inputs == -1:
|
||||
# Raw API prompts need no frontend state: simply omit the unused input.
|
||||
active_inputs = int(input_a is not _MISSING_INPUT) | (int(input_b is not _MISSING_INPUT) << 1)
|
||||
if active_inputs not in (1, 2):
|
||||
raise ValueError(
|
||||
"Auto Exclusive Switch requires exactly one enabled input. "
|
||||
"Bypass one branch or disconnect it; both enabled / both absent are invalid. "
|
||||
f"Received enabled-state={active_inputs}. "
|
||||
f"node={unique_id}, frontend={frontend_flags}, workflow={workflow_flags}, submitted={submitted_flags}."
|
||||
)
|
||||
name = "input_a" if active_inputs == 1 else "input_b"
|
||||
if (input_a if active_inputs == 1 else input_b) is _MISSING_INPUT:
|
||||
raise ValueError(f"The enabled branch {name} has no input.")
|
||||
return name
|
||||
|
||||
def check_lazy_status(self, input_a=_MISSING_INPUT, input_b=_MISSING_INPUT, active_inputs=-1, prompt=None, dynprompt=None, unique_id=None, extra_pnginfo=None):
|
||||
return [self._selected_input(input_a, input_b, active_inputs, prompt, dynprompt, unique_id, extra_pnginfo)]
|
||||
|
||||
def select(self, input_a=_MISSING_INPUT, input_b=_MISSING_INPUT, active_inputs=-1, prompt=None, dynprompt=None, unique_id=None, extra_pnginfo=None):
|
||||
selected = self._selected_input(input_a, input_b, active_inputs, prompt, dynprompt, unique_id, extra_pnginfo)
|
||||
value = input_a if selected == "input_a" else input_b
|
||||
if value is None:
|
||||
raise ValueError(f"The enabled branch {selected} returned no data.")
|
||||
return (value,)
|
||||
|
||||
|
||||
def _crop_state(value):
|
||||
try:
|
||||
state = json.loads(value or "{}")
|
||||
except (ValueError, TypeError) as exc:
|
||||
raise ValueError("Invalid crop selection data.") from exc
|
||||
if not isinstance(state, dict):
|
||||
raise ValueError("Invalid crop selection data.")
|
||||
return state
|
||||
|
||||
|
||||
def _crop_box(state, image_width, image_height):
|
||||
values = [state.get(k) for k in ("x", "y", "width", "height")]
|
||||
if any(type(v) is not int for v in values):
|
||||
raise ValueError("Crop coordinates and dimensions must be integers.")
|
||||
x, y, width, height = values
|
||||
if min(width, height) < 32 or width % 32 or height % 32:
|
||||
raise ValueError("Crop width and height must be positive multiples of 32.")
|
||||
if x < 0 or y < 0 or x + width > image_width or y + height > image_height:
|
||||
raise ValueError("The crop must fit entirely inside the source image.")
|
||||
return x, y, width, height
|
||||
|
||||
|
||||
def _load_layer(filename):
|
||||
if not filename:
|
||||
return None
|
||||
raster = _read_raster(_input_path(filename)).convert("RGB")
|
||||
return torch.from_numpy(np.asarray(raster, dtype=np.float32).copy() / 255)[None]
|
||||
|
||||
|
||||
def _blend_layer(original, generated, blend_data, state):
|
||||
if generated is None:
|
||||
return original
|
||||
x, y, width, height = _crop_box(state, original.shape[2], original.shape[1])
|
||||
generated = _image_tensor(generated).to(device=original.device, dtype=original.dtype)
|
||||
if generated.shape[1:3] != (height, width):
|
||||
raise ValueError(f"Inpaint result must match the selected crop ({width} x {height}); connect the inpaint node's image output.")
|
||||
alpha = torch.ones((1, height, width, 1), device=original.device, dtype=original.dtype)
|
||||
if blend_data:
|
||||
raster = _data_image(blend_data).convert("L")
|
||||
if raster.size != (width, height):
|
||||
raise ValueError("The layer mask dimensions must match the crop.")
|
||||
alpha = torch.from_numpy(np.asarray(raster, dtype=np.float32).copy() / 255)[None, ..., None].to(original)
|
||||
composite = original.expand(generated.shape[0], -1, -1, -1).clone()
|
||||
old = composite[:, y:y+height, x:x+width]
|
||||
composite[:, y:y+height, x:x+width] = old * (1-alpha) + generated * alpha
|
||||
return composite
|
||||
|
||||
|
||||
def _store_layer(image):
|
||||
import folder_paths
|
||||
pixels = (image.detach().cpu().clamp(0, 1).numpy()*255).round().astype(np.uint8)
|
||||
name = f"layer-{hashlib.sha256(str(pixels.shape).encode() + pixels.tobytes()).hexdigest()}.png"
|
||||
folder = Path(folder_paths.get_input_directory()) / "adachi-inpaint-layers"
|
||||
folder.mkdir(parents=True, exist_ok=True)
|
||||
if not (folder / name).exists():
|
||||
# Readers never see an incomplete PNG when concurrent prompts reuse a layer.
|
||||
with tempfile.NamedTemporaryFile(dir=folder, suffix=".png", delete=False) as stream:
|
||||
temporary = Path(stream.name)
|
||||
try:
|
||||
Image.fromarray(pixels).save(temporary)
|
||||
temporary.replace(folder / name)
|
||||
finally:
|
||||
temporary.unlink(missing_ok=True)
|
||||
return {"filename": name, "subfolder": "adachi-inpaint-layers", "type": "input"}
|
||||
|
||||
|
||||
class AdachiLayerCommit:
|
||||
"""Execution-only sink; keeps the visible feedback loop acyclic at runtime."""
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {"required": {
|
||||
"result": ("IMAGE",), "image": ("STRING", {"default": ""}),
|
||||
"source_data": ("STRING", {"default": ""}), "crop_state": ("STRING", {"default": "{}"}),
|
||||
"blend_data": ("STRING", {"default": ""}), "target": ("STRING", {"default": ""}),
|
||||
}}
|
||||
RETURN_TYPES = ("IMAGE",)
|
||||
FUNCTION = "compose"
|
||||
OUTPUT_NODE = True
|
||||
CATEGORY = "_Adachi/internal"
|
||||
DESCRIPTION = "Internal layer sink. Use Inline Mask in Crop & Blend mode."
|
||||
|
||||
def compose(self, result, image="", source_data="", crop_state="{}", blend_data="", target=""):
|
||||
raster = (_data_image(source_data) if source_data else _read_raster(_input_path(image))).convert("RGB")
|
||||
original = torch.from_numpy(np.asarray(raster, dtype=np.float32).copy()/255)[None]
|
||||
state = _crop_state(crop_state)
|
||||
generated = _image_tensor(result).cpu()
|
||||
composite = _blend_layer(original, generated, blend_data, state)
|
||||
layer = _store_layer(generated[-1])
|
||||
return {"ui": {"adachi_layer": [{"target": target, "job": state.get("job", ""), "image": layer}]}, "result": (composite,)}
|
||||
|
||||
|
||||
def normalize_crop_prompt(data):
|
||||
"""Ignore obsolete feedback links; adoption now happens only in Image Compare."""
|
||||
prompt = data.get("prompt", {})
|
||||
if isinstance(prompt, dict):
|
||||
for node in prompt.values():
|
||||
if isinstance(node, dict) and node.get("class_type") == "AdachiInlineMask":
|
||||
node.setdefault("inputs", {}).pop("result", None)
|
||||
return data
|
||||
|
||||
|
||||
def _comparison_origin(prompt, unique_id, dynprompt=None):
|
||||
"""Tag previews with their generating crop, so later adoption cannot hit another region."""
|
||||
def get_node(node_id):
|
||||
if dynprompt is not None:
|
||||
try:
|
||||
return dynprompt.get_node(str(node_id))
|
||||
except KeyError:
|
||||
pass
|
||||
return prompt.get(str(node_id), prompt.get(node_id)) if isinstance(prompt, dict) else None
|
||||
node = get_node(unique_id)
|
||||
link = node.get("inputs", {}).get("original") if isinstance(node, dict) else None
|
||||
queue = [str(link[0])] if isinstance(link, list) and len(link) == 2 else []
|
||||
seen, sources = set(), {}
|
||||
while queue and len(seen) < 256:
|
||||
node_id = queue.pop()
|
||||
if node_id in seen:
|
||||
continue
|
||||
seen.add(node_id)
|
||||
current = get_node(node_id)
|
||||
if not isinstance(current, dict):
|
||||
continue
|
||||
inputs = current.get("inputs", {})
|
||||
if current.get("class_type") == "AdachiInlineMask":
|
||||
mode = inputs.get("edit_mode", "mask")
|
||||
state = _crop_state(inputs.get("crop_state", "{}")) if mode == "crop" else {}
|
||||
sources[node_id] = {"source": node_id, "mode": mode, "job": state.get("job", "")}
|
||||
continue
|
||||
for value in inputs.values():
|
||||
if isinstance(value, list) and len(value) == 2 and type(value[1]) is int:
|
||||
queue.append(str(value[0]))
|
||||
return next(iter(sources.values())) if len(sources) == 1 else None
|
||||
|
||||
|
||||
NODE_CLASS_MAPPINGS = {
|
||||
@@ -559,12 +1011,16 @@ NODE_CLASS_MAPPINGS = {
|
||||
"AdachiInpaintComposite": AdachiInpaintComposite,
|
||||
"AdachiWebUIInpaint": AdachiWebUIInpaint,
|
||||
"AdachiImageCompare": AdachiImageCompare,
|
||||
"AdachiExclusiveSwitch": AdachiExclusiveSwitch,
|
||||
"AdachiLayerCommit": AdachiLayerCommit,
|
||||
}
|
||||
|
||||
NODE_DISPLAY_NAME_MAPPINGS = {
|
||||
"AdachiInlineMask": "内联蒙版 / Inline Mask",
|
||||
"AdachiInpaintPrepare": "重绘预处理 / Inpaint Prepare",
|
||||
"AdachiInpaintComposite": "原图回贴 / Inpaint Composite",
|
||||
"AdachiWebUIInpaint": "WebUI 局部重绘 / WebUI Inpaint",
|
||||
"AdachiImageCompare": "图像对比 / Image Compare",
|
||||
"AdachiInlineMask": "Inline Mask",
|
||||
"AdachiInpaintPrepare": "Inpaint Prepare",
|
||||
"AdachiInpaintComposite": "Inpaint Composite",
|
||||
"AdachiWebUIInpaint": "WebUI Inpaint",
|
||||
"AdachiImageCompare": "Image Compare",
|
||||
"AdachiExclusiveSwitch": "Auto Exclusive Switch",
|
||||
"AdachiLayerCommit": "Internal Layer Commit",
|
||||
}
|
||||
|
||||
@@ -20,7 +20,6 @@
|
||||
"mode": 0,
|
||||
"inputs": [
|
||||
{
|
||||
"localized_name": "image",
|
||||
"name": "image",
|
||||
"type": "STRING",
|
||||
"widget": {
|
||||
@@ -29,7 +28,6 @@
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"localized_name": "mask_data",
|
||||
"name": "mask_data",
|
||||
"type": "STRING",
|
||||
"widget": {
|
||||
@@ -38,7 +36,6 @@
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"localized_name": "source_data",
|
||||
"name": "source_data",
|
||||
"type": "STRING",
|
||||
"widget": {
|
||||
@@ -49,7 +46,6 @@
|
||||
],
|
||||
"outputs": [
|
||||
{
|
||||
"localized_name": "image",
|
||||
"name": "image",
|
||||
"type": "IMAGE",
|
||||
"links": [
|
||||
@@ -58,7 +54,6 @@
|
||||
]
|
||||
},
|
||||
{
|
||||
"localized_name": "mask",
|
||||
"name": "mask",
|
||||
"type": "MASK",
|
||||
"links": [
|
||||
@@ -91,7 +86,6 @@
|
||||
"mode": 0,
|
||||
"inputs": [
|
||||
{
|
||||
"localized_name": "Checkpoint名称",
|
||||
"name": "ckpt_name",
|
||||
"type": "COMBO",
|
||||
"widget": {
|
||||
@@ -102,7 +96,6 @@
|
||||
],
|
||||
"outputs": [
|
||||
{
|
||||
"localized_name": "模型",
|
||||
"name": "MODEL",
|
||||
"type": "MODEL",
|
||||
"links": [
|
||||
@@ -110,7 +103,6 @@
|
||||
]
|
||||
},
|
||||
{
|
||||
"localized_name": "CLIP",
|
||||
"name": "CLIP",
|
||||
"type": "CLIP",
|
||||
"links": [
|
||||
@@ -119,7 +111,6 @@
|
||||
]
|
||||
},
|
||||
{
|
||||
"localized_name": "VAE",
|
||||
"name": "VAE",
|
||||
"type": "VAE",
|
||||
"links": [
|
||||
@@ -150,13 +141,11 @@
|
||||
"mode": 0,
|
||||
"inputs": [
|
||||
{
|
||||
"localized_name": "clip",
|
||||
"name": "clip",
|
||||
"type": "CLIP",
|
||||
"link": 1
|
||||
},
|
||||
{
|
||||
"localized_name": "文本",
|
||||
"name": "text",
|
||||
"type": "STRING",
|
||||
"widget": {
|
||||
@@ -167,7 +156,6 @@
|
||||
],
|
||||
"outputs": [
|
||||
{
|
||||
"localized_name": "条件",
|
||||
"name": "CONDITIONING",
|
||||
"type": "CONDITIONING",
|
||||
"links": [
|
||||
@@ -175,7 +163,7 @@
|
||||
]
|
||||
}
|
||||
],
|
||||
"title": "正面提示词 / Positive",
|
||||
"title": "Positive",
|
||||
"properties": {
|
||||
"Node name for S&R": "CLIPTextEncode"
|
||||
},
|
||||
@@ -199,13 +187,11 @@
|
||||
"mode": 0,
|
||||
"inputs": [
|
||||
{
|
||||
"localized_name": "clip",
|
||||
"name": "clip",
|
||||
"type": "CLIP",
|
||||
"link": 2
|
||||
},
|
||||
{
|
||||
"localized_name": "文本",
|
||||
"name": "text",
|
||||
"type": "STRING",
|
||||
"widget": {
|
||||
@@ -216,7 +202,6 @@
|
||||
],
|
||||
"outputs": [
|
||||
{
|
||||
"localized_name": "条件",
|
||||
"name": "CONDITIONING",
|
||||
"type": "CONDITIONING",
|
||||
"links": [
|
||||
@@ -224,7 +209,7 @@
|
||||
]
|
||||
}
|
||||
],
|
||||
"title": "负面提示词 / Negative",
|
||||
"title": "Negative",
|
||||
"properties": {
|
||||
"Node name for S&R": "CLIPTextEncode"
|
||||
},
|
||||
@@ -248,64 +233,54 @@
|
||||
"mode": 0,
|
||||
"inputs": [
|
||||
{
|
||||
"localized_name": "model",
|
||||
"name": "model",
|
||||
"type": "MODEL",
|
||||
"link": 3
|
||||
},
|
||||
{
|
||||
"localized_name": "positive",
|
||||
"name": "positive",
|
||||
"type": "CONDITIONING",
|
||||
"link": 5
|
||||
},
|
||||
{
|
||||
"localized_name": "negative",
|
||||
"name": "negative",
|
||||
"type": "CONDITIONING",
|
||||
"link": 6
|
||||
},
|
||||
{
|
||||
"localized_name": "vae",
|
||||
"name": "vae",
|
||||
"type": "VAE",
|
||||
"link": 4
|
||||
},
|
||||
{
|
||||
"localized_name": "image",
|
||||
"name": "image",
|
||||
"type": "IMAGE",
|
||||
"link": 7
|
||||
},
|
||||
{
|
||||
"localized_name": "mask",
|
||||
"name": "mask",
|
||||
"type": "MASK",
|
||||
"link": 8
|
||||
},
|
||||
{
|
||||
"localized_name": "refiner_model",
|
||||
"name": "refiner_model",
|
||||
"shape": 7,
|
||||
"type": "MODEL",
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"localized_name": "refiner_positive",
|
||||
"name": "refiner_positive",
|
||||
"shape": 7,
|
||||
"type": "CONDITIONING",
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"localized_name": "refiner_negative",
|
||||
"name": "refiner_negative",
|
||||
"shape": 7,
|
||||
"type": "CONDITIONING",
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"localized_name": "area",
|
||||
"name": "area",
|
||||
"type": "COMBO",
|
||||
"widget": {
|
||||
@@ -314,7 +289,6 @@
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"localized_name": "width",
|
||||
"name": "width",
|
||||
"type": "INT",
|
||||
"widget": {
|
||||
@@ -323,7 +297,6 @@
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"localized_name": "height",
|
||||
"name": "height",
|
||||
"type": "INT",
|
||||
"widget": {
|
||||
@@ -332,7 +305,6 @@
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"localized_name": "padding",
|
||||
"name": "padding",
|
||||
"type": "INT",
|
||||
"widget": {
|
||||
@@ -341,7 +313,6 @@
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"localized_name": "mask_blur",
|
||||
"name": "mask_blur",
|
||||
"type": "FLOAT",
|
||||
"widget": {
|
||||
@@ -350,7 +321,6 @@
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"localized_name": "mask_grow",
|
||||
"name": "mask_grow",
|
||||
"type": "INT",
|
||||
"widget": {
|
||||
@@ -359,7 +329,6 @@
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"localized_name": "mask_mode",
|
||||
"name": "mask_mode",
|
||||
"type": "COMBO",
|
||||
"widget": {
|
||||
@@ -368,7 +337,6 @@
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"localized_name": "fill",
|
||||
"name": "fill",
|
||||
"type": "COMBO",
|
||||
"widget": {
|
||||
@@ -377,7 +345,6 @@
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"localized_name": "resize_mode",
|
||||
"name": "resize_mode",
|
||||
"type": "COMBO",
|
||||
"widget": {
|
||||
@@ -386,7 +353,6 @@
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"localized_name": "seed",
|
||||
"name": "seed",
|
||||
"type": "INT",
|
||||
"widget": {
|
||||
@@ -395,7 +361,6 @@
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"localized_name": "steps",
|
||||
"name": "steps",
|
||||
"type": "INT",
|
||||
"widget": {
|
||||
@@ -404,7 +369,6 @@
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"localized_name": "cfg",
|
||||
"name": "cfg",
|
||||
"type": "FLOAT",
|
||||
"widget": {
|
||||
@@ -413,7 +377,6 @@
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"localized_name": "sampler_name",
|
||||
"name": "sampler_name",
|
||||
"type": "COMBO",
|
||||
"widget": {
|
||||
@@ -422,7 +385,6 @@
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"localized_name": "scheduler",
|
||||
"name": "scheduler",
|
||||
"type": "COMBO",
|
||||
"widget": {
|
||||
@@ -431,7 +393,6 @@
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"localized_name": "denoise",
|
||||
"name": "denoise",
|
||||
"type": "FLOAT",
|
||||
"widget": {
|
||||
@@ -440,7 +401,6 @@
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"localized_name": "batch_size",
|
||||
"name": "batch_size",
|
||||
"type": "INT",
|
||||
"widget": {
|
||||
@@ -449,7 +409,6 @@
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"localized_name": "refiner_switch",
|
||||
"name": "refiner_switch",
|
||||
"type": "FLOAT",
|
||||
"widget": {
|
||||
@@ -458,7 +417,6 @@
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"localized_name": "inpaint_model",
|
||||
"name": "inpaint_model",
|
||||
"shape": 7,
|
||||
"type": "BOOLEAN",
|
||||
@@ -468,7 +426,6 @@
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"localized_name": "soft_edge",
|
||||
"name": "soft_edge",
|
||||
"shape": 7,
|
||||
"type": "BOOLEAN",
|
||||
@@ -478,7 +435,6 @@
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"localized_name": "soft_strength",
|
||||
"name": "soft_strength",
|
||||
"shape": 7,
|
||||
"type": "FLOAT",
|
||||
@@ -490,7 +446,6 @@
|
||||
],
|
||||
"outputs": [
|
||||
{
|
||||
"localized_name": "image",
|
||||
"name": "image",
|
||||
"type": "IMAGE",
|
||||
"links": [
|
||||
@@ -498,13 +453,11 @@
|
||||
]
|
||||
},
|
||||
{
|
||||
"localized_name": "crop",
|
||||
"name": "crop",
|
||||
"type": "IMAGE",
|
||||
"links": null
|
||||
},
|
||||
{
|
||||
"localized_name": "mask",
|
||||
"name": "mask",
|
||||
"type": "MASK",
|
||||
"links": null
|
||||
@@ -553,13 +506,11 @@
|
||||
"mode": 0,
|
||||
"inputs": [
|
||||
{
|
||||
"localized_name": "original",
|
||||
"name": "original",
|
||||
"type": "IMAGE",
|
||||
"link": 9
|
||||
},
|
||||
{
|
||||
"localized_name": "result",
|
||||
"name": "result",
|
||||
"type": "IMAGE",
|
||||
"link": 10
|
||||
@@ -567,7 +518,6 @@
|
||||
],
|
||||
"outputs": [
|
||||
{
|
||||
"localized_name": "image",
|
||||
"name": "image",
|
||||
"type": "IMAGE",
|
||||
"links": [
|
||||
@@ -596,13 +546,11 @@
|
||||
"mode": 0,
|
||||
"inputs": [
|
||||
{
|
||||
"localized_name": "图片",
|
||||
"name": "images",
|
||||
"type": "IMAGE",
|
||||
"link": 11
|
||||
},
|
||||
{
|
||||
"localized_name": "文件名前缀",
|
||||
"name": "filename_prefix",
|
||||
"type": "STRING",
|
||||
"widget": {
|
||||
@@ -635,7 +583,7 @@
|
||||
"outputs": [],
|
||||
"properties": {},
|
||||
"widgets_values": [
|
||||
"安达工作台 / Adachi-Inpaint-Workbench\n1. 选择自己的 checkpoint 喵\n2. 在左侧节点载入原图并直接涂抹喵\n3. 在 WebUI 重绘节点中选择画笔并调整重绘参数喵\n4. width/height 是采样分辨率,最终 image 回贴为原图尺寸喵\n分享时在重绘节点勾选「原图嵌入工作流」喵"
|
||||
"Adachi-Inpaint-Workbench\n1. Pick your own checkpoint\n2. Load an image in the left node and paint directly on it\n3. Select the brush and adjust inpainting parameters in the WebUI Inpaint node\n4. width/height is the sampling resolution; the final image is composited back at the source size\nTick \"Embed source in workflow\" in the inpaint node before sharing"
|
||||
],
|
||||
"color": "#432",
|
||||
"bgcolor": "#653"
|
||||
@@ -743,4 +691,4 @@
|
||||
}
|
||||
},
|
||||
"version": 0.4
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,7 +20,6 @@
|
||||
"mode": 0,
|
||||
"inputs": [
|
||||
{
|
||||
"localized_name": "image",
|
||||
"name": "image",
|
||||
"type": "STRING",
|
||||
"widget": {
|
||||
@@ -29,7 +28,6 @@
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"localized_name": "mask_data",
|
||||
"name": "mask_data",
|
||||
"type": "STRING",
|
||||
"widget": {
|
||||
@@ -38,7 +36,6 @@
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"localized_name": "source_data",
|
||||
"name": "source_data",
|
||||
"type": "STRING",
|
||||
"widget": {
|
||||
@@ -49,7 +46,6 @@
|
||||
],
|
||||
"outputs": [
|
||||
{
|
||||
"localized_name": "image",
|
||||
"name": "image",
|
||||
"type": "IMAGE",
|
||||
"links": [
|
||||
@@ -58,7 +54,6 @@
|
||||
]
|
||||
},
|
||||
{
|
||||
"localized_name": "mask",
|
||||
"name": "mask",
|
||||
"type": "MASK",
|
||||
"links": [
|
||||
@@ -91,7 +86,6 @@
|
||||
"mode": 0,
|
||||
"inputs": [
|
||||
{
|
||||
"localized_name": "Checkpoint名称",
|
||||
"name": "ckpt_name",
|
||||
"type": "COMBO",
|
||||
"widget": {
|
||||
@@ -102,7 +96,6 @@
|
||||
],
|
||||
"outputs": [
|
||||
{
|
||||
"localized_name": "模型",
|
||||
"name": "MODEL",
|
||||
"type": "MODEL",
|
||||
"links": [
|
||||
@@ -110,7 +103,6 @@
|
||||
]
|
||||
},
|
||||
{
|
||||
"localized_name": "CLIP",
|
||||
"name": "CLIP",
|
||||
"type": "CLIP",
|
||||
"links": [
|
||||
@@ -119,7 +111,6 @@
|
||||
]
|
||||
},
|
||||
{
|
||||
"localized_name": "VAE",
|
||||
"name": "VAE",
|
||||
"type": "VAE",
|
||||
"links": [
|
||||
@@ -151,13 +142,11 @@
|
||||
"mode": 0,
|
||||
"inputs": [
|
||||
{
|
||||
"localized_name": "clip",
|
||||
"name": "clip",
|
||||
"type": "CLIP",
|
||||
"link": 1
|
||||
},
|
||||
{
|
||||
"localized_name": "文本",
|
||||
"name": "text",
|
||||
"type": "STRING",
|
||||
"widget": {
|
||||
@@ -168,7 +157,6 @@
|
||||
],
|
||||
"outputs": [
|
||||
{
|
||||
"localized_name": "条件",
|
||||
"name": "CONDITIONING",
|
||||
"type": "CONDITIONING",
|
||||
"links": [
|
||||
@@ -176,7 +164,7 @@
|
||||
]
|
||||
}
|
||||
],
|
||||
"title": "正面提示词 / Positive",
|
||||
"title": "Positive",
|
||||
"properties": {
|
||||
"Node name for S&R": "CLIPTextEncode"
|
||||
},
|
||||
@@ -200,13 +188,11 @@
|
||||
"mode": 0,
|
||||
"inputs": [
|
||||
{
|
||||
"localized_name": "clip",
|
||||
"name": "clip",
|
||||
"type": "CLIP",
|
||||
"link": 2
|
||||
},
|
||||
{
|
||||
"localized_name": "文本",
|
||||
"name": "text",
|
||||
"type": "STRING",
|
||||
"widget": {
|
||||
@@ -217,7 +203,6 @@
|
||||
],
|
||||
"outputs": [
|
||||
{
|
||||
"localized_name": "条件",
|
||||
"name": "CONDITIONING",
|
||||
"type": "CONDITIONING",
|
||||
"links": [
|
||||
@@ -225,7 +210,7 @@
|
||||
]
|
||||
}
|
||||
],
|
||||
"title": "负面提示词 / Negative",
|
||||
"title": "Negative",
|
||||
"properties": {
|
||||
"Node name for S&R": "CLIPTextEncode"
|
||||
},
|
||||
@@ -249,19 +234,16 @@
|
||||
"mode": 0,
|
||||
"inputs": [
|
||||
{
|
||||
"localized_name": "image",
|
||||
"name": "image",
|
||||
"type": "IMAGE",
|
||||
"link": 3
|
||||
},
|
||||
{
|
||||
"localized_name": "mask",
|
||||
"name": "mask",
|
||||
"type": "MASK",
|
||||
"link": 4
|
||||
},
|
||||
{
|
||||
"localized_name": "area",
|
||||
"name": "area",
|
||||
"type": "COMBO",
|
||||
"widget": {
|
||||
@@ -270,7 +252,6 @@
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"localized_name": "width",
|
||||
"name": "width",
|
||||
"type": "INT",
|
||||
"widget": {
|
||||
@@ -279,7 +260,6 @@
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"localized_name": "height",
|
||||
"name": "height",
|
||||
"type": "INT",
|
||||
"widget": {
|
||||
@@ -288,7 +268,6 @@
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"localized_name": "padding",
|
||||
"name": "padding",
|
||||
"type": "INT",
|
||||
"widget": {
|
||||
@@ -297,7 +276,6 @@
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"localized_name": "mask_blur",
|
||||
"name": "mask_blur",
|
||||
"type": "FLOAT",
|
||||
"widget": {
|
||||
@@ -306,7 +284,6 @@
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"localized_name": "mask_grow",
|
||||
"name": "mask_grow",
|
||||
"type": "INT",
|
||||
"widget": {
|
||||
@@ -315,7 +292,6 @@
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"localized_name": "mask_mode",
|
||||
"name": "mask_mode",
|
||||
"type": "COMBO",
|
||||
"widget": {
|
||||
@@ -324,7 +300,6 @@
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"localized_name": "fill",
|
||||
"name": "fill",
|
||||
"type": "COMBO",
|
||||
"widget": {
|
||||
@@ -333,7 +308,6 @@
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"localized_name": "resize_mode",
|
||||
"name": "resize_mode",
|
||||
"type": "COMBO",
|
||||
"widget": {
|
||||
@@ -342,7 +316,6 @@
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"localized_name": "soft_edge",
|
||||
"name": "soft_edge",
|
||||
"shape": 7,
|
||||
"type": "BOOLEAN",
|
||||
@@ -352,7 +325,6 @@
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"localized_name": "soft_strength",
|
||||
"name": "soft_strength",
|
||||
"shape": 7,
|
||||
"type": "FLOAT",
|
||||
@@ -364,7 +336,6 @@
|
||||
],
|
||||
"outputs": [
|
||||
{
|
||||
"localized_name": "pixels",
|
||||
"name": "pixels",
|
||||
"type": "IMAGE",
|
||||
"links": [
|
||||
@@ -372,7 +343,6 @@
|
||||
]
|
||||
},
|
||||
{
|
||||
"localized_name": "mask",
|
||||
"name": "mask",
|
||||
"type": "MASK",
|
||||
"links": [
|
||||
@@ -380,7 +350,6 @@
|
||||
]
|
||||
},
|
||||
{
|
||||
"localized_name": "context",
|
||||
"name": "context",
|
||||
"type": "ADACHI_INPAINT_CONTEXT",
|
||||
"links": [
|
||||
@@ -421,13 +390,11 @@
|
||||
"mode": 0,
|
||||
"inputs": [
|
||||
{
|
||||
"localized_name": "像素",
|
||||
"name": "pixels",
|
||||
"type": "IMAGE",
|
||||
"link": 5
|
||||
},
|
||||
{
|
||||
"localized_name": "vae",
|
||||
"name": "vae",
|
||||
"type": "VAE",
|
||||
"link": 6
|
||||
@@ -435,7 +402,6 @@
|
||||
],
|
||||
"outputs": [
|
||||
{
|
||||
"localized_name": "Latent",
|
||||
"name": "LATENT",
|
||||
"type": "LATENT",
|
||||
"links": [
|
||||
@@ -464,13 +430,11 @@
|
||||
"mode": 0,
|
||||
"inputs": [
|
||||
{
|
||||
"localized_name": "Latent",
|
||||
"name": "samples",
|
||||
"type": "LATENT",
|
||||
"link": 7
|
||||
},
|
||||
{
|
||||
"localized_name": "遮罩",
|
||||
"name": "mask",
|
||||
"type": "MASK",
|
||||
"link": 8
|
||||
@@ -478,7 +442,6 @@
|
||||
],
|
||||
"outputs": [
|
||||
{
|
||||
"localized_name": "Latent",
|
||||
"name": "LATENT",
|
||||
"type": "LATENT",
|
||||
"links": [
|
||||
@@ -507,31 +470,26 @@
|
||||
"mode": 0,
|
||||
"inputs": [
|
||||
{
|
||||
"localized_name": "模型",
|
||||
"name": "model",
|
||||
"type": "MODEL",
|
||||
"link": 9
|
||||
},
|
||||
{
|
||||
"localized_name": "正面条件",
|
||||
"name": "positive",
|
||||
"type": "CONDITIONING",
|
||||
"link": 10
|
||||
},
|
||||
{
|
||||
"localized_name": "负面条件",
|
||||
"name": "negative",
|
||||
"type": "CONDITIONING",
|
||||
"link": 11
|
||||
},
|
||||
{
|
||||
"localized_name": "Latent图像",
|
||||
"name": "latent_image",
|
||||
"type": "LATENT",
|
||||
"link": 12
|
||||
},
|
||||
{
|
||||
"localized_name": "种子",
|
||||
"name": "seed",
|
||||
"type": "INT",
|
||||
"widget": {
|
||||
@@ -540,7 +498,6 @@
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"localized_name": "步数",
|
||||
"name": "steps",
|
||||
"type": "INT",
|
||||
"widget": {
|
||||
@@ -549,7 +506,6 @@
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"localized_name": "cfg",
|
||||
"name": "cfg",
|
||||
"type": "FLOAT",
|
||||
"widget": {
|
||||
@@ -558,7 +514,6 @@
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"localized_name": "采样器名称",
|
||||
"name": "sampler_name",
|
||||
"type": "COMBO",
|
||||
"widget": {
|
||||
@@ -567,7 +522,6 @@
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"localized_name": "调度器",
|
||||
"name": "scheduler",
|
||||
"type": "COMBO",
|
||||
"widget": {
|
||||
@@ -576,7 +530,6 @@
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"localized_name": "降噪",
|
||||
"name": "denoise",
|
||||
"type": "FLOAT",
|
||||
"widget": {
|
||||
@@ -587,7 +540,6 @@
|
||||
],
|
||||
"outputs": [
|
||||
{
|
||||
"localized_name": "Latent",
|
||||
"name": "LATENT",
|
||||
"type": "LATENT",
|
||||
"links": [
|
||||
@@ -624,13 +576,11 @@
|
||||
"mode": 0,
|
||||
"inputs": [
|
||||
{
|
||||
"localized_name": "Latent",
|
||||
"name": "samples",
|
||||
"type": "LATENT",
|
||||
"link": 13
|
||||
},
|
||||
{
|
||||
"localized_name": "vae",
|
||||
"name": "vae",
|
||||
"type": "VAE",
|
||||
"link": 14
|
||||
@@ -638,7 +588,6 @@
|
||||
],
|
||||
"outputs": [
|
||||
{
|
||||
"localized_name": "图像",
|
||||
"name": "IMAGE",
|
||||
"type": "IMAGE",
|
||||
"links": [
|
||||
@@ -667,13 +616,11 @@
|
||||
"mode": 0,
|
||||
"inputs": [
|
||||
{
|
||||
"localized_name": "generated",
|
||||
"name": "generated",
|
||||
"type": "IMAGE",
|
||||
"link": 15
|
||||
},
|
||||
{
|
||||
"localized_name": "context",
|
||||
"name": "context",
|
||||
"type": "ADACHI_INPAINT_CONTEXT",
|
||||
"link": 16
|
||||
@@ -681,7 +628,6 @@
|
||||
],
|
||||
"outputs": [
|
||||
{
|
||||
"localized_name": "image",
|
||||
"name": "image",
|
||||
"type": "IMAGE",
|
||||
"links": [
|
||||
@@ -710,13 +656,11 @@
|
||||
"mode": 0,
|
||||
"inputs": [
|
||||
{
|
||||
"localized_name": "original",
|
||||
"name": "original",
|
||||
"type": "IMAGE",
|
||||
"link": 17
|
||||
},
|
||||
{
|
||||
"localized_name": "result",
|
||||
"name": "result",
|
||||
"type": "IMAGE",
|
||||
"link": 18
|
||||
@@ -724,7 +668,6 @@
|
||||
],
|
||||
"outputs": [
|
||||
{
|
||||
"localized_name": "image",
|
||||
"name": "image",
|
||||
"type": "IMAGE",
|
||||
"links": [
|
||||
@@ -753,13 +696,11 @@
|
||||
"mode": 0,
|
||||
"inputs": [
|
||||
{
|
||||
"localized_name": "图片",
|
||||
"name": "images",
|
||||
"type": "IMAGE",
|
||||
"link": 19
|
||||
},
|
||||
{
|
||||
"localized_name": "文件名前缀",
|
||||
"name": "filename_prefix",
|
||||
"type": "STRING",
|
||||
"widget": {
|
||||
@@ -792,7 +733,7 @@
|
||||
"outputs": [],
|
||||
"properties": {},
|
||||
"widgets_values": [
|
||||
"安达工作台 / Adachi-Inpaint-Workbench — 标准节点组合\n选择模型,载入原图并涂抹,然后运行喵\nPrepare → VAE Encode → Set Latent Noise Mask → KSampler → VAE Decode → Composite 喵\n独立 Prepare 的 fill 请选择 original 或 fill 喵\nlatent_noise / latent_nothing 由一体采样节点实现,独立预处理不修改 latent 喵\n使用专用 inpaint checkpoint 时请改用原生 InpaintModelConditioning 或一体节点 inpaint_model 喵"
|
||||
"Adachi-Inpaint-Workbench - standard node combination\nPick a model, load an image, paint, then run\nPrepare -> VAE Encode -> Set Latent Noise Mask -> KSampler -> VAE Decode -> Composite\nFor standalone Prepare, choose fill = original or fill\nlatent_noise / latent_nothing are implemented by the all-in-one sampler; standalone Prepare does not touch the latent\nWith a dedicated inpaint checkpoint, use native InpaintModelConditioning or the all-in-one node's inpaint_model"
|
||||
],
|
||||
"color": "#432",
|
||||
"bgcolor": "#653"
|
||||
@@ -964,4 +905,4 @@
|
||||
}
|
||||
},
|
||||
"version": 0.4
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,335 @@
|
||||
{
|
||||
"id": "00000000-0000-0000-0000-000000000000",
|
||||
"revision": 0,
|
||||
"last_node_id": 6,
|
||||
"last_link_id": 3,
|
||||
"nodes": [
|
||||
{
|
||||
"id": 1,
|
||||
"type": "EmptyImage",
|
||||
"pos": [
|
||||
-350,
|
||||
140
|
||||
],
|
||||
"size": [
|
||||
270,
|
||||
160
|
||||
],
|
||||
"flags": {},
|
||||
"order": 0,
|
||||
"mode": 0,
|
||||
"inputs": [
|
||||
{
|
||||
"name": "width",
|
||||
"type": "INT",
|
||||
"widget": {
|
||||
"name": "width"
|
||||
},
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"name": "height",
|
||||
"type": "INT",
|
||||
"widget": {
|
||||
"name": "height"
|
||||
},
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"name": "batch_size",
|
||||
"type": "INT",
|
||||
"widget": {
|
||||
"name": "batch_size"
|
||||
},
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"name": "color",
|
||||
"type": "INT",
|
||||
"widget": {
|
||||
"name": "color"
|
||||
},
|
||||
"link": null
|
||||
}
|
||||
],
|
||||
"outputs": [
|
||||
{
|
||||
"name": "IMAGE",
|
||||
"type": "IMAGE",
|
||||
"links": [
|
||||
1
|
||||
]
|
||||
}
|
||||
],
|
||||
"properties": {
|
||||
"Node name for S&R": "EmptyImage"
|
||||
},
|
||||
"widgets_values": [
|
||||
512,
|
||||
512,
|
||||
1,
|
||||
8096934
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"type": "ImageInvert",
|
||||
"pos": [
|
||||
120,
|
||||
160
|
||||
],
|
||||
"size": [
|
||||
225,
|
||||
48
|
||||
],
|
||||
"flags": {},
|
||||
"order": 3,
|
||||
"mode": 0,
|
||||
"inputs": [
|
||||
{
|
||||
"name": "image",
|
||||
"type": "IMAGE",
|
||||
"link": 1
|
||||
}
|
||||
],
|
||||
"outputs": [
|
||||
{
|
||||
"name": "IMAGE",
|
||||
"type": "IMAGE",
|
||||
"links": [
|
||||
2
|
||||
]
|
||||
}
|
||||
],
|
||||
"properties": {
|
||||
"Node name for S&R": "ImageInvert"
|
||||
},
|
||||
"widgets_values": []
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"type": "ImageInvert",
|
||||
"pos": [
|
||||
510,
|
||||
160
|
||||
],
|
||||
"size": [
|
||||
225,
|
||||
48
|
||||
],
|
||||
"flags": {},
|
||||
"order": 4,
|
||||
"mode": 0,
|
||||
"inputs": [
|
||||
{
|
||||
"name": "image",
|
||||
"type": "IMAGE",
|
||||
"link": 2
|
||||
}
|
||||
],
|
||||
"outputs": [
|
||||
{
|
||||
"name": "IMAGE",
|
||||
"type": "IMAGE",
|
||||
"links": [
|
||||
3
|
||||
]
|
||||
}
|
||||
],
|
||||
"properties": {
|
||||
"Node name for S&R": "ImageInvert"
|
||||
},
|
||||
"widgets_values": []
|
||||
},
|
||||
{
|
||||
"id": 4,
|
||||
"type": "SaveImage",
|
||||
"pos": [
|
||||
920,
|
||||
140
|
||||
],
|
||||
"size": [
|
||||
270,
|
||||
76
|
||||
],
|
||||
"flags": {},
|
||||
"order": 5,
|
||||
"mode": 0,
|
||||
"inputs": [
|
||||
{
|
||||
"name": "images",
|
||||
"type": "IMAGE",
|
||||
"link": 3
|
||||
},
|
||||
{
|
||||
"name": "filename_prefix",
|
||||
"type": "STRING",
|
||||
"widget": {
|
||||
"name": "filename_prefix"
|
||||
},
|
||||
"link": null
|
||||
}
|
||||
],
|
||||
"outputs": [],
|
||||
"properties": {},
|
||||
"widgets_values": [
|
||||
"Adachi/GroupPresetExample"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 5,
|
||||
"type": "AdachiGroupPresets",
|
||||
"pos": [
|
||||
80,
|
||||
440
|
||||
],
|
||||
"size": [
|
||||
620,
|
||||
410
|
||||
],
|
||||
"flags": {},
|
||||
"order": 1,
|
||||
"mode": 0,
|
||||
"inputs": [],
|
||||
"outputs": [],
|
||||
"properties": {
|
||||
"adachi_group_presets": {
|
||||
"version": 1,
|
||||
"activeId": "01dbf1d1-c15a-4db1-97d5-9d522781c482",
|
||||
"presets": [
|
||||
{
|
||||
"id": "01dbf1d1-c15a-4db1-97d5-9d522781c482",
|
||||
"name": "All enabled",
|
||||
"groups": {
|
||||
"group:1": {
|
||||
"title": "Base",
|
||||
"mode": 0
|
||||
},
|
||||
"group:2": {
|
||||
"title": "Detail",
|
||||
"mode": 0
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "fe43bc1f-1a1e-4f49-a37b-c6e6ca7cbc8a",
|
||||
"name": "Skip detail",
|
||||
"groups": {
|
||||
"group:1": {
|
||||
"title": "Base",
|
||||
"mode": 0
|
||||
},
|
||||
"group:2": {
|
||||
"title": "Detail",
|
||||
"mode": 4
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "b881a666-4643-4af6-8feb-f1d02c47f113",
|
||||
"name": "Bypass both",
|
||||
"groups": {
|
||||
"group:1": {
|
||||
"title": "Base",
|
||||
"mode": 4
|
||||
},
|
||||
"group:2": {
|
||||
"title": "Detail",
|
||||
"mode": 4
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 6,
|
||||
"type": "Note",
|
||||
"pos": [
|
||||
820,
|
||||
550
|
||||
],
|
||||
"size": [
|
||||
350,
|
||||
180
|
||||
],
|
||||
"flags": {},
|
||||
"order": 2,
|
||||
"mode": 0,
|
||||
"inputs": [],
|
||||
"outputs": [],
|
||||
"properties": {},
|
||||
"widgets_values": [
|
||||
"Adachi-Inpaint-Workbench - Group Bypass Presets\nSelect a preset on the left to switch a whole group between enabled and bypassed; no connections required\nAdjust each group's state on the right, or click \"Save current group states\" to store the current workflow\nRight-click the node -> Apply preset to switch quickly\nThis example only inverts an image, so no model is needed"
|
||||
],
|
||||
"color": "#432",
|
||||
"bgcolor": "#653"
|
||||
}
|
||||
],
|
||||
"links": [
|
||||
[
|
||||
1,
|
||||
1,
|
||||
0,
|
||||
2,
|
||||
0,
|
||||
"IMAGE"
|
||||
],
|
||||
[
|
||||
2,
|
||||
2,
|
||||
0,
|
||||
3,
|
||||
0,
|
||||
"IMAGE"
|
||||
],
|
||||
[
|
||||
3,
|
||||
3,
|
||||
0,
|
||||
4,
|
||||
0,
|
||||
"IMAGE"
|
||||
]
|
||||
],
|
||||
"groups": [
|
||||
{
|
||||
"id": 1,
|
||||
"title": "Base",
|
||||
"bounding": [
|
||||
80,
|
||||
100,
|
||||
300,
|
||||
230
|
||||
],
|
||||
"color": "#3f789e",
|
||||
"font_size": 24,
|
||||
"flags": {}
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"title": "Detail",
|
||||
"bounding": [
|
||||
470,
|
||||
100,
|
||||
300,
|
||||
230
|
||||
],
|
||||
"color": "#3f789e",
|
||||
"font_size": 24,
|
||||
"flags": {}
|
||||
}
|
||||
],
|
||||
"config": {},
|
||||
"extra": {
|
||||
"ds": {
|
||||
"scale": 1,
|
||||
"offset": [
|
||||
0,
|
||||
0
|
||||
]
|
||||
}
|
||||
},
|
||||
"version": 0.4
|
||||
}
|
||||
@@ -0,0 +1,423 @@
|
||||
{
|
||||
"id": "00000000-0000-0000-0000-000000000000",
|
||||
"revision": 0,
|
||||
"last_node_id": 7,
|
||||
"last_link_id": 5,
|
||||
"nodes": [
|
||||
{
|
||||
"id": 1,
|
||||
"type": "EmptyImage",
|
||||
"pos": [
|
||||
0,
|
||||
120
|
||||
],
|
||||
"size": [
|
||||
270,
|
||||
130
|
||||
],
|
||||
"flags": {},
|
||||
"order": 0,
|
||||
"mode": 0,
|
||||
"inputs": [
|
||||
{
|
||||
"name": "width",
|
||||
"type": "INT",
|
||||
"widget": {
|
||||
"name": "width"
|
||||
},
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"name": "height",
|
||||
"type": "INT",
|
||||
"widget": {
|
||||
"name": "height"
|
||||
},
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"name": "batch_size",
|
||||
"type": "INT",
|
||||
"widget": {
|
||||
"name": "batch_size"
|
||||
},
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"name": "color",
|
||||
"type": "INT",
|
||||
"widget": {
|
||||
"name": "color"
|
||||
},
|
||||
"link": null
|
||||
}
|
||||
],
|
||||
"outputs": [
|
||||
{
|
||||
"name": "IMAGE",
|
||||
"type": "IMAGE",
|
||||
"links": [
|
||||
1
|
||||
]
|
||||
}
|
||||
],
|
||||
"properties": {
|
||||
"Node name for S&R": "EmptyImage"
|
||||
},
|
||||
"widgets_values": [
|
||||
64,
|
||||
64,
|
||||
1,
|
||||
16711680
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"type": "EmptyImage",
|
||||
"pos": [
|
||||
0,
|
||||
450
|
||||
],
|
||||
"size": [
|
||||
270,
|
||||
130
|
||||
],
|
||||
"flags": {},
|
||||
"order": 1,
|
||||
"mode": 0,
|
||||
"inputs": [
|
||||
{
|
||||
"name": "width",
|
||||
"type": "INT",
|
||||
"widget": {
|
||||
"name": "width"
|
||||
},
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"name": "height",
|
||||
"type": "INT",
|
||||
"widget": {
|
||||
"name": "height"
|
||||
},
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"name": "batch_size",
|
||||
"type": "INT",
|
||||
"widget": {
|
||||
"name": "batch_size"
|
||||
},
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"name": "color",
|
||||
"type": "INT",
|
||||
"widget": {
|
||||
"name": "color"
|
||||
},
|
||||
"link": null
|
||||
}
|
||||
],
|
||||
"outputs": [
|
||||
{
|
||||
"name": "IMAGE",
|
||||
"type": "IMAGE",
|
||||
"links": [
|
||||
2
|
||||
]
|
||||
}
|
||||
],
|
||||
"properties": {
|
||||
"Node name for S&R": "EmptyImage"
|
||||
},
|
||||
"widgets_values": [
|
||||
64,
|
||||
64,
|
||||
1,
|
||||
255
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"type": "ImageInvert",
|
||||
"pos": [
|
||||
300,
|
||||
120
|
||||
],
|
||||
"size": [
|
||||
140,
|
||||
26
|
||||
],
|
||||
"flags": {},
|
||||
"order": 3,
|
||||
"mode": 4,
|
||||
"inputs": [
|
||||
{
|
||||
"name": "image",
|
||||
"type": "IMAGE",
|
||||
"link": 1
|
||||
}
|
||||
],
|
||||
"outputs": [
|
||||
{
|
||||
"name": "IMAGE",
|
||||
"type": "IMAGE",
|
||||
"links": [
|
||||
3
|
||||
]
|
||||
}
|
||||
],
|
||||
"properties": {
|
||||
"Node name for S&R": "ImageInvert"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 4,
|
||||
"type": "ImageInvert",
|
||||
"pos": [
|
||||
300,
|
||||
450
|
||||
],
|
||||
"size": [
|
||||
140,
|
||||
26
|
||||
],
|
||||
"flags": {},
|
||||
"order": 4,
|
||||
"mode": 0,
|
||||
"inputs": [
|
||||
{
|
||||
"name": "image",
|
||||
"type": "IMAGE",
|
||||
"link": 2
|
||||
}
|
||||
],
|
||||
"outputs": [
|
||||
{
|
||||
"name": "IMAGE",
|
||||
"type": "IMAGE",
|
||||
"links": [
|
||||
4
|
||||
]
|
||||
}
|
||||
],
|
||||
"properties": {
|
||||
"Node name for S&R": "ImageInvert"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 5,
|
||||
"type": "AdachiExclusiveSwitch",
|
||||
"pos": [
|
||||
620,
|
||||
200
|
||||
],
|
||||
"size": [
|
||||
230,
|
||||
80
|
||||
],
|
||||
"flags": {},
|
||||
"order": 5,
|
||||
"mode": 0,
|
||||
"inputs": [
|
||||
{
|
||||
"name": "input_a",
|
||||
"shape": 7,
|
||||
"type": "*",
|
||||
"link": 3
|
||||
},
|
||||
{
|
||||
"name": "input_b",
|
||||
"shape": 7,
|
||||
"type": "*",
|
||||
"link": 4
|
||||
}
|
||||
],
|
||||
"outputs": [
|
||||
{
|
||||
"name": "output",
|
||||
"type": "*",
|
||||
"links": [
|
||||
5
|
||||
]
|
||||
}
|
||||
],
|
||||
"properties": {
|
||||
"Node name for S&R": "AdachiExclusiveSwitch"
|
||||
},
|
||||
"widgets_values": [
|
||||
-1
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 6,
|
||||
"type": "SaveImage",
|
||||
"pos": [
|
||||
940,
|
||||
200
|
||||
],
|
||||
"size": [
|
||||
270,
|
||||
58
|
||||
],
|
||||
"flags": {},
|
||||
"order": 6,
|
||||
"mode": 0,
|
||||
"inputs": [
|
||||
{
|
||||
"name": "images",
|
||||
"type": "IMAGE",
|
||||
"link": 5
|
||||
},
|
||||
{
|
||||
"name": "filename_prefix",
|
||||
"type": "STRING",
|
||||
"widget": {
|
||||
"name": "filename_prefix"
|
||||
},
|
||||
"link": null
|
||||
}
|
||||
],
|
||||
"outputs": [],
|
||||
"properties": {},
|
||||
"widgets_values": [
|
||||
"exclusive-test"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 7,
|
||||
"type": "AdachiGroupPresets",
|
||||
"pos": [
|
||||
600,
|
||||
430
|
||||
],
|
||||
"size": [
|
||||
620,
|
||||
410
|
||||
],
|
||||
"flags": {},
|
||||
"order": 2,
|
||||
"mode": 0,
|
||||
"inputs": [],
|
||||
"outputs": [],
|
||||
"properties": {
|
||||
"adachi_group_presets": {
|
||||
"version": 1,
|
||||
"activeId": "2908ca1a-7a3f-4eba-8203-524ab3f52d27",
|
||||
"presets": [
|
||||
{
|
||||
"id": "dd436f10-d4a4-46bc-aecb-fe185710f6e0",
|
||||
"name": "Use A only",
|
||||
"groups": {
|
||||
"group:1": {
|
||||
"title": "A",
|
||||
"mode": 0
|
||||
},
|
||||
"group:2": {
|
||||
"title": "B",
|
||||
"mode": 4
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "2908ca1a-7a3f-4eba-8203-524ab3f52d27",
|
||||
"name": "Use B only",
|
||||
"groups": {
|
||||
"group:1": {
|
||||
"title": "A",
|
||||
"mode": 4
|
||||
},
|
||||
"group:2": {
|
||||
"title": "B",
|
||||
"mode": 0
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
"links": [
|
||||
[
|
||||
1,
|
||||
1,
|
||||
0,
|
||||
3,
|
||||
0,
|
||||
"IMAGE"
|
||||
],
|
||||
[
|
||||
2,
|
||||
2,
|
||||
0,
|
||||
4,
|
||||
0,
|
||||
"IMAGE"
|
||||
],
|
||||
[
|
||||
3,
|
||||
3,
|
||||
0,
|
||||
5,
|
||||
0,
|
||||
"IMAGE"
|
||||
],
|
||||
[
|
||||
4,
|
||||
4,
|
||||
0,
|
||||
5,
|
||||
1,
|
||||
"IMAGE"
|
||||
],
|
||||
[
|
||||
5,
|
||||
5,
|
||||
0,
|
||||
6,
|
||||
0,
|
||||
"IMAGE"
|
||||
]
|
||||
],
|
||||
"groups": [
|
||||
{
|
||||
"id": 1,
|
||||
"title": "A",
|
||||
"bounding": [
|
||||
270,
|
||||
70,
|
||||
310,
|
||||
210
|
||||
],
|
||||
"color": "#3f789e",
|
||||
"font_size": 24,
|
||||
"flags": {}
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"title": "B",
|
||||
"bounding": [
|
||||
270,
|
||||
400,
|
||||
310,
|
||||
210
|
||||
],
|
||||
"color": "#3f789e",
|
||||
"font_size": 24,
|
||||
"flags": {}
|
||||
}
|
||||
],
|
||||
"config": {},
|
||||
"extra": {
|
||||
"ds": {
|
||||
"scale": 0.8,
|
||||
"offset": [
|
||||
100,
|
||||
20
|
||||
]
|
||||
}
|
||||
},
|
||||
"version": 0.4
|
||||
}
|
||||
@@ -0,0 +1,787 @@
|
||||
{
|
||||
"id": "58f1c513-1df0-4f53-af63-69da48ad43f0",
|
||||
"revision": 0,
|
||||
"last_node_id": 8,
|
||||
"last_link_id": 15,
|
||||
"nodes": [
|
||||
{
|
||||
"id": 1,
|
||||
"type": "AdachiInlineMask",
|
||||
"pos": [
|
||||
40,
|
||||
100
|
||||
],
|
||||
"size": [
|
||||
540,
|
||||
820
|
||||
],
|
||||
"flags": {},
|
||||
"order": 0,
|
||||
"mode": 0,
|
||||
"inputs": [
|
||||
{
|
||||
"name": "image",
|
||||
"type": "STRING",
|
||||
"widget": {
|
||||
"name": "image"
|
||||
},
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"name": "mask_data",
|
||||
"type": "STRING",
|
||||
"widget": {
|
||||
"name": "mask_data"
|
||||
},
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"name": "source_data",
|
||||
"type": "STRING",
|
||||
"widget": {
|
||||
"name": "source_data"
|
||||
},
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"name": "edit_mode",
|
||||
"shape": 7,
|
||||
"type": "COMBO",
|
||||
"widget": {
|
||||
"name": "edit_mode"
|
||||
},
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"name": "crop_state",
|
||||
"shape": 7,
|
||||
"type": "STRING",
|
||||
"widget": {
|
||||
"name": "crop_state"
|
||||
},
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"name": "blend_data",
|
||||
"shape": 7,
|
||||
"type": "STRING",
|
||||
"widget": {
|
||||
"name": "blend_data"
|
||||
},
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"name": "layer_image",
|
||||
"shape": 7,
|
||||
"type": "STRING",
|
||||
"widget": {
|
||||
"name": "layer_image"
|
||||
},
|
||||
"link": null
|
||||
}
|
||||
],
|
||||
"outputs": [
|
||||
{
|
||||
"name": "image",
|
||||
"type": "IMAGE",
|
||||
"links": [
|
||||
7,
|
||||
15
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "mask",
|
||||
"type": "MASK",
|
||||
"links": [
|
||||
8
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "full_image",
|
||||
"type": "IMAGE",
|
||||
"links": [
|
||||
13
|
||||
]
|
||||
}
|
||||
],
|
||||
"properties": {
|
||||
"Node name for S&R": "AdachiInlineMask"
|
||||
},
|
||||
"widgets_values": [
|
||||
"",
|
||||
"",
|
||||
"",
|
||||
"crop",
|
||||
"{\"job\":\"8d759783-b3cd-4dbc-b4ea-2c8e307be653\"}",
|
||||
"",
|
||||
""
|
||||
],
|
||||
"widgets_values_named": {
|
||||
"image": "",
|
||||
"mask_data": "",
|
||||
"source_data": "",
|
||||
"edit_mode": "crop",
|
||||
"crop_state": "{\"job\":\"8d759783-b3cd-4dbc-b4ea-2c8e307be653\"}",
|
||||
"blend_data": "",
|
||||
"layer_image": ""
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"type": "CheckpointLoaderSimple",
|
||||
"pos": [
|
||||
40,
|
||||
-300
|
||||
],
|
||||
"size": [
|
||||
340,
|
||||
130.65625
|
||||
],
|
||||
"flags": {},
|
||||
"order": 1,
|
||||
"mode": 0,
|
||||
"inputs": [
|
||||
{
|
||||
"name": "ckpt_name",
|
||||
"type": "COMBO",
|
||||
"widget": {
|
||||
"name": "ckpt_name"
|
||||
},
|
||||
"link": null
|
||||
}
|
||||
],
|
||||
"outputs": [
|
||||
{
|
||||
"name": "MODEL",
|
||||
"type": "MODEL",
|
||||
"links": [
|
||||
3
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "CLIP",
|
||||
"type": "CLIP",
|
||||
"links": [
|
||||
1,
|
||||
2
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "VAE",
|
||||
"type": "VAE",
|
||||
"links": [
|
||||
4
|
||||
]
|
||||
}
|
||||
],
|
||||
"properties": {
|
||||
"Node name for S&R": "CheckpointLoaderSimple"
|
||||
},
|
||||
"widgets_values": [
|
||||
"CHOOSE_YOUR_CHECKPOINT.safetensors"
|
||||
],
|
||||
"widgets_values_named": {
|
||||
"ckpt_name": "CHOOSE_YOUR_CHECKPOINT.safetensors"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"type": "CLIPTextEncode",
|
||||
"pos": [
|
||||
420,
|
||||
-350
|
||||
],
|
||||
"size": [
|
||||
350,
|
||||
150
|
||||
],
|
||||
"flags": {},
|
||||
"order": 4,
|
||||
"mode": 0,
|
||||
"inputs": [
|
||||
{
|
||||
"name": "clip",
|
||||
"type": "CLIP",
|
||||
"link": 1
|
||||
},
|
||||
{
|
||||
"name": "text",
|
||||
"type": "STRING",
|
||||
"widget": {
|
||||
"name": "text"
|
||||
},
|
||||
"link": null
|
||||
}
|
||||
],
|
||||
"outputs": [
|
||||
{
|
||||
"name": "CONDITIONING",
|
||||
"type": "CONDITIONING",
|
||||
"links": [
|
||||
5
|
||||
]
|
||||
}
|
||||
],
|
||||
"title": "Positive",
|
||||
"properties": {
|
||||
"Node name for S&R": "CLIPTextEncode"
|
||||
},
|
||||
"widgets_values": [
|
||||
"A detailed natural photograph, coherent lighting, high quality"
|
||||
],
|
||||
"widgets_values_named": {
|
||||
"text": "A detailed natural photograph, coherent lighting, high quality"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 4,
|
||||
"type": "CLIPTextEncode",
|
||||
"pos": [
|
||||
800,
|
||||
-350
|
||||
],
|
||||
"size": [
|
||||
350,
|
||||
150
|
||||
],
|
||||
"flags": {},
|
||||
"order": 5,
|
||||
"mode": 0,
|
||||
"inputs": [
|
||||
{
|
||||
"name": "clip",
|
||||
"type": "CLIP",
|
||||
"link": 2
|
||||
},
|
||||
{
|
||||
"name": "text",
|
||||
"type": "STRING",
|
||||
"widget": {
|
||||
"name": "text"
|
||||
},
|
||||
"link": null
|
||||
}
|
||||
],
|
||||
"outputs": [
|
||||
{
|
||||
"name": "CONDITIONING",
|
||||
"type": "CONDITIONING",
|
||||
"links": [
|
||||
6
|
||||
]
|
||||
}
|
||||
],
|
||||
"title": "Negative",
|
||||
"properties": {
|
||||
"Node name for S&R": "CLIPTextEncode"
|
||||
},
|
||||
"widgets_values": [
|
||||
"blurry, distorted, artifacts"
|
||||
],
|
||||
"widgets_values_named": {
|
||||
"text": "blurry, distorted, artifacts"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 5,
|
||||
"type": "AdachiWebUIInpaint",
|
||||
"pos": [
|
||||
700,
|
||||
100
|
||||
],
|
||||
"size": [
|
||||
430,
|
||||
767
|
||||
],
|
||||
"flags": {},
|
||||
"order": 6,
|
||||
"mode": 0,
|
||||
"inputs": [
|
||||
{
|
||||
"name": "model",
|
||||
"type": "MODEL",
|
||||
"link": 3
|
||||
},
|
||||
{
|
||||
"name": "positive",
|
||||
"type": "CONDITIONING",
|
||||
"link": 5
|
||||
},
|
||||
{
|
||||
"name": "negative",
|
||||
"type": "CONDITIONING",
|
||||
"link": 6
|
||||
},
|
||||
{
|
||||
"name": "vae",
|
||||
"type": "VAE",
|
||||
"link": 4
|
||||
},
|
||||
{
|
||||
"name": "image",
|
||||
"type": "IMAGE",
|
||||
"link": 7
|
||||
},
|
||||
{
|
||||
"name": "mask",
|
||||
"type": "MASK",
|
||||
"link": 8
|
||||
},
|
||||
{
|
||||
"name": "refiner_model",
|
||||
"shape": 7,
|
||||
"type": "MODEL",
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"name": "refiner_positive",
|
||||
"shape": 7,
|
||||
"type": "CONDITIONING",
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"name": "refiner_negative",
|
||||
"shape": 7,
|
||||
"type": "CONDITIONING",
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"name": "area",
|
||||
"type": "COMBO",
|
||||
"widget": {
|
||||
"name": "area"
|
||||
},
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"name": "width",
|
||||
"type": "INT",
|
||||
"widget": {
|
||||
"name": "width"
|
||||
},
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"name": "height",
|
||||
"type": "INT",
|
||||
"widget": {
|
||||
"name": "height"
|
||||
},
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"name": "padding",
|
||||
"type": "INT",
|
||||
"widget": {
|
||||
"name": "padding"
|
||||
},
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"name": "mask_blur",
|
||||
"type": "FLOAT",
|
||||
"widget": {
|
||||
"name": "mask_blur"
|
||||
},
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"name": "mask_grow",
|
||||
"type": "INT",
|
||||
"widget": {
|
||||
"name": "mask_grow"
|
||||
},
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"name": "mask_mode",
|
||||
"type": "COMBO",
|
||||
"widget": {
|
||||
"name": "mask_mode"
|
||||
},
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"name": "fill",
|
||||
"type": "COMBO",
|
||||
"widget": {
|
||||
"name": "fill"
|
||||
},
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"name": "resize_mode",
|
||||
"type": "COMBO",
|
||||
"widget": {
|
||||
"name": "resize_mode"
|
||||
},
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"name": "seed",
|
||||
"type": "INT",
|
||||
"widget": {
|
||||
"name": "seed"
|
||||
},
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"name": "steps",
|
||||
"type": "INT",
|
||||
"widget": {
|
||||
"name": "steps"
|
||||
},
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"name": "cfg",
|
||||
"type": "FLOAT",
|
||||
"widget": {
|
||||
"name": "cfg"
|
||||
},
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"name": "sampler_name",
|
||||
"type": "COMBO",
|
||||
"widget": {
|
||||
"name": "sampler_name"
|
||||
},
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"name": "scheduler",
|
||||
"type": "COMBO",
|
||||
"widget": {
|
||||
"name": "scheduler"
|
||||
},
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"name": "denoise",
|
||||
"type": "FLOAT",
|
||||
"widget": {
|
||||
"name": "denoise"
|
||||
},
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"name": "batch_size",
|
||||
"type": "INT",
|
||||
"widget": {
|
||||
"name": "batch_size"
|
||||
},
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"name": "refiner_switch",
|
||||
"type": "FLOAT",
|
||||
"widget": {
|
||||
"name": "refiner_switch"
|
||||
},
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"name": "inpaint_model",
|
||||
"shape": 7,
|
||||
"type": "BOOLEAN",
|
||||
"widget": {
|
||||
"name": "inpaint_model"
|
||||
},
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"name": "soft_edge",
|
||||
"shape": 7,
|
||||
"type": "BOOLEAN",
|
||||
"widget": {
|
||||
"name": "soft_edge"
|
||||
},
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"name": "soft_strength",
|
||||
"shape": 7,
|
||||
"type": "FLOAT",
|
||||
"widget": {
|
||||
"name": "soft_strength"
|
||||
},
|
||||
"link": null
|
||||
}
|
||||
],
|
||||
"outputs": [
|
||||
{
|
||||
"name": "image",
|
||||
"type": "IMAGE",
|
||||
"links": [
|
||||
10
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "crop",
|
||||
"type": "IMAGE",
|
||||
"links": null
|
||||
},
|
||||
{
|
||||
"name": "mask",
|
||||
"type": "MASK",
|
||||
"links": null
|
||||
}
|
||||
],
|
||||
"properties": {
|
||||
"Node name for S&R": "AdachiWebUIInpaint"
|
||||
},
|
||||
"widgets_values": [
|
||||
"only_masked",
|
||||
1024,
|
||||
1024,
|
||||
32,
|
||||
4,
|
||||
0,
|
||||
"inside",
|
||||
"original",
|
||||
"stretch",
|
||||
42,
|
||||
"fixed",
|
||||
20,
|
||||
7,
|
||||
"dpmpp_2m",
|
||||
"karras",
|
||||
0.75,
|
||||
1,
|
||||
0.8,
|
||||
false,
|
||||
false,
|
||||
0.5
|
||||
],
|
||||
"widgets_values_named": {
|
||||
"area": "only_masked",
|
||||
"width": 1024,
|
||||
"height": 1024,
|
||||
"padding": 32,
|
||||
"mask_blur": 4,
|
||||
"mask_grow": 0,
|
||||
"mask_mode": "inside",
|
||||
"fill": "original",
|
||||
"resize_mode": "stretch",
|
||||
"seed": 42,
|
||||
"control_after_generate": "fixed",
|
||||
"steps": 20,
|
||||
"cfg": 7,
|
||||
"sampler_name": "dpmpp_2m",
|
||||
"scheduler": "karras",
|
||||
"denoise": 0.75,
|
||||
"batch_size": 1,
|
||||
"refiner_switch": 0.8,
|
||||
"inpaint_model": false,
|
||||
"soft_edge": false,
|
||||
"soft_strength": 0.5
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 6,
|
||||
"type": "AdachiImageCompare",
|
||||
"pos": [
|
||||
1300,
|
||||
100
|
||||
],
|
||||
"size": [
|
||||
590,
|
||||
620
|
||||
],
|
||||
"flags": {},
|
||||
"order": 7,
|
||||
"mode": 0,
|
||||
"inputs": [
|
||||
{
|
||||
"name": "original",
|
||||
"type": "IMAGE",
|
||||
"link": 15
|
||||
},
|
||||
{
|
||||
"name": "result",
|
||||
"type": "IMAGE",
|
||||
"link": 10
|
||||
}
|
||||
],
|
||||
"outputs": [
|
||||
{
|
||||
"name": "image",
|
||||
"type": "IMAGE",
|
||||
"links": []
|
||||
}
|
||||
],
|
||||
"properties": {
|
||||
"Node name for S&R": "AdachiImageCompare"
|
||||
},
|
||||
"widgets_values": [],
|
||||
"widgets_values_named": {}
|
||||
},
|
||||
{
|
||||
"id": 7,
|
||||
"type": "SaveImage",
|
||||
"pos": [
|
||||
1300,
|
||||
850
|
||||
],
|
||||
"size": [
|
||||
430,
|
||||
450
|
||||
],
|
||||
"flags": {},
|
||||
"order": 3,
|
||||
"mode": 0,
|
||||
"inputs": [
|
||||
{
|
||||
"name": "images",
|
||||
"type": "IMAGE",
|
||||
"link": 13
|
||||
},
|
||||
{
|
||||
"name": "filename_prefix",
|
||||
"type": "STRING",
|
||||
"widget": {
|
||||
"name": "filename_prefix"
|
||||
},
|
||||
"link": null
|
||||
}
|
||||
],
|
||||
"outputs": [],
|
||||
"properties": {},
|
||||
"widgets_values": [
|
||||
"Adachi/CropBlend"
|
||||
],
|
||||
"widgets_values_named": {
|
||||
"filename_prefix": "Adachi/CropBlend"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 8,
|
||||
"type": "Note",
|
||||
"pos": [
|
||||
40,
|
||||
-190
|
||||
],
|
||||
"size": [
|
||||
540,
|
||||
260
|
||||
],
|
||||
"flags": {},
|
||||
"order": 2,
|
||||
"mode": 0,
|
||||
"inputs": [],
|
||||
"outputs": [],
|
||||
"properties": {},
|
||||
"widgets_values": [
|
||||
"Inline Mask: Crop & Blend\n1. Select your checkpoint and upload the full source.\n2. Choose Crop & Blend and a size preset, then left-click to lock the black dashed frame. Inpaint width/height follow the crop automatically.\n3. Paint inside the empty crop mask and run the workflow.\n4. Inspect Image Compare and click Adopt this result. The patch returns to this crop; Inline Mask has no result input.\n5. Paint the blend layer mask to keep new pixels; Alt restores original pixels. The repaint mask is retained.\n6. full_image is the current adopted full composite. Before Merge, hold right-click to preview the original and release to restore the workspace. Click the check mark to merge; then right-click releases the selection and left-click chooses a new area. Undo is the return arrow after Merge. Hover the bottom controls for instructions."
|
||||
],
|
||||
"widgets_values_named": {
|
||||
"text": "Inline Mask: Crop & Blend\n1. Select your checkpoint and upload the full source.\n2. Choose Crop & Blend and a size preset, then left-click to lock the black dashed frame. Inpaint width/height follow the crop automatically.\n3. Paint inside the empty crop mask and run the workflow.\n4. Inspect Image Compare and click Adopt this result. The patch returns to this crop; Inline Mask has no result input.\n5. Paint the blend layer mask to keep new pixels; Alt restores original pixels. The repaint mask is retained.\n6. full_image is the current adopted full composite. Reselect merges it before choosing a new area."
|
||||
},
|
||||
"color": "#432",
|
||||
"bgcolor": "#653"
|
||||
}
|
||||
],
|
||||
"links": [
|
||||
[
|
||||
1,
|
||||
2,
|
||||
1,
|
||||
3,
|
||||
0,
|
||||
"CLIP"
|
||||
],
|
||||
[
|
||||
2,
|
||||
2,
|
||||
1,
|
||||
4,
|
||||
0,
|
||||
"CLIP"
|
||||
],
|
||||
[
|
||||
3,
|
||||
2,
|
||||
0,
|
||||
5,
|
||||
0,
|
||||
"MODEL"
|
||||
],
|
||||
[
|
||||
4,
|
||||
2,
|
||||
2,
|
||||
5,
|
||||
3,
|
||||
"VAE"
|
||||
],
|
||||
[
|
||||
5,
|
||||
3,
|
||||
0,
|
||||
5,
|
||||
1,
|
||||
"CONDITIONING"
|
||||
],
|
||||
[
|
||||
6,
|
||||
4,
|
||||
0,
|
||||
5,
|
||||
2,
|
||||
"CONDITIONING"
|
||||
],
|
||||
[
|
||||
7,
|
||||
1,
|
||||
0,
|
||||
5,
|
||||
4,
|
||||
"IMAGE"
|
||||
],
|
||||
[
|
||||
8,
|
||||
1,
|
||||
1,
|
||||
5,
|
||||
5,
|
||||
"MASK"
|
||||
],
|
||||
[
|
||||
10,
|
||||
5,
|
||||
0,
|
||||
6,
|
||||
1,
|
||||
"IMAGE"
|
||||
],
|
||||
[
|
||||
13,
|
||||
1,
|
||||
2,
|
||||
7,
|
||||
0,
|
||||
"IMAGE"
|
||||
],
|
||||
[
|
||||
15,
|
||||
1,
|
||||
0,
|
||||
6,
|
||||
0,
|
||||
"IMAGE"
|
||||
]
|
||||
],
|
||||
"groups": [],
|
||||
"config": {},
|
||||
"extra": {
|
||||
"ds": {
|
||||
"scale": 0.5,
|
||||
"offset": [
|
||||
0,
|
||||
400
|
||||
]
|
||||
}
|
||||
},
|
||||
"version": 0.4
|
||||
}
|
||||
+13
-4
@@ -22,7 +22,7 @@ if (-not $destination.StartsWith($customRoot.TrimEnd('\') + '\', [StringComparis
|
||||
throw 'Install destination must stay within the selected custom_nodes directory.'
|
||||
}
|
||||
if ($destination.TrimEnd('\') -eq $packageRoot.TrimEnd('\')) {
|
||||
Write-Host 'This package is already in the selected ComfyUI custom_nodes directory. 喵'
|
||||
Write-Host 'This package is already in the selected ComfyUI custom_nodes directory.'
|
||||
exit 0
|
||||
}
|
||||
if ((Test-Path -LiteralPath $destination) -and (Test-Path -LiteralPath $legacyPath)) {
|
||||
@@ -38,7 +38,7 @@ if ($existingPath) {
|
||||
New-Item -ItemType Directory -Path $backupRoot -Force | Out-Null
|
||||
$backupFile = Join-Path $backupRoot ('Adachi-Inpaint-Workbench-' + (Get-Date -Format 'yyyyMMdd-HHmmss-fff') + '.zip')
|
||||
Compress-Archive -LiteralPath $existingPath -DestinationPath $backupFile
|
||||
Write-Host "Previous installation backed up: $backupFile 喵"
|
||||
Write-Host "Previous installation backed up: $backupFile"
|
||||
if ($existingPath -ne $destination) {
|
||||
# Verify both resolved absolute paths before moving the legacy folder.
|
||||
if ([IO.Path]::GetDirectoryName($existingPath) -ne $customRoot -or [IO.Path]::GetDirectoryName($destination) -ne $customRoot) {
|
||||
@@ -54,5 +54,14 @@ Get-ChildItem -LiteralPath $packageRoot -Force | Where-Object {
|
||||
} | ForEach-Object {
|
||||
Copy-Item -LiteralPath $_.FullName -Destination $destination -Recurse -Force
|
||||
}
|
||||
Write-Host "Installed Adachi-Inpaint-Workbench: $destination 喵"
|
||||
Write-Host 'Restart ComfyUI, then refresh the browser with Ctrl+F5. 喵'
|
||||
# These tracked files were retired in 0.6.2. The previous installation ZIP above
|
||||
# retains them for rollback; remove them from an overwritten installation too.
|
||||
foreach ($retiredRelative in @('web\magic_wand.js', 'web\magic_wand_worker.js', 'web\wand_selection.js', 'tests\test_magic_wand.mjs')) {
|
||||
$retiredPath = [IO.Path]::GetFullPath((Join-Path $destination $retiredRelative))
|
||||
if (-not $retiredPath.StartsWith($destination.TrimEnd('\') + '\', [StringComparison]::OrdinalIgnoreCase)) {
|
||||
throw 'Retired plugin file must stay within the install directory.'
|
||||
}
|
||||
if (Test-Path -LiteralPath $retiredPath -PathType Leaf) { Remove-Item -LiteralPath $retiredPath -Force }
|
||||
}
|
||||
Write-Host "Installed Adachi-Inpaint-Workbench: $destination"
|
||||
Write-Host 'Restart ComfyUI, then refresh the browser with Ctrl+F5.'
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"nodeCategories": {
|
||||
"Adachi-Inpaint-Workbench": "Adachi-Inpaint-Workbench"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,251 @@
|
||||
{
|
||||
"AdachiInlineMask": {
|
||||
"display_name": "Inline Mask",
|
||||
"description": "Paint an inpaint mask directly in the workflow.",
|
||||
"inputs": {
|
||||
"image": {
|
||||
"name": "image",
|
||||
"tooltip": "Input image path populated by inline upload."
|
||||
},
|
||||
"mask_data": {
|
||||
"name": "mask_data",
|
||||
"tooltip": "Editor mask PNG data URL; white repaints."
|
||||
},
|
||||
"source_data": {
|
||||
"name": "source_data",
|
||||
"tooltip": "Embedded source image for portable workflows."
|
||||
}
|
||||
},
|
||||
"outputs": {
|
||||
"0": {
|
||||
"name": "image"
|
||||
},
|
||||
"1": {
|
||||
"name": "mask"
|
||||
}
|
||||
}
|
||||
},
|
||||
"AdachiInpaintPrepare": {
|
||||
"display_name": "Inpaint Prepare",
|
||||
"description": "Crop and prepare masks with exact compositing context; use the all-in-one sampler for latent fill modes.",
|
||||
"inputs": {
|
||||
"image": {
|
||||
"name": "image",
|
||||
"tooltip": "Original image; output is restored to this exact size."
|
||||
},
|
||||
"mask": {
|
||||
"name": "mask",
|
||||
"tooltip": "White repaints; black preserves."
|
||||
},
|
||||
"area": {
|
||||
"name": "area",
|
||||
"tooltip": "Whole image or mask bounding-box inpainting."
|
||||
},
|
||||
"width": {
|
||||
"name": "width",
|
||||
"tooltip": "Sampling canvas width, independent of final image size."
|
||||
},
|
||||
"height": {
|
||||
"name": "height",
|
||||
"tooltip": "Sampling canvas height."
|
||||
},
|
||||
"padding": {
|
||||
"name": "padding",
|
||||
"tooltip": "Mask-only context padding in original pixels."
|
||||
},
|
||||
"mask_blur": {
|
||||
"name": "mask_blur",
|
||||
"tooltip": "Gaussian mask feathering in original pixels."
|
||||
},
|
||||
"mask_grow": {
|
||||
"name": "mask_grow",
|
||||
"tooltip": "Positive dilates; negative erodes the mask."
|
||||
},
|
||||
"mask_mode": {
|
||||
"name": "mask_mode",
|
||||
"tooltip": "Repaint inside or invert the mask."
|
||||
},
|
||||
"fill": {
|
||||
"name": "fill",
|
||||
"tooltip": "Original, surrounding-color fill, latent noise, or zero latent. Latent modes require the all-in-one sampler."
|
||||
},
|
||||
"resize_mode": {
|
||||
"name": "resize_mode",
|
||||
"tooltip": "Whole-image resize mode; mask-only mode always retains the entire mask."
|
||||
},
|
||||
"soft_edge": {
|
||||
"name": "soft_edge",
|
||||
"tooltip": "Extra feathering, not AUTOMATIC1111's Soft Inpainting algorithm."
|
||||
},
|
||||
"soft_strength": {
|
||||
"name": "soft_strength",
|
||||
"tooltip": "Adds 0-16 pixels of Gaussian feathering."
|
||||
}
|
||||
},
|
||||
"outputs": {
|
||||
"0": {
|
||||
"name": "pixels"
|
||||
},
|
||||
"1": {
|
||||
"name": "mask"
|
||||
},
|
||||
"2": {
|
||||
"name": "context"
|
||||
}
|
||||
}
|
||||
},
|
||||
"AdachiInpaintComposite": {
|
||||
"display_name": "Inpaint Composite",
|
||||
"description": "Restore original size and preserve pixels outside the effective mask exactly.",
|
||||
"inputs": {
|
||||
"generated": {
|
||||
"name": "generated",
|
||||
"tooltip": "Generated sampling canvas."
|
||||
},
|
||||
"context": {
|
||||
"name": "context",
|
||||
"tooltip": "Context from Adachi Inpaint Prepare."
|
||||
}
|
||||
},
|
||||
"outputs": {
|
||||
"0": {
|
||||
"name": "image"
|
||||
}
|
||||
}
|
||||
},
|
||||
"AdachiWebUIInpaint": {
|
||||
"display_name": "WebUI Inpaint",
|
||||
"description": "WebUI-style inpainting, crop, latent fill, sampling and original-size compositing.",
|
||||
"inputs": {
|
||||
"image": {
|
||||
"name": "image",
|
||||
"tooltip": "Original image; output is restored to this exact size."
|
||||
},
|
||||
"mask": {
|
||||
"name": "mask",
|
||||
"tooltip": "White repaints; black preserves."
|
||||
},
|
||||
"area": {
|
||||
"name": "area",
|
||||
"tooltip": "Whole image or mask bounding-box inpainting."
|
||||
},
|
||||
"width": {
|
||||
"name": "width",
|
||||
"tooltip": "Sampling canvas width, independent of final image size."
|
||||
},
|
||||
"height": {
|
||||
"name": "height",
|
||||
"tooltip": "Sampling canvas height."
|
||||
},
|
||||
"padding": {
|
||||
"name": "padding",
|
||||
"tooltip": "Mask-only context padding in original pixels."
|
||||
},
|
||||
"mask_blur": {
|
||||
"name": "mask_blur",
|
||||
"tooltip": "Gaussian mask feathering in original pixels."
|
||||
},
|
||||
"mask_grow": {
|
||||
"name": "mask_grow",
|
||||
"tooltip": "Positive dilates; negative erodes the mask."
|
||||
},
|
||||
"mask_mode": {
|
||||
"name": "mask_mode",
|
||||
"tooltip": "Repaint inside or invert the mask."
|
||||
},
|
||||
"fill": {
|
||||
"name": "fill",
|
||||
"tooltip": "Original, surrounding-color fill, latent noise, or zero latent. Latent modes require the all-in-one sampler."
|
||||
},
|
||||
"resize_mode": {
|
||||
"name": "resize_mode",
|
||||
"tooltip": "Whole-image resize mode; mask-only mode always retains the entire mask."
|
||||
},
|
||||
"seed": {
|
||||
"name": "seed",
|
||||
"tooltip": "Seed for a reproducible batch of distinct samples."
|
||||
},
|
||||
"denoise": {
|
||||
"name": "denoise",
|
||||
"tooltip": "Zero returns the original exactly; one fully denoises."
|
||||
},
|
||||
"batch_size": {
|
||||
"name": "batch_size",
|
||||
"tooltip": "Number of generated variants per input image."
|
||||
},
|
||||
"refiner_switch": {
|
||||
"name": "refiner_switch",
|
||||
"tooltip": "Fraction of steps on the base model when a refiner is connected."
|
||||
},
|
||||
"inpaint_model": {
|
||||
"name": "inpaint_model",
|
||||
"tooltip": "Enable only for dedicated inpainting models; uses ComfyUI's native InpaintModelConditioning."
|
||||
},
|
||||
"soft_edge": {
|
||||
"name": "soft_edge",
|
||||
"tooltip": "Extra feathering, not A1111 Soft Inpainting."
|
||||
},
|
||||
"refiner_model": {
|
||||
"name": "refiner_model",
|
||||
"tooltip": "Optional compatible refiner model, e.g. SDXL refiner."
|
||||
},
|
||||
"refiner_positive": {
|
||||
"name": "refiner_positive",
|
||||
"tooltip": "Encode using the refiner CLIP; defaults to original positive conditioning."
|
||||
},
|
||||
"refiner_negative": {
|
||||
"name": "refiner_negative",
|
||||
"tooltip": "Encode using the refiner CLIP; defaults to original negative conditioning."
|
||||
}
|
||||
},
|
||||
"outputs": {
|
||||
"0": {
|
||||
"name": "image"
|
||||
},
|
||||
"1": {
|
||||
"name": "crop"
|
||||
},
|
||||
"2": {
|
||||
"name": "mask"
|
||||
}
|
||||
}
|
||||
},
|
||||
"AdachiImageCompare": {
|
||||
"display_name": "Image Compare",
|
||||
"description": "Hover to compare; adopt a result into the upstream inline editor.",
|
||||
"inputs": {
|
||||
"original": {
|
||||
"name": "original",
|
||||
"tooltip": "Original image shown on the right."
|
||||
},
|
||||
"result": {
|
||||
"name": "result",
|
||||
"tooltip": "Full-size generated image shown on the left; use image, not crop."
|
||||
}
|
||||
},
|
||||
"outputs": {
|
||||
"0": {
|
||||
"name": "image"
|
||||
}
|
||||
}
|
||||
},
|
||||
"AdachiExclusiveSwitch": {
|
||||
"display_name": "Auto Exclusive Switch",
|
||||
"description": "Automatically forwards the only enabled input. Bypass one branch; both enabled or both absent is an error.",
|
||||
"inputs": {
|
||||
"input_a": {
|
||||
"name": "input_a",
|
||||
"tooltip": "First branch. Connect the same data type to both branches and the output."
|
||||
},
|
||||
"input_b": {
|
||||
"name": "input_b",
|
||||
"tooltip": "Second branch. Exactly one branch must remain enabled."
|
||||
}
|
||||
},
|
||||
"outputs": {
|
||||
"0": {
|
||||
"name": "output"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"nodeCategories": {
|
||||
"Adachi-Inpaint-Workbench": "安达工作台 / Adachi-Inpaint-Workbench"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,270 @@
|
||||
{
|
||||
"AdachiInlineMask": {
|
||||
"display_name": "内联蒙版 / Inline Mask",
|
||||
"description": "直接在工作流节点内涂抹蒙版,无需打开独立编辑器。",
|
||||
"inputs": {
|
||||
"image": {
|
||||
"name": "原图",
|
||||
"tooltip": "由内联编辑器上传填充的 ComfyUI input 图片路径。"
|
||||
},
|
||||
"mask_data": {
|
||||
"name": "蒙版数据",
|
||||
"tooltip": "编辑器保存的蒙版 PNG 数据;白色重绘。"
|
||||
},
|
||||
"source_data": {
|
||||
"name": "嵌入原图",
|
||||
"tooltip": "嵌入原图,便于工作流在其他机器使用。"
|
||||
},
|
||||
"edit_mode": {
|
||||
"name": "编辑模式"
|
||||
},
|
||||
"crop_state": {
|
||||
"name": "裁切选区"
|
||||
},
|
||||
"blend_data": {
|
||||
"name": "融合蒙版"
|
||||
},
|
||||
"layer_image": {
|
||||
"name": "重绘图层"
|
||||
}
|
||||
},
|
||||
"outputs": {
|
||||
"0": {
|
||||
"name": "图像"
|
||||
},
|
||||
"1": {
|
||||
"name": "蒙版"
|
||||
},
|
||||
"2": {
|
||||
"name": "完整图像"
|
||||
}
|
||||
}
|
||||
},
|
||||
"AdachiInpaintPrepare": {
|
||||
"display_name": "重绘预处理 / Inpaint Prepare",
|
||||
"description": "局部重绘裁剪、蒙版处理与精确回贴上下文;latent 填充请使用一体采样节点。",
|
||||
"inputs": {
|
||||
"image": {
|
||||
"name": "原图",
|
||||
"tooltip": "原图;输出会还原为这个尺寸。"
|
||||
},
|
||||
"mask": {
|
||||
"name": "蒙版",
|
||||
"tooltip": "白色重绘,黑色保护。"
|
||||
},
|
||||
"area": {
|
||||
"name": "重绘范围",
|
||||
"tooltip": "整张原图重绘,或仅蒙版包围框区域重绘。"
|
||||
},
|
||||
"width": {
|
||||
"name": "宽度",
|
||||
"tooltip": "采样画布宽度;最终输出仍为原图尺寸。"
|
||||
},
|
||||
"height": {
|
||||
"name": "高度",
|
||||
"tooltip": "采样画布高度。"
|
||||
},
|
||||
"padding": {
|
||||
"name": "外扩边距",
|
||||
"tooltip": "仅蒙版区域:原图像素单位的上下文边距。"
|
||||
},
|
||||
"mask_blur": {
|
||||
"name": "蒙版模糊",
|
||||
"tooltip": "原图像素单位的高斯羽化半径。"
|
||||
},
|
||||
"mask_grow": {
|
||||
"name": "蒙版扩张",
|
||||
"tooltip": "正数扩张,负数收缩。"
|
||||
},
|
||||
"mask_mode": {
|
||||
"name": "蒙版内外",
|
||||
"tooltip": "重绘蒙版内,或反相重绘蒙版外。"
|
||||
},
|
||||
"fill": {
|
||||
"name": "填充方式",
|
||||
"tooltip": "原图像素、周围颜色填充、潜空间噪声或空白潜空间;后两项由一体采样节点在 latent 层实现。"
|
||||
},
|
||||
"resize_mode": {
|
||||
"name": "缩放方式",
|
||||
"tooltip": "整图模式的缩放方式;仅蒙版模式始终保留完整蒙版。"
|
||||
},
|
||||
"soft_edge": {
|
||||
"name": "额外羽化",
|
||||
"tooltip": "额外羽化;不是 A1111 的 Soft Inpainting 原算法。"
|
||||
},
|
||||
"soft_strength": {
|
||||
"name": "羽化强度",
|
||||
"tooltip": "额外增加 0–16 像素的高斯羽化。"
|
||||
}
|
||||
},
|
||||
"outputs": {
|
||||
"0": {
|
||||
"name": "像素"
|
||||
},
|
||||
"1": {
|
||||
"name": "蒙版"
|
||||
},
|
||||
"2": {
|
||||
"name": "上下文"
|
||||
}
|
||||
}
|
||||
},
|
||||
"AdachiInpaintComposite": {
|
||||
"display_name": "原图回贴 / Inpaint Composite",
|
||||
"description": "还原原图尺寸,有效蒙版外保持原像素不变。",
|
||||
"inputs": {
|
||||
"generated": {
|
||||
"name": "采样图",
|
||||
"tooltip": "采样后的裁剪图。"
|
||||
},
|
||||
"context": {
|
||||
"name": "上下文",
|
||||
"tooltip": "预处理节点输出的裁剪与原图上下文。"
|
||||
}
|
||||
},
|
||||
"outputs": {
|
||||
"0": {
|
||||
"name": "图像"
|
||||
}
|
||||
}
|
||||
},
|
||||
"AdachiWebUIInpaint": {
|
||||
"display_name": "WebUI 局部重绘 / WebUI Inpaint",
|
||||
"description": "WebUI 式局部重绘:整图/蒙版区域、填充、采样与原尺寸回贴。",
|
||||
"inputs": {
|
||||
"image": {
|
||||
"name": "原图",
|
||||
"tooltip": "原图;输出会还原为这个尺寸。"
|
||||
},
|
||||
"mask": {
|
||||
"name": "蒙版",
|
||||
"tooltip": "白色重绘,黑色保护。"
|
||||
},
|
||||
"area": {
|
||||
"name": "重绘范围",
|
||||
"tooltip": "整张原图重绘,或仅蒙版包围框区域重绘。"
|
||||
},
|
||||
"width": {
|
||||
"name": "宽度",
|
||||
"tooltip": "采样画布宽度;最终输出仍为原图尺寸。"
|
||||
},
|
||||
"height": {
|
||||
"name": "高度",
|
||||
"tooltip": "采样画布高度。"
|
||||
},
|
||||
"padding": {
|
||||
"name": "外扩边距",
|
||||
"tooltip": "仅蒙版区域:原图像素单位的上下文边距。"
|
||||
},
|
||||
"mask_blur": {
|
||||
"name": "蒙版模糊",
|
||||
"tooltip": "原图像素单位的高斯羽化半径。"
|
||||
},
|
||||
"mask_grow": {
|
||||
"name": "蒙版扩张",
|
||||
"tooltip": "正数扩张,负数收缩。"
|
||||
},
|
||||
"mask_mode": {
|
||||
"name": "蒙版内外",
|
||||
"tooltip": "重绘蒙版内,或反相重绘蒙版外。"
|
||||
},
|
||||
"fill": {
|
||||
"name": "填充方式",
|
||||
"tooltip": "原图像素、周围颜色填充、潜空间噪声或空白潜空间。"
|
||||
},
|
||||
"resize_mode": {
|
||||
"name": "缩放方式",
|
||||
"tooltip": "整图模式的缩放方式;仅蒙版模式始终保留完整蒙版。"
|
||||
},
|
||||
"seed": {
|
||||
"name": "随机种子",
|
||||
"tooltip": "可复现的批量随机种子。"
|
||||
},
|
||||
"denoise": {
|
||||
"name": "重绘幅度",
|
||||
"tooltip": "0 原样返回原图,1 完全重绘。"
|
||||
},
|
||||
"batch_size": {
|
||||
"name": "每张生成数量",
|
||||
"tooltip": "每张输入图生成的变体数量。"
|
||||
},
|
||||
"refiner_switch": {
|
||||
"name": "Refiner 切换",
|
||||
"tooltip": "接入 Refiner 时 base 模型所占的采样步骤比例。"
|
||||
},
|
||||
"inpaint_model": {
|
||||
"name": "专用重绘模型",
|
||||
"tooltip": "仅专用 inpaint 模型开启;使用 ComfyUI 原生 InpaintModelConditioning。"
|
||||
},
|
||||
"soft_edge": {
|
||||
"name": "额外羽化",
|
||||
"tooltip": "额外羽化,并非 A1111 Soft Inpainting 原算法。"
|
||||
},
|
||||
"soft_strength": {
|
||||
"name": "羽化强度",
|
||||
"tooltip": "额外增加的高斯羽化强度。"
|
||||
},
|
||||
"refiner_model": {
|
||||
"name": "Refiner 模型",
|
||||
"tooltip": "可选的兼容 Refiner 模型,例如 SDXL refiner。"
|
||||
},
|
||||
"refiner_positive": {
|
||||
"name": "Refiner 正面",
|
||||
"tooltip": "用 Refiner 的 CLIP 编码;未连接则沿用原始正面条件。"
|
||||
},
|
||||
"refiner_negative": {
|
||||
"name": "Refiner 负面",
|
||||
"tooltip": "用 Refiner 的 CLIP 编码;未连接则沿用原始负面条件。"
|
||||
}
|
||||
},
|
||||
"outputs": {
|
||||
"0": {
|
||||
"name": "图像"
|
||||
},
|
||||
"1": {
|
||||
"name": "裁剪图"
|
||||
},
|
||||
"2": {
|
||||
"name": "蒙版"
|
||||
}
|
||||
}
|
||||
},
|
||||
"AdachiImageCompare": {
|
||||
"display_name": "图像对比 / Image Compare",
|
||||
"description": "鼠标悬停左右对比原图与重绘结果;点击可将结果回填到上游内联蒙版。",
|
||||
"inputs": {
|
||||
"original": {
|
||||
"name": "原图",
|
||||
"tooltip": "显示在右侧的原图,连接内联蒙版的 image。"
|
||||
},
|
||||
"result": {
|
||||
"name": "重绘结果",
|
||||
"tooltip": "显示在左侧的完整重绘图;请连接最终 image 而非 crop。"
|
||||
}
|
||||
},
|
||||
"outputs": {
|
||||
"0": {
|
||||
"name": "图像"
|
||||
}
|
||||
}
|
||||
},
|
||||
"AdachiExclusiveSwitch": {
|
||||
"display_name": "自动二选一 / Auto Exclusive Switch",
|
||||
"description": "自动输出唯一启用的分支;忽略或断开另一路,两路都启用或都无输入时提示错误,无需 switch。",
|
||||
"inputs": {
|
||||
"input_a": {
|
||||
"name": "输入 A",
|
||||
"tooltip": "第一路;两路及下游应使用相同数据类型,如正面条件、图像、模型。"
|
||||
},
|
||||
"input_b": {
|
||||
"name": "输入 B",
|
||||
"tooltip": "第二路;两路中需要且只能启用一路,另一支设为忽略或断开。"
|
||||
}
|
||||
},
|
||||
"outputs": {
|
||||
"0": {
|
||||
"name": "输出"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 79 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 34 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 85 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 44 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 128 KiB After Width: | Height: | Size: 676 KiB |
+2
-4
@@ -1,6 +1,6 @@
|
||||
[project]
|
||||
name = "adachi-inpaint-workbench"
|
||||
version = "0.4.1"
|
||||
version = "0.6.9"
|
||||
description = "Inline mask painting and WebUI-style inpainting nodes for ComfyUI"
|
||||
requires-python = ">=3.10"
|
||||
license = { file = "LICENSE" }
|
||||
@@ -18,9 +18,7 @@ Documentation = "https://github.com/adachi0130/Adachi-Inpaint-Workbench#readme"
|
||||
"Bug Tracker" = "https://github.com/adachi0130/Adachi-Inpaint-Workbench/issues"
|
||||
|
||||
[tool.comfy]
|
||||
# Set this to your actual Comfy Registry publisher ID before Registry publishing.
|
||||
# GitHub publication and the Manager legacy-list submission do not require it.
|
||||
PublisherId = ""
|
||||
PublisherId = "adachi0130"
|
||||
DisplayName = "Adachi-Inpaint-Workbench"
|
||||
|
||||
[tool.adachi-workbench]
|
||||
|
||||
+14
-14
@@ -1,22 +1,22 @@
|
||||
# Manager / Registry 发布
|
||||
# Manager / Registry publishing
|
||||
|
||||
GitHub 仓库公开并不代表 Manager 搜索清单或 Comfy Registry 已收录喵。
|
||||
本插件的 Manager 收录申请见 [PR #3378](https://github.com/Comfy-Org/ComfyUI-Manager/pull/3378),当前等待上游处理喵。
|
||||
A public GitHub repository does not by itself mean the plugin is listed in the Manager search index or in the Comfy Registry.
|
||||
The previous Manager listing submission is [PR #3378](https://github.com/Comfy-Org/ComfyUI-Manager/pull/3378). It was closed without merging; it is not confirmation that the plugin is searchable. Check the live Registry/Manager index for current availability.
|
||||
|
||||
## Manager 清单
|
||||
## Manager listing
|
||||
|
||||
[manager-entry.json](manager-entry.json) 是提交给 [ComfyUI-Manager](https://github.com/Comfy-Org/ComfyUI-Manager) 的条目,加入其根目录的 `custom-node-list.json` 并提交 PR,等待维护者合并及索引更新喵。
|
||||
提交方式以 [Manager 官方说明](https://github.com/Comfy-Org/ComfyUI-Manager#how-to-register-your-custom-node-into-comfyui-manager) 为准喵。
|
||||
收录前仍可使用 Manager 的 Git URL 安装,仓库地址为 `https://github.com/adachi0130/Adachi-Inpaint-Workbench` 喵。
|
||||
[manager-entry.json](manager-entry.json) records the legacy list entry submitted to [ComfyUI-Manager](https://github.com/Comfy-Org/ComfyUI-Manager).
|
||||
For current registration requirements, follow the [official Manager instructions](https://github.com/Comfy-Org/ComfyUI-Manager#how-to-register-your-custom-node-into-comfyui-manager) and the Registry publishing guide below.
|
||||
Until it is listed you can still install through the Manager's Git URL option, using `https://github.com/adachi0130/Adachi-Inpaint-Workbench`.
|
||||
|
||||
## Comfy Registry
|
||||
|
||||
根据 [官方发布指南](https://docs.comfy.org/registry/publishing),首次发布需要开发者建立自己的 Publisher 及 API Key 喵。
|
||||
Per the [official publishing guide](https://docs.comfy.org/registry/publishing), the first publish requires you to create your own Publisher and API key.
|
||||
|
||||
1. 登录 [Comfy Registry](https://registry.comfy.org/),创建自己的 Publisher,记录实际 Publisher ID 喵。
|
||||
2. 将 `pyproject.toml` 中 `[tool.comfy].PublisherId` 的空值改成该 ID,提交到 GitHub 喵。
|
||||
3. 在仓库 Settings → Secrets and variables → Actions 中添加 `REGISTRY_ACCESS_TOKEN`,值为 Registry 的发布 API Key 喵。
|
||||
4. 在 Actions 中手动运行 **Publish to Comfy Registry**,查看发布和平台校验结果喵。
|
||||
1. Sign in at [Comfy Registry](https://registry.comfy.org/) and create a Publisher, then note the actual Publisher ID.
|
||||
2. Check `[tool.comfy].PublisherId` in `pyproject.toml` (currently `adachi0130`) and confirm it matches the Publisher you own before publishing.
|
||||
3. In the repository Settings → Secrets and variables → Actions, add `REGISTRY_ACCESS_TOKEN` with the Registry publishing API key.
|
||||
4. Run **Publish to Comfy Registry** manually from the Actions tab and check the publish and platform validation results.
|
||||
|
||||
当前工作流仅手动触发,不会在未配置 Publisher 或 API Key 时自动发布喵。
|
||||
Registry 的版本发布后不可覆盖,后续发布需要先递增 `pyproject.toml` 版本号喵。
|
||||
The publishing workflow is manual-only. A Publisher ID in project metadata does not prove that an API key is configured or that a Registry release has been published.
|
||||
A Registry version cannot be overwritten once published, so later releases have to bump the version in `pyproject.toml`.
|
||||
|
||||
@@ -2,7 +2,9 @@
|
||||
"author": "adachi0130",
|
||||
"title": "Adachi-Inpaint-Workbench",
|
||||
"reference": "https://github.com/adachi0130/Adachi-Inpaint-Workbench",
|
||||
"files": ["https://github.com/adachi0130/Adachi-Inpaint-Workbench"],
|
||||
"files": [
|
||||
"https://github.com/adachi0130/Adachi-Inpaint-Workbench"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Inline mask painting with a compact image node, WebUI-style inpainting controls, whole-image and masked-area sampling, hover image comparison, and one-click result adoption. 内联蒙版、WebUI 风格局部重绘、整图/蒙版区域重绘、图像对比与结果回填。"
|
||||
"description": "Paint the inpaint mask directly on the node canvas instead of a modal mask editor, with no save/load round-trip per stroke. The connected inpaint node hosts the live painting tools and WebUI-style sampling controls, and supports whole-image or padded masked-area sampling with original-resolution compositing, Alt temporary erase, Ctrl+wheel brush size, hover image comparison and one-click adoption of a result as the next source image. MIT licensed; reuses ComfyUI's NumPy, Pillow and PyTorch."
|
||||
}
|
||||
|
||||
@@ -177,13 +177,13 @@ class BackendTests(unittest.TestCase):
|
||||
def test_embedded_source_and_mask_convention(self):
|
||||
rgba = Image.new("RGBA", (8, 4), (10, 20, 30, 255))
|
||||
rgba.putpixel((0, 0), (10, 20, 30, 0))
|
||||
pixels, alpha_mask = backend.AdachiInlineMask().load(source_data=data_url(rgba))
|
||||
pixels, alpha_mask, _ = backend.AdachiInlineMask().load(source_data=data_url(rgba))
|
||||
self.assertEqual(tuple(pixels.shape), (1, 4, 8, 3))
|
||||
self.assertEqual(float(alpha_mask[0, 0, 0]), 1)
|
||||
self.assertEqual(float(alpha_mask[0, 1, 1]), 0)
|
||||
blackwhite = Image.new("L", (8, 4), 0)
|
||||
blackwhite.putpixel((2, 1), 255)
|
||||
_, explicit_mask = backend.AdachiInlineMask().load(source_data=data_url(rgba), mask_data=data_url(blackwhite))
|
||||
_, explicit_mask, _ = backend.AdachiInlineMask().load(source_data=data_url(rgba), mask_data=data_url(blackwhite))
|
||||
self.assertEqual(float(explicit_mask[0, 1, 2]), 1)
|
||||
self.assertEqual(float(explicit_mask[0, 0, 0]), 0)
|
||||
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { appendComparison } from "../web/compare_history.js";
|
||||
|
||||
const first = {originals: ["source-a"], results: ["result-a"]};
|
||||
const second = appendComparison(first, {originals: ["source-b"], results: ["result-b", "result-c"]});
|
||||
assert.deepEqual(second, {originals: ["source-a", "source-b", "source-b"], results: ["result-a", "result-b", "result-c"]});
|
||||
assert.deepEqual(first, {originals: ["source-a"], results: ["result-a"]}, "Do not mutate saved history");
|
||||
const legacy = {originals: ["a", "b"], results: [1, 2, 3, 4]};
|
||||
assert.deepEqual(appendComparison(legacy, {originals: ["c"], results: [5]}), {
|
||||
originals: ["a", "a", "b", "b", "c"], results: [1, 2, 3, 4, 5],
|
||||
});
|
||||
assert.deepEqual(appendComparison(undefined, first), first);
|
||||
assert.deepEqual(appendComparison(first, {}), first);
|
||||
assert.deepEqual(appendComparison({}, {results: ["orphan"]}), {originals: [], results: []});
|
||||
assert.deepEqual(appendComparison(JSON.parse(JSON.stringify(second)), first).results, ["result-a", "result-b", "result-c"], "Cached execution replay must not count twice");
|
||||
const preview = {filename: "preview_001.png", subfolder: "", type: "temp"};
|
||||
const one = {originals: ["source-a"], results: [preview]};
|
||||
assert.equal(appendComparison(one, {originals: ["source-a"], results: [{...preview}]}).results.length, 1);
|
||||
assert.equal(appendComparison(one, {originals: ["source-a"], results: [{...preview, filename: "preview_002.png"}]}).results.length, 2);
|
||||
assert.equal(appendComparison(one, {originals: ["source-a"], results: [{...preview, subfolder: "other"}]}).results.length, 2);
|
||||
assert.equal(appendComparison(one, {originals: ["source-a"], results: [{...preview, type: "output"}]}).results.length, 2);
|
||||
assert.deepEqual(appendComparison({originals: ["source-a", "source-a"], results: [preview, {...preview}]}), one, "Repair duplicates already saved in workflows");
|
||||
console.log("Comparison history checks passed");
|
||||
@@ -0,0 +1,13 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import {syncCropDimensions} from '../web/parameter_bridge.js';
|
||||
const nodes=new Map(),links={},graph={links,getNodeById:id=>nodes.get(id),_nodes:[]};
|
||||
const source={id:1,type:'AdachiInlineMask',graph};nodes.set(1,source);graph._nodes.push(source);
|
||||
const make=(id,type,linkedWidth=false)=>{
|
||||
const n={id,type,graph,inputs:[{name:'image',link:id},...(linkedWidth?[{name:'width',link:999}]:[])],widgets:[{name:'width',value:640},{name:'height',value:640}]};
|
||||
nodes.set(id,n);graph._nodes.push(n);links[id]={origin_id:1};return n;
|
||||
};
|
||||
const sampler=make(2,'AdachiWebUIInpaint'),prepare=make(3,'AdachiInpaintPrepare',true);
|
||||
syncCropDimensions(source,1024,1536);
|
||||
assert.deepEqual(sampler.widgets.map(w=>w.value),[1024,1536]);assert.deepEqual(prepare.widgets.map(w=>w.value),[640,1536]);
|
||||
syncCropDimensions(source,9000,17);assert.deepEqual(sampler.widgets.map(w=>w.value),[8192,64]);
|
||||
console.log('Crop resolution sync: connected targets, linked-input protection and source-size limits passed');
|
||||
@@ -0,0 +1,29 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { CROP_PRESETS, cropAt } from "../web/crop_geometry.js";
|
||||
assert.ok(CROP_PRESETS.length <= 6);
|
||||
assert.ok(CROP_PRESETS.some(([w,h]) => w === 512 && h === 512));
|
||||
assert.ok(CROP_PRESETS.some(([w,h]) => w === 2048 && h === 2048));
|
||||
assert.ok(CROP_PRESETS.every(([w, h]) => w % 64 === 0 && h % 64 === 0 && Math.min(w,h) >= 512 && Math.max(w,h) <= 2048));
|
||||
assert.deepEqual(cropAt(2048, 3072, 1024, 1536, 400, 700), {
|
||||
x: 400,
|
||||
y: 700,
|
||||
width: 1024,
|
||||
height: 1536,
|
||||
});
|
||||
assert.deepEqual(cropAt(2048, 3072, 1024, 1536, 2040, 3070), {
|
||||
x: 1024,
|
||||
y: 1536,
|
||||
width: 1024,
|
||||
height: 1536,
|
||||
});
|
||||
assert.equal(cropAt(512, 512, 1024, 1536, 0, 0), null);
|
||||
assert.equal(cropAt(2048, 3072, 1025, 1536, 0, 0), null);
|
||||
assert.equal(cropAt(2048, 3072, 1024, 1536, NaN, 0), null);
|
||||
for (const x of [-100, 0, 12.9, 1000, 3000])
|
||||
for (const y of [-1, 0, 2200, 4000]) {
|
||||
const r = cropAt(2048, 3072, 1024, 1536, x, y);
|
||||
assert.ok(
|
||||
r.x >= 0 && r.y >= 0 && r.x + r.width <= 2048 && r.y + r.height <= 3072,
|
||||
);
|
||||
}
|
||||
console.log("Crop presets, source coordinates and edge clamping passed");
|
||||
@@ -0,0 +1,84 @@
|
||||
import base64
|
||||
import importlib.util
|
||||
import io
|
||||
import json
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import types
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
import numpy as np
|
||||
from PIL import Image
|
||||
import torch
|
||||
|
||||
spec=importlib.util.spec_from_file_location('inline_crop_tests',Path(__file__).resolve().parents[1]/'backend.py')
|
||||
backend=importlib.util.module_from_spec(spec);spec.loader.exec_module(backend)
|
||||
def url(image):
|
||||
b=io.BytesIO();image.save(b,format='PNG');return 'data:image/png;base64,'+base64.b64encode(b.getvalue()).decode()
|
||||
|
||||
class InlineCropTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
pixels=np.arange(96*128*3,dtype=np.uint8).reshape(96,128,3)
|
||||
self.source=url(Image.fromarray(pixels));self.original=torch.from_numpy(pixels.astype(np.float32)/255)[None]
|
||||
self.region=dict(x=32,y=16,width=64,height=64,locked=True,job='region-a')
|
||||
self.state=json.dumps(self.region)
|
||||
def test_legacy_mask_mode_ignores_result_and_keeps_original_ports(self):
|
||||
image,mask,full=backend.AdachiInlineMask().load(source_data=self.source,result=torch.ones(1,64,64,3))
|
||||
self.assertTrue(torch.equal(image,self.original));self.assertTrue(torch.equal(image,full));self.assertEqual(tuple(mask.shape),(1,96,128))
|
||||
def test_crop_source_and_generation_mask_are_sliced_at_exact_coordinates(self):
|
||||
pixels=np.zeros((96,128),dtype=np.uint8);pixels[20:24,35:40]=255
|
||||
image,mask,full=backend.AdachiInlineMask().load(source_data=self.source,mask_data=url(Image.fromarray(pixels)),edit_mode='crop',crop_state=self.state)
|
||||
self.assertTrue(torch.equal(image,self.original[:,16:80,32:96]));self.assertTrue(torch.equal(full,self.original))
|
||||
self.assertEqual(mask.sum().item(),20);self.assertEqual(mask[0,4,3].item(),1)
|
||||
def test_layer_blend_preserves_outside_and_supports_batch_and_soft_edges(self):
|
||||
alpha=np.zeros((64,64),dtype=np.uint8);alpha[:,:32]=255;alpha[:,32:48]=128
|
||||
result=torch.stack([torch.zeros(64,64,3),torch.ones(64,64,3)])
|
||||
blended=backend._blend_layer(self.original,result,url(Image.fromarray(alpha)),self.region)
|
||||
self.assertEqual(tuple(blended.shape),(2,96,128,3))
|
||||
outside=torch.ones(96,128,dtype=torch.bool);outside[16:80,32:96]=False
|
||||
for i in range(2):
|
||||
self.assertTrue(torch.equal(blended[i][outside],self.original[0][outside]))
|
||||
self.assertTrue(torch.equal(blended[i,16:80,32:64],result[i,:,:32]))
|
||||
self.assertTrue(torch.equal(blended[i,16:80,80:96],self.original[0,16:80,80:96]))
|
||||
self.assertTrue(torch.allclose(blended[i,16:80,64:80],self.original[0,16:80,64:80]*(127/255)+result[i,:,32:48]*(128/255)))
|
||||
def test_result_sink_persists_only_one_content_addressed_layer(self):
|
||||
with tempfile.TemporaryDirectory() as folder,patch.dict('sys.modules',{'folder_paths':types.SimpleNamespace(get_input_directory=lambda:folder)}):
|
||||
args=dict(result=torch.ones(2,64,64,3),source_data=self.source,crop_state=self.state,target='42')
|
||||
a=backend.AdachiLayerCommit().compose(**args);b=backend.AdachiLayerCommit().compose(**args)
|
||||
self.assertEqual(a['ui'],b['ui']);self.assertEqual(a['ui']['adachi_layer'][0]['target'],'42')
|
||||
self.assertEqual(a['ui']['adachi_layer'][0]['job'],'region-a')
|
||||
self.assertEqual(len(list(Path(folder).rglob('*.png'))),1)
|
||||
descriptor=a['ui']['adachi_layer'][0]['image'];name=descriptor['subfolder']+'/'+descriptor['filename']
|
||||
image,_,full=backend.AdachiInlineMask().load(source_data=self.source,edit_mode='crop',crop_state=self.state,layer_image=name)
|
||||
self.assertTrue(torch.equal(image,torch.ones(1,64,64,3)));self.assertTrue(torch.equal(full,a['result'][0][:1]))
|
||||
def test_invalid_regions_or_result_sizes_fail_before_writing(self):
|
||||
for change in ({'x':-1},{'y':80},{'width':65},{'height':0},{'x':True}):
|
||||
with self.subTest(change=change),self.assertRaises(ValueError):
|
||||
backend._blend_layer(self.original,torch.ones(1,64,64,3),'',{**self.region,**change})
|
||||
with patch.object(backend,'_store_layer') as store:
|
||||
with self.assertRaisesRegex(ValueError,'must match'):
|
||||
backend.AdachiLayerCommit().compose(torch.ones(1,32,64,3),source_data=self.source,crop_state=self.state)
|
||||
store.assert_not_called()
|
||||
def test_mask_mode_removes_feedback_even_when_connected(self):
|
||||
data={'prompt':{'1':{'class_type':'AdachiInlineMask','inputs':{'result':['2',0]}},'2':{'class_type':'ImageInvert','inputs':{'image':['1',0]}}}}
|
||||
backend.normalize_exclusive_prompt(data)
|
||||
self.assertNotIn('result',data['prompt']['1']['inputs']);self.assertEqual(len(data['prompt']),2)
|
||||
def test_crop_mode_has_no_result_socket_or_automatic_sink(self):
|
||||
self.assertNotIn('result', backend.AdachiInlineMask.INPUT_TYPES()['optional'])
|
||||
data={'prompt':{'1':{'class_type':'AdachiInlineMask','inputs':{'result':['2',0],'edit_mode':'crop','crop_state':self.state}},'2':{'class_type':'ImageInvert','inputs':{'image':['1',0]}},'3':{'class_type':'SaveImage','inputs':{'images':['1',2]}}}}
|
||||
backend.normalize_exclusive_prompt(data)
|
||||
self.assertEqual(len(data['prompt']),3)
|
||||
self.assertNotIn('result',data['prompt']['1']['inputs'])
|
||||
self.assertEqual(data['prompt']['3']['inputs']['images'],['1',2])
|
||||
def test_comparison_origin_tracks_exact_generating_region(self):
|
||||
prompt={'7':{'class_type':'AdachiInlineMask','inputs':{'edit_mode':'crop','crop_state':self.state}},'8':{'class_type':'Reroute','inputs':{'image':['7',0]}},'9':{'class_type':'AdachiImageCompare','inputs':{'original':['8',0]}}}
|
||||
self.assertEqual(backend._comparison_origin(prompt,'9'),{'source':'7','mode':'crop','job':'region-a'})
|
||||
prompt['7']['inputs']['crop_state']=json.dumps({**self.region,'job':'next-region'})
|
||||
self.assertEqual(backend._comparison_origin(prompt,'9')['job'],'next-region')
|
||||
self.assertIsNone(backend._comparison_origin({},'9'))
|
||||
def test_fingerprint_tracks_mode_blend_and_layer(self):
|
||||
first=backend.AdachiInlineMask.IS_CHANGED(source_data=self.source,edit_mode='mask')
|
||||
for extra in ({'edit_mode':'crop'},{'blend_data':'new'},{'layer_image':'changed.png'}):
|
||||
self.assertNotEqual(first,backend.AdachiInlineMask.IS_CHANGED(source_data=self.source,**extra))
|
||||
|
||||
if __name__=='__main__':unittest.main()
|
||||
@@ -0,0 +1,118 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { canStoreDraft, prepareInlineDraft, syncInlineWidgets, inlineWidgetNames } from "../web/draft_guard.js";
|
||||
class Storage {
|
||||
constructor(limit = 10000) {
|
||||
this.limit = limit;
|
||||
this.data = new Map();
|
||||
this.removed = [];
|
||||
}
|
||||
getItem(k) {
|
||||
return this.data.get(k) ?? null;
|
||||
}
|
||||
setItem(k, v) {
|
||||
const used = [...this.data].reduce(
|
||||
(n, [key, value]) => n + (key === k ? 0 : value.length),
|
||||
0,
|
||||
);
|
||||
if (used + v.length > this.limit)
|
||||
throw Object.assign(new Error("full"), { name: "QuotaExceededError" });
|
||||
this.data.set(k, v);
|
||||
}
|
||||
removeItem(k) {
|
||||
this.removed.push(k);
|
||||
this.data.delete(k);
|
||||
}
|
||||
}
|
||||
const storage = new Storage();
|
||||
storage.setItem("unrelated", "keep");
|
||||
assert.equal(canStoreDraft({ nodes: [] }, { storage }), true);
|
||||
assert.equal(canStoreDraft({ data: "x".repeat(20000) }, { storage }), false);
|
||||
assert.equal(storage.getItem("unrelated"), "keep");
|
||||
assert.ok(storage.removed.every((key) => key.startsWith("Adachi.DraftProbe:")));
|
||||
assert.equal(storage.data.size, 1);
|
||||
// Replacing a draft must reuse its existing space, rather than testing two full copies.
|
||||
const path = "workflows/Test.json";
|
||||
let hash = 2166136261;
|
||||
for (const c of path) hash = Math.imul(hash ^ c.charCodeAt(0), 16777619);
|
||||
const payloadKey = `Comfy.Workflow.Draft.v2:personal:${(hash >>> 0).toString(16).padStart(8, "0")}`;
|
||||
const oldGraph = { image: "x".repeat(6000) },
|
||||
oldRaw = JSON.stringify({
|
||||
data: JSON.stringify(oldGraph),
|
||||
updatedAt: Date.now(),
|
||||
});
|
||||
storage.setItem(
|
||||
"Comfy.Workflow.DraftIndex.v2:personal",
|
||||
JSON.stringify({ entries: { one: { path } } }),
|
||||
);
|
||||
storage.setItem(payloadKey, oldRaw);
|
||||
assert.equal(
|
||||
canStoreDraft({ ...oldGraph, mode: "crop" }, { path, storage }),
|
||||
true,
|
||||
);
|
||||
assert.equal(storage.getItem(payloadKey), oldRaw);
|
||||
assert.equal(
|
||||
canStoreDraft({ image: "x".repeat(12000) }, { path, storage }),
|
||||
false,
|
||||
);
|
||||
assert.equal(storage.getItem(payloadKey), oldRaw);
|
||||
assert.equal(
|
||||
canStoreDraft(
|
||||
{},
|
||||
{
|
||||
storage: {
|
||||
getItem() {
|
||||
throw Error("blocked");
|
||||
},
|
||||
setItem() {
|
||||
throw Object.assign(Error("blocked"), { name: "SecurityError" });
|
||||
},
|
||||
removeItem() {},
|
||||
},
|
||||
},
|
||||
),
|
||||
null,
|
||||
);
|
||||
console.log(
|
||||
"Draft guard: quota detection, replacement credit, probe cleanup and preservation of existing storage passed",
|
||||
);
|
||||
|
||||
const large = "data:image/png;base64," + "a".repeat(300000);
|
||||
const node = () => ({ type: "AdachiInlineMask", widgets_values: ["old.png", "mask", large, "crop", "region", "blend", "layer.png"], widgets_values_named: { image: "stale.png", mask_data: "stale-mask", source_data: large, edit_mode: "mask" } });
|
||||
const first = node(), nested = node();
|
||||
const graph = { nodes: [first, {type:"Other", widgets_values:[large]}], definitions: {subgraphs:[{nodes:[nested]}]} };
|
||||
const original = structuredClone(graph);
|
||||
let uploads = 0;
|
||||
assert.equal(await prepareInlineDraft(graph, { fits: g => g.nodes[0].widgets_values[2].length < 100 && g.definitions.subgraphs[0].nodes[0].widgets_values[2].length < 100, upload: async bytes => { assert.equal(bytes,large); return `source-${++uploads}.png`; } }),2);
|
||||
assert.equal(uploads,2);
|
||||
for (const n of [first,nested]) {
|
||||
assert.equal(n.widgets_values[2],"");
|
||||
assert.equal(n.widgets_values_named.source_data,"");
|
||||
assert.equal(n.widgets_values_named.image,n.widgets_values[0]);
|
||||
assert.equal(n.widgets_values_named.mask_data,"mask");
|
||||
assert.deepEqual(n.widgets_values.slice(3),["crop","region","blend","layer.png"]);
|
||||
}
|
||||
assert.deepEqual(graph.nodes[1],original.nodes[1]);
|
||||
for (const fits of [() => true, () => null]) {
|
||||
const g = {nodes:[node()]};
|
||||
assert.equal(await prepareInlineDraft(g,{fits,upload:()=>{throw Error("unexpected upload")}}),0);
|
||||
assert.equal(g.nodes[0].widgets_values[2],large);
|
||||
}
|
||||
const failure = {nodes:[node()]};
|
||||
await assert.rejects(prepareInlineDraft(failure,{fits:()=>false,upload:async()=>{throw Error("upload failed")}}),/upload failed/);
|
||||
assert.equal(failure.nodes[0].widgets_values[2],large);
|
||||
assert.equal(failure.nodes[0].widgets_values[0],"old.png");
|
||||
const namedOnly = {nodes:[{type:"AdachiInlineMask", widgets_values_named:{source_data:large,mask_data:"keep"}}]};
|
||||
await prepareInlineDraft(namedOnly,{fits:()=>false,upload:async()=>"named.png"});
|
||||
assert.equal(namedOnly.nodes[0].widgets_values_named.source_data,"");
|
||||
assert.equal(namedOnly.nodes[0].widgets_values_named.mask_data,"keep");
|
||||
const widgets=inlineWidgetNames.map((name,index)=>({name,value:`live-${index}`}));
|
||||
widgets.splice(1,0,{name:"unrelated",value:"untouched"});
|
||||
const snapshot={widgets_values:Array(8).fill("old"),widgets_values_named:{source_data:large,unrelated:"keep"}};
|
||||
syncInlineWidgets(snapshot,widgets);
|
||||
assert.equal(snapshot.widgets_values[3],"live-2");
|
||||
assert.equal(snapshot.widgets_values[1],"old");
|
||||
assert.equal(snapshot.widgets_values_named.source_data,"live-2");
|
||||
assert.equal(snapshot.widgets_values_named.unrelated,"keep");
|
||||
const arrayOnly={widgets_values:[]}; syncInlineWidgets(arrayOnly,widgets);
|
||||
assert.equal(arrayOnly.widgets_values_named,undefined);
|
||||
console.log("Draft preflight: root/subgraph sources, dual snapshots, unchanged masks/layers, fitting sources and failed uploads passed");
|
||||
@@ -0,0 +1,42 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { branchIsEnabled } from "../web/exclusive_routes.js";
|
||||
|
||||
const nodes = new Map(), links = new Map();
|
||||
const graph = {getNodeById: id => nodes.get(id), getLink: id => links.get(id)};
|
||||
let sequence = 0;
|
||||
function node(type, options = {}) {
|
||||
const value = {id: ++sequence, type, mode: 0, inputs: [], graph, ...options};
|
||||
nodes.set(value.id, value); return value;
|
||||
}
|
||||
function connect(source, target, name = "value") {
|
||||
const id = ++sequence;
|
||||
links.set(id, {origin_id: source.id, origin_slot: 0});
|
||||
target.inputs.push({name, link: id});
|
||||
}
|
||||
const a = node("CLIPTextEncode"), b = node("CLIPTextEncode");
|
||||
const sa = node("SetNode", {isVirtualNode: true}), sb = node("SetNode", {isVirtualNode: true});
|
||||
connect(a, sa); connect(b, sb);
|
||||
const ga = node("GetNode", {isVirtualNode: true, findSetter: () => sa});
|
||||
const gb = node("GetNode", {isVirtualNode: true, findSetter: () => sb});
|
||||
const switchNode = node("AdachiExclusiveSwitch");
|
||||
connect(ga, switchNode, "input_a"); connect(gb, switchNode, "input_b");
|
||||
const state = () => Number(branchIsEnabled(switchNode, "input_a")) | (Number(branchIsEnabled(switchNode, "input_b")) << 1);
|
||||
assert.equal(state(), 3, "both real branches enabled");
|
||||
sa.mode = 4; assert.equal(state(), 2, "ignored Set disables A despite enabled Get");
|
||||
sa.mode = 0; sb.mode = 4; assert.equal(state(), 1, "reverse ignored Set selects A");
|
||||
sb.mode = 0; a.mode = 4; assert.equal(state(), 2, "ignored encoder is found beyond Get/Set");
|
||||
a.mode = 0; b.mode = 2; assert.equal(state(), 1, "muted encoder is also disabled");
|
||||
b.mode = 0; ga.mode = 4; assert.equal(state(), 2, "ignored Get is disabled"); ga.mode = 0;
|
||||
const reroute = node("Reroute"); connect(a, reroute); sa.inputs = []; connect(reroute, sa);
|
||||
reroute.mode = 4; assert.equal(state(), 2, "ignored reroute behind Set is disabled");
|
||||
reroute.mode = 0; a.mode = 4; assert.equal(state(), 2, "enabled reroute follows ignored source"); a.mode = 0;
|
||||
sa.inputs = []; connect(ga, sa); assert.equal(state(), 2, "virtual routing cycle is disabled safely");
|
||||
ga.findSetter = () => null; assert.equal(state(), 2, "missing setter is disabled");
|
||||
const modern = node("VirtualRouter", {isVirtualNode: true, resolveVirtualOutput: () => ({node: a, slot: 0})});
|
||||
const routed = node("AdachiExclusiveSwitch"); connect(modern, routed, "input_a");
|
||||
assert.equal(branchIsEnabled(routed, "input_a"), true, "modern virtual output API is followed");
|
||||
a.mode = 4;
|
||||
assert.equal(branchIsEnabled(routed, "input_a"), false, "modern virtual output respects ignored source");
|
||||
assert.equal(branchIsEnabled({...switchNode, graph: null}, "input_a"), false);
|
||||
assert.equal(branchIsEnabled(switchNode, "not_connected"), false);
|
||||
console.log("Exclusive routing: Get/Set, bypass/mute, reroutes, cycles and missing inputs passed");
|
||||
@@ -0,0 +1,176 @@
|
||||
"""The selector must preserve arbitrary values and never silently prefer a branch."""
|
||||
import importlib.util
|
||||
import copy
|
||||
from pathlib import Path
|
||||
import unittest
|
||||
|
||||
import torch
|
||||
|
||||
spec = importlib.util.spec_from_file_location("exclusive_backend", Path(__file__).resolve().parents[1] / "backend.py")
|
||||
backend = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(backend)
|
||||
|
||||
|
||||
class ExclusiveSwitchTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.node = backend.AdachiExclusiveSwitch()
|
||||
|
||||
def workflow(self):
|
||||
return {"nodes": [
|
||||
{"id": 1, "type": "CLIPTextEncode", "mode": 4},
|
||||
{"id": 2, "type": "CLIPTextEncode", "mode": 0},
|
||||
{"id": 3, "type": "SetNode", "mode": 4, "widgets_values": ["p_0"], "inputs": [{"link": 1}]},
|
||||
{"id": 4, "type": "SetNode", "mode": 0, "widgets_values": ["p"], "inputs": [{"link": 2}]},
|
||||
{"id": 5, "type": "GetNode", "mode": 0, "widgets_values": ["p_0"]},
|
||||
{"id": 6, "type": "GetNode", "mode": 0, "widgets_values": ["p"]},
|
||||
{"id": 532, "type": "AdachiExclusiveSwitch", "inputs": [{"name": "input_a", "link": 3}, {"name": "input_b", "link": 4}]},
|
||||
], "links": [[1, 1, 0, 3, 0, "*"], [2, 2, 0, 4, 0, "*"], [3, 5, 0, 532, 0, "*"], [4, 6, 0, 532, 1, "*"]]}
|
||||
|
||||
def test_single_connected_branch_is_requested(self):
|
||||
self.assertEqual(self.node.check_lazy_status(input_a=None), ["input_a"])
|
||||
self.assertEqual(self.node.check_lazy_status(input_b=None), ["input_b"])
|
||||
|
||||
def test_bypassed_passthrough_branch_is_not_requested(self):
|
||||
self.assertEqual(self.node.check_lazy_status(input_a=None, input_b=None, active_inputs=1), ["input_a"])
|
||||
self.assertEqual(self.node.check_lazy_status(input_a=None, input_b=None, active_inputs=2), ["input_b"])
|
||||
a, b = object(), object()
|
||||
self.assertIs(self.node.select(a, b, 1)[0], a)
|
||||
self.assertIs(self.node.select(a, b, 2)[0], b)
|
||||
|
||||
def test_ambiguous_and_empty_inputs_fail(self):
|
||||
for inputs in ({}, {"input_a": None, "input_b": None}, {"active_inputs": 0}, {"active_inputs": 3}):
|
||||
with self.subTest(inputs=inputs), self.assertRaisesRegex(ValueError, "exactly one"):
|
||||
self.node.check_lazy_status(**inputs)
|
||||
|
||||
def test_missing_selected_input_and_none_data_fail(self):
|
||||
with self.assertRaisesRegex(ValueError, "has no input"):
|
||||
self.node.check_lazy_status(input_b=None, active_inputs=1)
|
||||
with self.assertRaisesRegex(ValueError, "returned no data"):
|
||||
self.node.select(input_a=None)
|
||||
|
||||
def test_falsey_values_and_tensors_are_forwarded_by_identity(self):
|
||||
for value in (False, 0, "", [], {}, torch.zeros(1, 4, 4, 3), torch.ones(1, 4, 4), {"samples": torch.zeros(1, 4, 8, 8)}, [[torch.zeros(1, 2, 3), {}]]):
|
||||
with self.subTest(type=type(value)):
|
||||
self.assertIs(self.node.select(input_a=value)[0], value)
|
||||
self.assertIs(self.node.select(input_b=value)[0], value)
|
||||
|
||||
def test_submitted_single_connection_overrides_stale_flags(self):
|
||||
for name in ("input_a", "input_b"):
|
||||
prompt = {"532": {"inputs": {name: ["source", 0], "active_inputs": 3}}}
|
||||
for stale in (-1, 0, 1, 2, 3):
|
||||
with self.subTest(name=name, stale=stale):
|
||||
args = {name: None, "active_inputs": stale, "prompt": prompt, "unique_id": "532"}
|
||||
self.assertEqual(self.node.check_lazy_status(**args), [name])
|
||||
value = object()
|
||||
args[name] = value
|
||||
self.assertIs(self.node.select(**args)[0], value)
|
||||
|
||||
def test_submitted_empty_or_ambiguous_connections_still_fail(self):
|
||||
for inputs in ({}, {"input_a": ["a", 0], "input_b": ["b", 0]}):
|
||||
with self.subTest(inputs=inputs), self.assertRaisesRegex(ValueError, "exactly one"):
|
||||
self.node.check_lazy_status(active_inputs=3, prompt={"1": {"inputs": inputs}}, unique_id="1")
|
||||
prompt = {"1": {"inputs": {"input_a": ["a", 0], "input_b": ["b", 0]}}}
|
||||
self.assertEqual(self.node.check_lazy_status(input_a=None, input_b=None, active_inputs=2, prompt=prompt, unique_id="1"), ["input_b"])
|
||||
|
||||
def test_dynamic_subgraph_connection_is_authoritative(self):
|
||||
class DynamicPrompt:
|
||||
def get_node(self, node_id):
|
||||
self_id = "subgraph:532"
|
||||
if node_id != self_id:
|
||||
raise KeyError(node_id)
|
||||
return {"inputs": {"input_b": ["nested-source", 0]}}
|
||||
self.assertEqual(self.node.check_lazy_status(input_b=None, active_inputs=3,
|
||||
prompt={}, dynprompt=DynamicPrompt(), unique_id="subgraph:532"), ["input_b"])
|
||||
|
||||
def test_enabled_gets_follow_ignored_set_and_encoder_in_workflow(self):
|
||||
workflow = self.workflow()
|
||||
args = dict(input_a=None, input_b=None, active_inputs=3, unique_id="532", extra_pnginfo={"workflow": workflow})
|
||||
self.assertEqual(self.node.check_lazy_status(**args), ["input_b"])
|
||||
for stale in range(-1, 4):
|
||||
self.assertEqual(self.node.check_lazy_status(**{**args, "active_inputs": stale}), ["input_b"])
|
||||
for node in workflow["nodes"][:4]:
|
||||
node["mode"] = 0 if node["mode"] == 4 else 4
|
||||
self.assertEqual(self.node.check_lazy_status(**args), ["input_a"])
|
||||
|
||||
def test_ignored_set_alone_or_encoder_alone_disables_route(self):
|
||||
for source_mode, set_mode in ((4, 0), (0, 4), (2, 0), (0, 2)):
|
||||
workflow = self.workflow()
|
||||
workflow["nodes"][0]["mode"] = source_mode
|
||||
workflow["nodes"][2]["mode"] = set_mode
|
||||
self.assertEqual(backend._workflow_exclusive_flags({"workflow": workflow}, "532"), 2)
|
||||
|
||||
def test_workflow_ambiguous_empty_cycle_missing_set_are_not_selected(self):
|
||||
workflow = self.workflow()
|
||||
for node in workflow["nodes"][:4]:
|
||||
node["mode"] = 0
|
||||
self.assertEqual(backend._workflow_exclusive_flags({"workflow": workflow}, "532"), 3)
|
||||
for node in workflow["nodes"][:4]:
|
||||
node["mode"] = 4
|
||||
self.assertEqual(backend._workflow_exclusive_flags({"workflow": workflow}, "532"), 0)
|
||||
workflow = self.workflow()
|
||||
workflow["nodes"][2]["mode"] = 0
|
||||
workflow["links"][0][1] = 5
|
||||
self.assertEqual(backend._workflow_exclusive_flags({"workflow": workflow}, "532"), 2)
|
||||
workflow["nodes"][4]["widgets_values"] = ["missing"]
|
||||
self.assertEqual(backend._workflow_exclusive_flags({"workflow": workflow}, "532"), 2)
|
||||
|
||||
def test_prompt_normalization_before_cache_preserves_workflow(self):
|
||||
workflow = self.workflow()
|
||||
saved = copy.deepcopy(workflow)
|
||||
request = {"prompt": {"532": {"class_type": "AdachiExclusiveSwitch", "inputs": {"input_a": ["a", 0], "input_b": ["b", 0], "active_inputs": 3}}},
|
||||
"extra_data": {"extra_pnginfo": {"workflow": workflow}}}
|
||||
self.assertIs(backend.normalize_exclusive_prompt(request), request)
|
||||
self.assertEqual(request["prompt"]["532"]["inputs"], {"input_b": ["b", 0], "active_inputs": 2})
|
||||
self.assertEqual(workflow, saved)
|
||||
plain = {"prompt": {"532": {"class_type": "AdachiExclusiveSwitch", "inputs": {"input_a": ["a", 0]}}}}
|
||||
original = copy.deepcopy(plain)
|
||||
backend.normalize_exclusive_prompt(plain)
|
||||
self.assertEqual(plain, original)
|
||||
|
||||
def test_scoped_subgraph_and_dictionary_links(self):
|
||||
child = self.workflow()
|
||||
child["id"] = "child"
|
||||
child["links"] = [dict(zip(("id", "origin_id", "origin_slot", "target_id", "target_slot", "type"), link)) for link in child["links"]]
|
||||
workflow = {"nodes": [{"id": 349, "type": "child"}], "definitions": {"subgraphs": [child]}}
|
||||
self.assertEqual(backend._workflow_exclusive_flags({"workflow": workflow}, "349:532"), 2)
|
||||
self.assertIsNone(backend._workflow_exclusive_flags({"workflow": workflow}, "532"))
|
||||
|
||||
def test_missing_selected_link_is_restored_through_get_set(self):
|
||||
workflow = self.workflow()
|
||||
request = {"prompt": {"2": {"class_type": "CLIPTextEncode", "inputs": {}},
|
||||
"532": {"class_type": "AdachiExclusiveSwitch", "inputs": {"active_inputs": 0}}},
|
||||
"extra_data": {"extra_pnginfo": {"workflow": workflow}}}
|
||||
backend.normalize_exclusive_prompt(request)
|
||||
self.assertEqual(request["prompt"]["532"]["inputs"], {"active_inputs": 2, "input_b": ["2", 0]})
|
||||
|
||||
def test_missing_subgraph_output_link_is_restored_to_flattened_node(self):
|
||||
workflow = {"nodes": [
|
||||
{"id": 349, "type": "child", "mode": 0},
|
||||
{"id": 521, "type": "CLIPTextEncode", "mode": 4},
|
||||
{"id": 532, "type": "AdachiExclusiveSwitch", "inputs": [{"name": "input_a", "link": 1}, {"name": "input_b", "link": 2}]},
|
||||
], "links": [[1, 349, 2, 532, 0, "CONDITIONING"], [2, 521, 0, 532, 1, "CONDITIONING"]],
|
||||
"definitions": {"subgraphs": [{"id": "child", "nodes": [{"id": 412, "type": "CLIPTextEncode", "mode": 0}],
|
||||
"outputs": [{"linkIds": []}, {"linkIds": []}, {"linkIds": [2019]}],
|
||||
"links": [{"id": 2019, "origin_id": 412, "origin_slot": 0, "target_id": -20, "target_slot": 2}]}]}}
|
||||
request = {"prompt": {"349:412": {"class_type": "CLIPTextEncode", "inputs": {}},
|
||||
"532": {"class_type": "AdachiExclusiveSwitch", "inputs": {"active_inputs": 1}}},
|
||||
"extra_data": {"extra_pnginfo": {"workflow": workflow}}}
|
||||
saved = copy.deepcopy(workflow)
|
||||
backend.normalize_exclusive_prompt(request)
|
||||
self.assertEqual(request["prompt"]["532"]["inputs"], {"active_inputs": 1, "input_a": ["349:412", 0]})
|
||||
self.assertEqual(workflow, saved)
|
||||
# Do not invent a source that was never submitted, or use a mismatched
|
||||
# node type that happens to have the same execution ID.
|
||||
for source in (None, {"class_type": "OtherNode", "inputs": {}}):
|
||||
bad = copy.deepcopy(request)
|
||||
bad["prompt"]["532"]["inputs"].pop("input_a")
|
||||
if source is None:
|
||||
bad["prompt"].pop("349:412")
|
||||
else:
|
||||
bad["prompt"]["349:412"] = source
|
||||
backend.normalize_exclusive_prompt(bad)
|
||||
self.assertNotIn("input_a", bad["prompt"]["532"]["inputs"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,134 @@
|
||||
"""Regression coverage for image models using single-frame video-derived VAEs."""
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import types
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
|
||||
spec = importlib.util.spec_from_file_location("vae_format_backend", Path(__file__).resolve().parents[1] / "backend.py")
|
||||
backend = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(backend)
|
||||
|
||||
|
||||
class VideoDerivedVAE:
|
||||
latent_dim = 3
|
||||
downscale_ratio = (lambda t: (t + 3) // 4, 8, 8)
|
||||
|
||||
def __init__(self):
|
||||
self.encoded_batches = []
|
||||
|
||||
def spacial_compression_encode(self):
|
||||
return 8
|
||||
|
||||
def encode(self, pixels):
|
||||
self.encoded_batches.append(pixels.shape[0])
|
||||
# Like Wan/Qwen VAE, an IMAGE batch would otherwise become time.
|
||||
frames = F.interpolate(pixels.mean(-1)[:, None], scale_factor=1 / 8, mode="bilinear", align_corners=False)
|
||||
return frames.permute(1, 0, 2, 3)[None].repeat(1, 16, 1, 1, 1)
|
||||
|
||||
def decode(self, samples):
|
||||
image = F.interpolate(samples[:, :1, 0], scale_factor=8, mode="nearest")
|
||||
return image.repeat(1, 3, 1, 1).permute(0, 2, 3, 1)[:, None]
|
||||
|
||||
|
||||
class ImageVAEFormatTests(unittest.TestCase):
|
||||
def inputs(self):
|
||||
image = torch.stack([torch.full((64, 64, 3), .2), torch.full((64, 64, 3), .8)])
|
||||
masks = torch.zeros(2, 64, 64)
|
||||
masks[0, :, :32] = 1
|
||||
masks[1, :, 32:] = 1
|
||||
return image, masks
|
||||
|
||||
def test_5d_latents_preserve_batch_masks_compositing_and_variants(self):
|
||||
for area in ("whole_image", "only_masked"):
|
||||
with self.subTest(area=area):
|
||||
image, masks = self.inputs()
|
||||
vae, captured = VideoDerivedVAE(), []
|
||||
def sample(*args, **kwargs):
|
||||
captured.append(args[8])
|
||||
return (args[8],)
|
||||
with patch.dict(sys.modules, {"nodes": types.SimpleNamespace(common_ksampler=sample)}):
|
||||
result, crop, mask = backend.AdachiWebUIInpaint().sample(None, [], [], vae, image, masks,
|
||||
width=64, height=64, area=area, mask_blur=0, batch_size=2)
|
||||
self.assertEqual(vae.encoded_batches, [1, 1, 1, 1])
|
||||
self.assertEqual(captured[0]["samples"].shape, (4, 16, 1, 8, 8))
|
||||
self.assertEqual(captured[0]["noise_mask"].shape, (4, 1, 1, 8, 8))
|
||||
self.assertTrue(torch.allclose(captured[0]["samples"].mean((1, 2, 3, 4)), torch.tensor([.2, .2, .8, .8])))
|
||||
originals, masks = image.repeat_interleave(2, 0), masks.repeat_interleave(2, 0)
|
||||
self.assertEqual(result.shape, originals.shape)
|
||||
self.assertEqual(crop.shape, (4, 64, 64, 3))
|
||||
self.assertEqual(mask.shape, (4, 64, 64))
|
||||
self.assertTrue(torch.equal(result[masks == 0], originals[masks == 0]))
|
||||
|
||||
def test_5d_noise_and_zero_fill_only_modify_masked_latents(self):
|
||||
image, masks = self.inputs()
|
||||
captured = []
|
||||
def sample(*args, **kwargs):
|
||||
captured.append(args[8])
|
||||
return (args[8],)
|
||||
with patch.dict(sys.modules, {"nodes": types.SimpleNamespace(common_ksampler=sample)}):
|
||||
for fill in ("latent_noise", "latent_noise", "latent_nothing"):
|
||||
backend.AdachiWebUIInpaint().sample(None, [], [], VideoDerivedVAE(), image, masks,
|
||||
width=64, height=64, area="whole_image", mask_blur=0, fill=fill, seed=42)
|
||||
self.assertTrue(torch.equal(captured[0]["samples"], captured[1]["samples"]))
|
||||
for latent in captured:
|
||||
protected = (latent["noise_mask"] == 0).expand_as(latent["samples"])
|
||||
expected = torch.tensor([.2, .8])[:, None, None, None, None].expand_as(latent["samples"])
|
||||
self.assertTrue(torch.allclose(latent["samples"][protected], expected[protected]))
|
||||
selected = (captured[2]["noise_mask"] == 1).expand_as(captured[2]["samples"])
|
||||
self.assertTrue(torch.equal(captured[2]["samples"][selected], torch.zeros_like(captured[2]["samples"][selected])))
|
||||
self.assertFalse(torch.equal(captured[0]["samples"][0], captured[0]["samples"][1]))
|
||||
|
||||
def test_unknown_vae_wrapper_recovers_independent_batch(self):
|
||||
vae = VideoDerivedVAE()
|
||||
wrapper = types.SimpleNamespace(encode=vae.encode)
|
||||
samples = backend._encode_still_images(wrapper, self.inputs()[0])
|
||||
self.assertEqual(samples.shape, (2, 16, 1, 8, 8))
|
||||
self.assertEqual(vae.encoded_batches, [2, 1, 1])
|
||||
|
||||
def test_native_inpaint_conditioning_keeps_5d_batch_axis(self):
|
||||
image, masks = self.inputs()
|
||||
original_meta = {"marker": "retained"}
|
||||
conditioning = [[torch.zeros(1, 2, 3), original_meta]]
|
||||
class Native:
|
||||
def encode(self, positive, negative, pixels, vae, mask, noise_mask):
|
||||
metadata = dict(original_meta, concat_latent_image=vae.encode(pixels), concat_mask=mask[:, None])
|
||||
return [[positive[0][0], metadata]], [[negative[0][0], metadata]], {"samples": vae.encode(pixels), "native_field": True}
|
||||
def sample(*args, **kwargs):
|
||||
self.assertEqual(args[6][0][1]["concat_mask"].shape, (2, 1, 1, 64, 64))
|
||||
self.assertEqual(args[6][0][1]["concat_latent_image"].shape, (2, 16, 1, 8, 8))
|
||||
self.assertTrue(args[8]["native_field"])
|
||||
return (args[8],)
|
||||
with patch.dict(sys.modules, {"nodes": types.SimpleNamespace(common_ksampler=sample, InpaintModelConditioning=Native)}):
|
||||
backend.AdachiWebUIInpaint().sample(None, conditioning, conditioning, VideoDerivedVAE(), image, masks,
|
||||
width=64, height=64, mask_blur=0, inpaint_model=True)
|
||||
self.assertEqual(original_meta, {"marker": "retained"})
|
||||
|
||||
def test_refiner_preserves_single_frame_shape(self):
|
||||
image, masks = self.inputs()
|
||||
calls = []
|
||||
def sample(*args, **kwargs):
|
||||
calls.append(args[8]["samples"].shape)
|
||||
return (args[8],)
|
||||
with patch.dict(sys.modules, {"nodes": types.SimpleNamespace(common_ksampler=sample)}):
|
||||
backend.AdachiWebUIInpaint().sample(None, [], [], VideoDerivedVAE(), image, masks, refiner_model=object(),
|
||||
width=64, height=64, mask_blur=0)
|
||||
self.assertEqual(calls, [(2, 16, 1, 8, 8)] * 2)
|
||||
|
||||
def test_actual_video_or_invalid_vae_outputs_fail_explicitly(self):
|
||||
for samples in (torch.zeros(1, 16, 2, 8, 8), torch.zeros(1, 8, 8), "bad"):
|
||||
with self.subTest(type=type(samples)), self.assertRaises(ValueError):
|
||||
backend._check_image_latents(samples, 1)
|
||||
with self.assertRaisesRegex(ValueError, "batch"):
|
||||
backend._check_image_latents(torch.zeros(1, 4, 8, 8), 2)
|
||||
vae = types.SimpleNamespace(decode=lambda latent: torch.zeros(1, 2, 64, 64, 3))
|
||||
with self.assertRaisesRegex(ValueError, "multiple frames"):
|
||||
backend._decode_still_images(vae, torch.zeros(1, 16, 1, 8, 8), 1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,11 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import {removeLegacyFeedback} from '../web/legacy_feedback.js';
|
||||
const make=()=>({nodes:[{id:1,type:'AdachiInlineMask',inputs:[{name:'result',link:10},{name:'image',link:11}],outputs:[]},{id:2,type:'Source',inputs:[],outputs:[{links:[10,11]}]}],links:[[10,2,0,1,0,'IMAGE'],[11,2,0,1,1,'STRING']]});
|
||||
const graph=make();graph.definitions={subgraphs:[make()]};removeLegacyFeedback(graph);
|
||||
for(const g of [graph,...graph.definitions.subgraphs]){
|
||||
assert.deepEqual(g.nodes[0].inputs,[{name:'image',link:11}]);assert.deepEqual(g.links,[[11,2,0,1,0,'STRING']]);assert.deepEqual(g.nodes[1].outputs[0].links,[11]);
|
||||
}
|
||||
removeLegacyFeedback(graph);assert.equal(graph.links.length,1);
|
||||
const modern=make();modern.links=modern.links.map(([id,origin_id,origin_slot,target_id,target_slot,type])=>({id,origin_id,origin_slot,target_id,target_slot,type}));removeLegacyFeedback(modern);assert.equal(modern.links.length,1);assert.equal(modern.links[0].target_slot,0);
|
||||
const orphan=make();orphan.nodes[0].inputs=[{name:'image',link:null}];removeLegacyFeedback(orphan);assert.equal(orphan.links.length,0);
|
||||
console.log('Legacy feedback migration: tuple/object links, slot reindexing, nested graphs, orphan cleanup and idempotence passed');
|
||||
+61
-64
@@ -1,5 +1,5 @@
|
||||
/* Original hover-comparison UI, MIT licensed. */
|
||||
import { registerImageWheel } from "./wheel_gestures.js";
|
||||
import { T } from "./i18n.js";
|
||||
const element = (tag, className, text) => {
|
||||
const node = document.createElement(tag);
|
||||
if (className) node.className = className;
|
||||
@@ -9,7 +9,7 @@ const element = (tag, className, text) => {
|
||||
const imageFrom = url => new Promise((resolve, reject) => {
|
||||
const image = new Image();
|
||||
image.onload = () => resolve(image);
|
||||
image.onerror = () => reject(new Error("预览已过期或无法加载,请重新运行 / Preview unavailable; run the workflow again"));
|
||||
image.onerror = () => reject(new Error(T("Preview unavailable; run the workflow again")));
|
||||
image.src = url;
|
||||
});
|
||||
|
||||
@@ -18,61 +18,52 @@ export class ImageCompareView {
|
||||
this.options = options;
|
||||
this.root = element("div", "dd-inpaint dd-comparer");
|
||||
this.originals = []; this.results = []; this.index = 0;
|
||||
this.zoom = 1; this.pan = { x: 0, y: 0 }; this.split = .5;
|
||||
this.split = .5;
|
||||
this.version = 0; this.ready = false;
|
||||
this.dimensionsLabel = element("span", "dd-dimensions");
|
||||
const toolbar = element("div", "dd-row dd-compare-toolbar");
|
||||
toolbar.append(element("span", "dd-compare-label", "结果"));
|
||||
this.resultSelect = element("select"); this.resultSelect.setAttribute("aria-label", "选择重绘结果 / Choose result");
|
||||
toolbar.append(element("span", "dd-compare-label", T("Result")));
|
||||
this.resultSelect = element("select"); this.resultSelect.setAttribute("aria-label", T("Choose result"));
|
||||
this.resultSelect.onchange = () => { this.index = Number(this.resultSelect.value); this.options.onSelect?.(this.index); this.loadSelected(); };
|
||||
toolbar.append(this.resultSelect, this.dimensionsLabel);
|
||||
const spacer = element("span", "dd-spacer"); toolbar.append(spacer);
|
||||
const fit = element("button", "", "适应"); fit.type = "button";
|
||||
fit.onclick = () => { this.zoom = 1; this.pan = { x: 0, y: 0 }; this.schedule(); }; toolbar.append(fit);
|
||||
const fit = element("button", "", T("Fit")); fit.type = "button";
|
||||
fit.onclick = event => { event.preventDefault(); event.stopPropagation(); this.schedule(); }; toolbar.append(fit);
|
||||
this.stage = element("div", "dd-stage dd-compare-stage");
|
||||
this.canvas = document.createElement("canvas"); this.canvas.tabIndex = 0;
|
||||
this.canvas.setAttribute("aria-label", "左重绘结果、右原图,移动鼠标竖线对比 / Result left, original right; hover to compare");
|
||||
this.canvas.setAttribute("aria-label", T("Result left, original right; hover to compare"));
|
||||
this.canvas.oncontextmenu = event => event.preventDefault();
|
||||
this.canvas.addEventListener("pointerenter", event => { this.hovered = true; this.move(event); this.schedule(); });
|
||||
this.canvas.addEventListener("pointerleave", () => { this.hovered = false; this.schedule(); });
|
||||
this.stage.append(this.canvas);
|
||||
this.empty = element("div", "dd-empty", "连接原图与重绘结果,然后运行工作流"); this.stage.append(this.empty);
|
||||
this.divider = element("div");
|
||||
Object.assign(this.divider.style, { position: "absolute", background: "#ffffffb3", pointerEvents: "none" });
|
||||
this.divider.hidden = true;
|
||||
this.stage.append(this.canvas, this.divider);
|
||||
this.empty = element("div", "dd-empty", T("Connect an original image and a result, then run the workflow")); this.stage.append(this.empty);
|
||||
const adoption = element("div", "dd-row dd-adoption");
|
||||
adoption.append(element("span", "dd-compare-label", "回填到"));
|
||||
this.targetSelect = element("select"); this.targetSelect.setAttribute("aria-label", "接收结果的内联蒙版 / Target inline editor");
|
||||
adoption.append(element("span", "dd-compare-label", T("Adopt into")));
|
||||
this.targetSelect = element("select"); this.targetSelect.setAttribute("aria-label", T("Target inline editor"));
|
||||
this.targetSelect.onfocus = () => this.refreshTargets();
|
||||
this.targetSelect.onchange = () => { this.manualTarget = true; this.updateButton(); };
|
||||
adoption.append(this.targetSelect);
|
||||
this.adoptButton = element("button", "dd-primary", "采用此结果"); this.adoptButton.type = "button";
|
||||
this.adoptButton = element("button", "dd-primary", T("Adopt this result")); this.adoptButton.type = "button";
|
||||
this.adoptButton.onclick = () => this.adopt(); adoption.append(this.adoptButton);
|
||||
this.message = element("div", "dd-status", "鼠标移动竖线对比 · 滚轮缩放 · 中键拖动");
|
||||
this.message = element("div", "dd-status", T("Result left, original right; hover to compare"));
|
||||
this.message.hidden = true; this.message.setAttribute("role", "alert");
|
||||
this.root.append(this.stage, toolbar, adoption, this.message);
|
||||
this.canvas.addEventListener("pointermove", event => this.move(event));
|
||||
this.canvas.addEventListener("pointerdown", event => {
|
||||
if (!this.ready) return;
|
||||
if (!this.ready || event.button !== 0) return;
|
||||
event.preventDefault(); event.stopPropagation(); this.canvas.focus({ preventScroll: true });
|
||||
if (event.button === 1 || this.space) {
|
||||
this.drag = { id: event.pointerId, x: event.clientX, y: event.clientY, pan: { ...this.pan } };
|
||||
this.canvas.setPointerCapture(event.pointerId);
|
||||
} else this.move(event);
|
||||
this.move(event);
|
||||
});
|
||||
const finish = event => {
|
||||
if (!this.drag || this.drag.id !== event.pointerId) return;
|
||||
const id = this.drag.id; this.drag = null;
|
||||
if (this.canvas.hasPointerCapture(id)) this.canvas.releasePointerCapture(id);
|
||||
};
|
||||
for (const name of ["pointerup", "pointercancel", "lostpointercapture"]) this.canvas.addEventListener(name, finish);
|
||||
this.stopWheelCapture = registerImageWheel(this.canvas, () => this.ready, event => this.wheel(event), options.onGraphWheel);
|
||||
this.canvas.addEventListener("wheel", event => this.wheel(event), { passive: false });
|
||||
this.canvas.addEventListener("keydown", event => {
|
||||
if (event.code === "Space") { event.preventDefault(); event.stopPropagation(); this.space = true; }
|
||||
else if (["ArrowLeft", "ArrowRight"].includes(event.key)) {
|
||||
if (["ArrowLeft", "ArrowRight"].includes(event.key)) {
|
||||
event.preventDefault(); event.stopPropagation();
|
||||
this.split = Math.max(0, Math.min(1, this.split + (event.key === "ArrowRight" ? .02 : -.02))); this.schedule();
|
||||
}
|
||||
});
|
||||
this.canvas.addEventListener("keyup", event => { if (event.code === "Space") this.space = false; });
|
||||
this.canvas.addEventListener("blur", () => { this.space = false; });
|
||||
this.observer = new ResizeObserver(() => this.schedule()); this.observer.observe(this.stage);
|
||||
this.refreshTargets(); this.updateButton();
|
||||
}
|
||||
@@ -83,7 +74,7 @@ export class ImageCompareView {
|
||||
const selected = this.targetSelect.value;
|
||||
const { editors = [], preferred = "" } = this.options.getTargets?.() || {};
|
||||
this.targetSelect.replaceChildren();
|
||||
const placeholder = element("option", "", "选择内联蒙版"); placeholder.value = ""; this.targetSelect.append(placeholder);
|
||||
const placeholder = element("option", "", T("Select an inline mask")); placeholder.value = ""; this.targetSelect.append(placeholder);
|
||||
for (const editor of editors) {
|
||||
const option = element("option", "", editor.label); option.value = String(editor.id); this.targetSelect.append(option);
|
||||
}
|
||||
@@ -92,7 +83,7 @@ export class ImageCompareView {
|
||||
this.updateButton();
|
||||
}
|
||||
|
||||
updateButton() { this.adoptButton.disabled = !this.ready || !this.targetSelect.value || !!this.busy; this.adoptButton.textContent = this.busy ? "采用中…" : "采用此结果"; }
|
||||
updateButton() { this.adoptButton.disabled = !this.ready || !this.targetSelect.value || !!this.busy; this.adoptButton.textContent = this.busy ? T("Adopting…") : T("Adopt this result"); }
|
||||
|
||||
async setData(data, index = this.index) {
|
||||
this.originals = Array.isArray(data?.originals) ? data.originals : [];
|
||||
@@ -129,46 +120,31 @@ export class ImageCompareView {
|
||||
this.refreshTargets();
|
||||
if (!this.ready || !this.targetSelect.value || this.busy) return;
|
||||
const target = this.targetSelect.value, result = this.results[this.index];
|
||||
this.busy = true; this.updateButton(); this.status("正在将结果设为新原图…");
|
||||
this.busy = true; this.updateButton(); this.status(T("Setting the result as the new source image…"));
|
||||
try {
|
||||
await this.options.onAdopt(target, result);
|
||||
if (!this.destroyed) this.status("已采用:回到内联蒙版,可继续涂抹重绘");
|
||||
if (!this.destroyed) this.status(T("Adopted: back in the inline mask, keep painting to inpaint again"));
|
||||
} catch (error) { if (!this.destroyed) this.status(error.message, true); }
|
||||
finally { this.busy = false; if (!this.destroyed) this.updateButton(); }
|
||||
}
|
||||
|
||||
transform() {
|
||||
const rect = this.canvas.getBoundingClientRect();
|
||||
if (this.viewport?.width && this.viewport?.height && rect.width && rect.height) {
|
||||
this.pan.x *= rect.width / this.viewport.width;
|
||||
this.pan.y *= rect.height / this.viewport.height;
|
||||
}
|
||||
this.viewport = { width: rect.width, height: rect.height };
|
||||
const scale = this.before ? Math.min(rect.width / this.before.width, rect.height / this.before.height) * this.zoom : 1;
|
||||
return { width: rect.width, height: rect.height, scale, x: (rect.width - (this.before?.width || 0) * scale) / 2 + this.pan.x, y: (rect.height - (this.before?.height || 0) * scale) / 2 + this.pan.y };
|
||||
const scale = this.before ? Math.min(rect.width / this.before.width, rect.height / this.before.height) : 1;
|
||||
return { width: rect.width, height: rect.height, scale, x: (rect.width - (this.before?.width || 0) * scale) / 2, y: (rect.height - (this.before?.height || 0) * scale) / 2 };
|
||||
}
|
||||
|
||||
position(event) { const rect = this.canvas.getBoundingClientRect(), t = this.transform(); return { x: (event.clientX - rect.left - t.x) / t.scale, y: (event.clientY - rect.top - t.y) / t.scale }; }
|
||||
|
||||
wheel(event) {
|
||||
if (!this.ready) return;
|
||||
event.preventDefault(); event.stopPropagation();
|
||||
const before = this.position(event), rect = this.canvas.getBoundingClientRect();
|
||||
this.zoom = Math.max(.1, Math.min(32, this.zoom * Math.exp(-event.deltaY * .0015)));
|
||||
const t = this.transform();
|
||||
this.pan.x += event.clientX - rect.left - (t.x + before.x * t.scale);
|
||||
this.pan.y += event.clientY - rect.top - (t.y + before.y * t.scale);
|
||||
this.schedule();
|
||||
this.options.onGraphWheel?.(event);
|
||||
}
|
||||
|
||||
move(event) {
|
||||
if (!this.ready) return;
|
||||
this.hovered = true;
|
||||
if (this.drag) {
|
||||
event.preventDefault(); event.stopPropagation();
|
||||
this.pan.x = this.drag.pan.x + event.clientX - this.drag.x;
|
||||
this.pan.y = this.drag.pan.y + event.clientY - this.drag.y;
|
||||
} else this.split = Math.max(0, Math.min(1, this.position(event).x / this.before.width));
|
||||
this.split = Math.max(0, Math.min(1, this.position(event).x / this.before.width));
|
||||
this.schedule();
|
||||
}
|
||||
|
||||
@@ -177,26 +153,47 @@ export class ImageCompareView {
|
||||
render() {
|
||||
const t = this.transform(), ratio = Math.min(devicePixelRatio || 1, 2);
|
||||
if (!t.width || !t.height) return;
|
||||
const width = Math.round(t.width * ratio), height = Math.round(t.height * ratio);
|
||||
// Graph zoom changes the screen rect, not the amount of source detail.
|
||||
// Never allocate a huge upscaled bitmap just to magnify existing pixels.
|
||||
const rasterRatio = Math.min(ratio, this.ready ? 1 / t.scale : ratio,
|
||||
8192 / t.width, 8192 / t.height, Math.sqrt(16 * 1024 * 1024 / (t.width * t.height)));
|
||||
const width = Math.max(1, Math.round(t.width * rasterRatio)), height = Math.max(1, Math.round(t.height * rasterRatio));
|
||||
if (this.canvas.width !== width || this.canvas.height !== height) { this.canvas.width = width; this.canvas.height = height; }
|
||||
const ctx = this.canvas.getContext("2d");
|
||||
ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.clearRect(0, 0, width, height);
|
||||
if (!this.ready) return;
|
||||
ctx.setTransform(t.scale * ratio, 0, 0, t.scale * ratio, t.x * ratio, t.y * ratio);
|
||||
ctx.drawImage(this.after, 0, 0, this.before.width, this.before.height);
|
||||
if (!this.hovered) return;
|
||||
ctx.setTransform(1, 0, 0, 1, 0, 0);
|
||||
this.divider.hidden = !this.ready || !this.hovered;
|
||||
if (!this.ready) { ctx.clearRect(0, 0, width, height); this.lastPaint = null; return; }
|
||||
const split = this.split * this.before.width;
|
||||
const lineX = Math.round((t.x + split * t.scale) * rasterRatio) + .5;
|
||||
if (this.hovered) {
|
||||
const screenScale = t.width / this.canvas.clientWidth || 1;
|
||||
Object.assign(this.divider.style, {
|
||||
left: `${(t.x + split * t.scale) / screenScale}px`, top: `${t.y / screenScale}px`,
|
||||
height: `${this.before.height * t.scale / screenScale}px`, width: `${1 / screenScale}px`,
|
||||
});
|
||||
}
|
||||
const key = [this.version, width, height, t.scale * rasterRatio, t.x * rasterRatio, t.y * rasterRatio].join(":");
|
||||
const previous = this.lastPaint;
|
||||
ctx.save();
|
||||
// While hovering, pixels outside the old/new divider positions are
|
||||
// unchanged. Clip the redraw to that strip rather than repainting all.
|
||||
if (previous?.key === key && previous.hovered && this.hovered) {
|
||||
const left = Math.max(0, Math.floor(Math.min(previous.lineX, lineX)) - 2);
|
||||
const right = Math.min(width, Math.ceil(Math.max(previous.lineX, lineX)) + 2);
|
||||
ctx.beginPath(); ctx.rect(left, 0, right - left, height); ctx.clip();
|
||||
}
|
||||
ctx.clearRect(0, 0, width, height);
|
||||
ctx.setTransform(t.scale * rasterRatio, 0, 0, t.scale * rasterRatio, t.x * rasterRatio, t.y * rasterRatio);
|
||||
ctx.drawImage(this.after, 0, 0, this.before.width, this.before.height);
|
||||
this.lastPaint = { key, hovered: this.hovered, lineX };
|
||||
if (!this.hovered) { ctx.restore(); return; }
|
||||
ctx.save(); ctx.beginPath(); ctx.rect(split, 0, this.before.width - split, this.before.height); ctx.clip();
|
||||
ctx.drawImage(this.before, 0, 0); ctx.restore();
|
||||
ctx.setTransform(1, 0, 0, 1, 0, 0);
|
||||
const lineX = Math.round((t.x + split * t.scale) * ratio) + .5;
|
||||
ctx.beginPath(); ctx.moveTo(lineX, t.y * ratio); ctx.lineTo(lineX, (t.y + this.before.height * t.scale) * ratio);
|
||||
ctx.strokeStyle = "#ffffffb3"; ctx.lineWidth = 1; ctx.stroke();
|
||||
ctx.restore();
|
||||
}
|
||||
|
||||
destroy() {
|
||||
this.destroyed = true; ++this.version; cancelAnimationFrame(this.frame); this.observer.disconnect();
|
||||
this.stopWheelCapture();
|
||||
this.before = this.after = null; this.canvas.width = this.canvas.height = 0; this.root.remove();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
// Store one matching original per result, including batches from older workflows.
|
||||
export function appendComparison(previous, incoming) {
|
||||
const pairs = data => {
|
||||
const originals = Array.isArray(data?.originals) ? data.originals : [];
|
||||
const results = Array.isArray(data?.results) ? data.results : [];
|
||||
if (!originals.length || !results.length) return { originals: [], results: [] };
|
||||
const repetitions = results.length / originals.length;
|
||||
return {
|
||||
originals: results.map((_, index) => originals[Math.min(originals.length - 1, Math.floor(index / repetitions))]),
|
||||
results,
|
||||
};
|
||||
};
|
||||
const before = pairs(previous), next = pairs(incoming);
|
||||
const history = { originals: [], results: [] }, seen = new Set();
|
||||
for (const data of [before, next]) data.results.forEach((result, index) => {
|
||||
// Cached execution notifications can replay the same preview. Its file
|
||||
// identity is stable, while a genuinely new generation gets a new file.
|
||||
const key = typeof result === "object" && result !== null
|
||||
? JSON.stringify([result.type || "temp", result.subfolder || "", result.filename])
|
||||
: JSON.stringify(result);
|
||||
if (seen.has(key)) return;
|
||||
seen.add(key);
|
||||
history.originals.push(data.originals[index]); history.results.push(result);
|
||||
});
|
||||
return history;
|
||||
}
|
||||
+36
-10
@@ -1,7 +1,10 @@
|
||||
import { app } from "../../scripts/app.js";
|
||||
import { api } from "../../scripts/api.js";
|
||||
import { ImageCompareView } from "./compare.js";
|
||||
import { ImageCompareView } from "./compare.js?v=0.5.9";
|
||||
import { appendComparison } from "./compare_history.js?v=0.5.8";
|
||||
import { routeWheelOutsideImage } from "./wheel_routing.js";
|
||||
import { T } from "./i18n.js";
|
||||
import { bindWidgetToNodeWidth } from "./widget_layout.js?v=0.5.5";
|
||||
|
||||
function viewUrl(image) {
|
||||
const type = ["input", "output", "temp"].includes(image?.type) ? image.type : "temp";
|
||||
@@ -11,7 +14,7 @@ function viewUrl(image) {
|
||||
function targets(node) {
|
||||
const graph = node.graph;
|
||||
const editors = (graph?._nodes || []).filter(candidate => candidate.type === "AdachiInlineMask" && candidate.adachiUseResult)
|
||||
.map(candidate => ({ id: candidate.id, label: `${candidate.title || "内联蒙版"} #${candidate.id}` }));
|
||||
.map(candidate => ({ id: candidate.id, label: `${candidate.title || T("Inline Mask")} #${candidate.id}` }));
|
||||
const sourceLink = graph?.links?.[node.inputs?.find(input => input.name === "original")?.link];
|
||||
const queue = sourceLink ? [sourceLink.origin_id] : [], seen = new Set(), upstream = new Set();
|
||||
while (queue.length && seen.size < 256) {
|
||||
@@ -40,32 +43,55 @@ app.registerExtension({
|
||||
onSelect: index => { node.properties.adachi_result_index = index; },
|
||||
async onAdopt(id, image) {
|
||||
const target = node.graph?.getNodeById(id);
|
||||
if (!target?.adachiUseResult) throw new Error("找不到接收结果的内联蒙版节点");
|
||||
if (!target?.adachiUseResult) throw new Error(T("No inline mask node is available to receive the result"));
|
||||
const response = await api.fetchApi(`/view?${new URLSearchParams({ filename: image.filename, subfolder: image.subfolder || "", type: image.type || "temp" })}`);
|
||||
if (!response.ok) throw new Error("结果预览已过期,请重新运行工作流");
|
||||
if (!response.ok) throw new Error(T("Result preview expired; run the workflow again"));
|
||||
const blob = await response.blob();
|
||||
if (blob.size > 64 * 1024 * 1024) throw new Error("结果图片超过 64 MiB,请先缩小");
|
||||
await target.adachiUseResult(new File([blob], `adachi-result-${Date.now()}.png`, { type: "image/png" }));
|
||||
if (blob.size > 64 * 1024 * 1024) throw new Error(T("Result image exceeds 64 MiB; downscale it first"));
|
||||
await target.adachiUseResult(new File([blob], `adachi-result-${Date.now()}.png`, { type: "image/png" }), image.adachi_origin);
|
||||
// Adoption starts a new round. Keep the accepted image visible
|
||||
// as 1/1, then replace it with the next round's first outputs.
|
||||
const data = { originals: [image], results: [image] };
|
||||
node.properties.adachi_compare = data;
|
||||
node.properties.adachi_result_index = 0;
|
||||
node.properties.adachi_compare_new_round = true;
|
||||
await compare.setData(data, 0);
|
||||
app.graph?.change?.();
|
||||
},
|
||||
});
|
||||
node.adachiCompare = compare;
|
||||
const stopWheelRouting = routeWheelOutsideImage(compare.root, compare.canvas, () => compare.ready);
|
||||
const stopWheelRouting = routeWheelOutsideImage(compare.root, null, () => false);
|
||||
const widget = node.addDOMWidget("adachi_compare", "adachi_compare_view", compare.root, {
|
||||
serialize: false, hideOnZoom: false, getMinHeight: () => 420, getMaxHeight: () => 4096,
|
||||
});
|
||||
widget.serialize = false;
|
||||
bindWidgetToNodeWidth(node, widget, compare.root);
|
||||
const executed = node.onExecuted;
|
||||
node.onExecuted = function (output) {
|
||||
const result = executed?.apply(this, arguments);
|
||||
const data = { originals: output?.adachi_originals || [], results: output?.adachi_results || [] };
|
||||
if (!output?.adachi_originals?.length || !output?.adachi_results?.length) return result;
|
||||
const previous = node.properties.adachi_compare_new_round
|
||||
? appendComparison() : appendComparison(node.properties.adachi_compare);
|
||||
const data = appendComparison(previous, {
|
||||
originals: output.adachi_originals,
|
||||
results: output.adachi_results.map(image => output.adachi_origin?.[0]
|
||||
? {...image, adachi_origin:output.adachi_origin[0]} : image),
|
||||
});
|
||||
node.properties.adachi_compare = data;
|
||||
compare.setData(data, node.properties.adachi_result_index || 0);
|
||||
node.properties.adachi_compare_new_round = false;
|
||||
node.properties.adachi_result_index = data.results.length > previous.results.length
|
||||
? data.results.length - 1 : Math.max(0, Math.min(data.results.length - 1, node.properties.adachi_result_index || 0));
|
||||
compare.setData(data, node.properties.adachi_result_index);
|
||||
return result;
|
||||
};
|
||||
const configured = node.onConfigure;
|
||||
node.onConfigure = function () {
|
||||
const result = configured?.apply(this, arguments);
|
||||
if (node.properties.adachi_compare) compare.setData(node.properties.adachi_compare, node.properties.adachi_result_index || 0);
|
||||
if (node.properties.adachi_compare) {
|
||||
node.properties.adachi_compare = appendComparison(node.properties.adachi_compare);
|
||||
node.properties.adachi_result_index = Math.max(0, Math.min(node.properties.adachi_compare.results.length - 1, node.properties.adachi_result_index || 0));
|
||||
compare.setData(node.properties.adachi_compare, node.properties.adachi_result_index);
|
||||
}
|
||||
return result;
|
||||
};
|
||||
const removed = node.onRemoved;
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
export const CROP_PRESETS = [
|
||||
[1024, 1536],
|
||||
[512, 512],
|
||||
[768, 1024],
|
||||
[1024, 1024],
|
||||
[1536, 2048],
|
||||
[2048, 2048],
|
||||
];
|
||||
|
||||
export function cropAt(width, height, cropWidth, cropHeight, x, y) {
|
||||
if (
|
||||
![width, height, cropWidth, cropHeight, x, y].every(Number.isFinite) ||
|
||||
cropWidth < 32 ||
|
||||
cropHeight < 32 ||
|
||||
cropWidth % 32 ||
|
||||
cropHeight % 32 ||
|
||||
cropWidth > width ||
|
||||
cropHeight > height
|
||||
)
|
||||
return null;
|
||||
return {
|
||||
x: Math.max(0, Math.min(width - cropWidth, Math.floor(x))),
|
||||
y: Math.max(0, Math.min(height - cropHeight, Math.floor(y))),
|
||||
width: cropWidth,
|
||||
height: cropHeight,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
// Probe only our own temporary key. Existing ComfyUI drafts are never edited or deleted.
|
||||
export const inlineWidgetNames = [
|
||||
"image", "mask_data", "source_data", "edit_mode", "crop_state", "blend_data", "layer_image",
|
||||
];
|
||||
|
||||
// Some extensions also serialize a named snapshot. Keep it in step with the
|
||||
// actual widgets, otherwise a removed embedding can survive in that snapshot.
|
||||
export function syncInlineWidgets(data, widgets) {
|
||||
for (const name of inlineWidgetNames) {
|
||||
const index = widgets.findIndex((widget) => widget.name === name);
|
||||
if (index < 0) continue;
|
||||
if (Array.isArray(data.widgets_values)) data.widgets_values[index] = widgets[index].value;
|
||||
if (data.widgets_values_named && typeof data.widgets_values_named === "object")
|
||||
data.widgets_values_named[name] = widgets[index].value;
|
||||
}
|
||||
}
|
||||
|
||||
function inlineNodes(graph, seen = new Set()) {
|
||||
if (!graph || seen.has(graph)) return [];
|
||||
seen.add(graph);
|
||||
return [
|
||||
...(graph.nodes || []).filter((node) => node.type === "AdachiInlineMask"),
|
||||
...(graph.definitions?.subgraphs || []).flatMap((subgraph) => inlineNodes(subgraph, seen)),
|
||||
];
|
||||
}
|
||||
|
||||
// Called before graph configuration: native autosave must never see the large
|
||||
// source first, since a quota failure disables its storage for the entire tab.
|
||||
export async function prepareInlineDraft(graph, { fits, upload }) {
|
||||
const nodes = inlineNodes(graph);
|
||||
for (const node of nodes) {
|
||||
if (!Array.isArray(node.widgets_values)) continue;
|
||||
for (const [index, name] of inlineWidgetNames.entries()) {
|
||||
if (index < node.widgets_values.length && node.widgets_values_named)
|
||||
node.widgets_values_named[name] = node.widgets_values[index];
|
||||
}
|
||||
}
|
||||
const candidates = nodes.filter((node) => {
|
||||
const embedded = node.widgets_values?.[2] ?? node.widgets_values_named?.source_data;
|
||||
return typeof embedded === "string" && embedded.startsWith("data:") && embedded.length >= 256 * 1024;
|
||||
}).sort((a, b) => (b.widgets_values?.[2] ?? b.widgets_values_named.source_data).length - (a.widgets_values?.[2] ?? a.widgets_values_named.source_data).length);
|
||||
let converted = 0;
|
||||
for (const node of candidates) {
|
||||
if (fits(graph) !== false) break;
|
||||
const embedded = node.widgets_values?.[2] ?? node.widgets_values_named.source_data;
|
||||
const filename = await upload(embedded);
|
||||
if (typeof filename !== "string" || !filename) throw new Error("Source upload returned no filename");
|
||||
// Commit only after a successful exact upload. All masks and layers stay intact.
|
||||
if (Array.isArray(node.widgets_values)) {
|
||||
node.widgets_values[0] = filename;
|
||||
node.widgets_values[2] = "";
|
||||
}
|
||||
if (node.widgets_values_named) {
|
||||
node.widgets_values_named.image = filename;
|
||||
node.widgets_values_named.source_data = "";
|
||||
}
|
||||
converted++;
|
||||
}
|
||||
return converted;
|
||||
}
|
||||
|
||||
export function canStoreDraft(
|
||||
graph,
|
||||
{ path = "", workspace = "personal", storage } = {},
|
||||
) {
|
||||
try {
|
||||
storage ??= globalThis.localStorage;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
const serialized = JSON.stringify({
|
||||
data: JSON.stringify(graph),
|
||||
updatedAt: Date.now(),
|
||||
});
|
||||
let credit = 0;
|
||||
try {
|
||||
if (path) {
|
||||
const index = JSON.parse(
|
||||
storage.getItem(`Comfy.Workflow.DraftIndex.v2:${workspace}`) || "null",
|
||||
);
|
||||
if (
|
||||
Object.values(index?.entries || {}).some((entry) => entry.path === path)
|
||||
) {
|
||||
// Standard FNV-1a path hash used by the current ComfyUI draft format.
|
||||
let hash = 2166136261;
|
||||
for (let i = 0; i < path.length; i++)
|
||||
hash = Math.imul(hash ^ path.charCodeAt(i), 16777619);
|
||||
const key = `Comfy.Workflow.Draft.v2:${workspace}:${(hash >>> 0).toString(16).padStart(8, "0")}`;
|
||||
credit = storage.getItem(key)?.length || 0;
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
/* Unknown metadata: a conservative probe still preserves all existing drafts. */
|
||||
}
|
||||
const needed = Math.max(0, serialized.length - credit);
|
||||
if (!needed) return true;
|
||||
const key = `Adachi.DraftProbe:${crypto.randomUUID()}`;
|
||||
try {
|
||||
storage.setItem(key, " ".repeat(needed));
|
||||
return true;
|
||||
} catch (error) {
|
||||
return error?.name === "QuotaExceededError" ? false : null;
|
||||
} finally {
|
||||
try {
|
||||
storage.removeItem(key);
|
||||
} catch {
|
||||
/* Storage may be unavailable. */
|
||||
}
|
||||
}
|
||||
}
|
||||
+47
-1
@@ -56,7 +56,7 @@
|
||||
.dd-inpaint .dd-param-number-label { display: flex; align-items: center; justify-content: space-between; gap: 5px; color: var(--dd-muted); font-size: 11px; }
|
||||
.dd-inpaint .dd-param-field input[type="number"] { width: 86px; min-width: 0; padding: 4px 5px; border: 1px solid var(--dd-line); border-radius: 4px; background: var(--dd-panel); color: var(--dd-text); font: inherit; font-variant-numeric: tabular-nums; }
|
||||
.dd-inpaint .dd-param-field select, .dd-inpaint .dd-param-header select { min-width: 0; max-width: 100%; color: var(--dd-text); background: var(--dd-panel); border: 1px solid var(--dd-line); border-radius: 4px; padding: 5px; font: inherit; }
|
||||
.dd-inpaint .dd-param-field:has(input[aria-label="随机种子"]) input { width: 130px; }
|
||||
.dd-inpaint .dd-param-field:has(input[aria-label="Seed"]) input { width: 130px; }
|
||||
.dd-inpaint .dd-param-resolution { display: flex; justify-content: space-between; align-items: center; gap: 10px; }
|
||||
.dd-inpaint .dd-param-resolution button { font-size: 11px; }
|
||||
.dd-inpaint .dd-param-advanced { border-top: 1px solid var(--dd-line); padding-top: 7px; }
|
||||
@@ -82,6 +82,7 @@
|
||||
.dd-inline-minimal > .dd-resize-handle { position: absolute; z-index: 2; bottom: 0; width: 100%; height: 5px; min-height: 5px; border: 0; color: transparent; background: transparent; }
|
||||
.dd-inline-minimal > .dd-resize-handle:hover { background: #ffc07966; }
|
||||
.dd-inline-minimal > .dd-status:not([hidden]) { position: absolute; bottom: 6px; left: 0; right: 0; background: #20242bee; }
|
||||
.dd-inline-minimal.dd-crop-mode > .dd-status:not([hidden]) { bottom: 40px; }
|
||||
.dd-editor-controls { height: auto; flex: 0 0 auto; border: 0; border-radius: 0; background: transparent; overflow: visible; }
|
||||
.dd-editor-controls .dd-source-info { justify-content: space-between; }
|
||||
.dd-editor-controls .dd-filename { padding-left: 0; flex: 1; }
|
||||
@@ -96,3 +97,48 @@
|
||||
.dd-comparer .dd-compare-captions { position: absolute; top: 8px; left: 8px; right: 8px; display: flex; justify-content: space-between; pointer-events: none; }
|
||||
.dd-comparer .dd-compare-captions span { background: #171d27cc; color: #f1e3cf; padding: 3px 7px; border-radius: 3px; font-size: 11px; }
|
||||
@container (max-width: 380px) { .dd-inpaint .dd-settings { grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 3px 12px; } }
|
||||
.dd-group-presets { border: 0; border-radius: 4px; container-type: inline-size; contain: size layout; }
|
||||
.dd-gp-toolbar, .dd-gp-form { display: flex; align-items: center; gap: 7px; padding: 9px 10px; flex: 0 0 auto; }
|
||||
.dd-gp-toolbar { justify-content: space-between; border-bottom: 1px solid var(--dd-line); }
|
||||
.dd-gp-toolbar strong { font-size: 12px; font-weight: 500; }
|
||||
.dd-group-presets button { min-height: 26px; padding: 4px 7px; font-size: 11px; }
|
||||
.dd-gp-form input { flex: 1; min-width: 0; color: var(--dd-text); background: var(--dd-panel); border: 1px solid var(--dd-line); padding: 5px 6px; font: inherit; border-radius: 3px; }
|
||||
.dd-gp-body { display: grid; grid-template-columns: minmax(130px, 40%) minmax(0, 1fr); flex: 1; min-height: 0; }
|
||||
.dd-gp-presets { border-right: 1px solid var(--dd-line); padding: 7px; display: flex; flex-direction: column; gap: 5px; }
|
||||
.dd-gp-presets button { text-align: left; flex: 0 0 auto; white-space: normal; overflow-wrap: anywhere; }
|
||||
.dd-gp-detail { display: flex; flex-direction: column; min-height: 0; min-width: 0; }
|
||||
.dd-gp-detail-head { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px; }
|
||||
.dd-gp-detail-head strong { font-size: 12px; font-weight: 500; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.dd-gp-groups { flex: 1; min-height: 0; padding: 0 8px; }
|
||||
.dd-gp-scroll { overflow-y: auto; overscroll-behavior: contain; }
|
||||
.dd-gp-group { display: flex; align-items: center; gap: 7px; padding: 7px 0; border-bottom: 1px solid #41495566; }
|
||||
.dd-gp-color { flex: 0 0 4px; width: 4px; height: 20px; border-radius: 2px; }
|
||||
.dd-gp-group-name { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.dd-gp-group select { max-width: 118px; color: var(--dd-text); background: var(--dd-panel); border: 1px solid var(--dd-line); border-radius: 3px; padding: 4px; font: inherit; font-size: 11px; }
|
||||
.dd-gp-changed .dd-gp-group-name { color: var(--dd-accent); }
|
||||
.dd-gp-footer { display: flex; flex-wrap: wrap; gap: 5px; padding: 9px 8px; }
|
||||
.dd-gp-status { flex: 0 0 auto; padding: 5px 10px 7px; color: var(--dd-muted); font-size: 10px; border-top: 1px solid var(--dd-line); }
|
||||
.dd-gp-empty { color: var(--dd-muted); padding: 10px 4px; font-size: 11px; }
|
||||
|
||||
/* Compact controls shared by the mask and crop/blend modes. */
|
||||
.dd-inline-minimal .dd-mode-select { position:absolute; z-index:3; top:5px; right:5px; max-width:42%; color:var(--dd-text); background:#252b34e8; border:1px solid var(--dd-line); border-radius:4px; height:23px; font:11px "Segoe UI","Microsoft YaHei",sans-serif; padding:1px 3px; pointer-events:auto; }
|
||||
.dd-inline-minimal .dd-crop-bar { position:absolute; z-index:3; bottom:7px; left:5px; right:5px; display:flex; gap:3px; flex-wrap:wrap; align-items:center; width:fit-content; max-width:calc(100% - 10px); background:#20242be8; border-radius:4px; padding:3px; pointer-events:auto; }
|
||||
.dd-inline-minimal .dd-crop-bar button { min-height:23px; height:23px; padding:1px 6px; min-width:24px; }
|
||||
.dd-inline-minimal .dd-crop-bar select,.dd-inline-minimal .dd-crop-custom input { color:var(--dd-text); background:var(--dd-panel); border:1px solid var(--dd-line); border-radius:3px; height:23px; font:11px "Segoe UI","Microsoft YaHei",sans-serif; max-width:112px; }
|
||||
.dd-inline-minimal .dd-crop-custom { display:flex; gap:3px; }
|
||||
.dd-inline-minimal .dd-crop-custom input { width:66px; }
|
||||
.dd-inline-minimal > .dd-files { right:auto; }
|
||||
|
||||
|
||||
.dd-workbench .dd-workbench-fold {flex:0 0 auto;border-bottom:1px solid var(--dd-line);}
|
||||
.dd-workbench .dd-workbench-fold:not([open]) > :not(summary) {display:none !important;}
|
||||
.dd-workbench .dd-workbench-fold>summary {padding:6px 10px;color:var(--dd-muted);font-size:11px;cursor:pointer;list-style:none;display:flex;gap:6px;align-items:center;}
|
||||
.dd-workbench .dd-workbench-fold>summary::before {content:"▸";font-size:10px;color:var(--dd-accent);}
|
||||
.dd-workbench .dd-workbench-fold[open]>summary::before {content:"▾";}
|
||||
.dd-workbench .dd-workbench-fold>summary:hover {color:var(--dd-text);background:#ffffff05;}
|
||||
.dd-workbench .dd-workbench-fold>summary:focus-visible {outline:1px solid var(--dd-accent);outline-offset:-2px;}
|
||||
.dd-workbench .dd-param-mask-settings {display:flex;flex-direction:column;gap:8px;padding:7px 12px 9px;}
|
||||
.dd-workbench .dd-workbench-actions {flex:0 0 auto;}
|
||||
.dd-workbench .dd-workbench-actions:empty {display:none;}
|
||||
.dd-workbench .dd-workbench-actions .dd-actions {padding:6px 10px;gap:4px;}
|
||||
.dd-workbench .dd-workbench-actions .dd-actions button {min-height:24px;padding:3px 7px;}
|
||||
|
||||
+135
-54
@@ -1,5 +1,6 @@
|
||||
/* Original implementation, MIT licensed. No WebUI source is bundled. */
|
||||
import { registerImageWheel } from "./wheel_gestures.js";
|
||||
import { T } from "./i18n.js";
|
||||
const el = (tag, cls, text) => {
|
||||
const node = document.createElement(tag);
|
||||
if (cls) node.className = cls;
|
||||
@@ -10,7 +11,7 @@ const makeCanvas = () => document.createElement("canvas");
|
||||
const loadImage = (url) => new Promise((resolve, reject) => {
|
||||
const image = new Image();
|
||||
image.onload = () => resolve(image);
|
||||
image.onerror = () => reject(new Error("无法读取图像 / Cannot load image"));
|
||||
image.onerror = () => reject(new Error(T("Cannot load image")));
|
||||
image.src = url;
|
||||
});
|
||||
|
||||
@@ -23,6 +24,8 @@ export class InlineMaskEditor {
|
||||
this.mask = makeCanvas();
|
||||
this.baseMask = makeCanvas();
|
||||
this.overlay = makeCanvas();
|
||||
this.scene = makeCanvas();
|
||||
this.maskRevision = 0;
|
||||
this.tool = "brush";
|
||||
this.view = "overlay";
|
||||
this.brushSize = 64;
|
||||
@@ -87,12 +90,12 @@ export class InlineMaskEditor {
|
||||
|
||||
build() {
|
||||
const head = el("div", "dd-head");
|
||||
this.sizeLabel = el("span", "dd-dimensions", "内联蒙版 · INLINE MASK");
|
||||
this.sizeLabel = el("span", "dd-dimensions", T("INLINE MASK"));
|
||||
head.append(this.sizeLabel);
|
||||
this.root.append(head);
|
||||
const files = el("div", "dd-row dd-files");
|
||||
this.loadButton = this.button(files, "载入原图", "上传图片,也可拖放或粘贴 / Upload image", () => this.imageInput.click(), "dd-primary");
|
||||
this.filename = el("span", "dd-filename", "拖放图片到画布");
|
||||
this.loadButton = this.button(files, "↑", T("Upload an image, or drop / paste one"), () => this.imageInput.click(), "dd-primary");
|
||||
this.filename = el("span", "dd-filename", T("Drop an image onto the canvas"));
|
||||
files.append(this.filename);
|
||||
this.root.append(files);
|
||||
this.imageInput = el("input");
|
||||
@@ -118,25 +121,25 @@ export class InlineMaskEditor {
|
||||
const tools = el("div", "dd-row dd-tools");
|
||||
this.toolButtons = {};
|
||||
for (const [name, label, title] of [
|
||||
["brush", "画笔", "画笔 B / Brush"], ["erase", "橡皮", "橡皮 E,按住 Alt 或鼠标右键临时擦除 / Eraser"],
|
||||
["rect", "矩形", "矩形 R / Rectangle"], ["lasso", "套索", "自由套索 L / Freehand lasso"],
|
||||
["pan", "移动", "移动 H,或按住空格 / Pan"],
|
||||
]) this.toolButtons[name] = this.button(tools, label, title, () => this.setTool(name));
|
||||
["brush", "Brush", "Brush (B)"], ["erase", "Eraser", "Eraser (E); hold Alt for temporary erase"],
|
||||
["rect", "Rectangle", "Rectangle (R)"], ["lasso", "Lasso", "Freehand lasso (L)"],
|
||||
["pan", "Pan", "Pan (H), or hold Space"],
|
||||
]) this.toolButtons[name] = this.button(tools, T(label), T(title), () => this.setTool(name));
|
||||
this.root.append(tools);
|
||||
const settings = el("div", "dd-settings");
|
||||
this.addSlider(settings, "笔径", "brushSize", 1, 512, "px");
|
||||
this.addSlider(settings, "硬度", "hardness", 0, 100, "%");
|
||||
this.addSlider(settings, "笔触", "brushOpacity", 1, 100, "%");
|
||||
this.addSlider(settings, "叠加", "overlayOpacity", 0, 100, "%");
|
||||
this.addSlider(settings, T("Brush size"), "brushSize", 1, 512, "px");
|
||||
this.addSlider(settings, T("Hardness"), "hardness", 0, 100, "%");
|
||||
this.addSlider(settings, T("Brush opacity"), "brushOpacity", 1, 100, "%");
|
||||
this.addSlider(settings, T("Overlay"), "overlayOpacity", 0, 100, "%");
|
||||
this.stage = el("div", "dd-stage");
|
||||
this.canvas = makeCanvas();
|
||||
this.canvas.setAttribute("aria-label", "直接涂抹蒙版;橙色区域将被重绘 / Inline mask painting canvas");
|
||||
this.canvas.setAttribute("aria-label", T("Inline mask painting canvas; orange areas are repainted"));
|
||||
this.stage.append(this.canvas);
|
||||
this.empty = el("div", "dd-empty");
|
||||
this.empty.append(el("span", "dd-empty-symbol", "+"), el("strong", "", "把原图拖到这里"), el("span", "", "直接在节点中涂抹需要重绘的区域"));
|
||||
this.empty.append(el("span", "dd-empty-symbol", "+"), el("strong", "", T("Drop an image here")), el("span", "", T("Paint the areas to repaint directly in this node")));
|
||||
this.stage.append(this.empty);
|
||||
this.root.append(this.stage, settings);
|
||||
this.canvas.oncontextmenu = event => event.preventDefault();
|
||||
this.canvas.oncontextmenu = event => { event.preventDefault(); event.stopPropagation(); };
|
||||
this.canvas.addEventListener("pointerdown", event => this.pointerDown(event));
|
||||
this.canvas.addEventListener("pointermove", event => this.pointerMove(event));
|
||||
this.canvas.addEventListener("pointerup", event => this.pointerUp(event));
|
||||
@@ -151,32 +154,40 @@ export class InlineMaskEditor {
|
||||
if (file) this.upload(file);
|
||||
});
|
||||
const actions = el("div", "dd-row dd-actions");
|
||||
this.undoButton = this.button(actions, "撤销", "撤销 Ctrl+Z / Undo", () => this.undo());
|
||||
this.redoButton = this.button(actions, "重做", "重做 Ctrl+Shift+Z / Redo", () => this.redo());
|
||||
this.button(actions, "反转", "反转绘制的蒙版 / Invert painted mask", () => this.action({ type: "invert" }));
|
||||
this.button(actions, "全选", "重绘整张图 / Fill mask", () => this.action({ type: "fill" }));
|
||||
this.button(actions, "清空", "清空蒙版 / Clear mask", () => this.action({ type: "clear" }));
|
||||
this.button(actions, "导入蒙版", "白色重绘,黑色保护 / Import mask", () => { if (this.ready) this.maskInput.click(); });
|
||||
this.button(actions, "导出", "导出原始分辨率黑白蒙版 / Export mask PNG", () => this.download());
|
||||
this.actions = actions;
|
||||
this.undoButton = this.button(actions, T("Undo"), T("Undo (Ctrl+Z)"), () => this.undo());
|
||||
this.redoButton = this.button(actions, T("Redo"), T("Redo (Ctrl+Shift+Z)"), () => this.redo());
|
||||
this.button(actions, T("Invert"), T("Invert the painted mask"), () => this.action({ type: "invert" }));
|
||||
this.button(actions, T("Fill"), T("Fill the whole image with mask"), () => this.action({ type: "fill" }));
|
||||
this.button(actions, T("Clear"), T("Clear the mask"), () => this.action({ type: "clear" }));
|
||||
this.button(actions, T("Import mask"), T("White repaints, black preserves"), () => { if (this.ready) this.maskInput.click(); });
|
||||
this.button(actions, T("Export"), T("Export the mask PNG at full resolution"), () => this.download());
|
||||
this.root.append(actions);
|
||||
const footer = el("div", "dd-row dd-viewbar");
|
||||
this.viewButtons = {};
|
||||
for (const [name, label] of [["overlay", "叠加"], ["image", "原图"], ["mask", "蒙版"]]) {
|
||||
this.viewButtons[name] = this.button(footer, label, `${label} / ${name}`, () => { this.view = name; this.updateButtons(); this.schedule(); });
|
||||
for (const [name, label] of [["overlay", "Overlay"], ["image", "Image"], ["mask", "Mask"]]) {
|
||||
const text = T(label);
|
||||
this.viewButtons[name] = this.button(footer, text, `${text} / ${name}`, () => { this.view = name; this.updateButtons(); this.schedule(); });
|
||||
}
|
||||
const spacer = el("span", "dd-spacer");
|
||||
footer.append(spacer);
|
||||
this.zoomLabel = el("span", "dd-zoom", "100%");
|
||||
footer.append(this.zoomLabel);
|
||||
this.button(footer, "适应", "适应画布 / Fit image", () => this.fit());
|
||||
this.fitButton = this.button(footer, "⛶", T("Fit the image to the canvas"), () => this.fit());
|
||||
this.keepButton = this.button(footer, "", T("Keep"), event => { event.stopPropagation(); this.setKeepFit(!this.keepFit); });
|
||||
this.keepButton.innerHTML = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m16 3 5 5-4 1-4 4 1 4-3 3-3-6-6-3 3-3 4 1 4-4zM8 16l-6 6"/></svg>';
|
||||
// The inline button must not select/bring forward the ComfyUI node:
|
||||
// newer frontends can remeasure its DOM widget on that bubbling click.
|
||||
const fitAction = this.fitButton.onclick;
|
||||
this.fitButton.onclick = event => { event.stopPropagation(); fitAction(event); };
|
||||
this.root.append(footer);
|
||||
const embedRow = el("label", "dd-embed");
|
||||
this.embed = el("input");
|
||||
this.embed.type = "checkbox";
|
||||
this.embed.onchange = () => this.options.onEmbed?.(this.embed.checked);
|
||||
embedRow.append(this.embed, document.createTextNode("原图嵌入工作流 · 分享时无需另传原图"));
|
||||
embedRow.append(this.embed, document.createTextNode(T("Embed the source image in the workflow; no separate file needed when sharing")));
|
||||
this.root.append(embedRow);
|
||||
this.message = el("div", "dd-status", "Alt 临时擦除 · Ctrl+滚轮调笔径 · 滚轮缩放 / 空格拖动");
|
||||
this.message = el("div", "dd-status", T("Alt = temporary erase · Ctrl+wheel = brush size · wheel = zoom · Space = pan"));
|
||||
this.message.hidden = true;
|
||||
this.message.setAttribute("role", "alert");
|
||||
this.root.append(this.message);
|
||||
@@ -187,6 +198,9 @@ export class InlineMaskEditor {
|
||||
const info = el("div", "dd-row dd-source-info"); info.append(this.filename, this.sizeLabel);
|
||||
head.remove();
|
||||
this.controls.append(info, tools, settings, actions, footer, embedRow);
|
||||
actions.addEventListener("keydown", event => this.keydown(event));
|
||||
this.loadButton.after(this.fitButton);
|
||||
this.fitButton.after(this.keepButton);
|
||||
// These are the original live controls; the sampler mounts this
|
||||
// same DOM tree so brush state and callbacks are preserved.
|
||||
}
|
||||
@@ -215,21 +229,22 @@ export class InlineMaskEditor {
|
||||
}
|
||||
|
||||
async upload(file) {
|
||||
if (file.size > 64 * 1024 * 1024) { this.status("图片文件不能超过 64 MB / File is too large", true); return; }
|
||||
if (file.size > 64 * 1024 * 1024) { this.status(T("File is too large (max 64 MB)"), true); return; }
|
||||
try {
|
||||
this.status("正在载入原图… / Loading image…");
|
||||
this.status(T("Loading image…"));
|
||||
await this.options.onUpload?.(file);
|
||||
} catch (error) { this.status(error.message, true); }
|
||||
}
|
||||
|
||||
async setImage(url, maskData = "", name = "") {
|
||||
this.stroke = null; this.pointerId = null;
|
||||
const version = ++this.loadVersion;
|
||||
this.ready = false;
|
||||
try {
|
||||
const [image, loadedMask] = await Promise.all([loadImage(url), maskData ? loadImage(maskData) : Promise.resolve(null)]);
|
||||
if (version !== this.loadVersion || this.destroyed) return;
|
||||
if (image.width * image.height > 32 * 1024 * 1024 || Math.max(image.width, image.height) > 16384) {
|
||||
throw new Error("图像超过 3200 万像素或单边 16384px,请先缩小 / Image is too large");
|
||||
throw new Error(T("Image is too large; keep it under 32 MP and 16384 px per side"));
|
||||
}
|
||||
this.image = image;
|
||||
for (const canvas of [this.mask, this.baseMask]) { canvas.width = image.width; canvas.height = image.height; }
|
||||
@@ -251,7 +266,7 @@ export class InlineMaskEditor {
|
||||
if (version !== this.loadVersion || this.destroyed) return;
|
||||
this.baseMask.getContext("2d").drawImage(this.mask, 0, 0);
|
||||
this.sizeLabel.textContent = `${image.width} × ${image.height}`;
|
||||
this.filename.textContent = name || "内嵌原图 / Embedded image";
|
||||
this.filename.textContent = name || T("Embedded image");
|
||||
this.filename.title = this.filename.textContent;
|
||||
this.empty.hidden = true;
|
||||
this.ready = true;
|
||||
@@ -260,13 +275,29 @@ export class InlineMaskEditor {
|
||||
this.fit();
|
||||
this.updateButtons();
|
||||
this.options.onImage?.(image);
|
||||
this.status("橙色为绘制蒙版 · Alt 临时擦除 · Ctrl+滚轮调笔径");
|
||||
this.status(T("Orange is the painted mask · Alt = temporary erase · Ctrl+wheel = brush size"));
|
||||
} catch (error) {
|
||||
if (version === this.loadVersion && !this.destroyed) this.status(error.message, true);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async replaceSource(url, name = "") {
|
||||
const version = ++this.loadVersion;
|
||||
const image = await loadImage(url);
|
||||
if (version !== this.loadVersion || this.destroyed) return;
|
||||
if (image.width !== this.mask.width || image.height !== this.mask.height) {
|
||||
throw new Error(T("The result size must match the source image to preserve the mask"));
|
||||
}
|
||||
// Replacing only the source preserves mask pixels, the base snapshot,
|
||||
// command history, redo history, active strokes and the current view.
|
||||
this.flush();
|
||||
this.image = image;
|
||||
this.filename.textContent = name || T("Embedded image");
|
||||
this.filename.title = this.filename.textContent;
|
||||
this.updateButtons(); this.schedule();
|
||||
}
|
||||
|
||||
importMask(ctx, image) {
|
||||
const scratch = makeCanvas();
|
||||
scratch.width = this.mask.width; scratch.height = this.mask.height;
|
||||
@@ -292,6 +323,8 @@ export class InlineMaskEditor {
|
||||
}
|
||||
|
||||
updateButtons() {
|
||||
this.keepButton?.classList.toggle("dd-active", !!this.keepFit);
|
||||
this.keepButton?.setAttribute("aria-pressed", String(!!this.keepFit));
|
||||
this.stage?.classList.toggle("dd-erasing", !!(this.altErase || this.tool === "erase" || this.stroke?.type === "erase"));
|
||||
for (const [name, button] of Object.entries(this.toolButtons || {})) {
|
||||
const active = name === (this.altErase ? "erase" : this.tool);
|
||||
@@ -308,6 +341,7 @@ export class InlineMaskEditor {
|
||||
|
||||
dimensions() {
|
||||
const r = this.canvas.getBoundingClientRect();
|
||||
if (this.keepFit) { this.zoom = 1; this.pan = { x: 0, y: 0 }; }
|
||||
if (this.viewport?.width && this.viewport?.height && r.width && r.height) {
|
||||
this.pan.x *= r.width / this.viewport.width;
|
||||
this.pan.y *= r.height / this.viewport.height;
|
||||
@@ -324,7 +358,9 @@ export class InlineMaskEditor {
|
||||
}
|
||||
|
||||
pointerDown(event) {
|
||||
if (event.button === 2) { event.preventDefault(); event.stopPropagation(); return; }
|
||||
if (!this.ready || this.pointerId != null) return;
|
||||
if (this.keepFit && (this.space || (!event.altKey && this.tool === "pan") || event.button === 1)) return;
|
||||
event.preventDefault(); event.stopPropagation(); this.root.focus({ preventScroll: true });
|
||||
this.altErase = !!event.altKey; this.updateButtons();
|
||||
this.pointerId = event.pointerId;
|
||||
@@ -335,7 +371,7 @@ export class InlineMaskEditor {
|
||||
return;
|
||||
}
|
||||
if (this.view === "image") { this.view = "overlay"; this.updateButtons(); }
|
||||
this.stroke = { type: event.button === 2 || event.altKey ? "erase" : this.tool, size: this.brushSize, hardness: this.hardness, opacity: this.brushOpacity, points: [this.cursor] };
|
||||
this.stroke = { type: event.altKey ? "erase" : this.tool, size: this.brushSize, hardness: this.hardness, opacity: this.brushOpacity, points: [this.cursor] };
|
||||
this.updateButtons();
|
||||
if (["brush", "erase"].includes(this.stroke.type)) this.paintSegment(this.mask.getContext("2d"), this.stroke, this.cursor, this.cursor);
|
||||
this.schedule();
|
||||
@@ -353,7 +389,7 @@ export class InlineMaskEditor {
|
||||
} else if (this.stroke) {
|
||||
const events = event.getCoalescedEvents?.() || [event];
|
||||
if (["brush", "erase"].includes(this.stroke.type)) {
|
||||
const type = event.altKey || (event.buttons & 2) ? "erase" : this.tool;
|
||||
const type = event.altKey ? "erase" : this.tool;
|
||||
if (["brush", "erase"].includes(type) && type !== this.stroke.type) {
|
||||
// Keep separate commands when Alt is pressed/released mid-stroke.
|
||||
const pivot = this.stroke.points.at(-1);
|
||||
@@ -392,7 +428,10 @@ export class InlineMaskEditor {
|
||||
}
|
||||
|
||||
paintSegment(ctx, command, a, b) {
|
||||
if (ctx.canvas === this.mask) this.maskRevision++;
|
||||
ctx.save();
|
||||
const bounds = this.options.paintBounds?.();
|
||||
if (bounds) { ctx.beginPath(); ctx.rect(bounds.x, bounds.y, bounds.width, bounds.height); ctx.clip(); }
|
||||
ctx.globalCompositeOperation = command.type === "erase" ? "destination-out" : "source-over";
|
||||
ctx.globalAlpha = command.opacity / 100;
|
||||
if (command.hardness >= 99 && a.p === 1 && b.p === 1) {
|
||||
@@ -419,6 +458,9 @@ export class InlineMaskEditor {
|
||||
}
|
||||
|
||||
drawCommand(ctx, command) {
|
||||
ctx.save();
|
||||
const bounds = this.options.paintBounds?.();
|
||||
if (bounds) { ctx.beginPath(); ctx.rect(bounds.x, bounds.y, bounds.width, bounds.height); ctx.clip(); }
|
||||
const w = this.mask.width, h = this.mask.height;
|
||||
if (["brush", "erase"].includes(command.type)) {
|
||||
this.paintSegment(ctx, command, command.points[0], command.points[0]);
|
||||
@@ -427,7 +469,14 @@ export class InlineMaskEditor {
|
||||
else if (command.type === "fill") { ctx.save(); ctx.fillStyle = "white"; ctx.fillRect(0, 0, w, h); ctx.restore(); }
|
||||
else if (command.type === "invert") {
|
||||
ctx.save(); ctx.globalCompositeOperation = "xor"; ctx.fillStyle = "white"; ctx.fillRect(0, 0, w, h); ctx.restore();
|
||||
} else if (command.type === "import") this.importMask(ctx, command.image);
|
||||
} else if (command.type === "import") {
|
||||
if (!bounds) this.importMask(ctx, command.image);
|
||||
else {
|
||||
const imported = makeCanvas(); imported.width = w; imported.height = h;
|
||||
this.importMask(imported.getContext("2d"), command.image);
|
||||
ctx.clearRect(0, 0, w, h); ctx.drawImage(imported, 0, 0); imported.width = imported.height = 0;
|
||||
}
|
||||
}
|
||||
else if (["rect", "lasso"].includes(command.type)) {
|
||||
const a = command.points[0], b = command.points.at(-1);
|
||||
ctx.save(); ctx.fillStyle = "white"; ctx.globalAlpha = command.opacity / 100;
|
||||
@@ -435,12 +484,18 @@ export class InlineMaskEditor {
|
||||
else { ctx.beginPath(); ctx.moveTo(a.x, a.y); for (const p of command.points) ctx.lineTo(p.x, p.y); ctx.closePath(); ctx.fill(); }
|
||||
ctx.restore();
|
||||
}
|
||||
ctx.restore();
|
||||
}
|
||||
|
||||
remember(command) {
|
||||
this.history.push(command); this.future = [];
|
||||
// Keep commands rather than full-resolution pixel snapshots; memory stays small.
|
||||
if (this.history.length > 500) this.drawCommand(this.baseMask.getContext("2d"), this.history.shift());
|
||||
let bitmapBytes = this.history.reduce((total, item) => total + (item.image ? item.image.width * item.image.height * 4 : 0), 0);
|
||||
while (this.history.length > 500 || (this.history.length > 1 && bitmapBytes > 64 * 1024 * 1024)) {
|
||||
const first = this.history.shift();
|
||||
this.drawCommand(this.baseMask.getContext("2d"), first);
|
||||
bitmapBytes -= first.image ? first.image.width * first.image.height * 4 : 0;
|
||||
}
|
||||
this.updateButtons();
|
||||
}
|
||||
|
||||
@@ -460,6 +515,7 @@ export class InlineMaskEditor {
|
||||
redo() { if (this.future.length && !this.stroke) { this.history.push(this.future.pop()); this.replay(); } }
|
||||
|
||||
changed() {
|
||||
this.maskRevision++;
|
||||
this.dirty = true;
|
||||
this.flush();
|
||||
this.schedule();
|
||||
@@ -502,6 +558,13 @@ export class InlineMaskEditor {
|
||||
|
||||
fit() { this.zoom = 1; this.pan = { x: 0, y: 0 }; this.schedule(); }
|
||||
|
||||
setKeepFit(enabled, notify = true) {
|
||||
this.keepFit = !!enabled;
|
||||
if (this.keepFit) this.fit();
|
||||
this.updateButtons(); this.schedule();
|
||||
if (notify) this.options.onKeepFit?.(this.keepFit);
|
||||
}
|
||||
|
||||
setBrushSize(value) {
|
||||
this.brushSizeInput.value = Math.max(1, Math.min(512, Math.round(value)));
|
||||
this.brushSizeInput.dispatchEvent(new Event("input"));
|
||||
@@ -510,6 +573,13 @@ export class InlineMaskEditor {
|
||||
wheel(event) {
|
||||
if (!this.ready) return;
|
||||
event.preventDefault(); event.stopPropagation();
|
||||
if (event.shiftKey) {
|
||||
const delta = event.deltaY * (event.deltaMode === 1 ? 16 : event.deltaMode === 2 ? 100 : 1);
|
||||
this.hardnessInput.value = Math.max(0, Math.min(100, this.hardness + (delta < 0 ? 5 : delta > 0 ? -5 : 0)));
|
||||
this.hardnessInput.dispatchEvent(new Event("input"));
|
||||
this.cursor = this.point(event); this.schedule(); return;
|
||||
}
|
||||
if (this.keepFit && !event.ctrlKey) { this.options.onGraphWheel?.(event); return; }
|
||||
if (event.ctrlKey) {
|
||||
const delta = event.deltaY * (event.deltaMode === 1 ? 16 : event.deltaMode === 2 ? 100 : 1);
|
||||
if (delta) {
|
||||
@@ -544,27 +614,38 @@ export class InlineMaskEditor {
|
||||
schedule() { if (!this.frame && !this.destroyed) this.frame = requestAnimationFrame(() => { this.frame = 0; this.render(); }); }
|
||||
|
||||
render() {
|
||||
const view = this.options.displayView?.() || this.view;
|
||||
const rect = this.canvas.getBoundingClientRect();
|
||||
if (!rect.width || !rect.height) return;
|
||||
const ratio = Math.min(devicePixelRatio || 1, 2);
|
||||
const w = Math.round(rect.width * ratio), h = Math.round(rect.height * ratio);
|
||||
if (this.canvas.width !== w || this.canvas.height !== h) { this.canvas.width = w; this.canvas.height = h; this.overlay.width = w; this.overlay.height = h; }
|
||||
const ctx = this.canvas.getContext("2d");
|
||||
ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.clearRect(0, 0, w, h);
|
||||
if (!this.ready) return;
|
||||
const d = this.dimensions();
|
||||
ctx.setTransform(ratio * d.scale, 0, 0, ratio * d.scale, ratio * d.x, ratio * d.y);
|
||||
if (this.view !== "mask") ctx.drawImage(this.image, 0, 0);
|
||||
else { ctx.fillStyle = "black"; ctx.fillRect(0, 0, this.image.width, this.image.height); }
|
||||
if (this.view !== "image") {
|
||||
const overlay = this.overlay.getContext("2d");
|
||||
overlay.setTransform(1, 0, 0, 1, 0, 0); overlay.clearRect(0, 0, w, h);
|
||||
overlay.setTransform(ratio * d.scale, 0, 0, ratio * d.scale, ratio * d.x, ratio * d.y);
|
||||
overlay.drawImage(this.mask, 0, 0);
|
||||
if (this.view === "overlay") { overlay.globalCompositeOperation = "source-in"; overlay.fillStyle = "#ffad45"; overlay.fillRect(0, 0, this.mask.width, this.mask.height); overlay.globalCompositeOperation = "source-over"; }
|
||||
ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.globalAlpha = this.view === "mask" ? 1 : this.overlayOpacity / 100; ctx.drawImage(this.overlay, 0, 0); ctx.globalAlpha = 1;
|
||||
const ratio = Math.min(devicePixelRatio || 1, 2, this.ready ? 1 / d.scale : 2,
|
||||
8192 / rect.width, 8192 / rect.height, Math.sqrt(8 * 1024 * 1024 / (rect.width * rect.height)));
|
||||
const w = Math.max(1, Math.round(rect.width * ratio)), h = Math.max(1, Math.round(rect.height * ratio));
|
||||
if (this.canvas.width !== w || this.canvas.height !== h) { this.canvas.width = w; this.canvas.height = h; this.overlay.width = w; this.overlay.height = h; }
|
||||
const display = this.canvas.getContext("2d");
|
||||
if (!this.ready) { display.clearRect(0, 0, w, h); this.sceneKey = null; return; }
|
||||
const key = [this.loadVersion, this.maskRevision, w, h, d.scale * ratio, d.x * ratio, d.y * ratio, view, this.overlayOpacity, this.options.sceneRevision?.() || 0].join(":");
|
||||
if (key !== this.sceneKey) {
|
||||
if (this.scene.width !== w || this.scene.height !== h) { this.scene.width = w; this.scene.height = h; }
|
||||
const ctx = this.scene.getContext("2d");
|
||||
ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.clearRect(0, 0, w, h);
|
||||
ctx.setTransform(ratio * d.scale, 0, 0, ratio * d.scale, ratio * d.x, ratio * d.y);
|
||||
if (view !== "mask") { if (!this.options.drawSource?.(ctx)) ctx.drawImage(this.image, 0, 0); }
|
||||
else { ctx.fillStyle = "black"; ctx.fillRect(0, 0, this.image.width, this.image.height); }
|
||||
if (view !== "image" && (view === "mask" || this.options.showMask?.() !== false)) {
|
||||
const overlay = this.overlay.getContext("2d");
|
||||
overlay.setTransform(1, 0, 0, 1, 0, 0); overlay.clearRect(0, 0, w, h);
|
||||
overlay.setTransform(ratio * d.scale, 0, 0, ratio * d.scale, ratio * d.x, ratio * d.y);
|
||||
overlay.drawImage(this.mask, 0, 0);
|
||||
if (view === "overlay") { overlay.globalCompositeOperation = "source-in"; overlay.fillStyle = "#ffad45"; overlay.fillRect(0, 0, this.mask.width, this.mask.height); overlay.globalCompositeOperation = "source-over"; }
|
||||
ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.globalAlpha = view === "mask" ? 1 : this.overlayOpacity / 100; ctx.drawImage(this.overlay, 0, 0); ctx.globalAlpha = 1;
|
||||
}
|
||||
this.sceneKey = key;
|
||||
}
|
||||
const ctx = display;
|
||||
ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.clearRect(0, 0, w, h); ctx.drawImage(this.scene, 0, 0);
|
||||
ctx.setTransform(ratio * d.scale, 0, 0, ratio * d.scale, ratio * d.x, ratio * d.y);
|
||||
this.options.drawOverlay?.(ctx, d);
|
||||
if (this.stroke && ["rect", "lasso"].includes(this.stroke.type)) {
|
||||
ctx.save(); ctx.strokeStyle = "#ffcf85"; ctx.lineWidth = 1.5 / d.scale; ctx.setLineDash([5 / d.scale, 4 / d.scale]);
|
||||
const a = this.stroke.points[0], b = this.stroke.points.at(-1);
|
||||
@@ -572,7 +653,7 @@ export class InlineMaskEditor {
|
||||
else { ctx.beginPath(); ctx.moveTo(a.x, a.y); for (const p of this.stroke.points) ctx.lineTo(p.x, p.y); ctx.stroke(); }
|
||||
ctx.restore();
|
||||
}
|
||||
if (this.cursor && (this.altErase || ["brush", "erase"].includes(this.tool)) && !this.drag) {
|
||||
if (this.cursor && (this.altErase || ["brush", "erase"].includes(this.tool)) && !this.drag && this.options.showCursor?.() !== false) {
|
||||
const erasing = this.altErase || this.tool === "erase" || this.stroke?.type === "erase";
|
||||
ctx.save();
|
||||
if (erasing) ctx.setLineDash([4 / d.scale, 3 / d.scale]);
|
||||
@@ -590,7 +671,7 @@ export class InlineMaskEditor {
|
||||
window.removeEventListener("keydown", this.modifierDown, true);
|
||||
window.removeEventListener("keyup", this.modifierUp, true);
|
||||
window.removeEventListener("blur", this.modifierUp);
|
||||
for (const canvas of [this.mask, this.baseMask, this.overlay, this.canvas]) canvas.width = canvas.height = 0;
|
||||
for (const canvas of [this.mask, this.baseMask, this.overlay, this.scene, this.canvas]) canvas.width = canvas.height = 0;
|
||||
this.history = []; this.future = []; this.image = null; this.controls?.remove(); this.root.remove();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
const disabled = node => node.mode === 2 || node.mode === 4;
|
||||
const inputLink = (graph, input) => input?.link == null ? null
|
||||
: graph.getLink?.(input.link) ?? graph.links?.[input.link];
|
||||
|
||||
/** Follow routing nodes without treating ordinary processing nodes as routers. */
|
||||
export function branchIsEnabled(node, name) {
|
||||
const graph = node.graph;
|
||||
if (!graph) return false;
|
||||
const seen = new Set();
|
||||
function visit(source, slot = 0) {
|
||||
if (!source || seen.has(source) || disabled(source)) return false;
|
||||
seen.add(source);
|
||||
const sourceGraph = source.graph || graph;
|
||||
const follow = link => link ? visit(sourceGraph.getNodeById(link.origin_id), link.origin_slot) : false;
|
||||
|
||||
// KJ Get nodes have no physical inputs. Follow their actual setter so
|
||||
// its ignored state is checked too; getInputLink alone skips the Set.
|
||||
if (source.isVirtualNode && typeof source.findSetter === "function") {
|
||||
return visit(source.findSetter(sourceGraph), slot);
|
||||
}
|
||||
if (source.type === "Reroute" || source.type === "SetNode") {
|
||||
return follow(inputLink(sourceGraph, source.inputs?.[slot] || source.inputs?.[0]));
|
||||
}
|
||||
if (source.isVirtualNode && typeof source.resolveVirtualOutput === "function") {
|
||||
const resolved = source.resolveVirtualOutput(slot);
|
||||
if (resolved?.node) return visit(resolved.node, resolved.slot ?? 0);
|
||||
}
|
||||
if (source.isVirtualNode && typeof source.getInputLink === "function") {
|
||||
return follow(source.getInputLink(slot));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
const link = inputLink(graph, node.inputs?.find(input => input.name === name));
|
||||
return link ? visit(graph.getNodeById(link.origin_id), link.origin_slot) : false;
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import { app } from "../../scripts/app.js";
|
||||
import { branchIsEnabled } from "./exclusive_routes.js?v=0.5.6";
|
||||
|
||||
app.registerExtension({
|
||||
name: "AdachiWorkbench.ExclusiveSwitch",
|
||||
async beforeRegisterNodeDef(nodeType, nodeData) {
|
||||
if (nodeData.name !== "AdachiExclusiveSwitch") return;
|
||||
const created = nodeType.prototype.onNodeCreated;
|
||||
nodeType.prototype.onNodeCreated = function () {
|
||||
const result = created?.apply(this, arguments);
|
||||
const widget = this.widgets?.find(widget => widget.name === "active_inputs");
|
||||
if (widget) {
|
||||
widget.type = "hidden";
|
||||
widget.hidden = true;
|
||||
widget.options ??= {};
|
||||
widget.options.hidden = true;
|
||||
widget.computeSize = () => [0, -4];
|
||||
widget.serializeValue = executionNode => {
|
||||
const flags = Number(branchIsEnabled(this, "input_a"))
|
||||
| (Number(branchIsEnabled(this, "input_b")) << 1);
|
||||
// Recent frontends resolve ignored virtual Get nodes before
|
||||
// backend lazy execution, sometimes trying a nonexistent input.
|
||||
// Drop only inactive links in the detached execution DTO;
|
||||
// the editable graph and saved workflow keep all their wires.
|
||||
if (executionNode !== this && executionNode?.node === this) {
|
||||
for (const input of executionNode.inputs || []) {
|
||||
const bit = input.name === "input_a" ? 1 : input.name === "input_b" ? 2 : 0;
|
||||
if (bit && !(flags & bit) && "linkId" in input
|
||||
&& !this.inputs.includes(input)) input.linkId = null;
|
||||
}
|
||||
}
|
||||
return flags;
|
||||
};
|
||||
}
|
||||
const internalSlot = this.inputs?.findIndex(input => input.name === "active_inputs");
|
||||
if (internalSlot >= 0) this.removeInput(internalSlot);
|
||||
this.setSize([230, 80]);
|
||||
return result;
|
||||
};
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,105 @@
|
||||
/* Serializable group presets; no ComfyUI or third-party extension dependency. */
|
||||
export const GROUP_PRESETS_TYPE = "AdachiGroupPresets";
|
||||
const ACTIVE = 0, BYPASS = 4;
|
||||
const uuid = () => globalThis.crypto?.randomUUID?.() || `${Date.now()}-${Math.random().toString(36).slice(2)}`;
|
||||
|
||||
function groupKey(group, persist = false) {
|
||||
if (group.id != null && group.id !== -1) return `group:${group.id}`;
|
||||
if (persist) { group.flags ??= {}; group.flags.adachi_preset_id ??= uuid(); }
|
||||
return group.flags?.adachi_preset_id ? `legacy:${group.flags.adachi_preset_id}` : `unsaved:${group.title}:${Array.from(group.pos || []).join(",")}`;
|
||||
}
|
||||
|
||||
function members(group, seen = new Set()) {
|
||||
if (seen.has(group)) return [];
|
||||
seen.add(group); group.recomputeInsideNodes?.();
|
||||
const result = new Set();
|
||||
for (const item of group._children || group._nodes || group.nodes || []) {
|
||||
if (typeof item.recomputeInsideNodes === "function") {
|
||||
for (const node of members(item, seen)) result.add(node);
|
||||
} else if (item.mode != null && item.type !== GROUP_PRESETS_TYPE) result.add(item);
|
||||
}
|
||||
return [...result];
|
||||
}
|
||||
|
||||
export class GroupPresetState {
|
||||
constructor(node, change) { this.node = node; this.change = change; this.restore(); }
|
||||
restore() {
|
||||
const raw = this.node.properties.adachi_group_presets;
|
||||
const ids = new Set();
|
||||
const presets = (Array.isArray(raw?.presets) ? raw.presets : []).filter(p => p && typeof p.id === "string" && !ids.has(p.id) && ids.add(p.id)).map(p => ({
|
||||
id: p.id, name: String(p.name || "Preset"),
|
||||
groups: Object.fromEntries(Object.entries(p.groups || {}).filter(([, state]) => state && [ACTIVE, BYPASS].includes(state.mode)).map(([key, state]) => [key, { mode: state.mode, title: String(state.title || key) }])),
|
||||
}));
|
||||
this.node.properties.adachi_group_presets = { version: 1, activeId: presets.some(p => p.id === raw?.activeId) ? raw.activeId : presets[0]?.id || null, presets };
|
||||
}
|
||||
get data() { return this.node.properties.adachi_group_presets; }
|
||||
get active() { return this.data.presets.find(p => p.id === this.data.activeId) || null; }
|
||||
groups(persist = false) {
|
||||
return Array.from(this.node.graph?.groups || this.node.graph?._groups || []).map(group => {
|
||||
const nodes = members(group);
|
||||
const modes = new Set(nodes.map(node => node.mode));
|
||||
return { key: groupKey(group, persist), title: String(group.title || "Group"), color: group.color || "#64748b", group, nodes, mode: modes.size === 1 ? [...modes][0] : nodes.length ? -1 : ACTIVE,
|
||||
area: Math.abs((group.size?.[0] || 1) * (group.size?.[1] || 1)) };
|
||||
});
|
||||
}
|
||||
capture() {
|
||||
return Object.fromEntries(this.groups(true).map(group => [group.key, { title: group.title, mode: group.nodes.some(node => node.mode === ACTIVE) || !group.nodes.length ? ACTIVE : BYPASS }]));
|
||||
}
|
||||
add(name) {
|
||||
const title = String(name).trim(); if (!title) return null;
|
||||
let created;
|
||||
this.change(() => {
|
||||
created = { id: uuid(), name: title, groups: this.capture() };
|
||||
this.data.presets.push(created); this.data.activeId = created.id;
|
||||
});
|
||||
return created;
|
||||
}
|
||||
rename(id, name) {
|
||||
const preset = this.data.presets.find(p => p.id === id), title = String(name).trim();
|
||||
if (preset && title) this.change(() => { preset.name = title; });
|
||||
}
|
||||
saveCurrent() { if (this.active) this.change(() => { this.active.groups = this.capture(); }); }
|
||||
remove(id) {
|
||||
this.change(() => {
|
||||
this.data.presets = this.data.presets.filter(p => p.id !== id);
|
||||
if (this.data.activeId === id) { this.data.activeId = this.data.presets[0]?.id || null; if (this.active) this.applyStates(this.active); }
|
||||
});
|
||||
}
|
||||
setGroup(presetId, key, mode) {
|
||||
const preset = this.data.presets.find(p => p.id === presetId), group = this.groups().find(g => g.key === key);
|
||||
if (!preset || !group) return;
|
||||
this.change(() => {
|
||||
if (mode == null) delete preset.groups[key];
|
||||
else {
|
||||
const stableKey = groupKey(group.group, true);
|
||||
if (stableKey !== key) delete preset.groups[key];
|
||||
preset.groups[stableKey] = { title: group.title, mode: mode === BYPASS ? BYPASS : ACTIVE };
|
||||
}
|
||||
if (this.data.activeId === presetId) this.applyStates(preset);
|
||||
});
|
||||
}
|
||||
apply(id) {
|
||||
const preset = this.data.presets.find(p => p.id === id); if (!preset) return null;
|
||||
let result;
|
||||
this.change(() => { this.data.activeId = id; result = this.applyStates(preset); });
|
||||
return result;
|
||||
}
|
||||
planStates(preset, available = this.groups()) {
|
||||
const groups = available.filter(g => preset.groups[g.key]).sort((a, b) => b.area - a.area || a.key.localeCompare(b.key));
|
||||
const plan = new Map(), overlaps = new Set();
|
||||
// Smaller (more specific) groups override enclosing/overlapping groups.
|
||||
for (const group of groups) {
|
||||
const mode = preset.groups[group.key].mode;
|
||||
for (const node of group.nodes) {
|
||||
if (plan.has(node) && plan.get(node) !== mode) overlaps.add(node);
|
||||
plan.set(node, mode);
|
||||
}
|
||||
}
|
||||
return { plan, stats: { groups: groups.length, nodes: plan.size, overlaps: overlaps.size, missing: Object.keys(preset.groups).length - groups.length } };
|
||||
}
|
||||
applyStates(preset) {
|
||||
const { plan, stats } = this.planStates(preset);
|
||||
for (const [node, mode] of plan) node.mode = mode;
|
||||
return stats;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
import { app } from "../../scripts/app.js";
|
||||
import { T } from "./i18n.js";
|
||||
import { GROUP_PRESETS_TYPE, GroupPresetState } from "./group_preset_state.js";
|
||||
|
||||
const el = (tag, cls, text) => { const e = document.createElement(tag); if (cls) e.className = cls; if (text) e.textContent = text; return e; };
|
||||
function ensureStyle() {
|
||||
if (document.getElementById("adachi-inpaint-style")) return;
|
||||
const link = el("link"); link.id = "adachi-inpaint-style"; link.rel = "stylesheet";
|
||||
link.href = new URL("./editor.css", import.meta.url).href; document.head.append(link);
|
||||
}
|
||||
|
||||
class GroupPresetsPanel {
|
||||
constructor(node) {
|
||||
this.node = node; this.root = el("div", "dd-inpaint dd-group-presets");
|
||||
this.model = new GroupPresetState(node, operation => {
|
||||
app.canvas?.emitBeforeChange?.();
|
||||
try { operation(); node.graph?.setDirtyCanvas(true, true); }
|
||||
finally { app.canvas?.emitAfterChange?.(); }
|
||||
this.refresh(true);
|
||||
});
|
||||
const toolbar = el("div", "dd-gp-toolbar"); toolbar.append(el("strong", "", T("Group presets")));
|
||||
this.add = this.button(toolbar, T("+ New preset"), () => this.showForm("add"));
|
||||
this.form = el("form", "dd-gp-form"); this.form.hidden = true;
|
||||
this.nameInput = el("input"); this.nameInput.type = "text"; this.nameInput.maxLength = 120;
|
||||
this.nameInput.setAttribute("aria-label", T("Preset name"));
|
||||
this.form.append(this.nameInput);
|
||||
const save = this.button(this.form, T("Save"), () => this.submitName()); save.classList.add("dd-primary");
|
||||
this.button(this.form, T("Cancel"), () => { this.form.hidden = true; });
|
||||
this.form.onsubmit = event => { event.preventDefault(); this.submitName(); };
|
||||
this.nameInput.onkeydown = event => { event.stopPropagation(); if (event.key === "Escape") { event.preventDefault(); this.form.hidden = true; } };
|
||||
const body = el("div", "dd-gp-body");
|
||||
this.presets = el("nav", "dd-gp-presets dd-gp-scroll"); this.presets.setAttribute("aria-label", T("Presets"));
|
||||
const detail = el("section", "dd-gp-detail");
|
||||
const head = el("div", "dd-gp-detail-head"); this.title = el("strong"); head.append(this.title);
|
||||
this.rename = this.button(head, T("Rename"), () => this.showForm("rename"));
|
||||
this.groups = el("div", "dd-gp-groups dd-gp-scroll"); this.groups.setAttribute("aria-label", T("Group states"));
|
||||
const footer = el("div", "dd-gp-footer");
|
||||
this.capture = this.button(footer, T("Save current group states"), () => this.model.saveCurrent());
|
||||
this.remove = this.button(footer, T("Delete preset"), () => { if (this.model.active) this.model.remove(this.model.active.id); });
|
||||
detail.append(head, this.groups, footer); body.append(this.presets, detail);
|
||||
this.status = el("div", "dd-gp-status"); this.status.setAttribute("role", "status");
|
||||
this.root.append(toolbar, this.form, body, this.status);
|
||||
this.onWheel = event => {
|
||||
if (!this.root.contains(event.target)) return;
|
||||
const scroll = event.target.closest(".dd-gp-scroll");
|
||||
if (scroll && ((event.deltaY < 0 && scroll.scrollTop > 0) || (event.deltaY > 0 && scroll.scrollTop + scroll.clientHeight < scroll.scrollHeight - 1))) {
|
||||
event.stopPropagation(); return;
|
||||
}
|
||||
event.preventDefault(); event.stopPropagation(); app.canvas?.processMouseWheel(event);
|
||||
};
|
||||
window.addEventListener("wheel", this.onWheel, { capture: true, passive: false });
|
||||
this.timer = setInterval(() => { if (this.root.isConnected && !document.hidden) this.refresh(); }, 500);
|
||||
this.refresh(true);
|
||||
}
|
||||
button(parent, label, callback) { const button = el("button", "", label); button.type = "button"; button.onclick = event => { event.stopPropagation(); callback(); }; parent.append(button); return button; }
|
||||
showForm(mode) {
|
||||
this.formMode = mode; this.form.hidden = false;
|
||||
this.nameInput.value = mode === "rename" ? this.model.active?.name || "" : `${T("Preset")} ${this.model.data.presets.length + 1}`;
|
||||
this.nameInput.focus({ preventScroll: true }); this.nameInput.select();
|
||||
}
|
||||
submitName() {
|
||||
const name = this.nameInput.value.trim(); if (!name) { this.nameInput.focus(); return; }
|
||||
if (this.formMode === "rename" && this.model.active) this.model.rename(this.model.active.id, name);
|
||||
else this.model.add(name);
|
||||
this.form.hidden = true;
|
||||
}
|
||||
apply(id) {
|
||||
this.model.apply(id);
|
||||
}
|
||||
refresh(force = false) {
|
||||
const active = this.model.active, groups = this.model.groups();
|
||||
const signature = JSON.stringify([this.model.data, groups.map(g => [g.key, g.title, g.color, g.nodes.map(n => [n.id, n.mode])]), T("Group presets")]);
|
||||
if (!force && signature === this.signature) return;
|
||||
this.signature = signature;
|
||||
const navScroll = this.presets.scrollTop, groupScroll = this.groups.scrollTop;
|
||||
this.presets.replaceChildren(); this.groups.replaceChildren();
|
||||
for (const preset of this.model.data.presets) {
|
||||
const button = this.button(this.presets, preset.name, () => this.apply(preset.id));
|
||||
button.dataset.presetId = preset.id; button.title = preset.name;
|
||||
button.classList.toggle("dd-active", preset.id === active?.id);
|
||||
button.setAttribute("aria-pressed", String(preset.id === active?.id));
|
||||
}
|
||||
if (!this.model.data.presets.length) this.presets.append(el("div", "dd-gp-empty", T("Add a preset to get started")));
|
||||
this.title.textContent = active?.name || T("Group states"); this.title.title = this.title.textContent;
|
||||
const expected = active ? this.model.planStates(active, groups) : { plan: new Map(), stats: {} };
|
||||
for (const group of groups) {
|
||||
const row = el("label", "dd-gp-group"); row.dataset.groupKey = group.key;
|
||||
const dot = el("span", "dd-gp-color"); dot.style.background = group.color;
|
||||
const label = el("span", "dd-gp-group-name", group.title); label.title = `${group.title} · ${group.key}`;
|
||||
const select = el("select"); select.setAttribute("aria-label", group.title); select.disabled = !active;
|
||||
for (const [value, name] of [["", "Keep current"], ["0", "Enabled"], ["4", "Bypassed"]]) {
|
||||
const option = el("option", "", T(name)); option.value = value; select.append(option);
|
||||
}
|
||||
const saved = active?.groups[group.key]; select.value = saved ? String(saved.mode) : "";
|
||||
if (saved && group.nodes.some(n => n.mode !== expected.plan.get(n))) { row.classList.add("dd-gp-changed"); label.title += ` · ${T("Current group state differs from the preset")}`; }
|
||||
select.onchange = () => { if (active) this.model.setGroup(active.id, group.key, select.value === "" ? null : Number(select.value)); };
|
||||
row.append(dot, label, select); this.groups.append(row);
|
||||
}
|
||||
if (!groups.length) this.groups.append(el("div", "dd-gp-empty", T("No groups in this workflow yet")));
|
||||
for (const button of [this.rename, this.capture, this.remove]) button.disabled = !active;
|
||||
const missing = active ? Object.keys(active.groups).filter(key => !groups.some(g => g.key === key)).length : 0;
|
||||
this.status.textContent = `${this.model.data.presets.length} ${T("presets")} · ${groups.length} ${T("groups")}${missing ? ` · ${missing} ${T("missing groups")}` : ""}${expected.stats.overlaps ? ` · ${T("Overlapping groups use the smaller group's setting")}` : ""}`;
|
||||
this.presets.scrollTop = navScroll; this.groups.scrollTop = groupScroll;
|
||||
}
|
||||
destroy() { clearInterval(this.timer); window.removeEventListener("wheel", this.onWheel, true); this.root.remove(); }
|
||||
}
|
||||
|
||||
app.registerExtension({
|
||||
name: "Adachi.GroupPresets",
|
||||
registerCustomNodes() {
|
||||
ensureStyle();
|
||||
class GroupPresetsNode extends LGraphNode {
|
||||
constructor() {
|
||||
super(T("Group Bypass Presets"));
|
||||
this.isVirtualNode = true; this.comfyClass = GROUP_PRESETS_TYPE;
|
||||
this.serialize_widgets = false;
|
||||
this.properties ??= {};
|
||||
this.adachiGroupPresets = new GroupPresetsPanel(this);
|
||||
const widget = this.addDOMWidget("group_presets", "adachi_group_presets", this.adachiGroupPresets.root, {
|
||||
serialize: false, hideOnZoom: false, getMinHeight: () => 290, getMaxHeight: () => 1600,
|
||||
});
|
||||
widget.serialize = false; this.setSize([620, 410]);
|
||||
}
|
||||
onAdded() { this.adachiGroupPresets.refresh(true); }
|
||||
onConfigure() { this.adachiGroupPresets.model.restore(); this.adachiGroupPresets.refresh(true); }
|
||||
onRemoved() { this.adachiGroupPresets.destroy(); }
|
||||
getExtraMenuOptions(_, options) {
|
||||
const panel = this.adachiGroupPresets;
|
||||
options.push(null, { content: T("Apply preset"), has_submenu: true, disabled: !panel.model.data.presets.length,
|
||||
submenu: { options: panel.model.data.presets.map(p => ({ content: `${p.id === panel.model.data.activeId ? "✓ " : ""}${p.name}`, callback: () => panel.apply(p.id) })) } },
|
||||
{ content: T("+ New preset"), callback: () => panel.showForm("add") },
|
||||
{ content: T("Save current group states"), disabled: !panel.model.active, callback: () => panel.model.saveCurrent() });
|
||||
}
|
||||
}
|
||||
GroupPresetsNode.title = T("Group Bypass Presets");
|
||||
GroupPresetsNode.desc = T("Switch saved group enable/bypass presets; no connections required.");
|
||||
LiteGraph.registerNodeType(GROUP_PRESETS_TYPE, GroupPresetsNode);
|
||||
GroupPresetsNode.category = "Adachi-Inpaint-Workbench";
|
||||
},
|
||||
});
|
||||
+216
@@ -0,0 +1,216 @@
|
||||
// Locale-aware labels for this plugin's own canvas UI.
|
||||
//
|
||||
// The English string in the call site is the default and the dictionary key, so any
|
||||
// missing translation falls back to English. ComfyUI's locales/ files only cover node
|
||||
// definitions (display name, category, sockets, tooltips); the custom panel and canvas
|
||||
// buttons are drawn by this plugin, so they translate here by reading Comfy.Locale.
|
||||
|
||||
const ZH = {
|
||||
"Mask: paint the full image. Crop & Blend: select a region, inpaint it, then adopt and blend the result.": "普通蒙版:在整图涂抹。裁切融合:选定局部、重绘,再从图像对比采用结果并融合图层。",
|
||||
"Crop resolution presets. Changing size releases the current selection; left-click the image to place a new region. Inpaint dimensions follow when selected.": "裁切分辨率预设。切换尺寸会取消当前选定,再左键点击图片定位新区域;选定后自动填写 Inpaint 宽高。",
|
||||
"Swap width and height, release the current selection, then left-click to place the new region.": "交换宽高并取消当前选定,再左键点击图片选择新区域。",
|
||||
"Edit layer blending: brush keeps the new result; Alt restores original pixels. Hold right-click to preview the original, release to return.": "编辑融合蒙版:画笔保留重绘结果,Alt 擦回原图。按住右键查看原图,松开恢复当前工作区。",
|
||||
"Merge the visible result and blend mask into the source image. After merging, right-click releases the selected region.": "将当前可见结果和融合蒙版合并到原图。合并后,右键恢复为取消选区。",
|
||||
"Undo the last stroke in the active repaint or blend mask (Ctrl+Z). Redo with Ctrl+Shift+Z.": "撤销当前重绘蒙版或融合蒙版的上一笔(Ctrl+Z);Ctrl+Shift+Z 可重做。",
|
||||
"Custom crop dimension in 64-pixel steps. Changing it releases the selected region.": "自定义裁切宽高,按 64 像素递增;修改尺寸会取消当前选定。",
|
||||
"Paint inside the selected region. Right-click releases the selection; left-click places a new one. Alt: erase. Ctrl+wheel: brush size; Shift+wheel: hardness.": "在选区内涂蒙版。右键取消选定,再左键选择新区域;Alt 擦除;Ctrl+滚轮调笔径,Shift+滚轮调硬度。",
|
||||
"Select a crop region before adopting a result": "请先选择裁切区域再采用结果",
|
||||
"Finish editing before adopting a result": "请结束当前编辑后再采用结果",
|
||||
"This result belongs to another crop; generate a result for the current region": "该结果来自其他选区,请为当前选区重新生成",
|
||||
"Result dimensions must match the selected crop": "结果宽高必须与当前裁切区域一致",
|
||||
"The crop changed while adopting the result": "采用过程中选区已改变,请重新生成结果",
|
||||
"Painting tools and mask settings": "绘图工具与蒙版设置",
|
||||
"Browser draft storage was full. The source was saved as an input file; the image, masks and layers are preserved.": "浏览器草稿空间不足,已将原图保存为图片文件;图像、蒙版和图层均已保留。",
|
||||
"Editing mode": "编辑模式",
|
||||
"Crop & Blend": "裁切融合",
|
||||
"Crop size": "裁切尺寸",
|
||||
"Custom": "自定义",
|
||||
"Swap crop dimensions": "交换宽高",
|
||||
"Choose another region": "重新选区(自动合并当前图层)",
|
||||
"Repaint mask": "重绘蒙版",
|
||||
"Blend layers: brush keeps new pixels; Alt restores original": "图层融合:画笔保留新图,Alt 擦回原图",
|
||||
"Merge the visible layers": "合并当前可见图层",
|
||||
"Group Bypass Presets": "组忽略预设 / Group Bypass Presets",
|
||||
"Switch saved group enable/bypass presets; no connections required.": "切换已保存的分组启用/忽略预设,无需接线。",
|
||||
"Group presets": "分组预设",
|
||||
"+ New preset": "+ 添加预设",
|
||||
"Preset name": "预设名称",
|
||||
"Save": "保存",
|
||||
"Cancel": "取消",
|
||||
"Presets": "预设列表",
|
||||
"Group states": "分组状态",
|
||||
"Rename": "改名",
|
||||
"Save current group states": "记住当前分组状态",
|
||||
"Delete preset": "删除预设",
|
||||
"Preset": "预设",
|
||||
"Apply preset": "应用预设",
|
||||
"Add a preset to get started": "添加第一套预设",
|
||||
"No groups in this workflow yet": "当前工作流还没有分组",
|
||||
"Keep current": "保持当前",
|
||||
"Enabled": "打开",
|
||||
"Bypassed": "忽略",
|
||||
"Current group state differs from the preset": "当前分组状态与预设不同",
|
||||
"Overlapping groups use the smaller group's setting": "重叠分组以较小分组的设置为准",
|
||||
"presets": "套预设",
|
||||
"groups": "个分组",
|
||||
"missing groups": "个分组已不存在",
|
||||
// compare.js
|
||||
"Result": "结果",
|
||||
"Choose result": "选择重绘结果",
|
||||
"Connect an original image and a result, then run the workflow": "连接原图与重绘结果,然后运行工作流",
|
||||
"Adopt into": "回填到",
|
||||
"Target inline editor": "接收结果的内联蒙版",
|
||||
"Adopt this result": "采用此结果",
|
||||
"Move to compare · wheel to zoom · middle-drag to pan": "鼠标移动对比 · 滚轮缩放 · 中键拖动",
|
||||
"Select an inline mask": "选择内联蒙版",
|
||||
"Adopting…": "采用中…",
|
||||
"Setting the result as the new source image…": "正在将结果设为新原图…",
|
||||
"Adopted: back in the inline mask, keep painting to inpaint again": "已采用:回到内联蒙版,可继续涂抹重绘",
|
||||
"Inline Mask": "内联蒙版",
|
||||
"No inline mask node is available to receive the result": "找不到接收结果的内联蒙版节点",
|
||||
"Result preview expired; run the workflow again": "结果预览已过期,请重新运行工作流",
|
||||
"Result image exceeds 64 MiB; downscale it first": "结果图片超过 64 MiB,请先缩小",
|
||||
|
||||
// editor.js
|
||||
"Cannot load image": "无法读取图像",
|
||||
"INLINE MASK": "内联蒙版 · INLINE MASK",
|
||||
"Load image": "载入原图",
|
||||
"Upload an image, or drop / paste one": "上传图片,也可拖放或粘贴",
|
||||
"Drop an image onto the canvas": "拖放图片到画布",
|
||||
"Brush": "画笔",
|
||||
"Brush (B)": "画笔 (B)",
|
||||
"Eraser": "橡皮",
|
||||
"Eraser (E); hold Alt for temporary erase": "橡皮 (E),按住 Alt 临时擦除",
|
||||
"Rectangle": "矩形",
|
||||
"Rectangle (R)": "矩形 (R)",
|
||||
"Lasso": "套索",
|
||||
"Freehand lasso (L)": "自由套索 (L)",
|
||||
"Pan": "移动",
|
||||
"Pan (H), or hold Space": "移动 (H),或按住空格",
|
||||
"Brush size": "笔径",
|
||||
"Hardness": "硬度",
|
||||
"Brush opacity": "笔触",
|
||||
"Overlay": "叠加",
|
||||
"Drop an image here": "把原图拖到这里",
|
||||
"Paint the areas to repaint directly in this node": "直接在节点中涂抹需要重绘的区域",
|
||||
"Undo": "撤销",
|
||||
"Undo (Ctrl+Z)": "撤销 (Ctrl+Z)",
|
||||
"Redo": "重做",
|
||||
"Redo (Ctrl+Shift+Z)": "重做 (Ctrl+Shift+Z)",
|
||||
"Invert": "反转",
|
||||
"Invert the painted mask": "反转绘制的蒙版",
|
||||
"Fill": "全选",
|
||||
"Fill the whole image with mask": "重绘整张图",
|
||||
"Clear": "清空",
|
||||
"Clear the mask": "清空蒙版",
|
||||
"Import mask": "导入蒙版",
|
||||
"White repaints, black preserves": "白色重绘,黑色保护",
|
||||
"Export": "导出",
|
||||
"Export the mask PNG at full resolution": "导出原始分辨率黑白蒙版",
|
||||
"Image": "原图",
|
||||
"Mask": "蒙版",
|
||||
"Fit": "适应",
|
||||
"Keep": "保持",
|
||||
"Upload": "上传",
|
||||
"Fit the image to the canvas": "适应画布",
|
||||
"File is too large (max 64 MB)": "图片文件不能超过 64 MB",
|
||||
"Loading image…": "正在载入原图…",
|
||||
"Embedded image": "内嵌原图",
|
||||
"Orange is the painted mask · Alt = temporary erase · Ctrl+wheel = brush size": "橙色为绘制蒙版 · Alt 临时擦除 · Ctrl+滚轮调笔径",
|
||||
"Image is too large; keep it under 32 MP and 16384 px per side": "图像超过 3200 万像素或单边 16384px,请先缩小",
|
||||
|
||||
// inline_inpaint.js
|
||||
"The inline mask node was removed": "内联蒙版节点已移除",
|
||||
"Adopted the result as the new source image; the mask and undo history were preserved": "已采用重绘结果作为新原图,蒙版与撤销记录已保留",
|
||||
"The result size must match the source image to preserve the mask": "为保留蒙版,重绘结果尺寸必须与原图一致",
|
||||
"Wait for the source image to finish loading before adopting a result": "请等待原图加载完成后再采用结果",
|
||||
"Drag to resize canvas height": "上下拖动调整画布高度",
|
||||
"Resize canvas height": "调整画布高度",
|
||||
"Upload failed": "上传失败",
|
||||
|
||||
// inpaint_node.js
|
||||
"Connect an inline mask to show the painting tools": "连接内联蒙版后显示画笔工具",
|
||||
"The painting tools live in the other inpaint node connected to this image": "画笔工具位于连接此原图的另一个重绘节点",
|
||||
|
||||
// inpaint_panel.js
|
||||
"WebUI Inpaint": "WebUI 局部重绘",
|
||||
"Controlled WebUI inpaint node": "控制的局部重绘节点",
|
||||
"Connect a WebUI inpaint node to edit its parameters here": "连接 WebUI 局部重绘节点后,在这里调整参数",
|
||||
"Mask mode": "重绘区域",
|
||||
"Fill content": "重绘参考内容",
|
||||
"Sampling area": "重绘画布",
|
||||
"Sampling resolution": "采样分辨率",
|
||||
"Use source size": "使用原图宽高",
|
||||
"Fill width and height from the current source image; aligned to 8 px and clamped to 64-8192 px": "填写当前原图宽高;按 8 的倍数对齐,并限制在 64–8192 像素",
|
||||
"Width": "宽度",
|
||||
"Height": "高度",
|
||||
"Denoise": "重绘幅度",
|
||||
"Sampler": "采样器",
|
||||
"Scheduler": "调度器",
|
||||
"Steps": "采样步数",
|
||||
"CFG scale": "提示词引导 CFG",
|
||||
"Seed": "随机种子",
|
||||
"After generate": "生成后种子",
|
||||
"Mask, batch and advanced settings": "蒙版、批量与高级设置",
|
||||
"Context padding": "蒙版外扩边距",
|
||||
"Mask blur": "蒙版模糊",
|
||||
"Mask grow / shrink": "蒙版扩张 / 收缩",
|
||||
"Batch size": "每张生成数量",
|
||||
"Resize mode": "缩放方式",
|
||||
"Use dedicated inpaint model": "使用专用 Inpaint 模型",
|
||||
"Extra edge feathering": "额外羽化边缘",
|
||||
"Feather strength": "额外羽化强度",
|
||||
"Refiner switch ratio": "Refiner 切换比例",
|
||||
|
||||
"Preview unavailable; run the workflow again": "预览已过期或无法加载,请重新运行",
|
||||
"Result left, original right; hover to compare": "左重绘结果、右原图,移动鼠标竖线对比",
|
||||
"Inline mask painting canvas; orange areas are repainted": "直接涂抹蒙版;橙色区域将被重绘",
|
||||
"Embed the source image in the workflow; no separate file needed when sharing": "原图嵌入工作流 · 分享时无需另传原图",
|
||||
"Alt = temporary erase · Ctrl+wheel = brush size · wheel = zoom · Space = pan": "Alt 临时擦除 · Ctrl+滚轮调笔径 · 滚轮缩放 / 空格拖动",
|
||||
|
||||
// enum values
|
||||
"enum:Inside mask": "蒙版内",
|
||||
"enum:Outside mask": "蒙版外",
|
||||
"enum:Fill": "填充",
|
||||
"enum:Original pixels": "原图像素",
|
||||
"enum:Latent noise": "潜空间噪声",
|
||||
"enum:Empty latent": "空白潜空间",
|
||||
"enum:Whole image": "整图重绘",
|
||||
"enum:Masked area only": "仅蒙版区域",
|
||||
"enum:Stretch": "拉伸",
|
||||
"enum:Center crop": "居中裁剪",
|
||||
"enum:Aspect fill": "保比例填充",
|
||||
"enum:Fixed": "固定种子",
|
||||
"enum:Increment": "生成后递增",
|
||||
"enum:Decrement": "生成后递减",
|
||||
"enum:Randomize": "生成后随机",
|
||||
};
|
||||
|
||||
const DICTS = { zh: ZH };
|
||||
|
||||
function readLocale() {
|
||||
try {
|
||||
const api = globalThis.comfyAPI;
|
||||
const value = api?.app?.ui?.settings?.getSettingValue?.("Comfy.Locale");
|
||||
if (value) return String(value);
|
||||
} catch (_) { /* settings unavailable before the app boots */ }
|
||||
try {
|
||||
const value = globalThis.app?.ui?.settings?.getSettingValue?.("Comfy.Locale");
|
||||
if (value) return String(value);
|
||||
} catch (_) { /* ignore */ }
|
||||
return "en";
|
||||
}
|
||||
|
||||
export function localeDict() {
|
||||
const base = readLocale().split("-")[0].toLowerCase();
|
||||
return DICTS[base] || null;
|
||||
}
|
||||
|
||||
// Translate a user-facing string. `context` disambiguates identical English strings
|
||||
// that need different translations (for example the Fill button and the Fill enum).
|
||||
export function T(text, context) {
|
||||
const dict = localeDict();
|
||||
if (!dict) return text;
|
||||
const key = context ? `${context}:${text}` : text;
|
||||
return dict[key] ?? text;
|
||||
}
|
||||
@@ -0,0 +1,668 @@
|
||||
import { CROP_PRESETS, cropAt } from "./crop_geometry.js?v=0.6.2";
|
||||
import { T } from "./i18n.js";
|
||||
import { syncCropDimensions } from "./parameter_bridge.js?v=0.6.4";
|
||||
import { installResultAdoption } from "./result_adoption.js?v=0.6.4";
|
||||
|
||||
const fields = ["mask", "baseMask", "history", "future", "lastMask", "dirty"];
|
||||
const canvas = (w, h) =>
|
||||
Object.assign(document.createElement("canvas"), { width: w, height: h });
|
||||
const load = async (url) => {
|
||||
const image = new Image();
|
||||
image.src = url;
|
||||
await image.decode();
|
||||
return image;
|
||||
};
|
||||
const make = (tag, cls) => {
|
||||
const e = document.createElement(tag);
|
||||
e.className = cls;
|
||||
return e;
|
||||
};
|
||||
|
||||
export class InlineCropController {
|
||||
constructor(
|
||||
node,
|
||||
editor,
|
||||
{ find, hide, changed, imageUrl, beforeModeChange },
|
||||
) {
|
||||
Object.assign(this, { node, editor, changed, imageUrl, beforeModeChange });
|
||||
this.widgets = Object.fromEntries(
|
||||
["edit_mode", "crop_state", "blend_data", "layer_image"].map((name) => [
|
||||
name,
|
||||
find(name),
|
||||
]),
|
||||
);
|
||||
Object.values(this.widgets).forEach(hide);
|
||||
this.contexts = {};
|
||||
this.target = "mask";
|
||||
this.layer = null;
|
||||
this.revision = 0;
|
||||
this.acceptVersion = 0;
|
||||
this.cropWidth = 1024;
|
||||
this.cropHeight = 1536;
|
||||
this.patchCanvas = canvas(1, 1);
|
||||
this.build();
|
||||
installResultAdoption(node, this);
|
||||
const originalFlush = editor.flush.bind(editor);
|
||||
editor.flush = () => {
|
||||
if (this.target !== "blend") return originalFlush();
|
||||
if (!editor.ready || !this.region?.locked)
|
||||
return this.widgets.blend_data.value;
|
||||
if (!editor.dirty && !editor.stroke) return this.widgets.blend_data.value;
|
||||
const r = this.region,
|
||||
out = canvas(r.width, r.height),
|
||||
ctx = out.getContext("2d");
|
||||
ctx.fillStyle = "black";
|
||||
ctx.fillRect(0, 0, r.width, r.height);
|
||||
ctx.drawImage(
|
||||
editor.mask,
|
||||
r.x,
|
||||
r.y,
|
||||
r.width,
|
||||
r.height,
|
||||
0,
|
||||
0,
|
||||
r.width,
|
||||
r.height,
|
||||
);
|
||||
this.widgets.blend_data.value = out.toDataURL("image/png");
|
||||
out.width = out.height = 0;
|
||||
editor.dirty = false;
|
||||
return this.widgets.blend_data.value;
|
||||
};
|
||||
editor.options.sceneRevision = () =>
|
||||
`${this.mode}:${this.target}:${this.revision}`;
|
||||
editor.options.drawSource = (ctx) => this.drawSource(ctx, {preview:this.previewOriginal});
|
||||
editor.options.displayView = () => this.previewOriginal ? "image" : editor.view;
|
||||
editor.options.showCursor = () => !this.previewOriginal;
|
||||
editor.options.showMask = () =>
|
||||
this.mode !== "crop" || (this.target === "mask" && this.region?.locked);
|
||||
editor.options.drawOverlay = (ctx, d) => this.drawOverlay(ctx, d);
|
||||
editor.options.paintBounds = () =>
|
||||
this.mode === "crop" && this.region?.locked ? this.region : undefined;
|
||||
const down = editor.pointerDown.bind(editor),
|
||||
move = editor.pointerMove.bind(editor);
|
||||
editor.pointerDown = (e) => {
|
||||
if (!editor.ready) return;
|
||||
if (this.previewOriginal) { e.preventDefault(); e.stopPropagation(); return; }
|
||||
if (this.busy) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
return;
|
||||
}
|
||||
if (this.mode === "crop" && e.button === 2) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
editor.root.focus({ preventScroll: true });
|
||||
if (this.layer && this.region.locked && !editor.stroke && editor.pointerId == null) {
|
||||
this.previewOriginal = true;
|
||||
this.originalPreviewPointer = e.pointerId;
|
||||
editor.canvas.setPointerCapture(e.pointerId);
|
||||
editor.cursor = null;
|
||||
this.revision++;
|
||||
editor.schedule();
|
||||
} else if (!this.layer && this.region.locked) this.run(() => this.reselect());
|
||||
return;
|
||||
}
|
||||
if (
|
||||
this.mode === "crop" &&
|
||||
!this.region?.locked &&
|
||||
e.button === 0 &&
|
||||
!editor.space
|
||||
) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
editor.root.focus({ preventScroll: true });
|
||||
const p = editor.point(e),
|
||||
r = cropAt(
|
||||
editor.image.width,
|
||||
editor.image.height,
|
||||
this.cropWidth,
|
||||
this.cropHeight,
|
||||
p.x,
|
||||
p.y,
|
||||
);
|
||||
if (r) this.lock(r);
|
||||
return;
|
||||
}
|
||||
down(e);
|
||||
};
|
||||
editor.pointerMove = (e) => {
|
||||
if (this.previewOriginal) { editor.cursor = null; return; }
|
||||
if (
|
||||
this.mode === "crop" &&
|
||||
editor.ready &&
|
||||
!this.region?.locked &&
|
||||
!editor.drag
|
||||
) {
|
||||
const p = editor.point(e);
|
||||
this.hover = cropAt(
|
||||
editor.image.width,
|
||||
editor.image.height,
|
||||
this.cropWidth,
|
||||
this.cropHeight,
|
||||
p.x,
|
||||
p.y,
|
||||
);
|
||||
}
|
||||
move(e);
|
||||
};
|
||||
this.finishPreview = event => {
|
||||
if (event.pointerId !== this.originalPreviewPointer) return;
|
||||
if (event.type === "pointerup" && (event.buttons & 2)) return;
|
||||
event.preventDefault(); event.stopPropagation();
|
||||
this.stopOriginalPreview();
|
||||
};
|
||||
for (const name of ["pointerup", "pointercancel"]) {
|
||||
window.addEventListener(name, this.finishPreview, true);
|
||||
}
|
||||
editor.canvas.addEventListener("lostpointercapture", this.finishPreview, true);
|
||||
this.previewBlur = () => this.stopOriginalPreview();
|
||||
window.addEventListener("blur", this.previewBlur);
|
||||
editor.canvas.addEventListener("pointerleave", () => {
|
||||
this.hover = null;
|
||||
editor.schedule();
|
||||
});
|
||||
editor.root.addEventListener("keydown", (e) => {
|
||||
if (e.key === "Escape" && this.mode === "crop" && !editor.stroke) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
this.reselect();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
get mode() {
|
||||
return this.widgets.edit_mode.value || "mask";
|
||||
}
|
||||
stopOriginalPreview() {
|
||||
if (!this.previewOriginal) return;
|
||||
const pointer = this.originalPreviewPointer;
|
||||
this.previewOriginal = false;
|
||||
this.originalPreviewPointer = null;
|
||||
if (pointer != null && this.editor.canvas.hasPointerCapture(pointer)) {
|
||||
this.editor.canvas.releasePointerCapture(pointer);
|
||||
}
|
||||
this.revision++;
|
||||
this.editor.schedule();
|
||||
}
|
||||
get region() {
|
||||
try {
|
||||
return JSON.parse(this.widgets.crop_state.value || "{}");
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
state(value) {
|
||||
this.widgets.crop_state.value = JSON.stringify(value);
|
||||
this.revision++;
|
||||
}
|
||||
snapshot() {
|
||||
return Object.fromEntries(fields.map((k) => [k, this.editor[k]]));
|
||||
}
|
||||
activate(target) {
|
||||
if (this.target === target) return;
|
||||
this.editor.flush();
|
||||
this.contexts[this.target] = this.snapshot();
|
||||
const next = this.contexts[target];
|
||||
if (!next) return;
|
||||
Object.assign(this.editor, next);
|
||||
this.target = target;
|
||||
this.editor.maskRevision++;
|
||||
this.editor.updateButtons();
|
||||
this.editor.schedule();
|
||||
this.sync();
|
||||
}
|
||||
build() {
|
||||
const e = this.editor;
|
||||
this.modeSelect = make("select", "dd-mode-select");
|
||||
this.modeSelect.setAttribute("aria-label", T("Editing mode"));
|
||||
this.modeSelect.title = T("Mask: paint the full image. Crop & Blend: select a region, inpaint it, then adopt and blend the result.");
|
||||
for (const [value, label] of [
|
||||
["mask", "Mask"],
|
||||
["crop", "Crop & Blend"],
|
||||
]) {
|
||||
const option = document.createElement("option");
|
||||
option.value = value;
|
||||
option.textContent = T(label);
|
||||
this.modeSelect.append(option);
|
||||
}
|
||||
this.modeSelect.onchange = () => this.setMode(this.modeSelect.value);
|
||||
e.root.append(this.modeSelect);
|
||||
this.bar = make("div", "dd-crop-bar");
|
||||
this.preset = make("select", "");
|
||||
this.preset.setAttribute("aria-label", T("Crop size"));
|
||||
this.preset.title = T("Crop resolution presets. Changing size releases the current selection; left-click the image to place a new region. Inpaint dimensions follow when selected.");
|
||||
for (const [w, h] of CROP_PRESETS) {
|
||||
const o = document.createElement("option");
|
||||
o.value = `${w}x${h}`;
|
||||
o.textContent = `${w} × ${h}`;
|
||||
this.preset.append(o);
|
||||
}
|
||||
const custom = document.createElement("option");
|
||||
custom.value = "custom";
|
||||
custom.textContent = T("Custom");
|
||||
this.preset.append(custom);
|
||||
this.preset.onchange = () => this.run(() => {
|
||||
const custom = this.preset.value === "custom";
|
||||
const [width, height] = custom
|
||||
? [this.cropWidth, this.cropHeight]
|
||||
: this.preset.value.split("x").map(Number);
|
||||
return this.changeSize(width, height, {custom});
|
||||
});
|
||||
this.bar.append(this.preset);
|
||||
const button = (text, title, action) =>
|
||||
e.button(this.bar, text, T(title), () => this.run(action));
|
||||
this.swapButton = button("⇄", "Swap width and height, release the current selection, then left-click to place the new region.", () =>
|
||||
this.changeSize(this.cropHeight, this.cropWidth),
|
||||
);
|
||||
// Shown in both modes: one click clears the mask of the active target.
|
||||
// It sits right after the swap control in Crop & Blend, and is the only
|
||||
// visible button in Mask mode.
|
||||
this.clearButton = button("🗑", "Clear the mask", () => e.action({ type: "clear" }));
|
||||
this.swapButton.after(this.clearButton);
|
||||
this.maskButton = button("◌", "Paint inside the selected region. Right-click releases the selection; left-click places a new one. Alt: erase. Ctrl+wheel: brush size; Shift+wheel: hardness.", () => {
|
||||
this.activate("mask");
|
||||
this.changed();
|
||||
});
|
||||
this.blendButton = button(
|
||||
"◐",
|
||||
"Edit layer blending: brush keeps the new result; Alt restores original pixels. Hold right-click to preview the original, release to return.",
|
||||
() => {
|
||||
this.activate("blend");
|
||||
this.changed();
|
||||
},
|
||||
);
|
||||
this.commitButton = button("✓", "Merge the visible result and blend mask into the source image. After merging, right-click releases the selected region.", () =>
|
||||
this.flatten(),
|
||||
);
|
||||
// Move the original live button, retaining its history and disabled state.
|
||||
this.undoButton = e.undoButton;
|
||||
this.undoButton.textContent = "↶";
|
||||
this.undoButton.title = T("Undo the last stroke in the active repaint or blend mask (Ctrl+Z). Redo with Ctrl+Shift+Z.");
|
||||
this.commitButton.after(this.undoButton);
|
||||
this.custom = make("div", "dd-crop-custom");
|
||||
this.custom.hidden = true;
|
||||
for (const key of ["cropWidth", "cropHeight"]) {
|
||||
const input = make("input", "");
|
||||
input.type = "number";
|
||||
input.min = 64;
|
||||
input.max = 16384;
|
||||
input.step = 64;
|
||||
input.value = this[key];
|
||||
input.setAttribute(
|
||||
"aria-label",
|
||||
T(key === "cropWidth" ? "Width" : "Height"),
|
||||
);
|
||||
input.title = T("Custom crop dimension in 64-pixel steps. Changing it releases the selected region.");
|
||||
input.onchange = () => this.run(() => {
|
||||
const value = Math.max(64, Math.min(16384, Math.round(Number(input.value) / 64) * 64));
|
||||
return this.changeSize(key === "cropWidth" ? value : this.cropWidth,
|
||||
key === "cropHeight" ? value : this.cropHeight, {custom:true});
|
||||
});
|
||||
this.custom.append(input);
|
||||
}
|
||||
this.bar.append(this.custom);
|
||||
e.root.append(this.bar);
|
||||
this.sync();
|
||||
}
|
||||
async run(action) {
|
||||
if (
|
||||
this.busy ||
|
||||
this.editor.stroke
|
||||
)
|
||||
return;
|
||||
try {
|
||||
await action();
|
||||
} catch (error) {
|
||||
this.editor.status(error.message, true);
|
||||
}
|
||||
}
|
||||
sync() {
|
||||
this.editor.root.classList.toggle("dd-crop-mode", this.mode === "crop");
|
||||
this.modeSelect.value = this.mode;
|
||||
// No hover text on the painting canvas; the bottom controls carry the hints.
|
||||
this.editor.canvas.removeAttribute("title");
|
||||
for (const control of [this.preset, this.swapButton, this.maskButton, this.blendButton, this.commitButton]) {
|
||||
control.hidden = this.mode !== "crop";
|
||||
}
|
||||
this.custom.hidden = this.mode !== "crop" || this.preset.value !== "custom";
|
||||
this.undoButton.disabled = !!this.busy || !this.editor.history.length;
|
||||
this.clearButton.disabled = !!this.busy || !this.editor.ready;
|
||||
this.blendButton.disabled = !this.layer;
|
||||
this.commitButton.disabled = !this.layer;
|
||||
this.maskButton.classList.toggle("dd-active", this.target === "mask");
|
||||
this.blendButton.classList.toggle("dd-active", this.target === "blend");
|
||||
this.modeSelect.disabled = !!this.busy;
|
||||
this.preset.disabled = !!this.busy;
|
||||
this.swapButton.disabled = !!this.busy;
|
||||
for (const input of this.custom.children)
|
||||
input.disabled = !!this.busy;
|
||||
}
|
||||
setMode(mode) {
|
||||
if (
|
||||
this.editor.stroke ||
|
||||
this.busy
|
||||
) {
|
||||
this.sync();
|
||||
return;
|
||||
}
|
||||
if (mode === this.mode) {
|
||||
this.sync();
|
||||
return;
|
||||
}
|
||||
const apply = () => {
|
||||
this.stopOriginalPreview();
|
||||
this.activate("mask");
|
||||
this.widgets.edit_mode.value = mode;
|
||||
this.state({ ...this.region, job: crypto.randomUUID() });
|
||||
this.editor.fit();
|
||||
this.sync();
|
||||
this.changed();
|
||||
};
|
||||
const recovery = this.beforeModeChange?.();
|
||||
if (!recovery?.then) {
|
||||
if (recovery !== false) apply();
|
||||
return;
|
||||
}
|
||||
this.busy = true;
|
||||
this.sync();
|
||||
return recovery
|
||||
.then((ok) => {
|
||||
this.busy = false;
|
||||
if (ok !== false && !this.editor.destroyed) apply();
|
||||
else this.sync();
|
||||
})
|
||||
.catch((error) => {
|
||||
this.busy = false;
|
||||
this.sync();
|
||||
this.editor.status(error.message, true);
|
||||
});
|
||||
}
|
||||
syncPreset() {
|
||||
const value = `${this.cropWidth}x${this.cropHeight}`;
|
||||
this.preset.value = [...this.preset.options].some((o) => o.value === value)
|
||||
? value
|
||||
: "custom";
|
||||
this.custom.hidden = this.preset.value !== "custom";
|
||||
[...this.custom.children].forEach(
|
||||
(e, i) => (e.value = i ? this.cropHeight : this.cropWidth),
|
||||
);
|
||||
}
|
||||
sizeChanged() {
|
||||
this.hover = null;
|
||||
this.editor.schedule();
|
||||
this.syncPreset();
|
||||
}
|
||||
async changeSize(width, height, {custom = false} = {}) {
|
||||
if (this.busy || this.editor.stroke) { this.syncPreset(); return; }
|
||||
try {
|
||||
// Use the same merge-before-reselect behavior as the reselect button.
|
||||
if (this.region.locked) await this.reselect();
|
||||
this.cropWidth = width;
|
||||
this.cropHeight = height;
|
||||
this.sizeChanged();
|
||||
if (custom) { this.preset.value = "custom"; this.custom.hidden = false; }
|
||||
this.sync();
|
||||
this.changed();
|
||||
} catch (error) {
|
||||
this.syncPreset();
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
reset() {
|
||||
this.stopOriginalPreview();
|
||||
this.layer = null;
|
||||
this.widgets.layer_image.value = "";
|
||||
this.widgets.blend_data.value = "";
|
||||
this.contexts = {};
|
||||
this.target = "mask";
|
||||
this.hover = null;
|
||||
this.state({ locked: false, job: crypto.randomUUID() });
|
||||
const { width, height } = this.editor.image;
|
||||
for (const o of this.preset.options)
|
||||
if (o.value !== "custom") {
|
||||
const [w, h] = o.value.split("x").map(Number);
|
||||
o.disabled = w > width || h > height;
|
||||
}
|
||||
if (this.cropWidth > width || this.cropHeight > height) {
|
||||
this.cropWidth = Math.min(1024, Math.floor(width / 64) * 64);
|
||||
this.cropHeight = Math.min(1536, Math.floor(height / 64) * 64);
|
||||
}
|
||||
this.syncPreset();
|
||||
this.sync();
|
||||
this.editor.schedule();
|
||||
}
|
||||
lock(region) {
|
||||
this.activate("mask");
|
||||
this.contexts.blend = null;
|
||||
this.layer = null;
|
||||
this.widgets.layer_image.value = "";
|
||||
this.widgets.blend_data.value = "";
|
||||
this.state({ ...region, locked: true, job: crypto.randomUUID() });
|
||||
const e = this.editor;
|
||||
// A new crop only limits the painting area; the repaint mask starts empty.
|
||||
for (const c of [e.mask, e.baseMask])
|
||||
c.getContext("2d").clearRect(0, 0, c.width, c.height);
|
||||
e.history = [];
|
||||
e.future = [];
|
||||
e.changed();
|
||||
syncCropDimensions(this.node, region.width, region.height);
|
||||
this.sync();
|
||||
this.changed();
|
||||
}
|
||||
makeBlend(data = "") {
|
||||
const r = this.region,
|
||||
e = this.editor,
|
||||
mask = canvas(e.image.width, e.image.height),
|
||||
baseMask = canvas(e.image.width, e.image.height);
|
||||
const ctx = mask.getContext("2d");
|
||||
ctx.fillStyle = "white";
|
||||
ctx.fillRect(r.x, r.y, r.width, r.height);
|
||||
baseMask.getContext("2d").drawImage(mask, 0, 0);
|
||||
this.contexts.blend = {
|
||||
mask,
|
||||
baseMask,
|
||||
history: [],
|
||||
future: [],
|
||||
lastMask: "",
|
||||
dirty: false,
|
||||
};
|
||||
if (!data) return Promise.resolve();
|
||||
return load(data).then((image) => {
|
||||
const out = canvas(r.width, r.height),
|
||||
c = out.getContext("2d");
|
||||
c.drawImage(image, 0, 0);
|
||||
const pixels = c.getImageData(0, 0, r.width, r.height);
|
||||
for (let i = 0; i < pixels.data.length; i += 4) {
|
||||
pixels.data[i + 3] = pixels.data[i];
|
||||
pixels.data[i] = pixels.data[i + 1] = pixels.data[i + 2] = 255;
|
||||
}
|
||||
ctx.clearRect(0, 0, mask.width, mask.height);
|
||||
ctx.putImageData(pixels, r.x, r.y);
|
||||
const base = baseMask.getContext("2d");
|
||||
base.clearRect(0, 0, baseMask.width, baseMask.height);
|
||||
base.drawImage(mask, 0, 0);
|
||||
out.width = out.height = 0;
|
||||
});
|
||||
}
|
||||
async restore() {
|
||||
this.stopOriginalPreview();
|
||||
this.target = "mask";
|
||||
this.contexts = {};
|
||||
this.layer = null;
|
||||
const r = this.region;
|
||||
if (r.locked) {
|
||||
this.cropWidth = r.width;
|
||||
this.cropHeight = r.height;
|
||||
this.syncPreset();
|
||||
if (this.widgets.layer_image.value) {
|
||||
this.layer = await load(this.imageUrl(this.widgets.layer_image.value));
|
||||
await this.makeBlend(this.widgets.blend_data.value);
|
||||
if (this.mode === "crop") this.activate("blend");
|
||||
}
|
||||
}
|
||||
this.revision++;
|
||||
this.sync();
|
||||
this.editor.schedule();
|
||||
}
|
||||
async accept(record, {allowBusy = false} = {}) {
|
||||
if (
|
||||
this.editor.destroyed ||
|
||||
this.mode !== "crop" ||
|
||||
!this.region.locked ||
|
||||
record.job !== this.region.job ||
|
||||
(this.busy && !allowBusy)
|
||||
)
|
||||
return;
|
||||
if (this.editor.stroke) {
|
||||
this.pendingResult = record;
|
||||
clearTimeout(this.resultTimer);
|
||||
this.resultTimer = setTimeout(() => {
|
||||
const next = this.pendingResult;
|
||||
this.pendingResult = null;
|
||||
this.accept(next).catch((error) =>
|
||||
this.editor.status(error.message, true),
|
||||
);
|
||||
}, 50);
|
||||
return;
|
||||
}
|
||||
const name = record.image.subfolder
|
||||
? `${record.image.subfolder}/${record.image.filename}`
|
||||
: record.image.filename;
|
||||
if (name === this.widgets.layer_image.value) return;
|
||||
const version = ++this.acceptVersion;
|
||||
const image = await load(this.imageUrl(name));
|
||||
if (
|
||||
this.editor.destroyed ||
|
||||
version !== this.acceptVersion ||
|
||||
record.job !== this.region.job ||
|
||||
this.mode !== "crop"
|
||||
)
|
||||
return;
|
||||
this.layer = image;
|
||||
this.widgets.layer_image.value = name;
|
||||
if (!this.contexts.blend && this.target !== "blend")
|
||||
await this.makeBlend(this.widgets.blend_data.value);
|
||||
this.activate("blend");
|
||||
this.revision++;
|
||||
this.sync();
|
||||
this.editor.schedule();
|
||||
this.changed();
|
||||
}
|
||||
drawSource(ctx, {preview = false} = {}) {
|
||||
if (this.mode !== "crop") return false;
|
||||
const e = this.editor,
|
||||
r = this.region;
|
||||
ctx.drawImage(e.image, 0, 0);
|
||||
if (!preview && this.layer && r.locked) {
|
||||
const key = `${this.revision}:${e.maskRevision}`;
|
||||
if (this.patchKey !== key) {
|
||||
this.patchCanvas.width = r.width;
|
||||
this.patchCanvas.height = r.height;
|
||||
const c = this.patchCanvas.getContext("2d");
|
||||
c.drawImage(this.layer, 0, 0);
|
||||
const mask =
|
||||
this.target === "blend" ? e.mask : this.contexts.blend?.mask;
|
||||
if (mask) {
|
||||
c.globalCompositeOperation = "destination-in";
|
||||
c.drawImage(
|
||||
mask,
|
||||
r.x,
|
||||
r.y,
|
||||
r.width,
|
||||
r.height,
|
||||
0,
|
||||
0,
|
||||
r.width,
|
||||
r.height,
|
||||
);
|
||||
c.globalCompositeOperation = "source-over";
|
||||
}
|
||||
this.patchKey = key;
|
||||
}
|
||||
ctx.drawImage(this.patchCanvas, r.x, r.y);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
drawOverlay(ctx, d) {
|
||||
if (this.mode !== "crop") return;
|
||||
const r = this.region.locked ? this.region : this.hover;
|
||||
if (!r) return;
|
||||
ctx.save();
|
||||
if (this.region.locked) {
|
||||
ctx.fillStyle = "#0008";
|
||||
ctx.beginPath();
|
||||
ctx.rect(0, 0, this.editor.image.width, this.editor.image.height);
|
||||
ctx.rect(r.x, r.y, r.width, r.height);
|
||||
ctx.fill("evenodd");
|
||||
}
|
||||
ctx.strokeStyle = "#000000";
|
||||
ctx.lineWidth = 1 / d.scale;
|
||||
ctx.setLineDash([6 / d.scale, 4 / d.scale]);
|
||||
ctx.strokeRect(r.x, r.y, r.width, r.height);
|
||||
ctx.restore();
|
||||
}
|
||||
async flatten() {
|
||||
if (!this.layer) return;
|
||||
this.stopOriginalPreview();
|
||||
this.editor.flush();
|
||||
this.busy = true;
|
||||
this.sync();
|
||||
try {
|
||||
const e = this.editor,
|
||||
c = canvas(e.image.width, e.image.height);
|
||||
this.drawSource(c.getContext("2d"));
|
||||
const blob = await new Promise((resolve) =>
|
||||
c.toBlob(resolve, "image/png"),
|
||||
);
|
||||
c.width = c.height = 0;
|
||||
this.activate("mask");
|
||||
await e.options.onUpload(
|
||||
new File([blob], `merged-${crypto.randomUUID()}.png`, {
|
||||
type: "image/png",
|
||||
}),
|
||||
{ preserveMask: true, preserveCrop: true },
|
||||
);
|
||||
this.layer = null;
|
||||
this.widgets.layer_image.value = "";
|
||||
this.widgets.blend_data.value = "";
|
||||
this.contexts.blend = null;
|
||||
this.state({ ...this.region, job: crypto.randomUUID() });
|
||||
} finally {
|
||||
this.busy = false;
|
||||
this.sync();
|
||||
this.editor.schedule();
|
||||
this.changed();
|
||||
}
|
||||
}
|
||||
async reselect() {
|
||||
if (
|
||||
this.busy ||
|
||||
this.editor.stroke
|
||||
)
|
||||
return;
|
||||
await this.flatten();
|
||||
this.activate("mask");
|
||||
this.state({ locked: false, job: crypto.randomUUID() });
|
||||
this.hover = null;
|
||||
this.sync();
|
||||
this.editor.schedule();
|
||||
this.changed();
|
||||
}
|
||||
destroy() {
|
||||
this.stopOriginalPreview();
|
||||
window.removeEventListener("blur", this.previewBlur);
|
||||
for (const name of ["pointerup", "pointercancel"]) {
|
||||
window.removeEventListener(name, this.finishPreview, true);
|
||||
}
|
||||
this.editor.canvas.removeEventListener("lostpointercapture", this.finishPreview, true);
|
||||
clearTimeout(this.resultTimer);
|
||||
this.pendingResult = null;
|
||||
this.acceptVersion++;
|
||||
for (const context of Object.values(this.contexts))
|
||||
for (const key of ["mask", "baseMask"])
|
||||
if (context?.[key] !== this.editor[key] && context?.[key])
|
||||
context[key].width = context[key].height = 0;
|
||||
this.patchCanvas.width = this.patchCanvas.height = 0;
|
||||
}
|
||||
}
|
||||
+110
-32
@@ -1,16 +1,19 @@
|
||||
import { app } from "../../scripts/app.js";
|
||||
import { api } from "../../scripts/api.js";
|
||||
import { InlineMaskEditor } from "./editor.js";
|
||||
import { installInpaintWorkbench } from "./inpaint_node.js";
|
||||
import { InlineMaskEditor } from "./editor.js?v=0.6.7";
|
||||
import { installInpaintWorkbench } from "./inpaint_node.js?v=0.6.1";
|
||||
import { bindWidgetToNodeWidth } from "./widget_layout.js?v=0.5.5";
|
||||
import { routeWheelOutsideImage } from "./wheel_routing.js";
|
||||
import { InlineCropController } from "./inline_crop.js?v=0.6.9";
|
||||
import { canStoreDraft, prepareInlineDraft, syncInlineWidgets } from "./draft_guard.js?v=0.6.3";
|
||||
import { T } from "./i18n.js";
|
||||
import { removeLegacyFeedback } from "./legacy_feedback.js?v=0.6.4";
|
||||
|
||||
const styleId = "adachi-inpaint-style";
|
||||
if (!document.getElementById(styleId)) {
|
||||
const link = document.createElement("link");
|
||||
link.id = styleId; link.rel = "stylesheet";
|
||||
link.href = new URL("./editor.css", import.meta.url).href;
|
||||
document.head.append(link);
|
||||
}
|
||||
const stylesheet = document.getElementById(styleId) || document.createElement("link");
|
||||
stylesheet.id = styleId; stylesheet.rel = "stylesheet";
|
||||
stylesheet.href = new URL("./editor.css?v=0.6.2", import.meta.url).href;
|
||||
if (!stylesheet.isConnected) document.head.append(stylesheet);
|
||||
|
||||
function hide(widget) {
|
||||
if (!widget) return;
|
||||
@@ -36,9 +39,44 @@ function imageUrl(value) {
|
||||
return api.apiURL(`/view?${params}`);
|
||||
}
|
||||
|
||||
function draftOptions() {
|
||||
let workspace = "personal";
|
||||
try { const current = JSON.parse(sessionStorage.getItem("Comfy.Workspace.Current") || "null"); if (current?.type !== "personal" && current?.id) workspace = current.id; } catch { /* Personal workspace. */ }
|
||||
return { workspace, path: app.extensionManager?.workflow?.activeWorkflow?.path || "" };
|
||||
}
|
||||
|
||||
async function uploadEmbeddedSource(embedded) {
|
||||
const blob = await (await fetch(embedded)).blob();
|
||||
if (blob.size > 64 * 1024 * 1024) throw Error(T("File is too large (max 64 MB)"));
|
||||
const body = new FormData();
|
||||
body.append("image", blob, `source-${crypto.randomUUID()}.png`);
|
||||
body.append("type", "input"); body.append("subfolder", "adachi-inpaint");
|
||||
const response = await api.fetchApi("/upload/image", {method:"POST", body});
|
||||
if (!response.ok) throw Error(`${T("Upload failed")} (${response.status})`);
|
||||
const uploaded = await response.json();
|
||||
if (typeof uploaded.name !== "string" || !uploaded.name) throw Error(T("Upload failed"));
|
||||
return uploaded.subfolder ? `${uploaded.subfolder}/${uploaded.name}` : uploaded.name;
|
||||
}
|
||||
|
||||
app.registerExtension({
|
||||
name: "Adachi.InlineInpaint",
|
||||
async beforeConfigureGraph(graphData) {
|
||||
removeLegacyFeedback(graphData);
|
||||
if (app.ui.settings.getSettingValue("Comfy.Workflow.Persist") === false) return;
|
||||
try {
|
||||
// The active workflow can still be the previous tab at this point;
|
||||
// do not claim its replacement credit for an incoming workflow.
|
||||
const options = { ...draftOptions(), path: "" };
|
||||
const count = await prepareInlineDraft(graphData, {
|
||||
fits: graph => canStoreDraft(graph, options), upload: uploadEmbeddedSource,
|
||||
});
|
||||
if (count) console.info(`[Adachi Inpaint] Saved ${count} oversized embedded source(s) as exact input files before workflow draft initialization. Masks and layers were preserved.`);
|
||||
} catch (error) {
|
||||
console.warn("[Adachi Inpaint] Draft preflight failed; embedded source data was retained.", error);
|
||||
}
|
||||
},
|
||||
async beforeRegisterNodeDef(nodeType, nodeData) {
|
||||
if (nodeData.name === "AdachiLayerCommit") { nodeType.skip_list = true; return; }
|
||||
if (["AdachiWebUIInpaint", "AdachiInpaintPrepare"].includes(nodeData.name)) { installInpaintWorkbench(nodeType); return; }
|
||||
if (nodeData.name !== "AdachiInlineMask") return;
|
||||
const originalCreated = nodeType.prototype.onNodeCreated;
|
||||
@@ -56,6 +94,9 @@ app.registerExtension({
|
||||
const find = name => node.widgets?.find(widget => widget.name === name);
|
||||
const imageWidget = find("image"), maskWidget = find("mask_data"), sourceWidget = find("source_data");
|
||||
for (const widget of [imageWidget, maskWidget, sourceWidget]) hide(widget);
|
||||
let crop;
|
||||
let draftRecovery = null;
|
||||
let draftNoticeTimer = 0;
|
||||
let restoring = false;
|
||||
let restoreFrame = 0;
|
||||
let uploadVersion = 0;
|
||||
@@ -64,12 +105,11 @@ app.registerExtension({
|
||||
cancelAnimationFrame(fitFrame);
|
||||
fitFrame = requestAnimationFrame(() => {
|
||||
if (!editor.ready || editor.destroyed || !node.graph) return;
|
||||
const rect = editor.canvas.getBoundingClientRect();
|
||||
const scale = app.canvas?.ds?.scale || 1;
|
||||
if (!rect.width || !rect.height) return;
|
||||
const overhead = node.size[1] - rect.height / scale;
|
||||
const height = overhead + rect.width / scale * editor.image.height / editor.image.width;
|
||||
node.setSize([node.size[0], Math.max(240, Math.min(4200, Math.ceil(height)))]);
|
||||
const width = editor.canvas.clientWidth, height = editor.canvas.clientHeight;
|
||||
if (!width || !height) return;
|
||||
const overhead = node.size[1] - height;
|
||||
const fittedHeight = overhead + width * editor.image.height / editor.image.width;
|
||||
node.setSize([node.size[0], Math.max(240, Math.min(4200, Math.ceil(fittedHeight)))]);
|
||||
node.properties.adachi_compact_ui = true;
|
||||
editor.schedule();
|
||||
});
|
||||
@@ -80,7 +120,7 @@ app.registerExtension({
|
||||
if (!embedded && !filename) return;
|
||||
restoring = true;
|
||||
editor.embed.checked = !!embedded;
|
||||
try { await editor.setImage(embedded || imageUrl(filename), maskWidget?.value || "", embedded ? "内嵌原图 / Embedded image" : filename); }
|
||||
try { crop?.activate("mask"); await editor.setImage(embedded || imageUrl(filename), maskWidget?.value || "", embedded ? T("Embedded image") : filename); await crop?.restore(); }
|
||||
catch (error) { console.warn("[Adachi Inpaint]", error); }
|
||||
finally { restoring = false; }
|
||||
};
|
||||
@@ -88,39 +128,75 @@ app.registerExtension({
|
||||
compact: true,
|
||||
onChange(data) { if (maskWidget && !restoring) maskWidget.value = data; },
|
||||
onDirty() { markChanged(); },
|
||||
onKeepFit(enabled) { node.properties.adachi_keep_fit = enabled; markChanged(); },
|
||||
onImage() { if (!restoring || !node.properties.adachi_compact_ui) fitNodeToImage(); },
|
||||
onGraphWheel: event => app.canvas?.processMouseWheel(event),
|
||||
async onUpload(file) {
|
||||
async onUpload(file, { preserveMask = false, preserveCrop = false } = {}) {
|
||||
if (preserveMask && editor.image && !editor.ready) throw new Error(T("Wait for the source image to finish loading before adopting a result"));
|
||||
const version = ++uploadVersion;
|
||||
const body = new FormData();
|
||||
body.append("image", file, file.name);
|
||||
body.append("type", "input");
|
||||
body.append("subfolder", "adachi-inpaint");
|
||||
const response = await api.fetchApi("/upload/image", { method: "POST", body });
|
||||
if (!response.ok) throw new Error(`上传失败 / Upload failed (${response.status})`);
|
||||
if (!response.ok) throw new Error(`${T("Upload failed")} (${response.status})`);
|
||||
const uploaded = await response.json();
|
||||
if (version !== uploadVersion || editor.destroyed) return;
|
||||
const name = uploaded.subfolder ? `${uploaded.subfolder}/${uploaded.name}` : uploaded.name;
|
||||
imageWidget.value = name;
|
||||
maskWidget.value = "";
|
||||
sourceWidget.value = "";
|
||||
restoring = false;
|
||||
await editor.setImage(imageUrl(name), "", file.name);
|
||||
if (editor.embed.checked) sourceWidget.value = editor.sourceData();
|
||||
crop?.activate("mask");
|
||||
if (preserveMask && editor.ready) await editor.replaceSource(imageUrl(name), file.name);
|
||||
else await editor.setImage(imageUrl(name), "", file.name);
|
||||
if (version !== uploadVersion || editor.destroyed) return;
|
||||
imageWidget.value = name;
|
||||
maskWidget.value = preserveMask ? editor.flush() : "";
|
||||
sourceWidget.value = editor.embed.checked ? editor.sourceData() : "";
|
||||
if (!preserveCrop) crop?.reset();
|
||||
await beforeModeChange();
|
||||
markChanged();
|
||||
},
|
||||
onEmbed(enabled) {
|
||||
if (sourceWidget) sourceWidget.value = enabled ? editor.sourceData() : "";
|
||||
const recovery = enabled ? beforeModeChange() : null;
|
||||
if (recovery?.then) return recovery.then(() => markChanged()).catch(error => editor.status(error.message, true));
|
||||
markChanged();
|
||||
},
|
||||
});
|
||||
editor.root.dataset.adachiVersion = "0.6.7";
|
||||
const beforeModeChange = () => {
|
||||
if (draftRecovery) return draftRecovery;
|
||||
const embedded = sourceWidget?.value;
|
||||
if (!editor.ready || !embedded?.startsWith("data:") || embedded.length < 256 * 1024) return;
|
||||
if (app.ui.settings.getSettingValue("Comfy.Workflow.Persist") === false) return;
|
||||
const graph = app.rootGraph || node.graph;
|
||||
if (canStoreDraft(graph.serialize(), draftOptions()) !== false) return;
|
||||
// Persist a fresh, exact copy before dropping any embedded bytes.
|
||||
// This also repairs portable workflows whose original input path is absent.
|
||||
draftRecovery = (async () => {
|
||||
const version = editor.loadVersion;
|
||||
const name = await uploadEmbeddedSource(embedded);
|
||||
if (editor.destroyed || editor.loadVersion !== version || sourceWidget.value !== embedded) return false;
|
||||
imageWidget.value = name;
|
||||
sourceWidget.value = ""; editor.embed.checked = false;
|
||||
editor.message.textContent = T("Browser draft storage was full. The source was saved as an input file; the image, masks and layers are preserved.");
|
||||
editor.message.classList.remove("dd-error"); editor.message.hidden = false;
|
||||
const notice = editor.message.textContent;
|
||||
clearTimeout(draftNoticeTimer);
|
||||
draftNoticeTimer = setTimeout(() => { if (!editor.destroyed && editor.message.textContent === notice) editor.message.hidden = true; }, 8000);
|
||||
return true;
|
||||
})().finally(() => { draftRecovery = null; });
|
||||
return draftRecovery;
|
||||
};
|
||||
crop = new InlineCropController(node, editor, {find, hide, changed:markChanged, imageUrl, beforeModeChange});
|
||||
node.adachiCrop = crop;
|
||||
node.adachiEditor = editor;
|
||||
const stopWheelRouting = routeWheelOutsideImage(editor.root, editor.canvas, () => editor.ready);
|
||||
node.adachiUseResult = async file => {
|
||||
if (editor.destroyed) throw new Error("内联蒙版节点已移除");
|
||||
await editor.options.onUpload(file);
|
||||
node.adachiUseResult = async (file, origin) => {
|
||||
if (editor.destroyed) throw new Error(T("The inline mask node was removed"));
|
||||
if (crop.mode === "crop") return node.adachiAdoptCrop(file, origin);
|
||||
await editor.options.onUpload(file, { preserveMask: true });
|
||||
editor.view = "overlay"; editor.updateButtons(); editor.schedule();
|
||||
editor.status("已采用重绘结果作为新原图,旧蒙版已清空");
|
||||
editor.status(T("Adopted the result as the new source image; the mask and undo history were preserved"));
|
||||
};
|
||||
const domWidget = node.addDOMWidget("adachi_canvas", "adachi_inline_mask", editor.root, {
|
||||
serialize: false,
|
||||
@@ -129,16 +205,17 @@ app.registerExtension({
|
||||
getMaxHeight: () => 4096,
|
||||
});
|
||||
domWidget.serialize = false;
|
||||
bindWidgetToNodeWidth(node, domWidget, editor.root);
|
||||
// Leave computeLayoutSize in charge: a fixed computeSize height
|
||||
// prevents the DOM canvas from growing with the node vertically.
|
||||
const resizeHandle = document.createElement("div");
|
||||
resizeHandle.className = "dd-resize-handle";
|
||||
resizeHandle.textContent = "↕";
|
||||
resizeHandle.title = "上下拖动调整画布高度 / Drag to resize canvas height";
|
||||
resizeHandle.title = T("Drag to resize canvas height");
|
||||
resizeHandle.tabIndex = 0;
|
||||
resizeHandle.setAttribute("role", "separator");
|
||||
resizeHandle.setAttribute("aria-orientation", "horizontal");
|
||||
resizeHandle.setAttribute("aria-label", "调整画布高度 / Resize canvas height");
|
||||
resizeHandle.setAttribute("aria-label", T("Resize canvas height"));
|
||||
editor.root.append(resizeHandle);
|
||||
let resizing = null;
|
||||
const resizeHeight = height => {
|
||||
@@ -179,23 +256,24 @@ app.registerExtension({
|
||||
};
|
||||
const previousSerializeNode = node.onSerialize;
|
||||
node.onSerialize = function (data) {
|
||||
const result = previousSerializeNode?.apply(this, arguments);
|
||||
editor.flush();
|
||||
const index = node.widgets.indexOf(maskWidget);
|
||||
if (data?.widgets_values && index >= 0) data.widgets_values[index] = maskWidget.value;
|
||||
return previousSerializeNode?.apply(this, arguments);
|
||||
if (data) syncInlineWidgets(data, node.widgets);
|
||||
return result;
|
||||
};
|
||||
const previousQueued = maskWidget.beforeQueued;
|
||||
maskWidget.beforeQueued = function () { editor.flush(); return previousQueued?.apply(this, arguments); };
|
||||
const previousConfigure = node.onConfigure;
|
||||
node.onConfigure = function () {
|
||||
const configured = previousConfigure?.apply(this, arguments);
|
||||
editor.setKeepFit(!!node.properties.adachi_keep_fit, false);
|
||||
cancelAnimationFrame(restoreFrame); restoreFrame = requestAnimationFrame(restore);
|
||||
return configured;
|
||||
};
|
||||
const previousImageCallback = imageWidget.callback;
|
||||
imageWidget.callback = function () { previousImageCallback?.apply(this, arguments); restore(); };
|
||||
const previousRemoved = node.onRemoved;
|
||||
node.onRemoved = function () { cancelAnimationFrame(restoreFrame); cancelAnimationFrame(fitFrame); stopWheelRouting(); editor.destroy(); return previousRemoved?.apply(this, arguments); };
|
||||
node.onRemoved = function () { clearTimeout(draftNoticeTimer); cancelAnimationFrame(restoreFrame); cancelAnimationFrame(fitFrame); stopWheelRouting(); crop.destroy(); editor.destroy(); return previousRemoved?.apply(this, arguments); };
|
||||
node.setSize([Math.max(380, node.size[0]), Math.max(480, node.size[1])]);
|
||||
restoreFrame = requestAnimationFrame(restore);
|
||||
return result;
|
||||
|
||||
+33
-10
@@ -1,17 +1,26 @@
|
||||
import { app } from "../../scripts/app.js";
|
||||
import { InpaintParameterPanel } from "./inpaint_panel.js";
|
||||
import { InpaintParameterPanel } from "./inpaint_panel.js?v=0.6.1";
|
||||
import { connectedEditor, connectedSamplers, relocateWidgets } from "./parameter_bridge.js";
|
||||
import { routeWheelOutsideImage } from "./wheel_routing.js";
|
||||
import { T } from "./i18n.js";
|
||||
import { bindWidgetToNodeWidth } from "./widget_layout.js?v=0.5.5";
|
||||
|
||||
export function installInpaintWorkbench(nodeType) {
|
||||
const created = nodeType.prototype.onNodeCreated;
|
||||
nodeType.prototype.onNodeCreated = function () {
|
||||
const result = created?.apply(this, arguments), node = this;
|
||||
const root = document.createElement("div"); root.className = "dd-inpaint dd-workbench";
|
||||
const fold = document.createElement("details"); fold.className = "dd-workbench-fold";
|
||||
const summary = document.createElement("summary"); summary.textContent = T("Painting tools and mask settings");
|
||||
summary.addEventListener("pointerdown", event => event.stopPropagation());
|
||||
summary.addEventListener("click", event => event.stopPropagation());
|
||||
fold.append(summary);
|
||||
const tools = document.createElement("div"); tools.className = "dd-workbench-tools";
|
||||
const placeholder = document.createElement("div"); placeholder.className = "dd-param-placeholder dd-tools-placeholder";
|
||||
placeholder.textContent = "连接内联蒙版后显示画笔工具";
|
||||
tools.append(placeholder); root.append(tools);
|
||||
placeholder.textContent = T("Connect an inline mask to show the painting tools");
|
||||
tools.append(placeholder); fold.append(tools);
|
||||
const actionHost = document.createElement("div"); actionHost.className = "dd-workbench-actions";
|
||||
root.append(fold, actionHost);
|
||||
let source = null, mountedEditor = null, frame = 0, removed = false;
|
||||
const markChanged = () => {
|
||||
app.canvas?.emitBeforeChange?.(); app.canvas?.emitAfterChange?.();
|
||||
@@ -26,14 +35,15 @@ export function installInpaintWorkbench(nodeType) {
|
||||
const next = canMount ? editor : null;
|
||||
if (next !== mountedEditor) {
|
||||
if (mountedEditor?.controls.parentElement === tools) mountedEditor.controls.remove();
|
||||
if (mountedEditor?.actions.parentElement === actionHost) mountedEditor.actions.remove();
|
||||
mountedEditor = next;
|
||||
if (next) tools.append(next.controls);
|
||||
if (next) { tools.append(next.controls); actionHost.append(next.actions); }
|
||||
scheduleSize();
|
||||
}
|
||||
placeholder.hidden = !!next;
|
||||
placeholder.textContent = editor ? "画笔工具位于连接此原图的另一个重绘节点" : "连接内联蒙版后显示画笔工具";
|
||||
placeholder.textContent = editor ? T("The painting tools live in the other inpaint node connected to this image") : T("Connect an inline mask to show the painting tools");
|
||||
};
|
||||
const contentHeight = () => (tools.scrollHeight || 30) + (panel?.root.scrollHeight || 620);
|
||||
const contentHeight = () => fold.offsetHeight + actionHost.offsetHeight + (panel?.root.scrollHeight || 620);
|
||||
const scheduleSize = () => {
|
||||
cancelAnimationFrame(frame);
|
||||
frame = requestAnimationFrame(() => {
|
||||
@@ -44,28 +54,41 @@ export function installInpaintWorkbench(nodeType) {
|
||||
});
|
||||
};
|
||||
let panel;
|
||||
fold.open = !!node.properties.adachi_tools_open;
|
||||
fold.ontoggle = () => {
|
||||
if (node.properties.adachi_tools_open !== fold.open) {
|
||||
node.properties.adachi_tools_open = fold.open; markChanged();
|
||||
}
|
||||
scheduleSize();
|
||||
};
|
||||
panel = new InpaintParameterPanel({
|
||||
getTargets: () => { refreshEditor(); return [node]; },
|
||||
getImage: () => source?.adachiEditor?.ready ? source.adachiEditor.image : null,
|
||||
getImage: () => source?.adachiEditor?.ready ? (source.adachiCrop?.mode === "crop" && source.adachiCrop.region.locked ? source.adachiCrop.region : source.adachiEditor.image) : null,
|
||||
onTargetChange: (previous, next) => relocateWidgets(node, previous, next),
|
||||
onDirty: markChanged, onHeight: scheduleSize,
|
||||
onMaskSettings: element => {
|
||||
fold.querySelector(".dd-param-mask-settings")?.remove();
|
||||
fold.append(element); scheduleSize();
|
||||
},
|
||||
});
|
||||
root.append(panel.root);
|
||||
node.adachiParameters = panel; node.adachiWorkbench = { root, tools, get source() { return source; } };
|
||||
node.adachiParameters = panel; node.adachiWorkbench = { root, tools, fold, actionHost, get source() { return source; } };
|
||||
const stopWheelRouting = routeWheelOutsideImage(root, null, () => false);
|
||||
const widget = node.addDOMWidget("adachi_workbench", "adachi_inpaint_controls", root, {
|
||||
serialize: false, hideOnZoom: false, getMinHeight: contentHeight, getMaxHeight: () => Math.max(4096, contentHeight()),
|
||||
});
|
||||
widget.serialize = false;
|
||||
const observer = new ResizeObserver(scheduleSize); observer.observe(tools);
|
||||
bindWidgetToNodeWidth(node, widget, root);
|
||||
const observer = new ResizeObserver(scheduleSize); observer.observe(tools); observer.observe(fold); observer.observe(actionHost);
|
||||
const configured = node.onConfigure;
|
||||
node.onConfigure = function () { const result = configured?.apply(this, arguments); queueMicrotask(() => { if (!removed) { panel.refresh(); scheduleSize(); } }); return result; };
|
||||
node.onConfigure = function () { const result = configured?.apply(this, arguments); fold.open = !!node.properties.adachi_tools_open; queueMicrotask(() => { if (!removed) { panel.refresh(); scheduleSize(); } }); return result; };
|
||||
const connections = node.onConnectionsChange;
|
||||
node.onConnectionsChange = function () { const result = connections?.apply(this, arguments); queueMicrotask(() => { if (!removed) panel.refresh(); }); return result; };
|
||||
const previousRemoved = node.onRemoved;
|
||||
node.onRemoved = function () {
|
||||
removed = true; cancelAnimationFrame(frame); observer.disconnect();
|
||||
if (mountedEditor?.controls.parentElement === tools) mountedEditor.controls.remove();
|
||||
if (mountedEditor?.actions.parentElement === actionHost) mountedEditor.actions.remove();
|
||||
panel.destroy(); stopWheelRouting(); root.remove();
|
||||
return previousRemoved?.apply(this, arguments);
|
||||
};
|
||||
|
||||
+40
-33
@@ -1,22 +1,23 @@
|
||||
/* Inline controls edit the connected sampler's real widgets, not a second set of parameters. */
|
||||
import { T } from "./i18n.js";
|
||||
const el = (tag, cls, text) => { const e = document.createElement(tag); if (cls) e.className = cls; if (text) e.textContent = text; return e; };
|
||||
export const INPAINT_FIELDS = ["mask_mode", "fill", "area", "padding", "width", "height", "denoise", "sampler_name", "scheduler", "steps", "cfg", "seed", "control_after_generate", "batch_size", "mask_blur", "mask_grow", "resize_mode", "inpaint_model", "soft_edge", "soft_strength", "refiner_switch"];
|
||||
const choices = {
|
||||
mask_mode: { inside: "蒙版内", outside: "蒙版外" },
|
||||
fill: { fill: "填充", original: "原图像素", latent_noise: "潜空间噪声", latent_nothing: "空白潜空间" },
|
||||
area: { whole_image: "整图重绘", only_masked: "仅蒙版区域" },
|
||||
resize_mode: { stretch: "拉伸", crop: "居中裁剪", fill: "保比例填充" },
|
||||
control_after_generate: { fixed: "固定种子", increment: "生成后递增", decrement: "生成后递减", randomize: "生成后随机" },
|
||||
mask_mode: { inside: "Inside mask", outside: "Outside mask" },
|
||||
fill: { fill: "Fill", original: "Original pixels", latent_noise: "Latent noise", latent_nothing: "Empty latent" },
|
||||
area: { whole_image: "Whole image", only_masked: "Masked area only" },
|
||||
resize_mode: { stretch: "Stretch", crop: "Center crop", fill: "Aspect fill" },
|
||||
control_after_generate: { fixed: "Fixed", increment: "Increment", decrement: "Decrement", randomize: "Randomize" },
|
||||
};
|
||||
|
||||
export class InpaintParameterPanel {
|
||||
constructor(options) {
|
||||
this.options = options; this.bindings = []; this.root = el("section", "dd-parameters");
|
||||
const header = el("div", "dd-param-header"); header.append(el("strong", "", "局部重绘"));
|
||||
this.targetSelect = el("select"); this.targetSelect.setAttribute("aria-label", "控制的局部重绘节点");
|
||||
const header = el("div", "dd-param-header"); header.append(el("strong", "", T("WebUI Inpaint")));
|
||||
this.targetSelect = el("select"); this.targetSelect.setAttribute("aria-label", T("Controlled WebUI inpaint node"));
|
||||
this.targetSelect.onchange = () => { this.preferred = this.targetSelect.value; this.options.onPreferred?.(this.preferred); this.refresh(); };
|
||||
header.append(this.targetSelect); this.root.append(header);
|
||||
this.placeholder = el("div", "dd-param-placeholder", "连接 WebUI 局部重绘节点后,在这里调整参数");
|
||||
this.placeholder = el("div", "dd-param-placeholder", T("Connect a WebUI inpaint node to edit its parameters here"));
|
||||
this.body = el("div", "dd-param-body"); this.root.append(this.placeholder, this.body);
|
||||
this.observer = new ResizeObserver(() => options.onHeight?.()); this.observer.observe(this.root);
|
||||
this.timer = setInterval(() => { if (this.root.isConnected && !document.hidden) this.refresh(); }, 350);
|
||||
@@ -30,7 +31,7 @@ export class InpaintParameterPanel {
|
||||
const signature = targets.map(n => `${n.id}:${n.title}`).join("|");
|
||||
if (signature !== this.signature) {
|
||||
this.signature = signature; this.targetSelect.replaceChildren();
|
||||
for (const n of targets) { const option = el("option", "", `${n.title || "局部重绘"} #${n.id}`); option.value = String(n.id); this.targetSelect.append(option); }
|
||||
for (const n of targets) { const option = el("option", "", `${n.title || T("WebUI Inpaint")} #${n.id}`); option.value = String(n.id); this.targetSelect.append(option); }
|
||||
}
|
||||
this.targetSelect.hidden = targets.length < 2;
|
||||
if (next) this.targetSelect.value = String(next.id);
|
||||
@@ -56,20 +57,22 @@ export class InpaintParameterPanel {
|
||||
|
||||
enum(parent, name, label, pills = false) {
|
||||
const widget = this.widget(name); if (!widget) return;
|
||||
label = T(label);
|
||||
const wrapper = el("div", "dd-param-field"); wrapper.append(el("span", "dd-param-label", label));
|
||||
let values = widget.options?.values; if (typeof values === "function") values = values();
|
||||
if (!Array.isArray(values)) values = Object.keys(choices[name] || {});
|
||||
if (!values.includes(widget.value)) values = [widget.value, ...values];
|
||||
const display = value => choices[name]?.[value] ? T(choices[name][value], "enum") : String(value);
|
||||
if (pills) {
|
||||
const row = el("div", "dd-param-pills");
|
||||
const buttons = values.map(value => {
|
||||
const button = el("button", "", choices[name]?.[value] || String(value)); button.type = "button";
|
||||
const button = el("button", "", display(value)); button.type = "button";
|
||||
button.onclick = () => { this.write(name, value, true); this.refresh(); }; row.append(button); return { button, value };
|
||||
});
|
||||
wrapper.append(row); this.bindings.push({ sync: () => { for (const {button,value} of buttons) { button.classList.toggle("dd-active", widget.value === value); button.setAttribute("aria-pressed", String(widget.value === value)); button.disabled = this.linked(name); } } });
|
||||
} else {
|
||||
const select = el("select"); select.setAttribute("aria-label", label);
|
||||
for (const value of values) { const option = el("option", "", choices[name]?.[value] || String(value)); option.value = value; select.append(option); }
|
||||
for (const value of values) { const option = el("option", "", display(value)); option.value = value; select.append(option); }
|
||||
select.onchange = () => this.write(name, select.value, true); wrapper.append(select);
|
||||
this.bindings.push({ sync: () => { if (document.activeElement !== select) select.value = widget.value; select.disabled = this.linked(name); } });
|
||||
}
|
||||
@@ -78,6 +81,7 @@ export class InpaintParameterPanel {
|
||||
|
||||
number(parent, name, label, { min, max, step = 1, range = false, rangeMax = max } = {}) {
|
||||
const widget = this.widget(name); if (!widget) return;
|
||||
label = T(label);
|
||||
min ??= widget.options?.min ?? 0; max ??= widget.options?.max ?? 1000000;
|
||||
const wrapper = el("label", "dd-param-field"); const row = el("span", "dd-param-number-label"); row.append(el("span", "", label));
|
||||
const input = el("input"); input.type = "number"; input.min = min; input.max = max; input.step = step; input.setAttribute("aria-label", label); row.append(input); wrapper.append(row);
|
||||
@@ -90,7 +94,7 @@ export class InpaintParameterPanel {
|
||||
};
|
||||
input.oninput = () => update(input.value); input.onchange = () => { update(input.value); input.value = widget.value; this.options.onDirty?.(); };
|
||||
if (range) {
|
||||
slider = el("input"); slider.type = "range"; slider.min = min; slider.max = rangeMax ?? max; slider.step = step; slider.setAttribute("aria-label", `${label}滑条`);
|
||||
slider = el("input"); slider.type = "range"; slider.min = min; slider.max = rangeMax ?? max; slider.step = step; slider.setAttribute("aria-label", `${label} slider`);
|
||||
slider.oninput = () => { update(slider.value); input.value = widget.value; }; slider.onchange = () => this.options.onDirty?.(); wrapper.append(slider);
|
||||
}
|
||||
this.bindings.push({ sync: () => {
|
||||
@@ -103,19 +107,22 @@ export class InpaintParameterPanel {
|
||||
toggle(parent, name, label) {
|
||||
const widget = this.widget(name); if (!widget) return;
|
||||
const wrapper = el("label", "dd-param-toggle"), input = el("input"); input.type = "checkbox";
|
||||
input.onchange = () => this.write(name, input.checked, true); wrapper.append(input, document.createTextNode(label)); parent.append(wrapper);
|
||||
input.onchange = () => this.write(name, input.checked, true); wrapper.append(input, document.createTextNode(T(label))); parent.append(wrapper);
|
||||
this.bindings.push({ sync: () => { input.checked = !!widget.value; input.disabled = this.linked(name); } });
|
||||
}
|
||||
|
||||
grid(parent) { const grid = el("div", "dd-param-grid"); parent.append(grid); return grid; }
|
||||
|
||||
build() {
|
||||
this.enum(this.body, "mask_mode", "重绘区域", true);
|
||||
this.enum(this.body, "fill", "重绘参考内容", true);
|
||||
this.enum(this.body, "area", "重绘画布", true);
|
||||
const resolution = el("div", "dd-param-resolution"); resolution.append(el("span", "dd-param-label", "采样分辨率"));
|
||||
this.sourceSize = el("button", "", "使用原图宽高"); this.sourceSize.type = "button";
|
||||
this.sourceSize.title = "填写当前原图宽高;按 8 的倍数对齐,并限制在 64–8192 像素";
|
||||
this.maskSettings = el("div", "dd-param-mask-settings");
|
||||
this.enum(this.maskSettings, "mask_mode", "Mask mode", true);
|
||||
this.enum(this.maskSettings, "fill", "Fill content", true);
|
||||
this.body.append(this.maskSettings);
|
||||
this.options.onMaskSettings?.(this.maskSettings);
|
||||
this.enum(this.body, "area", "Sampling area", true);
|
||||
const resolution = el("div", "dd-param-resolution"); resolution.append(el("span", "dd-param-label", T("Sampling resolution")));
|
||||
this.sourceSize = el("button", "", T("Use source size")); this.sourceSize.type = "button";
|
||||
this.sourceSize.title = T("Fill width and height from the current source image; aligned to 8 px and clamped to 64-8192 px");
|
||||
this.sourceSize.onclick = () => {
|
||||
const image = this.options.getImage?.(); if (!image) return;
|
||||
const aligned = value => Math.max(64, Math.min(8192, Math.round(value / 8) * 8));
|
||||
@@ -123,23 +130,23 @@ export class InpaintParameterPanel {
|
||||
this.options.onDirty?.(); this.refresh();
|
||||
};
|
||||
resolution.append(this.sourceSize); this.body.append(resolution);
|
||||
this.number(this.body, "width", "宽度", { min: 64, max: 8192, step: 8, range: true });
|
||||
this.number(this.body, "height", "高度", { min: 64, max: 8192, step: 8, range: true });
|
||||
this.number(this.body, "denoise", "重绘幅度", { min: 0, max: 1, step: .01, range: true });
|
||||
const sampling = this.grid(this.body); this.enum(sampling, "sampler_name", "采样器"); this.enum(sampling, "scheduler", "调度器");
|
||||
this.number(this.body, "width", "Width", { min: 64, max: 8192, step: 8, range: true });
|
||||
this.number(this.body, "height", "Height", { min: 64, max: 8192, step: 8, range: true });
|
||||
this.number(this.body, "denoise", "Denoise", { min: 0, max: 1, step: .01, range: true });
|
||||
const sampling = this.grid(this.body); this.enum(sampling, "sampler_name", "Sampler"); this.enum(sampling, "scheduler", "Scheduler");
|
||||
const scale = this.grid(this.body);
|
||||
this.number(scale, "steps", "采样步数", { min: 1, max: 10000, range: true, rangeMax: 150 });
|
||||
this.number(scale, "cfg", "提示词引导 CFG", { min: 0, max: 100, step: .1, range: true, rangeMax: 30 });
|
||||
const seed = this.grid(this.body); this.number(seed, "seed", "随机种子", { min: 0, max: Number.MAX_SAFE_INTEGER }); this.enum(seed, "control_after_generate", "生成后种子");
|
||||
const advanced = el("details", "dd-param-advanced"), summary = el("summary", "", "蒙版、批量与高级设置"); advanced.append(summary);
|
||||
this.number(scale, "steps", "Steps", { min: 1, max: 10000, range: true, rangeMax: 150 });
|
||||
this.number(scale, "cfg", "CFG scale", { min: 0, max: 100, step: .1, range: true, rangeMax: 30 });
|
||||
const seed = this.grid(this.body); this.number(seed, "seed", "Seed", { min: 0, max: Number.MAX_SAFE_INTEGER }); this.enum(seed, "control_after_generate", "After generate");
|
||||
const advanced = el("details", "dd-param-advanced"), summary = el("summary", "", T("Mask, batch and advanced settings")); advanced.append(summary);
|
||||
const content = el("div", "dd-param-advanced-body"); advanced.append(content);
|
||||
this.number(content, "padding", "蒙版外扩边距", { min: 0, max: 2048 });
|
||||
this.number(content, "padding", "Context padding", { min: 0, max: 2048 });
|
||||
const masks = this.grid(content);
|
||||
this.number(masks, "mask_blur", "蒙版模糊", { min: 0, max: 128, step: .5 }); this.number(masks, "mask_grow", "蒙版扩张 / 收缩", { min: -128, max: 128 });
|
||||
const batch = this.grid(content); this.number(batch, "batch_size", "每张生成数量", { min: 1, max: 16 }); this.enum(batch, "resize_mode", "缩放方式");
|
||||
this.toggle(content, "inpaint_model", "使用专用 Inpaint 模型"); this.toggle(content, "soft_edge", "额外羽化边缘");
|
||||
this.number(content, "soft_strength", "额外羽化强度", { min: 0, max: 1, step: .05, range: true });
|
||||
this.number(content, "refiner_switch", "Refiner 切换比例", { min: 0, max: 1, step: .01, range: true }); this.body.append(advanced);
|
||||
this.number(masks, "mask_blur", "Mask blur", { min: 0, max: 128, step: .5 }); this.number(masks, "mask_grow", "Mask grow / shrink", { min: -128, max: 128 });
|
||||
const batch = this.grid(content); this.number(batch, "batch_size", "Batch size", { min: 1, max: 16 }); this.enum(batch, "resize_mode", "Resize mode");
|
||||
this.toggle(content, "inpaint_model", "Use dedicated inpaint model"); this.toggle(content, "soft_edge", "Extra edge feathering");
|
||||
this.number(content, "soft_strength", "Feather strength", { min: 0, max: 1, step: .05, range: true });
|
||||
this.number(content, "refiner_switch", "Refiner switch ratio", { min: 0, max: 1, step: .01, range: true }); this.body.append(advanced);
|
||||
}
|
||||
|
||||
destroy() { clearInterval(this.timer); this.observer.disconnect(); this.options.onTargetChange?.(this.target, null); this.target = null; this.root.remove(); }
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
// Remove obsolete feedback edges before LiteGraph assigns saved socket indices.
|
||||
export function removeLegacyFeedback(graph, seen = new Set()) {
|
||||
if (!graph || seen.has(graph)) return;
|
||||
seen.add(graph);
|
||||
const nodes = new Map((graph.nodes || []).map(node => [String(node.id), node]));
|
||||
const removed = new Set(), indices = new Map();
|
||||
for (const node of nodes.values()) {
|
||||
if (node.type !== "AdachiInlineMask") continue;
|
||||
const slots = (node.inputs || []).flatMap((input, index) => input.name === "result" ? [index] : []);
|
||||
indices.set(String(node.id), slots);
|
||||
for (const slot of slots) if (node.inputs[slot].link != null) removed.add(String(node.inputs[slot].link));
|
||||
}
|
||||
const entries = Array.isArray(graph.links) ? graph.links.map((link, index) => [index, link]) : Object.entries(graph.links || {});
|
||||
for (const [, link] of entries) {
|
||||
const id = Array.isArray(link) ? link[0] : link.id;
|
||||
const target = String(Array.isArray(link) ? link[3] : link.target_id);
|
||||
const slot = Array.isArray(link) ? link[4] : link.target_slot;
|
||||
if (!indices.has(target)) continue;
|
||||
const input = nodes.get(target).inputs?.[slot], slots = indices.get(target);
|
||||
// Also repair orphaned feedback edges from a previously migrated save.
|
||||
if (slots.includes(slot) || String(input?.link) !== String(id)) removed.add(String(id));
|
||||
else if (Array.isArray(link)) link[4] -= slots.filter(index => index < slot).length;
|
||||
else link.target_slot -= slots.filter(index => index < slot).length;
|
||||
}
|
||||
if (Array.isArray(graph.links)) graph.links = graph.links.filter(link => !removed.has(String(Array.isArray(link) ? link[0] : link.id)));
|
||||
else for (const [key, link] of entries) if (removed.has(String(Array.isArray(link) ? link[0] : link.id))) delete graph.links[key];
|
||||
for (const node of nodes.values()) {
|
||||
if (node.type === "AdachiInlineMask") node.inputs = (node.inputs || []).filter(input => input.name !== "result");
|
||||
for (const output of node.outputs || []) if (Array.isArray(output.links)) output.links = output.links.filter(id => !removed.has(String(id)));
|
||||
}
|
||||
for (const subgraph of graph.definitions?.subgraphs || []) removeLegacyFeedback(subgraph, seen);
|
||||
}
|
||||
@@ -35,6 +35,23 @@ export function connectedSamplers(source) {
|
||||
.sort((a, b) => Number(b.type === "AdachiWebUIInpaint") - Number(a.type === "AdachiWebUIInpaint"));
|
||||
}
|
||||
|
||||
// Use the same rounding, range and linked-input rules as Use source size.
|
||||
export function syncCropDimensions(source, width, height) {
|
||||
const aligned = value => Math.max(64, Math.min(8192, Math.round(value / 8) * 8));
|
||||
for (const target of connectedSamplers(source)) {
|
||||
target.adachiParameters?.refresh();
|
||||
for (const [name, value] of [["width", width], ["height", height]]) {
|
||||
if (target.inputs?.some(input => input.name === name && input.link != null)) continue;
|
||||
const widget = target.widgets?.find(widget => widget.name === name);
|
||||
if (widget && widget.value !== aligned(value)) {
|
||||
widget.value = aligned(value);
|
||||
widget.callback?.(widget.value);
|
||||
}
|
||||
}
|
||||
target.adachiParameters?.refresh();
|
||||
}
|
||||
}
|
||||
|
||||
export function relocateWidgets(owner, previous, next) {
|
||||
if (previous) {
|
||||
for (const widget of previous.widgets || []) {
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import { api } from "../../scripts/api.js";
|
||||
import { T } from "./i18n.js";
|
||||
|
||||
export function installResultAdoption(node, crop) {
|
||||
// Saved workflows may still contain the old feedback socket and wire.
|
||||
const removeLegacyInput = () => {
|
||||
const index = node.inputs?.findIndex(input => input.name === "result");
|
||||
if (index >= 0) node.removeInput(index);
|
||||
};
|
||||
removeLegacyInput();
|
||||
const configured = node.onConfigure;
|
||||
node.onConfigure = function () {
|
||||
const result = configured?.apply(this, arguments);
|
||||
removeLegacyInput();
|
||||
return result;
|
||||
};
|
||||
node.adachiAdoptCrop = async (file, origin) => {
|
||||
const editor = crop.editor, region = crop.region;
|
||||
if (!editor.ready || !region.locked) throw Error(T("Select a crop region before adopting a result"));
|
||||
if (crop.busy || editor.stroke) throw Error(T("Finish editing before adopting a result"));
|
||||
if (origin && (origin.mode !== "crop" || String(origin.source) !== String(node.id) || origin.job !== region.job)) {
|
||||
throw Error(T("This result belongs to another crop; generate a result for the current region"));
|
||||
}
|
||||
if (file.size > 64 * 1024 * 1024) throw Error(T("File is too large (max 64 MB)"));
|
||||
crop.busy = true; crop.sync();
|
||||
const objectUrl = URL.createObjectURL(file);
|
||||
try {
|
||||
const image = new Image(); image.src = objectUrl; await image.decode();
|
||||
if (image.width !== region.width || image.height !== region.height) {
|
||||
throw Error(T("Result dimensions must match the selected crop"));
|
||||
}
|
||||
const body = new FormData();
|
||||
body.append("image", file, `adopted-${crypto.randomUUID()}.png`);
|
||||
body.append("type", "input"); body.append("subfolder", "adachi-inpaint-layers");
|
||||
const response = await api.fetchApi("/upload/image", {method:"POST", body});
|
||||
if (!response.ok) throw Error(`${T("Upload failed")} (${response.status})`);
|
||||
const uploaded = await response.json();
|
||||
if (typeof uploaded.name !== "string" || !uploaded.name) throw Error(T("Upload failed"));
|
||||
if (editor.destroyed || crop.mode !== "crop" || crop.region.job !== region.job) {
|
||||
throw Error(T("The crop changed while adopting the result"));
|
||||
}
|
||||
const descriptor = {filename:uploaded.name, subfolder:uploaded.subfolder || "", type:"input"};
|
||||
await crop.accept({job:region.job, image:descriptor}, {allowBusy:true});
|
||||
const name = descriptor.subfolder ? `${descriptor.subfolder}/${descriptor.filename}` : descriptor.filename;
|
||||
if (crop.widgets.layer_image.value !== name) throw Error(T("The crop changed while adopting the result"));
|
||||
editor.status("");
|
||||
} finally {
|
||||
URL.revokeObjectURL(objectUrl); crop.busy = false; crop.sync();
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
/** Fill the node in graph coordinates, independently of cached DOM measurements. */
|
||||
export function bindWidgetToNodeWidth(node, widget, element) {
|
||||
// Classic ComfyUI uses widget.width before node.width for its DOM host.
|
||||
// A cached screen-space width is scaled a second time when zoomed out.
|
||||
// These single-column widgets always occupy the node's available width;
|
||||
// the frontend still applies its own widget margins and vertical layout.
|
||||
Object.defineProperty(widget, "width", {
|
||||
configurable: true,
|
||||
enumerable: true,
|
||||
get: () => Math.max(1, Number(node.size[0]) || 1),
|
||||
set: () => {},
|
||||
});
|
||||
element.style.width = "100%";
|
||||
element.style.maxWidth = "100%";
|
||||
element.style.minWidth = "0";
|
||||
}
|
||||
Reference in New Issue
Block a user