Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6df8cbef30 | ||
|
|
a2d8687993 | ||
|
|
6931d4811f | ||
|
|
8b3e7adcf4 | ||
|
|
cc2a66c74a | ||
|
|
c3f7c85b9e | ||
|
|
01862135da | ||
|
|
46cbe4266b | ||
|
|
ecf7472ff5 | ||
|
|
6b3cbb3268 | ||
|
|
9771f7e3fb | ||
|
|
90e4c9e24d | ||
|
|
c96badf1b9 | ||
|
|
b8286a5e51 | ||
|
|
d030a3b717 | ||
|
|
4bad6fae7e | ||
|
|
9a91d30530 | ||
|
|
c93d4b013c | ||
|
|
a3b0e7eaff | ||
|
|
cfb85445fa | ||
|
|
9e875c7a99 | ||
|
|
39b688403d | ||
|
|
2359960a54 | ||
|
|
fffcb49c4d | ||
|
|
a89b04f81b | ||
|
|
f137bfc751 | ||
|
|
6cd2c40fb8 | ||
|
|
0fb68ddd16 | ||
|
|
e583c6b529 | ||
|
|
58b9305a02 | ||
|
|
654488efd3 | ||
|
|
3e15a45cb8 | ||
|
|
82ea8ce773 | ||
|
|
8cdf32e3b1 | ||
|
|
1b5eb256f9 | ||
|
|
545332f43e | ||
|
|
5ce3248216 | ||
|
|
c70894a020 | ||
|
|
a756747d08 | ||
|
|
c93e9eada9 | ||
|
|
1fb017f772 | ||
|
|
c4cec35a19 | ||
|
|
9ee1a0dd52 | ||
|
|
15587a5d56 | ||
|
|
75c2ccc562 | ||
|
|
bcd68b11cd | ||
|
|
83cea8e955 | ||
|
|
8417d42ff6 | ||
|
|
5188d04b02 | ||
|
|
f62ff73d2c | ||
|
|
d348e71664 | ||
|
|
98c6f11904 | ||
|
|
2d3a4ffe32 | ||
|
|
8bd45cb519 | ||
|
|
afb9c567eb | ||
|
|
f2ad940d32 | ||
|
|
99b44c1bc2 | ||
|
|
f721466c14 | ||
|
|
2b3a3bfe45 | ||
|
|
f1cdcfeff5 | ||
|
|
9f4e02c7f5 | ||
|
|
05415abf49 | ||
|
|
946400d441 | ||
|
|
57c56de26b | ||
|
|
8e4c230300 | ||
|
|
d365f7752c | ||
|
|
e8e5e5a09e | ||
|
|
3640df2bf4 | ||
|
|
ba7e993888 | ||
|
|
9a22a329f3 | ||
|
|
32f653e18d | ||
|
|
03185836b9 | ||
|
|
7812a98ddc | ||
|
|
609375766b | ||
|
|
7cc6e8c20a | ||
|
|
5acc0d6e8c | ||
|
|
ce6d34b24e | ||
|
|
98b53ddd71 | ||
|
|
d7347e790c | ||
|
|
3c101e1b8a | ||
|
|
fdd64969ae | ||
|
|
7135b9e721 | ||
|
|
738dd63182 | ||
|
|
f231989e69 | ||
|
|
c42a963d68 | ||
|
|
c701bb5002 | ||
|
|
0196bca21e | ||
|
|
d92fcf436c | ||
|
|
89dc3a4e94 | ||
|
|
2e8333a4cc | ||
|
|
cc35c8e4e6 | ||
|
|
f7789930c1 | ||
|
|
b775a1d93d | ||
|
|
430f7cf276 | ||
|
|
df8f2b57d3 | ||
|
|
42f3559e8c | ||
|
|
ba301ce39a | ||
|
|
1c86920d3b | ||
|
|
39ade25cc2 | ||
|
|
3ff5ff7902 | ||
|
|
f764beef53 | ||
|
|
1fb0d3dcc7 |
@@ -3,6 +3,7 @@ __pycache__/
|
||||
*.pyc
|
||||
*.pyo
|
||||
*.pyd
|
||||
.venv/
|
||||
.Python
|
||||
build/
|
||||
develop-eggs/
|
||||
|
||||
@@ -1,146 +1,137 @@
|
||||
# ComfyUI Prompt Manager
|
||||
## A comprehensive prompt and workflow toolkit for [ComfyUI](https://github.com/comfyanonymous/ComfyUI) — Save, Generate, Extract, Build, and Reuse workflows with full LoRA support.
|
||||
## A comprehensive prompt and recipe toolkit for [ComfyUI](https://github.com/comfyanonymous/ComfyUI)
|
||||
|
||||
A complete prompt and workflow management suite featuring:
|
||||
ComfyUI Prompt Manager is an all-in-one prompt and recipe toolkit for ComfyUI, built for creating recipes from scratch or by extracting core workflow elements from Images and Videos with embedded workflows. It includes local LLM-powered prompt generation (llama.cpp or Ollama) with automatic download of Qwen3.5 models, LoRA stack tooling, and end-to-end Recipe nodes to build, edit, render, save, and reuse repeatable generation pipelines. It can extract core metadata from media generated in ComfyUI, A1111, and Forge, supporting Wan Workflows with dual model/stack support.
|
||||
|
||||
## v2.0 Introduces: Workflow Extractor + Workflow Builder + Workflow Renderer + Workflow Manager
|
||||
> **Naming Update (v2.1):**
|
||||
> We have shifted from using the term "Workflow" to "Recipe" for this toolset.
|
||||
> This is an unfortunate but needed naming change to better represent the purpose of this tool.
|
||||
|
||||
The goal of this v2.0 workflow layer is to strip workflows down to their core elements so they are easier to understand, edit, and reuse.
|
||||
> **New in v2.5.0:**
|
||||
> Recipe Builder can now setup Multi Model all in one Node. Gone is the need to stack multiple Builder nodes when setting multi model workflows.
|
||||
> You can build and route `model_a` through `model_d` in one node, keep per-slot prompts/LoRAs/sampler data, and extract Builder-authored recipes from media with v2 metadata preserved as the authoritative source.
|
||||
> Added a New Multi Lora Stack node, that is based on Lora-Manager and works with it. Simply select the column you want to add to and then added loras with be added to it.
|
||||
> This new Multi Model may break combatibility wirh previous workflows, but this is now MUCH closer to the initial visioin! One node to build the entire Recipe.
|
||||
|
||||
- Extract metadata from source images and videos (ComfyUI or A1111/Forge)
|
||||
- Reduce complex graphs into a clean, editable workflow core
|
||||
- Rebuild and run from that simplified core with Workflow Builder to Workflow Renderer
|
||||
- Save and reuse clean workflow entries through Workflow Manager
|
||||
- Combine with Prompt tools (Prompt Manager, and Prompt Generator) for easier prompt creation and generation.
|
||||
## What This Provides
|
||||
|
||||
Think of it as workflow de-spaghetti: keep the important parts, remove unnecessary complexity.
|
||||
|
||||
This release marks version 2.0.0. More polish and quality-of-life improvements are planned.
|
||||
|
||||
**Prompt Manager** — Save and organize prompts with categories, complete with matching LoRA stacks, trigger words, and thumbnail previews. Supports dual LoRA stacks for complex workflows like Wan videos. Toggle LoRAs on/off or adjust strengths directly from saved presets. Supports workflow_data input from Workflow Builder or Prompt Extractor to pull workflow prompts and LoRA stacks directly into PMA. Will also remap LoRAs if paths differ.
|
||||
|
||||
**Prompt Generator** — Generate and enhance prompts using local LLMs via [llama.cpp](https://github.com/ggerganov/llama.cpp) or [Ollama](https://ollama.com). Supports text enhancement, image analysis with vision models (Qwen3.5), and thinking mode for deeper reasoning. Analyze up to 5 images at once.
|
||||
|
||||
**Prompt Extractor** — Extract prompts, LoRA configurations, and checkpoint/model paths from existing images, videos, or JSON workflow files. Extracts the first frame from any video. Automatically parses embedded metadata and outputs active LoRAs as LoRA stacks, plus resolved model paths (High/Low for dual-model workflows like Wan). Supports ComfyUI, A1111/Forge, and WebP metadata formats. When used with Prompt Manager Advanced, LoRAs are automatically found if available, regardless of path. For those that are not, right-click offers the option to look for them on Civitai. Browse files from both your input and output folders.
|
||||
|
||||
**Prompt Model Loader** — Load checkpoints, diffusion, or GGUF models from a string path output by Prompt Extractor. Auto-detects whether the model is a checkpoint (outputs MODEL + CLIP + VAE) or a diffusion/UNET/GGUF model (outputs MODEL only). Displays model type badge and name directly on the node. Works around ComfyUI's combo type limitation, allowing extracted model paths to connect directly to a loader. Supports [ComfyUI-GGUF](https://github.com/city96/ComfyUI-GGUF) models when the extension is installed.
|
||||
|
||||
**Workflow Suite of Tools** — Build and re-render extracted workflows with dedicated nodes:
|
||||
|
||||
- **Workflow Extractor**: Reads workflow metadata and normalizes it into reusable workflow_data.
|
||||
- **Workflow Builder**: Lets you edit and assemble a clean core workflow from extracted metadata.
|
||||
- **Workflow Renderer**: Runs built-in workflow templates for near one-click generation after Builder setup.
|
||||
- **Workflow Bridge**: Passes workflow context and routing data between nodes cleanly.
|
||||
- **Workflow Model Loader**: Resolves and loads the right model/checkpoint from workflow data.
|
||||
- **Workflow Manager**: Saves and reuses cleaned workflow entries for fast reruns.
|
||||
|
||||
Builder + Renderer + Workflow Manager provides a streamlined generation path: configure Builder once, connect Renderer and Save Image/Save Video, and save both the output and the resulting workflow.
|
||||
|
||||
Built-in workflow support includes Flux 1, Flux 2, SDXL, Wan, Qwen, Z-Image, Wan Image, and Wan Video (I2V and T2V).
|
||||
|
||||
**Workflow Builder + Workflow Manager Reuse Loop** — Build workflow_data from extracted image/video metadata or from Workflow Builder directly, then save and reuse those workflow entries through Workflow Manager.
|
||||
___
|
||||
- **Prompt tools**: Prompt Manager, Prompt Extractor
|
||||
- **Local LLM support**: Prompt Generator using llama.cpp or Ollama. Supports text enhancement and image analysis with vision models (Qwen3.5)
|
||||
- **Recipe tools**: Recipe Extractor, Recipe Builder, Recipe Builder (WAN), Recipe Hub, Recipe Relay, Recipe Renderer, Recipe Model Loader, Recipe Manager
|
||||
- **LoRA workflow support**: Display and modify added Loras. When reusing Saved presets, values can still be changed.
|
||||
- **Model support**: Recipe Renderer supports: Flux 1/2, Ernie, SDXL, Wan, Qwen, Z-Image, Wan Image, Wan Video (I2V/T2V)
|
||||
- **Lora Preview**: When [Lora-Manager](https://github.com/willmiao/ComfyUI-Lora-Manager) is installed, LoRAs can be previewed on hover.
|
||||
- **Prompt Browser**: Includes a Browser to easily find and select your prompts or Recipes.
|
||||
- **Advance Image Loader**: Extractors can serve as advanced Image loaders, loading from Input or Ouput.
|
||||
---
|
||||
|
||||
<div align="center">
|
||||
<figcaption>Prompt Manager Advanced, with Lora and trigger word support</figcaption>
|
||||
<img src="docs/prompt_manager_advanced.png" alt="Prompt Manager">
|
||||
<figcaption>Prompt Creation With Lora and Trigger Words</figcaption>
|
||||
<img src="docs/images/prompt_generator_text.png" alt="Prompt Manager">
|
||||
</div>
|
||||
|
||||
<div align="center">
|
||||
<figcaption>Prompt Extractor connected to Manager Advanced, so workflow can be saved with Loras</figcaption>
|
||||
<img src="docs/prompt_extractor.png" alt="Prompt Manager">
|
||||
<figcaption>Generating Prompts based on Images</figcaption>
|
||||
<img src="docs/images/prompt_generator_image.png" alt="Prompt Generator">
|
||||
</div>
|
||||
|
||||
<div align="center">
|
||||
<figcaption>Advanced Prompt Generator</figcaption>
|
||||
<img src="docs/prompt_generator_advanced.png" alt="Prompt Manager">
|
||||
<figcaption>Advanced Prompt Generation using Multiple Images</figcaption>
|
||||
<img src="docs/images/prompt_generator_advanced.png" alt="Prompt Generator">
|
||||
</div>
|
||||
|
||||
<div align="center">
|
||||
<figcaption>Simple Prompt Generator</figcaption>
|
||||
<img src="docs/prompt_manager.png" alt="Prompt Manager">
|
||||
<figcaption>Recipe extraction and modifcation (Adding a Style Lora)</figcaption>
|
||||
<img src="docs/images/workflow_builder.png" alt="Recipe Builder">
|
||||
</div>
|
||||
|
||||
<div align="center">
|
||||
<figcaption>Workflow Builder</figcaption>
|
||||
<img src="docs/workflow_builder.jpg" alt="Prompt Manager">
|
||||
<figcaption>Easily find saved Prompts & Recipe using the Built-in File Browser</figcaption>
|
||||
<img src="docs/images/prompt_selector.png" alt="Recipe Builder">
|
||||
</div>
|
||||
|
||||
### Key features:
|
||||
### Prompt Manager:
|
||||
- **Category Organization**: Create and manage multiple categories to organize your prompts
|
||||
- **Save & Load Prompts**: Quickly save and recall your favorite prompts with custom names
|
||||
- **NSFW Tagging**: Mark categories and individual prompts as NSFW with visual badge indicator on the node title bar
|
||||
- **NSFW Filtering**: Hide/show NSFW content via a global preference — NSFW categories and prompts are filtered from dropdowns when hidden
|
||||
- **LLM Input Toggle**: Connect text outputs from other nodes and toggle between using them or your internal prompts
|
||||
- **LLM Input Toggle**: When in use, display of categories and prompt is disabled, allowing user to switch category and save.
|
||||
- **Persistent Storage**: All prompts saved in your ComfyUI user folder
|
||||
<div align="center">
|
||||
<figcaption>Use Extractor Nodes as an Image Loader, allowing browsing from Input and Output folder.</figcaption>
|
||||
<img src="docs/images/adv_file_loading.png" alt="Recipe Builder">
|
||||
</div>
|
||||
|
||||
### Prompt Manager Advanced:
|
||||
- **All Prompt Manager Features**: Everything from the basic Prompt Manager, plus LoRA and trigger-word integration
|
||||
- **NSFW Tagging**: Mark categories and individual prompts as NSFW — red "NSFW" badge appears on the prompt selector and in the thumbnail browser
|
||||
- **NSFW Filtering**: Session-persistent NSFW toggle button in the thumbnail browser to show/hide NSFW content; navigation arrows skip NSFW entries when hidden
|
||||
- **List View Mode**: Switch between thumbnail grid and compact list view in the prompt browser, with session-persistent preference
|
||||
- **Prompt Thumbnails**: Save thumbnail images with your prompts for visual identification in the dropdown
|
||||
- **Dual LoRA Stack Support**: Two separate LoRA stack inputs/outputs for complex workflows (e.g., Wan video with different LoRAs for image and video)
|
||||
- **Visual LoRA Tags**: See connected LoRAs as clickable tags with strength values
|
||||
- **Toggle LoRAs On/Off**: Click any LoRA tag to enable/disable it without disconnecting
|
||||
- **Editable Strengths**: Click the strength value on any tag to adjust it inline
|
||||
- **Trigger Words Support**: Save and display trigger words alongside prompts and LoRAs; can use [ComfyUI-Lora-Manager](https://github.com/infantesimone/ComfyUI-Lora-Manager) trigger words.
|
||||
- **Right-Click to Delete**: Right-click any LoRA or trigger word tag to remove it
|
||||
- **Save LoRAs with Prompts**: When you save a prompt, the current LoRA configuration is saved with it
|
||||
- **Override Mode**: Toggle "Override Lora" to ignore connected inputs and use only saved preset LoRAs
|
||||
- **Merge Mode**: When override is off, connected LoRAs are merged with saved presets
|
||||
- **Workflow Data Input**: Optional workflow_data input from Workflow Builder or Prompt Extractor, with use_workflow_data toggle support to use extracted prompt and LoRA stacks directly in PMA
|
||||
- **LoRA Manager Integration**: If [ComfyUI-Lora-Manager](https://github.com/infantesimone/ComfyUI-Lora-Manager) is installed, hovering over LoRA tags shows preview images
|
||||
- **Missing LoRA Detection**: LoRAs that aren't found on your system are highlighted in red
|
||||
- **Thumbnail Generation**: Right-click any prompt to generate a thumbnail using a selectable checkpoint model. Model choice persists in ComfyUI preferences.
|
||||
|
||||
### Prompt Extractor:
|
||||
- **Extract from Images/Videos**: Load images or videos and extract embedded prompts, LoRAs, and workflow metadata
|
||||
- **Model/Checkpoint Extraction**: Extracts checkpoint and UNET model paths from workflows, with High/Low (A/B) assignment for dual-model setups like Wan video
|
||||
- **A1111/Forge Support**: Parses A1111 parameters format to extract prompts, LoRAs, and model names from Forge/A1111 generated images
|
||||
- **WebP Metadata Support**: Reads EXIF metadata from WebP images (RIFF format parser)
|
||||
- **JSON Workflow Support**: Browse and load JSON workflow files directly to extract prompts and LoRA configurations
|
||||
- **Input/Output Folder Switching**: Toggle between browsing your input or output folder directly from the node
|
||||
- **Dual LoRA Stack Output**: Outputs two separate LoRA stacks for workflows using dual stacking (e.g., Wan video)
|
||||
- **Active LoRA Filtering**: Only extracts LoRAs that are marked as active in the source workflow
|
||||
- **Wide Node Compatibility**: Supports 11+ model loader types including CheckpointLoader, UNETLoader, UnetLoaderGGUF, DiffusionModelLoader, WanVideoModelLoader, CyberdyneModelHub, and more
|
||||
- **Preview in Manager**: View extracted data and repathed LoRAs using Manager Advanced.
|
||||
|
||||
### Prompt Model Loader:
|
||||
- **String-to-Model Loading**: Takes a model path string (from Prompt Extractor) and loads the model directly
|
||||
- **Auto-Detection**: Automatically detects whether the path is a checkpoint (returns MODEL + CLIP + VAE) or diffusion/UNET/GGUF model (returns MODEL only)
|
||||
- **GGUF Support**: Loads GGUF models when [ComfyUI-GGUF](https://github.com/city96/ComfyUI-GGUF) is installed, with automatic runtime detection
|
||||
- **Visual Model Info**: Displays model type badge (Checkpoint/Diffusion/GGUF) and model name directly on the node
|
||||
- **State Persistence**: Model info display and output slot visibility persist across tab switches and workflow reloads
|
||||
- **Graceful Error Handling**: Displays a red "NOT FOUND" badge instead of crashing when a model path cannot be resolved
|
||||
- **Model Path Resolution**: Works with both full paths and relative paths, searching checkpoints, diffusion_models, and unet folders
|
||||
- **Weight Dtype Support**: Optional weight dtype selection for memory optimization
|
||||
- **Family Filtering Tip**: Family filtering works best when model families are separated into clear folder structures (for example folders that include family cues like i2v/t2v/high/low).
|
||||
## v2.0 Introduces The Recipe Toolset
|
||||
|
||||
### Prompt Generator
|
||||
- **Three Generation Modes**: Enhance text prompts, analyze images, or analyze images with custom instructions
|
||||
- **Dual Backend Support**: Use llama.cpp (local server, default) or Ollama as the LLM backend
|
||||
- **Prompt Enhancement**: Transform basic prompts into detailed descriptions using local LLMs
|
||||
- **Vision Analysis**: Analyze images with vision-capable models to generate detailed descriptions
|
||||
- **Custom Image Analysis**: Provide your own instructions for image analysis
|
||||
- **JSON Output**: Optional structured JSON output with scene breakdown
|
||||
- **Thinking Support**: Support Thinking models to perform deeper generative reasoning.
|
||||
- **Automatic Server Management**: Starts/stops llama.cpp server as needed, with automatic shut off at exit.
|
||||
- **Smart Model Selection**: Auto-selects appropriate model based on mode, using mmproj-based vision detection.
|
||||
Version 2.x introduces a Recipe toolset that can be used on its own, or in combination with the Prompt toolset.
|
||||
|
||||
### Prompt Generator Options
|
||||
- **Model Selection**: Choose from local models or download Qwen3.5 models from HuggingFace
|
||||
- **Auto-Download**: Automatically downloads both model and required mmproj files for vision models
|
||||
- **LLM Parameters**: Fine-tune temperature, top_k, top_p, min_p, repeat_penalty and context size.
|
||||
- **Custom Instructions**: Override default system prompt for different enhancement styles.
|
||||
- **Extra Image Inputs**: Combine up to 5 images to generate your prompt.
|
||||
- **Console Debugging**: Enable outputting the entire process to the console for debugging purposes.
|
||||
- Use the Recipe toolset when you want repeatable generation pipelines from extracted or hand-edited recipe data.
|
||||
- Recipe Data includes prompts (pos & neg), LoRA stack, mode used, KSampler settings, resolution, seed, and more.
|
||||
- This data can be created using Recipe Builder or extracted from existing media with Recipe Extractor.
|
||||
- Recipe Renderer provides an easy way to render this recipe.
|
||||
- Recipe data can also be used traditionally with the Recipe Relay node, which can access all of it.
|
||||
- Use the Prompt toolset when you want fast prompt library management and local LLM-assisted prompt creation.
|
||||
- Prompt Generator allows creation of new prompts using the LLM model of your choice.
|
||||
- Prompt Manager can save these to be reusable later.
|
||||
- Prompt Extractor is similar to Recipe Extractor, but can individually output prompts or LoRAs.
|
||||
- Use both together when you want to create Recipes, but use different prompts.
|
||||
|
||||
### Preference Options
|
||||
- Set choices for preferred models for both base mode and vision mode.
|
||||
- Set a new default model location. Previous folders (gguf and llm) are still scanned, but new downloads are saved to the new default.
|
||||
- Set a custom location for Llama.cpp. If Llama.cpp was not added to your system PATH, this option lets you specify its location.
|
||||
- **LLM Backend**: Choose between llama.cpp (default) or Ollama as the generation backend.
|
||||
- **Ollama Settings**: Configure Ollama URL and keep-alive duration for model memory management.
|
||||
In short: Prompt tools help you author and manage Prompts + LoRA intent, while Recipe tools help you build, execute and reuse full generation configurations.
|
||||
|
||||
## Toolset Overview
|
||||
|
||||
### Prompt Toolset
|
||||
|
||||
- Prompt Manager: dual LoRA stacks, trigger words, thumbnail workflows, and advanced save flows.
|
||||
- Prompt Extractor: reads metadata from images/videos/JSON and outputs prompt + LoRA + recipe context.
|
||||
- Prompt Generator + Options: local LLM prompt creation and enhancement using llama.cpp or Ollama.
|
||||
- Prompt Manager (Basic): category-based prompt save/load. A no-frills basic version (The OG).
|
||||
|
||||
### Recipe Toolset
|
||||
|
||||
- Recipe Extractor: normalizes extracted metadata into reusable recipe_data.
|
||||
- Recipe Builder: edit and validate recipe_data in a cleaner authoring surface.
|
||||
- Recipe Renderer: execute recipe_data through built-in generation templates.
|
||||
- Recipe Hub: merge/append model blocks into one `recipe_data` and expose each model block as its own output.
|
||||
- Recipe Relay: edit one model block (`model_data`) with seed and LoRA stack overrides.
|
||||
- Recipe Model Loader: resolve and load models from recipe_data.
|
||||
- Recipe Manager: save and reuse recipe entries.
|
||||
|
||||
## Common Pipelines
|
||||
|
||||
### Prompt-first Pipeline
|
||||
|
||||
1. Write or generate prompts and connect LoRA stacks into Prompt Manager.
|
||||
2. Generate with your normal ComfyUI graph.
|
||||
3. Save reusable prompt entries when satisfied.
|
||||
|
||||
### Recipe-first Pipeline
|
||||
|
||||
1. Create preset in Recipe Builder
|
||||
- By extracting recipe_data from media or JSON, using Recipe Extractor
|
||||
- Or by directly modifying Recipe Builder to the values you want.
|
||||
2. Render in Recipe Renderer.
|
||||
3. Save reusable recipe entries with Recipe Manager.
|
||||
- To include Thumbnail, add after the Renderer node.
|
||||
|
||||
### Hybrid Pipeline
|
||||
|
||||
1. Extract or build recipe_data.
|
||||
2. Add Prompt Generator or Save prompts into Builder.
|
||||
3. Add LoRAs, either using LoRA stackers or saved LoRA stacks in Prompt Manager.
|
||||
4. Render through Recipe Renderer.
|
||||
5. Save final reusable entries in Recipe Manager.
|
||||
|
||||
## Preferences And Settings
|
||||
|
||||
- Addon settings are available in ComfyUI Preferences (Settings) under Prompt Manager.
|
||||
- This is where you set model/backend defaults, NSFW visibility defaults, view preferences, and related addon behavior.
|
||||
- Prompt Generator backend choices (llama.cpp or Ollama) and related options are configured there.
|
||||
|
||||
## Workflow Examples
|
||||
|
||||
Workflow examples are provided to help understand the basics.
|
||||
|
||||
## Documentation
|
||||
|
||||
- Detailed node and feature reference: [docs/feature-reference.md](docs/feature-reference.md)
|
||||
- Full changelog history: [docs/changelog.md](docs/changelog.md)
|
||||
|
||||
## Installation
|
||||
|
||||
@@ -148,7 +139,6 @@ ___
|
||||
```
|
||||
cd ComfyUI/custom_nodes/
|
||||
```
|
||||
|
||||
2. Clone this repository:
|
||||
```bash
|
||||
git clone https://github.com/FranckyB/ComfyUI-Prompt-Manager.git
|
||||
@@ -158,96 +148,18 @@ ___
|
||||
cd ComfyUI-Prompt-Manager
|
||||
pip install -r requirements.txt
|
||||
```
|
||||
4. Install [llama.cpp](https://github.com/ggml-org/llama.cpp/tree/master)
|
||||
Windows:
|
||||
```bash
|
||||
winget install llama.cpp
|
||||
```
|
||||
Linux:
|
||||
```bash
|
||||
brew install llama.cpp
|
||||
```
|
||||
5. If you have them, place your .gguf models in the models/gguf folder, or set your preferred folder path in preferences.
|
||||
|
||||
6. Restart ComfyUI
|
||||
|
||||
## Usage
|
||||
|
||||
### Prompt Manager
|
||||
|
||||
1. **Add the Node**: Add Node → Prompt Manager
|
||||
2. **Select a Category**: Use the dropdown to choose from your categories
|
||||
3. **Choose a Prompt**: Select a saved prompt from the name dropdown
|
||||
4. **Connect prompt output**: Connect Prompt Manager output to your clip text encode node.
|
||||
|
||||
### Prompt Manager Advanced
|
||||
|
||||
1. **Add the Node**: Add Node → Prompt Manager → Prompt Manager Advanced
|
||||
2. **Connect LoRA Stackers**: Connect LoRA stacker nodes (e.g., from LoRA Manager) to `lora_stack_a` and/or `lora_stack_b` inputs
|
||||
3. **View LoRA Tags**: Connected LoRAs appear as clickable tags showing name and strength
|
||||
4. **Toggle LoRAs**: Click a tag to enable/disable that LoRA (disabled tags turn gray)
|
||||
5. **Adjust Strength**: Click the strength number on a tag to edit it inline
|
||||
6. **Save with LoRAs**: Click "Save Prompt" to save both the prompt text and current LoRA configuration
|
||||
7. **Workflow Input (Optional)**: Connect workflow_data from Workflow Builder or Prompt Extractor and enable use_workflow_data to use extracted prompt and LoRA stacks in PMA
|
||||
8. **Override Mode**: Enable "Override Lora" checkbox to ignore connected inputs and use only the saved preset LoRAs
|
||||
9. **Connect Outputs**: Use `lora_stack_a` and `lora_stack_b` outputs with the Apply LoRA Stack node
|
||||
|
||||
### Prompt Extractor
|
||||
|
||||
1. **Add the Node**: Add Node → Prompt Manager → Prompt Extractor
|
||||
2. **Choose Source Folder**: Use the `source_folder` dropdown to browse files from either your **input** or **output** folder
|
||||
3. **Load Media**: Select an image or video from the file browser, or drag-and-drop files onto the node
|
||||
4. **JSON Workflows**: Supports extracting from JSON workflow files directly
|
||||
5. **Extract Data**: The node automatically extracts prompts, LoRAs, and trigger words from embedded metadata
|
||||
6. **View Results**: Extracted positive/negative prompts display in the text outputs, LoRA stacks output as LORA_STACK
|
||||
7. **Use with Manager**: Connect the LoRA stack outputs to Prompt Manager Advanced to view and save the extracted configuration
|
||||
|
||||
|
||||
### Prompt Generator
|
||||
|
||||
**Basic Usage** (assuming a model is present in models\gguf):
|
||||
1. **Add the Node**: Add Node → Prompt Generator
|
||||
2. **Select Mode**: Choose from:
|
||||
- "Enhance User Prompt" - Improve text prompts with LLM
|
||||
- "Analyze Image" - Generate detailed image descriptions
|
||||
- "Analyze Image with Prompt" - Analyze images with custom instructions
|
||||
3. **Connect inputs**: Connect image for vision modes, or just use text for enhancement mode
|
||||
4. **Output as Json**: Use Format_as_Json to experiment with Json prompts.
|
||||
5. **Push the LLM**: Use enable_thinking to enable the model to perform deeper generative reasoning before producing the final prompt.
|
||||
6. **Save memory**: Toggle "stop_server_after" ON to free VRAM after generation
|
||||
7. **Run Workflow**: Generated prompt displays and can be saved to Prompt Manager
|
||||
|
||||
**Advanced Usage**:
|
||||
1. **Add the Options Node**: Add Node → Prompt Generator Options
|
||||
2. **Connect Options**: Connect the options node to the Prompt Generator Options input
|
||||
3. **Analyze multiple images**: Connect up to 4 additional images, for a total of 5.
|
||||
4. **Select from available models**: Select from models found in your models\gguf folder. Qwen models will be available to download.
|
||||
5. **Adjust settings**: Adjust LLM parameters (temperature, top_k, etc.)
|
||||
6. **Customize LLM**: Customize the default LLM instructions to modify the responses llama returns.
|
||||
7. **Enable Debugging**: Enable complete printout of process to console using show_everything_in_console
|
||||
|
||||
**Qwen models found in options**
|
||||
- Qwen3.5-9B-UD-Q4_K_XL.gguf: Unsloth Dynamic 4-bit, good balance (~6GB VRAM)
|
||||
- Qwen3.5-9B-Q8_0.gguf: Standard 8-bit, high quality (~9.5GB VRAM)
|
||||
- Qwen3.5-9B-UD-Q8_K_XL.gguf: Unsloth Dynamic 8-bit, best quality (~13GB VRAM)
|
||||
|
||||
All Qwen3.5 models are unified vision+text — every model supports both text enhancement and image analysis via its mmproj file. Thinking mode is controlled at runtime via a toggle, no separate model variant needed.
|
||||
|
||||
**Model Management**:
|
||||
- Place gguf files in models/gguf folder
|
||||
- Downloaded models are also placed in this folder.
|
||||
|
||||
**Preferences**:
|
||||
Preference settings can be found in ComfyUI Settings → Prompt Manager
|
||||
- **Preferred Base Model**: Name of model used for "Enhance User Prompt" mode
|
||||
- **Preferred Vision Model**: Name of model used for "Analyze Image" modes
|
||||
- **Set Default Port** You can set the port used by Llama.cpp
|
||||
- **Close Llama on Exit** By default Llama.cpp will be closed on exit.
|
||||
- **Hide NSFW by Default**: When enabled, NSFW categories and prompts are hidden from all dropdowns, navigation, and the thumbnail browser
|
||||
- **Default View Mode**: Choose between thumbnail grid or list view for the Advanced prompt browser
|
||||
- **LLM Backend**: Choose between llama.cpp (default) or Ollama
|
||||
- **Ollama URL**: Set the Ollama server address (default: http://127.0.0.1:11434)
|
||||
- **Keep Alive Duration**: How long Ollama keeps the model loaded after a request (e.g. 5m, 30m, 0 for immediate unload)
|
||||
4. Install [llama.cpp](https://github.com/ggml-org/llama.cpp/tree/master):
|
||||
- Windows:
|
||||
```bash
|
||||
winget install llama.cpp
|
||||
```
|
||||
- Linux:
|
||||
```bash
|
||||
brew install llama.cpp
|
||||
```
|
||||
5. Place custom `.gguf` models in models/gguf.
|
||||
- Or use preferences to set a custom path.
|
||||
6. Restart ComfyUI.
|
||||
|
||||
## Requirements
|
||||
|
||||
@@ -260,401 +172,3 @@ Preference settings can be found in ComfyUI Settings → Prompt Manager
|
||||
- Pillow
|
||||
- colorama
|
||||
- llama-server (from llama.cpp)
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
**Problem**: Prompts don't appear in the dropdown
|
||||
- **Solution**: Make sure the category has saved prompts. Try creating a new prompt first.
|
||||
|
||||
**Problem**: Changes aren't saved
|
||||
- **Solution**: Click the "Save Prompt" button after making changes. Direct edits in the text field are temporary.
|
||||
|
||||
**Problem**: Can't see LLM output in the node
|
||||
- **Solution**: Make sure the LLM output is connected to the "llm_input" and run the workflow.
|
||||
|
||||
**Problem**: "llama-server command not found"
|
||||
- **Solution**: Install llama.cpp and make sure `llama-server` is available in command line. See [llama.cpp releases](https://github.com/ggerganov/llama.cpp/releases)
|
||||
|
||||
**Problem**: "No models found"
|
||||
- **Solution**: Either place a .gguf file in the `models/` folder, or connect the Prompt Generator Options node and select a model size (1.7B, 4B, or 8B) to download from HuggingFace
|
||||
|
||||
**Problem**: Server won't start
|
||||
- **Solution**: Check that port 8080 is not in use. Close any existing llama-server processes.
|
||||
|
||||
**Problem**: Model download fails
|
||||
- **Solution**: Check your internet connection and HuggingFace availability. Large models may take time to download.
|
||||
|
||||
**Problem**: Generation is slow
|
||||
- **Solution**: Use a smaller quantized model (Q4 instead of Q8), or toggle 'stop_server_after' to quit llama.cpp after generating a prompt.
|
||||
|
||||
**Problem**: Default model used is not what I want
|
||||
- **Solution**: You can set your preferred model in the ComfyUI settings. Simply add its full name, with .gguf extension, for both the VL and base models. Enabling Thinking in the Generator might change what is used for VL models.
|
||||
|
||||
|
||||
## Changelog
|
||||
|
||||
### version 2.0.0
|
||||
- **Prompt Manager becomes Prompt + Workflow Manager**
|
||||
- Workflow Manager now allows saving Workflow and is integrated with Prompt Manager save/reuse behavior
|
||||
- Extractor, Builder, and Manager workflow loop now focuses on simplified, reusable workflow cores
|
||||
- Workflow save/reuse behavior aligned with workflow_data-first persistence for consistent prompt and LoRA retention
|
||||
- Documentation updated to reflect full prompt and workflow scope
|
||||
- More polish improvements coming soon
|
||||
|
||||
### version 1.25.0
|
||||
- **Workflow Tools Release Milestone**
|
||||
- Workflow Builder / Workflow Renderer / Workflow Bridge / Workflow Model Loader now form a complete editable workflow pipeline
|
||||
- Improved extractor-to-builder update flow for image/video metadata refresh
|
||||
- Improved Builder dropdown stability and selection persistence on first open
|
||||
- Improved tab-switch persistence for Builder UI state, including LoRA stacks and LoRA state
|
||||
- Improved compatibility when extracting from workflows generated by Builder persistence data
|
||||
|
||||
- **Wan i2v Workflow Quality and UX Improvements**
|
||||
- Better high/low model handling and dual-pass sampler defaults in workflow path
|
||||
- Improved model-family filtering and unsupported-family handling in Builder/Renderer
|
||||
- Improved workflow update diagnostics to simplify troubleshooting of resolution and model propagation
|
||||
|
||||
- **Prompt Manager Advanced Save + Thumbnail Improvements**
|
||||
- Save flow now reuses the full Advanced browser UI (same search, category tools, NSFW/filter handling, and existing prompt selection behavior)
|
||||
- Save action terminology updated to **Save Workflow** for workflow-oriented entries
|
||||
- Save now enforces category selection before submission to avoid uncategorized/invalid saves
|
||||
- Workflow Saver save action now uses failure-only notifications (no success toast spam)
|
||||
- Thumbnail generation now tries Workflow Renderer first when workflow_data is present, with automatic fallback to the basic checkpoint/LoRA thumbnail path
|
||||
- Renderer thumbnail path now forces thumbnail-safe resolution and single-frame batch settings before queueing (consistent size, batch=1)
|
||||
|
||||
### version 1.22.6
|
||||
- **Prompt Extractor now extract Prompt Extractor**
|
||||
- Prompt Extractor now embeds extracted data in the workflow, so it can extract itself.
|
||||
|
||||
### version 1.22.5
|
||||
- **Thumbnail Generation in Prompt Manager Advanced**
|
||||
- Right-click any prompt to generate a thumbnail using a basic KSampler workflow
|
||||
- Checkpoint model selector with filterable list of all available checkpoints
|
||||
- Includes saved LoRAs (both stacks, active only) for more accurate thumbnails
|
||||
- LoRA paths resolved via existing fuzzy matching — renamed LoRAs are found automatically
|
||||
- Random seed on each generation — re-generate to get a different result
|
||||
- Selected checkpoint persists in ComfyUI preferences across sessions
|
||||
- Change model anytime via right-click menu or ComfyUI Settings → Prompt Manager
|
||||
- Spinner overlay during generation with 120s timeout
|
||||
|
||||
- **Improved Model High/Low Detection**
|
||||
- Better detection of embedded high/low indicators in model names (e.g., `tastysinHighV81`, `tastysinLowV81`)
|
||||
|
||||
### version 1.22.1
|
||||
- **Prompt Model Loader Improvements**
|
||||
- Added GGUF model support via runtime detection of [ComfyUI-GGUF](https://github.com/city96/ComfyUI-GGUF) extension
|
||||
- Visual model type badge (Checkpoint/Diffusion/GGUF/NOT FOUND) and model name displayed on the node
|
||||
- CLIP and VAE output slots automatically hidden for non-checkpoint models
|
||||
- State persistence: model info and output slot visibility survive tab switches and workflow reloads
|
||||
- Graceful error handling: shows red "NOT FOUND" badge instead of crashing on missing models
|
||||
- Searches `unet_gguf` folder paths registered by ComfyUI-GGUF
|
||||
|
||||
### version 1.22.0
|
||||
- **New Node: Prompt Model Loader**
|
||||
- Loads checkpoints or diffusion/UNET models from a string path (output by Prompt Extractor)
|
||||
- Auto-detects model type: checkpoints return MODEL + CLIP + VAE, diffusion models return MODEL only
|
||||
- Searches ComfyUI checkpoints, diffusion_models, and unet folders automatically
|
||||
- Optional weight dtype selection for memory optimization
|
||||
|
||||
- **Model/Checkpoint Extraction in Prompt Extractor**
|
||||
- Extracts checkpoint and UNET model paths from workflow metadata
|
||||
- High/Low (A/B) model assignment for dual-model workflows (e.g., Wan video with different models per noise level)
|
||||
- Resolves extracted model names to local file paths using ComfyUI's folder system
|
||||
- Supports 11+ model loader types: CheckpointLoaderSimple, UNETLoader, UnetLoaderGGUF, DiffusionModelLoader, WanVideoModelLoader, CyberdyneModelHub (dual high/low), and more
|
||||
- New `model_a` and `model_b` STRING outputs on the Prompt Extractor node
|
||||
|
||||
- **A1111/Forge Image Support**
|
||||
- Parses `Model:` field from A1111/Forge parameters format (both JS and Python paths)
|
||||
- Extracts model names from images generated by Automatic1111, Forge, and compatible UIs
|
||||
|
||||
- **WebP Metadata Support**
|
||||
- Added RIFF/EXIF parser for reading ComfyUI metadata from WebP images
|
||||
- Fixed EXIF tag reading to use correct tags (0x010e ImageDescription, 0x010f Make) for ComfyUI metadata
|
||||
|
||||
- **Video Metadata Improvements**
|
||||
- Added `comment` tag parsing in ffprobe fallback for videos that store metadata as JSON wrapper
|
||||
|
||||
### version 1.21.2
|
||||
- **Improved Thumbnail Extraction**
|
||||
- prompt extractor: enhance video thumbnail extraction and error handling for unsupported formats
|
||||
|
||||
- **Improve llama-server**
|
||||
- Increase server startup timeout from 30s to 120s for large models
|
||||
- Detect early server crashes and show stderr output to user
|
||||
- Fix _get_model_keywords docstring to reflect version preservation (qwen3.5)
|
||||
|
||||
### version 1.21.1
|
||||
- **Bug Fix** - Fixed issues caused by restructure
|
||||
|
||||
### version 1.21.0
|
||||
- **Removed miscellaneous tools** — Switch Any, Save Video H26x, Apply LoRA Stack, Better Image Loader, and Animated Latent Preview have been moved to a dedicated repository: [ComfyUI-FBnodes](https://github.com/FranckyB/ComfyUI-FBnodes)
|
||||
- **Project restructure** — Organized node files into `nodes/` and utility modules into `py/` for cleaner codebase
|
||||
|
||||
### version 1.20.0
|
||||
- **New Node: Better Image Loader**
|
||||
- Streamlined image and video loader with the same file browser as Prompt Extractor
|
||||
- Browse input or output folders, preview images and videos, scrub through video frames
|
||||
- Drag-and-drop support, single IMAGE output — no metadata extraction or LoRA processing
|
||||
- **Prompt Extractor: Input/Output Folder Switching**
|
||||
- New `source_folder` toggle to browse files from either your input or output directory
|
||||
- File browser, thumbnails, and previews all respect the selected source folder
|
||||
- **Switch Any Bug Fix**
|
||||
- Fixed SwitchAnyBool not triggering upstream node execution
|
||||
- Fixed SwitchAny input names reverting to defaults after execution
|
||||
|
||||
### version 1.19.0
|
||||
- **True Switch Any Node**
|
||||
- Added a 10 input 'True' Switch any node, that takes any inputs, doesn't lock in the type.
|
||||
- Allows rename of inputs using a simple string with all names split using , or ;
|
||||
- True lazy support, any Non selected input is disconnected internally.
|
||||
- **Metadata Json**
|
||||
- Added metadata output, so workflow found can be visualized
|
||||
- **Bug Fix**
|
||||
- Fixed bug where page reload and switching workflow would needlessly refetch the prompt.
|
||||
|
||||
### version 1.18.0
|
||||
- **Thumbnail Hover Preview**
|
||||
- Intelligent delay system: 1000ms initial, then 50ms for fast browsing (resets after 2s inactivity)
|
||||
- Preference toggle in ComfyUI Settings and browser UI (🔍 Preview / 🔍 Off)
|
||||
- Auto-scroll to selected prompt when browser opens
|
||||
- **Improved Thumbnail Quality**
|
||||
- Increased resolution to 200x200 (up from 128x128) with aspect ratio preservation
|
||||
- Optimized JSON storage format
|
||||
|
||||
### version 1.17.6
|
||||
- **Swap LoRA Stack Outputs**
|
||||
- Added `swap_lora_outputs` toggle to swap LoRA Stack A and B outputs
|
||||
- Useful for quickly testing different LoRA configurations in dual-stack workflows
|
||||
- **LoRA Input Handling Fixes**
|
||||
- Fixed issue when no LoRA input was connected: toggling LoRAs off would cause the list to refresh and revert the toggle state
|
||||
- Fixed inability to set LoRA strength to 0 (zero values were incorrectly replaced with 1.0)
|
||||
- Fixed saving prompts to use current displayed state instead of re-querying connected inputs
|
||||
- Added automatic cleanup of input-derived LoRAs when they're no longer present in the connected input
|
||||
- Improving `use_lora_input` toggle behavior to properly remove input-derived LoRAs when switching OFF while preserving preset LoRA toggle states
|
||||
|
||||
### version 1.17.5
|
||||
- **Browser Context Menu Enhancements**
|
||||
- Added "Delete Prompt", "Rename and Move Prompt" option to prompt right-click menu in the thumbnail browser
|
||||
- Added "Delete Category", "Rename Category" options to category right-click menu
|
||||
- Added "+" button at the end of the category list to create new categories directly from the browser
|
||||
- All browser operations preserve unsaved prompt state (text, loras, trigger words are not reset)
|
||||
- **Streamlined More Dropdown**
|
||||
- Removed Rename Category, New Category, Delete Category, and Delete Prompt from the "More" dropdown (now accessible via browser context menus)
|
||||
|
||||
### version 1.17.0
|
||||
- **NSFW Tagging & Filtering**
|
||||
- Mark entire categories or individual prompts as NSFW
|
||||
- Visual red "NSFW" badge on the Prompt Manager node title bar and on the Advanced prompt selector
|
||||
- NSFW badge appears on all prompts within an NSFW-tagged category in the thumbnail browser
|
||||
- Category buttons show red border for NSFW categories in the thumbnail browser
|
||||
- Global preference to hide/show NSFW content — filters dropdowns, navigation arrows, and browser
|
||||
- Session-persistent NSFW toggle button in the Advanced thumbnail browser
|
||||
- Toggle NSFW on categories and prompts via context menu or the save/new category dialogs
|
||||
- **List View Mode**
|
||||
- New compact list view alternative to the thumbnail grid in the Advanced prompt browser
|
||||
- Toggle between grid and list view with a button in the browser controls bar
|
||||
- View mode preference is session-persistent
|
||||
- Default view mode configurable in ComfyUI settings
|
||||
- **UI Improvements**
|
||||
- Search input moved into the controls bar with a clear (×) button
|
||||
- Separator line between category buttons and prompt content
|
||||
|
||||
### version 1.16.0
|
||||
- **Ollama Support**
|
||||
- Added Ollama as an alternative LLM backend alongside llama.cpp
|
||||
- Auto-discovers available Ollama models when no model is explicitly configured
|
||||
- Keep-alive duration setting controls how long Ollama keeps the model loaded in memory
|
||||
- "Stop server after" toggle unloads the model from Ollama memory to free VRAM
|
||||
- **Upgraded to Qwen3.5 Models**
|
||||
- Replaced Qwen3/Qwen3VL models with unified Qwen3.5-9B (vision+text in one model)
|
||||
- Three download options: UD-Q4_K_XL (~6GB), Q8_0 (~9.5GB), UD-Q8_K_XL (~13GB)
|
||||
- Thinking mode is now a runtime toggle — no separate model variant needed
|
||||
- **mmproj-Based Vision Detection**
|
||||
- Vision model detection no longer relies on "VL" in the filename
|
||||
- Models are identified as vision-capable based on the presence of an mmproj file
|
||||
- Heuristic matching supports user-provided models outside the predefined registry
|
||||
- Backward compatible with existing Qwen3VL models and their mmproj files
|
||||
- **Bug Fixes**
|
||||
- Fixed seed control_after_generate not working (increment/decrement/randomize)
|
||||
- Improved Prompt Extractor detection logic
|
||||
|
||||
### version 1.15.9
|
||||
- **Bug Fixes**
|
||||
- Improved Prompt Extractor, enhanced detection logic
|
||||
|
||||
### version 1.15.7
|
||||
- **Added Rename Category Option**
|
||||
- **Bug Fixes**
|
||||
|
||||
### version 1.15.6
|
||||
- **Video Metadata Reader - VHS Compatible**
|
||||
- Added capability to read metadata from VideoHelperSuite generated videos.
|
||||
|
||||
### version 1.15.5
|
||||
- **Added get video components+ node**
|
||||
- Since our save video node can saves latents, this also returns the matching latent (if found) and filepath.
|
||||
- **Video Preview in Prompt Extractor**
|
||||
- Added the option to preview in fullscreen with dark overlay for both images and video on the Prompt Extractor node.
|
||||
|
||||
### version 1.15.0
|
||||
- **Added Animated Latent Preview**
|
||||
- Added Similar option to VideoHelperSuite, to display animated Latent preview. With the addition that it works in TAESD mode.
|
||||
- Check for VideoHelperSuite node, so not to conflict with it. (Will do nothing if installed)
|
||||
|
||||
### version 1.14.5
|
||||
- **Added Save Latent support to Save Video node**
|
||||
- allows to save the full data of a generation to then experiment without the need to regenerate.
|
||||
- added some very quick workflow examples.
|
||||
-A simplified version of my Wan workflow
|
||||
-A basic Z-Image base workflow with Prompt Generator.
|
||||
- Small bug fixes
|
||||
|
||||
### version 1.14.0
|
||||
- **Addition of a "Save Video H264/H265" node, that replicates ComfyUI's Video Node**
|
||||
- Adds choice between H264/H265
|
||||
- Choice of Chroma Subsampling between yuv420, yuv422, yuv444
|
||||
- Can set Constant Rate Factor (compression level)
|
||||
- Generates a quick proxy video if chosen format could not play in browser (H265 + yuv422 or H265 + yuv444)
|
||||
- Unlike VideoHelperSuite, clip with Audio also include Metadata. Which can then be used with Prompt Extractor.
|
||||
|
||||
### version 1.13.5
|
||||
- Added browse window with thumbnails in Extractor, with cache system for speedup.
|
||||
- Bug fix for issue caused by new additions.
|
||||
|
||||
### version 1.12.7
|
||||
- Quality of life improvements and added option to change the strength of any LoRA in Manager, so we can tweak extracted workflows live.
|
||||
|
||||
### version 1.12.6
|
||||
- Tweak to caching behavior for prompt extractor and prompt manager advanced
|
||||
|
||||
### version 1.12.5
|
||||
- Some dependencies to FFMpeg were still present, remove them and added a frame_position value, so we can specify what frame to get from video.
|
||||
|
||||
### version 1.12.0
|
||||
- Prompt Extractor: Added Lora inputs, so it can be used as a passthrough, with a None Choice at top, to easily deactivate it.
|
||||
- Prompt Extractor: Improved logic for determining positive prompts in workflow.
|
||||
- Prompt Extractor: Improved logic for finding High and Low Lora Stacks
|
||||
- Prompt Manager Advanced: Added Fuzzy Logic to find Loras that might have been renamed
|
||||
- Prompt Manager Advanced: Fixed issue of Lora buttons getting cleared when changing tab.
|
||||
|
||||
### Version 1.11.5
|
||||
- Slight adjustement to extractor node, gets metadata in a method more consistent with ComfyUI, removing need for ffmpeg for videos.
|
||||
|
||||
### Version 1.11.2
|
||||
- Slight adjustement to extractor node to behave exactly like the Load image node, while also supporting Videos. (With extract first frame support)
|
||||
|
||||
### Version 1.11.0
|
||||
- **New Node: Prompt Extractor** - Extract prompts and LoRA configurations from images, videos, and JSON workflows
|
||||
- Loads embedded metadata from PNG, JPEG, WebP images and MP4 videos
|
||||
- Browse and load JSON workflow files directly
|
||||
- Dual LoRA stack output for workflows using two stacks (e.g., Wan video)
|
||||
- Filters inactive LoRAs - only extracts LoRAs marked as active
|
||||
- Supports extraction from CLIP Text Encode, samplers, and LoRA stackers
|
||||
- Compatible with Power Lora Loader, WanMoeKSamplerAdvanced, and other common nodes
|
||||
- **Prompt Thumbnails** - Save thumbnail images with prompts in Prompt Manager Advanced
|
||||
- Visual identification of prompts in the dropdown selector
|
||||
- Thumbnails stored alongside prompt data for easy management
|
||||
- **Simplified "New Prompt" button**
|
||||
- Now clears fields immediately without asking for a name
|
||||
- Enter the name when saving instead of when creating
|
||||
- Keeps you in the current category for faster workflow
|
||||
- **Bug fixes and improvements**
|
||||
- Fixed JSON workflow file path resolution
|
||||
- Improved LoRA extraction for complex workflows
|
||||
|
||||
### Version 1.10.0
|
||||
- **Unified UI for Prompt Manager and Prompt Manager Advanced**
|
||||
- Three-button layout: Save Prompt, New Prompt, and More (dropdown menu)
|
||||
- New Prompt button creates a temporary prompt that isn't saved until you click Save Prompt
|
||||
- Save Prompt opens a modal with category selection (create new or select existing)
|
||||
- More dropdown includes: Import JSON, Export JSON, Delete Prompt, Delete Category
|
||||
- **Import/Export JSON functionality**
|
||||
- Export all prompts to a JSON file
|
||||
- Import prompts with Merge (add to existing) or Replace (overwrite all) options
|
||||
- Proper cancel handling without false success messages
|
||||
- **Multi-tab synchronization**
|
||||
- Changing category or prompt reloads data from server
|
||||
- Prevents conflicts when editing prompts in multiple browser tabs
|
||||
- **Prompt Manager now preserves LoRA data**
|
||||
- LoRA stacks, trigger words, and active states are preserved when saving from basic Prompt Manager
|
||||
- Seamless compatibility between Prompt Manager and Prompt Manager Advanced
|
||||
- **Trigger Words support in Prompt Manager Advanced**
|
||||
- Save and restore trigger words alongside prompts and LoRAs
|
||||
- Trigger words display as editable text when loading saved prompts
|
||||
- **Improved unsaved changes detection**
|
||||
- Warning when switching away from newly created (unsaved) prompts
|
||||
- Cancel button properly reverts dropdown to previous selection
|
||||
|
||||
### Version 1.9.0
|
||||
- **New Node: Prompt Manager Advanced** - Extended prompt manager with LoRA stack support
|
||||
- Dual LoRA stack inputs/outputs for complex workflows (Wan video, etc.)
|
||||
- Visual LoRA tags showing name and editable strength values
|
||||
- Toggle LoRAs on/off by clicking tags
|
||||
- Save LoRA configurations alongside prompts
|
||||
- Override mode to ignore connected inputs and use saved presets
|
||||
- Merge mode combines connected LoRAs with saved presets
|
||||
- Missing LoRA detection with visual warnings
|
||||
- Integration with LoRA Manager for hover previews
|
||||
- **New Node: Apply LoRA Stack** - Simple node to apply LORA_STACK to model/clip
|
||||
- Categories and prompts now display in alphabetical order
|
||||
- Fixed dropdown refresh after saving prompts
|
||||
|
||||
### Version 1.8.3
|
||||
- Added option to leave Llama server running when closing ComfyUI.
|
||||
|
||||
### Version 1.8.2
|
||||
- Added custom model path preference and enhance model management
|
||||
|
||||
### Version 1.8.1
|
||||
- Added option to set a custom Llama path in preferences, for those that have specific installs.
|
||||
|
||||
### Version 1.8.0
|
||||
- Added support for Qwen3VL Thinking model variants, with download options thru the Generator Options node.
|
||||
- Model manager now searches for relevant `mmproj` files using model-name components for more reliable vision-model linking.
|
||||
- Detailed console output options (debug logging)
|
||||
- `enable_thinking` toggle to enable/disable the model's reasoning/thinking mode.
|
||||
- Options node now accepts multiple images for analysis.
|
||||
- Better Llama shutdown behavior to force-close the server when Comfy exits.
|
||||
- Uses model-reported sampling params by default when available; the Options node can override them per-parameter.
|
||||
- Moved preference API endpoints and cache handling into `model_manager.py` for cleaner management and persistence.
|
||||
|
||||
### Version 1.7.0
|
||||
- Added three-mode prompt generator: "Enhance User Prompt", "Analyze Image", "Analyze Image with Prompt"
|
||||
- Enhanced vision model workflow with dedicated image analysis modes
|
||||
- Added custom image analysis with user-provided instructions (e.g., "describe the lighting", "identify objects")
|
||||
- Added model preferences system integrated with ComfyUI Settings
|
||||
- Added automatic model preference management (separate settings for base and vision models)
|
||||
- Improved model selection with preference fallback to smallest model
|
||||
- Filtered mmproj files from model selection dropdowns
|
||||
- Model preferences stored in ComfyUI settings for persistence across updates
|
||||
|
||||
### Version 1.6.0
|
||||
- Added Qwen3VL vision model support for image analysis
|
||||
- Added JSON output format option with structured scene breakdown
|
||||
- Added adjustable context size parameter (512-32768 tokens)
|
||||
- Added automatic mmproj file download for vision models
|
||||
- Added image resizing to ~2MP to optimize token usage
|
||||
- Added token usage logging for monitoring context consumption
|
||||
- Improved model selection logic with automatic VL/non-VL detection
|
||||
- Fixed multiple directory support for model search (gguf + LLM folders)
|
||||
|
||||
### Version 1.5.1
|
||||
- LLM output remains available when use_llm is off, so it can be edited.
|
||||
- Improved caching detection: any change to options will be detected and force a new output.
|
||||
- Improved some UI quirks
|
||||
|
||||
### Version 1.5.0
|
||||
- Added Prompt Generator node with automatic llama.cpp server management
|
||||
- Added Prompt Generator Options node for model selection and parameters
|
||||
- Automatic model detection and auto-download from HuggingFace for Qwen3 models.
|
||||
- VRAM management with optional server shutdown
|
||||
|
||||
### Version 1.1.0
|
||||
- Added LLM input toggle for switching between internal and external text
|
||||
- Made text fields scrollable even when disabled
|
||||
- Fixed reload bugs with toggle state
|
||||
|
||||
### Version 1.0.0
|
||||
- Initial release
|
||||
- Category and prompt management
|
||||
- LLM output integration
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
"""
|
||||
"""
|
||||
ComfyUI Prompt Manager - A comprehensive prompt and workflow management system for ComfyUI.
|
||||
Features: prompt & workflow management, LoRA stacks, workflow extraction, workflow generation.
|
||||
"""
|
||||
__version__ = "2.0.0"
|
||||
__version__ = "2.5.1"
|
||||
__author__ = "François Beaudry"
|
||||
__license__ = "MIT"
|
||||
|
||||
@@ -12,45 +12,54 @@ from .nodes.prompt_manager_basic import PromptManager
|
||||
from .nodes.prompt_generator import PromptGenerator
|
||||
from .nodes.prompt_generator_options import PromptGenOptions
|
||||
from .nodes.prompt_extractor import PromptExtractor
|
||||
from .nodes.prompt_extractor import WorkflowExtractor
|
||||
from .nodes.workflow_builder import WorkflowBuilder
|
||||
from .nodes.workflow_renderer import WorkflowRenderer
|
||||
from .nodes.workflow_bridge import WorkflowBridge
|
||||
from .nodes.workflow_model_loader import WorkflowModelLoader
|
||||
from .nodes.workflow_manager import WorkflowManager
|
||||
from .nodes.prompt_extractor import WorkflowExtractor as RecipeExtractor
|
||||
from .nodes.recipe_builder import RecipeBuilder
|
||||
from .nodes.recipe_renderer import WorkflowRenderer as RecipeRenderer
|
||||
from .nodes.recipe_relay import WorkflowRelay as RecipeRelay
|
||||
from .nodes.recipe_model_loader import WorkflowModelLoader as RecipeModelLoader
|
||||
from .nodes.recipe_model_picker import RecipeModelPicker
|
||||
from .nodes.recipe_manager import WorkflowManager as RecipeManager
|
||||
from .nodes.multi_prompt import RecipeBuilderMultiPrompts
|
||||
from .nodes.multi_lora_stacker import MultiLoraStackerLM, MultiLoraCombine
|
||||
|
||||
NODE_CLASS_MAPPINGS = {
|
||||
"PromptApplyLora": ApplyLoraPlusPlus,
|
||||
"PromptManagerAdvanced": PromptManagerAdvanced,
|
||||
"PromptManager": PromptManager,
|
||||
"PromptGenerator": PromptGenerator,
|
||||
"PromptGenOptions": PromptGenOptions,
|
||||
"PromptExtractor": PromptExtractor,
|
||||
"WorkflowExtractor": WorkflowExtractor,
|
||||
"WorkflowBuilder": WorkflowBuilder,
|
||||
"WorkflowRenderer": WorkflowRenderer,
|
||||
"WorkflowBridge": WorkflowBridge,
|
||||
"WorkflowModelLoader": WorkflowModelLoader,
|
||||
"WorkflowManager": WorkflowManager,
|
||||
"PromptApplyLora": ApplyLoraPlusPlus,
|
||||
"PromptManagerAdvanced": PromptManagerAdvanced,
|
||||
"PromptManager": PromptManager,
|
||||
"PromptGenerator": PromptGenerator,
|
||||
"PromptGenOptions": PromptGenOptions,
|
||||
"PromptExtractor": PromptExtractor,
|
||||
"RecipeExtractor": RecipeExtractor,
|
||||
"RecipeBuilder": RecipeBuilder,
|
||||
"RecipeRenderer": RecipeRenderer,
|
||||
"RecipeRelay": RecipeRelay,
|
||||
"RecipeModelLoader": RecipeModelLoader,
|
||||
"RecipeModelPicker": RecipeModelPicker,
|
||||
"RecipeManager": RecipeManager,
|
||||
"RecipeBuilderMultiPrompts": RecipeBuilderMultiPrompts,
|
||||
"MultiLoraStackerLM": MultiLoraStackerLM,
|
||||
"MultiLoraCombine": MultiLoraCombine,
|
||||
}
|
||||
|
||||
NODE_DISPLAY_NAME_MAPPINGS = {
|
||||
"PromptApplyLora": "Apply LoRA++",
|
||||
"PromptManagerAdvanced": "Prompt Manager",
|
||||
"PromptManager": "Prompt Manager (Basic)",
|
||||
"PromptGenerator": "Prompt Generator",
|
||||
"PromptGenOptions": "Prompt Generator Options",
|
||||
"PromptExtractor": "Prompt Extractor",
|
||||
"WorkflowExtractor": "Workflow Extractor",
|
||||
"WorkflowBuilder": "Workflow Builder",
|
||||
"WorkflowRenderer": "Workflow Renderer",
|
||||
"WorkflowBridge": "Workflow Bridge",
|
||||
"WorkflowModelLoader": "Workflow Model Loader",
|
||||
"WorkflowManager": "Workflow Manager",
|
||||
"PromptApplyLora": "Apply LoRA++",
|
||||
"PromptManagerAdvanced": "Prompt Manager",
|
||||
"PromptManager": "Prompt Manager (Basic)",
|
||||
"PromptGenerator": "Prompt Generator",
|
||||
"PromptGenOptions": "Prompt Generator Options",
|
||||
"PromptExtractor": "Prompt Extractor",
|
||||
"RecipeExtractor": "Recipe Extractor",
|
||||
"RecipeBuilder": "Recipe Builder",
|
||||
"RecipeRenderer": "Recipe Renderer",
|
||||
"RecipeRelay": "Recipe Relay",
|
||||
"RecipeModelLoader": "Recipe Model Loader",
|
||||
"RecipeModelPicker": "Recipe Model Picker",
|
||||
"RecipeManager": "Recipe Manager",
|
||||
"RecipeBuilderMultiPrompts": "Multi Prompts",
|
||||
"MultiLoraStackerLM": "Multi LoRA Stack",
|
||||
"MultiLoraCombine": "Multi LoRA Combine",
|
||||
}
|
||||
|
||||
WEB_DIRECTORY = "./js"
|
||||
|
||||
__all__ = ['NODE_CLASS_MAPPINGS', 'NODE_DISPLAY_NAME_MAPPINGS', 'WEB_DIRECTORY']
|
||||
|
||||
print("[PromptManager] Nodes registered: Apply LoRA++, Prompt Manager (Basic), Prompt Manager, Prompt Generator, Prompt Generator Options, Prompt Extractor, Workflow Extractor, Workflow Builder, Workflow Renderer, Workflow Bridge, Workflow Model Loader, Workflow Manager")
|
||||
print("[PromptManager] Nodes registered: Apply LoRA++, Prompt Manager, Prompt Generator, Prompt Extractor, Recipe Extractor, Recipe Builder, Recipe Renderer, Recipe Relay, Recipe Manager")
|
||||
|
||||
@@ -1,38 +0,0 @@
|
||||
import sys, json, subprocess, io
|
||||
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace')
|
||||
|
||||
# Check videos with missing loader types
|
||||
test_files = {
|
||||
'DiffusionModelLoaderKJ': r'D:\ComfyUI-Dev\input\Workflow\Vids\2026_01_08_60FPS_00002.mp4',
|
||||
'WanVideoModelLoader': r'D:\ComfyUI-Dev\input\Workflow\Vids\vid_00061.mp4',
|
||||
'SeaArtUnetLoader': r'D:\ComfyUI-Dev\input\Workflow\Vids\25439d30-d0d7-4dd4-b64c-b46345c76351.mp4',
|
||||
'CyberdyneModelHub': r'D:\ComfyUI-Dev\input\Workflow\Vids\d39dbdc3-f08c-44e1-bd4c-410ecb08d3c9.mp4',
|
||||
'CheckpointInNum': r'D:\ComfyUI-Dev\input\Workflow\Vids\num__00168.mp4',
|
||||
}
|
||||
|
||||
for label, f in test_files.items():
|
||||
print(f"\n=== {label} ===")
|
||||
r = subprocess.run(['ffprobe','-v','quiet','-print_format','json','-show_format',f], capture_output=True, text=True, timeout=10)
|
||||
data = json.loads(r.stdout)
|
||||
tags = data['format']['tags']
|
||||
|
||||
# Try direct tags first, then comment
|
||||
prompt = tags.get('prompt')
|
||||
if not prompt:
|
||||
comment = tags.get('comment', '{}')
|
||||
comment_data = json.loads(comment)
|
||||
prompt = comment_data.get('prompt', '{}')
|
||||
|
||||
if isinstance(prompt, str):
|
||||
prompt = json.loads(prompt)
|
||||
|
||||
targets = ['Diffusion', 'Wan', 'SeaArt', 'Cyberdyne', 'Checkpoint', 'UNET', 'Unet', 'Model']
|
||||
for nid, ndata in prompt.items():
|
||||
ct = ndata.get('class_type', '')
|
||||
if 'Cyberdyne' in ct or ct == 'Wan_Cyberdyne_Genisys':
|
||||
inputs = ndata.get('inputs', {})
|
||||
inp_str = json.dumps(inputs)
|
||||
if len(inp_str) > 800:
|
||||
inp_str = inp_str[:800] + '...'
|
||||
print(f" Node {nid}: {ct}")
|
||||
print(f" inputs: {inp_str}")
|
||||
@@ -0,0 +1,92 @@
|
||||
# Changelog
|
||||
|
||||
## version 2.5.0
|
||||
- **Recipe Builder is now Multi-model Only**
|
||||
- Expanded Builder authoring around `recipe_data` with slot-aware model blocks (`model_a`/`model_b`/`model_c`/`model_d`).
|
||||
- Improved cross-slot behavior for prompts, LoRAs, sampler settings, and resolution handling in multi-model workflows.
|
||||
- **Authoritative Builder extraction flow**
|
||||
- Extraction now preserves Builder-authored v2 model data as the source of truth when embedded Builder v2 metadata is present.
|
||||
- Added compatibility safeguards so legacy/non-v2 workflows continue to use fallback extraction logic.
|
||||
- **Builder lock/reset and execution consistency**
|
||||
- Improved update and execute behavior so incoming recipe values, lock states, and current UI values resolve more predictably.
|
||||
- Strength/reset handling was tightened for better consistency across slot updates and reruns.
|
||||
- **New LoRA utility node: MultiLoraCombine**
|
||||
- Added `MultiLoraCombine` to merge optional multi-stack input with optional stack A/B/C/D inputs into a single `MULTI_LORA_STACK` output.
|
||||
- Helps consolidate mixed LoRA sources for multi-model Builder and downstream recipe flows.
|
||||
- **New feature: Multi LoRA Stacker with Lora-Manager compatibility**
|
||||
- Added a new Multi LoRA Stacker for slot-aware and multi-stack recipe flows.
|
||||
- Compatible with [Lora-Manager](https://github.com/willmiao/ComfyUI-Lora-Manager), including interoperability with managed LoRA selections and previews.
|
||||
|
||||
## version 2.2.0
|
||||
- **Recipe_data v2 expansion and slot-aware workflows**
|
||||
- Expanded v2 compatibility across Builder, Relay, Renderer, Manager, and extraction utilities.
|
||||
- Improved model slot behavior for `model_a`/`model_b`/`model_c`/`model_d`, including WAN pair handling.
|
||||
- **Recipe Builder Update flow and persistence improvements**
|
||||
- Update Recipe now respects Pull From selection consistently and supports expected clear behavior for empty/none selections.
|
||||
- Pull From / Send To state persistence improved across tab switches and workflow reloads.
|
||||
- Update Recipe visibility refined to avoid incomplete Builder-to-Builder pull paths.
|
||||
- **LoRA synchronization and execution-order fixes**
|
||||
- Fixed connected LoRA add/remove timing so `recipe_data` reflects changes on first execute.
|
||||
- Improved LoRA state authority between connected inputs and persisted UI overrides.
|
||||
- **Renderer validation hardening**
|
||||
- Renderer now fails fast with a clear error when the selected model slot is undefined.
|
||||
- Prevents silent renders from empty/non-existent selected model slots.
|
||||
- **Prompt Generator GPU utilization and VRAM prep**
|
||||
- Ensured llama.cpp server launch uses `-ngl 100` so generation is pushed to GPU as much as possible.
|
||||
- Added more aggressive cache/VRAM flushing before generation to reduce memory pressure and improve run reliability.
|
||||
|
||||
## version 2.1.1
|
||||
- Updated Documentation
|
||||
- Bug fixes
|
||||
|
||||
## version 2.1.0
|
||||
- **Naming Migration: Workflow -> Recipe**
|
||||
- Renamed node/toolset terminology to Recipe naming across the addon UI and docs.
|
||||
- Bug fixes.
|
||||
|
||||
## version 2.0.2
|
||||
- Added Ernie family support in Workflow Builder/Renderer.
|
||||
- Bug fixes.
|
||||
|
||||
## version 2.0.1
|
||||
- **Added Denoise options to Workflow Pipeline**
|
||||
- Workflow data now contains denoise value (Extractor returns 1 by default).
|
||||
- Allows mid-run model handoff using KSampler denoise.
|
||||
- Bug fixes.
|
||||
|
||||
## version 2.0.0
|
||||
- **Prompt Manager becomes Prompt + Workflow Manager**
|
||||
- Workflow Manager allows saving workflow and integrates with Prompt Manager save/reuse behavior.
|
||||
- Extractor/Builder/Manager workflow loop focused on simplified reusable workflow cores.
|
||||
- recipe_data-first persistence improvements.
|
||||
- Documentation updates.
|
||||
|
||||
## version 1.25.0
|
||||
- **Workflow Tools Release Milestone**
|
||||
- Workflow Builder / Workflow Renderer / Workflow Bridge / Workflow Model Loader form a complete editable workflow pipeline.
|
||||
- Improved extractor-to-builder update flow.
|
||||
- Improved Builder dropdown stability and persistence.
|
||||
- Improved tab-switch persistence for Builder UI state.
|
||||
- Improved compatibility with Builder persistence extraction.
|
||||
- **Wan i2v workflow quality and UX improvements**
|
||||
- **Prompt Manager Advanced save + thumbnail improvements**
|
||||
|
||||
## version 1.22.6
|
||||
- Prompt Extractor now embeds extracted data in workflow so it can extract itself.
|
||||
|
||||
## version 1.22.5
|
||||
- Thumbnail generation in Prompt Manager Advanced.
|
||||
- Improved model high/low detection.
|
||||
|
||||
## version 1.22.1
|
||||
- Prompt Model Loader improvements, including GGUF support and persistence improvements.
|
||||
|
||||
## version 1.22.0
|
||||
- New node: Prompt Model Loader.
|
||||
- Expanded model/checkpoint extraction in Prompt Extractor.
|
||||
- A1111/Forge image support improvements.
|
||||
- WebP metadata support improvements.
|
||||
- Video metadata parsing improvements.
|
||||
|
||||
## version 1.21.x to 1.0.0
|
||||
Older historical entries were previously listed in README and can still be recovered from repository history.
|
||||
@@ -0,0 +1,97 @@
|
||||
# Feature Reference
|
||||
|
||||
This page contains the detailed feature overview that was moved out of the main README for faster scanning.
|
||||
|
||||
## Prompt Toolset
|
||||
|
||||
### Prompt Manager
|
||||
- All Prompt Manager features, plus LoRA and trigger-word integration
|
||||
- Dual LoRA stack support for complex pipelines (for example Wan video)
|
||||
- LoRA tags with inline strength editing
|
||||
- Toggle active state per LoRA without rewiring
|
||||
- Save LoRAs with prompt entries
|
||||
- Override/merge behavior for connected vs saved LoRAs
|
||||
- Optional recipe_data input integration
|
||||
- Missing LoRA highlighting and LoRA Manager preview support
|
||||
- Thumbnail generation from saved prompt entries
|
||||
|
||||
### Prompt Manager (Basic)
|
||||
- Category-based prompt organization
|
||||
- Save/load prompts quickly
|
||||
- NSFW tagging and filtering
|
||||
- LLM input toggle
|
||||
- Persistent storage in your ComfyUI user folder
|
||||
|
||||
### Prompt Extractor
|
||||
- Extract prompt/model/LoRA metadata from image, video, and JSON workflow files
|
||||
- Supports ComfyUI, A1111/Forge, and WebP metadata formats
|
||||
- First-frame extraction from videos
|
||||
- Dual LoRA stack extraction for compatible workflows
|
||||
- Input/output folder browsing
|
||||
- Can also be used as an advanced media loader with metadata awareness
|
||||
|
||||
### Prompt Generator
|
||||
- Local LLM generation with llama.cpp or Ollama
|
||||
- Text enhancement and image analysis modes
|
||||
- Optional JSON output mode
|
||||
- Thinking mode support
|
||||
- Multi-image support (up to 5 total with options node)
|
||||
- Prompt Generator Options node for model and parameter control
|
||||
|
||||
## Recipe Toolset
|
||||
|
||||
The Recipe Toolset is designed to build, manage, and rerun reusable generation pipelines. You can author recipes from scratch in Builder, combine recipe logic with Prompt Manager/Prompt Manager Advanced to reuse saved prompts, or import existing metadata via Extractor when you want to bootstrap from prior outputs.
|
||||
|
||||
### Recipe Builder
|
||||
- Central editing surface to build or modify recipes
|
||||
- Primary authoring path for creating recipes from scratch
|
||||
- Provides a recipe-focused workspace to inspect, adjust, and refine recipe fields without manually wiring every parameter node-by-node
|
||||
- Can be used standalone or connected with other recipe/prompt nodes
|
||||
- Works well with Prompt Manager so saved prompts can be reused as part of recipe-driven pipelines
|
||||
- Ideal for iterative tuning: extract once, then keep adjusting recipe values and rerendering until the pipeline is where you want it
|
||||
- Helps standardize presets so repeated jobs start from consistent known-good settings
|
||||
|
||||
### Recipe Extractor
|
||||
- Reads and normalizes workflow metadata into reusable recipe data
|
||||
- Converts raw generation metadata into a structured recipe format that is easier to edit and pass between nodes
|
||||
- Helps preserve key settings (for example model family, sampler context, and recipe-specific parameters) when moving from ad-hoc runs to reusable setups
|
||||
- Useful when you want to recreate a look/style from existing outputs and then iterate from a stable baseline
|
||||
|
||||
### Recipe Renderer
|
||||
- Executes recipe-driven generation for fast reruns after setup
|
||||
- Interprets recipe data and applies it to generation execution so you can reproduce prior results or batch variants with minimal manual changes
|
||||
- Reduces setup overhead for repeated jobs by moving configuration logic into reusable recipe data
|
||||
- Especially useful when you want to test multiple prompt/input variations while keeping the same core generation recipe intact
|
||||
|
||||
### Recipe Relay
|
||||
- Relays recipe data and compatible passthrough context across nodes
|
||||
- Acts as a clean handoff point for recipe payloads so larger graphs stay modular and easier to reason about
|
||||
- Preserves compatible context as data moves through the pipeline, reducing brittle copy/paste style wiring patterns
|
||||
- Helpful when splitting complex graphs into logical stages (extract/build/render/manage) without losing recipe continuity
|
||||
|
||||
### Recipe Model Loader
|
||||
- Loads model/checkpoint assets based on recipe data
|
||||
- Resolves and applies model selections encoded in recipes so execution follows the intended model path automatically
|
||||
- Supports model slot selection and loader-specific behavior
|
||||
- Makes recipe playback more reliable across sessions by tying loader behavior to saved recipe intent instead of manual recollection
|
||||
- Useful for multi-model pipelines where model choice is part of the recipe contract, not an afterthought
|
||||
|
||||
### Recipe Manager
|
||||
- Save, browse, and reuse recipe entries
|
||||
- Provides persistent recipe storage so successful setups can be cataloged and recalled quickly
|
||||
- Works with Builder to quickly review and update saved recipe data
|
||||
- Encourages a library-style workflow: capture working recipes, name/tag them, and reapply them across projects
|
||||
- Great for maintaining repeatable production presets while still allowing safe versioned edits over time
|
||||
|
||||
## Model Family Support
|
||||
|
||||
Built-in support includes:
|
||||
- Flux 1
|
||||
- Flux 2
|
||||
- Ernie
|
||||
- SDXL
|
||||
- Wan
|
||||
- Qwen
|
||||
- Z-Image
|
||||
- Wan Image
|
||||
- Wan Video (I2V and T2V)
|
||||
|
After Width: | Height: | Size: 531 KiB |
|
Before Width: | Height: | Size: 766 KiB After Width: | Height: | Size: 766 KiB |
|
After Width: | Height: | Size: 670 KiB |
|
After Width: | Height: | Size: 743 KiB |
|
After Width: | Height: | Size: 280 KiB |
|
After Width: | Height: | Size: 1.2 MiB |
|
Before Width: | Height: | Size: 387 KiB |
|
Before Width: | Height: | Size: 450 KiB |
|
Before Width: | Height: | Size: 120 KiB |
|
Before Width: | Height: | Size: 229 KiB |
|
Before Width: | Height: | Size: 359 KiB After Width: | Height: | Size: 53 KiB |
|
After Width: | Height: | Size: 93 KiB |
|
After Width: | Height: | Size: 50 KiB |
|
After Width: | Height: | Size: 95 KiB |
|
After Width: | Height: | Size: 72 KiB |
|
After Width: | Height: | Size: 102 KiB |
|
Before Width: | Height: | Size: 267 KiB After Width: | Height: | Size: 40 KiB |
|
Before Width: | Height: | Size: 254 KiB |
|
Before Width: | Height: | Size: 229 KiB |
@@ -0,0 +1,656 @@
|
||||
import { app } from "../../scripts/app.js";
|
||||
import { api } from "../../scripts/api.js";
|
||||
import { PM_UI_PALETTE } from "./ui_palette.js";
|
||||
|
||||
const NODE_CLASS = "MultiLoraStackerLM";
|
||||
const LM_PROVIDER_CLASS = "Lora Stacker (LoraManager)";
|
||||
const STYLE_ID = "pm-multi-lm-style";
|
||||
const MIN_NODE_WIDTH = 1080;
|
||||
const MIN_NODE_HEIGHT = 320;
|
||||
const DEFAULT_NODE_WIDTH = 1080;
|
||||
const DEFAULT_NODE_HEIGHT = 430;
|
||||
// Height constants mirroring LM's loras_widget_utils.js
|
||||
const LM_LORA_ENTRY_H = 40;
|
||||
const LM_HEADER_H = 32;
|
||||
const LM_CONTAINER_PAD = 12;
|
||||
const LM_EMPTY_H = 100;
|
||||
// Per-column chrome: title(22) + search textarea(50) + col padding(16)
|
||||
const COL_CHROME_H = 88;
|
||||
|
||||
let loraCodeListenerAttached = false;
|
||||
let promptSerializationPatched = false;
|
||||
|
||||
const SLOT_DEFS = [
|
||||
{ key: "model_a", label: "Model A", short: "A", state: "loras_state_a" },
|
||||
{ key: "model_b", label: "Model B", short: "B", state: "loras_state_b" },
|
||||
{ key: "model_c", label: "Model C", short: "C", state: "loras_state_c" },
|
||||
{ key: "model_d", label: "Model D", short: "D", state: "loras_state_d" },
|
||||
];
|
||||
|
||||
let lmBridgePromise = null;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Styles
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function ensureStyles() {
|
||||
if (document.getElementById(STYLE_ID)) return;
|
||||
const p = PM_UI_PALETTE || {};
|
||||
const panel = p.panel || "hsl(216 11% 15%)";
|
||||
const panelBorder = p.panelBorder || "hsl(216 20% 65% / 0.24)";
|
||||
const inputBg = p.inputBg || "hsl(220 15% 10%)";
|
||||
const inputBorder = p.inputBorder || "hsl(218 10% 41%)";
|
||||
const textHeading = p.textHeading || "hsl(220 13% 85%)";
|
||||
const textPrimary = p.textPrimary || "hsl(0 0% 87%)";
|
||||
const textHint = p.textHint || "hsl(216 15% 65%)";
|
||||
const cardBg = p.cardBg || "hsl(219 16% 18%)";
|
||||
const accentBorder = "rgba(255,255,255,0.98)";
|
||||
const accentSoft = "rgba(255,255,255,0.42)";
|
||||
|
||||
const style = document.createElement("style");
|
||||
style.id = STYLE_ID;
|
||||
style.textContent = `
|
||||
.pm-multi-lm-root {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
box-sizing: border-box;
|
||||
padding: 6px 6px 6px 6px;
|
||||
overflow: hidden;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
.pm-multi-lm-root,
|
||||
.pm-multi-lm-root * {
|
||||
scrollbar-width: none;
|
||||
-ms-overflow-style: none;
|
||||
}
|
||||
.pm-multi-lm-root::-webkit-scrollbar,
|
||||
.pm-multi-lm-root *::-webkit-scrollbar {
|
||||
width: 0;
|
||||
height: 0;
|
||||
display: none;
|
||||
}
|
||||
.pm-multi-lm-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(4, minmax(200px, 1fr));
|
||||
gap: 8px;
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
align-items: stretch;
|
||||
}
|
||||
.pm-multi-lm-col {
|
||||
border: 1px solid ${panelBorder};
|
||||
border-radius: 8px;
|
||||
background: ${panel};
|
||||
padding: 8px;
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
flex-shrink: 0;
|
||||
min-height: 0;
|
||||
height: 100%;
|
||||
}
|
||||
.pm-multi-lm-col.active-slot {
|
||||
border-color: ${accentBorder};
|
||||
box-shadow: inset 0 0 0 1px ${accentSoft};
|
||||
}
|
||||
.pm-multi-lm-col.active-slot .pm-multi-lm-title {
|
||||
color: ${accentBorder};
|
||||
}
|
||||
.pm-multi-lm-title {
|
||||
font-weight: 700;
|
||||
font-size: 12px;
|
||||
letter-spacing: 0.02em;
|
||||
color: ${textHeading};
|
||||
margin-bottom: 6px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.pm-multi-lm-search {
|
||||
width: 100%;
|
||||
min-height: 38px;
|
||||
resize: vertical;
|
||||
box-sizing: border-box;
|
||||
border: 1px solid ${inputBorder};
|
||||
border-radius: 6px;
|
||||
padding: 6px 8px;
|
||||
background: ${inputBg};
|
||||
color: ${textPrimary};
|
||||
margin-bottom: 6px;
|
||||
font-size: 12px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.pm-multi-lm-search::placeholder {
|
||||
color: ${textHint};
|
||||
}
|
||||
.pm-multi-lm-list-host {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
overflow-y: auto;
|
||||
overflow-x: hidden;
|
||||
scrollbar-width: none;
|
||||
-ms-overflow-style: none;
|
||||
}
|
||||
.pm-multi-lm-list-host .lm-loras-container {
|
||||
height: 100%;
|
||||
max-height: none;
|
||||
background: ${cardBg};
|
||||
scrollbar-width: none;
|
||||
-ms-overflow-style: none;
|
||||
}
|
||||
.pm-multi-lm-list-host::-webkit-scrollbar,
|
||||
.pm-multi-lm-list-host .lm-loras-container::-webkit-scrollbar {
|
||||
width: 0;
|
||||
height: 0;
|
||||
display: none;
|
||||
}
|
||||
`;
|
||||
document.head.appendChild(style);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// LM bridge loader
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
async function loadLmBridge() {
|
||||
if (lmBridgePromise) return lmBridgePromise;
|
||||
lmBridgePromise = Promise.all([
|
||||
import("/extensions/ComfyUI-Lora-Manager/autocomplete.js"),
|
||||
import("/extensions/ComfyUI-Lora-Manager/loras_widget.js"),
|
||||
import("/extensions/ComfyUI-Lora-Manager/utils.js"),
|
||||
import("/extensions/ComfyUI-Lora-Manager/lora_syntax_utils.js"),
|
||||
]).then(([autocompleteMod, lorasWidgetMod, utilsMod, syntaxMod]) => ({
|
||||
AutoComplete: autocompleteMod.AutoComplete,
|
||||
addLorasWidget: lorasWidgetMod.addLorasWidget,
|
||||
mergeLoras: utilsMod.mergeLoras,
|
||||
applyLoraValuesToText: syntaxMod.applyLoraValuesToText,
|
||||
})).catch((err) => {
|
||||
console.warn("[PromptManager] Failed to load Lora-Manager bridge modules", err);
|
||||
lmBridgePromise = null;
|
||||
return null;
|
||||
});
|
||||
return lmBridgePromise;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Widget helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function getWidgetByName(node, name) {
|
||||
if (!node || !Array.isArray(node.widgets)) return null;
|
||||
return node.widgets.find((w) => w && w.name === name) ?? null;
|
||||
}
|
||||
|
||||
function ensureStateWidget(node, name) {
|
||||
let widget = getWidgetByName(node, name);
|
||||
if (widget) return widget;
|
||||
if (!node || typeof node.addWidget !== "function") return null;
|
||||
return node.addWidget("text", name, "[]", null, { multiline: true });
|
||||
}
|
||||
|
||||
function hideWidget(widget) {
|
||||
if (!widget || widget.__pm_hidden) return;
|
||||
widget.__pm_hidden = true;
|
||||
// Keep original widget type (STRING) so graphToPrompt includes state values.
|
||||
widget.hidden = true;
|
||||
widget.computeSize = () => [0, -4];
|
||||
widget.draw = function () {};
|
||||
if (widget.element) widget.element.style.display = "none";
|
||||
}
|
||||
|
||||
function hideStateWidgets(node) {
|
||||
if (!node || !Array.isArray(node.widgets)) return;
|
||||
for (const widget of node.widgets) {
|
||||
if (!widget || widget.name === "multi_lora_ui") continue;
|
||||
hideWidget(widget);
|
||||
}
|
||||
}
|
||||
|
||||
function parseLorasState(value) {
|
||||
if (Array.isArray(value)) return value;
|
||||
if (value && typeof value === "object" && Array.isArray(value.__value__)) {
|
||||
return value.__value__;
|
||||
}
|
||||
if (value && typeof value === "object" && typeof value.__value__ === "string") {
|
||||
try {
|
||||
const parsed = JSON.parse(value.__value__);
|
||||
return Array.isArray(parsed) ? parsed : [];
|
||||
} catch (_e) {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
if (typeof value !== "string") return [];
|
||||
const raw = value.trim();
|
||||
if (!raw || raw === "[]") return [];
|
||||
try {
|
||||
const parsed = JSON.parse(raw);
|
||||
return Array.isArray(parsed) ? parsed : [];
|
||||
} catch (_e) {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
function writeLorasState(widget, listValue) {
|
||||
if (!widget) return;
|
||||
widget.value = JSON.stringify(Array.isArray(listValue) ? listValue : []);
|
||||
}
|
||||
|
||||
function getSlotByKey(node, slotKey) {
|
||||
if (!node || !Array.isArray(node.__pmMultiLmSlots)) return null;
|
||||
return node.__pmMultiLmSlots.find((s) => s && s.key === slotKey) ?? null;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Apply incoming lora code to a slot
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function applyIncomingLoraCode(node, slotKey, code, mode) {
|
||||
if (!node || typeof code !== "string") return;
|
||||
const slot = getSlotByKey(node, slotKey);
|
||||
if (!slot || !slot.searchInput) return;
|
||||
const current = String(slot.searchInput.value || "");
|
||||
slot.searchInput.value = (mode === "replace" || !current) ? code : `${current}\n${code}`;
|
||||
slot.searchInput.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// lora_code_update listener (attached once, synchronously)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function attachLoraCodeListener() {
|
||||
if (loraCodeListenerAttached) return;
|
||||
loraCodeListenerAttached = true;
|
||||
|
||||
api.addEventListener("lora_code_update", (event) => {
|
||||
const detail = event?.detail;
|
||||
if (!detail) return;
|
||||
|
||||
const nodeId = Number(detail.id);
|
||||
if (!Number.isFinite(nodeId) || nodeId < 0) return;
|
||||
|
||||
const loraCode = typeof detail.lora_code === "string" ? detail.lora_code : "";
|
||||
const mode = typeof detail.mode === "string" ? detail.mode : "append";
|
||||
|
||||
// Find our node by integer ID
|
||||
const nodes = app.graph?._nodes;
|
||||
if (!Array.isArray(nodes)) return;
|
||||
const targetNode = nodes.find((n) => Number(n.id) === nodeId && n.type === NODE_CLASS);
|
||||
if (!targetNode) return;
|
||||
|
||||
// Route to the currently-selected active slot
|
||||
const activeSlot = targetNode.properties?.pmActiveSlot ?? "model_a";
|
||||
applyIncomingLoraCode(targetNode, activeSlot, loraCode, mode);
|
||||
});
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Prompt serialization shim:
|
||||
// Keep LM comfyClass for manager integration, but serialize this node as its
|
||||
// real backend class so ComfyUI validates against MultiLoraStackerLM inputs.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function attachPromptSerializationShim() {
|
||||
if (promptSerializationPatched) return;
|
||||
if (!app || typeof app.graphToPrompt !== "function") return;
|
||||
|
||||
promptSerializationPatched = true;
|
||||
const originalGraphToPrompt = app.graphToPrompt.bind(app);
|
||||
|
||||
app.graphToPrompt = async function (...args) {
|
||||
const swapped = [];
|
||||
const nodes = app.graph?._nodes;
|
||||
|
||||
if (Array.isArray(nodes)) {
|
||||
for (const node of nodes) {
|
||||
if (!node || node.type !== NODE_CLASS) continue;
|
||||
if (node.comfyClass !== LM_PROVIDER_CLASS) continue;
|
||||
swapped.push(node);
|
||||
node.comfyClass = NODE_CLASS;
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
return await originalGraphToPrompt(...args);
|
||||
} finally {
|
||||
for (const node of swapped) {
|
||||
node.comfyClass = LM_PROVIDER_CLASS;
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Active-slot selection (click a section to target LM sends)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function setActiveSlot(node, slotKey) {
|
||||
if (!node) return;
|
||||
if (!node.properties) node.properties = {};
|
||||
node.properties.pmActiveSlot = slotKey;
|
||||
updateActiveColumnHighlight(node);
|
||||
}
|
||||
|
||||
function updateActiveColumnHighlight(node) {
|
||||
if (!Array.isArray(node.__pmMultiLmSlots)) return;
|
||||
const activeSlot = node.properties?.pmActiveSlot ?? "model_a";
|
||||
for (const slot of node.__pmMultiLmSlots) {
|
||||
if (slot?.col) slot.col.classList.toggle("active-slot", slot.key === activeSlot);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Embedded loras widget via fakeNode pattern
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function createEmbeddedLorasWidget(node, lm, widgetName, initialValue, onChange) {
|
||||
const host = document.createElement("div");
|
||||
host.className = "pm-multi-lm-list-host";
|
||||
|
||||
const fakeNode = {
|
||||
addDOMWidget(name, type, container, options) {
|
||||
return {
|
||||
name,
|
||||
type,
|
||||
callback: null,
|
||||
element: container,
|
||||
get value() {
|
||||
return typeof options?.getValue === "function" ? options.getValue() : [];
|
||||
},
|
||||
set value(v) {
|
||||
if (typeof options?.setValue === "function") options.setValue(v);
|
||||
},
|
||||
};
|
||||
},
|
||||
setDirtyCanvas(fg, bg) { node?.setDirtyCanvas?.(fg, bg); },
|
||||
};
|
||||
|
||||
const out = lm.addLorasWidget(fakeNode, widgetName, {}, onChange);
|
||||
if (out?.widget?.element) host.appendChild(out.widget.element);
|
||||
if (out?.widget && Array.isArray(initialValue) && initialValue.length > 0) {
|
||||
out.widget.value = initialValue;
|
||||
}
|
||||
|
||||
return { host, widget: out?.widget ?? null };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Height management — mirrors LM's updateWidgetHeight approach:
|
||||
// set CSS vars on the root element so ComfyUI's layout system resizes the node,
|
||||
// never calling node.setSize() (which would prevent user resize).
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function computeContentHeight(node) {
|
||||
let maxListH = LM_EMPTY_H;
|
||||
if (Array.isArray(node.__pmMultiLmSlots)) {
|
||||
for (const slot of node.__pmMultiLmSlots) {
|
||||
const count = Array.isArray(slot.lorasWidget?.value) ? slot.lorasWidget.value.length : 0;
|
||||
const h = count === 0
|
||||
? LM_EMPTY_H
|
||||
: LM_CONTAINER_PAD + LM_HEADER_H + Math.min(count, 12) * LM_LORA_ENTRY_H;
|
||||
if (h > maxListH) maxListH = h;
|
||||
}
|
||||
}
|
||||
return COL_CHROME_H + maxListH + 20;
|
||||
}
|
||||
|
||||
function notifyHeightChange(node) {
|
||||
const root = node?.__pmMultiLmRoot;
|
||||
if (!root) return;
|
||||
const h = computeContentHeight(node);
|
||||
root.style.setProperty('--comfy-widget-min-height', `${h}px`);
|
||||
root.style.setProperty('--comfy-widget-height', `${h}px`);
|
||||
applyNodeSizeConstraints(node);
|
||||
setTimeout(() => { node?.setDirtyCanvas?.(true, true); }, 10);
|
||||
}
|
||||
|
||||
function applyNodeSizeConstraints(node, useDefaultSize = false) {
|
||||
if (!node || node.__pmApplyingSizeConstraint) return;
|
||||
|
||||
const currentW = Number(node?.size?.[0]) || 0;
|
||||
const currentH = Number(node?.size?.[1]) || 0;
|
||||
|
||||
const targetW = useDefaultSize
|
||||
? Math.max(DEFAULT_NODE_WIDTH, MIN_NODE_WIDTH, currentW)
|
||||
: Math.max(MIN_NODE_WIDTH, currentW);
|
||||
|
||||
const targetH = useDefaultSize
|
||||
? Math.max(DEFAULT_NODE_HEIGHT, MIN_NODE_HEIGHT, currentH)
|
||||
: Math.max(MIN_NODE_HEIGHT, currentH);
|
||||
|
||||
if (targetW === currentW && targetH === currentH) return;
|
||||
|
||||
node.__pmApplyingSizeConstraint = true;
|
||||
try {
|
||||
node.setSize([targetW, targetH]);
|
||||
} finally {
|
||||
node.__pmApplyingSizeConstraint = false;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Per-slot column builder
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function buildSlotColumn(node, lm, slotDef) {
|
||||
const stateWidget = ensureStateWidget(node, slotDef.state);
|
||||
hideWidget(stateWidget);
|
||||
|
||||
const col = document.createElement("div");
|
||||
col.className = "pm-multi-lm-col";
|
||||
col.title = `Click to make ${slotDef.label} the LoRA Manager target`;
|
||||
col.addEventListener("pointerdown", () => setActiveSlot(node, slotDef.key));
|
||||
|
||||
const title = document.createElement("div");
|
||||
title.className = "pm-multi-lm-title";
|
||||
title.textContent = slotDef.label;
|
||||
|
||||
const searchInput = document.createElement("textarea");
|
||||
searchInput.className = "pm-multi-lm-search";
|
||||
searchInput.placeholder = "Search LoRAs to add\u2026";
|
||||
searchInput.rows = 1;
|
||||
searchInput.addEventListener("focus", () => setActiveSlot(node, slotDef.key));
|
||||
|
||||
// Attach LM autocomplete to the search textarea
|
||||
new lm.AutoComplete(searchInput, "loras", { showPreview: false });
|
||||
|
||||
const initialState = parseLorasState(stateWidget?.value ?? "[]");
|
||||
|
||||
let isSyncing = false;
|
||||
|
||||
const embedded = createEmbeddedLorasWidget(
|
||||
node, lm, `${slotDef.key}_loras`, initialState,
|
||||
(value) => {
|
||||
if (isSyncing) return;
|
||||
isSyncing = true;
|
||||
try {
|
||||
const safe = Array.isArray(value) ? value : [];
|
||||
writeLorasState(stateWidget, safe);
|
||||
const nextText = lm.applyLoraValuesToText(searchInput.value || "", safe);
|
||||
if (searchInput.value !== nextText) searchInput.value = nextText;
|
||||
} finally {
|
||||
isSyncing = false;
|
||||
notifyHeightChange(node);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// When user types or autocomplete fires, merge into the loras list
|
||||
searchInput.addEventListener("input", () => {
|
||||
if (isSyncing) return;
|
||||
isSyncing = true;
|
||||
try {
|
||||
const existing = Array.isArray(embedded.widget?.value) ? embedded.widget.value : [];
|
||||
const merged = lm.mergeLoras(searchInput.value || "", existing);
|
||||
if (embedded.widget) embedded.widget.value = merged;
|
||||
writeLorasState(stateWidget, merged);
|
||||
} finally {
|
||||
isSyncing = false;
|
||||
notifyHeightChange(node);
|
||||
}
|
||||
});
|
||||
|
||||
col.appendChild(title);
|
||||
col.appendChild(searchInput);
|
||||
col.appendChild(embedded.host);
|
||||
embedded.host.addEventListener("pointerdown", () => setActiveSlot(node, slotDef.key));
|
||||
|
||||
return { key: slotDef.key, stateWidget, searchInput, lorasWidget: embedded.widget, col };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Restore widget state from persisted JSON
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function refreshFromStoredValues(node) {
|
||||
if (!node?.__pmMultiLmSlots || !node.__pmMultiLmBridge) return;
|
||||
for (const slot of node.__pmMultiLmSlots) {
|
||||
const state = parseLorasState(slot.stateWidget?.value ?? "[]");
|
||||
|
||||
// Restore from persisted JSON directly. Do NOT call mergeLoras here:
|
||||
// mergeLoras requires syntax in text input, and would drop entries
|
||||
// during tab-switch/workflow-load when textarea is initially empty.
|
||||
if (slot.lorasWidget) slot.lorasWidget.value = state;
|
||||
writeLorasState(slot.stateWidget, state);
|
||||
|
||||
// Keep syntax textarea consistent with restored list.
|
||||
const nextText = node.__pmMultiLmBridge.applyLoraValuesToText(slot.searchInput.value || "", state);
|
||||
if (slot.searchInput.value !== nextText) slot.searchInput.value = nextText;
|
||||
}
|
||||
notifyHeightChange(node);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Main async UI setup
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
async function setupNodeUi(node) {
|
||||
if (!node || node.__pmMultiLmReady) return;
|
||||
|
||||
ensureStyles();
|
||||
const lm = await loadLmBridge();
|
||||
if (!lm || node.__pmMultiLmReady) return;
|
||||
|
||||
hideStateWidgets(node);
|
||||
|
||||
const root = document.createElement("div");
|
||||
root.className = "pm-multi-lm-root";
|
||||
|
||||
// 4-column LoRA grid
|
||||
const grid = document.createElement("div");
|
||||
grid.className = "pm-multi-lm-grid";
|
||||
root.appendChild(grid);
|
||||
|
||||
const slots = SLOT_DEFS.map((slotDef) => {
|
||||
const slot = buildSlotColumn(node, lm, slotDef);
|
||||
grid.appendChild(slot.col);
|
||||
return slot;
|
||||
});
|
||||
|
||||
const uiWidget = node.addDOMWidget("multi_lora_ui", "div", root, {
|
||||
serialize: false,
|
||||
hideOnZoom: false,
|
||||
getMinHeight: () => computeContentHeight(node),
|
||||
getHeight: () => "100%",
|
||||
});
|
||||
|
||||
node.__pmMultiLmBridge = lm;
|
||||
node.__pmMultiLmSlots = slots;
|
||||
node.__pmMultiLmRoot = root;
|
||||
node.__pmMultiLmReady = true;
|
||||
node.__pmMultiLmRefresh = () => {
|
||||
refreshFromStoredValues(node);
|
||||
updateActiveColumnHighlight(node);
|
||||
};
|
||||
|
||||
// comfyClass already set synchronously in onNodeCreated — no registry tricks needed
|
||||
// Restore any lora data that onConfigure may have written before async completed
|
||||
refreshFromStoredValues(node);
|
||||
hideStateWidgets(node);
|
||||
updateActiveColumnHighlight(node);
|
||||
notifyHeightChange(node);
|
||||
applyNodeSizeConstraints(node);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Extension registration
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
app.registerExtension({
|
||||
name: "PromptManager.MultiLoraStackerLM",
|
||||
|
||||
async beforeRegisterNodeDef(nodeType) {
|
||||
if (nodeType.comfyClass !== NODE_CLASS) return;
|
||||
|
||||
// Attach the send-to-node listener once, immediately (synchronous)
|
||||
attachLoraCodeListener();
|
||||
// Ensure prompt uses backend class while keeping LM comfyClass at runtime.
|
||||
attachPromptSerializationShim();
|
||||
|
||||
// ── onNodeCreated ──────────────────────────────────────────────────
|
||||
const onNodeCreated = nodeType.prototype.onNodeCreated;
|
||||
nodeType.prototype.onNodeCreated = function () {
|
||||
const result = onNodeCreated ? onNodeCreated.apply(this, arguments) : undefined;
|
||||
|
||||
this.serialize_widgets = true;
|
||||
|
||||
// Set comfyClass SYNCHRONOUSLY so LM WorkflowRegistry includes us
|
||||
// on the next lora_registry_refresh sweep
|
||||
this.comfyClass = LM_PROVIDER_CLASS;
|
||||
|
||||
if (!this.properties) this.properties = {};
|
||||
if (!this.properties.pmActiveSlot) this.properties.pmActiveSlot = "model_a";
|
||||
|
||||
applyNodeSizeConstraints(this, true);
|
||||
|
||||
void setupNodeUi(this);
|
||||
return result;
|
||||
};
|
||||
|
||||
// ── onConfigure (workflow load / tab switch) ──────────────────────
|
||||
const onConfigure = nodeType.prototype.onConfigure;
|
||||
nodeType.prototype.onConfigure = function (config) {
|
||||
const result = onConfigure ? onConfigure.apply(this, arguments) : undefined;
|
||||
|
||||
// Re-assert comfyClass in case ComfyUI reset it during configure
|
||||
this.comfyClass = LM_PROVIDER_CLASS;
|
||||
|
||||
hideStateWidgets(this);
|
||||
|
||||
if (typeof this.__pmMultiLmRefresh === "function") {
|
||||
this.__pmMultiLmRefresh();
|
||||
}
|
||||
|
||||
applyNodeSizeConstraints(this);
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
const onModeChange = nodeType.prototype.onModeChange;
|
||||
nodeType.prototype.onModeChange = function () {
|
||||
const result = onModeChange ? onModeChange.apply(this, arguments) : undefined;
|
||||
hideStateWidgets(this);
|
||||
if (typeof this.__pmMultiLmRefresh === "function") {
|
||||
this.__pmMultiLmRefresh();
|
||||
}
|
||||
applyNodeSizeConstraints(this);
|
||||
return result;
|
||||
};
|
||||
|
||||
const onResize = nodeType.prototype.onResize;
|
||||
nodeType.prototype.onResize = function () {
|
||||
const result = onResize ? onResize.apply(this, arguments) : undefined;
|
||||
applyNodeSizeConstraints(this);
|
||||
return result;
|
||||
};
|
||||
|
||||
// ── onRemoved ──────────────────────────────────────────────────────
|
||||
const onRemoved = nodeType.prototype.onRemoved;
|
||||
nodeType.prototype.onRemoved = function () {
|
||||
this.__pmMultiLmSlots = null;
|
||||
this.__pmMultiLmRoot = null;
|
||||
this.__pmMultiLmBridge = null;
|
||||
this.__pmMultiLmReady = false;
|
||||
this.__pmMultiLmRefresh = null;
|
||||
return onRemoved ? onRemoved.apply(this, arguments) : undefined;
|
||||
};
|
||||
},
|
||||
});
|
||||
@@ -209,6 +209,271 @@ function _normalizeExtractedLoraOrder(extracted) {
|
||||
return normalized;
|
||||
}
|
||||
|
||||
function _extractorParseJsonObjectSafe(rawValue, fallback = null) {
|
||||
if (rawValue && typeof rawValue === "object") return rawValue;
|
||||
if (typeof rawValue !== "string") return fallback;
|
||||
const trimmed = rawValue.trim();
|
||||
if (!trimmed) return fallback;
|
||||
try {
|
||||
const parsed = JSON.parse(trimmed);
|
||||
return parsed && typeof parsed === "object" ? parsed : fallback;
|
||||
} catch {
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
|
||||
function _extractorModelNameForSummary(pathLike) {
|
||||
const raw = String(pathLike || "").trim();
|
||||
if (!raw) return "";
|
||||
const parts = raw.replace(/\\/g, "/").split("/");
|
||||
const base = parts[parts.length - 1] || raw;
|
||||
return base.replace(/\.(safetensors|ckpt|pt|pth|bin|gguf|sft)$/i, "");
|
||||
}
|
||||
|
||||
function _extractorNormalizeSummaryLoras(list) {
|
||||
if (!Array.isArray(list)) return [];
|
||||
return list
|
||||
.map((item) => {
|
||||
if (!item || typeof item !== "object") return null;
|
||||
const name = String(item.name || "").trim();
|
||||
if (!name) return null;
|
||||
const strengthRaw = Number(item.model_strength ?? item.strength ?? 1.0);
|
||||
const strength = Number.isFinite(strengthRaw) ? strengthRaw : 1.0;
|
||||
const available = item.available !== false && item.found !== false;
|
||||
return {
|
||||
name,
|
||||
strength,
|
||||
active: item.active !== false,
|
||||
available,
|
||||
found: item.found !== false,
|
||||
};
|
||||
})
|
||||
.filter(Boolean)
|
||||
.sort((a, b) => String(a.name).localeCompare(String(b.name)));
|
||||
}
|
||||
|
||||
function _extractorSummarizeWorkflowDataDiscovery(rawWorkflowData) {
|
||||
const empty = {
|
||||
modelCount: 0,
|
||||
modelDetails: [],
|
||||
source: "RecipeExtractor",
|
||||
};
|
||||
|
||||
const wf = _extractorParseJsonObjectSafe(rawWorkflowData, null);
|
||||
if (!wf || typeof wf !== "object") return empty;
|
||||
|
||||
const slotOrder = ["model_a", "model_b", "model_c", "model_d"];
|
||||
const modelDetails = [];
|
||||
const models = (wf.models && typeof wf.models === "object") ? wf.models : null;
|
||||
|
||||
if (models) {
|
||||
for (const slot of slotOrder) {
|
||||
const block = models[slot];
|
||||
if (!block || typeof block !== "object") continue;
|
||||
const modelName = String(block.model || "").trim();
|
||||
const loras = _extractorNormalizeSummaryLoras(block.loras);
|
||||
if (!modelName && loras.length === 0) continue;
|
||||
modelDetails.push({
|
||||
slotLabel: String(slot).replace("model_", "").toUpperCase(),
|
||||
modelDisplay: _extractorModelNameForSummary(modelName),
|
||||
family: String(block.family || "").trim(),
|
||||
loras,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
const modelA = String(wf.model_a || "").trim();
|
||||
const modelB = String(wf.model_b || "").trim();
|
||||
const lorasA = _extractorNormalizeSummaryLoras(wf.loras_a);
|
||||
const lorasB = _extractorNormalizeSummaryLoras(wf.loras_b);
|
||||
|
||||
if (modelA || lorasA.length > 0) {
|
||||
modelDetails.push({
|
||||
slotLabel: "A",
|
||||
modelDisplay: _extractorModelNameForSummary(modelA),
|
||||
family: "",
|
||||
loras: lorasA,
|
||||
});
|
||||
}
|
||||
if (modelB || lorasB.length > 0) {
|
||||
modelDetails.push({
|
||||
slotLabel: "B",
|
||||
modelDisplay: _extractorModelNameForSummary(modelB),
|
||||
family: "",
|
||||
loras: lorasB,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
modelCount: modelDetails.length,
|
||||
modelDetails,
|
||||
source: String(wf._source || "RecipeExtractor"),
|
||||
};
|
||||
}
|
||||
|
||||
function _createExtractorSummaryLoraTag(lora) {
|
||||
const tag = document.createElement("div");
|
||||
const isAvailable = lora?.available !== false && lora?.found !== false;
|
||||
const strength = Number(lora?.strength ?? 1.0);
|
||||
|
||||
tag.style.cssText = `
|
||||
display:inline-flex;
|
||||
align-items:center;
|
||||
gap:6px;
|
||||
width:200px;
|
||||
height:24px;
|
||||
padding:4px 10px;
|
||||
box-sizing:border-box;
|
||||
border-radius:6px;
|
||||
border:1px solid ${isAvailable ? "rgba(71,145,220,0.85)" : "rgba(220,53,69,0.9)"};
|
||||
background:${isAvailable ? "rgba(61,134,210,0.9)" : "rgba(220,53,69,0.9)"};
|
||||
color:#fff;
|
||||
flex-shrink:0;
|
||||
font-size:12px;
|
||||
`;
|
||||
|
||||
const nameSpan = document.createElement("span");
|
||||
nameSpan.textContent = String(lora?.name || "");
|
||||
nameSpan.style.cssText = "flex-grow:1; overflow:hidden; text-overflow:ellipsis; white-space:nowrap;";
|
||||
tag.appendChild(nameSpan);
|
||||
|
||||
const strengthBadge = document.createElement("span");
|
||||
strengthBadge.textContent = Number.isFinite(strength) ? strength.toFixed(2) : "1.00";
|
||||
strengthBadge.style.cssText = "font-size:10px; font-weight:600; padding:1px 6px; border-radius:999px; background:rgba(255,255,255,0.15);";
|
||||
tag.appendChild(strengthBadge);
|
||||
|
||||
return tag;
|
||||
}
|
||||
|
||||
function _showExtractorWorkflowSummaryDialog(summary) {
|
||||
return new Promise((resolve) => {
|
||||
const overlay = document.createElement("div");
|
||||
overlay.style.cssText = "position:fixed; inset:0; background:rgba(0,0,0,0.7); z-index:9999;";
|
||||
|
||||
const dialog = document.createElement("div");
|
||||
dialog.style.cssText = "position:fixed; top:50%; left:50%; transform:translate(-50%, -50%); width:min(452px, 92vw); max-height:78vh; overflow:auto; background:#232930; border:1px solid #3c4b59; border-radius:10px; padding:12px; z-index:10000; box-shadow:0 8px 28px rgba(0,0,0,0.55);";
|
||||
|
||||
const title = document.createElement("div");
|
||||
title.textContent = "Summary";
|
||||
title.style.cssText = "margin-bottom:8px; font-size:17px; font-weight:700; color:#e7eef6;";
|
||||
dialog.appendChild(title);
|
||||
|
||||
const meta = document.createElement("div");
|
||||
meta.style.cssText = "margin-bottom:12px; color:#9eb2c6; font-size:12px; padding-bottom:10px; border-bottom:1px solid rgba(115,144,170,0.35);";
|
||||
meta.innerHTML = `<b style=\"color:#c5d8ea;\">Models found:</b> ${summary.modelCount}`;
|
||||
dialog.appendChild(meta);
|
||||
|
||||
const modelsSection = document.createElement("div");
|
||||
modelsSection.style.cssText = "margin-bottom:14px;";
|
||||
modelsSection.innerHTML = `<div style=\"color:#8fb8dc; font-weight:700; margin-bottom:6px;\">Models</div>`;
|
||||
const modelsList = document.createElement("div");
|
||||
modelsList.style.cssText = "display:flex; flex-direction:column; gap:6px;";
|
||||
if (!summary.modelDetails.length) {
|
||||
const none = document.createElement("div");
|
||||
none.textContent = "No models found.";
|
||||
none.style.cssText = "color:#9aa8b7; font-size:12px;";
|
||||
modelsList.appendChild(none);
|
||||
} else {
|
||||
for (const item of summary.modelDetails) {
|
||||
const row = document.createElement("div");
|
||||
const familyText = item.family ? ` (${item.family})` : "";
|
||||
row.textContent = `${item.slotLabel}: ${item.modelDisplay || "(none)"}${familyText}`;
|
||||
row.style.cssText = "color:#d9e6f3; font-size:13px; background:rgba(37,48,60,0.55); border:1px solid rgba(96,124,150,0.35); border-radius:6px; padding:6px 8px;";
|
||||
modelsList.appendChild(row);
|
||||
}
|
||||
}
|
||||
modelsSection.appendChild(modelsList);
|
||||
dialog.appendChild(modelsSection);
|
||||
|
||||
const loraDivider = document.createElement("div");
|
||||
loraDivider.style.cssText = "height:1px; background:rgba(115,144,170,0.35); margin:2px 0 12px 0;";
|
||||
dialog.appendChild(loraDivider);
|
||||
|
||||
const loraSection = document.createElement("div");
|
||||
loraSection.innerHTML = `<div style=\"color:#8fb8dc; font-weight:700; margin-bottom:8px;\">LoRAs</div>`;
|
||||
if (!summary.modelDetails.some((m) => Array.isArray(m.loras) && m.loras.length > 0)) {
|
||||
const none = document.createElement("div");
|
||||
none.textContent = "No LoRAs found.";
|
||||
none.style.cssText = "color:#9aa8b7; font-size:12px; margin-bottom:8px;";
|
||||
loraSection.appendChild(none);
|
||||
} else {
|
||||
for (const item of summary.modelDetails) {
|
||||
if (!Array.isArray(item.loras) || item.loras.length === 0) continue;
|
||||
const stackCard = document.createElement("div");
|
||||
stackCard.style.cssText = "background:rgba(30,40,52,0.55); border:1px solid rgba(96,124,150,0.35); border-radius:8px; padding:6px; margin-bottom:6px;";
|
||||
|
||||
const stackTitle = document.createElement("div");
|
||||
stackTitle.textContent = `Stack ${item.slotLabel}:`;
|
||||
stackTitle.style.cssText = "color:#c5d8ea; font-size:12px; margin:0 0 6px 0;";
|
||||
stackCard.appendChild(stackTitle);
|
||||
|
||||
const stackTags = document.createElement("div");
|
||||
stackTags.style.cssText = "display:grid; grid-template-columns: 200px 200px; justify-content:start; gap:2px;";
|
||||
for (const lora of item.loras) {
|
||||
stackTags.appendChild(_createExtractorSummaryLoraTag(lora));
|
||||
}
|
||||
stackCard.appendChild(stackTags);
|
||||
loraSection.appendChild(stackCard);
|
||||
}
|
||||
}
|
||||
dialog.appendChild(loraSection);
|
||||
|
||||
const actions = document.createElement("div");
|
||||
actions.style.cssText = "display:flex; justify-content:flex-end; margin-top:14px;";
|
||||
const okBtn = document.createElement("button");
|
||||
okBtn.textContent = "OK";
|
||||
okBtn.style.cssText = "padding:8px 16px; background:#2f7dbf; color:#fff; border:none; border-radius:6px; cursor:pointer;";
|
||||
actions.appendChild(okBtn);
|
||||
dialog.appendChild(actions);
|
||||
|
||||
const cleanup = () => {
|
||||
if (overlay.parentNode) document.body.removeChild(overlay);
|
||||
if (dialog.parentNode) document.body.removeChild(dialog);
|
||||
};
|
||||
|
||||
okBtn.onclick = () => { cleanup(); resolve(true); };
|
||||
overlay.onclick = () => { cleanup(); resolve(true); };
|
||||
|
||||
document.body.appendChild(overlay);
|
||||
document.body.appendChild(dialog);
|
||||
okBtn.focus();
|
||||
});
|
||||
}
|
||||
|
||||
async function showExtractorWorkflowDiscoverySummary(node) {
|
||||
const rawCached = node?.properties?.pe_extracted_data;
|
||||
let workflowData = _extractorParseJsonObjectSafe(rawCached, null);
|
||||
|
||||
if (!workflowData) {
|
||||
const imageWidget = node?.widgets?.find((w) => w.name === "image");
|
||||
const filename = String(imageWidget?.value || "").trim();
|
||||
const sourceFolder = node?._sourceFolder || "input";
|
||||
if (filename && filename !== "(none)") {
|
||||
try {
|
||||
const previewResp = await fetch(`/prompt-extractor/extract-preview?filename=${encodeURIComponent(filename)}&source=${encodeURIComponent(sourceFolder)}`);
|
||||
if (previewResp.ok) {
|
||||
const previewData = await previewResp.json();
|
||||
if (previewData?.extracted && typeof previewData.extracted === "object") {
|
||||
workflowData = _normalizeExtractedLoraOrder(previewData.extracted);
|
||||
node.properties = node.properties || {};
|
||||
node.properties.pe_extracted_data = JSON.stringify(workflowData);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('[PromptExtractor] Could not refresh extracted preview data:', error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!workflowData || typeof workflowData !== "object") {
|
||||
await _showExtractorWorkflowSummaryDialog({ modelCount: 0, modelDetails: [], source: "RecipeExtractor" });
|
||||
return;
|
||||
}
|
||||
|
||||
const summary = _extractorSummarizeWorkflowDataDiscovery(workflowData);
|
||||
await _showExtractorWorkflowSummaryDialog(summary);
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract metadata from JPEG/WebP file
|
||||
* Reads EXIF UserComment field (0x9286) for workflow metadata
|
||||
@@ -932,7 +1197,7 @@ app.registerExtension({
|
||||
// Find the node with this filename
|
||||
if (app.graph && app.graph._nodes) {
|
||||
for (const node of app.graph._nodes) {
|
||||
if (node.type === "PromptExtractor" || node.type === "WorkflowExtractor") {
|
||||
if (node.type === "PromptExtractor" || node.type === "RecipeExtractor") {
|
||||
const imageWidget = node.widgets?.find(w => w.name === "image");
|
||||
const frameWidget = node.widgets?.find(w => w.name === "frame_position");
|
||||
|
||||
@@ -954,7 +1219,7 @@ app.registerExtension({
|
||||
},
|
||||
|
||||
async beforeRegisterNodeDef(nodeType, nodeData, app) {
|
||||
if (nodeData.name === "PromptExtractor" || nodeData.name === "WorkflowExtractor") {
|
||||
if (nodeData.name === "PromptExtractor" || nodeData.name === "RecipeExtractor") {
|
||||
const onNodeCreated = nodeType.prototype.onNodeCreated;
|
||||
|
||||
nodeType.prototype.onNodeCreated = function () {
|
||||
@@ -1155,7 +1420,7 @@ app.registerExtension({
|
||||
const result = onConfigure ? onConfigure.apply(this, arguments) : undefined;
|
||||
|
||||
// ── Migration: remove stale inputs/outputs from old workflows ──
|
||||
const isWorkflowExtractor = this.type === "WorkflowExtractor";
|
||||
const isWorkflowExtractor = this.type === "RecipeExtractor";
|
||||
const VALID_INPUTS = isWorkflowExtractor
|
||||
? new Set([])
|
||||
: new Set(["lora_stack_a", "lora_stack_b"]);
|
||||
@@ -1168,7 +1433,7 @@ app.registerExtension({
|
||||
}
|
||||
const VALID_OUTPUTS = isWorkflowExtractor
|
||||
? [
|
||||
{ name: "workflow_data", type: "WORKFLOW_DATA" },
|
||||
{ name: "recipe_data", type: "RECIPE_DATA" },
|
||||
{ name: "image", type: "IMAGE" },
|
||||
]
|
||||
: [
|
||||
@@ -1176,7 +1441,7 @@ app.registerExtension({
|
||||
{ name: "negative_prompt", type: "STRING" },
|
||||
{ name: "lora_stack_a", type: "LORA_STACK" },
|
||||
{ name: "lora_stack_b", type: "LORA_STACK" },
|
||||
{ name: "workflow_data", type: "WORKFLOW_DATA" },
|
||||
{ name: "recipe_data", type: "RECIPE_DATA" },
|
||||
{ name: "image", type: "IMAGE" },
|
||||
];
|
||||
if (this.outputs) {
|
||||
@@ -1354,29 +1619,57 @@ app.registerExtension({
|
||||
|
||||
// Draw status indicator if we have an image and node is not minimized
|
||||
if (node.imgs && node.imgs.length > 0 && !(node.flags && node.flags.collapsed)) {
|
||||
const radius = 7;
|
||||
ctx.save();
|
||||
const titleHeight = LiteGraph.NODE_TITLE_HEIGHT || 30;
|
||||
// Position in top-right, raised 20px to be in title bar
|
||||
const x = node.size[0] - radius - 8;
|
||||
const y = (titleHeight / 2) - 30;
|
||||
const infoWidth = 30;
|
||||
const infoHeight = 14;
|
||||
const infoX = node.size[0] - infoWidth - 8;
|
||||
const infoY = (titleHeight / 2) - 37;
|
||||
const cornerRadius = 7;
|
||||
|
||||
// Draw indicator circle
|
||||
ctx.beginPath();
|
||||
ctx.arc(x, y, radius, 0, Math.PI * 2);
|
||||
ctx.fillStyle = node.hasWorkflow ? '#00ff00' : '#ff3333';
|
||||
// Draw compact info pill (blue active, gray inactive)
|
||||
const drawRoundRect = (x, y, w, h, r) => {
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(x + r, y);
|
||||
ctx.lineTo(x + w - r, y);
|
||||
ctx.quadraticCurveTo(x + w, y, x + w, y + r);
|
||||
ctx.lineTo(x + w, y + h - r);
|
||||
ctx.quadraticCurveTo(x + w, y + h, x + w - r, y + h);
|
||||
ctx.lineTo(x + r, y + h);
|
||||
ctx.quadraticCurveTo(x, y + h, x, y + h - r);
|
||||
ctx.lineTo(x, y + r);
|
||||
ctx.quadraticCurveTo(x, y, x + r, y);
|
||||
ctx.closePath();
|
||||
};
|
||||
|
||||
drawRoundRect(infoX, infoY, infoWidth, infoHeight, cornerRadius);
|
||||
ctx.fillStyle = node.hasWorkflow ? 'rgba(55, 142, 255, 0.92)' : 'rgba(120, 130, 140, 0.35)';
|
||||
ctx.fill();
|
||||
ctx.strokeStyle = node.hasWorkflow ? '#054405' : '#550505';
|
||||
ctx.strokeStyle = 'rgba(240, 248, 255, 0.95)';
|
||||
ctx.lineWidth = 1;
|
||||
ctx.stroke();
|
||||
|
||||
ctx.fillStyle = node.hasWorkflow ? '#ffffff' : 'rgba(220, 226, 234, 0.75)';
|
||||
ctx.font = 'bold 8px sans-serif';
|
||||
ctx.textAlign = 'center';
|
||||
ctx.textBaseline = 'middle';
|
||||
ctx.fillText('info', infoX + (infoWidth / 2), infoY + (infoHeight / 2) + 0.5);
|
||||
|
||||
node._workflowInfoBounds = {
|
||||
x: infoX,
|
||||
y: infoY,
|
||||
width: infoWidth,
|
||||
height: infoHeight,
|
||||
};
|
||||
|
||||
// Draw preview play icon (simple triangle) left of workflow indicator - only for images/videos
|
||||
const imageWidget = node.widgets?.find(w => w.name === "image");
|
||||
const currentFile = imageWidget?.value;
|
||||
|
||||
if (isPreviewableFile(currentFile)) {
|
||||
const playX = node.size[0] - radius - 8 - 34;
|
||||
const playY = (titleHeight / 2) - 30;
|
||||
const triSize = 8;
|
||||
const playX = infoX - 14;
|
||||
const playY = infoY + (infoHeight / 2);
|
||||
const triSize = 7;
|
||||
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(playX - triSize, playY - triSize);
|
||||
@@ -1396,7 +1689,9 @@ app.registerExtension({
|
||||
} else {
|
||||
node._previewIconBounds = null;
|
||||
}
|
||||
ctx.restore();
|
||||
} else {
|
||||
node._workflowInfoBounds = null;
|
||||
node._previewIconBounds = null;
|
||||
}
|
||||
|
||||
@@ -1407,23 +1702,15 @@ app.registerExtension({
|
||||
const onMouseMove = node.onMouseMove;
|
||||
node.onMouseMove = function(e, localPos, canvas) {
|
||||
const result = onMouseMove ? onMouseMove.apply(this, arguments) : undefined;
|
||||
|
||||
// Check if hovering over indicator
|
||||
const radius = 7;
|
||||
const titleHeight = LiteGraph.NODE_TITLE_HEIGHT || 30;
|
||||
// Position raised 20px to be in title bar
|
||||
const indicatorX = node.size[0] - radius - 8;
|
||||
const indicatorY = (titleHeight / 2) - 30;
|
||||
|
||||
const dist = Math.sqrt(
|
||||
Math.pow(localPos[0] - indicatorX, 2) +
|
||||
Math.pow(localPos[1] - indicatorY, 2)
|
||||
);
|
||||
|
||||
if (dist <= radius) {
|
||||
canvas.canvas.title = node.hasWorkflow ?
|
||||
'Workflow metadata found' :
|
||||
|
||||
const infoBounds = node._workflowInfoBounds;
|
||||
if (infoBounds &&
|
||||
localPos[0] >= infoBounds.x && localPos[0] <= infoBounds.x + infoBounds.width &&
|
||||
localPos[1] >= infoBounds.y && localPos[1] <= infoBounds.y + infoBounds.height) {
|
||||
canvas.canvas.title = node.hasWorkflow ?
|
||||
'Workflow metadata found (info available)' :
|
||||
'No workflow metadata';
|
||||
canvas.canvas.style.cursor = node.hasWorkflow ? 'pointer' : '';
|
||||
node._hoverPreviewIcon = false;
|
||||
} else if (node._previewIconBounds) {
|
||||
// Check if hovering over preview icon
|
||||
@@ -1450,6 +1737,18 @@ app.registerExtension({
|
||||
const onMouseDown = node.onMouseDown;
|
||||
node.onMouseDown = function(e, localPos, canvas) {
|
||||
// Check if clicking on preview icon
|
||||
if (node._workflowInfoBounds) {
|
||||
const b = node._workflowInfoBounds;
|
||||
if (localPos[0] >= b.x && localPos[0] <= b.x + b.width &&
|
||||
localPos[1] >= b.y && localPos[1] <= b.y + b.height) {
|
||||
if (node.hasWorkflow) {
|
||||
void showExtractorWorkflowDiscoverySummary(node);
|
||||
return true;
|
||||
}
|
||||
return onMouseDown ? onMouseDown.apply(this, arguments) : undefined;
|
||||
}
|
||||
}
|
||||
|
||||
if (node._previewIconBounds && node.imgs && node.imgs.length > 0) {
|
||||
const bounds = node._previewIconBounds;
|
||||
if (localPos[0] >= bounds.x && localPos[0] <= bounds.x + bounds.width &&
|
||||
@@ -1478,7 +1777,7 @@ app.registerExtension({
|
||||
});
|
||||
|
||||
/**
|
||||
* Extract metadata and update workflow indicator (without affecting display)
|
||||
* Extract metadata and update recipe indicator (without affecting display)
|
||||
*/
|
||||
async function extractAndUpdateMetadata(node, filename) {
|
||||
if (!filename || filename === "(none)") {
|
||||
@@ -1552,7 +1851,7 @@ async function extractAndUpdateMetadata(node, filename) {
|
||||
await cacheFileMetadata(filename, metadata);
|
||||
}
|
||||
|
||||
// Update workflow status
|
||||
// Update recipe status
|
||||
if (ext === 'json') {
|
||||
node.hasWorkflow = !!(metadata && (metadata.workflow || (metadata.nodes && metadata.links)));
|
||||
} else {
|
||||
@@ -1564,7 +1863,7 @@ async function extractAndUpdateMetadata(node, filename) {
|
||||
node.setDirtyCanvas(true, true);
|
||||
app.graph.setDirtyCanvas(true, true);
|
||||
|
||||
// Extract full preview data for WorkflowBuilder's "Update Workflow" button.
|
||||
// Extract full preview data for RecipeBuilder's "Update Recipe" button.
|
||||
// Runs the Python parse+build pipeline on the cached metadata so WB can
|
||||
// pull it without executing PromptExtractor (live-menu pattern).
|
||||
if (node.hasWorkflow) {
|
||||
@@ -1667,7 +1966,7 @@ async function loadImageFile(node, filename) {
|
||||
// Cache metadata (or lack thereof) for Python backend
|
||||
await cacheFileMetadata(filename, metadata);
|
||||
|
||||
// Update workflow status flag - check for workflow or parameters
|
||||
// Update recipe status flag - check for workflow or parameters
|
||||
node.hasWorkflow = !!(metadata && (metadata.workflow || metadata.parameters));
|
||||
|
||||
// Force canvas redraw to update indicator immediately
|
||||
@@ -1731,7 +2030,7 @@ async function loadJSONFile(node, filename) {
|
||||
// Cache metadata (or lack thereof) for Python backend
|
||||
await cacheFileMetadata(filename, metadata);
|
||||
|
||||
// Update workflow status flag
|
||||
// Update recipe status flag
|
||||
// Check if metadata has workflow property OR if metadata itself is a workflow (has nodes/links)
|
||||
node.hasWorkflow = !!(metadata && (metadata.workflow || (metadata.nodes && metadata.links)));
|
||||
// Track that this JSON is now loaded
|
||||
@@ -1841,7 +2140,7 @@ async function loadVideoFrame(node, filename) {
|
||||
await cacheFileMetadata(filename, metadata);
|
||||
node._metadataCached = true;
|
||||
|
||||
// Update workflow status flag - check for workflow or parameters
|
||||
// Update recipe status flag - check for workflow or parameters
|
||||
node.hasWorkflow = !!(metadata && (metadata.workflow || metadata.parameters));
|
||||
|
||||
// Force canvas redraw to update indicator immediately
|
||||
|
||||
@@ -339,7 +339,7 @@ app.registerExtension({
|
||||
|
||||
// Load prompts asynchronously (data only, not widgets)
|
||||
loadPrompts(node).then(() => {
|
||||
filterPromptDropdown(node);
|
||||
filterPromptDropdown(node, { preserveDanglingSelection: true });
|
||||
|
||||
// Ensure height is sufficient after data is loaded
|
||||
setTimeout(() => {
|
||||
@@ -362,17 +362,24 @@ app.registerExtension({
|
||||
const result = onConfigure?.apply(this, arguments);
|
||||
|
||||
const node = this;
|
||||
// Mark workflow restore so async onNodeCreated load does not coerce selection.
|
||||
node._configuredFromWorkflow = true;
|
||||
node._restoringFromWorkflow = true;
|
||||
|
||||
// Reload prompts from server and reapply filtering
|
||||
setTimeout(() => {
|
||||
loadPrompts(node).then(() => {
|
||||
filterPromptDropdown(node);
|
||||
try {
|
||||
filterPromptDropdown(node, { preserveDanglingSelection: true });
|
||||
|
||||
// Reattach button bar if needed
|
||||
if (!node.buttonBarAttached) {
|
||||
addButtonBar(node);
|
||||
setupCategoryChangeHandler(node);
|
||||
setupUseExternalToggleHandler(node);
|
||||
// Reattach button bar if needed
|
||||
if (!node.buttonBarAttached) {
|
||||
addButtonBar(node);
|
||||
setupCategoryChangeHandler(node);
|
||||
setupUseExternalToggleHandler(node);
|
||||
}
|
||||
} finally {
|
||||
node._restoringFromWorkflow = false;
|
||||
}
|
||||
});
|
||||
}, 100);
|
||||
@@ -523,7 +530,8 @@ function hasUnsavedChanges(node) {
|
||||
return currentText !== savedText;
|
||||
}
|
||||
|
||||
function filterPromptDropdown(node) {
|
||||
function filterPromptDropdown(node, options = {}) {
|
||||
const preserveDanglingSelection = options?.preserveDanglingSelection === true;
|
||||
// Filter name dropdown to only show prompts from current category
|
||||
const categoryWidget = node.widgets.find(w => w.name === "category");
|
||||
const promptWidget = node.widgets.find(w => w.name === "name");
|
||||
@@ -532,13 +540,23 @@ function filterPromptDropdown(node) {
|
||||
const hideNSFW = app.ui.settings.getSettingValue("PromptManager.DefaultHideNSFW");
|
||||
|
||||
// Filter NSFW categories from the category dropdown
|
||||
if (hideNSFW && node.prompts) {
|
||||
if (node.prompts) {
|
||||
let categories = Object.keys(node.prompts).sort((a, b) => a.localeCompare(b));
|
||||
categories = categories.filter(cat => node.prompts[cat]?.["__meta__"]?.nsfw !== true);
|
||||
categoryWidget.options.values = categories.length > 0 ? categories : ["Default"];
|
||||
const currentCategoryValue = String(categoryWidget.value || "");
|
||||
|
||||
// If current category is now hidden, switch to first visible
|
||||
if (!categories.includes(categoryWidget.value) && categories.length > 0) {
|
||||
if (hideNSFW) {
|
||||
categories = categories.filter(cat => node.prompts[cat]?.["__meta__"]?.nsfw !== true);
|
||||
}
|
||||
|
||||
let categoryOptions = categories.length > 0 ? [...categories] : ["Default"];
|
||||
if (preserveDanglingSelection && currentCategoryValue && !categoryOptions.includes(currentCategoryValue)) {
|
||||
categoryOptions = [currentCategoryValue, ...categoryOptions];
|
||||
}
|
||||
categoryWidget.options.values = categoryOptions;
|
||||
|
||||
// If current category is now hidden, switch only when we are not preserving
|
||||
// workflow-restored dangling selections.
|
||||
if (!categoryOptions.includes(categoryWidget.value) && categories.length > 0) {
|
||||
categoryWidget.value = categories[0];
|
||||
}
|
||||
}
|
||||
@@ -554,6 +572,10 @@ function filterPromptDropdown(node) {
|
||||
promptNames = promptNames.filter(name => !node.prompts[currentCategory][name]?.nsfw);
|
||||
}
|
||||
}
|
||||
const currentPromptValue = String(promptWidget.value || "");
|
||||
if (preserveDanglingSelection && currentPromptValue && !promptNames.includes(currentPromptValue)) {
|
||||
promptNames = [currentPromptValue, ...promptNames];
|
||||
}
|
||||
if (promptNames.length === 0) {
|
||||
promptNames.push("");
|
||||
}
|
||||
@@ -766,6 +788,13 @@ function setupCategoryChangeHandler(node) {
|
||||
|
||||
// Update prompt dropdown when category changes
|
||||
categoryWidget.callback = async function(value) {
|
||||
if (node._restoringFromWorkflow) {
|
||||
if (originalCallback) {
|
||||
originalCallback.apply(this, arguments);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (originalCallback) {
|
||||
originalCallback.apply(this, arguments);
|
||||
}
|
||||
@@ -806,6 +835,13 @@ function setupCategoryChangeHandler(node) {
|
||||
|
||||
// Update text widget when prompt selection changes
|
||||
promptWidget.callback = async function(value) {
|
||||
if (node._restoringFromWorkflow) {
|
||||
if (originalPromptCallback) {
|
||||
originalPromptCallback.apply(this, arguments);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (originalPromptCallback) {
|
||||
originalPromptCallback.apply(this, arguments);
|
||||
}
|
||||
@@ -864,7 +900,7 @@ function setupCategoryChangeHandler(node) {
|
||||
|
||||
if (hasOtherCategoryPrompts) {
|
||||
setTimeout(() => {
|
||||
filterPromptDropdown(node);
|
||||
filterPromptDropdown(node, { preserveDanglingSelection: node._restoringFromWorkflow === true });
|
||||
}, 50);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/**
|
||||
* WorkflowModelLoader extension.
|
||||
* RecipeModelLoader extension.
|
||||
* Shows color-coded loaded assets (Model/VAE/CLIP) from workflow_data.
|
||||
*/
|
||||
|
||||
@@ -200,7 +200,7 @@ function _isRerouteNode(n) {
|
||||
}
|
||||
|
||||
function _resolveWorkflowUpstreamLink(node) {
|
||||
const wfInputIdx = (node.inputs || []).findIndex((i) => i?.name === "workflow_data");
|
||||
const wfInputIdx = (node.inputs || []).findIndex((i) => i?.name === "recipe_data");
|
||||
if (wfInputIdx < 0) return null;
|
||||
let linkId = node.inputs[wfInputIdx]?.link;
|
||||
if (linkId == null) return null;
|
||||
@@ -294,7 +294,7 @@ function _refreshInfoFromUpstream(node) {
|
||||
|
||||
const inferred = _inferInfoFromWorkflowData(node, wf);
|
||||
if (!inferred) return false;
|
||||
node._applyWorkflowModelLoaderInfo(inferred);
|
||||
node._applyRecipeModelLoaderInfo(inferred);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -316,22 +316,22 @@ function _defaultInfoFromWidgets(node) {
|
||||
}
|
||||
|
||||
app.registerExtension({
|
||||
name: "PromptManager.WorkflowModelLoader",
|
||||
name: "PromptManager.RecipeModelLoader",
|
||||
|
||||
async beforeRegisterNodeDef(nodeType, nodeData) {
|
||||
if (nodeData.name !== "WorkflowModelLoader") return;
|
||||
if (nodeData.name !== "RecipeModelLoader") return;
|
||||
|
||||
const origOnExecuted = nodeType.prototype.onExecuted;
|
||||
nodeType.prototype.onExecuted = function (message) {
|
||||
origOnExecuted?.apply(this, arguments);
|
||||
const info = message?.workflow_model_loader_info?.[0];
|
||||
if (!info) return;
|
||||
this._applyWorkflowModelLoaderInfo(info);
|
||||
this._applyRecipeModelLoaderInfo(info);
|
||||
};
|
||||
|
||||
nodeType.prototype._applyWorkflowModelLoaderInfo = function (info) {
|
||||
nodeType.prototype._applyRecipeModelLoaderInfo = function (info) {
|
||||
const selected = _sanitizeChoice(info.model, MODEL_CHOICES, "model_a");
|
||||
this._workflowModelLoaderInfo = {
|
||||
this._recipeModelLoaderInfo = {
|
||||
model: selected,
|
||||
model_name: info.model_name || "",
|
||||
loader_type: info.loader_type || "",
|
||||
@@ -344,7 +344,7 @@ app.registerExtension({
|
||||
uses_checkpoint_vae: !!info.uses_checkpoint_vae,
|
||||
uses_checkpoint_clip: !!info.uses_checkpoint_clip,
|
||||
};
|
||||
this._ensureWorkflowModelInfoWidget();
|
||||
this._ensureRecipeModelInfoWidget();
|
||||
this.setDirtyCanvas(true, true);
|
||||
};
|
||||
|
||||
@@ -352,10 +352,10 @@ app.registerExtension({
|
||||
nodeType.prototype.onNodeCreated = function () {
|
||||
const r = origOnNodeCreated?.apply(this, arguments);
|
||||
_restoreOrNormalizeWidgetState(this);
|
||||
if (!this._workflowModelLoaderInfo) {
|
||||
this._workflowModelLoaderInfo = _defaultInfoFromWidgets(this);
|
||||
if (!this._recipeModelLoaderInfo) {
|
||||
this._recipeModelLoaderInfo = _defaultInfoFromWidgets(this);
|
||||
}
|
||||
this._ensureWorkflowModelInfoWidget();
|
||||
this._ensureRecipeModelInfoWidget();
|
||||
_refreshInfoFromUpstream(this);
|
||||
this.setDirtyCanvas(true, true);
|
||||
return r;
|
||||
@@ -387,8 +387,9 @@ app.registerExtension({
|
||||
this.properties = this.properties || {};
|
||||
this.properties.wfml_model = ws.model;
|
||||
this.properties.wfml_weight_dtype = ws.weight_dtype;
|
||||
if (this._workflowModelLoaderInfo) {
|
||||
o._workflowModelLoaderInfo = this._workflowModelLoaderInfo;
|
||||
if (this._recipeModelLoaderInfo) {
|
||||
o._recipeModelLoaderInfo = this._recipeModelLoaderInfo;
|
||||
o._workflowModelLoaderInfo = this._recipeModelLoaderInfo;
|
||||
}
|
||||
if (o) {
|
||||
o.properties = o.properties || {};
|
||||
@@ -401,36 +402,36 @@ app.registerExtension({
|
||||
nodeType.prototype.onConfigure = function (info) {
|
||||
origOnConfigure?.apply(this, arguments);
|
||||
_restoreOrNormalizeWidgetState(this);
|
||||
const state = info?._workflowModelLoaderInfo;
|
||||
const state = info?._recipeModelLoaderInfo || info?._workflowModelLoaderInfo;
|
||||
if (state) {
|
||||
requestAnimationFrame(() => {
|
||||
this._applyWorkflowModelLoaderInfo(state);
|
||||
this._applyRecipeModelLoaderInfo(state);
|
||||
_refreshInfoFromUpstream(this);
|
||||
});
|
||||
} else {
|
||||
requestAnimationFrame(() => {
|
||||
this._workflowModelLoaderInfo = _defaultInfoFromWidgets(this);
|
||||
this._ensureWorkflowModelInfoWidget();
|
||||
this._recipeModelLoaderInfo = _defaultInfoFromWidgets(this);
|
||||
this._ensureRecipeModelInfoWidget();
|
||||
_refreshInfoFromUpstream(this);
|
||||
this.setDirtyCanvas(true, true);
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
nodeType.prototype._ensureWorkflowModelInfoWidget = function () {
|
||||
let widget = this.widgets?.find(w => w.name === "_workflow_model_loader_info");
|
||||
nodeType.prototype._ensureRecipeModelInfoWidget = function () {
|
||||
let widget = this.widgets?.find(w => w.name === "_recipe_model_loader_info");
|
||||
if (!widget) {
|
||||
widget = {
|
||||
name: "_workflow_model_loader_info",
|
||||
name: "_recipe_model_loader_info",
|
||||
type: "custom",
|
||||
y: 0,
|
||||
computeSize: () => {
|
||||
const rows = _buildRows(this._workflowModelLoaderInfo || {});
|
||||
const rows = _buildRows(this._recipeModelLoaderInfo || {});
|
||||
const h = Math.max(26, (rows.length * 22) + 6);
|
||||
return [0, h];
|
||||
},
|
||||
draw: function (ctx, node, widgetWidth, y) {
|
||||
const info = node._workflowModelLoaderInfo;
|
||||
const info = node._recipeModelLoaderInfo;
|
||||
if (!info) return;
|
||||
|
||||
const rows = _buildRows(info);
|
||||
@@ -0,0 +1,120 @@
|
||||
/**
|
||||
* Recipe Model Picker
|
||||
*
|
||||
* Keeps Type/Model/VAE/CLIP widgets in sync with Builder family filtering
|
||||
* and emits a single model_data payload for Recipe Relay.
|
||||
*/
|
||||
import { app } from "../../scripts/app.js";
|
||||
|
||||
const DEFAULT_ASSET = "(Default)";
|
||||
const DEFAULT_FAMILY = "sdxl";
|
||||
|
||||
function getWidget(node, name) {
|
||||
return node?.widgets?.find((w) => w.name === name) || null;
|
||||
}
|
||||
|
||||
function setWidgetOptions(widget, values, fallback = "") {
|
||||
if (!widget?.options) return;
|
||||
const list = Array.isArray(values) && values.length > 0 ? values : [fallback];
|
||||
widget.options.values = list;
|
||||
}
|
||||
|
||||
function ensureWidgetValue(widget, preferred, fallback = "") {
|
||||
if (!widget?.options) return;
|
||||
const values = Array.isArray(widget.options.values) ? widget.options.values : [];
|
||||
const candidate = (preferred != null && values.includes(preferred))
|
||||
? preferred
|
||||
: (values.includes(widget.value) ? widget.value : null);
|
||||
widget.value = candidate != null ? candidate : (values[0] ?? fallback);
|
||||
}
|
||||
|
||||
async function fetchJson(url) {
|
||||
const response = await fetch(url);
|
||||
return response.json();
|
||||
}
|
||||
|
||||
function familyKeyFromTypeValue(typeValue, familiesMap) {
|
||||
const raw = String(typeValue || "").trim();
|
||||
if (!raw) return DEFAULT_FAMILY;
|
||||
|
||||
if (familiesMap[raw]) return raw;
|
||||
|
||||
for (const [key, label] of Object.entries(familiesMap)) {
|
||||
if (label === raw) return key;
|
||||
}
|
||||
|
||||
return DEFAULT_FAMILY;
|
||||
}
|
||||
|
||||
async function reloadPickerLists(node) {
|
||||
const typeWidget = getWidget(node, "type");
|
||||
const modelWidget = getWidget(node, "model");
|
||||
const vaeWidget = getWidget(node, "vae");
|
||||
const clipWidget = getWidget(node, "clip");
|
||||
if (!typeWidget || !modelWidget || !vaeWidget || !clipWidget) return;
|
||||
|
||||
let families = node._recipePickerFamilies;
|
||||
if (!families) {
|
||||
try {
|
||||
const data = await fetchJson("/workflow-extractor/list-families");
|
||||
families = data?.families || {};
|
||||
} catch {
|
||||
families = {};
|
||||
}
|
||||
node._recipePickerFamilies = families;
|
||||
}
|
||||
|
||||
const familyKey = familyKeyFromTypeValue(typeWidget.value, families);
|
||||
|
||||
const [modelsData, vaesData, clipsData] = await Promise.all([
|
||||
fetchJson(`/workflow-extractor/list-models?family=${encodeURIComponent(familyKey)}`),
|
||||
fetchJson(`/workflow-extractor/list-vaes?family=${encodeURIComponent(familyKey)}`),
|
||||
fetchJson(`/workflow-extractor/list-clips?family=${encodeURIComponent(familyKey)}`),
|
||||
]).catch(() => [{ models: [] }, { vaes: [] }, { clips: [] }]);
|
||||
|
||||
const models = Array.isArray(modelsData?.models) ? modelsData.models : [];
|
||||
const vaes = Array.isArray(vaesData?.vaes) ? vaesData.vaes : [];
|
||||
const clips = Array.isArray(clipsData?.clips) ? clipsData.clips : [];
|
||||
|
||||
const prevModel = modelWidget.value;
|
||||
const prevVae = vaeWidget.value;
|
||||
const prevClip = clipWidget.value;
|
||||
|
||||
setWidgetOptions(modelWidget, models, "");
|
||||
setWidgetOptions(vaeWidget, [DEFAULT_ASSET, ...vaes], DEFAULT_ASSET);
|
||||
setWidgetOptions(clipWidget, [DEFAULT_ASSET, ...clips], DEFAULT_ASSET);
|
||||
|
||||
ensureWidgetValue(modelWidget, prevModel, "");
|
||||
ensureWidgetValue(vaeWidget, prevVae, DEFAULT_ASSET);
|
||||
ensureWidgetValue(clipWidget, prevClip, DEFAULT_ASSET);
|
||||
|
||||
if (typeof modelWidget.callback === "function") modelWidget.callback(modelWidget.value);
|
||||
if (typeof vaeWidget.callback === "function") vaeWidget.callback(vaeWidget.value);
|
||||
if (typeof clipWidget.callback === "function") clipWidget.callback(clipWidget.value);
|
||||
|
||||
app.graph.setDirtyCanvas(true, true);
|
||||
}
|
||||
|
||||
app.registerExtension({
|
||||
name: "prompt-manager.recipe-model-picker",
|
||||
async nodeCreated(node) {
|
||||
if (node.comfyClass !== "RecipeModelPicker") return;
|
||||
|
||||
const typeWidget = getWidget(node, "type");
|
||||
if (!typeWidget) return;
|
||||
|
||||
const originalTypeCallback = typeWidget.callback;
|
||||
typeWidget.callback = async function wrappedTypeCallback(value) {
|
||||
if (typeof originalTypeCallback === "function") {
|
||||
originalTypeCallback.call(this, value);
|
||||
}
|
||||
await reloadPickerLists(node);
|
||||
};
|
||||
|
||||
requestAnimationFrame(() => {
|
||||
reloadPickerLists(node).catch(() => {
|
||||
// Keep node usable even if API endpoints are temporarily unavailable.
|
||||
});
|
||||
});
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,18 @@
|
||||
/**
|
||||
* Recipe Relay — set a compact default width for newly created nodes.
|
||||
*/
|
||||
import { app } from "../../scripts/app.js";
|
||||
|
||||
const RELAY_DEFAULT_WIDTH = 220;
|
||||
|
||||
app.registerExtension({
|
||||
name: "prompt-manager.recipe-relay",
|
||||
async nodeCreated(node) {
|
||||
if (node.comfyClass !== "RecipeRelay") return;
|
||||
|
||||
requestAnimationFrame(() => {
|
||||
node.setSize([RELAY_DEFAULT_WIDTH, node.size[1]]);
|
||||
app.graph.setDirtyCanvas(true, true);
|
||||
});
|
||||
},
|
||||
});
|
||||
@@ -1,12 +1,12 @@
|
||||
/**
|
||||
* Workflow Renderer — Set initial node size to match Workflow Builder width.
|
||||
* Recipe Renderer — Set initial node size to match Recipe Builder width.
|
||||
*/
|
||||
import { app } from "../../scripts/app.js";
|
||||
|
||||
app.registerExtension({
|
||||
name: "prompt-manager.workflow-renderer",
|
||||
name: "prompt-manager.recipe-renderer",
|
||||
async nodeCreated(node) {
|
||||
if (node.comfyClass !== "WorkflowRenderer") return;
|
||||
if (node.comfyClass !== "RecipeRenderer") return;
|
||||
requestAnimationFrame(() => {
|
||||
node.setSize([320, node.size[1]]);
|
||||
app.graph.setDirtyCanvas(true, true);
|
||||
@@ -0,0 +1,275 @@
|
||||
"""Multi-slot LoRA stacker outputting four independent LORA_STACK outputs (A/B/C/D)."""
|
||||
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
|
||||
from ..py.lora_utils import resolve_lora_path
|
||||
try:
|
||||
from ..py.lora_utils import get_lora_relative_path
|
||||
except Exception:
|
||||
def get_lora_relative_path(lora_name):
|
||||
return str(lora_name or ""), False
|
||||
|
||||
|
||||
def _try_get_lm_get_lora_info():
|
||||
"""Return LM's get_lora_info function if it is already loaded in sys.modules."""
|
||||
for mod in sys.modules.values():
|
||||
fn = getattr(mod, "get_lora_info", None)
|
||||
if callable(fn):
|
||||
module_name = getattr(fn, "__module__", "") or ""
|
||||
if "lora_manager" in module_name.lower():
|
||||
return fn
|
||||
return None
|
||||
|
||||
|
||||
def _build_lora_stack(loras_json):
|
||||
"""
|
||||
Build a LORA_STACK list from the JSON state persisted by the JS widget.
|
||||
|
||||
Each entry: {"name": str, "strength": float, "clipStrength": float, "active": bool}
|
||||
Returns a list of (lora_path, model_strength, clip_strength) tuples.
|
||||
"""
|
||||
if isinstance(loras_json, str):
|
||||
raw = loras_json.strip()
|
||||
if not raw or raw == "[]":
|
||||
return []
|
||||
try:
|
||||
loras = json.loads(raw)
|
||||
except Exception:
|
||||
return []
|
||||
elif isinstance(loras_json, dict) and "__value__" in loras_json:
|
||||
loras = loras_json["__value__"]
|
||||
elif isinstance(loras_json, list):
|
||||
loras = loras_json
|
||||
else:
|
||||
return []
|
||||
|
||||
if not isinstance(loras, list):
|
||||
return []
|
||||
|
||||
get_lora_info = _try_get_lm_get_lora_info()
|
||||
stack = []
|
||||
|
||||
def _normalize_to_relative_lora(raw_value, fallback_name):
|
||||
candidate = str(raw_value or "").strip()
|
||||
if candidate:
|
||||
rel_path, available = get_lora_relative_path(candidate)
|
||||
if available and rel_path:
|
||||
return rel_path
|
||||
|
||||
candidate_base = os.path.basename(candidate.replace("\\", "/")).strip()
|
||||
if candidate_base:
|
||||
rel_path, available = get_lora_relative_path(candidate_base)
|
||||
if available and rel_path:
|
||||
return rel_path
|
||||
|
||||
fallback = str(fallback_name or "").strip()
|
||||
if fallback:
|
||||
rel_path, available = get_lora_relative_path(fallback)
|
||||
if available and rel_path:
|
||||
return rel_path
|
||||
return fallback
|
||||
|
||||
for lora in loras:
|
||||
if not isinstance(lora, dict):
|
||||
continue
|
||||
if not lora.get("active", True):
|
||||
continue
|
||||
|
||||
name = str(lora.get("name", "")).strip()
|
||||
if not name:
|
||||
continue
|
||||
|
||||
try:
|
||||
strength = float(lora.get("strength", 1.0))
|
||||
except (TypeError, ValueError):
|
||||
strength = 1.0
|
||||
|
||||
try:
|
||||
clip_strength = float(lora.get("clipStrength", strength))
|
||||
except (TypeError, ValueError):
|
||||
clip_strength = strength
|
||||
|
||||
# Prefer LM's path resolver (has full cache); fall back to folder_paths scan.
|
||||
lora_path = None
|
||||
if get_lora_info is not None:
|
||||
try:
|
||||
result = get_lora_info(name)
|
||||
if isinstance(result, tuple) and result[0]:
|
||||
lora_path = _normalize_to_relative_lora(result[0], name)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if not lora_path:
|
||||
resolved, available = resolve_lora_path(name)
|
||||
lora_path = _normalize_to_relative_lora(resolved if (available and resolved) else name, name)
|
||||
|
||||
stack.append((lora_path, strength, clip_strength))
|
||||
|
||||
return stack
|
||||
|
||||
|
||||
class MultiLoraStackerLM:
|
||||
"""Multi-slot LoRA stacker with four independent stacks (A / B / C / D)."""
|
||||
|
||||
NAME = "Multi Lora Stacker (LoraManager)"
|
||||
CATEGORY = "Prompt Manager"
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {
|
||||
# JSON arrays persisted by the JS loras widget – one per slot.
|
||||
"loras_state_a": ("STRING", {"default": "[]", "multiline": True}),
|
||||
"loras_state_b": ("STRING", {"default": "[]", "multiline": True}),
|
||||
"loras_state_c": ("STRING", {"default": "[]", "multiline": True}),
|
||||
"loras_state_d": ("STRING", {"default": "[]", "multiline": True}),
|
||||
},
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("MULTI_LORA_STACK",)
|
||||
RETURN_NAMES = ("multi_lora_stack",)
|
||||
FUNCTION = "stack_multi"
|
||||
DESCRIPTION = (
|
||||
"Multi-slot LoRA stacker with a visual 4-panel UI (A / B / C / D). "
|
||||
"Outputs one MULTI_LORA_STACK payload containing all four stacks."
|
||||
)
|
||||
|
||||
def stack_multi(
|
||||
self,
|
||||
loras_state_a="[]",
|
||||
loras_state_b="[]",
|
||||
loras_state_c="[]",
|
||||
loras_state_d="[]",
|
||||
**kwargs,
|
||||
):
|
||||
stack_a = _build_lora_stack(loras_state_a)
|
||||
stack_b = _build_lora_stack(loras_state_b)
|
||||
stack_c = _build_lora_stack(loras_state_c)
|
||||
stack_d = _build_lora_stack(loras_state_d)
|
||||
multi_lora_stack = {
|
||||
"a": stack_a,
|
||||
"b": stack_b,
|
||||
"c": stack_c,
|
||||
"d": stack_d,
|
||||
}
|
||||
return (multi_lora_stack,)
|
||||
|
||||
|
||||
def _coerce_lora_stack(raw_stack):
|
||||
"""Normalize an incoming LORA_STACK-like payload to list[(path, model, clip)]."""
|
||||
if raw_stack is None:
|
||||
return []
|
||||
|
||||
if isinstance(raw_stack, dict) and "__value__" in raw_stack:
|
||||
raw_stack = raw_stack.get("__value__")
|
||||
|
||||
if not isinstance(raw_stack, list):
|
||||
return []
|
||||
|
||||
out = []
|
||||
for item in raw_stack:
|
||||
if isinstance(item, (list, tuple)) and len(item) >= 1:
|
||||
path = str(item[0] or "").strip()
|
||||
if not path:
|
||||
continue
|
||||
try:
|
||||
model_strength = float(item[1]) if len(item) >= 2 else 1.0
|
||||
except Exception:
|
||||
model_strength = 1.0
|
||||
try:
|
||||
clip_strength = float(item[2]) if len(item) >= 3 else model_strength
|
||||
except Exception:
|
||||
clip_strength = model_strength
|
||||
out.append((path, model_strength, clip_strength))
|
||||
continue
|
||||
|
||||
if isinstance(item, dict):
|
||||
path = str(item.get("path") or item.get("name") or "").strip()
|
||||
if not path:
|
||||
continue
|
||||
try:
|
||||
model_strength = float(item.get("model_strength", item.get("strength", 1.0)))
|
||||
except Exception:
|
||||
model_strength = 1.0
|
||||
try:
|
||||
clip_strength = float(item.get("clip_strength", model_strength))
|
||||
except Exception:
|
||||
clip_strength = model_strength
|
||||
out.append((path, model_strength, clip_strength))
|
||||
|
||||
return out
|
||||
|
||||
|
||||
class MultiLoraCombine:
|
||||
"""Combine optional multi stack + optional A/B/C/D stacks into one MULTI_LORA_STACK."""
|
||||
|
||||
NAME = "Multi LoRA Combine"
|
||||
CATEGORY = "Prompt Manager"
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {},
|
||||
"optional": {
|
||||
"multi_lora_stack": ("MULTI_LORA_STACK", {
|
||||
"tooltip": "Optional existing MULTI_LORA_STACK to merge into.",
|
||||
}),
|
||||
"lora_stack_a": ("LORA_STACK", {
|
||||
"tooltip": "Optional stack to append to slot A.",
|
||||
}),
|
||||
"lora_stack_b": ("LORA_STACK", {
|
||||
"tooltip": "Optional stack to append to slot B.",
|
||||
}),
|
||||
"lora_stack_c": ("LORA_STACK", {
|
||||
"tooltip": "Optional stack to append to slot C.",
|
||||
}),
|
||||
"lora_stack_d": ("LORA_STACK", {
|
||||
"tooltip": "Optional stack to append to slot D.",
|
||||
}),
|
||||
},
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("MULTI_LORA_STACK",)
|
||||
RETURN_NAMES = ("multi_lora_stack",)
|
||||
FUNCTION = "combine_multi"
|
||||
DESCRIPTION = (
|
||||
"Combine an optional MULTI_LORA_STACK with optional LORA_STACK A/B/C/D "
|
||||
"inputs and output one MULTI_LORA_STACK payload."
|
||||
)
|
||||
|
||||
def combine_multi(
|
||||
self,
|
||||
multi_lora_stack=None,
|
||||
lora_stack_a=None,
|
||||
lora_stack_b=None,
|
||||
lora_stack_c=None,
|
||||
lora_stack_d=None,
|
||||
**kwargs,
|
||||
):
|
||||
# Start from empty payload when no multi input is connected.
|
||||
out_a = []
|
||||
out_b = []
|
||||
out_c = []
|
||||
out_d = []
|
||||
|
||||
if isinstance(multi_lora_stack, dict):
|
||||
out_a = _coerce_lora_stack(multi_lora_stack.get("a"))
|
||||
out_b = _coerce_lora_stack(multi_lora_stack.get("b"))
|
||||
out_c = _coerce_lora_stack(multi_lora_stack.get("c"))
|
||||
out_d = _coerce_lora_stack(multi_lora_stack.get("d"))
|
||||
|
||||
# Append separate stack inputs to each slot (if connected).
|
||||
out_a.extend(_coerce_lora_stack(lora_stack_a))
|
||||
out_b.extend(_coerce_lora_stack(lora_stack_b))
|
||||
out_c.extend(_coerce_lora_stack(lora_stack_c))
|
||||
out_d.extend(_coerce_lora_stack(lora_stack_d))
|
||||
|
||||
merged = {
|
||||
"a": out_a,
|
||||
"b": out_b,
|
||||
"c": out_c,
|
||||
"d": out_d,
|
||||
}
|
||||
return (merged,)
|
||||
@@ -0,0 +1,33 @@
|
||||
"""Bundled multi-slot helper node for Recipe Builder."""
|
||||
|
||||
import json
|
||||
|
||||
|
||||
class RecipeBuilderMultiPrompts:
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {},
|
||||
"optional": {
|
||||
"model_a": ("STRING", {"forceInput": True}),
|
||||
"model_b": ("STRING", {"forceInput": True}),
|
||||
"model_c": ("STRING", {"forceInput": True}),
|
||||
"model_d": ("STRING", {"forceInput": True}),
|
||||
},
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("STRING",)
|
||||
RETURN_NAMES = ("multi_prompt",)
|
||||
FUNCTION = "bundle"
|
||||
CATEGORY = "Prompt Manager"
|
||||
DESCRIPTION = "Bundle model_a/model_b/model_c/model_d prompts into a JSON string payload."
|
||||
|
||||
def bundle(self,
|
||||
model_a="", model_b="", model_c="", model_d=""):
|
||||
payload = {
|
||||
"model_a": str(model_a or ""),
|
||||
"model_b": str(model_b or ""),
|
||||
"model_c": str(model_c or ""),
|
||||
"model_d": str(model_d or ""),
|
||||
}
|
||||
return (json.dumps(payload, ensure_ascii=True),)
|
||||
@@ -10,7 +10,7 @@ import torch
|
||||
import server
|
||||
import comfy.samplers
|
||||
from ..py.workflow_families import get_family_label
|
||||
from ..py.workflow_data_utils import strip_runtime_objects, to_json_safe_workflow_data
|
||||
from ..py.workflow_data_utils import ensure_v2_recipe_data, strip_runtime_objects, to_json_safe_workflow_data
|
||||
|
||||
# Import PIL for image metadata reading
|
||||
try:
|
||||
@@ -27,7 +27,7 @@ except ImportError:
|
||||
_file_metadata_cache = {}
|
||||
# Cache for video frames extracted by JavaScript
|
||||
_video_frames_cache = {}
|
||||
# Cache for last extracted info per node (keyed by unique_id) — used by WorkflowBuilder's
|
||||
# Cache for last extracted info per node (keyed by unique_id) — used by RecipeBuilder's
|
||||
# "Update Workflow" button to pull data without re-executing PromptExtractor.
|
||||
_last_extracted_info = {}
|
||||
|
||||
@@ -416,7 +416,7 @@ async def list_input_files(request):
|
||||
return server.web.json_response({"files": [], "error": str(e)}, status=500)
|
||||
|
||||
|
||||
# API endpoint to get cached extracted info for WorkflowBuilder's "Update Workflow" button.
|
||||
# API endpoint to get cached extracted info for RecipeBuilder's "Update Workflow" button.
|
||||
# Accepts ?node_id=<id> for a specific PE node, or returns all cached entries.
|
||||
@server.PromptServer.instance.routes.get("/prompt-extractor/get-extracted-data")
|
||||
async def get_extracted_data(request):
|
||||
@@ -443,10 +443,10 @@ async def get_extracted_data(request):
|
||||
|
||||
|
||||
# API endpoint to extract metadata from a file on demand (no node execution required).
|
||||
# Used by WorkflowBuilder's "Update Workflow" button and PE JS on file selection.
|
||||
# Used by RecipeBuilder's "Update Workflow" button and PE JS on file selection.
|
||||
@server.PromptServer.instance.routes.get("/prompt-extractor/extract-preview")
|
||||
async def extract_preview(request):
|
||||
"""Extract metadata from a file and return structured info for WorkflowBuilder."""
|
||||
"""Extract metadata from a file and return structured info for RecipeBuilder."""
|
||||
try:
|
||||
filename = request.rel_url.query.get('filename', '')
|
||||
source = request.rel_url.query.get('source', 'input')
|
||||
@@ -595,6 +595,10 @@ async def extract_preview(request):
|
||||
|
||||
vae_found = True
|
||||
vae_name_str = vae.get('name', '') if isinstance(vae, dict) else (vae or '')
|
||||
if isinstance(vae_name_str, list):
|
||||
vae_name_str = next((v for v in vae_name_str if isinstance(v, str) and v.strip()), '')
|
||||
elif not isinstance(vae_name_str, str):
|
||||
vae_name_str = str(vae_name_str or '')
|
||||
if vae_name_str and not vae_name_str.startswith('('):
|
||||
vae_found = resolve_vae_name(vae_name_str) is not None
|
||||
|
||||
@@ -1630,7 +1634,7 @@ def traverse_to_find_text(node_id, input_slot, node_map, link_map, visited=None,
|
||||
# PromptExtractor / WorkflowRenderer — text outputs are computed at runtime,
|
||||
# NOT stored in widgets_values (which contain file selector, toggles, etc.).
|
||||
# Without this guard the generic fallback below picks up the image filename.
|
||||
if node_type in ['PromptExtractor', 'WorkflowRenderer', 'WorkflowGenerator']:
|
||||
if node_type in ['PromptExtractor', 'RecipeExtractor', 'WorkflowRenderer', 'RecipeRenderer']:
|
||||
return ""
|
||||
|
||||
# Generic: if node has a text/string output, check widgets
|
||||
@@ -1666,17 +1670,22 @@ def extract_power_lora_loader(node):
|
||||
# Format: {"on": true, "lora": "path/to/lora.safetensors", "strength": 1.0, "strengthTwo": null}
|
||||
# Extract ALL LoRAs, not just active ones
|
||||
if val.get('lora'):
|
||||
lora_path = val['lora']
|
||||
lora_name = os.path.splitext(os.path.basename(val['lora']))[0]
|
||||
resolved_lora, available = resolve_lora_path(lora_name)
|
||||
if not available:
|
||||
resolved_lora = lora_name
|
||||
|
||||
strength = float(val.get('strength', 1.0))
|
||||
strength_two = val.get('strengthTwo')
|
||||
clip_strength = float(strength_two) if strength_two is not None else strength
|
||||
is_active = val.get('on', True)
|
||||
|
||||
loras.append({
|
||||
'name': os.path.splitext(os.path.basename(lora_path))[0],
|
||||
'path': lora_path,
|
||||
'name': lora_name,
|
||||
'path': resolved_lora,
|
||||
'model_strength': strength,
|
||||
'clip_strength': clip_strength,
|
||||
'available': available,
|
||||
'active': is_active
|
||||
})
|
||||
|
||||
@@ -1697,6 +1706,9 @@ def extract_lora_manager_stacker(node):
|
||||
lora_name = lora.get('name', '')
|
||||
# Extract ALL LoRAs, not just active ones
|
||||
if lora_name:
|
||||
resolved_lora, available = resolve_lora_path(lora_name)
|
||||
if not available:
|
||||
resolved_lora = lora_name
|
||||
# Handle strength as string or number
|
||||
strength = lora.get('strength', 1.0)
|
||||
if isinstance(strength, str):
|
||||
@@ -1708,9 +1720,10 @@ def extract_lora_manager_stacker(node):
|
||||
|
||||
loras.append({
|
||||
'name': lora_name,
|
||||
'path': '',
|
||||
'path': resolved_lora,
|
||||
'model_strength': float(strength),
|
||||
'clip_strength': float(clip_strength),
|
||||
'available': available,
|
||||
'active': is_active
|
||||
})
|
||||
|
||||
@@ -1745,11 +1758,17 @@ def extract_wan_video_lora_select_multi(node):
|
||||
if isinstance(strength_val, (int, float)):
|
||||
strength = float(strength_val)
|
||||
|
||||
lora_name = os.path.splitext(os.path.basename(lora_name))[0]
|
||||
resolved_lora, available = resolve_lora_path(lora_name)
|
||||
if not available:
|
||||
resolved_lora = lora_name
|
||||
|
||||
loras.append({
|
||||
'name': os.path.splitext(os.path.basename(lora_name))[0],
|
||||
'path': lora_name,
|
||||
'name': lora_name,
|
||||
'path': resolved_lora,
|
||||
'model_strength': strength,
|
||||
'clip_strength': strength, # WanVideo doesn't separate model/clip strength
|
||||
'available': available,
|
||||
'active': True # All LoRAs in the list are considered active
|
||||
})
|
||||
|
||||
@@ -1785,20 +1804,32 @@ def extract_wan_video_lora_select_multi(node):
|
||||
|
||||
is_active = item.get('on', item.get('active', item.get('enabled', True)))
|
||||
|
||||
lora_name = os.path.splitext(os.path.basename(lora_name))[0]
|
||||
resolved_lora, available = resolve_lora_path(lora_name)
|
||||
if not available:
|
||||
resolved_lora = lora_name
|
||||
|
||||
loras.append({
|
||||
'name': os.path.splitext(os.path.basename(lora_name))[0],
|
||||
'path': lora_name,
|
||||
'name': lora_name,
|
||||
'path': resolved_lora,
|
||||
'model_strength': strength,
|
||||
'clip_strength': clip_strength,
|
||||
'available': available,
|
||||
'active': is_active
|
||||
})
|
||||
elif isinstance(item, str) and item and item != 'None':
|
||||
# Format 2: Simple string list of LoRA names
|
||||
lora_name = os.path.splitext(os.path.basename(item))[0]
|
||||
resolved_lora, available = resolve_lora_path(lora_name)
|
||||
if not available:
|
||||
resolved_lora = lora_name
|
||||
|
||||
loras.append({
|
||||
'name': os.path.splitext(os.path.basename(item))[0],
|
||||
'path': item,
|
||||
'name': lora_name,
|
||||
'path': resolved_lora,
|
||||
'model_strength': 1.0,
|
||||
'clip_strength': 1.0,
|
||||
'available': available,
|
||||
'active': True
|
||||
})
|
||||
# Format 3: Dictionary containing LoRA info
|
||||
@@ -1822,11 +1853,17 @@ def extract_wan_video_lora_select_multi(node):
|
||||
|
||||
is_active = val.get('on', val.get('active', val.get('enabled', True)))
|
||||
|
||||
lora_name = os.path.splitext(os.path.basename(lora_name))[0]
|
||||
resolved_lora, available = resolve_lora_path(lora_name)
|
||||
if not available:
|
||||
resolved_lora = lora_name
|
||||
|
||||
loras.append({
|
||||
'name': os.path.splitext(os.path.basename(lora_name))[0],
|
||||
'path': lora_name,
|
||||
'name': lora_name,
|
||||
'path': resolved_lora,
|
||||
'model_strength': strength,
|
||||
'clip_strength': clip_strength,
|
||||
'available': available,
|
||||
'active': is_active
|
||||
})
|
||||
|
||||
@@ -1861,11 +1898,17 @@ def extract_lora_loader_stack_rgthree(node):
|
||||
if isinstance(strength_val, (int, float)):
|
||||
strength = float(strength_val)
|
||||
|
||||
lora_name = os.path.splitext(os.path.basename(lora_name))[0]
|
||||
resolved_lora, available = resolve_lora_path(lora_name)
|
||||
if not available:
|
||||
resolved_lora = lora_name
|
||||
|
||||
loras.append({
|
||||
'name': os.path.splitext(os.path.basename(lora_name))[0],
|
||||
'path': lora_name,
|
||||
'name': lora_name,
|
||||
'path': resolved_lora,
|
||||
'model_strength': strength,
|
||||
'clip_strength': strength, # No separate model/clip strength
|
||||
'available': available,
|
||||
'active': True # All LoRAs are active (no on/off toggle)
|
||||
})
|
||||
|
||||
@@ -1899,20 +1942,26 @@ def extract_standard_lora_loader(node):
|
||||
else:
|
||||
clip_strength = model_strength
|
||||
|
||||
lora_name = os.path.splitext(os.path.basename(lora_name))[0]
|
||||
resolved_lora, available = resolve_lora_path(lora_name)
|
||||
if not available:
|
||||
resolved_lora = lora_name
|
||||
|
||||
# Standard LoRA loaders are always active (no on/off toggle)
|
||||
return [{
|
||||
'name': os.path.splitext(os.path.basename(lora_name))[0],
|
||||
'path': lora_name,
|
||||
'name': lora_name,
|
||||
'path': resolved_lora,
|
||||
'model_strength': model_strength,
|
||||
'clip_strength': clip_strength,
|
||||
'active': True
|
||||
'available': available,
|
||||
'active': True,
|
||||
}]
|
||||
|
||||
|
||||
def extract_loras_from_node(node):
|
||||
"""
|
||||
Extract LoRAs from any supported LoRA loader node type.
|
||||
Returns a list of LoRA dicts: {name, path, model_strength, clip_strength}
|
||||
Returns a list of LoRA dicts: {name, path, model_strength, clip_strength, available, active}
|
||||
"""
|
||||
node_type = node.get('type', '')
|
||||
|
||||
@@ -2320,10 +2369,18 @@ def parse_workflow_for_prompts(prompt_data, workflow_data=None):
|
||||
# Skip blacklisted LoRAs
|
||||
if is_lora_blacklisted(lora['name']):
|
||||
continue
|
||||
|
||||
lora_name = os.path.splitext(os.path.basename(lora['name']))[0]
|
||||
resolved_lora, available = resolve_lora_path(lora_name)
|
||||
if not available:
|
||||
resolved_lora = lora_name
|
||||
|
||||
result['loras_a'].append({
|
||||
'name': lora['name'],
|
||||
'name': lora_name,
|
||||
'path': resolved_lora,
|
||||
'model_strength': lora['model_strength'],
|
||||
'clip_strength': lora['clip_strength'],
|
||||
'available': available,
|
||||
'active': True
|
||||
})
|
||||
|
||||
@@ -2417,6 +2474,7 @@ def parse_workflow_for_prompts(prompt_data, workflow_data=None):
|
||||
'steps_a': ui_state.get('steps_a', 20),
|
||||
'steps_b': ui_state.get('steps_b'),
|
||||
'cfg': ui_state.get('cfg', 5.0),
|
||||
'denoise': 1.0,
|
||||
'seed_a': ui_state.get('seed_a', 0),
|
||||
'seed_b': ui_state.get('seed_b'),
|
||||
'sampler_name': ui_state.get('sampler_name', 'euler'),
|
||||
@@ -2531,12 +2589,12 @@ def parse_workflow_for_prompts(prompt_data, workflow_data=None):
|
||||
break
|
||||
|
||||
# PromptExtractor / WorkflowBuilder / WorkflowRenderer nodes — collect
|
||||
# embedded extracted_data. Also accept legacy WorkflowGenerator.
|
||||
elif node_type in ('PromptExtractor', 'WorkflowBuilder', 'WorkflowRenderer', 'WorkflowGenerator'):
|
||||
# embedded extracted_data. Also accept legacy RecipeRenderer.
|
||||
elif node_type in ('PromptExtractor', 'RecipeExtractor', 'WorkflowBuilder', 'WorkflowRenderer', 'RecipeBuilder', 'RecipeRenderer'):
|
||||
ext_data = None
|
||||
# Builder videos now persist authoritative UI state in properties.
|
||||
# Prefer that over stale extracted_data snapshots when available.
|
||||
if node_type == 'WorkflowBuilder':
|
||||
if node_type in ('WorkflowBuilder', 'RecipeBuilder'):
|
||||
ext_data = _build_embedded_from_builder_ui(node)
|
||||
if not ext_data:
|
||||
ext_data = node.get('extracted_data')
|
||||
@@ -2559,28 +2617,28 @@ def parse_workflow_for_prompts(prompt_data, workflow_data=None):
|
||||
break
|
||||
|
||||
# ========================================
|
||||
# RESOLVE EMBEDDED DATA (PromptExtractor vs WorkflowRenderer)
|
||||
# RESOLVE EMBEDDED DATA (PromptExtractor vs RecipeRenderer)
|
||||
# ========================================
|
||||
# Priority when multiple embedded sources are present:
|
||||
# 1. WorkflowRenderer / WorkflowGenerator (actual render source)
|
||||
# 2. WorkflowBuilder
|
||||
# 1. RecipeRenderer / WorkflowRenderer (actual render source)
|
||||
# 2. RecipeBuilder
|
||||
# 3. PromptExtractor
|
||||
if _embedded_candidates:
|
||||
has_render = any(nt in ('WorkflowRenderer', 'WorkflowGenerator') for nt, *_ in _embedded_candidates)
|
||||
has_builder = any(nt == 'WorkflowBuilder' for nt, *_ in _embedded_candidates)
|
||||
has_render = any(nt in ('WorkflowRenderer', 'RecipeRenderer') for nt, *_ in _embedded_candidates)
|
||||
has_builder = any(nt in ('WorkflowBuilder', 'RecipeBuilder') for nt, *_ in _embedded_candidates)
|
||||
builder_prompt_candidate = None
|
||||
|
||||
if has_render:
|
||||
chosen = [
|
||||
c for c in _embedded_candidates
|
||||
if c[0] in ('WorkflowRenderer', 'WorkflowGenerator')
|
||||
if c[0] in ('WorkflowRenderer', 'RecipeRenderer')
|
||||
]
|
||||
if len(_embedded_candidates) > len(chosen):
|
||||
print("[PromptExtractor] Multiple embedded sources found — preferring WorkflowRenderer/WorkflowGenerator")
|
||||
print("[PromptExtractor] Multiple embedded sources found — preferring RecipeRenderer")
|
||||
elif has_builder:
|
||||
chosen = [c for c in _embedded_candidates if c[0] == 'WorkflowBuilder']
|
||||
chosen = [c for c in _embedded_candidates if c[0] in ('WorkflowBuilder', 'RecipeBuilder')]
|
||||
if len(_embedded_candidates) > len(chosen):
|
||||
print("[PromptExtractor] Both PromptExtractor and WorkflowBuilder found — preferring WorkflowBuilder embedded data")
|
||||
print("[PromptExtractor] Both PromptExtractor and Builder found — preferring Builder embedded data")
|
||||
|
||||
# When multiple builder nodes are present, select a single prompt source.
|
||||
# Prefer the first builder (stable workflow order), then first non-empty prompt.
|
||||
@@ -2598,9 +2656,9 @@ def parse_workflow_for_prompts(prompt_data, workflow_data=None):
|
||||
# Builder-only workflows can contain several builder nodes from
|
||||
# multi-branch generation graphs; use one prompt source instead of
|
||||
# concatenating all builder prompts.
|
||||
if node_type != 'WorkflowBuilder' or not has_render:
|
||||
if node_type not in ['WorkflowBuilder', 'RecipeBuilder'] or not has_render:
|
||||
use_for_prompt = True
|
||||
if node_type == 'WorkflowBuilder' and builder_prompt_candidate:
|
||||
if node_type in ['WorkflowBuilder', 'RecipeBuilder'] and builder_prompt_candidate:
|
||||
use_for_prompt = (node_id == builder_prompt_candidate[1])
|
||||
|
||||
if use_for_prompt:
|
||||
@@ -2812,11 +2870,17 @@ def parse_workflow_for_prompts(prompt_data, workflow_data=None):
|
||||
continue
|
||||
strength = float(lora_item.get('strength', 1.0))
|
||||
clip_strength = float(lora_item.get('clip_strength', strength))
|
||||
|
||||
resolved_lora, available = resolve_lora_path(lora_name)
|
||||
if not available:
|
||||
resolved_lora = lora_name
|
||||
|
||||
chain_loras_list.append({
|
||||
'name': lora_name,
|
||||
'path': lora_name,
|
||||
'path': resolved_lora,
|
||||
'model_strength': strength,
|
||||
'clip_strength': clip_strength,
|
||||
'available': available,
|
||||
'active': True
|
||||
})
|
||||
|
||||
@@ -3071,11 +3135,15 @@ def parse_workflow_for_prompts(prompt_data, workflow_data=None):
|
||||
target_seen.add(lora_name)
|
||||
strength = float(lora_item.get('strength', 1.0))
|
||||
clip_strength = float(lora_item.get('clip_strength', strength))
|
||||
resolved_lora, available = resolve_lora_path(lora_name)
|
||||
if not available:
|
||||
resolved_lora = lora_name
|
||||
target_stack.append({
|
||||
'name': lora_name,
|
||||
'path': lora_name,
|
||||
'path': resolved_lora,
|
||||
'model_strength': strength,
|
||||
'clip_strength': clip_strength
|
||||
'clip_strength': clip_strength,
|
||||
'available': available,
|
||||
})
|
||||
|
||||
# Standard LoRA loaders (API format)
|
||||
@@ -3105,11 +3173,17 @@ def parse_workflow_for_prompts(prompt_data, workflow_data=None):
|
||||
lora_names_seen_a.add(lora_name)
|
||||
model_strength = float(inputs.get('strength_model', inputs.get('strength', 1.0)))
|
||||
clip_strength = float(inputs.get('strength_clip', model_strength))
|
||||
|
||||
resolved_lora, available = resolve_lora_path(lora_basename)
|
||||
if not available:
|
||||
resolved_lora = lora_basename
|
||||
|
||||
loras_a.append({
|
||||
'name': lora_basename,
|
||||
'path': lora_name,
|
||||
'path': resolved_lora,
|
||||
'model_strength': model_strength,
|
||||
'clip_strength': clip_strength
|
||||
'clip_strength': clip_strength,
|
||||
'available': found
|
||||
})
|
||||
|
||||
# Also check for LoRA syntax in prompts: <lora:name:strength>
|
||||
@@ -3126,11 +3200,17 @@ def parse_workflow_for_prompts(prompt_data, workflow_data=None):
|
||||
lora_names_seen_a.add(lora_name)
|
||||
model_strength = float(match.group(2)) if match.group(2) else 1.0
|
||||
clip_strength = float(match.group(3)) if match.group(3) else model_strength
|
||||
|
||||
resolved_lora, available = resolve_lora_path(lora_name)
|
||||
if not available:
|
||||
resolved_lora = lora_name
|
||||
|
||||
loras_a.append({
|
||||
'name': lora_name,
|
||||
'path': '',
|
||||
'path': resolved_lora,
|
||||
'model_strength': model_strength,
|
||||
'clip_strength': clip_strength
|
||||
'clip_strength': clip_strength,
|
||||
'available': found
|
||||
})
|
||||
|
||||
# Embedded prompt text is fallback-only. Prefer prompts extracted from
|
||||
@@ -3555,8 +3635,8 @@ class PromptExtractor:
|
||||
|
||||
CATEGORY = "Prompt Manager"
|
||||
DESCRIPTION = "Extract prompts, LoRA configurations, and model paths from images, videos, and workflow files."
|
||||
RETURN_TYPES = ("STRING", "STRING", "LORA_STACK", "LORA_STACK", "WORKFLOW_DATA", "IMAGE")
|
||||
RETURN_NAMES = ("positive_prompt", "negative_prompt", "lora_stack_a", "lora_stack_b", "workflow_data", "image")
|
||||
RETURN_TYPES = ("STRING", "STRING", "LORA_STACK", "LORA_STACK", "IMAGE")
|
||||
RETURN_NAMES = ("positive_prompt", "negative_prompt", "lora_stack_a", "lora_stack_b", "image")
|
||||
FUNCTION = "extract"
|
||||
OUTPUT_NODE = False
|
||||
|
||||
@@ -3580,6 +3660,10 @@ class PromptExtractor:
|
||||
workflow_data = ""
|
||||
model_a = ""
|
||||
model_b = ""
|
||||
authoritative_builder_v2 = False
|
||||
|
||||
class _BuilderV2Done(Exception):
|
||||
pass
|
||||
|
||||
# Handle None or missing image parameter
|
||||
if image is None:
|
||||
@@ -3686,7 +3770,7 @@ class PromptExtractor:
|
||||
model_b = os.path.basename(raw_models_b[0].replace('\\', '/'))
|
||||
print(f"[PromptExtractor] Model B: {model_b}")
|
||||
|
||||
# Build workflow_data in the same structured format as WorkflowBuilder
|
||||
# Build workflow_data in the same structured format as RecipeBuilder
|
||||
# so both nodes output identical workflow_data that can feed PromptManagerAdvanced.
|
||||
if prompt_data or workflow_data:
|
||||
try:
|
||||
@@ -3696,15 +3780,76 @@ class PromptExtractor:
|
||||
extract_vae_info,
|
||||
extract_clip_info,
|
||||
extract_resolution,
|
||||
extract_recipe_builder_models_from_workflow,
|
||||
_get_authoritative_builder_v2_payload,
|
||||
build_simplified_workflow_data,
|
||||
get_model_family,
|
||||
get_family_label,
|
||||
)
|
||||
# Use raw workflow_data dict (before we overwrite the var below)
|
||||
_raw_wf = workflow_data # still a dict here
|
||||
|
||||
_builder_v2_payload = _get_authoritative_builder_v2_payload(_raw_wf)
|
||||
if isinstance(_builder_v2_payload, dict):
|
||||
authoritative_builder_v2 = True
|
||||
workflow_data = ensure_v2_recipe_data(_builder_v2_payload, source="PromptExtractor")
|
||||
|
||||
_models = workflow_data.get('models', {}) if isinstance(workflow_data.get('models'), dict) else {}
|
||||
_model_a_block = _models.get('model_a') if isinstance(_models.get('model_a'), dict) else {}
|
||||
_model_b_block = _models.get('model_b') if isinstance(_models.get('model_b'), dict) else {}
|
||||
|
||||
positive_prompt = str(_model_a_block.get('positive_prompt', positive_prompt) or '')
|
||||
negative_prompt = str(_model_a_block.get('negative_prompt', negative_prompt) or '')
|
||||
model_a = str(_model_a_block.get('model', model_a) or '')
|
||||
model_b = str(_model_b_block.get('model', model_b) or '')
|
||||
loras_a = _model_a_block.get('loras', loras_a) if isinstance(_model_a_block.get('loras'), list) else loras_a
|
||||
loras_b = _model_b_block.get('loras', loras_b) if isinstance(_model_b_block.get('loras'), list) else loras_b
|
||||
|
||||
if unique_id is not None:
|
||||
from ..py.lora_utils import resolve_lora_path as _resolve_lora
|
||||
_lora_avail = {}
|
||||
for _l in loras_a + loras_b:
|
||||
_ln = _l.get('name', '') if isinstance(_l, dict) else ''
|
||||
if _ln:
|
||||
_, _found = _resolve_lora(_ln)
|
||||
_lora_avail[_ln] = _found
|
||||
|
||||
_m_a_sampler = _model_a_block.get('sampler') if isinstance(_model_a_block.get('sampler'), dict) else {}
|
||||
_m_a_res = _model_a_block.get('resolution') if isinstance(_model_a_block.get('resolution'), dict) else {}
|
||||
_m_a_clip = _model_a_block.get('clip', [])
|
||||
if not isinstance(_m_a_clip, list):
|
||||
_m_a_clip = [_m_a_clip] if _m_a_clip else []
|
||||
|
||||
_last_extracted_info[str(unique_id)] = {
|
||||
'_source_file': file_path,
|
||||
'_source_folder': source_folder,
|
||||
'positive_prompt': positive_prompt,
|
||||
'negative_prompt': negative_prompt,
|
||||
'model_a': model_a,
|
||||
'model_b': model_b,
|
||||
'model_a_found': True,
|
||||
'model_b_found': True,
|
||||
'loras_a': loras_a,
|
||||
'loras_b': loras_b,
|
||||
'vae': {'name': str(_model_a_block.get('vae', '') or ''), 'source': 'RecipeBuilder'},
|
||||
'vae_found': True,
|
||||
'clip': {'names': _m_a_clip, 'type': str(_model_a_block.get('clip_type', '') or ''), 'source': 'RecipeBuilder'},
|
||||
'sampler': _m_a_sampler,
|
||||
'resolution': _m_a_res,
|
||||
'is_video': ext in ['.mp4', '.webm', '.mov', '.avi'],
|
||||
'model_family': str(_model_a_block.get('family', '') or ''),
|
||||
'model_family_label': get_family_label(str(_model_a_block.get('family', '') or '')),
|
||||
'lora_availability': _lora_avail,
|
||||
}
|
||||
print(f"[PromptExtractor] Cached authoritative Builder v2 info for node {unique_id}")
|
||||
|
||||
print(f"[PromptExtractor] Using authoritative Builder v2 metadata ({len(_models)} model slots)")
|
||||
raise _BuilderV2Done()
|
||||
|
||||
_is_a1111 = isinstance(prompt_data, dict) and 'prompt' in prompt_data and 'loras' in prompt_data
|
||||
|
||||
_sampler = extract_sampler_params(prompt_data, _raw_wf)
|
||||
_sampler['denoise'] = 1.0
|
||||
_vae = extract_vae_info(prompt_data, _raw_wf)
|
||||
_clip = extract_clip_info(prompt_data, _raw_wf)
|
||||
_res = extract_resolution(prompt_data, _raw_wf)
|
||||
@@ -3799,12 +3944,36 @@ class PromptExtractor:
|
||||
'model_family': _family,
|
||||
'model_family_label': get_family_label(_family),
|
||||
}
|
||||
|
||||
# For RecipeBuilder-authored workflows, map each builder by
|
||||
# its send slot (model_a..model_d). If multiple builders target
|
||||
# the same slot, the last builder wins.
|
||||
_builder_models = extract_recipe_builder_models_from_workflow(_raw_wf)
|
||||
if _builder_models:
|
||||
_extracted_for_wf['models'] = _builder_models
|
||||
for _slot in ('model_a', 'model_b', 'model_c', 'model_d'):
|
||||
_block = _builder_models.get(_slot)
|
||||
if isinstance(_block, dict):
|
||||
_extracted_for_wf[_slot] = str(_block.get('model', '') or '')
|
||||
_model_a_block = _builder_models.get('model_a') if isinstance(_builder_models.get('model_a'), dict) else None
|
||||
if _model_a_block:
|
||||
_extracted_for_wf['positive_prompt'] = str(_model_a_block.get('positive_prompt', positive_prompt) or '')
|
||||
_extracted_for_wf['negative_prompt'] = str(_model_a_block.get('negative_prompt', negative_prompt) or '')
|
||||
_extracted_for_wf['loras_a'] = _model_a_block.get('loras', loras_a) if isinstance(_model_a_block.get('loras'), list) else loras_a
|
||||
if isinstance(_model_a_block.get('sampler'), dict):
|
||||
_extracted_for_wf['sampler'] = _model_a_block['sampler']
|
||||
if isinstance(_model_a_block.get('resolution'), dict):
|
||||
_extracted_for_wf['resolution'] = _model_a_block['resolution']
|
||||
_model_b_block = _builder_models.get('model_b') if isinstance(_builder_models.get('model_b'), dict) else None
|
||||
if _model_b_block and isinstance(_model_b_block.get('loras'), list):
|
||||
_extracted_for_wf['loras_b'] = _model_b_block.get('loras', loras_b)
|
||||
|
||||
_simplified = build_simplified_workflow_data(
|
||||
_extracted_for_wf,
|
||||
overrides={'_source': 'PromptExtractor'},
|
||||
sampler_params=_sampler,
|
||||
)
|
||||
# Add model / VAE availability so WorkflowBuilder can show red
|
||||
# Add model / VAE availability so RecipeBuilder can show red
|
||||
from ..py.workflow_extraction_utils import resolve_model_name, resolve_vae_name
|
||||
if model_a:
|
||||
_res_a, _ = resolve_model_name(model_a)
|
||||
@@ -3813,12 +3982,16 @@ class PromptExtractor:
|
||||
_res_b, _ = resolve_model_name(model_b)
|
||||
_simplified['model_b_found'] = _res_b is not None
|
||||
_vae_name = _vae.get('name', '') if isinstance(_vae, dict) else (_vae or '')
|
||||
if isinstance(_vae_name, list):
|
||||
_vae_name = next((v for v in _vae_name if isinstance(v, str) and v.strip()), '')
|
||||
elif not isinstance(_vae_name, str):
|
||||
_vae_name = str(_vae_name or '')
|
||||
if _vae_name and not _vae_name.startswith('('):
|
||||
_simplified['vae_found'] = resolve_vae_name(_vae_name) is not None
|
||||
workflow_data = _simplified
|
||||
print(f"[PromptExtractor] Output structured workflow_data (dict, {len(workflow_data)} keys)")
|
||||
|
||||
# Cache extracted info for WorkflowBuilder's "Update Workflow" button.
|
||||
# Cache extracted info for RecipeBuilder's "Update Workflow" button.
|
||||
# Shape matches what WB's updateUI() expects (ui_info['extracted']).
|
||||
if unique_id is not None:
|
||||
from ..py.lora_utils import resolve_lora_path as _resolve_lora
|
||||
@@ -3851,13 +4024,93 @@ class PromptExtractor:
|
||||
}
|
||||
print(f"[PromptExtractor] Cached extracted info for node {unique_id}")
|
||||
|
||||
except _BuilderV2Done:
|
||||
pass
|
||||
except Exception as e:
|
||||
print(f"[PromptExtractor] Error building structured workflow_data: {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
workflow_data = {}
|
||||
sampler_fallback = {
|
||||
"steps_a": 20,
|
||||
"cfg": 5.0,
|
||||
"denoise": 1.0,
|
||||
"seed_a": 0,
|
||||
"sampler_name": "euler",
|
||||
"scheduler": "simple",
|
||||
}
|
||||
try:
|
||||
if isinstance(_sampler, dict):
|
||||
sampler_fallback.update(_sampler)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
resolution_fallback = {
|
||||
"width": 768,
|
||||
"height": 1280,
|
||||
"batch_size": 1,
|
||||
"length": None,
|
||||
}
|
||||
try:
|
||||
if isinstance(_res, dict):
|
||||
resolution_fallback.update(_res)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
vae_name = ""
|
||||
clip_names = []
|
||||
clip_type = ""
|
||||
family_fallback = "sdxl"
|
||||
try:
|
||||
if isinstance(_vae, dict):
|
||||
vae_name = str(_vae.get("name", "") or "")
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
if isinstance(_clip, dict):
|
||||
raw_clip_names = _clip.get("names", [])
|
||||
if isinstance(raw_clip_names, list):
|
||||
clip_names = raw_clip_names
|
||||
elif isinstance(raw_clip_names, str) and raw_clip_names:
|
||||
clip_names = [raw_clip_names]
|
||||
clip_type = str(_clip.get("type", "") or "")
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
if isinstance(_family, str) and _family:
|
||||
family_fallback = _family
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
model_a_block = {
|
||||
"family": family_fallback,
|
||||
"model": model_a,
|
||||
"positive_prompt": positive_prompt,
|
||||
"negative_prompt": negative_prompt,
|
||||
"loras": loras_a if isinstance(loras_a, list) else [],
|
||||
"vae": vae_name,
|
||||
"clip": clip_names,
|
||||
"clip_type": clip_type,
|
||||
"sampler": sampler_fallback if isinstance(sampler_fallback, dict) else {},
|
||||
"resolution": resolution_fallback if isinstance(resolution_fallback, dict) else {},
|
||||
}
|
||||
workflow_data = {
|
||||
"_source": "PromptExtractor",
|
||||
"version": 2,
|
||||
"models": {
|
||||
"model_a": model_a_block,
|
||||
},
|
||||
}
|
||||
if model_b or (isinstance(loras_b, list) and loras_b):
|
||||
workflow_data["models"]["model_b"] = {
|
||||
"family": family_fallback,
|
||||
"model": model_b,
|
||||
"loras": loras_b if isinstance(loras_b, list) else [],
|
||||
"sampler": sampler_fallback if isinstance(sampler_fallback, dict) else {},
|
||||
"resolution": resolution_fallback if isinstance(resolution_fallback, dict) else {},
|
||||
}
|
||||
workflow_data = ensure_v2_recipe_data(workflow_data, source="PromptExtractor")
|
||||
else:
|
||||
workflow_data = {}
|
||||
workflow_data = ensure_v2_recipe_data({}, source="PromptExtractor")
|
||||
|
||||
# Process loras only if use_lora_input_only is disabled (extract mode)
|
||||
if not use_lora_input_only:
|
||||
@@ -3949,8 +4202,8 @@ class PromptExtractor:
|
||||
# Connected lora_stack inputs may have added LoRAs that weren't in
|
||||
# the extracted metadata. Push the merged set into workflow_data
|
||||
# (the _simplified dict) and the _last_extracted_info cache so
|
||||
# WorkflowBuilder's "Update Workflow" button sees the full set.
|
||||
if isinstance(workflow_data, dict) and (final_lora_stack_a or final_lora_stack_b):
|
||||
# RecipeBuilder's "Update Workflow" button sees the full set.
|
||||
if isinstance(workflow_data, dict) and not authoritative_builder_v2 and (final_lora_stack_a or final_lora_stack_b):
|
||||
def _tuples_to_lora_dicts(stack_tuples):
|
||||
"""Convert (path, model_str, clip_str) tuples to LoRA dicts."""
|
||||
result = []
|
||||
@@ -3966,8 +4219,17 @@ class PromptExtractor:
|
||||
|
||||
merged_a = _tuples_to_lora_dicts(final_lora_stack_a)
|
||||
merged_b = _tuples_to_lora_dicts(final_lora_stack_b)
|
||||
workflow_data['loras_a'] = merged_a
|
||||
workflow_data['loras_b'] = merged_b
|
||||
models = workflow_data.get('models', {}) if isinstance(workflow_data.get('models'), dict) else {}
|
||||
model_a_block = models.get('model_a') if isinstance(models.get('model_a'), dict) else {}
|
||||
model_a_block['loras'] = merged_a
|
||||
models['model_a'] = model_a_block
|
||||
|
||||
if merged_b or isinstance(models.get('model_b'), dict):
|
||||
model_b_block = models.get('model_b') if isinstance(models.get('model_b'), dict) else {}
|
||||
model_b_block['loras'] = merged_b
|
||||
models['model_b'] = model_b_block
|
||||
|
||||
workflow_data['models'] = models
|
||||
|
||||
# Update the _last_extracted_info cache too
|
||||
uid_str = str(unique_id) if unique_id is not None else None
|
||||
@@ -3983,6 +4245,9 @@ class PromptExtractor:
|
||||
avail[_ln] = _found
|
||||
_last_extracted_info[uid_str]['lora_availability'] = avail
|
||||
|
||||
if isinstance(workflow_data, dict):
|
||||
workflow_data = ensure_v2_recipe_data(workflow_data, source="PromptExtractor")
|
||||
|
||||
# Provide placeholder image tensor if none loaded (e.g., for JSON files)
|
||||
if image_tensor is None:
|
||||
image_tensor = get_placeholder_image_tensor()
|
||||
@@ -4016,14 +4281,18 @@ class PromptExtractor:
|
||||
enriched = []
|
||||
for lora_path, strength, clip_strength in stack_tuples:
|
||||
lora_name = os.path.splitext(os.path.basename(lora_path))[0]
|
||||
_, found = resolve_lora_path(lora_name)
|
||||
|
||||
resolved_lora, available = resolve_lora_path(lora_name)
|
||||
if not available:
|
||||
resolved_lora = lora_name
|
||||
|
||||
enriched.append({
|
||||
'name': lora_name,
|
||||
'path': lora_path,
|
||||
'path': resolved_lora,
|
||||
'strength': strength,
|
||||
'clip_strength': clip_strength,
|
||||
'available': available,
|
||||
'active': True,
|
||||
'available': found,
|
||||
})
|
||||
return enriched
|
||||
|
||||
@@ -4044,7 +4313,8 @@ class PromptExtractor:
|
||||
extracted_data.setdefault('positive_prompt', positive_prompt.strip())
|
||||
extracted_data.setdefault('negative_prompt', negative_prompt.strip())
|
||||
extracted_data.setdefault('model_a', model_a.strip())
|
||||
extracted_data.setdefault('model_b', model_b.strip())
|
||||
if model_b and model_b.strip():
|
||||
extracted_data.setdefault('model_b', model_b.strip())
|
||||
|
||||
wf_nodes = workflow.get('nodes', []) if isinstance(workflow, dict) else []
|
||||
for wf_node in wf_nodes:
|
||||
@@ -4112,7 +4382,7 @@ class PromptExtractor:
|
||||
|
||||
class WorkflowExtractor:
|
||||
"""
|
||||
Simplified extractor for WorkflowBuilder — outputs only workflow_data + image.
|
||||
Simplified extractor for RecipeBuilder — outputs only workflow_data + image.
|
||||
No LoRA inputs/outputs, no prompt outputs. Same extraction logic as PromptExtractor.
|
||||
Uses composition (not inheritance) to avoid ComfyUI node-type confusion on reload.
|
||||
"""
|
||||
@@ -4156,9 +4426,9 @@ class WorkflowExtractor:
|
||||
}
|
||||
|
||||
CATEGORY = "Prompt Manager"
|
||||
DESCRIPTION = "Extract workflow data from images, videos, and workflow files. Simplified version for WorkflowBuilder."
|
||||
RETURN_TYPES = ("WORKFLOW_DATA", "IMAGE")
|
||||
RETURN_NAMES = ("workflow_data", "image")
|
||||
DESCRIPTION = "Extract workflow data from images, videos, and workflow files. Simplified version for RecipeBuilder."
|
||||
RETURN_TYPES = ("RECIPE_DATA", "IMAGE")
|
||||
RETURN_NAMES = ("recipe_data", "image")
|
||||
FUNCTION = "extract_workflow"
|
||||
OUTPUT_NODE = False
|
||||
|
||||
@@ -4179,7 +4449,7 @@ class WorkflowExtractor:
|
||||
workflow_data = full[4]
|
||||
image_tensor = full[5]
|
||||
return {
|
||||
# Keep WorkflowExtractor silent in UI previews for the same reason
|
||||
# Keep RecipeExtractor silent in UI previews for the same reason
|
||||
# as PromptExtractor: avoid replacing final generation thumbnails.
|
||||
"ui": {},
|
||||
"result": (workflow_data, image_tensor),
|
||||
|
||||
@@ -3,6 +3,7 @@ import subprocess
|
||||
import time
|
||||
import os
|
||||
import sys
|
||||
import gc
|
||||
import atexit
|
||||
import signal
|
||||
import psutil
|
||||
@@ -10,6 +11,7 @@ import json
|
||||
import base64
|
||||
import ctypes
|
||||
import numpy as np
|
||||
import torch
|
||||
from colorama import Fore, Style
|
||||
from PIL import Image
|
||||
from io import BytesIO
|
||||
@@ -335,7 +337,7 @@ class PromptGenerator:
|
||||
"tooltip": "Enable thinking/reasoning mode for compatible models (DeepSeek format)"
|
||||
}),
|
||||
"stop_server_after": ("BOOLEAN", {
|
||||
"default": False,
|
||||
"default": True,
|
||||
"tooltip": "Stop the llama.cpp server after each prompt (for resource saving, but slower)."
|
||||
}),
|
||||
"options": ("OPTIONS", {
|
||||
@@ -364,12 +366,12 @@ class PromptGenerator:
|
||||
return False
|
||||
|
||||
@staticmethod
|
||||
def start_server(model_name, context_size=4096, use_vision_model=False):
|
||||
def start_server(model_name, context_size=2048, use_vision_model=False):
|
||||
"""Start llama.cpp server with specified model
|
||||
|
||||
Args:
|
||||
model_name: Name of the model to use
|
||||
context_size: Context size (default 4096)
|
||||
context_size: Context size (default 2048)
|
||||
use_vision_model: Whether to use the vision model's mmproj
|
||||
|
||||
Returns:
|
||||
@@ -437,7 +439,7 @@ class PromptGenerator:
|
||||
print_pg(error_msg, RED)
|
||||
|
||||
# Build command arguments
|
||||
cmd_args = [server_cmd, "-m", model_path, "--port", str(PromptGenerator.SERVER_PORT), "--no-warmup", "-c", str(context_size)]
|
||||
cmd_args = [server_cmd, "-m", model_path, "--port", str(PromptGenerator.SERVER_PORT), "--no-warmup", "-ngl", "100", "-c", str(context_size)]
|
||||
|
||||
# Add vision flags for models with mmproj
|
||||
if use_vision_model:
|
||||
@@ -634,19 +636,19 @@ class PromptGenerator:
|
||||
data = response.json()
|
||||
params = data.get("default_generation_settings", {}).get("params", {})
|
||||
_model_default_params = {
|
||||
"temperature": round(params.get("temperature", 0.8), 4),
|
||||
"top_k": int(params.get("top_k", 40)),
|
||||
"top_p": round(params.get("top_p", 0.95), 4),
|
||||
"min_p": round(params.get("min_p", 0.05), 4),
|
||||
"temperature": round(params.get("temperature", 0.7), 4),
|
||||
"top_k": int(params.get("top_k", 20)),
|
||||
"top_p": round(params.get("top_p", 0.9), 4),
|
||||
"min_p": round(params.get("min_p", 0.0), 4),
|
||||
"repeat_penalty": round(params.get("repeat_penalty", 1.0), 4),
|
||||
}
|
||||
return _model_default_params
|
||||
except Exception:
|
||||
_model_default_params = {
|
||||
"temperature": 0.8,
|
||||
"top_k": 40,
|
||||
"top_p": 0.95,
|
||||
"min_p": 0.05,
|
||||
"temperature": 0.7,
|
||||
"top_k": 20,
|
||||
"top_p": 0.9,
|
||||
"min_p": 0.0,
|
||||
"repeat_penalty": 1.0
|
||||
}
|
||||
return _model_default_params
|
||||
@@ -660,16 +662,56 @@ class PromptGenerator:
|
||||
# Always attempt to fetch defaults; fetch_model_defaults() will fall back to built-in defaults on error, ensuring a dict is
|
||||
return PromptGenerator.fetch_model_defaults()
|
||||
|
||||
def convert_prompt(self, seed: int, mode="Enhance Prompt (Image)", prompt="", image=None, format_as_json=False, enable_thinking=True, stop_server_after=False, options=None, **kwargs) -> str:
|
||||
@staticmethod
|
||||
def _comfy_cache_cleanup_compat(force=True):
|
||||
"""Call Comfy cache cleanup with compatibility across versions."""
|
||||
if hasattr(comfy.model_management, "soft_empty_cache"):
|
||||
try:
|
||||
# Newer Comfy builds may accept a force flag.
|
||||
comfy.model_management.soft_empty_cache(force)
|
||||
except TypeError:
|
||||
# Older builds expose no-arg soft_empty_cache.
|
||||
comfy.model_management.soft_empty_cache()
|
||||
elif hasattr(comfy.model_management, "cleanup_models"):
|
||||
comfy.model_management.cleanup_models()
|
||||
|
||||
@staticmethod
|
||||
def flush_vram(unload_models=True):
|
||||
"""Aggressive VRAM cleanup for low-headroom systems."""
|
||||
try:
|
||||
if unload_models and hasattr(comfy.model_management, "unload_all_models"):
|
||||
comfy.model_management.unload_all_models()
|
||||
|
||||
PromptGenerator._comfy_cache_cleanup_compat(force=True)
|
||||
gc.collect()
|
||||
|
||||
if torch.cuda.is_available():
|
||||
torch.cuda.empty_cache()
|
||||
try:
|
||||
torch.cuda.ipc_collect()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
print_pg(f"VRAM flush executed (unload_models={'ON' if unload_models else 'OFF'}).")
|
||||
except Exception as e:
|
||||
print_pg(f"Warning: VRAM flush failed: {e}", RED)
|
||||
|
||||
@staticmethod
|
||||
def cleanup_vram_before_run():
|
||||
"""Aggressive pre-run VRAM cleanup before generation starts."""
|
||||
PromptGenerator.flush_vram(unload_models=True)
|
||||
|
||||
def convert_prompt(self, seed: int, mode="Enhance Prompt (Image)", prompt="", image=None, format_as_json=False, enable_thinking=True, stop_server_after=True, options=None, **kwargs) -> str:
|
||||
"""Convert prompt using llama.cpp server or Ollama, with caching for repeated requests."""
|
||||
global _current_model
|
||||
|
||||
print_pg_header() # Print header for this execution
|
||||
self.cleanup_vram_before_run()
|
||||
|
||||
# Determine LLM backend: "ollama" or "llama.cpp"
|
||||
use_ollama = (
|
||||
(options and options.get("llm_backend") == "ollama")
|
||||
or _preferences_cache.get("llm_backend", "llama.cpp") == "ollama"
|
||||
(options and options.get("llm_backend") == "ollama") or
|
||||
_preferences_cache.get("llm_backend", "llama.cpp") == "ollama"
|
||||
)
|
||||
|
||||
# Extract console option from connected options node
|
||||
@@ -784,7 +826,7 @@ class PromptGenerator:
|
||||
|
||||
# If the current model is not the one we want, or server is not running, restart
|
||||
# Also restart if context_size has changed (llama.cpp only)
|
||||
context_size = options.get("context_size", 4096) if options else 4096
|
||||
context_size = options.get("context_size", 2048) if options else 2048
|
||||
if not use_ollama:
|
||||
if _current_model != model_to_use or _current_context_size != context_size or not self.is_server_alive():
|
||||
self.stop_server()
|
||||
@@ -1073,6 +1115,9 @@ class PromptGenerator:
|
||||
print_pg("Perhaps your query requires a larger context size.\nConsider increasing it using the Generator Options node.", RED)
|
||||
error_msg += "\nConsider increasing context size using Generator Options node."
|
||||
raise RuntimeError(error_msg)
|
||||
finally:
|
||||
# Aggressive post-run cleanup to release VRAM pressure for Comfy pipelines.
|
||||
self.flush_vram(unload_models=True)
|
||||
|
||||
# ================================================================
|
||||
# Ollama generation helper
|
||||
@@ -1241,6 +1286,9 @@ class PromptGenerator:
|
||||
error_msg = f"Error (Ollama): {e}"
|
||||
print_pg(error_msg, RED)
|
||||
raise RuntimeError(error_msg)
|
||||
finally:
|
||||
# Aggressive post-run cleanup to release VRAM pressure for Comfy pipelines.
|
||||
self.flush_vram(unload_models=True)
|
||||
|
||||
def print_token_stats(self, usage_stats, cached_token_counts, thinking_content, full_response, images):
|
||||
"""Print token statistics using pre-cached counts"""
|
||||
|
||||
@@ -58,21 +58,21 @@ class PromptGenOptions:
|
||||
"tooltip": "Use the model's default sampling parameters (overrides temperature, top_p, etc)"
|
||||
}),
|
||||
"temperature": ("FLOAT", {
|
||||
"default": 0.8,
|
||||
"default": 0.7,
|
||||
"min": 0.0,
|
||||
"max": 2.0,
|
||||
"step": 0.01,
|
||||
"tooltip": "Controls randomness (0.0 = deterministic, 2.0 = very random)"
|
||||
}),
|
||||
"top_k": ("INT", {
|
||||
"default": 40,
|
||||
"default": 20,
|
||||
"min": 0,
|
||||
"max": 100,
|
||||
"step": 1,
|
||||
"tooltip": "Sample from top K most likely tokens (0 = disabled)"
|
||||
}),
|
||||
"top_p": ("FLOAT", {
|
||||
"default": 0.95,
|
||||
"default": 0.9,
|
||||
"min": 0.0,
|
||||
"max": 1.0,
|
||||
"step": 0.01,
|
||||
|
||||
@@ -11,7 +11,7 @@ from datetime import datetime
|
||||
from io import BytesIO
|
||||
import folder_paths
|
||||
import server
|
||||
from ..py.workflow_data_utils import to_json_safe_workflow_data
|
||||
from ..py.workflow_data_utils import ensure_v2_recipe_data, to_json_safe_workflow_data, build_v2_recipe_data_from_prompt
|
||||
|
||||
# Import numpy and PIL for image processing (available in ComfyUI environment)
|
||||
try:
|
||||
@@ -73,6 +73,97 @@ def image_to_base64_thumbnail(image_tensor, max_size=200):
|
||||
return None
|
||||
|
||||
|
||||
def _has_meaningful_workflow_data(workflow_data):
|
||||
"""Return True when workflow_data contains authored prompt/model/lora content."""
|
||||
if not isinstance(workflow_data, dict):
|
||||
return False
|
||||
|
||||
if int(workflow_data.get("version", 0) or 0) >= 2 and isinstance(workflow_data.get("models"), dict):
|
||||
for mk in ("model_a", "model_b", "model_c", "model_d"):
|
||||
block = workflow_data.get("models", {}).get(mk)
|
||||
if not isinstance(block, dict):
|
||||
continue
|
||||
positive_prompt = str(block.get("positive_prompt", "")).strip()
|
||||
model_name = str(block.get("model", "")).strip()
|
||||
loras = block.get("loras")
|
||||
has_loras = isinstance(loras, list) and any(
|
||||
isinstance(lora_item, dict) and str(lora_item.get("name", "")).strip()
|
||||
for lora_item in loras
|
||||
)
|
||||
if positive_prompt or model_name or has_loras:
|
||||
return True
|
||||
return False
|
||||
|
||||
positive_prompt = str(workflow_data.get("positive_prompt", "")).strip()
|
||||
model_a = str(workflow_data.get("model_a", "")).strip()
|
||||
model_b = str(workflow_data.get("model_b", "")).strip()
|
||||
|
||||
loras_a = workflow_data.get("loras_a")
|
||||
has_loras_a = isinstance(loras_a, list) and any(
|
||||
isinstance(lora_item, dict) and str(lora_item.get("name", "")).strip()
|
||||
for lora_item in loras_a
|
||||
)
|
||||
|
||||
loras_b = workflow_data.get("loras_b")
|
||||
has_loras_b = isinstance(loras_b, list) and any(
|
||||
isinstance(lora_item, dict) and str(lora_item.get("name", "")).strip()
|
||||
for lora_item in loras_b
|
||||
)
|
||||
|
||||
return bool(positive_prompt or model_a or model_b or has_loras_a or has_loras_b)
|
||||
|
||||
|
||||
def _normalize_workflow_loras_for_prompt(loras):
|
||||
"""Normalize workflow_data LoRA list to prompt-manager LoRA schema."""
|
||||
normalized = []
|
||||
if not isinstance(loras, list):
|
||||
return normalized
|
||||
for lora in loras:
|
||||
if not isinstance(lora, dict):
|
||||
continue
|
||||
name = str(lora.get("name", "")).strip()
|
||||
if not name:
|
||||
continue
|
||||
strength = lora.get("strength", lora.get("model_strength", 1.0))
|
||||
clip_strength = lora.get("clip_strength", strength)
|
||||
normalized.append({
|
||||
"name": name,
|
||||
"path": str(lora.get("path", name) or name),
|
||||
"strength": strength,
|
||||
"clip_strength": clip_strength,
|
||||
"active": lora.get("active", True),
|
||||
"available": bool(lora.get("available", True)),
|
||||
})
|
||||
return normalized
|
||||
|
||||
|
||||
def _derive_prompt_fields_from_workflow_data(workflow_data):
|
||||
"""Derive prompt + LoRA compatibility fields from v2 workflow_data model blocks."""
|
||||
if not isinstance(workflow_data, dict):
|
||||
return {
|
||||
"prompt": "",
|
||||
"negative_prompt": "",
|
||||
"loras_a": [],
|
||||
"loras_b": [],
|
||||
"model_a": "",
|
||||
"model_b": "",
|
||||
}
|
||||
|
||||
wf_v2 = ensure_v2_recipe_data(workflow_data, source="PromptManagerAdvanced")
|
||||
wf_models = wf_v2.get("models", {}) if isinstance(wf_v2.get("models"), dict) else {}
|
||||
model_a_block = wf_models.get("model_a") if isinstance(wf_models.get("model_a"), dict) else {}
|
||||
model_b_block = wf_models.get("model_b") if isinstance(wf_models.get("model_b"), dict) else {}
|
||||
|
||||
return {
|
||||
"prompt": str(model_a_block.get("positive_prompt", "") or ""),
|
||||
"negative_prompt": str(model_a_block.get("negative_prompt", "") or ""),
|
||||
"loras_a": _normalize_workflow_loras_for_prompt(model_a_block.get("loras", [])),
|
||||
"loras_b": _normalize_workflow_loras_for_prompt(model_b_block.get("loras", [])),
|
||||
"model_a": str(model_a_block.get("model", "") or ""),
|
||||
"model_b": str(model_b_block.get("model", "") or ""),
|
||||
}
|
||||
|
||||
|
||||
# ── Shared LoRA utilities ─────────────────────────────────────────────────────
|
||||
from ..py.lora_utils import (
|
||||
get_available_loras,
|
||||
@@ -127,31 +218,25 @@ class PromptManagerAdvanced:
|
||||
first_category = categories[0] if categories else "Default"
|
||||
|
||||
# Get first prompt from first category
|
||||
# Keep new node instances empty until the user explicitly selects a prompt.
|
||||
first_prompt = ""
|
||||
first_prompt_text = ""
|
||||
if prompts_data and first_category in prompts_data and prompts_data[first_category]:
|
||||
first_category_prompts = [k for k in prompts_data[first_category].keys() if k != "__meta__"]
|
||||
first_prompt = sorted(first_category_prompts, key=str.lower)[0] if first_category_prompts else ""
|
||||
if first_prompt:
|
||||
first_prompt_text = prompts_data[first_category][first_prompt].get("prompt", "")
|
||||
|
||||
return {
|
||||
"required": {
|
||||
"category": (categories, {"default": first_category}),
|
||||
"name": (all_prompts_list, {"default": first_prompt}),
|
||||
"use_prompt_input": ("BOOLEAN", {"default": False, "label_on": "on", "label_off": "off", "tooltip": "Toggle to use connected prompt input instead of internal text"}),
|
||||
"use_prompt_input": ("BOOLEAN", {
|
||||
"default": False,
|
||||
"label_on": "on",
|
||||
"label_off": "off",
|
||||
"tooltip": "Toggle to use connected prompt input instead of internal text"}),
|
||||
"use_lora_input": ("BOOLEAN", {
|
||||
"default": False,
|
||||
"label_on": "on",
|
||||
"label_off": "off",
|
||||
"tooltip": "When enabled, use LoRAs from connected inputs. When off, use only prompt LoRAs."
|
||||
}),
|
||||
"use_workflow_data": ("BOOLEAN", {
|
||||
"default": False,
|
||||
"label_on": "on",
|
||||
"label_off": "off",
|
||||
"tooltip": "When enabled, use connected workflow_data prompt/LoRAs at execution."
|
||||
}),
|
||||
"text": ("STRING", {
|
||||
"multiline": True,
|
||||
"default": first_prompt_text,
|
||||
@@ -172,26 +257,24 @@ class PromptManagerAdvanced:
|
||||
"lora_stack_b": ("LORA_STACK", {"tooltip": "Second LoRA stack input (e.g., for video model)"}),
|
||||
"trigger_words": ("STRING", {"forceInput": True, "tooltip": "Comma-separated trigger words to append to prompt"}),
|
||||
"thumbnail_image": ("IMAGE", {"tooltip": "Connect an image to use as thumbnail when saving the prompt"}),
|
||||
"workflow_data": ("WORKFLOW_DATA", {"forceInput": True, "tooltip": "Connect workflow_data from WorkflowBuilder or PromptExtractor"}),
|
||||
},
|
||||
"hidden": {
|
||||
"unique_id": "UNIQUE_ID",
|
||||
"loras_a_toggle": "STRING",
|
||||
"loras_b_toggle": "STRING",
|
||||
"trigger_words_toggle": "STRING",
|
||||
"saved_workflow_data": "STRING",
|
||||
}
|
||||
}
|
||||
|
||||
CATEGORY = "Prompt Manager"
|
||||
DESCRIPTION = "Full-featured prompt manager with dual LoRA stack support, trigger words, and thumbnail browser."
|
||||
RETURN_TYPES = ("STRING", "LORA_STACK", "LORA_STACK", "WORKFLOW_DATA")
|
||||
RETURN_NAMES = ("prompt", "lora_stack_a", "lora_stack_b", "workflow_data")
|
||||
RETURN_TYPES = ("STRING", "LORA_STACK", "LORA_STACK", "RECIPE_DATA")
|
||||
RETURN_NAMES = ("prompt", "lora_stack_a", "lora_stack_b", "recipe_data")
|
||||
FUNCTION = "get_prompt"
|
||||
OUTPUT_NODE = True
|
||||
|
||||
@classmethod
|
||||
def IS_CHANGED(cls, category, name, use_prompt_input, use_lora_input=True, use_workflow_data=False, text="", swap_lora_outputs=False,
|
||||
def IS_CHANGED(cls, category, name, use_prompt_input, use_lora_input=True, text="", swap_lora_outputs=False,
|
||||
**kwargs):
|
||||
"""
|
||||
Track changes to the node's inputs to determine if re-execution is needed.
|
||||
@@ -202,7 +285,6 @@ class PromptManagerAdvanced:
|
||||
lora_stack_a = kwargs.get('lora_stack_a', None)
|
||||
lora_stack_b = kwargs.get('lora_stack_b', None)
|
||||
trigger_words = kwargs.get('trigger_words', None)
|
||||
workflow_data = kwargs.get('workflow_data', None)
|
||||
# Return tuple of all values that should trigger re-execution when changed
|
||||
# Convert lists/objects to strings for hashable comparison
|
||||
return (
|
||||
@@ -210,14 +292,12 @@ class PromptManagerAdvanced:
|
||||
name,
|
||||
use_prompt_input,
|
||||
use_lora_input,
|
||||
use_workflow_data,
|
||||
text,
|
||||
swap_lora_outputs,
|
||||
str(prompt_input) if prompt_input else None,
|
||||
str(lora_stack_a) if lora_stack_a else None,
|
||||
str(lora_stack_b) if lora_stack_b else None,
|
||||
trigger_words,
|
||||
str(workflow_data) if workflow_data else None,
|
||||
)
|
||||
|
||||
@classmethod
|
||||
@@ -464,11 +544,11 @@ class PromptManagerAdvanced:
|
||||
# Not found
|
||||
return lora_path, False
|
||||
|
||||
def get_prompt(self, category, name, use_prompt_input, use_lora_input=True, use_workflow_data=False, text="", swap_lora_outputs=False,
|
||||
def get_prompt(self, category, name, use_prompt_input, use_lora_input=True, text="", swap_lora_outputs=False,
|
||||
prompt=None, lora_stack_a=None, lora_stack_b=None,
|
||||
trigger_words=None, thumbnail_image=None, workflow_data=None,
|
||||
trigger_words=None, thumbnail_image=None,
|
||||
unique_id=None, loras_a_toggle=None, loras_b_toggle=None, trigger_words_toggle=None,
|
||||
saved_workflow_data=None):
|
||||
**kwargs):
|
||||
"""Return the prompt text and filtered lora stacks based on toggle states"""
|
||||
|
||||
# ========================================
|
||||
@@ -532,54 +612,21 @@ class PromptManagerAdvanced:
|
||||
# CONTINUE WITH NORMAL PROCESSING
|
||||
# ========================================
|
||||
|
||||
# Resolve workflow payload candidates.
|
||||
# IMPORTANT: when use_workflow_data is OFF, do not pass through live
|
||||
# upstream workflow_data updates to this node's workflow_data output.
|
||||
prompts_data = self.load_prompts()
|
||||
prompt_entry = prompts_data.get(category, {}).get(name, {}) if isinstance(prompts_data, dict) else {}
|
||||
stored_prompt_wf = prompt_entry.get("workflow_data") if isinstance(prompt_entry, dict) else None
|
||||
|
||||
live_workflow_data = None
|
||||
if isinstance(workflow_data, dict):
|
||||
live_workflow_data = workflow_data
|
||||
elif isinstance(workflow_data, str) and workflow_data.strip():
|
||||
try:
|
||||
parsed = json.loads(workflow_data)
|
||||
if isinstance(parsed, dict):
|
||||
live_workflow_data = parsed
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
live_workflow_data = None
|
||||
|
||||
hidden_saved_wf = None
|
||||
if isinstance(saved_workflow_data, str) and saved_workflow_data.strip():
|
||||
try:
|
||||
parsed_saved = json.loads(saved_workflow_data)
|
||||
if isinstance(parsed_saved, dict):
|
||||
hidden_saved_wf = parsed_saved
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
hidden_saved_wf = None
|
||||
|
||||
if use_workflow_data:
|
||||
# Workflow mode ON: keep local manager state authoritative.
|
||||
# Priority: hidden saved widget -> prompt-stored workflow_data -> live upstream fallback.
|
||||
resolved_workflow_data = hidden_saved_wf
|
||||
if resolved_workflow_data is None and isinstance(stored_prompt_wf, dict):
|
||||
resolved_workflow_data = stored_prompt_wf
|
||||
if resolved_workflow_data is None:
|
||||
resolved_workflow_data = live_workflow_data
|
||||
else:
|
||||
# Workflow mode OFF: never source from connected/hidden live payload.
|
||||
resolved_workflow_data = stored_prompt_wf if isinstance(stored_prompt_wf, dict) else None
|
||||
resolved_workflow_data = ensure_v2_recipe_data(stored_prompt_wf, source="PromptManagerAdvanced") if isinstance(stored_prompt_wf, dict) else None
|
||||
workflow_fields = _derive_prompt_fields_from_workflow_data(resolved_workflow_data)
|
||||
|
||||
# Choose which text to use based on the toggles
|
||||
# Priority: use_prompt_input > use_workflow_data > internal text
|
||||
# Priority: use_prompt_input > internal text
|
||||
if use_prompt_input and prompt:
|
||||
output_text = prompt
|
||||
elif use_workflow_data and resolved_workflow_data:
|
||||
wf = resolved_workflow_data if isinstance(resolved_workflow_data, dict) else {}
|
||||
output_text = wf.get('positive_prompt', '') or text or ""
|
||||
else:
|
||||
output_text = text if text else ""
|
||||
if not output_text.strip() and workflow_fields.get("prompt"):
|
||||
# Compatibility fallback: v2 prompt is authoritative in model_a block.
|
||||
output_text = workflow_fields.get("prompt", "")
|
||||
|
||||
# Capture the original input loras BEFORE any processing
|
||||
# These are used by the frontend to detect when inputs change
|
||||
@@ -626,28 +673,64 @@ class PromptManagerAdvanced:
|
||||
preset_stack_a = self._build_stack_from_toggle(loras_a_toggle) if loras_a_toggle else []
|
||||
preset_stack_b = self._build_stack_from_toggle(loras_b_toggle) if loras_b_toggle else []
|
||||
|
||||
# Compatibility fallback: when no saved toggle payload exists, seed
|
||||
# PMA stack defaults from v2 model_a/model_b LoRA blocks.
|
||||
if not preset_stack_a and not loras_a_toggle:
|
||||
preset_stack_a = [
|
||||
(
|
||||
lora.get("name", ""),
|
||||
lora.get("strength", lora.get("model_strength", 1.0)),
|
||||
lora.get("clip_strength", lora.get("strength", lora.get("model_strength", 1.0))),
|
||||
)
|
||||
for lora in workflow_fields.get("loras_a", [])
|
||||
if isinstance(lora, dict) and lora.get("name")
|
||||
]
|
||||
if not preset_stack_b and not loras_b_toggle:
|
||||
preset_stack_b = [
|
||||
(
|
||||
lora.get("name", ""),
|
||||
lora.get("strength", lora.get("model_strength", 1.0)),
|
||||
lora.get("clip_strength", lora.get("strength", lora.get("model_strength", 1.0))),
|
||||
)
|
||||
for lora in workflow_fields.get("loras_b", [])
|
||||
if isinstance(lora, dict) and lora.get("name")
|
||||
]
|
||||
|
||||
# Get ALL preset loras including unavailable ones (for display purposes)
|
||||
all_preset_loras_a = self._get_all_loras_from_toggle(loras_a_toggle) if loras_a_toggle else []
|
||||
all_preset_loras_b = self._get_all_loras_from_toggle(loras_b_toggle) if loras_b_toggle else []
|
||||
|
||||
wf_loras_a = []
|
||||
wf_loras_b = []
|
||||
if use_workflow_data and resolved_workflow_data and isinstance(resolved_workflow_data, dict):
|
||||
wf_loras_a = [
|
||||
(wf_lora['name'], wf_lora.get('model_strength', 1.0), wf_lora.get('clip_strength', 1.0))
|
||||
for wf_lora in resolved_workflow_data.get('loras_a', []) if isinstance(wf_lora, dict) and wf_lora.get('name')
|
||||
# If no saved toggle payload exists yet, preserve active flags from
|
||||
# incoming workflow_data loras as the initial authoritative state.
|
||||
if not all_preset_loras_a and not loras_a_toggle:
|
||||
all_preset_loras_a = [
|
||||
{
|
||||
"name": lora.get("name", ""),
|
||||
"strength": float(lora.get("strength", lora.get("model_strength", 1.0))),
|
||||
"clip_strength": float(lora.get("clip_strength", lora.get("strength", lora.get("model_strength", 1.0)))),
|
||||
"active": lora.get("active", True),
|
||||
"available": bool(lora.get("available", True)),
|
||||
}
|
||||
for lora in workflow_fields.get("loras_a", [])
|
||||
if isinstance(lora, dict) and lora.get("name")
|
||||
]
|
||||
wf_loras_b = [
|
||||
(wf_lora['name'], wf_lora.get('model_strength', 1.0), wf_lora.get('clip_strength', 1.0))
|
||||
for wf_lora in resolved_workflow_data.get('loras_b', []) if isinstance(wf_lora, dict) and wf_lora.get('name')
|
||||
if not all_preset_loras_b and not loras_b_toggle:
|
||||
all_preset_loras_b = [
|
||||
{
|
||||
"name": lora.get("name", ""),
|
||||
"strength": float(lora.get("strength", lora.get("model_strength", 1.0))),
|
||||
"clip_strength": float(lora.get("clip_strength", lora.get("strength", lora.get("model_strength", 1.0)))),
|
||||
"active": lora.get("active", True),
|
||||
"available": bool(lora.get("available", True)),
|
||||
}
|
||||
for lora in workflow_fields.get("loras_b", [])
|
||||
if isinstance(lora, dict) and lora.get("name")
|
||||
]
|
||||
|
||||
# When use_lora_input is disabled, ignore connected stacks and use only saved loras
|
||||
if not use_lora_input:
|
||||
# If workflow mode is enabled and workflow_data carries LoRAs, show/use those.
|
||||
# Otherwise, fall back to saved preset LoRAs.
|
||||
lora_stack_a = wf_loras_a if wf_loras_a else preset_stack_a
|
||||
lora_stack_b = wf_loras_b if wf_loras_b else preset_stack_b
|
||||
lora_stack_a = preset_stack_a
|
||||
lora_stack_b = preset_stack_b
|
||||
else:
|
||||
# Merge: preset loras + connected loras (avoiding duplicates by lora name)
|
||||
# Handle case where connected stack might be None or empty
|
||||
@@ -661,12 +744,6 @@ class PromptManagerAdvanced:
|
||||
else:
|
||||
lora_stack_b = preset_stack_b if preset_stack_b else []
|
||||
|
||||
# Merge workflow_data loras (lowest priority — existing stacks take precedence)
|
||||
if wf_loras_a:
|
||||
lora_stack_a = self._merge_lora_stacks(lora_stack_a, wf_loras_a)
|
||||
if wf_loras_b:
|
||||
lora_stack_b = self._merge_lora_stacks(lora_stack_b, wf_loras_b)
|
||||
|
||||
# Process lora stacks with toggle data (filter inactive, apply strength)
|
||||
processed_stack_a = self._process_lora_toggle(lora_stack_a, loras_a_toggle)
|
||||
processed_stack_b = self._process_lora_toggle(lora_stack_b, loras_b_toggle)
|
||||
@@ -674,13 +751,8 @@ class PromptManagerAdvanced:
|
||||
# Display logic: Include ALL loras (available + unavailable) so UI shows complete picture
|
||||
# Build display from available loras first, then add unavailable ones
|
||||
if not use_lora_input:
|
||||
if use_workflow_data and (wf_loras_a or wf_loras_b):
|
||||
# Workflow mode: display workflow LoRAs directly.
|
||||
loras_a_display = self._format_loras_for_display(lora_stack_a)
|
||||
loras_b_display = self._format_loras_for_display(lora_stack_b)
|
||||
else:
|
||||
loras_a_display = self._format_loras_for_display_with_unavailable(preset_stack_a, all_preset_loras_a)
|
||||
loras_b_display = self._format_loras_for_display_with_unavailable(preset_stack_b, all_preset_loras_b)
|
||||
loras_a_display = self._format_loras_for_display_with_unavailable(preset_stack_a, all_preset_loras_a)
|
||||
loras_b_display = self._format_loras_for_display_with_unavailable(preset_stack_b, all_preset_loras_b)
|
||||
else:
|
||||
loras_a_display = self._format_loras_for_display_with_unavailable(lora_stack_a, all_preset_loras_a)
|
||||
loras_b_display = self._format_loras_for_display_with_unavailable(lora_stack_b, all_preset_loras_b)
|
||||
@@ -703,9 +775,7 @@ class PromptManagerAdvanced:
|
||||
"node_id": unique_id,
|
||||
"prompt": output_text,
|
||||
"use_prompt_input": use_prompt_input,
|
||||
"use_workflow_data": use_workflow_data,
|
||||
"prompt_input": prompt,
|
||||
"workflow_data": to_json_safe_workflow_data(resolved_workflow_data) if isinstance(resolved_workflow_data, dict) else None,
|
||||
"loras_a": loras_a_display,
|
||||
"loras_b": loras_b_display,
|
||||
"input_loras_a": input_loras_a, # Original input loras for change detection
|
||||
@@ -728,45 +798,23 @@ class PromptManagerAdvanced:
|
||||
if swap_lora_outputs:
|
||||
out_stack_a, out_stack_b = out_stack_b, out_stack_a
|
||||
|
||||
# Build workflow_data output — start from incoming or saved data, update with PMA state
|
||||
if isinstance(resolved_workflow_data, dict):
|
||||
out_workflow_data = dict(resolved_workflow_data)
|
||||
else:
|
||||
out_workflow_data = {}
|
||||
out_workflow_data['positive_prompt'] = final_output
|
||||
out_workflow_data['loras_a'] = [
|
||||
{
|
||||
'name': lora.get('name', ''),
|
||||
'model_strength': lora.get('model_strength', lora.get('strength', 1.0)),
|
||||
'clip_strength': lora.get('clip_strength', lora.get('strength', 1.0)),
|
||||
'active': lora.get('active', True),
|
||||
'available': lora.get('available', True),
|
||||
'found': lora.get('available', True),
|
||||
}
|
||||
for lora in loras_a_display
|
||||
if isinstance(lora, dict) and lora.get('name')
|
||||
]
|
||||
out_workflow_data['loras_b'] = [
|
||||
{
|
||||
'name': lora.get('name', ''),
|
||||
'model_strength': lora.get('model_strength', lora.get('strength', 1.0)),
|
||||
'clip_strength': lora.get('clip_strength', lora.get('strength', 1.0)),
|
||||
'active': lora.get('active', True),
|
||||
'available': lora.get('available', True),
|
||||
'found': lora.get('available', True),
|
||||
}
|
||||
for lora in loras_b_display
|
||||
if isinstance(lora, dict) and lora.get('name')
|
||||
]
|
||||
out_workflow_data['_source'] = 'PromptManagerAdvanced'
|
||||
neg_prompt = str(workflow_fields.get('negative_prompt', '') or '')
|
||||
out_workflow_data = build_v2_recipe_data_from_prompt(
|
||||
prompt_text=final_output,
|
||||
negative_prompt=neg_prompt,
|
||||
loras_a=loras_a_display,
|
||||
loras_b=loras_b_display,
|
||||
source='PromptManagerAdvanced',
|
||||
base_recipe_data=resolved_workflow_data,
|
||||
)
|
||||
|
||||
return (final_output, out_stack_a, out_stack_b, out_workflow_data)
|
||||
|
||||
def check_lazy_status(self, category, name, use_prompt_input, use_lora_input=True, use_workflow_data=False, text="", swap_lora_outputs=False,
|
||||
def check_lazy_status(self, category, name, use_prompt_input, use_lora_input=True, text="", swap_lora_outputs=False,
|
||||
prompt=None, lora_stack_a=None, lora_stack_b=None,
|
||||
trigger_words=None, thumbnail_image=None, workflow_data=None,
|
||||
trigger_words=None, thumbnail_image=None,
|
||||
unique_id=None, loras_a_toggle=None, loras_b_toggle=None,
|
||||
trigger_words_toggle=None, saved_workflow_data=None):
|
||||
trigger_words_toggle=None):
|
||||
"""Tell ComfyUI which lazy inputs are needed based on current settings.
|
||||
|
||||
When use_prompt_input is enabled, we need to request the prompt_input
|
||||
@@ -871,7 +919,6 @@ class PromptManagerAdvanced:
|
||||
"active": True,
|
||||
"strength": model_strength,
|
||||
"available": available,
|
||||
"found": available
|
||||
})
|
||||
seen_names.add(lora_name_lower)
|
||||
|
||||
@@ -914,7 +961,6 @@ class PromptManagerAdvanced:
|
||||
"clip_strength": float(item.get('clip_strength', item.get('strength', 1.0))),
|
||||
"active": item.get('active', True),
|
||||
"available": found,
|
||||
"found": found
|
||||
})
|
||||
|
||||
return all_loras
|
||||
@@ -926,6 +972,20 @@ class PromptManagerAdvanced:
|
||||
"""
|
||||
# Start with the available loras from the stack
|
||||
display_list = self._format_loras_for_display(lora_stack) if lora_stack else []
|
||||
preset_by_name = {
|
||||
str(item.get('name', '')).lower(): item
|
||||
for item in (all_preset_loras or [])
|
||||
if isinstance(item, dict) and item.get('name')
|
||||
}
|
||||
|
||||
# Preserve active state from preset/toggle/workflow payload for rows
|
||||
# that are already present in the display list.
|
||||
for row in display_list:
|
||||
row_name_lower = str(row.get('name', '')).lower()
|
||||
preset = preset_by_name.get(row_name_lower)
|
||||
if preset is not None:
|
||||
row['active'] = preset.get('active', True)
|
||||
|
||||
seen_names = set(item['name'].lower() for item in display_list)
|
||||
|
||||
# Add any unavailable preset loras that aren't already in the list
|
||||
@@ -940,7 +1000,6 @@ class PromptManagerAdvanced:
|
||||
"active": lora['active'],
|
||||
"strength": lora['strength'],
|
||||
"available": lora['available'],
|
||||
"found": lora.get('found', lora['available'])
|
||||
})
|
||||
seen_names.add(lora_name_lower)
|
||||
|
||||
@@ -1171,21 +1230,19 @@ async def save_prompt_advanced(request):
|
||||
print(f"[PromptManagerAdvanced] Removing old casing '{old_name}' before saving as '{name}'")
|
||||
del prompts[category][old_name]
|
||||
|
||||
# Normalize lora data - save name, strengths, and active state
|
||||
# Paths are resolved at runtime for portability
|
||||
# Normalize lora data - keep path when present for lossless save/restore.
|
||||
def normalize_lora_data(loras):
|
||||
normalized = []
|
||||
for lora in loras:
|
||||
if isinstance(lora, dict) and lora.get('name'):
|
||||
available = lora.get('available', lora.get('found', True))
|
||||
found = lora.get('found', available)
|
||||
available = lora.get('available', lora.get('available', True))
|
||||
normalized.append({
|
||||
"name": lora.get('name'),
|
||||
"path": lora.get('path', lora.get('name')),
|
||||
"strength": lora.get('strength', lora.get('model_strength', 1.0)),
|
||||
"clip_strength": lora.get('clip_strength', lora.get('strength', 1.0)),
|
||||
"active": lora.get('active', True),
|
||||
"available": bool(available),
|
||||
"found": bool(found),
|
||||
})
|
||||
return normalized
|
||||
|
||||
@@ -1202,15 +1259,14 @@ async def save_prompt_advanced(request):
|
||||
continue
|
||||
strength = lora.get('strength', lora.get('model_strength', 1.0))
|
||||
clip_strength = lora.get('clip_strength', strength)
|
||||
available = lora.get('available', lora.get('found', True))
|
||||
found = lora.get('found', available)
|
||||
available = lora.get('available', lora.get('available', True))
|
||||
normalized.append({
|
||||
"name": name,
|
||||
"path": lora.get('path', name),
|
||||
"strength": strength,
|
||||
"clip_strength": clip_strength,
|
||||
"active": lora.get('active', True),
|
||||
"available": bool(available),
|
||||
"found": bool(found),
|
||||
})
|
||||
return normalized
|
||||
|
||||
@@ -1245,12 +1301,12 @@ async def save_prompt_advanced(request):
|
||||
workflow_data = data.get("workflow_data")
|
||||
wf_to_save = None
|
||||
if isinstance(workflow_data, dict):
|
||||
wf_to_save = to_json_safe_workflow_data(workflow_data)
|
||||
wf_to_save = to_json_safe_workflow_data(ensure_v2_recipe_data(workflow_data, source="PromptManagerAdvanced"))
|
||||
elif isinstance(workflow_data, str) and workflow_data.strip():
|
||||
try:
|
||||
parsed_wf = json.loads(workflow_data)
|
||||
if isinstance(parsed_wf, dict):
|
||||
wf_to_save = to_json_safe_workflow_data(parsed_wf)
|
||||
wf_to_save = to_json_safe_workflow_data(ensure_v2_recipe_data(parsed_wf, source="PromptManagerAdvanced"))
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
wf_to_save = None
|
||||
|
||||
@@ -1258,17 +1314,20 @@ async def save_prompt_advanced(request):
|
||||
normalized_loras_a = normalize_lora_data(loras_a)
|
||||
normalized_loras_b = normalize_lora_data(loras_b)
|
||||
|
||||
# Workflow Saver parity: when workflow_data is present, treat its LoRA lists
|
||||
# as authoritative for persistence.
|
||||
wf_loras_a = normalize_workflow_lora_data((wf_to_save or {}).get("loras_a", []))
|
||||
wf_loras_b = normalize_workflow_lora_data((wf_to_save or {}).get("loras_b", []))
|
||||
if isinstance(wf_to_save, dict):
|
||||
if "loras_a" in wf_to_save:
|
||||
workflow_has_meaningful_data = _has_meaningful_workflow_data(wf_to_save)
|
||||
|
||||
# Workflow Saver parity: when meaningful workflow_data is present, treat
|
||||
# its LoRA lists as authoritative for persistence.
|
||||
wf_models = (wf_to_save or {}).get("models", {}) if isinstance((wf_to_save or {}).get("models"), dict) else {}
|
||||
wf_loras_a = normalize_workflow_lora_data((wf_models.get("model_a") or {}).get("loras", []))
|
||||
wf_loras_b = normalize_workflow_lora_data((wf_models.get("model_b") or {}).get("loras", []))
|
||||
if isinstance(wf_to_save, dict) and workflow_has_meaningful_data:
|
||||
if isinstance(wf_models.get("model_a"), dict) and wf_loras_a:
|
||||
normalized_loras_a = wf_loras_a
|
||||
elif not normalized_loras_a and wf_loras_a:
|
||||
normalized_loras_a = wf_loras_a
|
||||
|
||||
if "loras_b" in wf_to_save:
|
||||
if isinstance(wf_models.get("model_b"), dict) and wf_loras_b:
|
||||
normalized_loras_b = wf_loras_b
|
||||
elif not normalized_loras_b and wf_loras_b:
|
||||
normalized_loras_b = wf_loras_b
|
||||
@@ -1290,11 +1349,12 @@ async def save_prompt_advanced(request):
|
||||
|
||||
# Persist prompt fields from workflow_data snapshot when available.
|
||||
if isinstance(wf_to_save, dict):
|
||||
if isinstance(wf_to_save.get("positive_prompt"), str):
|
||||
prompt_data["prompt"] = wf_to_save.get("positive_prompt", "")
|
||||
if isinstance(wf_to_save.get("negative_prompt"), str):
|
||||
prompt_data["negative_prompt"] = wf_to_save.get("negative_prompt", "")
|
||||
prompt_data["saved_from"] = "WorkflowManager"
|
||||
model_a_block = wf_models.get("model_a") if isinstance(wf_models.get("model_a"), dict) else {}
|
||||
if isinstance(model_a_block.get("positive_prompt"), str) and model_a_block.get("positive_prompt", "").strip():
|
||||
prompt_data["prompt"] = model_a_block.get("positive_prompt", "")
|
||||
if isinstance(model_a_block.get("negative_prompt"), str):
|
||||
prompt_data["negative_prompt"] = model_a_block.get("negative_prompt", "")
|
||||
prompt_data["saved_from"] = "RecipeManager"
|
||||
prompt_data["saved_at"] = datetime.utcnow().isoformat() + "Z"
|
||||
|
||||
if wf_to_save:
|
||||
@@ -1304,7 +1364,7 @@ async def save_prompt_advanced(request):
|
||||
# edits without a currently connected workflow_data source.
|
||||
existing_wf = existing_prompt.get("workflow_data")
|
||||
if isinstance(existing_wf, dict):
|
||||
prompt_data["workflow_data"] = to_json_safe_workflow_data(existing_wf)
|
||||
prompt_data["workflow_data"] = to_json_safe_workflow_data(ensure_v2_recipe_data(existing_wf, source="PromptManagerAdvanced"))
|
||||
|
||||
if thumbnail:
|
||||
prompt_data["thumbnail"] = thumbnail
|
||||
@@ -1317,7 +1377,7 @@ async def save_prompt_advanced(request):
|
||||
prompt_data["nsfw"] = existing_prompt["nsfw"]
|
||||
|
||||
# Preserve any extra fields from an existing prompt that this node does not manage.
|
||||
# This includes workflow_config (added by WorkflowManager) and any future extensions.
|
||||
# This includes workflow_config (added by RecipeManager) and any future extensions.
|
||||
# Known managed keys — everything else is preserved verbatim.
|
||||
_MANAGED_KEYS = {"prompt", "negative_prompt", "loras_a", "loras_b", "trigger_words", "thumbnail", "nsfw", "workflow_data", "saved_from", "saved_at"}
|
||||
for extra_key, extra_val in existing_prompt.items():
|
||||
@@ -1476,24 +1536,39 @@ async def get_prompt_data_advanced(request):
|
||||
|
||||
prompt_data = prompts[category][name]
|
||||
|
||||
# Compatibility: if prompt/loras are missing at top-level, derive them
|
||||
# from v2 workflow_data model_a/model_b blocks.
|
||||
prompt_response = dict(prompt_data)
|
||||
workflow_data = prompt_response.get("workflow_data")
|
||||
derived = _derive_prompt_fields_from_workflow_data(workflow_data)
|
||||
|
||||
if not str(prompt_response.get("prompt", "")).strip() and derived.get("prompt"):
|
||||
prompt_response["prompt"] = derived.get("prompt", "")
|
||||
|
||||
if not isinstance(prompt_response.get("loras_a"), list) or len(prompt_response.get("loras_a") or []) == 0:
|
||||
prompt_response["loras_a"] = derived.get("loras_a", [])
|
||||
|
||||
if not isinstance(prompt_response.get("loras_b"), list) or len(prompt_response.get("loras_b") or []) == 0:
|
||||
prompt_response["loras_b"] = derived.get("loras_b", [])
|
||||
|
||||
# Add availability info to loras
|
||||
def add_availability(loras):
|
||||
result = []
|
||||
for lora in loras:
|
||||
lora_copy = dict(lora)
|
||||
_, found = get_lora_relative_path(lora.get('name', ''))
|
||||
lora_copy['available'] = found
|
||||
_, available = get_lora_relative_path(lora.get('name', ''))
|
||||
lora_copy['available'] = available
|
||||
result.append(lora_copy)
|
||||
return result
|
||||
|
||||
return server.web.json_response({
|
||||
"success": True,
|
||||
"data": {
|
||||
"prompt": prompt_data.get("prompt", ""),
|
||||
"loras_a": add_availability(prompt_data.get("loras_a", [])),
|
||||
"loras_b": add_availability(prompt_data.get("loras_b", [])),
|
||||
"trigger_words": prompt_data.get("trigger_words", []),
|
||||
"workflow_data": prompt_data.get("workflow_data")
|
||||
"prompt": prompt_response.get("prompt", ""),
|
||||
"loras_a": add_availability(prompt_response.get("loras_a", [])),
|
||||
"loras_b": add_availability(prompt_response.get("loras_b", [])),
|
||||
"trigger_words": prompt_response.get("trigger_words", []),
|
||||
"workflow_data": prompt_response.get("workflow_data")
|
||||
}
|
||||
})
|
||||
except Exception as e:
|
||||
|
||||
@@ -13,7 +13,7 @@ from io import BytesIO
|
||||
|
||||
import server
|
||||
|
||||
from ..py.workflow_data_utils import to_json_safe_workflow_data
|
||||
from ..py.workflow_data_utils import ensure_v2_recipe_data, get_v2_model_block, to_json_safe_workflow_data, build_v2_recipe_data_from_prompt
|
||||
from .prompt_manager_adv import PromptManagerAdvanced
|
||||
|
||||
try:
|
||||
@@ -46,12 +46,12 @@ def _image_to_base64_thumbnail(image_tensor, max_size=200):
|
||||
base64_str = base64.b64encode(buffer.getvalue()).decode("utf-8")
|
||||
return f"data:image/jpeg;base64,{base64_str}"
|
||||
except Exception as e:
|
||||
print(f"[WorkflowManager] Thumbnail generation failed: {e}")
|
||||
print(f"[RecipeManager] Thumbnail generation failed: {e}")
|
||||
return None
|
||||
|
||||
|
||||
class WorkflowManager(PromptManagerAdvanced):
|
||||
"""Workflow-focused manager that edits and forwards WORKFLOW_DATA."""
|
||||
"""Workflow-focused manager that edits and forwards RECIPE_DATA."""
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
@@ -67,13 +67,9 @@ class WorkflowManager(PromptManagerAdvanced):
|
||||
|
||||
first_category = categories[0] if categories else "Default"
|
||||
|
||||
# Keep new node instances empty until the user explicitly selects a prompt.
|
||||
first_prompt = ""
|
||||
first_prompt_text = ""
|
||||
if prompts_data and first_category in prompts_data and prompts_data[first_category]:
|
||||
first_category_prompts = [k for k in prompts_data[first_category].keys() if k != "__meta__"]
|
||||
first_prompt = sorted(first_category_prompts, key=str.lower)[0] if first_category_prompts else ""
|
||||
if first_prompt:
|
||||
first_prompt_text = prompts_data[first_category][first_prompt].get("prompt", "")
|
||||
|
||||
return {
|
||||
"required": {
|
||||
@@ -84,11 +80,11 @@ class WorkflowManager(PromptManagerAdvanced):
|
||||
"default": first_prompt_text,
|
||||
"placeholder": "Enter prompt text",
|
||||
"dynamicPrompts": False,
|
||||
"tooltip": "Edit workflow_data prompt text directly",
|
||||
"tooltip": "Edit prompt text directly",
|
||||
}),
|
||||
},
|
||||
"optional": {
|
||||
"workflow_data": ("WORKFLOW_DATA", {"forceInput": True, "tooltip": "Connected workflow_data to edit/forward"}),
|
||||
"recipe_data": ("RECIPE_DATA", {"forceInput": True, "tooltip": "Connected recipe_data to edit/forward"}),
|
||||
},
|
||||
"hidden": {
|
||||
"unique_id": "UNIQUE_ID",
|
||||
@@ -100,14 +96,14 @@ class WorkflowManager(PromptManagerAdvanced):
|
||||
|
||||
CATEGORY = "Prompt Manager"
|
||||
DESCRIPTION = "Workflow-data focused manager (no use switches, no trigger words)."
|
||||
RETURN_TYPES = ("WORKFLOW_DATA",)
|
||||
RETURN_NAMES = ("workflow_data",)
|
||||
RETURN_TYPES = ("RECIPE_DATA",)
|
||||
RETURN_NAMES = ("recipe_data",)
|
||||
FUNCTION = "get_workflow"
|
||||
OUTPUT_NODE = True
|
||||
|
||||
@classmethod
|
||||
def IS_CHANGED(cls, category, name, text="", **kwargs):
|
||||
workflow_data = kwargs.get("workflow_data", None)
|
||||
recipe_data = kwargs.get("recipe_data", None)
|
||||
loras_a_toggle = kwargs.get("loras_a_toggle", "")
|
||||
loras_b_toggle = kwargs.get("loras_b_toggle", "")
|
||||
saved_workflow_data = kwargs.get("saved_workflow_data", "")
|
||||
@@ -115,7 +111,7 @@ class WorkflowManager(PromptManagerAdvanced):
|
||||
category,
|
||||
name,
|
||||
text,
|
||||
str(workflow_data) if workflow_data else None,
|
||||
str(recipe_data) if recipe_data else None,
|
||||
loras_a_toggle or "",
|
||||
loras_b_toggle or "",
|
||||
saved_workflow_data or "",
|
||||
@@ -126,47 +122,84 @@ class WorkflowManager(PromptManagerAdvanced):
|
||||
category,
|
||||
name,
|
||||
text="",
|
||||
workflow_data=None,
|
||||
recipe_data=None,
|
||||
unique_id=None,
|
||||
loras_a_toggle=None,
|
||||
loras_b_toggle=None,
|
||||
saved_workflow_data=None,
|
||||
):
|
||||
prompts_data = self.load_prompts()
|
||||
|
||||
def _as_workflow_dict(raw):
|
||||
if isinstance(raw, dict):
|
||||
return raw
|
||||
if isinstance(raw, str) and raw.strip():
|
||||
try:
|
||||
parsed = json.loads(raw)
|
||||
return parsed if isinstance(parsed, dict) else None
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
return None
|
||||
return None
|
||||
|
||||
prompt_entry = prompts_data.get(category, {}).get(name, {}) if isinstance(prompts_data, dict) else {}
|
||||
stored_prompt_wf = prompt_entry.get("workflow_data") if isinstance(prompt_entry, dict) else None
|
||||
# On reload, category/name can be temporarily out of sync in the UI.
|
||||
# If direct lookup misses, find the selected name in any category.
|
||||
if not isinstance(prompt_entry, dict) or not prompt_entry:
|
||||
if isinstance(prompts_data, dict) and isinstance(name, str) and name:
|
||||
for cat_prompts in prompts_data.values():
|
||||
if isinstance(cat_prompts, dict) and isinstance(cat_prompts.get(name), dict):
|
||||
prompt_entry = cat_prompts.get(name)
|
||||
break
|
||||
|
||||
live_workflow_data = None
|
||||
if isinstance(workflow_data, dict):
|
||||
live_workflow_data = workflow_data
|
||||
elif isinstance(workflow_data, str) and workflow_data.strip():
|
||||
try:
|
||||
parsed = json.loads(workflow_data)
|
||||
if isinstance(parsed, dict):
|
||||
live_workflow_data = parsed
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
live_workflow_data = None
|
||||
stored_prompt_wf = _as_workflow_dict(prompt_entry.get("workflow_data")) if isinstance(prompt_entry, dict) else None
|
||||
|
||||
hidden_saved_wf = None
|
||||
if isinstance(saved_workflow_data, str) and saved_workflow_data.strip():
|
||||
try:
|
||||
parsed_saved = json.loads(saved_workflow_data)
|
||||
if isinstance(parsed_saved, dict):
|
||||
hidden_saved_wf = parsed_saved
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
hidden_saved_wf = None
|
||||
live_workflow_data = _as_workflow_dict(recipe_data)
|
||||
|
||||
hidden_saved_wf = _as_workflow_dict(saved_workflow_data)
|
||||
|
||||
# WorkflowManager should prefer live connected workflow_data when present,
|
||||
# then fall back to local serialized state.
|
||||
resolved_workflow_data = live_workflow_data if isinstance(live_workflow_data, dict) else None
|
||||
resolved_workflow_data = ensure_v2_recipe_data(live_workflow_data, source="RecipeManager") if isinstance(live_workflow_data, dict) else None
|
||||
if resolved_workflow_data is None:
|
||||
resolved_workflow_data = hidden_saved_wf
|
||||
resolved_workflow_data = ensure_v2_recipe_data(hidden_saved_wf, source="RecipeManager") if isinstance(hidden_saved_wf, dict) else None
|
||||
if resolved_workflow_data is None and isinstance(stored_prompt_wf, dict):
|
||||
resolved_workflow_data = stored_prompt_wf
|
||||
resolved_workflow_data = ensure_v2_recipe_data(stored_prompt_wf, source="RecipeManager")
|
||||
|
||||
# Prompt-only fallback: allow RecipeManager to open saved PMA prompts
|
||||
# (prompt + lora stacks) by synthesizing minimal v2 recipe_data.
|
||||
if resolved_workflow_data is None and isinstance(prompt_entry, dict):
|
||||
prompt_text = str(prompt_entry.get("prompt", "") or text or "")
|
||||
negative_text = str(prompt_entry.get("negative_prompt", "") or "")
|
||||
prompt_loras_a = prompt_entry.get("loras_a", []) if isinstance(prompt_entry.get("loras_a"), list) else []
|
||||
prompt_loras_b = prompt_entry.get("loras_b", []) if isinstance(prompt_entry.get("loras_b"), list) else []
|
||||
|
||||
has_prompt_payload = bool(
|
||||
prompt_text.strip() or
|
||||
negative_text.strip() or
|
||||
len(prompt_loras_a) > 0 or
|
||||
len(prompt_loras_b) > 0
|
||||
)
|
||||
|
||||
if has_prompt_payload:
|
||||
resolved_workflow_data = build_v2_recipe_data_from_prompt(
|
||||
prompt_text=prompt_text,
|
||||
negative_prompt=negative_text,
|
||||
loras_a=prompt_loras_a,
|
||||
loras_b=prompt_loras_b,
|
||||
source="RecipeManager",
|
||||
)
|
||||
|
||||
wf = resolved_workflow_data if isinstance(resolved_workflow_data, dict) else {}
|
||||
wf_model_a = get_v2_model_block(wf, "model_a") or {}
|
||||
wf_model_b = get_v2_model_block(wf, "model_b") or {}
|
||||
wf_has_model_b = isinstance(get_v2_model_block(wf, "model_b"), dict)
|
||||
incoming_wf = live_workflow_data if isinstance(live_workflow_data, dict) else None
|
||||
output_text = (wf.get("positive_prompt", "") or text or "")
|
||||
incoming_has_model_b = None
|
||||
if isinstance(incoming_wf, dict):
|
||||
incoming_v2 = ensure_v2_recipe_data(incoming_wf, source="RecipeManager")
|
||||
incoming_models = incoming_v2.get("models", {}) if isinstance(incoming_v2.get("models"), dict) else {}
|
||||
incoming_has_model_b = isinstance(incoming_models.get("model_b"), dict)
|
||||
output_text = (wf_model_a.get("positive_prompt", "") or text or "")
|
||||
generated_thumbnail = _image_to_base64_thumbnail(wf.get("IMAGE")) if isinstance(wf, dict) else None
|
||||
incoming_thumbnail = _image_to_base64_thumbnail(incoming_wf.get("IMAGE")) if isinstance(incoming_wf, dict) else None
|
||||
workflow_thumbnail = incoming_thumbnail if isinstance(incoming_thumbnail, str) and incoming_thumbnail else (
|
||||
@@ -179,25 +212,39 @@ class WorkflowManager(PromptManagerAdvanced):
|
||||
|
||||
# Build preset stacks from saved toggle state.
|
||||
preset_stack_a = self._build_stack_from_toggle(loras_a_toggle) if loras_a_toggle else []
|
||||
preset_stack_b = self._build_stack_from_toggle(loras_b_toggle) if loras_b_toggle else []
|
||||
preset_stack_b = self._build_stack_from_toggle(loras_b_toggle) if (wf_has_model_b and loras_b_toggle) else []
|
||||
|
||||
all_preset_loras_a = self._get_all_loras_from_toggle(loras_a_toggle) if loras_a_toggle else []
|
||||
all_preset_loras_b = self._get_all_loras_from_toggle(loras_b_toggle) if loras_b_toggle else []
|
||||
all_preset_loras_b = self._get_all_loras_from_toggle(loras_b_toggle) if (wf_has_model_b and loras_b_toggle) else []
|
||||
|
||||
wf_loras_a = [
|
||||
(lora["name"], lora.get("model_strength", 1.0), lora.get("clip_strength", 1.0))
|
||||
for lora in wf.get("loras_a", [])
|
||||
if isinstance(lora, dict) and lora.get("name")
|
||||
]
|
||||
wf_loras_b = [
|
||||
(lora["name"], lora.get("model_strength", 1.0), lora.get("clip_strength", 1.0))
|
||||
for lora in wf.get("loras_b", [])
|
||||
for lora in wf_model_a.get("loras", [])
|
||||
if isinstance(lora, dict) and lora.get("name")
|
||||
]
|
||||
wf_loras_b = []
|
||||
if wf_has_model_b:
|
||||
wf_loras_b = [
|
||||
(lora["name"], lora.get("model_strength", 1.0), lora.get("clip_strength", 1.0))
|
||||
for lora in wf_model_b.get("loras", [])
|
||||
if isinstance(lora, dict) and lora.get("name")
|
||||
]
|
||||
|
||||
# WorkflowManager is workflow-data centric: workflow LoRAs are base, preset toggles merge in.
|
||||
merged_stack_a = self._merge_lora_stacks(wf_loras_a, preset_stack_a) if (wf_loras_a or preset_stack_a) else []
|
||||
merged_stack_b = self._merge_lora_stacks(wf_loras_b, preset_stack_b) if (wf_loras_b or preset_stack_b) else []
|
||||
# WorkflowManager is workflow-data centric: preserve connected workflow order
|
||||
# and use toggles only to modify active/strength state for those entries.
|
||||
# Fallback to preset stack only when no workflow LoRAs are present.
|
||||
if wf_loras_a:
|
||||
merged_stack_a = list(wf_loras_a)
|
||||
else:
|
||||
merged_stack_a = list(preset_stack_a) if preset_stack_a else []
|
||||
|
||||
if wf_has_model_b:
|
||||
if wf_loras_b:
|
||||
merged_stack_b = list(wf_loras_b)
|
||||
else:
|
||||
merged_stack_b = list(preset_stack_b) if preset_stack_b else []
|
||||
else:
|
||||
merged_stack_b = []
|
||||
|
||||
processed_stack_a = self._process_lora_toggle(merged_stack_a, loras_a_toggle)
|
||||
processed_stack_b = self._process_lora_toggle(merged_stack_b, loras_b_toggle)
|
||||
@@ -215,7 +262,7 @@ class WorkflowManager(PromptManagerAdvanced):
|
||||
"use_prompt_input": False,
|
||||
"use_workflow_data": True,
|
||||
"prompt_input": "",
|
||||
"workflow_data": to_json_safe_workflow_data(incoming_wf) if isinstance(incoming_wf, dict) else (
|
||||
"workflow_data": to_json_safe_workflow_data(ensure_v2_recipe_data(recipe_data, source="RecipeManager")) if isinstance(recipe_data, dict) else (
|
||||
to_json_safe_workflow_data(resolved_workflow_data) if isinstance(resolved_workflow_data, dict) else None
|
||||
),
|
||||
"loras_a": loras_a_display,
|
||||
@@ -239,33 +286,75 @@ class WorkflowManager(PromptManagerAdvanced):
|
||||
},
|
||||
})
|
||||
|
||||
out_workflow_data = dict(resolved_workflow_data) if isinstance(resolved_workflow_data, dict) else {}
|
||||
out_workflow_data["positive_prompt"] = output_text
|
||||
out_workflow_data["loras_a"] = [
|
||||
out_workflow_data = ensure_v2_recipe_data(
|
||||
dict(resolved_workflow_data) if isinstance(resolved_workflow_data, dict) else {},
|
||||
source="RecipeManager",
|
||||
)
|
||||
|
||||
models_out = out_workflow_data.get("models", {})
|
||||
if not isinstance(models_out, dict):
|
||||
models_out = {}
|
||||
out_workflow_data["models"] = models_out
|
||||
|
||||
has_existing_model_b = isinstance(models_out.get("model_b"), dict)
|
||||
model_a_out = models_out.get("model_a") if isinstance(models_out.get("model_a"), dict) else {}
|
||||
model_b_out = models_out.get("model_b") if isinstance(models_out.get("model_b"), dict) else {}
|
||||
|
||||
model_a_out["positive_prompt"] = output_text
|
||||
model_a_out["loras"] = [
|
||||
{
|
||||
"name": lora.get("name", ""),
|
||||
"path": lora.get("path", lora.get("name", "")),
|
||||
"model_strength": lora.get("model_strength", lora.get("strength", 1.0)),
|
||||
"clip_strength": lora.get("clip_strength", lora.get("strength", 1.0)),
|
||||
"active": lora.get("active", True),
|
||||
"available": lora.get("available", True),
|
||||
"found": lora.get("found", lora.get("available", True)),
|
||||
}
|
||||
for lora in loras_a_display
|
||||
if isinstance(lora, dict) and lora.get("name")
|
||||
]
|
||||
out_workflow_data["loras_b"] = [
|
||||
model_b_loras = [
|
||||
{
|
||||
"name": lora.get("name", ""),
|
||||
"path": lora.get("path", lora.get("name", "")),
|
||||
"model_strength": lora.get("model_strength", lora.get("strength", 1.0)),
|
||||
"clip_strength": lora.get("clip_strength", lora.get("strength", 1.0)),
|
||||
"active": lora.get("active", True),
|
||||
"available": lora.get("available", True),
|
||||
"found": lora.get("found", lora.get("available", True)),
|
||||
}
|
||||
for lora in loras_b_display
|
||||
if isinstance(lora, dict) and lora.get("name")
|
||||
]
|
||||
out_workflow_data["_source"] = "WorkflowManager"
|
||||
|
||||
models_out["model_a"] = model_a_out
|
||||
model_a_name = str(model_a_out.get("model", "") or "").strip()
|
||||
model_b_name = str(model_b_out.get("model", "") or "").strip()
|
||||
model_b_pos = str(model_b_out.get("positive_prompt", "") or "").strip()
|
||||
model_b_neg = str(model_b_out.get("negative_prompt", "") or "").strip()
|
||||
model_b_has_runtime = any(
|
||||
model_b_out.get(k) is not None
|
||||
for k in ("MODEL", "CLIP", "VAE", "POSITIVE", "NEGATIVE")
|
||||
)
|
||||
# model_b is considered meaningful when it has authored content
|
||||
# that is not just a mirrored default of model_a.
|
||||
keep_model_b = bool(model_b_loras) or bool(model_b_pos) or bool(model_b_neg) or model_b_has_runtime
|
||||
if model_b_name and model_b_name != model_a_name:
|
||||
keep_model_b = True
|
||||
|
||||
if (has_existing_model_b and model_b_name and model_b_name == model_a_name and
|
||||
not model_b_loras and not model_b_pos and not model_b_neg and not model_b_has_runtime):
|
||||
keep_model_b = False
|
||||
|
||||
# Canonical rule: if incoming recipe_data had no model_b, scrub model_b from output.
|
||||
if incoming_has_model_b is False:
|
||||
keep_model_b = False
|
||||
|
||||
if keep_model_b:
|
||||
model_b_out["loras"] = model_b_loras
|
||||
models_out["model_b"] = model_b_out
|
||||
else:
|
||||
models_out.pop("model_b", None)
|
||||
out_workflow_data["_source"] = "RecipeManager"
|
||||
|
||||
return (out_workflow_data,)
|
||||
|
||||
@@ -47,7 +47,7 @@ def _load_gguf_unet(unet_path):
|
||||
gguf = _get_gguf_module()
|
||||
if gguf is None:
|
||||
raise RuntimeError(
|
||||
"[WorkflowModelLoader] This workflow requires ComfyUI-GGUF, "
|
||||
"[RecipeModelLoader] This workflow requires ComfyUI-GGUF, "
|
||||
"but UnetLoaderGGUF is not available."
|
||||
)
|
||||
|
||||
@@ -67,7 +67,7 @@ def _load_gguf_unet(unet_path):
|
||||
|
||||
if model is None:
|
||||
raise RuntimeError(
|
||||
f"[WorkflowModelLoader] Could not detect model type of GGUF: {unet_path}"
|
||||
f"[RecipeModelLoader] Could not detect model type of GGUF: {unet_path}"
|
||||
)
|
||||
|
||||
model = gguf["GGUFModelPatcher"].clone(model)
|
||||
@@ -110,6 +110,44 @@ def _build_model_options(weight_dtype):
|
||||
return model_options
|
||||
|
||||
|
||||
def _is_runtime_object(value):
|
||||
"""True when value looks like a live Comfy runtime object, not workflow metadata."""
|
||||
return value is not None and not isinstance(value, (str, int, float, bool, list, tuple, dict))
|
||||
|
||||
|
||||
def _extract_preloaded_assets(workflow_data, selected_model_slot):
|
||||
"""
|
||||
Reuse already-loaded assets carried in workflow_data (e.g. from RecipeRenderer).
|
||||
Returns (model, clip, vae) or None when passthrough is unavailable.
|
||||
"""
|
||||
if not isinstance(workflow_data, dict):
|
||||
return None
|
||||
|
||||
# v2 recipe_data: runtime assets are model-scoped.
|
||||
if int(workflow_data.get("version", 0) or 0) >= 2 and isinstance(workflow_data.get("models"), dict):
|
||||
block = workflow_data.get("models", {}).get(selected_model_slot)
|
||||
if isinstance(block, dict):
|
||||
model = block.get("MODEL")
|
||||
clip = block.get("CLIP")
|
||||
vae = block.get("VAE")
|
||||
if _is_runtime_object(model) and _is_runtime_object(clip) and _is_runtime_object(vae):
|
||||
return (model, clip, vae)
|
||||
|
||||
model_key = "MODEL_B" if selected_model_slot == "model_b" else "MODEL_A"
|
||||
model = workflow_data.get(model_key)
|
||||
clip = workflow_data.get("CLIP")
|
||||
vae = workflow_data.get("VAE")
|
||||
|
||||
if not _is_runtime_object(model):
|
||||
return None
|
||||
if not _is_runtime_object(clip):
|
||||
return None
|
||||
if not _is_runtime_object(vae):
|
||||
return None
|
||||
|
||||
return (model, clip, vae)
|
||||
|
||||
|
||||
def _resolve_path(name, folder_key_candidates):
|
||||
"""
|
||||
Resolve a model filename against one or more Comfy folder keys.
|
||||
@@ -186,7 +224,7 @@ def _load_checkpoint_by_name(ckpt_name):
|
||||
"""
|
||||
ckpt_path = _resolve_path(ckpt_name, ["checkpoints", "diffusion_models", "unet"])
|
||||
if not ckpt_path:
|
||||
raise FileNotFoundError(f"[WorkflowModelLoader] Checkpoint not found: {ckpt_name}")
|
||||
raise FileNotFoundError(f"[RecipeModelLoader] Checkpoint not found: {ckpt_name}")
|
||||
|
||||
out = comfy.sd.load_checkpoint_guess_config(
|
||||
ckpt_path,
|
||||
@@ -206,7 +244,7 @@ def _load_diffusion_model_by_name(model_name, weight_dtype="default"):
|
||||
"""
|
||||
model_path = _resolve_path(model_name, ["diffusion_models", "unet", "unet_gguf", "checkpoints"])
|
||||
if not model_path:
|
||||
raise FileNotFoundError(f"[WorkflowModelLoader] Diffusion model not found: {model_name}")
|
||||
raise FileNotFoundError(f"[RecipeModelLoader] Diffusion model not found: {model_name}")
|
||||
|
||||
if model_name.lower().endswith(".gguf"):
|
||||
return _load_gguf_unet(model_path)
|
||||
@@ -214,7 +252,7 @@ def _load_diffusion_model_by_name(model_name, weight_dtype="default"):
|
||||
model_options = _build_model_options(weight_dtype)
|
||||
model = comfy.sd.load_diffusion_model(model_path, model_options=model_options)
|
||||
if model is None:
|
||||
raise RuntimeError(f"[WorkflowModelLoader] Could not load diffusion model: {model_name}")
|
||||
raise RuntimeError(f"[RecipeModelLoader] Could not load diffusion model: {model_name}")
|
||||
return model
|
||||
|
||||
|
||||
@@ -224,7 +262,7 @@ def _load_vae_by_name(vae_name):
|
||||
"""
|
||||
vae_path = _resolve_path(vae_name, ["vae", "checkpoints"])
|
||||
if not vae_path:
|
||||
raise FileNotFoundError(f"[WorkflowModelLoader] VAE not found: {vae_name}")
|
||||
raise FileNotFoundError(f"[RecipeModelLoader] VAE not found: {vae_name}")
|
||||
|
||||
sd = comfy.utils.load_torch_file(vae_path)
|
||||
return comfy.sd.VAE(sd=sd)
|
||||
@@ -242,7 +280,7 @@ def _load_clip_by_names(clip_names, clip_type=""):
|
||||
for name in clip_names:
|
||||
clip_path = _resolve_path(name, ["text_encoders", "clip", "checkpoints"])
|
||||
if not clip_path:
|
||||
raise FileNotFoundError(f"[WorkflowModelLoader] CLIP not found: {name}")
|
||||
raise FileNotFoundError(f"[RecipeModelLoader] CLIP not found: {name}")
|
||||
clip_paths.append(clip_path)
|
||||
|
||||
clip_type = (clip_type or "").strip().lower()
|
||||
@@ -274,21 +312,21 @@ def _load_clip_by_names(clip_names, clip_type=""):
|
||||
|
||||
class WorkflowModelLoader:
|
||||
CATEGORY = "Prompt Manager"
|
||||
RETURN_TYPES = ("MODEL", "CLIP", "VAE", "STRING")
|
||||
RETURN_NAMES = ("model", "clip", "vae", "model_name")
|
||||
RETURN_TYPES = ("MODEL", "CLIP", "VAE")
|
||||
RETURN_NAMES = ("model", "clip", "vae")
|
||||
FUNCTION = "get_model"
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {
|
||||
"workflow_data": ("WORKFLOW_DATA", {
|
||||
"tooltip": "Workflow data containing model name strings to load.",
|
||||
"recipe_data": ("RECIPE_DATA", {
|
||||
"tooltip": "Recipe data containing model name strings to load.",
|
||||
"forceInput": True,
|
||||
}),
|
||||
"model": (["model_a", "model_b"], {
|
||||
"model": (["model_a", "model_b", "model_c", "model_d"], {
|
||||
"default": "model_a",
|
||||
"tooltip": "Which model slot to load from workflow_data.",
|
||||
"tooltip": "Which model slot to load from recipe_data.",
|
||||
}),
|
||||
"weight_dtype": (WEIGHT_DTYPE_OPTIONS, {
|
||||
"default": "default",
|
||||
@@ -297,28 +335,56 @@ class WorkflowModelLoader:
|
||||
}
|
||||
}
|
||||
|
||||
def get_model(self, workflow_data, model="model_a", weight_dtype="default"):
|
||||
spec = self._normalize_spec(workflow_data)
|
||||
def get_model(self, recipe_data, model="model_a", weight_dtype="default"):
|
||||
workflow_data = recipe_data
|
||||
selected_model_slot = model
|
||||
if selected_model_slot not in ("model_a", "model_b"):
|
||||
if selected_model_slot not in ("model_a", "model_b", "model_c", "model_d"):
|
||||
selected_model_slot = "model_a"
|
||||
|
||||
# Initialize selected slot before normalization so v2 parsing can
|
||||
# safely resolve per-slot loader/clip/vae fields.
|
||||
self._model_key = selected_model_slot
|
||||
self._weight_dtype = weight_dtype
|
||||
|
||||
passthrough_assets = _extract_preloaded_assets(workflow_data, selected_model_slot)
|
||||
|
||||
spec = self._normalize_spec(workflow_data)
|
||||
loader_type = spec.get("loader_type", "").lower()
|
||||
selected_name = spec.get(selected_model_slot, "")
|
||||
selected_display_name = _short_display_name(selected_name)
|
||||
|
||||
if passthrough_assets is not None:
|
||||
model_obj, clip_obj, vae_obj = passthrough_assets
|
||||
clip_names = spec.get("clip") or []
|
||||
vae_name = spec.get("vae", "")
|
||||
ui_info = {
|
||||
"model": selected_model_slot,
|
||||
"model_name": selected_display_name or _short_display_name(spec.get("model_name", "")),
|
||||
"loader_type": loader_type or "passthrough",
|
||||
"model_kind": "passthrough",
|
||||
"vae_name": vae_name,
|
||||
"clip_names": clip_names,
|
||||
"status": "ok",
|
||||
"error_message": "",
|
||||
"missing_name": "",
|
||||
"uses_checkpoint_vae": False,
|
||||
"uses_checkpoint_clip": False,
|
||||
}
|
||||
return {
|
||||
"ui": {"workflow_model_loader_info": [ui_info]},
|
||||
"result": (model_obj, clip_obj, vae_obj),
|
||||
}
|
||||
|
||||
if loader_type == "checkpoint":
|
||||
core_result = self._load_checkpoint_mode(spec)
|
||||
elif loader_type in ("unet", "diffusion"):
|
||||
core_result = self._load_unet_mode(spec)
|
||||
else:
|
||||
raise ValueError(
|
||||
f"[WorkflowModelLoader] Unsupported loader_type: {spec.get('loader_type')}"
|
||||
f"[RecipeModelLoader] Unsupported loader_type: {spec.get('loader_type')}"
|
||||
)
|
||||
|
||||
result = (*core_result, selected_display_name)
|
||||
result = core_result
|
||||
|
||||
clip_names = spec.get("clip") or []
|
||||
vae_name = spec.get("vae", "")
|
||||
@@ -343,6 +409,7 @@ class WorkflowModelLoader:
|
||||
"uses_checkpoint_vae": (loader_type == "checkpoint" and not vae_name),
|
||||
"uses_checkpoint_clip": (loader_type == "checkpoint" and len(clip_names) == 0),
|
||||
}
|
||||
|
||||
return {
|
||||
"ui": {"workflow_model_loader_info": [ui_info]},
|
||||
"result": result,
|
||||
@@ -350,17 +417,50 @@ class WorkflowModelLoader:
|
||||
|
||||
@staticmethod
|
||||
def _is_placeholder(value):
|
||||
"""True for display-only strings like '(from checkpoint)', '(none)', etc."""
|
||||
"""True for display-only strings like '(Default)', '(none)', etc."""
|
||||
return isinstance(value, str) and value.startswith("(")
|
||||
|
||||
def _normalize_spec(self, spec):
|
||||
spec = dict(spec or {})
|
||||
spec["model_a"] = (spec.get("model_a") or "").strip()
|
||||
spec["model_b"] = (spec.get("model_b") or "").strip()
|
||||
spec["model_c"] = (spec.get("model_c") or "").strip()
|
||||
spec["model_d"] = (spec.get("model_d") or "").strip()
|
||||
spec["loader_type"] = (spec.get("loader_type") or "").strip()
|
||||
spec["clip_type"] = (spec.get("clip_type") or "").strip()
|
||||
|
||||
# VAE / CLIP: placeholders like '(from checkpoint)' mean "use what
|
||||
# v2 recipe_data stores model config in per-slot blocks.
|
||||
if int(spec.get("version", 0) or 0) >= 2 and isinstance(spec.get("models"), dict):
|
||||
models = spec.get("models", {})
|
||||
for key in ("model_a", "model_b", "model_c", "model_d"):
|
||||
block = models.get(key)
|
||||
if isinstance(block, dict):
|
||||
model_name = (block.get("model") or "").strip() if isinstance(block.get("model"), str) else ""
|
||||
if model_name:
|
||||
spec[key] = model_name
|
||||
|
||||
selected_key = getattr(self, "_model_key", "model_a")
|
||||
if selected_key not in ("model_a", "model_b", "model_c", "model_d"):
|
||||
selected_key = "model_a"
|
||||
selected_block = models.get(selected_key) if isinstance(models.get(selected_key), dict) else None
|
||||
if isinstance(selected_block, dict):
|
||||
loader_type = (selected_block.get("loader_type") or "").strip() if isinstance(selected_block.get("loader_type"), str) else ""
|
||||
clip_type = (selected_block.get("clip_type") or "").strip() if isinstance(selected_block.get("clip_type"), str) else ""
|
||||
vae_name = (selected_block.get("vae") or "").strip() if isinstance(selected_block.get("vae"), str) else ""
|
||||
clip_names = selected_block.get("clip")
|
||||
|
||||
if loader_type:
|
||||
spec["loader_type"] = loader_type
|
||||
if clip_type:
|
||||
spec["clip_type"] = clip_type
|
||||
if vae_name:
|
||||
spec["vae"] = vae_name
|
||||
if isinstance(clip_names, list):
|
||||
spec["clip"] = clip_names
|
||||
elif isinstance(clip_names, str) and clip_names.strip():
|
||||
spec["clip"] = [clip_names.strip()]
|
||||
|
||||
# VAE / CLIP: placeholders like '(Default)' mean "use what
|
||||
# the checkpoint already provides" — normalise to empty.
|
||||
vae = (spec.get("vae") or "").strip()
|
||||
spec["vae"] = "" if self._is_placeholder(vae) else vae
|
||||
@@ -0,0 +1,184 @@
|
||||
"""
|
||||
Recipe Model Picker
|
||||
|
||||
Builder-style model selector that outputs structured model_data for Recipe Relay.
|
||||
"""
|
||||
|
||||
import folder_paths
|
||||
from ..py.workflow_families import (
|
||||
MODEL_FAMILIES,
|
||||
get_all_family_labels,
|
||||
get_model_family,
|
||||
get_compatible_families,
|
||||
list_compatible_vaes,
|
||||
list_compatible_clips,
|
||||
)
|
||||
|
||||
|
||||
DEFAULT_ASSET = "(Default)"
|
||||
|
||||
|
||||
def _gather_models(folder_names):
|
||||
gathered = []
|
||||
seen = set()
|
||||
for folder_name in folder_names:
|
||||
try:
|
||||
for model_name in folder_paths.get_filename_list(folder_name):
|
||||
if model_name not in seen:
|
||||
seen.add(model_name)
|
||||
gathered.append(model_name)
|
||||
except Exception:
|
||||
continue
|
||||
return gathered
|
||||
|
||||
|
||||
def _list_models_for_family(family_key):
|
||||
family_key = str(family_key or "").strip()
|
||||
if not family_key:
|
||||
return sorted(_gather_models(["checkpoints", "diffusion_models", "unet", "unet_gguf"]))
|
||||
|
||||
compat = get_compatible_families(family_key)
|
||||
compat_specs = [MODEL_FAMILIES.get(fam, {}) for fam in compat]
|
||||
|
||||
preferred_folders = []
|
||||
for spec in compat_specs:
|
||||
for folder_name in (spec.get("model_folders", []) or []):
|
||||
if folder_name and folder_name not in preferred_folders:
|
||||
preferred_folders.append(folder_name)
|
||||
|
||||
if preferred_folders:
|
||||
model_folders = preferred_folders
|
||||
elif family_key == "sdxl":
|
||||
model_folders = ["checkpoints"]
|
||||
else:
|
||||
model_folders = ["diffusion_models", "unet", "unet_gguf"]
|
||||
|
||||
all_models = _gather_models(model_folders)
|
||||
models = [m for m in all_models if get_model_family(m) in compat]
|
||||
|
||||
if not models:
|
||||
compat_has_checkpoint = any(spec.get("checkpoint", False) for spec in compat_specs if spec)
|
||||
if compat_has_checkpoint and family_key == "sdxl":
|
||||
models = _gather_models(["checkpoints"])
|
||||
else:
|
||||
folder_patterns = []
|
||||
name_patterns = []
|
||||
for fam in compat:
|
||||
spec = MODEL_FAMILIES.get(fam, {})
|
||||
folder_patterns.extend([
|
||||
p.lower().replace("\\", "/").strip("/")
|
||||
for p in spec.get("folders", []) if p
|
||||
])
|
||||
name_patterns.extend([p.lower() for p in spec.get("names", []) if p])
|
||||
|
||||
relaxed = []
|
||||
for model_name in all_models:
|
||||
model_lower = model_name.lower().replace("\\", "/")
|
||||
folder_hit = any(fp and fp in model_lower for fp in folder_patterns)
|
||||
name_hit = any(pat and pat in model_lower for pat in name_patterns)
|
||||
if folder_hit or name_hit:
|
||||
relaxed.append(model_name)
|
||||
models = relaxed
|
||||
|
||||
if family_key == "wan_video_i2v" and models:
|
||||
i2v_t2v = []
|
||||
for model_name in models:
|
||||
lower_name = model_name.lower().replace("\\", "/")
|
||||
if ("i2v" in lower_name) or ("t2v" in lower_name):
|
||||
i2v_t2v.append(model_name)
|
||||
if i2v_t2v:
|
||||
models = i2v_t2v
|
||||
|
||||
return sorted(models)
|
||||
|
||||
|
||||
def _family_maps():
|
||||
labels = dict(get_all_family_labels() or {})
|
||||
labels.pop("ltxv", None)
|
||||
keys = sorted(labels.keys(), key=lambda k: (k != "sdxl", labels.get(k, k).lower()))
|
||||
label_to_key = {labels[k]: k for k in keys}
|
||||
type_values = [labels[k] for k in keys]
|
||||
return labels, label_to_key, type_values
|
||||
|
||||
|
||||
def _family_key_from_type_value(type_value):
|
||||
labels, label_to_key, _ = _family_maps()
|
||||
value = str(type_value or "").strip()
|
||||
if value in labels:
|
||||
return value
|
||||
if value in label_to_key:
|
||||
return label_to_key[value]
|
||||
return "sdxl"
|
||||
|
||||
class RecipeModelPicker:
|
||||
"""Select family/model/vae/clip and output a single model_data payload."""
|
||||
|
||||
@classmethod
|
||||
def _sync_inputs(cls):
|
||||
labels, _label_to_key, type_values = _family_maps()
|
||||
default_family = "sdxl" if "sdxl" in labels else (next(iter(labels.keys()), "sdxl"))
|
||||
default_type = labels.get(default_family, "SDXL")
|
||||
|
||||
model_values = _list_models_for_family(default_family)
|
||||
if not model_values:
|
||||
model_values = [""]
|
||||
|
||||
vae_values = [DEFAULT_ASSET] + list_compatible_vaes(default_family)
|
||||
clip_values = [DEFAULT_ASSET] + list_compatible_clips(default_family)
|
||||
|
||||
cls._TYPE_VALUES = tuple(type_values or ["SDXL"])
|
||||
cls._MODEL_VALUES = tuple(model_values)
|
||||
cls._VAE_VALUES = tuple(vae_values)
|
||||
cls._CLIP_VALUES = tuple(clip_values)
|
||||
cls._DEFAULT_TYPE = default_type
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
cls._sync_inputs()
|
||||
return {
|
||||
"required": {
|
||||
"type": (cls._TYPE_VALUES, {"default": cls._DEFAULT_TYPE, "tooltip": "Model family (Builder type)."}),
|
||||
"model": (cls._MODEL_VALUES, {"tooltip": "Primary model for selected family."}),
|
||||
"vae": (cls._VAE_VALUES, {"default": DEFAULT_ASSET, "tooltip": "Optional VAE override; (Default) keeps family defaults."}),
|
||||
"clip": (cls._CLIP_VALUES, {"default": DEFAULT_ASSET, "tooltip": "Optional CLIP override; (Default) keeps family defaults."}),
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("ANY",)
|
||||
RETURN_NAMES = ("model_data",)
|
||||
FUNCTION = "pick"
|
||||
CATEGORY = "Prompt Manager"
|
||||
DESCRIPTION = "Builder-style Type/Model/VAE/CLIP selector that outputs model_data for Recipe Relay."
|
||||
|
||||
def pick(self, type, model, vae, clip):
|
||||
family = _family_key_from_type_value(type)
|
||||
family_spec = MODEL_FAMILIES.get(family, {})
|
||||
|
||||
selected_model = str(model or "").strip()
|
||||
if selected_model:
|
||||
detected = get_model_family(selected_model)
|
||||
if detected and not family:
|
||||
family = detected
|
||||
family_spec = MODEL_FAMILIES.get(family, {})
|
||||
|
||||
loader_type = "checkpoint" if family_spec.get("checkpoint", False) else "unet"
|
||||
clip_type = family_spec.get("clip_type", "")
|
||||
|
||||
selected_vae = str(vae or "").strip()
|
||||
if selected_vae == DEFAULT_ASSET:
|
||||
selected_vae = ""
|
||||
|
||||
selected_clip = str(clip or "").strip()
|
||||
if selected_clip == DEFAULT_ASSET:
|
||||
selected_clip = ""
|
||||
|
||||
model_data = {
|
||||
"model": selected_model,
|
||||
"family": family,
|
||||
"loader_type": loader_type,
|
||||
"clip_type": clip_type,
|
||||
"vae": selected_vae,
|
||||
"clip": [selected_clip] if selected_clip else [],
|
||||
}
|
||||
|
||||
return (model_data,)
|
||||
@@ -0,0 +1,825 @@
|
||||
"""
|
||||
ComfyUI Workflow Bridge - Pure passthrough node.
|
||||
Unpacks recipe_data into individual typed outputs.
|
||||
Any connected optional input overrides the corresponding field before output.
|
||||
Models (MODEL/CLIP/VAE) are passed through only and cached on the selected model block.
|
||||
Use RecipeModelLoader for loading from authored model names.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import folder_paths
|
||||
import nodes
|
||||
import comfy.samplers
|
||||
from ..py.lora_utils import resolve_lora_path, get_lora_relative_path, strip_lora_extension
|
||||
from ..py.workflow_extraction_utils import resolve_model_name
|
||||
from ..py.workflow_families import get_model_family, MODEL_FAMILIES
|
||||
|
||||
|
||||
MODEL_EXTENSIONS = (".safetensors", ".ckpt", ".pt", ".pth", ".gguf")
|
||||
|
||||
|
||||
def _strip_model_ext(name):
|
||||
base = os.path.basename(str(name or "").replace("\\", "/"))
|
||||
lower = base.lower()
|
||||
for ext in MODEL_EXTENSIONS:
|
||||
if lower.endswith(ext):
|
||||
return base[:-len(ext)]
|
||||
return os.path.splitext(base)[0]
|
||||
|
||||
|
||||
def _resolve_rel_path(raw_name, folder_keys):
|
||||
"""Resolve a model-like name to a relative Comfy path in the provided folder keys."""
|
||||
if not raw_name:
|
||||
return "", False
|
||||
|
||||
raw = str(raw_name).strip().replace("\\", "/")
|
||||
if not raw:
|
||||
return "", False
|
||||
|
||||
base = os.path.basename(raw).lower()
|
||||
base_no_ext = _strip_model_ext(base).lower()
|
||||
|
||||
for key in folder_keys:
|
||||
try:
|
||||
file_list = folder_paths.get_filename_list(key)
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
for rel in file_list:
|
||||
rel_norm = rel.replace("\\", "/")
|
||||
if rel_norm == raw:
|
||||
return rel, True
|
||||
|
||||
rel_base = os.path.basename(rel_norm).lower()
|
||||
if rel_base == base:
|
||||
return rel, True
|
||||
|
||||
if _strip_model_ext(rel_base).lower() == base_no_ext:
|
||||
return rel, True
|
||||
|
||||
return os.path.basename(raw), False
|
||||
|
||||
|
||||
def _get_live_ksampler_combo_types():
|
||||
"""Mirror the active KSampler enum sockets to avoid stale type mismatches."""
|
||||
default_samplers = comfy.samplers.KSampler.SAMPLERS
|
||||
default_schedulers = comfy.samplers.KSampler.SCHEDULERS
|
||||
try:
|
||||
from nodes import KSampler as CoreKSampler
|
||||
required = CoreKSampler.INPUT_TYPES().get("required", {})
|
||||
samplers = required.get("sampler_name", (default_samplers,))[0]
|
||||
schedulers = required.get("scheduler", (default_schedulers,))[0]
|
||||
return samplers, schedulers
|
||||
except Exception:
|
||||
return default_samplers, default_schedulers
|
||||
|
||||
|
||||
def _get_live_loader_combo_types():
|
||||
"""Mirror active loader combo socket types so Relay connects to core load nodes."""
|
||||
def _from_node(node_names, key, fallback):
|
||||
for node_name in node_names:
|
||||
try:
|
||||
cls = nodes.NODE_CLASS_MAPPINGS.get(node_name)
|
||||
if cls is None:
|
||||
continue
|
||||
required = cls.INPUT_TYPES().get("required", {})
|
||||
combo = required.get(key)
|
||||
if isinstance(combo, tuple) and len(combo) >= 1:
|
||||
return combo[0]
|
||||
except Exception:
|
||||
continue
|
||||
return fallback
|
||||
|
||||
ckpt_enum = _from_node(
|
||||
["CheckpointLoaderSimple", "CheckpointLoader"],
|
||||
"ckpt_name",
|
||||
folder_paths.get_filename_list("checkpoints"),
|
||||
)
|
||||
unet_enum = _from_node(
|
||||
["UNETLoader", "UnetLoader", "DiffusionModelLoader"],
|
||||
"unet_name",
|
||||
folder_paths.get_filename_list("diffusion_models"),
|
||||
)
|
||||
vae_enum = _from_node(
|
||||
["VAELoader"],
|
||||
"vae_name",
|
||||
folder_paths.get_filename_list("vae"),
|
||||
)
|
||||
clip_enum = _from_node(
|
||||
["CLIPLoader"],
|
||||
"clip_name",
|
||||
folder_paths.get_filename_list("text_encoders"),
|
||||
)
|
||||
return ckpt_enum, unet_enum, vae_enum, clip_enum
|
||||
|
||||
|
||||
_LIVE_SAMPLERS, _LIVE_SCHEDULERS = _get_live_ksampler_combo_types()
|
||||
_LIVE_CKPTS, _LIVE_UNETS, _LIVE_VAES, _LIVE_CLIPS = _get_live_loader_combo_types()
|
||||
|
||||
|
||||
_MODEL_KEYS = ("model_a", "model_b", "model_c", "model_d")
|
||||
|
||||
|
||||
def _normalize_model_slot(value):
|
||||
key = str(value or "model_a").strip().lower()
|
||||
return key if key in _MODEL_KEYS else "model_a"
|
||||
|
||||
|
||||
def _relay_default_sampler():
|
||||
return {
|
||||
"steps": 10,
|
||||
"cfg": 5,
|
||||
"sampler_name": "euler",
|
||||
"scheduler": "simple",
|
||||
"denoise": 1.0,
|
||||
"seed": 0,
|
||||
}
|
||||
|
||||
|
||||
def _relay_default_resolution():
|
||||
return {
|
||||
"width": 512,
|
||||
"height": 512,
|
||||
"batch_size": 1,
|
||||
"length": 1,
|
||||
}
|
||||
|
||||
|
||||
def _relay_default_model_block():
|
||||
return {
|
||||
"positive_prompt": "",
|
||||
"negative_prompt": "",
|
||||
"family": "sdxl",
|
||||
"model": "",
|
||||
"loras": [],
|
||||
"clip_type": "",
|
||||
"loader_type": "",
|
||||
"vae": "",
|
||||
"clip": [],
|
||||
"sampler": _relay_default_sampler(),
|
||||
"resolution": _relay_default_resolution(),
|
||||
}
|
||||
|
||||
|
||||
def _selected_model_block(wf, model_slot, create=False):
|
||||
if not isinstance(wf.get("models"), dict):
|
||||
if not create:
|
||||
return None
|
||||
wf["models"] = {}
|
||||
|
||||
models = wf["models"]
|
||||
slot = _normalize_model_slot(model_slot)
|
||||
block = models.get(slot)
|
||||
if isinstance(block, dict):
|
||||
return block
|
||||
if not create:
|
||||
return None
|
||||
|
||||
block = dict(_relay_default_model_block())
|
||||
models[slot] = block
|
||||
return block
|
||||
|
||||
|
||||
DEFAULT_RECIPE_DATA = {
|
||||
"_source": "RecipeRelay",
|
||||
"version": 2,
|
||||
"models": {},
|
||||
}
|
||||
|
||||
|
||||
class WorkflowRelay:
|
||||
"""
|
||||
Pure passthrough bridge node.
|
||||
Unpacks recipe_data into individual typed outputs and forwards
|
||||
any connected MODEL/CLIP/VAE inputs. No model loading.
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def _sync_combo_types(cls):
|
||||
samplers, schedulers = _get_live_ksampler_combo_types()
|
||||
ckpts, unets, vaes, clips = _get_live_loader_combo_types()
|
||||
cls._SAMPLER_ENUM = samplers
|
||||
cls._SCHEDULER_ENUM = schedulers
|
||||
cls._UNET_ENUM = unets
|
||||
cls._CKPT_ENUM = ckpts
|
||||
cls._VAE_ENUM = vaes
|
||||
cls._CLIP_ENUM = clips
|
||||
cls.RETURN_TYPES = (
|
||||
"RECIPE_DATA",
|
||||
"MODEL", "CLIP", "CONDITIONING", "CONDITIONING", "VAE", "LATENT", "IMAGE", "MASK", "*", "*",
|
||||
"INT", "INT", "FLOAT",
|
||||
cls._SAMPLER_ENUM, cls._SCHEDULER_ENUM, "FLOAT",
|
||||
"STRING", "STRING",
|
||||
"LORA_STACK",
|
||||
"INT", "INT", "INT", "INT",
|
||||
"STRING", "STRING",
|
||||
cls._CKPT_ENUM, cls._UNET_ENUM, cls._VAE_ENUM, cls._CLIP_ENUM,
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
cls._sync_combo_types()
|
||||
return {
|
||||
"required": {},
|
||||
"optional": {
|
||||
"recipe_data": ("RECIPE_DATA", {"forceInput": True, "tooltip": "Optional recipe_data input. If omitted, bridge starts from an empty payload dict."}),
|
||||
"model_slot": (_MODEL_KEYS, {"default": "model_a", "tooltip": "Select which model slot to read/update in recipe_data."}),
|
||||
"model": ("MODEL", {"tooltip": "Pass-through Model"}),
|
||||
"clip": ("CLIP", {"tooltip": "Pass-through CLIP"}),
|
||||
"positive": ("CONDITIONING", {"tooltip": "Pass-through positive conditioning"}),
|
||||
"negative": ("CONDITIONING", {"tooltip": "Pass-through negative conditioning"}),
|
||||
"vae": ("VAE", {"tooltip": "Pass-through VAE"}),
|
||||
"latent": ("LATENT", {"tooltip": "Pass-through latent"}),
|
||||
"image": ("IMAGE", {"tooltip": "Pass-through image"}),
|
||||
"mask": ("MASK", {"tooltip": "Pass-through mask"}),
|
||||
"extra_1": ("*", {"tooltip": "Pass-through extra data (any type)"}),
|
||||
"extra_2": ("*", {"tooltip": "Pass-through extra data (any type)"}),
|
||||
"seed": ("INT", {"forceInput": True, "tooltip": "Override sampler seed"}),
|
||||
"steps": ("INT", {"forceInput": True, "tooltip": "Override sampling steps"}),
|
||||
"cfg": ("FLOAT", {"forceInput": True, "tooltip": "Override CFG scale"}),
|
||||
"sampler_name": (cls._SAMPLER_ENUM, {"forceInput": True, "tooltip": "Override sampler name"}),
|
||||
"scheduler": (cls._SCHEDULER_ENUM, {"forceInput": True, "tooltip": "Override scheduler"}),
|
||||
"denoise": ("FLOAT", {"forceInput": True, "tooltip": "Override denoise"}),
|
||||
"pos_prompt": ("STRING", {"forceInput": True, "tooltip": "Override positive prompt"}),
|
||||
"neg_prompt": ("STRING", {"forceInput": True, "tooltip": "Override negative prompt"}),
|
||||
"lora_stack": ("LORA_STACK", {"tooltip": "Override LoRA stack"}),
|
||||
"width": ("INT", {"forceInput": True, "tooltip": "Override width"}),
|
||||
"height": ("INT", {"forceInput": True, "tooltip": "Override height"}),
|
||||
"batch_size": ("INT", {"forceInput": True, "tooltip": "Override batch size"}),
|
||||
"length": ("INT", {"forceInput": True, "tooltip": "Override video length"}),
|
||||
"model_name": ("STRING", {"forceInput": True, "tooltip": "Optional model name/path. Resolves and writes recipe model field(s)."}),
|
||||
"family": ("STRING", {"forceInput": True, "tooltip": "Optional model family override. Writes selected slot family in recipe_data."}),
|
||||
"model_data": ("*", {"forceInput": True, "tooltip": "Optional structured model payload from Recipe Model Picker."}),
|
||||
},
|
||||
}
|
||||
|
||||
RETURN_TYPES = (
|
||||
"RECIPE_DATA",
|
||||
"MODEL", "CLIP", "CONDITIONING", "CONDITIONING", "VAE", "LATENT", "IMAGE", "MASK", "*", "*",
|
||||
"INT", "INT", "FLOAT",
|
||||
_LIVE_SAMPLERS, _LIVE_SCHEDULERS, "FLOAT",
|
||||
"STRING", "STRING",
|
||||
"LORA_STACK",
|
||||
"INT", "INT", "INT", "INT",
|
||||
"STRING", "STRING",
|
||||
_LIVE_CKPTS, _LIVE_UNETS, _LIVE_VAES, _LIVE_CLIPS,
|
||||
)
|
||||
RETURN_NAMES = (
|
||||
"recipe_data",
|
||||
"model", "clip", "positive", "negative", "vae", "latent", "image", "mask", "extra_1", "extra_2",
|
||||
"seed", "steps", "cfg",
|
||||
"sampler_name", "scheduler", "denoise",
|
||||
"pos_prompt", "neg_prompt",
|
||||
"lora_stack",
|
||||
"width", "height", "batch_size", "length",
|
||||
"model_name", "family",
|
||||
"ckpt_name", "unet_name", "vae_name", "clip_name",
|
||||
)
|
||||
FUNCTION = "unpack"
|
||||
CATEGORY = "Prompt Manager"
|
||||
DESCRIPTION = (
|
||||
"Pure passthrough bridge node. Unpacks recipe_data into individual "
|
||||
"typed outputs. Slot runtime objects are cached on the selected model block."
|
||||
)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def unpack(self, recipe_data=None, model_slot="model_a", **kwargs):
|
||||
def _normalize_lora_stack_input(raw_stack):
|
||||
rows = []
|
||||
if raw_stack is None:
|
||||
return rows
|
||||
|
||||
for entry in raw_stack:
|
||||
if not (isinstance(entry, (list, tuple)) and len(entry) >= 1):
|
||||
continue
|
||||
|
||||
raw_name = str(entry[0] or "").strip()
|
||||
if not raw_name:
|
||||
continue
|
||||
|
||||
try:
|
||||
model_strength = float(entry[1]) if len(entry) >= 2 else 1.0
|
||||
except Exception:
|
||||
model_strength = 1.0
|
||||
|
||||
try:
|
||||
clip_strength = float(entry[2]) if len(entry) >= 3 else model_strength
|
||||
except Exception:
|
||||
clip_strength = model_strength
|
||||
|
||||
rel_path, available = get_lora_relative_path(raw_name)
|
||||
if not available or not rel_path:
|
||||
# Some valid LoRA identifiers resolve via full-path lookup
|
||||
# but not via relative-name lookup. Keep availability in
|
||||
# sync with relay output path resolution behavior.
|
||||
_resolved_full, resolved_available = resolve_lora_path(raw_name)
|
||||
if resolved_available:
|
||||
available = True
|
||||
rel_path = raw_name
|
||||
|
||||
display_name = strip_lora_extension(os.path.basename(str(rel_path).replace("\\", "/")))
|
||||
rows.append({
|
||||
'name': display_name,
|
||||
'path': rel_path,
|
||||
'model_strength': model_strength,
|
||||
'clip_strength': clip_strength,
|
||||
'active': True,
|
||||
'available': bool(available),
|
||||
})
|
||||
|
||||
return rows
|
||||
|
||||
def _resolve_lora_output_path(lora_item):
|
||||
if not isinstance(lora_item, dict):
|
||||
return "", False
|
||||
|
||||
candidate = str(lora_item.get('path') or lora_item.get('name') or '').strip()
|
||||
if not candidate:
|
||||
return "", False
|
||||
|
||||
rel_path, available = get_lora_relative_path(candidate)
|
||||
if available and rel_path:
|
||||
return rel_path, True
|
||||
|
||||
# Some stored payloads contain absolute paths or names with extensions.
|
||||
# Retry with basename and extension-stripped basename before declaring missing.
|
||||
candidate_base = os.path.basename(candidate.replace("\\", "/")).strip()
|
||||
if candidate_base:
|
||||
rel_path, available = get_lora_relative_path(candidate_base)
|
||||
if available and rel_path:
|
||||
return rel_path, True
|
||||
|
||||
candidate_base_no_ext = strip_lora_extension(candidate_base)
|
||||
if candidate_base_no_ext and candidate_base_no_ext != candidate_base:
|
||||
rel_path, available = get_lora_relative_path(candidate_base_no_ext)
|
||||
if available and rel_path:
|
||||
return rel_path, True
|
||||
|
||||
_, resolved_available = resolve_lora_path(candidate)
|
||||
if resolved_available:
|
||||
rel_path, available = get_lora_relative_path(candidate)
|
||||
if available and rel_path:
|
||||
return rel_path, True
|
||||
|
||||
if candidate_base:
|
||||
_, resolved_available = resolve_lora_path(candidate_base)
|
||||
if resolved_available:
|
||||
rel_path, available = get_lora_relative_path(candidate_base)
|
||||
if available and rel_path:
|
||||
return rel_path, True
|
||||
candidate_base_no_ext = strip_lora_extension(candidate_base)
|
||||
if candidate_base_no_ext and candidate_base_no_ext != candidate_base:
|
||||
_, resolved_available = resolve_lora_path(candidate_base_no_ext)
|
||||
if resolved_available:
|
||||
rel_path, available = get_lora_relative_path(candidate_base_no_ext)
|
||||
if available and rel_path:
|
||||
return rel_path, True
|
||||
|
||||
return candidate_base or candidate, False
|
||||
|
||||
def _short_display_name(name):
|
||||
raw = str(name or "").strip()
|
||||
if not raw:
|
||||
return ""
|
||||
base = os.path.basename(raw.replace("\\", "/"))
|
||||
return os.path.splitext(base)[0]
|
||||
|
||||
# Accept both dict and JSON string
|
||||
if isinstance(recipe_data, str):
|
||||
try:
|
||||
incoming_wf = json.loads(recipe_data)
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
incoming_wf = {}
|
||||
elif isinstance(recipe_data, dict):
|
||||
incoming_wf = dict(recipe_data)
|
||||
else:
|
||||
incoming_wf = {}
|
||||
|
||||
has_incoming_data = isinstance(incoming_wf, dict) and bool(incoming_wf)
|
||||
has_slot_write_request = any([
|
||||
kwargs.get('lora_stack') is not None,
|
||||
any(kwargs.get(k) is not None for k in ('pos_prompt', 'neg_prompt')),
|
||||
any(kwargs.get(k) is not None for k in ('steps', 'seed', 'cfg', 'denoise', 'sampler_name', 'scheduler')),
|
||||
any(kwargs.get(k) is not None for k in ('width', 'height', 'batch_size', 'length')),
|
||||
isinstance(kwargs.get('model_name'), str) and kwargs.get('model_name').strip() != '',
|
||||
kwargs.get('family') is not None,
|
||||
kwargs.get('model_data') is not None,
|
||||
])
|
||||
create_block_on_write = (not has_incoming_data) or has_slot_write_request
|
||||
|
||||
# Preserve incoming recipe_data exactly when present.
|
||||
# Only fall back to the empty template when no input payload exists.
|
||||
if has_incoming_data:
|
||||
wf = dict(incoming_wf)
|
||||
if isinstance(incoming_wf.get('sampler'), dict):
|
||||
wf['sampler'] = dict(incoming_wf['sampler'])
|
||||
if isinstance(incoming_wf.get('resolution'), dict):
|
||||
wf['resolution'] = dict(incoming_wf['resolution'])
|
||||
if isinstance(incoming_wf.get('models'), dict):
|
||||
wf['models'] = {
|
||||
k: dict(v) if isinstance(v, dict) else v
|
||||
for k, v in incoming_wf.get('models', {}).items()
|
||||
}
|
||||
else:
|
||||
wf = dict(DEFAULT_RECIPE_DATA)
|
||||
wf['models'] = {}
|
||||
|
||||
# Relay now treats recipe payloads as v2-only canonical data.
|
||||
wf['version'] = 2
|
||||
if not isinstance(wf.get('models'), dict):
|
||||
wf['models'] = {}
|
||||
|
||||
selected_slot = _normalize_model_slot(model_slot)
|
||||
selected_block = _selected_model_block(wf, selected_slot, create=create_block_on_write)
|
||||
|
||||
slot_family = selected_block.get('family', '') if isinstance(selected_block, dict) else ''
|
||||
slot_model_name = selected_block.get('model', '') if isinstance(selected_block, dict) else ''
|
||||
slot_positive = selected_block.get('positive_prompt', '') if isinstance(selected_block, dict) else ''
|
||||
slot_negative = selected_block.get('negative_prompt', '') if isinstance(selected_block, dict) else ''
|
||||
slot_vae = selected_block.get('vae', '') if isinstance(selected_block, dict) else ''
|
||||
slot_clip = selected_block.get('clip', []) if isinstance(selected_block, dict) else []
|
||||
slot_loras = selected_block.get('loras', []) if isinstance(selected_block, dict) else []
|
||||
slot_sampler = selected_block.get('sampler', {}) if isinstance(selected_block, dict) and isinstance(selected_block.get('sampler'), dict) else {}
|
||||
slot_resolution = selected_block.get('resolution', {}) if isinstance(selected_block, dict) and isinstance(selected_block.get('resolution'), dict) else {}
|
||||
|
||||
sampler = dict(_relay_default_sampler())
|
||||
if isinstance(wf.get('sampler'), dict):
|
||||
sampler.update(wf.get('sampler', {}))
|
||||
if isinstance(slot_sampler, dict):
|
||||
sampler.update(slot_sampler)
|
||||
|
||||
resolution = dict(_relay_default_resolution())
|
||||
if isinstance(wf.get('resolution'), dict):
|
||||
resolution.update(wf.get('resolution', {}))
|
||||
if isinstance(slot_resolution, dict):
|
||||
resolution.update(slot_resolution)
|
||||
|
||||
# -- Apply top-level overrides -------------------------------
|
||||
pos_text = kwargs.get('pos_prompt')
|
||||
if pos_text is not None:
|
||||
target_block = _selected_model_block(wf, selected_slot, create=create_block_on_write)
|
||||
if isinstance(target_block, dict):
|
||||
target_block['positive_prompt'] = pos_text
|
||||
|
||||
neg_text = kwargs.get('neg_prompt')
|
||||
if neg_text is not None:
|
||||
target_block = _selected_model_block(wf, selected_slot, create=create_block_on_write)
|
||||
if isinstance(target_block, dict):
|
||||
target_block['negative_prompt'] = neg_text
|
||||
|
||||
# -- LoRA stack overrides ------------------------------------
|
||||
if kwargs.get('lora_stack') is not None:
|
||||
normalized_stack = _normalize_lora_stack_input(kwargs['lora_stack'])
|
||||
target_block = _selected_model_block(wf, selected_slot, create=create_block_on_write)
|
||||
if isinstance(target_block, dict):
|
||||
target_block['loras'] = normalized_stack
|
||||
|
||||
# -- Resolution overrides ------------------------------------
|
||||
for key in ('width', 'height', 'batch_size', 'length'):
|
||||
if kwargs.get(key) is not None:
|
||||
resolution[key] = kwargs[key]
|
||||
wf['resolution'] = resolution
|
||||
|
||||
# # -- Sampler overrides ---------------------------------------
|
||||
# if kwargs.get('steps') is not None:
|
||||
# sampler['steps_a'] = kwargs['steps']
|
||||
# sampler['steps_b'] = kwargs['steps']
|
||||
# if kwargs.get('seed') is not None:
|
||||
# sampler['seed_a'] = kwargs['seed']
|
||||
# sampler['seed_b'] = kwargs['seed']
|
||||
|
||||
for key in ('cfg', 'denoise', 'sampler_name', 'scheduler'):
|
||||
if kwargs.get(key) is not None:
|
||||
sampler[key] = kwargs[key]
|
||||
wf['sampler'] = sampler
|
||||
|
||||
target_block = _selected_model_block(wf, selected_slot, create=create_block_on_write)
|
||||
if isinstance(target_block, dict):
|
||||
bs = target_block.get('sampler', {}) if isinstance(target_block.get('sampler'), dict) else {}
|
||||
if kwargs.get('steps') is not None:
|
||||
bs['steps'] = kwargs['steps']
|
||||
if kwargs.get('seed') is not None:
|
||||
bs['seed'] = kwargs['seed']
|
||||
for key in ('cfg', 'denoise', 'sampler_name', 'scheduler'):
|
||||
if kwargs.get(key) is not None:
|
||||
bs[key] = kwargs[key]
|
||||
target_block['sampler'] = bs
|
||||
|
||||
br = target_block.get('resolution', {}) if isinstance(target_block.get('resolution'), dict) else {}
|
||||
for key in ('width', 'height', 'batch_size', 'length'):
|
||||
if kwargs.get(key) is not None:
|
||||
br[key] = kwargs[key]
|
||||
if br:
|
||||
target_block['resolution'] = br
|
||||
|
||||
# -- Model/CLIP/VAE name overrides ---------------------------
|
||||
model_name_in = kwargs.get('model_name')
|
||||
if isinstance(model_name_in, str) and model_name_in.strip():
|
||||
resolved_name, _ = resolve_model_name(model_name_in)
|
||||
chosen_name = resolved_name or os.path.basename(model_name_in.strip().replace("\\", "/"))
|
||||
target_block = _selected_model_block(wf, selected_slot, create=create_block_on_write)
|
||||
if isinstance(target_block, dict):
|
||||
target_block['model'] = chosen_name
|
||||
|
||||
family = get_model_family(chosen_name)
|
||||
if family:
|
||||
family_spec = MODEL_FAMILIES.get(family, {})
|
||||
target_block = _selected_model_block(wf, selected_slot, create=create_block_on_write)
|
||||
if isinstance(target_block, dict):
|
||||
target_block['family'] = family
|
||||
target_block['clip_type'] = family_spec.get('clip_type', '')
|
||||
target_block['loader_type'] = 'checkpoint' if family_spec.get('checkpoint', False) else 'unet'
|
||||
|
||||
# -- Pass-through MODEL / CLIP / VAE -------------------------
|
||||
# Priority: explicit connected inputs > embedded objects in workflow_data.
|
||||
model = kwargs.get('model')
|
||||
if model is None:
|
||||
model = selected_block.get('MODEL') if isinstance(selected_block, dict) else None
|
||||
# if model is None:
|
||||
# model = wf.get('MODEL')
|
||||
# if model is None:
|
||||
# model = wf.get('MODEL_A')
|
||||
|
||||
selected_loader_type = (
|
||||
str((selected_block or {}).get('loader_type', '')).strip().lower()
|
||||
if isinstance(selected_block, dict)
|
||||
else ''
|
||||
)
|
||||
|
||||
clip = kwargs.get('clip')
|
||||
if clip is None:
|
||||
clip = selected_block.get('CLIP') if isinstance(selected_block, dict) else None
|
||||
if clip is None:
|
||||
clip = wf.get('CLIP')
|
||||
|
||||
vae = kwargs.get('vae')
|
||||
if vae is None:
|
||||
vae = selected_block.get('VAE') if isinstance(selected_block, dict) else None
|
||||
if vae is None:
|
||||
vae = wf.get('VAE')
|
||||
|
||||
positive = kwargs.get('positive')
|
||||
if positive is None:
|
||||
positive = selected_block.get('POSITIVE') if isinstance(selected_block, dict) else None
|
||||
if positive is None:
|
||||
positive = wf.get('POSITIVE')
|
||||
|
||||
negative = kwargs.get('negative')
|
||||
if negative is None:
|
||||
negative = selected_block.get('NEGATIVE') if isinstance(selected_block, dict) else None
|
||||
if negative is None:
|
||||
negative = wf.get('NEGATIVE')
|
||||
|
||||
extra_1 = kwargs.get('extra_1')
|
||||
if extra_1 is None:
|
||||
extra_1 = selected_block.get('EXTRA_1') if isinstance(selected_block, dict) else None
|
||||
if extra_1 is None:
|
||||
extra_1 = wf.get('EXTRA_1')
|
||||
|
||||
extra_2 = kwargs.get('extra_2')
|
||||
if extra_2 is None:
|
||||
extra_2 = selected_block.get('EXTRA_2') if isinstance(selected_block, dict) else None
|
||||
if extra_2 is None:
|
||||
extra_2 = wf.get('EXTRA_2')
|
||||
|
||||
latent = kwargs.get('latent')
|
||||
if latent is None:
|
||||
latent = wf.get('LATENT')
|
||||
|
||||
image = kwargs.get('image')
|
||||
if image is None:
|
||||
image = wf.get('IMAGE')
|
||||
|
||||
mask = kwargs.get('mask')
|
||||
if mask is None:
|
||||
mask = wf.get('MASK')
|
||||
|
||||
if isinstance(target_block, dict):
|
||||
if model is not None:
|
||||
target_block['MODEL'] = model
|
||||
if clip is not None:
|
||||
target_block['CLIP'] = clip
|
||||
if vae is not None:
|
||||
target_block['VAE'] = vae
|
||||
if positive is not None:
|
||||
target_block['POSITIVE'] = positive
|
||||
if negative is not None:
|
||||
target_block['NEGATIVE'] = negative
|
||||
if extra_1 is not None:
|
||||
target_block['EXTRA_1'] = extra_1
|
||||
if extra_2 is not None:
|
||||
target_block['EXTRA_2'] = extra_2
|
||||
|
||||
if latent is not None:
|
||||
wf['LATENT'] = latent
|
||||
if image is not None:
|
||||
wf['IMAGE'] = image
|
||||
if mask is not None:
|
||||
wf['MASK'] = mask
|
||||
|
||||
# -- Build lora stacks as tuples for LORA_STACK output -------
|
||||
# Filter not-found LoRAs here so downstream nodes receiving
|
||||
# LORA_STACK don't get unavailable entries. Keep wf['loras_*']
|
||||
# unchanged to preserve authored workflow_data for chaining.
|
||||
|
||||
def _is_active_available(lora_item):
|
||||
if not isinstance(lora_item, dict):
|
||||
return False
|
||||
resolved_path, available = _resolve_lora_output_path(lora_item)
|
||||
if not resolved_path:
|
||||
return False
|
||||
if lora_item.get('active', True) is False:
|
||||
return False
|
||||
# Ignore persisted availability flags; they may be stale across sessions.
|
||||
# Use current filesystem resolution as source of truth.
|
||||
return available
|
||||
|
||||
legacy_slot_loras = []
|
||||
lora_stack = [
|
||||
(_resolve_lora_output_path(item)[0], item.get('model_strength', 1.0), item.get('clip_strength', 1.0))
|
||||
for item in legacy_slot_loras
|
||||
if _is_active_available(item)
|
||||
]
|
||||
final_selected = _selected_model_block(wf, selected_slot, create=create_block_on_write)
|
||||
selected_loras = final_selected.get('loras', []) if isinstance(final_selected, dict) and isinstance(final_selected.get('loras'), list) else []
|
||||
if selected_loras:
|
||||
lora_stack = [
|
||||
(_resolve_lora_output_path(item)[0], item.get('model_strength', 1.0), item.get('clip_strength', 1.0))
|
||||
for item in selected_loras
|
||||
if _is_active_available(item)
|
||||
]
|
||||
elif not lora_stack and isinstance(slot_loras, list):
|
||||
lora_stack = [
|
||||
(_resolve_lora_output_path(item)[0], item.get('model_strength', 1.0), item.get('clip_strength', 1.0))
|
||||
for item in slot_loras
|
||||
if _is_active_available(item)
|
||||
]
|
||||
|
||||
final_sampler = dict(sampler)
|
||||
if isinstance(final_selected, dict) and isinstance(final_selected.get('sampler'), dict):
|
||||
final_sampler.update(final_selected.get('sampler', {}))
|
||||
|
||||
final_resolution = dict(resolution)
|
||||
if isinstance(final_selected, dict) and isinstance(final_selected.get('resolution'), dict):
|
||||
final_resolution.update(final_selected.get('resolution', {}))
|
||||
|
||||
final_model_name = ''
|
||||
if isinstance(final_selected, dict):
|
||||
final_model_name = _short_display_name(final_selected.get('model', ''))
|
||||
if not final_model_name:
|
||||
final_model_name = _short_display_name(slot_model_name)
|
||||
|
||||
final_pos = (final_selected.get('positive_prompt', '') if isinstance(final_selected, dict) else '') or slot_positive
|
||||
final_neg = (final_selected.get('negative_prompt', '') if isinstance(final_selected, dict) else '') or slot_negative
|
||||
|
||||
raw_model_data = kwargs.get('model_data')
|
||||
if isinstance(raw_model_data, str):
|
||||
try:
|
||||
model_data_in = json.loads(raw_model_data)
|
||||
except Exception:
|
||||
model_data_in = {}
|
||||
elif isinstance(raw_model_data, dict):
|
||||
model_data_in = dict(raw_model_data)
|
||||
else:
|
||||
model_data_in = {}
|
||||
|
||||
ckpt_name_in = str(model_data_in.get('ckpt_name', '') or '').strip()
|
||||
unet_name_in = str(model_data_in.get('unet_name', '') or '').strip()
|
||||
vae_name_in = str(model_data_in.get('vae_name', model_data_in.get('vae', '')) or '').strip()
|
||||
clip_name_in = str(model_data_in.get('clip_name', '') or '').strip()
|
||||
if not clip_name_in and isinstance(model_data_in.get('clip'), list) and model_data_in.get('clip'):
|
||||
clip_name_in = str(model_data_in.get('clip')[0] or '').strip()
|
||||
model_name_from_data = str(model_data_in.get('model', '') or '').strip()
|
||||
loader_type_from_data = str(model_data_in.get('loader_type', '') or '').strip().lower()
|
||||
family_from_data = str(model_data_in.get('family', '') or '').strip()
|
||||
clip_type_from_data = str(model_data_in.get('clip_type', '') or '').strip()
|
||||
|
||||
selected_model_raw = (final_selected.get('model', '') if isinstance(final_selected, dict) else '') or slot_model_name or ''
|
||||
selected_vae_raw = (final_selected.get('vae', '') if isinstance(final_selected, dict) else '') or slot_vae or ''
|
||||
selected_clip_raw = ''
|
||||
if isinstance(final_selected, dict) and isinstance(final_selected.get('clip'), list) and final_selected.get('clip'):
|
||||
selected_clip_raw = str(final_selected.get('clip')[0] or '').strip()
|
||||
elif isinstance(slot_clip, list) and slot_clip:
|
||||
selected_clip_raw = str(slot_clip[0] or '').strip()
|
||||
|
||||
selected_model_name = str(selected_model_raw or '').strip()
|
||||
selected_vae_name = str(selected_vae_raw or '').strip()
|
||||
selected_clip_name = str(selected_clip_raw or '').strip()
|
||||
|
||||
# Structured model_data / combo-name overrides are authoritative.
|
||||
if model_name_from_data:
|
||||
selected_model_name = model_name_from_data
|
||||
if loader_type_from_data in ('checkpoint', 'unet', 'diffusion'):
|
||||
selected_loader_type = 'unet' if loader_type_from_data == 'diffusion' else loader_type_from_data
|
||||
|
||||
# If checkpoint/unet names are provided, update model name and loader type
|
||||
# even when recipe_data did not previously declare a loader type.
|
||||
if ckpt_name_in:
|
||||
selected_model_name = ckpt_name_in
|
||||
selected_loader_type = 'checkpoint'
|
||||
elif unet_name_in:
|
||||
selected_model_name = unet_name_in
|
||||
selected_loader_type = 'unet'
|
||||
|
||||
if vae_name_in:
|
||||
selected_vae_name = vae_name_in
|
||||
if clip_name_in:
|
||||
selected_clip_name = clip_name_in
|
||||
|
||||
target_block = _selected_model_block(wf, selected_slot, create=create_block_on_write)
|
||||
if isinstance(target_block, dict):
|
||||
if selected_model_name:
|
||||
target_block['model'] = selected_model_name
|
||||
if selected_loader_type:
|
||||
target_block['loader_type'] = selected_loader_type
|
||||
if family_from_data:
|
||||
target_block['family'] = family_from_data
|
||||
if clip_type_from_data:
|
||||
target_block['clip_type'] = clip_type_from_data
|
||||
if selected_vae_name:
|
||||
target_block['vae'] = selected_vae_name
|
||||
if selected_clip_name:
|
||||
target_block['clip'] = [selected_clip_name]
|
||||
|
||||
if selected_model_name:
|
||||
detected_family = get_model_family(selected_model_name)
|
||||
if detected_family:
|
||||
detected_block = _selected_model_block(wf, selected_slot, create=create_block_on_write)
|
||||
if isinstance(detected_block, dict):
|
||||
detected_block['family'] = detected_family
|
||||
|
||||
family_in = kwargs.get('family')
|
||||
if family_in is not None:
|
||||
family_override = str(family_in or '').strip()
|
||||
family_block = _selected_model_block(wf, selected_slot, create=create_block_on_write)
|
||||
if isinstance(family_block, dict):
|
||||
family_block['family'] = family_override
|
||||
|
||||
# -- Extract all output values -------------------------------
|
||||
model_name = _short_display_name(selected_model_name) or final_model_name
|
||||
family_out = ''
|
||||
current_block = _selected_model_block(wf, selected_slot, create=False)
|
||||
if isinstance(current_block, dict):
|
||||
family_out = str(current_block.get('family', '') or '').strip()
|
||||
if not family_out:
|
||||
family_out = str(slot_family or '').strip()
|
||||
|
||||
resolved_ckpt_name, ckpt_found = _resolve_rel_path(selected_model_name, ("checkpoints",))
|
||||
resolved_unet_name, unet_found = _resolve_rel_path(selected_model_name, ("diffusion_models", "unet", "unet_gguf"))
|
||||
|
||||
# Infer loader type when metadata is missing but model path resolves.
|
||||
if selected_loader_type not in ('checkpoint', 'unet', 'diffusion'):
|
||||
if ckpt_found and not unet_found:
|
||||
selected_loader_type = 'checkpoint'
|
||||
elif unet_found and not ckpt_found:
|
||||
selected_loader_type = 'unet'
|
||||
elif ckpt_found and unet_found:
|
||||
family_spec = MODEL_FAMILIES.get(family_out, {}) if family_out else {}
|
||||
selected_loader_type = 'checkpoint' if family_spec.get('checkpoint', False) else 'unet'
|
||||
|
||||
# Always emit string outputs for combo-name sockets to avoid None flowing
|
||||
# into downstream standard loader nodes.
|
||||
if ckpt_name_in:
|
||||
ckpt_out = ckpt_name_in
|
||||
elif selected_loader_type == 'checkpoint':
|
||||
ckpt_out = resolved_ckpt_name if ckpt_found else (selected_model_name or "")
|
||||
elif ckpt_found and not unet_found:
|
||||
ckpt_out = resolved_ckpt_name
|
||||
else:
|
||||
ckpt_out = ""
|
||||
|
||||
if unet_name_in:
|
||||
unet_out = unet_name_in
|
||||
elif selected_loader_type in ('unet', 'diffusion'):
|
||||
unet_out = resolved_unet_name if unet_found else (selected_model_name or "")
|
||||
elif unet_found and not ckpt_found:
|
||||
unet_out = resolved_unet_name
|
||||
else:
|
||||
unet_out = ""
|
||||
vae_name_out = selected_vae_name or ""
|
||||
clip_name_out = selected_clip_name or ""
|
||||
|
||||
return (
|
||||
wf,
|
||||
model, clip, positive, negative, vae, latent, image, mask, extra_1, extra_2,
|
||||
final_sampler.get('seed_a', final_sampler.get('seed', 0)),
|
||||
final_sampler.get('steps_a', final_sampler.get('steps', 10)),
|
||||
final_sampler.get('cfg', 5.0),
|
||||
final_sampler.get('sampler_name', 'euler'),
|
||||
final_sampler.get('scheduler', 'simple'),
|
||||
final_sampler.get('denoise', 1.0),
|
||||
final_pos,
|
||||
final_neg,
|
||||
lora_stack,
|
||||
final_resolution.get('width', 512),
|
||||
final_resolution.get('height', 512),
|
||||
final_resolution.get('batch_size', 1),
|
||||
final_resolution.get('length', 0) or 0,
|
||||
model_name,
|
||||
family_out,
|
||||
ckpt_out,
|
||||
unet_out,
|
||||
vae_name_out,
|
||||
clip_name_out,
|
||||
)
|
||||
@@ -1,443 +0,0 @@
|
||||
"""
|
||||
ComfyUI Workflow Bridge - Pure passthrough node.
|
||||
Unpacks workflow_data into individual typed outputs.
|
||||
Any connected optional input overrides the corresponding field before output.
|
||||
Models (MODEL/CLIP/VAE) are passed through only - use WorkflowModelLoader for loading.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import folder_paths
|
||||
import comfy.samplers
|
||||
from ..py.lora_utils import resolve_lora_path
|
||||
from ..py.workflow_extraction_utils import resolve_model_name
|
||||
from ..py.workflow_families import get_model_family, MODEL_FAMILIES
|
||||
|
||||
|
||||
MODEL_EXTENSIONS = (".safetensors", ".ckpt", ".pt", ".pth", ".gguf")
|
||||
|
||||
|
||||
class _AnyType(str):
|
||||
"""Comfy wildcard type that can connect to any socket type."""
|
||||
|
||||
def __ne__(self, _other):
|
||||
return False
|
||||
|
||||
|
||||
ANY_TYPE = _AnyType("ANY")
|
||||
|
||||
|
||||
def _strip_model_ext(name):
|
||||
base = os.path.basename(str(name or "").replace("\\", "/"))
|
||||
lower = base.lower()
|
||||
for ext in MODEL_EXTENSIONS:
|
||||
if lower.endswith(ext):
|
||||
return base[:-len(ext)]
|
||||
return os.path.splitext(base)[0]
|
||||
|
||||
|
||||
def _resolve_rel_path(raw_name, folder_keys):
|
||||
"""Resolve a model-like name to a relative Comfy path in the provided folder keys."""
|
||||
if not raw_name:
|
||||
return "", False
|
||||
|
||||
raw = str(raw_name).strip().replace("\\", "/")
|
||||
if not raw:
|
||||
return "", False
|
||||
|
||||
base = os.path.basename(raw).lower()
|
||||
base_no_ext = _strip_model_ext(base).lower()
|
||||
|
||||
for key in folder_keys:
|
||||
try:
|
||||
file_list = folder_paths.get_filename_list(key)
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
for rel in file_list:
|
||||
rel_norm = rel.replace("\\", "/")
|
||||
if rel_norm == raw:
|
||||
return rel, True
|
||||
|
||||
rel_base = os.path.basename(rel_norm).lower()
|
||||
if rel_base == base:
|
||||
return rel, True
|
||||
|
||||
if _strip_model_ext(rel_base).lower() == base_no_ext:
|
||||
return rel, True
|
||||
|
||||
return os.path.basename(raw), False
|
||||
|
||||
|
||||
def _get_live_ksampler_combo_types():
|
||||
"""Mirror the active KSampler enum sockets to avoid stale type mismatches."""
|
||||
default_samplers = comfy.samplers.KSampler.SAMPLERS
|
||||
default_schedulers = comfy.samplers.KSampler.SCHEDULERS
|
||||
try:
|
||||
from nodes import KSampler as CoreKSampler
|
||||
required = CoreKSampler.INPUT_TYPES().get("required", {})
|
||||
samplers = required.get("sampler_name", (default_samplers,))[0]
|
||||
schedulers = required.get("scheduler", (default_schedulers,))[0]
|
||||
return samplers, schedulers
|
||||
except Exception:
|
||||
return default_samplers, default_schedulers
|
||||
|
||||
|
||||
_LIVE_SAMPLERS, _LIVE_SCHEDULERS = _get_live_ksampler_combo_types()
|
||||
|
||||
|
||||
DEFAULT_WORKFLOW_DATA = {
|
||||
"_source": "WorkflowBridge",
|
||||
"family": "",
|
||||
"model_a": "",
|
||||
"model_b": "",
|
||||
"positive_prompt": "",
|
||||
"negative_prompt": "",
|
||||
"loras_a": [],
|
||||
"loras_b": [],
|
||||
"vae": "",
|
||||
"clip": [],
|
||||
"clip_type": "",
|
||||
"loader_type": "",
|
||||
"sampler": {
|
||||
"steps_a": 10,
|
||||
"steps_b": 10,
|
||||
"cfg": 5,
|
||||
"seed_a": 0,
|
||||
"seed_b": 0,
|
||||
"sampler_name": "euler",
|
||||
"scheduler": "simple",
|
||||
},
|
||||
"resolution": {
|
||||
"width": 512,
|
||||
"height": 512,
|
||||
"batch_size": 1,
|
||||
"length": 1,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
class WorkflowBridge:
|
||||
"""
|
||||
Pure passthrough bridge node.
|
||||
Unpacks workflow_data into individual typed outputs and forwards
|
||||
any connected MODEL/CLIP/VAE inputs. No model loading.
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def _sync_combo_types(cls):
|
||||
samplers, schedulers = _get_live_ksampler_combo_types()
|
||||
cls._SAMPLER_ENUM = samplers
|
||||
cls._SCHEDULER_ENUM = schedulers
|
||||
cls.RETURN_TYPES = (
|
||||
"WORKFLOW_DATA",
|
||||
"MODEL", "MODEL", "CLIP", "CONDITIONING", "CONDITIONING", "VAE", "LATENT", "IMAGE", "MASK", ANY_TYPE,
|
||||
"INT", "INT", "INT", "INT", "FLOAT",
|
||||
cls._SAMPLER_ENUM, cls._SCHEDULER_ENUM,
|
||||
"STRING", "STRING",
|
||||
"LORA_STACK", "LORA_STACK",
|
||||
"INT", "INT", "INT", "INT",
|
||||
"STRING", "STRING", "STRING", "STRING",
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
cls._sync_combo_types()
|
||||
return {
|
||||
"required": {},
|
||||
"optional": {
|
||||
"workflow_data": ("WORKFLOW_DATA", {"forceInput": True, "tooltip": "Optional workflow data input. If omitted, bridge starts from an empty workflow_data dict."}),
|
||||
"model_a": ("MODEL", {"tooltip": "Pass-through Model A"}),
|
||||
"model_b": ("MODEL", {"tooltip": "Pass-through Model B"}),
|
||||
"clip": ("CLIP", {"tooltip": "Pass-through CLIP"}),
|
||||
"positive": ("CONDITIONING", {"tooltip": "Pass-through positive conditioning"}),
|
||||
"negative": ("CONDITIONING", {"tooltip": "Pass-through negative conditioning"}),
|
||||
"vae": ("VAE", {"tooltip": "Pass-through VAE"}),
|
||||
"latent": ("LATENT", {"tooltip": "Pass-through latent"}),
|
||||
"image": ("IMAGE", {"tooltip": "Pass-through image"}),
|
||||
"mask": ("MASK", {"tooltip": "Pass-through mask"}),
|
||||
"extra": (ANY_TYPE, {"tooltip": "Pass-through extra data (any type)"}),
|
||||
"seed_a": ("INT", {"forceInput": True, "tooltip": "Override seed A"}),
|
||||
"seed_b": ("INT", {"forceInput": True, "tooltip": "Override seed B (dual-sampler)"}),
|
||||
"steps_a": ("INT", {"forceInput": True, "tooltip": "Override sampling steps A"}),
|
||||
"steps_b": ("INT", {"forceInput": True, "tooltip": "Override sampling steps B (dual-sampler)"}),
|
||||
"cfg": ("FLOAT", {"forceInput": True, "tooltip": "Override CFG scale"}),
|
||||
"sampler_name": (cls._SAMPLER_ENUM, {"forceInput": True, "tooltip": "Override sampler name"}),
|
||||
"scheduler": (cls._SCHEDULER_ENUM, {"forceInput": True, "tooltip": "Override scheduler"}),
|
||||
"pos_prompt": ("STRING", {"forceInput": True, "tooltip": "Override positive prompt"}),
|
||||
"neg_prompt": ("STRING", {"forceInput": True, "tooltip": "Override negative prompt"}),
|
||||
"lora_stack_a": ("LORA_STACK", {"tooltip": "Override LoRA stack A"}),
|
||||
"lora_stack_b": ("LORA_STACK", {"tooltip": "Override LoRA stack B"}),
|
||||
"width": ("INT", {"forceInput": True, "tooltip": "Override width"}),
|
||||
"height": ("INT", {"forceInput": True, "tooltip": "Override height"}),
|
||||
"batch_size": ("INT", {"forceInput": True, "tooltip": "Override batch size"}),
|
||||
"length": ("INT", {"forceInput": True, "tooltip": "Override video length"}),
|
||||
"model_a_name": ("STRING", {"forceInput": True, "tooltip": "Optional Model A name/path. Resolves and writes workflow_data['model_a']."}),
|
||||
"model_b_name": ("STRING", {"forceInput": True, "tooltip": "Optional Model B name/path. Resolves and writes workflow_data['model_b']."}),
|
||||
"clip_name": ("STRING", {"forceInput": True, "tooltip": "Optional CLIP name/path. Resolves and writes workflow_data['clip']."}),
|
||||
"vae_name": ("STRING", {"forceInput": True, "tooltip": "Optional VAE name/path. Resolves and writes workflow_data['vae']."}),
|
||||
},
|
||||
}
|
||||
|
||||
RETURN_TYPES = (
|
||||
"WORKFLOW_DATA",
|
||||
"MODEL", "MODEL", "CLIP", "CONDITIONING", "CONDITIONING", "VAE", "LATENT", "IMAGE", "MASK", ANY_TYPE,
|
||||
"INT", "INT", "INT", "INT", "FLOAT",
|
||||
_LIVE_SAMPLERS, _LIVE_SCHEDULERS,
|
||||
"STRING", "STRING",
|
||||
"LORA_STACK", "LORA_STACK",
|
||||
"INT", "INT", "INT", "INT",
|
||||
"STRING", "STRING", "STRING", "STRING",
|
||||
)
|
||||
RETURN_NAMES = (
|
||||
"workflow_data",
|
||||
"model_a", "model_b", "clip", "positive", "negative", "vae", "latent", "image", "mask", "extra",
|
||||
"seed_a", "seed_b", "steps_a", "steps_b", "cfg",
|
||||
"sampler_name", "scheduler",
|
||||
"pos_prompt", "neg_prompt",
|
||||
"lora_stack_a", "lora_stack_b",
|
||||
"width", "height", "batch_size", "length",
|
||||
"model_a_name", "model_b_name", "clip_name", "vae_name",
|
||||
)
|
||||
FUNCTION = "unpack"
|
||||
CATEGORY = "Prompt Manager"
|
||||
DESCRIPTION = (
|
||||
"Pure passthrough bridge node. Unpacks workflow_data into individual "
|
||||
"typed outputs. Models are forwarded from connected inputs only."
|
||||
)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def unpack(self, workflow_data=None, **kwargs):
|
||||
def _short_display_name(name):
|
||||
raw = str(name or "").strip()
|
||||
if not raw:
|
||||
return ""
|
||||
base = os.path.basename(raw.replace("\\", "/"))
|
||||
return os.path.splitext(base)[0]
|
||||
|
||||
# Accept both dict and JSON string
|
||||
if isinstance(workflow_data, str):
|
||||
try:
|
||||
incoming_wf = json.loads(workflow_data)
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
incoming_wf = {}
|
||||
elif isinstance(workflow_data, dict):
|
||||
incoming_wf = dict(workflow_data)
|
||||
else:
|
||||
incoming_wf = {}
|
||||
|
||||
# Start from a full empty-workflow template, then layer incoming values.
|
||||
wf = dict(DEFAULT_WORKFLOW_DATA)
|
||||
if isinstance(incoming_wf, dict):
|
||||
wf.update(incoming_wf)
|
||||
|
||||
incoming_sampler = incoming_wf.get('sampler')
|
||||
if isinstance(incoming_sampler, dict):
|
||||
wf['sampler'] = dict(DEFAULT_WORKFLOW_DATA['sampler'])
|
||||
wf['sampler'].update(incoming_sampler)
|
||||
|
||||
incoming_resolution = incoming_wf.get('resolution')
|
||||
if isinstance(incoming_resolution, dict):
|
||||
wf['resolution'] = dict(DEFAULT_WORKFLOW_DATA['resolution'])
|
||||
wf['resolution'].update(incoming_resolution)
|
||||
|
||||
sampler = dict(wf.get('sampler', DEFAULT_WORKFLOW_DATA['sampler']))
|
||||
resolution = dict(wf.get('resolution', DEFAULT_WORKFLOW_DATA['resolution']))
|
||||
|
||||
# -- Apply top-level overrides -------------------------------
|
||||
pos_text = kwargs.get('pos_prompt')
|
||||
if pos_text is not None:
|
||||
wf['positive_prompt'] = pos_text
|
||||
|
||||
neg_text = kwargs.get('neg_prompt')
|
||||
if neg_text is not None:
|
||||
wf['negative_prompt'] = neg_text
|
||||
|
||||
# -- LoRA stack overrides ------------------------------------
|
||||
if kwargs.get('lora_stack_a') is not None:
|
||||
wf['loras_a'] = [
|
||||
{'name': n, 'model_strength': ms, 'clip_strength': cs}
|
||||
for n, ms, cs in kwargs['lora_stack_a']
|
||||
]
|
||||
if kwargs.get('lora_stack_b') is not None:
|
||||
wf['loras_b'] = [
|
||||
{'name': n, 'model_strength': ms, 'clip_strength': cs}
|
||||
for n, ms, cs in kwargs['lora_stack_b']
|
||||
]
|
||||
|
||||
# -- Resolution overrides ------------------------------------
|
||||
for key in ('width', 'height', 'batch_size', 'length'):
|
||||
if kwargs.get(key) is not None:
|
||||
resolution[key] = kwargs[key]
|
||||
wf['resolution'] = resolution
|
||||
|
||||
# -- Sampler overrides ---------------------------------------
|
||||
for key in ('steps_a', 'steps_b', 'cfg', 'seed_a', 'seed_b', 'sampler_name', 'scheduler'):
|
||||
if kwargs.get(key) is not None:
|
||||
sampler[key] = kwargs[key]
|
||||
wf['sampler'] = sampler
|
||||
|
||||
# -- Model/CLIP/VAE name overrides ---------------------------
|
||||
model_a_name_in = kwargs.get('model_a_name')
|
||||
model_b_name_in = kwargs.get('model_b_name')
|
||||
clip_name_in = kwargs.get('clip_name')
|
||||
vae_name_in = kwargs.get('vae_name')
|
||||
|
||||
if isinstance(model_a_name_in, str) and model_a_name_in.strip():
|
||||
resolved_a, _ = resolve_model_name(model_a_name_in)
|
||||
wf['model_a'] = resolved_a or os.path.basename(model_a_name_in.strip().replace("\\", "/"))
|
||||
|
||||
family = get_model_family(wf['model_a'])
|
||||
if family:
|
||||
wf['family'] = family
|
||||
family_spec = MODEL_FAMILIES.get(family, {})
|
||||
wf['clip_type'] = family_spec.get('clip_type', '')
|
||||
wf['loader_type'] = 'checkpoint' if family_spec.get('checkpoint', False) else 'unet'
|
||||
|
||||
if isinstance(model_b_name_in, str) and model_b_name_in.strip():
|
||||
resolved_b, _ = resolve_model_name(model_b_name_in)
|
||||
wf['model_b'] = resolved_b or os.path.basename(model_b_name_in.strip().replace("\\", "/"))
|
||||
|
||||
if isinstance(clip_name_in, str) and clip_name_in.strip():
|
||||
resolved_clip, _ = _resolve_rel_path(clip_name_in, ["text_encoders", "clip", "checkpoints"])
|
||||
wf['clip'] = [resolved_clip] if resolved_clip else []
|
||||
|
||||
if isinstance(vae_name_in, str) and vae_name_in.strip():
|
||||
resolved_vae, _ = _resolve_rel_path(vae_name_in, ["vae", "checkpoints"])
|
||||
wf['vae'] = resolved_vae
|
||||
|
||||
# -- Pass-through MODEL / CLIP / VAE -------------------------
|
||||
# Priority: explicit connected inputs > embedded objects in workflow_data.
|
||||
model_a = kwargs.get('model_a')
|
||||
if model_a is None:
|
||||
model_a = wf.get('MODEL_A')
|
||||
|
||||
model_b = kwargs.get('model_b')
|
||||
if model_b is None:
|
||||
model_b = wf.get('MODEL_B')
|
||||
|
||||
clip = kwargs.get('clip')
|
||||
if clip is None:
|
||||
clip = wf.get('CLIP')
|
||||
|
||||
vae = kwargs.get('vae')
|
||||
if vae is None:
|
||||
vae = wf.get('VAE')
|
||||
|
||||
positive = kwargs.get('positive')
|
||||
if positive is None:
|
||||
positive = wf.get('POSITIVE')
|
||||
|
||||
negative = kwargs.get('negative')
|
||||
if negative is None:
|
||||
negative = wf.get('NEGATIVE')
|
||||
|
||||
latent = kwargs.get('latent')
|
||||
if latent is None:
|
||||
latent = wf.get('LATENT')
|
||||
|
||||
image = kwargs.get('image')
|
||||
if image is None:
|
||||
image = wf.get('IMAGE')
|
||||
|
||||
mask = kwargs.get('mask')
|
||||
if mask is None:
|
||||
mask = wf.get('MASK')
|
||||
|
||||
extra = kwargs.get('extra')
|
||||
if extra is None:
|
||||
extra = wf.get('EXTRA')
|
||||
|
||||
if model_a is not None:
|
||||
wf['MODEL_A'] = model_a
|
||||
if model_b is not None:
|
||||
wf['MODEL_B'] = model_b
|
||||
if clip is not None:
|
||||
wf['CLIP'] = clip
|
||||
if vae is not None:
|
||||
wf['VAE'] = vae
|
||||
if positive is not None:
|
||||
wf['POSITIVE'] = positive
|
||||
if negative is not None:
|
||||
wf['NEGATIVE'] = negative
|
||||
if latent is not None:
|
||||
wf['LATENT'] = latent
|
||||
if image is not None:
|
||||
wf['IMAGE'] = image
|
||||
if mask is not None:
|
||||
wf['MASK'] = mask
|
||||
if extra is not None:
|
||||
wf['EXTRA'] = extra
|
||||
|
||||
# -- Build lora stacks as tuples for LORA_STACK output -------
|
||||
# Filter not-found LoRAs here so downstream nodes receiving
|
||||
# LORA_STACK don't get unavailable entries. Keep wf['loras_*']
|
||||
# unchanged to preserve authored workflow_data for chaining.
|
||||
_lora_found_cache = {}
|
||||
|
||||
def _lora_is_found(name):
|
||||
if not name:
|
||||
return False
|
||||
if name in _lora_found_cache:
|
||||
return _lora_found_cache[name]
|
||||
_, found = resolve_lora_path(name)
|
||||
_lora_found_cache[name] = bool(found)
|
||||
return _lora_found_cache[name]
|
||||
|
||||
def _is_active_available_found(lora_item):
|
||||
if not isinstance(lora_item, dict):
|
||||
return False
|
||||
lora_name = lora_item.get('name')
|
||||
if not lora_name:
|
||||
return False
|
||||
if lora_item.get('active', True) is False:
|
||||
return False
|
||||
if lora_item.get('available', True) is False:
|
||||
return False
|
||||
return _lora_is_found(lora_name)
|
||||
|
||||
lora_stack_a = [
|
||||
(item['name'], item.get('model_strength', 1.0), item.get('clip_strength', 1.0))
|
||||
for item in wf.get('loras_a', [])
|
||||
if _is_active_available_found(item)
|
||||
]
|
||||
lora_stack_b = [
|
||||
(item['name'], item.get('model_strength', 1.0), item.get('clip_strength', 1.0))
|
||||
for item in wf.get('loras_b', [])
|
||||
if _is_active_available_found(item)
|
||||
]
|
||||
|
||||
# -- Extract all output values -------------------------------
|
||||
model_a_name = _short_display_name(wf.get('model_a', ''))
|
||||
model_b_name = _short_display_name(wf.get('model_b', ''))
|
||||
clip_name = ''
|
||||
clip_field = wf.get('clip', [])
|
||||
if isinstance(clip_field, list) and clip_field:
|
||||
clip_name = _short_display_name(clip_field[0])
|
||||
elif isinstance(clip_field, str):
|
||||
clip_name = _short_display_name(clip_field)
|
||||
vae_name = _short_display_name(wf.get('vae', ''))
|
||||
|
||||
return (
|
||||
wf,
|
||||
model_a, model_b, clip, positive, negative, vae, latent, image, mask, extra,
|
||||
sampler.get('seed_a', sampler.get('seed', 0)),
|
||||
sampler.get('seed_b', 0) or 0,
|
||||
sampler.get('steps_a', sampler.get('steps', 10)),
|
||||
sampler.get('steps_b', sampler.get('steps_a', sampler.get('steps', 10))),
|
||||
sampler.get('cfg', 5.0),
|
||||
sampler.get('sampler_name', 'euler'),
|
||||
sampler.get('scheduler', 'simple'),
|
||||
wf.get('positive_prompt', ''),
|
||||
wf.get('negative_prompt', ''),
|
||||
lora_stack_a,
|
||||
lora_stack_b,
|
||||
resolution.get('width', 512),
|
||||
resolution.get('height', 512),
|
||||
resolution.get('batch_size', 1),
|
||||
resolution.get('length', 0) or 0,
|
||||
model_a_name,
|
||||
model_b_name,
|
||||
clip_name,
|
||||
vae_name,
|
||||
)
|
||||
@@ -142,7 +142,7 @@ def build_map(api, family_hint):
|
||||
Build a semantic field map for the given API workflow.
|
||||
Returns a dict: { field_name: [node_id_str, input_key] | null }
|
||||
|
||||
The map is used by WorkflowRenderer to patch values before execution.
|
||||
The map is used by RecipeRenderer to patch values before execution.
|
||||
"""
|
||||
m = {}
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ Shared LoRA resolution utilities for ComfyUI-Prompt-Manager.
|
||||
Provides fuzzy matching logic for finding LoRA files on disk, handling
|
||||
renamed LoRAs, WAN-related tokens, and partial name matches.
|
||||
|
||||
Used by: PromptManagerAdvanced, PromptExtractor, WorkflowBuilder, WorkflowRenderer.
|
||||
Used by: PromptManagerAdvanced, PromptExtractor, RecipeBuilder, RecipeRenderer.
|
||||
"""
|
||||
import os
|
||||
import re
|
||||
@@ -70,7 +70,7 @@ def fuzzy_match_lora(lora_name, lora_files):
|
||||
|
||||
Example: "DR34LAY_HIGH_V2" can match "DR34LAY_I2V_14B_HIGH_V2"
|
||||
|
||||
Returns (matched_file, True) if found, (None, False) otherwise.
|
||||
Returns (matched_file, True) if available, (None, False) otherwise.
|
||||
"""
|
||||
# Normalize the search name
|
||||
search_parts = _normalize_name_for_fuzzy(strip_lora_extension(lora_name))
|
||||
@@ -121,7 +121,7 @@ def fuzzy_match_lora(lora_name, lora_files):
|
||||
def get_lora_relative_path(lora_name):
|
||||
"""
|
||||
Get the relative path for a LoRA that ComfyUI expects for loading.
|
||||
Returns (relative_path, found) tuple.
|
||||
Returns (relative_path, available) tuple.
|
||||
Supports fuzzy matching for renamed LoRAs.
|
||||
"""
|
||||
lora_files = get_available_loras()
|
||||
@@ -135,11 +135,11 @@ def get_lora_relative_path(lora_name):
|
||||
return lora_file, True
|
||||
|
||||
# Try fuzzy match for renamed LoRAs
|
||||
fuzzy_match, found = fuzzy_match_lora(lora_name, lora_files)
|
||||
if found:
|
||||
fuzzy_match, available = fuzzy_match_lora(lora_name, lora_files)
|
||||
if available:
|
||||
return fuzzy_match, True
|
||||
|
||||
# Not found
|
||||
# Not available
|
||||
return lora_name, False
|
||||
|
||||
|
||||
@@ -147,7 +147,7 @@ def resolve_lora_path(lora_name):
|
||||
"""
|
||||
Resolve a LoRA name to its full path using ComfyUI's folder system.
|
||||
Uses exact matching first, then fuzzy matching with WAN token handling.
|
||||
Returns (full_path_or_name, found) tuple.
|
||||
Returns (full_path_or_name, available) tuple.
|
||||
"""
|
||||
lora_files = get_available_loras()
|
||||
|
||||
@@ -164,8 +164,8 @@ def resolve_lora_path(lora_name):
|
||||
return folder_paths.get_full_path("loras", lora_file), True
|
||||
|
||||
# Fuzzy match for renamed LoRAs
|
||||
fuzzy_match, found = fuzzy_match_lora(lora_name, lora_files)
|
||||
if found:
|
||||
fuzzy_match, available = fuzzy_match_lora(lora_name, lora_files)
|
||||
if available:
|
||||
return folder_paths.get_full_path("loras", fuzzy_match), True
|
||||
|
||||
return None, False
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
"""
|
||||
Utility functions for WORKFLOW_DATA dicts.
|
||||
Utility functions for RECIPE_DATA dicts.
|
||||
Runtime object keys (MODEL_A, MODEL_B, CLIP, VAE, POSITIVE, NEGATIVE, etc.)
|
||||
store non-serializable ComfyUI objects and must be stripped before JSON
|
||||
serialization.
|
||||
@@ -11,6 +11,7 @@ import math
|
||||
# Keys that hold runtime (non-JSON-serializable) objects/conditioning payloads.
|
||||
# These should never be persisted in saved prompt/workflow metadata.
|
||||
RUNTIME_OBJECT_KEYS = frozenset({
|
||||
"MODEL",
|
||||
"MODEL_A",
|
||||
"MODEL_B",
|
||||
"CLIP",
|
||||
@@ -18,11 +19,299 @@ RUNTIME_OBJECT_KEYS = frozenset({
|
||||
"LATENT",
|
||||
"IMAGE",
|
||||
"MASK",
|
||||
"EXTRA",
|
||||
"EXTRA_1",
|
||||
"EXTRA_2",
|
||||
"POSITIVE",
|
||||
"NEGATIVE",
|
||||
})
|
||||
|
||||
_MODEL_KEYS = ("model_a", "model_b", "model_c", "model_d")
|
||||
_LEGACY_TOP_LEVEL_KEYS = {
|
||||
"family",
|
||||
"model_a",
|
||||
"model_b",
|
||||
"positive_prompt",
|
||||
"negative_prompt",
|
||||
"loras_a",
|
||||
"loras_b",
|
||||
"vae",
|
||||
"clip",
|
||||
"clip_type",
|
||||
"loader_type",
|
||||
"sampler",
|
||||
"resolution",
|
||||
}
|
||||
|
||||
|
||||
def _as_clip_list(raw_clip):
|
||||
if isinstance(raw_clip, list):
|
||||
return list(raw_clip)
|
||||
if isinstance(raw_clip, tuple):
|
||||
return list(raw_clip)
|
||||
if raw_clip:
|
||||
return [raw_clip]
|
||||
return []
|
||||
|
||||
|
||||
def _has_meaningful_legacy_slot(recipe_data, slot_key, sampler):
|
||||
if slot_key not in ("model_a", "model_b"):
|
||||
return False
|
||||
|
||||
suffix = "a" if slot_key == "model_a" else "b"
|
||||
model_name = str(recipe_data.get(slot_key, "") or "").strip()
|
||||
loras_key = f"loras_{suffix}"
|
||||
loras = recipe_data.get(loras_key, []) if isinstance(recipe_data.get(loras_key), list) else []
|
||||
has_loras = len(loras) > 0
|
||||
|
||||
steps_key = f"steps_{suffix}"
|
||||
seed_key = f"seed_{suffix}"
|
||||
has_slot_sampler = isinstance(sampler.get(steps_key), (int, float)) or isinstance(sampler.get(seed_key), (int, float))
|
||||
|
||||
return bool(model_name or has_loras or has_slot_sampler)
|
||||
|
||||
|
||||
def _legacy_to_v2_recipe_data(recipe_data, source):
|
||||
sampler = recipe_data.get("sampler", {}) if isinstance(recipe_data.get("sampler"), dict) else {}
|
||||
resolution = recipe_data.get("resolution", {}) if isinstance(recipe_data.get("resolution"), dict) else {}
|
||||
|
||||
def _build_model_block(slot_key):
|
||||
is_b = slot_key == "model_b"
|
||||
suffix = "b" if is_b else "a"
|
||||
loras_key = f"loras_{suffix}"
|
||||
|
||||
steps_key = f"steps_{suffix}"
|
||||
seed_key = f"seed_{suffix}"
|
||||
steps = sampler.get(steps_key)
|
||||
if steps is None:
|
||||
steps = sampler.get("steps_a", sampler.get("steps", 20))
|
||||
|
||||
seed = sampler.get(seed_key)
|
||||
if seed is None:
|
||||
seed = sampler.get("seed_a", sampler.get("seed", 0))
|
||||
|
||||
return {
|
||||
"positive_prompt": str(recipe_data.get("positive_prompt", "") or ""),
|
||||
"negative_prompt": str(recipe_data.get("negative_prompt", "") or ""),
|
||||
"family": str(recipe_data.get("family", "") or ""),
|
||||
"model": str(recipe_data.get(slot_key, "") or ""),
|
||||
"loras": list(recipe_data.get(loras_key, [])) if isinstance(recipe_data.get(loras_key), list) else [],
|
||||
"clip_type": str(recipe_data.get("clip_type", "") or ""),
|
||||
"loader_type": str(recipe_data.get("loader_type", "") or ""),
|
||||
"vae": str(recipe_data.get("vae", "") or ""),
|
||||
"clip": _as_clip_list(recipe_data.get("clip", [])),
|
||||
"sampler": {
|
||||
"steps": int(steps if steps is not None else 20),
|
||||
"cfg": float(sampler.get("cfg", 5.0)),
|
||||
"denoise": float(sampler.get("denoise", 1.0)),
|
||||
"seed": int(seed if seed is not None else 0),
|
||||
"sampler_name": str(sampler.get("sampler_name", "euler") or "euler"),
|
||||
"scheduler": str(sampler.get("scheduler", "simple") or "simple"),
|
||||
},
|
||||
"resolution": {
|
||||
"width": int(resolution.get("width", 768)),
|
||||
"height": int(resolution.get("height", 1280)),
|
||||
"batch_size": int(resolution.get("batch_size", 1)),
|
||||
"length": resolution.get("length", None),
|
||||
},
|
||||
}
|
||||
|
||||
out = {
|
||||
"_source": str(recipe_data.get("_source") or source),
|
||||
"version": 2,
|
||||
"models": {},
|
||||
}
|
||||
|
||||
# Preserve non-legacy metadata/runtime keys at root.
|
||||
for key, val in recipe_data.items():
|
||||
if key in {"_source", "version", "models"}:
|
||||
continue
|
||||
if key in _LEGACY_TOP_LEVEL_KEYS:
|
||||
continue
|
||||
out[key] = val
|
||||
|
||||
if _has_meaningful_legacy_slot(recipe_data, "model_a", sampler):
|
||||
out["models"]["model_a"] = _build_model_block("model_a")
|
||||
|
||||
if _has_meaningful_legacy_slot(recipe_data, "model_b", sampler):
|
||||
out["models"]["model_b"] = _build_model_block("model_b")
|
||||
|
||||
return out
|
||||
|
||||
|
||||
def get_v2_model_block(recipe_data, model_key):
|
||||
"""Return a v2 model block dict for model_key, or None if unavailable."""
|
||||
if not isinstance(recipe_data, dict):
|
||||
return None
|
||||
if int(recipe_data.get("version", 0) or 0) < 2:
|
||||
return None
|
||||
models = recipe_data.get("models", {}) if isinstance(recipe_data.get("models"), dict) else {}
|
||||
block = models.get(model_key)
|
||||
return block if isinstance(block, dict) else None
|
||||
|
||||
|
||||
def ensure_v2_recipe_data(recipe_data, source="RecipeData"):
|
||||
"""Normalize recipe_data to strict v2 shape.
|
||||
|
||||
v2 contract is authoritative. Legacy top-level recipe fields are converted
|
||||
into v2 model blocks.
|
||||
"""
|
||||
if not isinstance(recipe_data, dict):
|
||||
return {
|
||||
"_source": source,
|
||||
"version": 2,
|
||||
"models": {},
|
||||
}
|
||||
|
||||
is_v2 = int(recipe_data.get("version", 0) or 0) >= 2 and isinstance(recipe_data.get("models"), dict)
|
||||
if not is_v2:
|
||||
return _legacy_to_v2_recipe_data(recipe_data, source)
|
||||
|
||||
out = {
|
||||
"_source": str(recipe_data.get("_source") or source),
|
||||
"version": 2,
|
||||
"models": {},
|
||||
}
|
||||
|
||||
# Preserve non-legacy root keys as passthrough metadata/runtime payload.
|
||||
for key, val in recipe_data.items():
|
||||
if key in {"_source", "version", "models"}:
|
||||
continue
|
||||
if key in _LEGACY_TOP_LEVEL_KEYS:
|
||||
continue
|
||||
out[key] = val
|
||||
|
||||
if is_v2:
|
||||
for mk in _MODEL_KEYS:
|
||||
block = recipe_data.get("models", {}).get(mk)
|
||||
if isinstance(block, dict):
|
||||
out["models"][mk] = dict(block)
|
||||
|
||||
return out
|
||||
|
||||
|
||||
def _coerce_prompt_loras(raw_loras):
|
||||
"""Convert prompt-style LoRA entries into canonical workflow LoRA dicts."""
|
||||
if not isinstance(raw_loras, list):
|
||||
return []
|
||||
|
||||
out = []
|
||||
for lora in raw_loras:
|
||||
if not isinstance(lora, dict):
|
||||
continue
|
||||
name = str(lora.get("name", "") or "").strip()
|
||||
if not name:
|
||||
continue
|
||||
|
||||
model_strength = lora.get("model_strength", lora.get("strength", 1.0))
|
||||
clip_strength = lora.get("clip_strength", lora.get("strength", model_strength))
|
||||
out.append({
|
||||
"name": name,
|
||||
"path": lora.get("path", name),
|
||||
"model_strength": model_strength,
|
||||
"clip_strength": clip_strength,
|
||||
"active": lora.get("active", True),
|
||||
"available": lora.get("available", True),
|
||||
})
|
||||
|
||||
return out
|
||||
|
||||
|
||||
def _blank_v2_model_block():
|
||||
"""Return a blank v2 model block matching RecipeBuilder defaults."""
|
||||
return {
|
||||
"positive_prompt": "",
|
||||
"negative_prompt": "",
|
||||
"family": "",
|
||||
"model": "",
|
||||
"loras": [],
|
||||
"clip_type": "",
|
||||
"loader_type": "",
|
||||
"vae": "",
|
||||
"clip": [],
|
||||
"sampler": {
|
||||
"steps": 20,
|
||||
"cfg": 5.0,
|
||||
"denoise": 1.0,
|
||||
"seed": 0,
|
||||
"sampler_name": "dpmpp_2m_sde",
|
||||
"scheduler": "karras",
|
||||
},
|
||||
"resolution": {
|
||||
"width": 768,
|
||||
"height": 1280,
|
||||
"batch_size": 1,
|
||||
"length": None,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _merge_model_block_with_template(existing_block):
|
||||
"""Merge an existing model block onto the blank v2 template."""
|
||||
merged = _blank_v2_model_block()
|
||||
if not isinstance(existing_block, dict):
|
||||
return merged
|
||||
|
||||
for key, value in existing_block.items():
|
||||
if key == "sampler" and isinstance(value, dict):
|
||||
sampler = dict(merged["sampler"])
|
||||
sampler.update(value)
|
||||
merged["sampler"] = sampler
|
||||
continue
|
||||
if key == "resolution" and isinstance(value, dict):
|
||||
resolution = dict(merged["resolution"])
|
||||
resolution.update(value)
|
||||
merged["resolution"] = resolution
|
||||
continue
|
||||
merged[key] = value
|
||||
|
||||
return merged
|
||||
|
||||
|
||||
def build_v2_recipe_data_from_prompt(
|
||||
prompt_text="",
|
||||
negative_prompt="",
|
||||
loras_a=None,
|
||||
loras_b=None,
|
||||
source="RecipeData",
|
||||
base_recipe_data=None,
|
||||
):
|
||||
"""Build/update v2 recipe_data from prompt text and LoRA stacks.
|
||||
|
||||
- Preserves existing non-legacy root metadata from base_recipe_data.
|
||||
- Preserves existing model names when available.
|
||||
- Writes prompt + negative_prompt + loras into model_a/model_b.
|
||||
"""
|
||||
out = ensure_v2_recipe_data(
|
||||
dict(base_recipe_data) if isinstance(base_recipe_data, dict) else {},
|
||||
source=source,
|
||||
)
|
||||
|
||||
models = out.get("models", {})
|
||||
if not isinstance(models, dict):
|
||||
models = {}
|
||||
out["models"] = models
|
||||
|
||||
model_a = _merge_model_block_with_template(models.get("model_a"))
|
||||
model_b = _merge_model_block_with_template(models.get("model_b"))
|
||||
|
||||
prompt_text = str(prompt_text or "")
|
||||
negative_prompt = str(negative_prompt or "")
|
||||
|
||||
model_a["positive_prompt"] = prompt_text
|
||||
model_b["positive_prompt"] = prompt_text
|
||||
|
||||
model_a["negative_prompt"] = negative_prompt
|
||||
model_b["negative_prompt"] = negative_prompt
|
||||
|
||||
model_a["loras"] = _coerce_prompt_loras(loras_a)
|
||||
model_b["loras"] = _coerce_prompt_loras(loras_b)
|
||||
|
||||
models["model_a"] = model_a
|
||||
models["model_b"] = model_b
|
||||
|
||||
out["_source"] = source
|
||||
return ensure_v2_recipe_data(out, source=source)
|
||||
|
||||
|
||||
def _strip_runtime_keys_deep(value):
|
||||
"""Recursively strip runtime-only keys from dict/list containers."""
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"""
|
||||
Shared extraction helpers for ComfyUI Prompt Manager.
|
||||
|
||||
Used by both WorkflowExtractor and WorkflowBuilder / WorkflowRenderer nodes.
|
||||
Used by both RecipeExtractor and RecipeBuilder / RecipeRenderer nodes.
|
||||
Handles: sampler params, VAE info, CLIP info, resolution, model resolution,
|
||||
and the full extract_all_from_file() entry point.
|
||||
"""
|
||||
@@ -33,21 +33,215 @@ VIDEO_LATENT_TYPES = ['WanVideoLatentImage', 'WanImageToVideo', 'EmptyHunyuanLat
|
||||
CHECKPOINT_TYPES = ('CheckpointLoaderSimple', 'CheckpointLoader', 'CheckpointLoaderNF4')
|
||||
|
||||
# Node types that carry embedded extracted_data.
|
||||
# Keep 'WorkflowGenerator' for backward compat with images generated before rename.
|
||||
# WorkflowBuilder stores authoritative extracted_data for Builder+Renderer graphs.
|
||||
# Keep both Workflow* and Recipe* names for compatibility across renamed graphs.
|
||||
_EMBEDDED_NODE_TYPES = (
|
||||
'WorkflowRenderer',
|
||||
'WorkflowGenerator',
|
||||
'RecipeRenderer',
|
||||
'WorkflowBuilder',
|
||||
'RecipeBuilder',
|
||||
'WorkflowGenerator',
|
||||
'PromptExtractor',
|
||||
)
|
||||
|
||||
|
||||
def _parse_json_object(value):
|
||||
if isinstance(value, dict):
|
||||
return value
|
||||
if not isinstance(value, str):
|
||||
return None
|
||||
text = value.strip()
|
||||
if not text.startswith('{'):
|
||||
return None
|
||||
try:
|
||||
parsed = json.loads(text)
|
||||
except Exception:
|
||||
return None
|
||||
return parsed if isinstance(parsed, dict) else None
|
||||
|
||||
|
||||
def _normalize_builder_model_slot(value):
|
||||
key = str(value or '').strip().lower().replace('-', '_')
|
||||
if key in ('model_a', 'a'):
|
||||
return 'model_a'
|
||||
if key in ('model_b', 'b'):
|
||||
return 'model_b'
|
||||
if key in ('model_c', 'c'):
|
||||
return 'model_c'
|
||||
if key in ('model_d', 'd'):
|
||||
return 'model_d'
|
||||
return 'model_a'
|
||||
|
||||
|
||||
def _normalize_builder_lora_list(raw_list):
|
||||
if not isinstance(raw_list, list):
|
||||
return []
|
||||
out = []
|
||||
for item in raw_list:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
name = str(item.get('name', '') or '').strip()
|
||||
if not name:
|
||||
continue
|
||||
model_strength = item.get('model_strength', item.get('strength', 1.0))
|
||||
clip_strength = item.get('clip_strength', item.get('strength', model_strength))
|
||||
try:
|
||||
model_strength = float(model_strength)
|
||||
except Exception:
|
||||
model_strength = 1.0
|
||||
try:
|
||||
clip_strength = float(clip_strength)
|
||||
except Exception:
|
||||
clip_strength = model_strength
|
||||
out.append({
|
||||
'name': name,
|
||||
'path': item.get('path', ''),
|
||||
'model_strength': model_strength,
|
||||
'clip_strength': clip_strength,
|
||||
'active': item.get('active', True) is not False,
|
||||
'available': item.get('available', True) is not False,
|
||||
})
|
||||
return out
|
||||
|
||||
|
||||
def extract_recipe_builder_models_from_workflow(workflow_data):
|
||||
"""Extract v2 model blocks from RecipeBuilder/WorkflowBuilder nodes.
|
||||
|
||||
Mapping rule: builder ``_send_model_slot`` decides which model block to fill.
|
||||
If multiple builders send to the same slot, the last builder wins.
|
||||
"""
|
||||
if not isinstance(workflow_data, dict):
|
||||
return {}
|
||||
nodes = workflow_data.get('nodes', [])
|
||||
if not isinstance(nodes, list):
|
||||
return {}
|
||||
|
||||
builders = []
|
||||
for index, node in enumerate(nodes):
|
||||
if not isinstance(node, dict):
|
||||
continue
|
||||
ntype = str(node.get('type', '') or '')
|
||||
if ntype not in ('RecipeBuilder', 'WorkflowBuilder'):
|
||||
continue
|
||||
order = node.get('order', index)
|
||||
try:
|
||||
order = int(order)
|
||||
except Exception:
|
||||
order = index
|
||||
builders.append((order, index, node))
|
||||
|
||||
if not builders:
|
||||
return {}
|
||||
|
||||
builders.sort(key=lambda x: (x[0], x[1]))
|
||||
models = {}
|
||||
for _, _, node in builders:
|
||||
props = node.get('properties', {}) if isinstance(node.get('properties'), dict) else {}
|
||||
raw = _parse_json_object(props.get('we_override_data'))
|
||||
if not raw:
|
||||
raw = _parse_json_object(props.get('we_ui_state'))
|
||||
if not raw:
|
||||
raw = {}
|
||||
if not raw:
|
||||
for widget_val in (node.get('widgets_values') or []):
|
||||
parsed = _parse_json_object(widget_val)
|
||||
if parsed:
|
||||
raw = parsed
|
||||
break
|
||||
if not raw:
|
||||
continue
|
||||
|
||||
target_slot = _normalize_builder_model_slot(raw.get('_send_model_slot', raw.get('send_model_slot')))
|
||||
family = str(raw.get('_family', raw.get('family', 'sdxl')) or 'sdxl')
|
||||
model_name = str(raw.get('model_a', raw.get('model', '')) or '')
|
||||
vae_name = str(raw.get('vae', '') or '')
|
||||
clip_raw = raw.get('clip_names', raw.get('clip', []))
|
||||
if isinstance(clip_raw, list):
|
||||
clip_names = [str(x) for x in clip_raw if str(x or '').strip()]
|
||||
elif isinstance(clip_raw, str) and clip_raw.strip():
|
||||
clip_names = [clip_raw]
|
||||
else:
|
||||
clip_names = []
|
||||
|
||||
sampler = {
|
||||
'steps': raw.get('steps_a', raw.get('steps', 20)),
|
||||
'cfg': raw.get('cfg', 5.0),
|
||||
'denoise': raw.get('denoise', 1.0),
|
||||
'seed': raw.get('seed_a', raw.get('seed', 0)),
|
||||
'sampler_name': raw.get('sampler_name', 'euler'),
|
||||
'scheduler': raw.get('scheduler', 'simple'),
|
||||
}
|
||||
resolution = {
|
||||
'width': raw.get('width', 768),
|
||||
'height': raw.get('height', 1280),
|
||||
'batch_size': raw.get('batch_size', 1),
|
||||
'length': raw.get('length'),
|
||||
}
|
||||
|
||||
models[target_slot] = {
|
||||
'positive_prompt': str(raw.get('positive_prompt', '') or ''),
|
||||
'negative_prompt': str(raw.get('negative_prompt', '') or ''),
|
||||
'family': family,
|
||||
'model': model_name,
|
||||
'loras': _normalize_builder_lora_list(raw.get('loras_a', [])),
|
||||
'clip_type': str(raw.get('clip_type', '') or ''),
|
||||
'loader_type': str(raw.get('loader_type', '') or ''),
|
||||
'vae': vae_name,
|
||||
'clip': clip_names,
|
||||
'sampler': sampler,
|
||||
'resolution': resolution,
|
||||
}
|
||||
|
||||
return models
|
||||
|
||||
|
||||
def _get_authoritative_builder_v2_payload(workflow_data):
|
||||
"""Return authoritative v2 payload from RecipeBuilder/WorkflowBuilder extracted_data.
|
||||
|
||||
New multi-model Builder saves a complete v2 workflow payload into node
|
||||
``extracted_data``. When present, this is the only trustworthy source for
|
||||
extraction because downstream nodes and runtime carriers may not reflect
|
||||
what originally generated the file.
|
||||
"""
|
||||
if not isinstance(workflow_data, dict):
|
||||
return None
|
||||
|
||||
best = None
|
||||
best_order = -10**9
|
||||
best_index = -1
|
||||
|
||||
for index, node in enumerate(workflow_data.get('nodes', [])):
|
||||
if not isinstance(node, dict):
|
||||
continue
|
||||
ntype = str(node.get('type', '') or '')
|
||||
if ntype not in ('RecipeBuilder', 'WorkflowBuilder'):
|
||||
continue
|
||||
ed = node.get('extracted_data')
|
||||
if not isinstance(ed, dict):
|
||||
continue
|
||||
if int(ed.get('version', 0) or 0) < 2:
|
||||
continue
|
||||
if not isinstance(ed.get('models'), dict):
|
||||
continue
|
||||
|
||||
try:
|
||||
order = int(node.get('order', index))
|
||||
except Exception:
|
||||
order = index
|
||||
|
||||
# Last Builder in execution/layout order wins.
|
||||
if (best is None) or (order > best_order) or (order == best_order and index > best_index):
|
||||
best = ed
|
||||
best_order = order
|
||||
best_index = index
|
||||
|
||||
return best
|
||||
|
||||
|
||||
def _get_embedded_extracted_data(workflow_data):
|
||||
"""Return the best ``extracted_data`` dict from a WR/WG or PE node, or *None*.
|
||||
|
||||
Prioritises WorkflowRenderer/WorkflowGenerator over WorkflowBuilder over
|
||||
PromptExtractor, and only returns data that actually contains ``sampler``
|
||||
Prioritises WorkflowRenderer/RecipeRenderer over WorkflowBuilder/RecipeBuilder
|
||||
over PromptExtractor, and only returns data that actually contains ``sampler``
|
||||
or ``resolution`` keys.
|
||||
"""
|
||||
if not workflow_data or not isinstance(workflow_data, dict):
|
||||
@@ -66,9 +260,9 @@ def _get_embedded_extracted_data(workflow_data):
|
||||
has_useful = bool(ed.get('sampler') or ed.get('resolution'))
|
||||
if not has_useful:
|
||||
continue
|
||||
if ntype in ('WorkflowRenderer', 'WorkflowGenerator'):
|
||||
if ntype in ('WorkflowRenderer', 'RecipeRenderer'):
|
||||
rank = 3
|
||||
elif ntype == 'WorkflowBuilder':
|
||||
elif ntype in ('WorkflowBuilder', 'RecipeBuilder'):
|
||||
rank = 2
|
||||
else:
|
||||
rank = 1
|
||||
@@ -88,12 +282,13 @@ def _get_embedded_extracted_data(workflow_data):
|
||||
def extract_sampler_params(prompt_data, workflow_data):
|
||||
"""
|
||||
Extract sampler parameters from KSampler nodes in API or workflow format.
|
||||
Returns a dict with steps_a, steps_b, cfg, seed_a, seed_b, sampler_name, scheduler.
|
||||
Returns a dict with steps_a, steps_b, cfg, denoise, seed_a, seed_b, sampler_name, scheduler.
|
||||
"""
|
||||
params = {
|
||||
'steps_a': 20,
|
||||
'steps_b': None, # WAN Video low-pass steps (None = same as steps_a)
|
||||
'cfg': 7.0,
|
||||
'denoise': 1.0,
|
||||
'seed_a': 0,
|
||||
'seed_b': None, # WAN Video second-sampler seed (None = use same as seed_a)
|
||||
'sampler_name': 'euler',
|
||||
@@ -242,7 +437,7 @@ def extract_vae_info(prompt_data, workflow_data):
|
||||
|
||||
if ct in CHECKPOINT_TYPES and inp.get('ckpt_name'):
|
||||
if not vae_info['name']:
|
||||
vae_info['name'] = '(from checkpoint)'
|
||||
vae_info['name'] = '(Default)'
|
||||
vae_info['source'] = 'checkpoint'
|
||||
# Don't return — a separate VAE loader later overrides this
|
||||
|
||||
@@ -259,7 +454,7 @@ def extract_vae_info(prompt_data, workflow_data):
|
||||
return vae_info
|
||||
|
||||
if ntype in CHECKPOINT_TYPES and widgets and not vae_info['name']:
|
||||
vae_info['name'] = '(from checkpoint)'
|
||||
vae_info['name'] = '(Default)'
|
||||
vae_info['source'] = 'checkpoint'
|
||||
|
||||
# ── Fallback: embedded extracted_data from WG / PE nodes ──────────────
|
||||
@@ -309,7 +504,7 @@ def extract_clip_info(prompt_data, workflow_data):
|
||||
return clip_info
|
||||
|
||||
if ct in CHECKPOINT_TYPES and inp.get('ckpt_name') and not clip_info['names']:
|
||||
clip_info['names'] = ['(from checkpoint)']
|
||||
clip_info['names'] = ['(Default)']
|
||||
clip_info['source'] = 'checkpoint'
|
||||
|
||||
if not clip_info['names'] and workflow_data and isinstance(workflow_data, dict):
|
||||
@@ -335,7 +530,7 @@ def extract_clip_info(prompt_data, workflow_data):
|
||||
return clip_info
|
||||
|
||||
if ntype in CHECKPOINT_TYPES and widgets and not clip_info['names']:
|
||||
clip_info['names'] = ['(from checkpoint)']
|
||||
clip_info['names'] = ['(Default)']
|
||||
clip_info['source'] = 'checkpoint'
|
||||
|
||||
# ── Fallback: embedded extracted_data from WG / PE nodes ──────────────
|
||||
@@ -546,8 +741,8 @@ def resolve_clip_names(clip_names, clip_type=''):
|
||||
|
||||
def _find_embedded_generation_data(workflow_data, prompt_data):
|
||||
"""
|
||||
Look for sampler / resolution / model data embedded by WorkflowRenderer
|
||||
(or legacy WorkflowGenerator) or PromptExtractor. Checks (in priority order):
|
||||
Look for sampler / resolution / model data embedded by RecipeRenderer
|
||||
(or legacy WorkflowRenderer) or PromptExtractor. Checks (in priority order):
|
||||
|
||||
1. WR/WG/WB node ``extracted_data`` (full dict with sampler + resolution)
|
||||
2. WR/WG/WB node ``widgets_values`` containing the ``override_data`` JSON
|
||||
@@ -567,6 +762,7 @@ def _find_embedded_generation_data(workflow_data, prompt_data):
|
||||
'steps_a': s.get('steps_a', s.get('steps', 20)),
|
||||
'steps_b': s.get('steps_b'),
|
||||
'cfg': s.get('cfg', 7.0),
|
||||
'denoise': 1.0,
|
||||
'seed_a': s.get('seed_a', s.get('seed', 0)),
|
||||
'seed_b': s.get('seed_b'),
|
||||
'sampler_name': s.get('sampler_name', 'euler'),
|
||||
@@ -607,6 +803,7 @@ def _find_embedded_generation_data(workflow_data, prompt_data):
|
||||
'steps_a': ov.get('steps_a', ov.get('steps', 20)),
|
||||
'steps_b': ov.get('steps_b'),
|
||||
'cfg': ov.get('cfg', 7.0),
|
||||
'denoise': 1.0,
|
||||
'seed_a': ov.get('seed_a', ov.get('seed', 0)),
|
||||
'seed_b': ov.get('seed_b'),
|
||||
'sampler_name': ov.get('sampler_name', 'euler'),
|
||||
@@ -626,7 +823,7 @@ def _find_embedded_generation_data(workflow_data, prompt_data):
|
||||
if workflow_data and isinstance(workflow_data, dict):
|
||||
for wf_node in workflow_data.get('nodes', []):
|
||||
ntype = wf_node.get('type', '')
|
||||
if ntype in ('WorkflowRenderer', 'WorkflowGenerator', 'WorkflowBuilder'):
|
||||
if ntype in ('WorkflowRenderer', 'RecipeRenderer', 'RecipeBuilder', 'WorkflowBuilder'):
|
||||
# Priority 1: extracted_data
|
||||
ed = wf_node.get('extracted_data')
|
||||
if ed and isinstance(ed, dict):
|
||||
@@ -656,7 +853,7 @@ def _find_embedded_generation_data(workflow_data, prompt_data):
|
||||
for node_id, node_data in prompt_data.items():
|
||||
if not isinstance(node_data, dict):
|
||||
continue
|
||||
if node_data.get('class_type') in ('WorkflowRenderer', 'WorkflowGenerator', 'WorkflowBuilder'):
|
||||
if node_data.get('class_type') in ('WorkflowRenderer', 'RecipeRenderer', 'RecipeBuilder', 'WorkflowBuilder'):
|
||||
inp = node_data.get('inputs', {})
|
||||
_apply_override_json(inp.get('override_data', ''), node_data['class_type'])
|
||||
break
|
||||
@@ -676,7 +873,7 @@ def extract_all_from_file(file_path, source_folder='input'):
|
||||
model_a, model_b,
|
||||
vae {'name', 'source'},
|
||||
clip {'names', 'type', 'source'},
|
||||
sampler {'steps_a', 'steps_b', 'cfg', 'seed_a', 'seed_b', 'sampler_name', 'scheduler'},
|
||||
sampler {'steps_a', 'steps_b', 'cfg', 'denoise', 'seed_a', 'seed_b', 'sampler_name', 'scheduler'},
|
||||
resolution {'width', 'height', 'batch_size', 'length'},
|
||||
is_video (bool)
|
||||
"""
|
||||
@@ -699,10 +896,13 @@ def extract_all_from_file(file_path, source_folder='input'):
|
||||
'loras_b': [],
|
||||
'model_a': '',
|
||||
'model_b': '',
|
||||
'model_c': '',
|
||||
'model_d': '',
|
||||
'models': {},
|
||||
'vae': {'name': '', 'source': 'unknown'},
|
||||
'clip': {'names': [], 'type': '', 'source': 'unknown'},
|
||||
'sampler': {
|
||||
'steps_a': 20, 'steps_b': None, 'cfg': 7.0, 'seed_a': 0, 'seed_b': None,
|
||||
'steps_a': 20, 'steps_b': None, 'cfg': 7.0, 'denoise': 1.0, 'seed_a': 0, 'seed_b': None,
|
||||
'sampler_name': 'euler', 'scheduler': 'normal',
|
||||
},
|
||||
'resolution': {'width': 512, 'height': 512, 'batch_size': 1, 'length': None},
|
||||
@@ -726,6 +926,78 @@ def extract_all_from_file(file_path, source_folder='input'):
|
||||
if not prompt_data and not workflow_data:
|
||||
return result
|
||||
|
||||
# New multi-model Builder format: if a RecipeBuilder/WorkflowBuilder node
|
||||
# embedded a full v2 payload, treat it as authoritative and stop here.
|
||||
builder_v2 = _get_authoritative_builder_v2_payload(workflow_data)
|
||||
if isinstance(builder_v2, dict):
|
||||
models_in = builder_v2.get('models') if isinstance(builder_v2.get('models'), dict) else {}
|
||||
model_slots = ('model_a', 'model_b', 'model_c', 'model_d')
|
||||
models = {}
|
||||
for slot in model_slots:
|
||||
block = models_in.get(slot)
|
||||
if isinstance(block, dict):
|
||||
models[slot] = block
|
||||
|
||||
result['models'] = models
|
||||
for slot in model_slots:
|
||||
block = models.get(slot)
|
||||
result[slot] = str((block or {}).get('model', '') or '') if isinstance(block, dict) else ''
|
||||
|
||||
# Primary preview fields come from model_a for backward compatibility.
|
||||
primary = models.get('model_a') if isinstance(models.get('model_a'), dict) else None
|
||||
if not primary:
|
||||
for slot in model_slots:
|
||||
candidate = models.get(slot)
|
||||
if isinstance(candidate, dict):
|
||||
primary = candidate
|
||||
break
|
||||
|
||||
if isinstance(primary, dict):
|
||||
result['positive_prompt'] = str(primary.get('positive_prompt', '') or '')
|
||||
result['negative_prompt'] = str(primary.get('negative_prompt', '') or '')
|
||||
result['loras_a'] = _normalize_builder_lora_list(primary.get('loras', []))
|
||||
model_b_block = models.get('model_b') if isinstance(models.get('model_b'), dict) else None
|
||||
result['loras_b'] = _normalize_builder_lora_list(model_b_block.get('loras', [])) if isinstance(model_b_block, dict) else []
|
||||
|
||||
sampler = primary.get('sampler') if isinstance(primary.get('sampler'), dict) else {}
|
||||
sampler_b = model_b_block.get('sampler') if isinstance(model_b_block, dict) and isinstance(model_b_block.get('sampler'), dict) else {}
|
||||
result['sampler'] = {
|
||||
'steps_a': int(sampler.get('steps', 20) or 20),
|
||||
'steps_b': int(sampler_b.get('steps')) if sampler_b.get('steps') is not None else None,
|
||||
'cfg': float(sampler.get('cfg', 7.0) or 7.0),
|
||||
'denoise': float(sampler.get('denoise', 1.0) or 1.0),
|
||||
'seed_a': int(sampler.get('seed', 0) or 0),
|
||||
'seed_b': int(sampler_b.get('seed')) if sampler_b.get('seed') is not None else None,
|
||||
'sampler_name': str(sampler.get('sampler_name', 'euler') or 'euler'),
|
||||
'scheduler': str(sampler.get('scheduler', 'normal') or 'normal'),
|
||||
}
|
||||
|
||||
resolution = primary.get('resolution') if isinstance(primary.get('resolution'), dict) else {}
|
||||
result['resolution'] = {
|
||||
'width': int(resolution.get('width', 512) or 512),
|
||||
'height': int(resolution.get('height', 512) or 512),
|
||||
'batch_size': int(resolution.get('batch_size', 1) or 1),
|
||||
'length': resolution.get('length'),
|
||||
}
|
||||
|
||||
vae_name = str(primary.get('vae', '') or '')
|
||||
result['vae'] = {'name': vae_name, 'source': 'RecipeBuilder'}
|
||||
clip_names = primary.get('clip', []) if isinstance(primary.get('clip'), list) else []
|
||||
result['clip'] = {
|
||||
'names': [str(x) for x in clip_names if str(x or '').strip()],
|
||||
'type': str(primary.get('clip_type', '') or ''),
|
||||
'source': 'RecipeBuilder',
|
||||
}
|
||||
|
||||
# Video if any slot declares latent length.
|
||||
result['is_video'] = any(
|
||||
isinstance(models.get(slot), dict) and
|
||||
isinstance(models[slot].get('resolution'), dict) and
|
||||
models[slot]['resolution'].get('length') is not None
|
||||
for slot in model_slots
|
||||
)
|
||||
return result
|
||||
|
||||
extracted = parse_workflow_for_prompts(prompt_data, workflow_data)
|
||||
result['positive_prompt'] = extracted.get('positive_prompt', '')
|
||||
result['negative_prompt'] = extracted.get('negative_prompt', '')
|
||||
@@ -742,6 +1014,34 @@ def extract_all_from_file(file_path, source_folder='input'):
|
||||
result['clip'] = extract_clip_info(prompt_data, workflow_data)
|
||||
result['resolution'] = extract_resolution(prompt_data, workflow_data)
|
||||
|
||||
# Prefer explicit builder slot mapping when the workflow contains RecipeBuilder nodes.
|
||||
builder_models = extract_recipe_builder_models_from_workflow(workflow_data)
|
||||
if builder_models:
|
||||
result['models'] = builder_models
|
||||
for slot in ('model_a', 'model_b', 'model_c', 'model_d'):
|
||||
block = builder_models.get(slot)
|
||||
if isinstance(block, dict):
|
||||
result[slot] = str(block.get('model', '') or '')
|
||||
|
||||
model_a_block = builder_models.get('model_a') if isinstance(builder_models.get('model_a'), dict) else None
|
||||
model_b_block = builder_models.get('model_b') if isinstance(builder_models.get('model_b'), dict) else None
|
||||
if model_a_block:
|
||||
result['positive_prompt'] = str(model_a_block.get('positive_prompt', result['positive_prompt']) or '')
|
||||
result['negative_prompt'] = str(model_a_block.get('negative_prompt', result['negative_prompt']) or '')
|
||||
result['loras_a'] = model_a_block.get('loras', result['loras_a']) if isinstance(model_a_block.get('loras'), list) else result['loras_a']
|
||||
result['sampler'] = model_a_block.get('sampler', result['sampler']) if isinstance(model_a_block.get('sampler'), dict) else result['sampler']
|
||||
result['resolution'] = model_a_block.get('resolution', result['resolution']) if isinstance(model_a_block.get('resolution'), dict) else result['resolution']
|
||||
if model_a_block.get('vae'):
|
||||
result['vae'] = {'name': str(model_a_block.get('vae') or ''), 'source': 'RecipeBuilder'}
|
||||
if isinstance(model_a_block.get('clip'), list):
|
||||
result['clip'] = {
|
||||
'names': model_a_block.get('clip') or [],
|
||||
'type': str(model_a_block.get('clip_type', result['clip'].get('type', '')) or ''),
|
||||
'source': 'RecipeBuilder',
|
||||
}
|
||||
if model_b_block and isinstance(model_b_block.get('loras'), list):
|
||||
result['loras_b'] = model_b_block.get('loras', result['loras_b'])
|
||||
|
||||
# ── A1111 / Forge override ────────────────────────────────────────────
|
||||
# When prompt_data is a parsed A1111 dict (has 'prompt' + 'loras' keys)
|
||||
# the ComfyUI extraction functions won't find anything. Apply the
|
||||
@@ -763,8 +1063,8 @@ def extract_all_from_file(file_path, source_folder='input'):
|
||||
_r['width'] = prompt_data['width']
|
||||
_r['height'] = prompt_data['height']
|
||||
|
||||
# ── Embedded data override (WorkflowRenderer / PromptExtractor) ──────
|
||||
# When a WorkflowRenderer generated the image there are no standalone
|
||||
# ── Embedded data override (RecipeRenderer / PromptExtractor) ──────
|
||||
# When a RecipeRenderer generated the image there are no standalone
|
||||
# KSampler / EmptyLatentImage nodes. Look for authoritative values in:
|
||||
# 1. extracted_data on the WG or PE node
|
||||
# 2. widgets_values override_data JSON on the WG node
|
||||
@@ -859,6 +1159,10 @@ def _build_sampler_dict(sampler, family):
|
||||
elif 'steps' in d:
|
||||
d.pop('steps')
|
||||
d.setdefault('steps_a', 20)
|
||||
try:
|
||||
d['denoise'] = 1.0 if d.get('denoise') is None else float(d.get('denoise', 1.0))
|
||||
except (TypeError, ValueError):
|
||||
d['denoise'] = 1.0
|
||||
if family in ('wan_video_i2v', 'wan_video_t2v'):
|
||||
# For WAN dual-sampler: if steps_b not set, split steps_a evenly
|
||||
if d.get('steps_b') is None:
|
||||
@@ -873,7 +1177,7 @@ def _build_sampler_dict(sampler, family):
|
||||
|
||||
def build_simplified_workflow_data(extracted, overrides=None, sampler_params=None):
|
||||
"""
|
||||
Build the shared workflow_data dict that both WorkflowBuilder and PromptExtractor output.
|
||||
Build the shared workflow_data dict that both RecipeBuilder and PromptExtractor output.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
@@ -886,7 +1190,7 @@ def build_simplified_workflow_data(extracted, overrides=None, sampler_params=Non
|
||||
if overrides is None:
|
||||
overrides = {}
|
||||
sampler = sampler_params if sampler_params is not None else extracted.get('sampler', {
|
||||
'steps_a': 20, 'steps_b': None, 'cfg': 7.0, 'seed_a': 0, 'seed_b': None,
|
||||
'steps_a': 20, 'steps_b': None, 'cfg': 7.0, 'denoise': 1.0, 'seed_a': 0, 'seed_b': None,
|
||||
'sampler_name': 'euler', 'scheduler': 'normal',
|
||||
})
|
||||
|
||||
@@ -945,16 +1249,18 @@ def build_simplified_workflow_data(extracted, overrides=None, sampler_params=Non
|
||||
# original graph — they shouldn't override the checkpoint's built-in ones.
|
||||
if loader_type == 'checkpoint':
|
||||
if not vae_override_explicit or not vae_val or vae_val.startswith('('):
|
||||
vae_val = '(from checkpoint)'
|
||||
vae_val = '(Default)'
|
||||
if not clip_override_explicit or not clip_val or clip_val == [] or \
|
||||
(len(clip_val) == 1 and (not clip_val[0] or clip_val[0].startswith('('))):
|
||||
clip_val = ['(from checkpoint)']
|
||||
clip_val = ['(Default)']
|
||||
|
||||
return {
|
||||
output = {
|
||||
"_source": overrides.get('_source', 'PromptExtractor'),
|
||||
"family": family,
|
||||
"model_a": overrides.get('model_a', extracted.get('model_a', '')),
|
||||
"model_b": overrides.get('model_b', extracted.get('model_b', '')),
|
||||
"model_c": overrides.get('model_c', extracted.get('model_c', '')),
|
||||
"model_d": overrides.get('model_d', extracted.get('model_d', '')),
|
||||
"positive_prompt": overrides.get('positive_prompt', extracted.get('positive_prompt', '')),
|
||||
"negative_prompt": overrides.get('negative_prompt', extracted.get('negative_prompt', '')),
|
||||
"loras_a": extracted.get('loras_a', []),
|
||||
@@ -971,3 +1277,11 @@ def build_simplified_workflow_data(extracted, overrides=None, sampler_params=Non
|
||||
"length": overrides.get('length', extracted.get('resolution', {}).get('length', None)),
|
||||
},
|
||||
}
|
||||
|
||||
# Preserve full v2 model blocks when available from RecipeBuilder-based workflows.
|
||||
extracted_models = extracted.get('models', {}) if isinstance(extracted.get('models'), dict) else {}
|
||||
if extracted_models:
|
||||
output['version'] = 2
|
||||
output['models'] = extracted_models
|
||||
|
||||
return output
|
||||
|
||||
@@ -29,6 +29,23 @@ import folder_paths
|
||||
# ─── Family definitions ──────────────────────────────────────────────────────
|
||||
|
||||
MODEL_FAMILIES = {
|
||||
# ── Ernie Image (Flux2 template/runtime) ─────────────────────────────────
|
||||
"ernie": {
|
||||
"label": "Ernie",
|
||||
# Name-only detection to avoid accidental family hits from unrelated
|
||||
# checkpoint folder names.
|
||||
"folders": [],
|
||||
"names": ["ernie-image-turbo", "ernie-image", "ernie"],
|
||||
# Ernie should be treated as diffusion/UNet family, not checkpoints.
|
||||
"model_folders": ["diffusion_models", "unet", "unet_gguf"],
|
||||
"vae": ["flux2-vae", "flux2_vae"],
|
||||
"clip_exact": ["ministral-3-3b.safetensors"],
|
||||
"clip": ["ministral"],
|
||||
"clip_exclude": ["prompt-enhancer", "enhancer", "mistral_3_small_flux2_fp8"],
|
||||
"clip_type": "flux2",
|
||||
"sampler": "flux2",
|
||||
},
|
||||
|
||||
# ── Flux 2 / Klein ───────────────────────────────────────────────────────
|
||||
"flux2": {
|
||||
"label": "Flux 2",
|
||||
@@ -146,7 +163,7 @@ MODEL_FAMILIES = {
|
||||
"folders": ["illustrious/", "pony/", "sdxl/"],
|
||||
"names": ["sdxl", "illustrious", "noob", "pony"],
|
||||
# SDXL uses its own finely-tuned VAE (sdxl_vae / sdxl-vae) or the
|
||||
# widely-used vae-ft-mse-840000 (originally SD1.5 but SDXL-compatible).
|
||||
# widely-used vae-ft-mse-840000 variant.
|
||||
"vae": ["sdxl_vae", "sdxl-vae", "vae-ft-mse"],
|
||||
# SDXL uses dual text encoders: CLIP-L + CLIP-G.
|
||||
"clip": ["clip_l", "clip_g"],
|
||||
@@ -154,19 +171,6 @@ MODEL_FAMILIES = {
|
||||
"sampler": "standard",
|
||||
"checkpoint": True,
|
||||
},
|
||||
# ── SD 1.5 ───────────────────────────────────────────────────────────────
|
||||
"sd15": {
|
||||
"label": "SD 1.5",
|
||||
"folders": [],
|
||||
"names": ["sd-1", "sd_1", "sd1", "v1-5", "v1_5", "v1.5", "dreamshaper", "realistic"],
|
||||
# SD1.5 canonical VAE: vae-ft-mse-840000 or vae-ft-ema-560000.
|
||||
"vae": ["vae-ft-mse-840000", "vae-ft-ema-560000", "orangemix", "blessed2"],
|
||||
# SD1.5 uses a single CLIP-L encoder only (NOT CLIP-G like SDXL).
|
||||
"clip": ["clip_l"],
|
||||
"clip_exclude": ["clip_g", "t5xxl", "umt5", "qwen", "gemma"],
|
||||
"sampler": "standard",
|
||||
"checkpoint": True,
|
||||
},
|
||||
# ── Qwen Image ───────────────────────────────────────────────────────────
|
||||
"qwen_image": {
|
||||
"label": "Qwen Image",
|
||||
@@ -183,6 +187,7 @@ MODEL_FAMILIES = {
|
||||
# Compatibility groups — checkpoint families that can share each other's models.
|
||||
# VAE/CLIP are NOT grouped (they differ per family) — model weights only.
|
||||
MODEL_COMPAT_GROUPS = [
|
||||
{"ernie"},
|
||||
{"sdxl"}, # SDXL-arch — all merged into one now
|
||||
{"flux1"}, # Flux1 variants — all merged into one now
|
||||
{"zimage"}, # Z-Image — all merged
|
||||
@@ -193,9 +198,9 @@ MODEL_COMPAT_GROUPS = [
|
||||
# Sampling strategy keys (referenced by workflow_builder.py / workflow_renderer.py)
|
||||
# Each key maps to a specific sampling code path.
|
||||
SAMPLER_STRATEGIES = {
|
||||
"standard": "standard", # KSampler — SD1.5, SDXL, Qwen
|
||||
"flux": "flux", # SamplerCustomAdvanced + BasicGuider (Flux1, LTX-Video)
|
||||
"flux2": "flux2", # SamplerCustomAdvanced + CFGGuider (Klein/Flux2)
|
||||
"standard": "standard", # KSampler — SDXL, Qwen
|
||||
"flux": "flux", # SamplerCustomAdvanced + BasicGuider (Flux1)
|
||||
"flux2": "flux2", # SamplerCustomAdvanced + CFGGuider (Klein/Flux2/Ernie)
|
||||
"zimage": "zimage", # ModelSamplingAuraFlow + standard KSampler (Z-Image)
|
||||
"wan_image": "wan_image", # Single KSampler — WAN Image
|
||||
"wan_video": "wan_video", # Dual KSamplerAdvanced high/low (WAN Video i2v + t2v)
|
||||
@@ -204,8 +209,8 @@ SAMPLER_STRATEGIES = {
|
||||
# Workflow template filenames (in workflows/api/) keyed by family.
|
||||
# Maps each family key to its _api.json and _map.json stem.
|
||||
FAMILY_WORKFLOW_STEMS = {
|
||||
"ernie": "flux_2",
|
||||
"sdxl": "sdxl",
|
||||
"sd15": None, # No template yet — falls back to hardcoded
|
||||
"flux1": "flux_1",
|
||||
"flux2": "flux_2",
|
||||
"zimage": "z_image",
|
||||
@@ -365,7 +370,8 @@ def list_compatible_vaes(family, return_recommended=False):
|
||||
Matching order:
|
||||
1. vae_exact — full basename match (e.g. "ae.safetensors"), case-insensitive
|
||||
2. vae — substring match against basename or full relative path
|
||||
Falls back to all VAEs when no patterns are defined or nothing matched.
|
||||
Checkpoint families may fall back to all VAEs when no matches are found.
|
||||
Non-checkpoint families stay strict (empty list) to avoid cross-family leaks.
|
||||
"""
|
||||
def _ret(lst, rec):
|
||||
return (sorted(lst), rec) if return_recommended else sorted(lst)
|
||||
@@ -382,7 +388,8 @@ def list_compatible_vaes(family, return_recommended=False):
|
||||
|
||||
if not exact_names and not patterns:
|
||||
try:
|
||||
return _ret(folder_paths.get_filename_list("vae"), None)
|
||||
all_vaes = folder_paths.get_filename_list("vae")
|
||||
return _ret(all_vaes if spec.get("checkpoint", False) else [], None)
|
||||
except Exception:
|
||||
return _ret([], None)
|
||||
|
||||
@@ -416,7 +423,7 @@ def list_compatible_vaes(family, return_recommended=False):
|
||||
|
||||
if matched:
|
||||
return _ret(matched, recommended)
|
||||
return _ret(all_vaes, None)
|
||||
return _ret(all_vaes if is_checkpoint else [], None)
|
||||
|
||||
|
||||
def list_compatible_clips(family, return_recommended=False):
|
||||
@@ -427,7 +434,8 @@ def list_compatible_clips(family, return_recommended=False):
|
||||
1. clip_exclude — if ANY exclude pattern is found in the basename/path, skip the file
|
||||
2. clip_exact — full basename match, case-insensitive
|
||||
3. clip — substring match against basename or full relative path
|
||||
Falls back to all CLIPs when no patterns are defined or nothing matched.
|
||||
Checkpoint families may fall back to all CLIPs when no matches are found.
|
||||
Non-checkpoint families stay strict (empty list) to avoid cross-family leaks.
|
||||
"""
|
||||
def _ret(lst, rec):
|
||||
return (sorted(lst), rec) if return_recommended else sorted(lst)
|
||||
@@ -443,7 +451,7 @@ def list_compatible_clips(family, return_recommended=False):
|
||||
|
||||
if not exact_names and not patterns:
|
||||
clips = _gather_all_clips()
|
||||
return _ret(clips, None)
|
||||
return _ret(clips if spec.get("checkpoint", False) else [], None)
|
||||
|
||||
all_clips = _gather_all_clips()
|
||||
|
||||
@@ -476,7 +484,7 @@ def list_compatible_clips(family, return_recommended=False):
|
||||
|
||||
if matched:
|
||||
return _ret(matched, recommended)
|
||||
return _ret(all_clips, None)
|
||||
return _ret(all_clips if is_checkpoint else [], None)
|
||||
|
||||
|
||||
def _gather_all_clips():
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
[project]
|
||||
name = "prompt-manager"
|
||||
description = "A comprehensive prompt management system for ComfyUI that saves complete workflow recipes including prompts, LoRAs, and their settings. Features AI-powered prompt generation, prompt extraction from ComfyUI/A1111 images and videos, and Dual LoRA Stack support for Wan workflows."
|
||||
version = "2.0.0"
|
||||
version = "2.5.1"
|
||||
license = {file = "LICENSE"}
|
||||
# classifiers = [
|
||||
# # For OS-independent nodes (works on all operating systems)
|
||||
|
||||
@@ -0,0 +1,660 @@
|
||||
# ComfyUI Prompt Manager
|
||||
## A comprehensive prompt and workflow toolkit for [ComfyUI](https://github.com/comfyanonymous/ComfyUI) — Save, Generate, Extract, Build, and Reuse workflows with full LoRA support.
|
||||
|
||||
A complete prompt and workflow management suite featuring:
|
||||
|
||||
## v2.0 Introduces: Workflow Extractor + Workflow Builder + Workflow Renderer + Workflow Manager
|
||||
|
||||
The goal of this v2.0 workflow layer is to strip workflows down to their core elements so they are easier to understand, edit, and reuse.
|
||||
|
||||
- Extract metadata from source images and videos (ComfyUI or A1111/Forge)
|
||||
- Reduce complex graphs into a clean, editable workflow core
|
||||
- Rebuild and run from that simplified core with Workflow Builder to Workflow Renderer
|
||||
- Save and reuse clean workflow entries through Workflow Manager
|
||||
- Combine with Prompt tools (Prompt Manager, and Prompt Generator) for easier prompt creation and generation.
|
||||
|
||||
Think of it as workflow de-spaghetti: keep the important parts, remove unnecessary complexity.
|
||||
|
||||
This release marks version 2.0.0. More polish and quality-of-life improvements are planned.
|
||||
|
||||
**Prompt Manager** — Save and organize prompts with categories, complete with matching LoRA stacks, trigger words, and thumbnail previews. Supports dual LoRA stacks for complex workflows like Wan videos. Toggle LoRAs on/off or adjust strengths directly from saved presets. Supports workflow_data input from Workflow Builder or Prompt Extractor to pull workflow prompts and LoRA stacks directly into PMA. Will also remap LoRAs if paths differ.
|
||||
|
||||
**Prompt Generator** — Generate and enhance prompts using local LLMs via [llama.cpp](https://github.com/ggerganov/llama.cpp) or [Ollama](https://ollama.com). Supports text enhancement, image analysis with vision models (Qwen3.5), and thinking mode for deeper reasoning. Analyze up to 5 images at once.
|
||||
|
||||
**Prompt Extractor** — Extract prompts, LoRA configurations, and checkpoint/model paths from existing images, videos, or JSON workflow files. Extracts the first frame from any video. Automatically parses embedded metadata and outputs active LoRAs as LoRA stacks, plus resolved model paths (High/Low for dual-model workflows like Wan). Supports ComfyUI, A1111/Forge, and WebP metadata formats. When used with Prompt Manager Advanced, LoRAs are automatically found if available, regardless of path. For those that are not, right-click offers the option to look for them on Civitai. Browse files from both your input and output folders.
|
||||
|
||||
**Prompt Model Loader** — Load checkpoints, diffusion, or GGUF models from a string path output by Prompt Extractor. Auto-detects whether the model is a checkpoint (outputs MODEL + CLIP + VAE) or a diffusion/UNET/GGUF model (outputs MODEL only). Displays model type badge and name directly on the node. Works around ComfyUI's combo type limitation, allowing extracted model paths to connect directly to a loader. Supports [ComfyUI-GGUF](https://github.com/city96/ComfyUI-GGUF) models when the extension is installed.
|
||||
|
||||
**Workflow Suite of Tools** — Build and re-render extracted workflows with dedicated nodes:
|
||||
|
||||
- **Workflow Extractor**: Reads workflow metadata and normalizes it into reusable workflow_data.
|
||||
- **Workflow Builder**: Lets you edit and assemble a clean core workflow from extracted metadata.
|
||||
- **Workflow Renderer**: Runs built-in workflow templates for near one-click generation after Builder setup.
|
||||
- **Workflow Bridge**: Passes workflow context and routing data between nodes cleanly.
|
||||
- **Workflow Model Loader**: Resolves and loads the right model/checkpoint from workflow data.
|
||||
- **Workflow Manager**: Saves and reuses cleaned workflow entries for fast reruns.
|
||||
|
||||
Builder + Renderer + Workflow Manager provides a streamlined generation path: configure Builder once, connect Renderer and Save Image/Save Video, and save both the output and the resulting workflow.
|
||||
|
||||
Built-in workflow support includes Flux 1, Flux 2, SDXL, Wan, Qwen, Z-Image, Wan Image, and Wan Video (I2V and T2V).
|
||||
|
||||
**Workflow Builder + Workflow Manager Reuse Loop** — Build workflow_data from extracted image/video metadata or from Workflow Builder directly, then save and reuse those workflow entries through Workflow Manager.
|
||||
___
|
||||
|
||||
<div align="center">
|
||||
<figcaption>Prompt Manager Advanced, with Lora and trigger word support</figcaption>
|
||||
<img src="docs/prompt_manager_advanced.png" alt="Prompt Manager">
|
||||
</div>
|
||||
<div align="center">
|
||||
<figcaption>Prompt Extractor connected to Manager Advanced, so workflow can be saved with Loras</figcaption>
|
||||
<img src="docs/prompt_extractor.png" alt="Prompt Manager">
|
||||
</div>
|
||||
<div align="center">
|
||||
<figcaption>Advanced Prompt Generator</figcaption>
|
||||
<img src="docs/prompt_generator_advanced.png" alt="Prompt Manager">
|
||||
</div>
|
||||
<div align="center">
|
||||
<figcaption>Simple Prompt Generator</figcaption>
|
||||
<img src="docs/prompt_manager.png" alt="Prompt Manager">
|
||||
</div>
|
||||
<div align="center">
|
||||
<figcaption>Workflow Builder</figcaption>
|
||||
<img src="docs/workflow_builder.jpg" alt="Prompt Manager">
|
||||
</div>
|
||||
|
||||
### Key features:
|
||||
### Prompt Manager:
|
||||
- **Category Organization**: Create and manage multiple categories to organize your prompts
|
||||
- **Save & Load Prompts**: Quickly save and recall your favorite prompts with custom names
|
||||
- **NSFW Tagging**: Mark categories and individual prompts as NSFW with visual badge indicator on the node title bar
|
||||
- **NSFW Filtering**: Hide/show NSFW content via a global preference — NSFW categories and prompts are filtered from dropdowns when hidden
|
||||
- **LLM Input Toggle**: Connect text outputs from other nodes and toggle between using them or your internal prompts
|
||||
- **LLM Input Toggle**: When in use, display of categories and prompt is disabled, allowing user to switch category and save.
|
||||
- **Persistent Storage**: All prompts saved in your ComfyUI user folder
|
||||
|
||||
### Prompt Manager Advanced:
|
||||
- **All Prompt Manager Features**: Everything from the basic Prompt Manager, plus LoRA and trigger-word integration
|
||||
- **NSFW Tagging**: Mark categories and individual prompts as NSFW — red "NSFW" badge appears on the prompt selector and in the thumbnail browser
|
||||
- **NSFW Filtering**: Session-persistent NSFW toggle button in the thumbnail browser to show/hide NSFW content; navigation arrows skip NSFW entries when hidden
|
||||
- **List View Mode**: Switch between thumbnail grid and compact list view in the prompt browser, with session-persistent preference
|
||||
- **Prompt Thumbnails**: Save thumbnail images with your prompts for visual identification in the dropdown
|
||||
- **Dual LoRA Stack Support**: Two separate LoRA stack inputs/outputs for complex workflows (e.g., Wan video with different LoRAs for image and video)
|
||||
- **Visual LoRA Tags**: See connected LoRAs as clickable tags with strength values
|
||||
- **Toggle LoRAs On/Off**: Click any LoRA tag to enable/disable it without disconnecting
|
||||
- **Editable Strengths**: Click the strength value on any tag to adjust it inline
|
||||
- **Trigger Words Support**: Save and display trigger words alongside prompts and LoRAs; can use [ComfyUI-Lora-Manager](https://github.com/infantesimone/ComfyUI-Lora-Manager) trigger words.
|
||||
- **Right-Click to Delete**: Right-click any LoRA or trigger word tag to remove it
|
||||
- **Save LoRAs with Prompts**: When you save a prompt, the current LoRA configuration is saved with it
|
||||
- **Override Mode**: Toggle "Override Lora" to ignore connected inputs and use only saved preset LoRAs
|
||||
- **Merge Mode**: When override is off, connected LoRAs are merged with saved presets
|
||||
- **Workflow Data Input**: Optional workflow_data input from Workflow Builder or Prompt Extractor, with use_workflow_data toggle support to use extracted prompt and LoRA stacks directly in PMA
|
||||
- **LoRA Manager Integration**: If [ComfyUI-Lora-Manager](https://github.com/infantesimone/ComfyUI-Lora-Manager) is installed, hovering over LoRA tags shows preview images
|
||||
- **Missing LoRA Detection**: LoRAs that aren't found on your system are highlighted in red
|
||||
- **Thumbnail Generation**: Right-click any prompt to generate a thumbnail using a selectable checkpoint model. Model choice persists in ComfyUI preferences.
|
||||
|
||||
### Prompt Extractor:
|
||||
- **Extract from Images/Videos**: Load images or videos and extract embedded prompts, LoRAs, and workflow metadata
|
||||
- **Model/Checkpoint Extraction**: Extracts checkpoint and UNET model paths from workflows, with High/Low (A/B) assignment for dual-model setups like Wan video
|
||||
- **A1111/Forge Support**: Parses A1111 parameters format to extract prompts, LoRAs, and model names from Forge/A1111 generated images
|
||||
- **WebP Metadata Support**: Reads EXIF metadata from WebP images (RIFF format parser)
|
||||
- **JSON Workflow Support**: Browse and load JSON workflow files directly to extract prompts and LoRA configurations
|
||||
- **Input/Output Folder Switching**: Toggle between browsing your input or output folder directly from the node
|
||||
- **Dual LoRA Stack Output**: Outputs two separate LoRA stacks for workflows using dual stacking (e.g., Wan video)
|
||||
- **Active LoRA Filtering**: Only extracts LoRAs that are marked as active in the source workflow
|
||||
- **Wide Node Compatibility**: Supports 11+ model loader types including CheckpointLoader, UNETLoader, UnetLoaderGGUF, DiffusionModelLoader, WanVideoModelLoader, CyberdyneModelHub, and more
|
||||
- **Preview in Manager**: View extracted data and repathed LoRAs using Manager Advanced.
|
||||
|
||||
### Prompt Model Loader:
|
||||
- **String-to-Model Loading**: Takes a model path string (from Prompt Extractor) and loads the model directly
|
||||
- **Auto-Detection**: Automatically detects whether the path is a checkpoint (returns MODEL + CLIP + VAE) or diffusion/UNET/GGUF model (returns MODEL only)
|
||||
- **GGUF Support**: Loads GGUF models when [ComfyUI-GGUF](https://github.com/city96/ComfyUI-GGUF) is installed, with automatic runtime detection
|
||||
- **Visual Model Info**: Displays model type badge (Checkpoint/Diffusion/GGUF) and model name directly on the node
|
||||
- **State Persistence**: Model info display and output slot visibility persist across tab switches and workflow reloads
|
||||
- **Graceful Error Handling**: Displays a red "NOT FOUND" badge instead of crashing when a model path cannot be resolved
|
||||
- **Model Path Resolution**: Works with both full paths and relative paths, searching checkpoints, diffusion_models, and unet folders
|
||||
- **Weight Dtype Support**: Optional weight dtype selection for memory optimization
|
||||
- **Family Filtering Tip**: Family filtering works best when model families are separated into clear folder structures (for example folders that include family cues like i2v/t2v/high/low).
|
||||
|
||||
### Prompt Generator
|
||||
- **Three Generation Modes**: Enhance text prompts, analyze images, or analyze images with custom instructions
|
||||
- **Dual Backend Support**: Use llama.cpp (local server, default) or Ollama as the LLM backend
|
||||
- **Prompt Enhancement**: Transform basic prompts into detailed descriptions using local LLMs
|
||||
- **Vision Analysis**: Analyze images with vision-capable models to generate detailed descriptions
|
||||
- **Custom Image Analysis**: Provide your own instructions for image analysis
|
||||
- **JSON Output**: Optional structured JSON output with scene breakdown
|
||||
- **Thinking Support**: Support Thinking models to perform deeper generative reasoning.
|
||||
- **Automatic Server Management**: Starts/stops llama.cpp server as needed, with automatic shut off at exit.
|
||||
- **Smart Model Selection**: Auto-selects appropriate model based on mode, using mmproj-based vision detection.
|
||||
|
||||
### Prompt Generator Options
|
||||
- **Model Selection**: Choose from local models or download Qwen3.5 models from HuggingFace
|
||||
- **Auto-Download**: Automatically downloads both model and required mmproj files for vision models
|
||||
- **LLM Parameters**: Fine-tune temperature, top_k, top_p, min_p, repeat_penalty and context size.
|
||||
- **Custom Instructions**: Override default system prompt for different enhancement styles.
|
||||
- **Extra Image Inputs**: Combine up to 5 images to generate your prompt.
|
||||
- **Console Debugging**: Enable outputting the entire process to the console for debugging purposes.
|
||||
|
||||
### Preference Options
|
||||
- Set choices for preferred models for both base mode and vision mode.
|
||||
- Set a new default model location. Previous folders (gguf and llm) are still scanned, but new downloads are saved to the new default.
|
||||
- Set a custom location for Llama.cpp. If Llama.cpp was not added to your system PATH, this option lets you specify its location.
|
||||
- **LLM Backend**: Choose between llama.cpp (default) or Ollama as the generation backend.
|
||||
- **Ollama Settings**: Configure Ollama URL and keep-alive duration for model memory management.
|
||||
|
||||
|
||||
## Installation
|
||||
|
||||
1. Navigate to your ComfyUI custom nodes directory:
|
||||
```
|
||||
cd ComfyUI/custom_nodes/
|
||||
```
|
||||
|
||||
2. Clone this repository:
|
||||
```bash
|
||||
git clone https://github.com/FranckyB/ComfyUI-Prompt-Manager.git
|
||||
```
|
||||
3. Install dependencies:
|
||||
```bash
|
||||
cd ComfyUI-Prompt-Manager
|
||||
pip install -r requirements.txt
|
||||
```
|
||||
4. Install [llama.cpp](https://github.com/ggml-org/llama.cpp/tree/master)
|
||||
Windows:
|
||||
```bash
|
||||
winget install llama.cpp
|
||||
```
|
||||
Linux:
|
||||
```bash
|
||||
brew install llama.cpp
|
||||
```
|
||||
5. If you have them, place your .gguf models in the models/gguf folder, or set your preferred folder path in preferences.
|
||||
|
||||
6. Restart ComfyUI
|
||||
|
||||
## Usage
|
||||
|
||||
### Prompt Manager
|
||||
|
||||
1. **Add the Node**: Add Node → Prompt Manager
|
||||
2. **Select a Category**: Use the dropdown to choose from your categories
|
||||
3. **Choose a Prompt**: Select a saved prompt from the name dropdown
|
||||
4. **Connect prompt output**: Connect Prompt Manager output to your clip text encode node.
|
||||
|
||||
### Prompt Manager Advanced
|
||||
|
||||
1. **Add the Node**: Add Node → Prompt Manager → Prompt Manager Advanced
|
||||
2. **Connect LoRA Stackers**: Connect LoRA stacker nodes (e.g., from LoRA Manager) to `lora_stack_a` and/or `lora_stack_b` inputs
|
||||
3. **View LoRA Tags**: Connected LoRAs appear as clickable tags showing name and strength
|
||||
4. **Toggle LoRAs**: Click a tag to enable/disable that LoRA (disabled tags turn gray)
|
||||
5. **Adjust Strength**: Click the strength number on a tag to edit it inline
|
||||
6. **Save with LoRAs**: Click "Save Prompt" to save both the prompt text and current LoRA configuration
|
||||
7. **Workflow Input (Optional)**: Connect workflow_data from Workflow Builder or Prompt Extractor and enable use_workflow_data to use extracted prompt and LoRA stacks in PMA
|
||||
8. **Override Mode**: Enable "Override Lora" checkbox to ignore connected inputs and use only the saved preset LoRAs
|
||||
9. **Connect Outputs**: Use `lora_stack_a` and `lora_stack_b` outputs with the Apply LoRA Stack node
|
||||
|
||||
### Prompt Extractor
|
||||
|
||||
1. **Add the Node**: Add Node → Prompt Manager → Prompt Extractor
|
||||
2. **Choose Source Folder**: Use the `source_folder` dropdown to browse files from either your **input** or **output** folder
|
||||
3. **Load Media**: Select an image or video from the file browser, or drag-and-drop files onto the node
|
||||
4. **JSON Workflows**: Supports extracting from JSON workflow files directly
|
||||
5. **Extract Data**: The node automatically extracts prompts, LoRAs, and trigger words from embedded metadata
|
||||
6. **View Results**: Extracted positive/negative prompts display in the text outputs, LoRA stacks output as LORA_STACK
|
||||
7. **Use with Manager**: Connect the LoRA stack outputs to Prompt Manager Advanced to view and save the extracted configuration
|
||||
|
||||
|
||||
### Prompt Generator
|
||||
|
||||
**Basic Usage** (assuming a model is present in models\gguf):
|
||||
1. **Add the Node**: Add Node → Prompt Generator
|
||||
2. **Select Mode**: Choose from:
|
||||
- "Enhance User Prompt" - Improve text prompts with LLM
|
||||
- "Analyze Image" - Generate detailed image descriptions
|
||||
- "Analyze Image with Prompt" - Analyze images with custom instructions
|
||||
3. **Connect inputs**: Connect image for vision modes, or just use text for enhancement mode
|
||||
4. **Output as Json**: Use Format_as_Json to experiment with Json prompts.
|
||||
5. **Push the LLM**: Use enable_thinking to enable the model to perform deeper generative reasoning before producing the final prompt.
|
||||
6. **Save memory**: Toggle "stop_server_after" ON to free VRAM after generation
|
||||
7. **Run Workflow**: Generated prompt displays and can be saved to Prompt Manager
|
||||
|
||||
**Advanced Usage**:
|
||||
1. **Add the Options Node**: Add Node → Prompt Generator Options
|
||||
2. **Connect Options**: Connect the options node to the Prompt Generator Options input
|
||||
3. **Analyze multiple images**: Connect up to 4 additional images, for a total of 5.
|
||||
4. **Select from available models**: Select from models found in your models\gguf folder. Qwen models will be available to download.
|
||||
5. **Adjust settings**: Adjust LLM parameters (temperature, top_k, etc.)
|
||||
6. **Customize LLM**: Customize the default LLM instructions to modify the responses llama returns.
|
||||
7. **Enable Debugging**: Enable complete printout of process to console using show_everything_in_console
|
||||
|
||||
**Qwen models found in options**
|
||||
- Qwen3.5-9B-UD-Q4_K_XL.gguf: Unsloth Dynamic 4-bit, good balance (~6GB VRAM)
|
||||
- Qwen3.5-9B-Q8_0.gguf: Standard 8-bit, high quality (~9.5GB VRAM)
|
||||
- Qwen3.5-9B-UD-Q8_K_XL.gguf: Unsloth Dynamic 8-bit, best quality (~13GB VRAM)
|
||||
|
||||
All Qwen3.5 models are unified vision+text — every model supports both text enhancement and image analysis via its mmproj file. Thinking mode is controlled at runtime via a toggle, no separate model variant needed.
|
||||
|
||||
**Model Management**:
|
||||
- Place gguf files in models/gguf folder
|
||||
- Downloaded models are also placed in this folder.
|
||||
|
||||
**Preferences**:
|
||||
Preference settings can be found in ComfyUI Settings → Prompt Manager
|
||||
- **Preferred Base Model**: Name of model used for "Enhance User Prompt" mode
|
||||
- **Preferred Vision Model**: Name of model used for "Analyze Image" modes
|
||||
- **Set Default Port** You can set the port used by Llama.cpp
|
||||
- **Close Llama on Exit** By default Llama.cpp will be closed on exit.
|
||||
- **Hide NSFW by Default**: When enabled, NSFW categories and prompts are hidden from all dropdowns, navigation, and the thumbnail browser
|
||||
- **Default View Mode**: Choose between thumbnail grid or list view for the Advanced prompt browser
|
||||
- **LLM Backend**: Choose between llama.cpp (default) or Ollama
|
||||
- **Ollama URL**: Set the Ollama server address (default: http://127.0.0.1:11434)
|
||||
- **Keep Alive Duration**: How long Ollama keeps the model loaded after a request (e.g. 5m, 30m, 0 for immediate unload)
|
||||
|
||||
## Requirements
|
||||
|
||||
- ComfyUI
|
||||
- Python 3.8+
|
||||
- requests
|
||||
- huggingface_hub
|
||||
- psutil
|
||||
- tqdm
|
||||
- Pillow
|
||||
- colorama
|
||||
- llama-server (from llama.cpp)
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
**Problem**: Prompts don't appear in the dropdown
|
||||
- **Solution**: Make sure the category has saved prompts. Try creating a new prompt first.
|
||||
|
||||
**Problem**: Changes aren't saved
|
||||
- **Solution**: Click the "Save Prompt" button after making changes. Direct edits in the text field are temporary.
|
||||
|
||||
**Problem**: Can't see LLM output in the node
|
||||
- **Solution**: Make sure the LLM output is connected to the "llm_input" and run the workflow.
|
||||
|
||||
**Problem**: "llama-server command not found"
|
||||
- **Solution**: Install llama.cpp and make sure `llama-server` is available in command line. See [llama.cpp releases](https://github.com/ggerganov/llama.cpp/releases)
|
||||
|
||||
**Problem**: "No models found"
|
||||
- **Solution**: Either place a .gguf file in the `models/` folder, or connect the Prompt Generator Options node and select a model size (1.7B, 4B, or 8B) to download from HuggingFace
|
||||
|
||||
**Problem**: Server won't start
|
||||
- **Solution**: Check that port 8080 is not in use. Close any existing llama-server processes.
|
||||
|
||||
**Problem**: Model download fails
|
||||
- **Solution**: Check your internet connection and HuggingFace availability. Large models may take time to download.
|
||||
|
||||
**Problem**: Generation is slow
|
||||
- **Solution**: Use a smaller quantized model (Q4 instead of Q8), or toggle 'stop_server_after' to quit llama.cpp after generating a prompt.
|
||||
|
||||
**Problem**: Default model used is not what I want
|
||||
- **Solution**: You can set your preferred model in the ComfyUI settings. Simply add its full name, with .gguf extension, for both the VL and base models. Enabling Thinking in the Generator might change what is used for VL models.
|
||||
|
||||
|
||||
## Changelog
|
||||
|
||||
### version 2.0.0
|
||||
- **Prompt Manager becomes Prompt + Workflow Manager**
|
||||
- Workflow Manager now allows saving Workflow and is integrated with Prompt Manager save/reuse behavior
|
||||
- Extractor, Builder, and Manager workflow loop now focuses on simplified, reusable workflow cores
|
||||
- Workflow save/reuse behavior aligned with workflow_data-first persistence for consistent prompt and LoRA retention
|
||||
- Documentation updated to reflect full prompt and workflow scope
|
||||
- More polish improvements coming soon
|
||||
|
||||
### version 1.25.0
|
||||
- **Workflow Tools Release Milestone**
|
||||
- Workflow Builder / Workflow Renderer / Workflow Bridge / Workflow Model Loader now form a complete editable workflow pipeline
|
||||
- Improved extractor-to-builder update flow for image/video metadata refresh
|
||||
- Improved Builder dropdown stability and selection persistence on first open
|
||||
- Improved tab-switch persistence for Builder UI state, including LoRA stacks and LoRA state
|
||||
- Improved compatibility when extracting from workflows generated by Builder persistence data
|
||||
|
||||
- **Wan i2v Workflow Quality and UX Improvements**
|
||||
- Better high/low model handling and dual-pass sampler defaults in workflow path
|
||||
- Improved model-family filtering and unsupported-family handling in Builder/Renderer
|
||||
- Improved workflow update diagnostics to simplify troubleshooting of resolution and model propagation
|
||||
|
||||
- **Prompt Manager Advanced Save + Thumbnail Improvements**
|
||||
- Save flow now reuses the full Advanced browser UI (same search, category tools, NSFW/filter handling, and existing prompt selection behavior)
|
||||
- Save action terminology updated to **Save Workflow** for workflow-oriented entries
|
||||
- Save now enforces category selection before submission to avoid uncategorized/invalid saves
|
||||
- Workflow Saver save action now uses failure-only notifications (no success toast spam)
|
||||
- Thumbnail generation now tries Workflow Renderer first when workflow_data is present, with automatic fallback to the basic checkpoint/LoRA thumbnail path
|
||||
- Renderer thumbnail path now forces thumbnail-safe resolution and single-frame batch settings before queueing (consistent size, batch=1)
|
||||
|
||||
### version 1.22.6
|
||||
- **Prompt Extractor now extract Prompt Extractor**
|
||||
- Prompt Extractor now embeds extracted data in the workflow, so it can extract itself.
|
||||
|
||||
### version 1.22.5
|
||||
- **Thumbnail Generation in Prompt Manager Advanced**
|
||||
- Right-click any prompt to generate a thumbnail using a basic KSampler workflow
|
||||
- Checkpoint model selector with filterable list of all available checkpoints
|
||||
- Includes saved LoRAs (both stacks, active only) for more accurate thumbnails
|
||||
- LoRA paths resolved via existing fuzzy matching — renamed LoRAs are found automatically
|
||||
- Random seed on each generation — re-generate to get a different result
|
||||
- Selected checkpoint persists in ComfyUI preferences across sessions
|
||||
- Change model anytime via right-click menu or ComfyUI Settings → Prompt Manager
|
||||
- Spinner overlay during generation with 120s timeout
|
||||
|
||||
- **Improved Model High/Low Detection**
|
||||
- Better detection of embedded high/low indicators in model names (e.g., `tastysinHighV81`, `tastysinLowV81`)
|
||||
|
||||
### version 1.22.1
|
||||
- **Prompt Model Loader Improvements**
|
||||
- Added GGUF model support via runtime detection of [ComfyUI-GGUF](https://github.com/city96/ComfyUI-GGUF) extension
|
||||
- Visual model type badge (Checkpoint/Diffusion/GGUF/NOT FOUND) and model name displayed on the node
|
||||
- CLIP and VAE output slots automatically hidden for non-checkpoint models
|
||||
- State persistence: model info and output slot visibility survive tab switches and workflow reloads
|
||||
- Graceful error handling: shows red "NOT FOUND" badge instead of crashing on missing models
|
||||
- Searches `unet_gguf` folder paths registered by ComfyUI-GGUF
|
||||
|
||||
### version 1.22.0
|
||||
- **New Node: Prompt Model Loader**
|
||||
- Loads checkpoints or diffusion/UNET models from a string path (output by Prompt Extractor)
|
||||
- Auto-detects model type: checkpoints return MODEL + CLIP + VAE, diffusion models return MODEL only
|
||||
- Searches ComfyUI checkpoints, diffusion_models, and unet folders automatically
|
||||
- Optional weight dtype selection for memory optimization
|
||||
|
||||
- **Model/Checkpoint Extraction in Prompt Extractor**
|
||||
- Extracts checkpoint and UNET model paths from workflow metadata
|
||||
- High/Low (A/B) model assignment for dual-model workflows (e.g., Wan video with different models per noise level)
|
||||
- Resolves extracted model names to local file paths using ComfyUI's folder system
|
||||
- Supports 11+ model loader types: CheckpointLoaderSimple, UNETLoader, UnetLoaderGGUF, DiffusionModelLoader, WanVideoModelLoader, CyberdyneModelHub (dual high/low), and more
|
||||
- New `model_a` and `model_b` STRING outputs on the Prompt Extractor node
|
||||
|
||||
- **A1111/Forge Image Support**
|
||||
- Parses `Model:` field from A1111/Forge parameters format (both JS and Python paths)
|
||||
- Extracts model names from images generated by Automatic1111, Forge, and compatible UIs
|
||||
|
||||
- **WebP Metadata Support**
|
||||
- Added RIFF/EXIF parser for reading ComfyUI metadata from WebP images
|
||||
- Fixed EXIF tag reading to use correct tags (0x010e ImageDescription, 0x010f Make) for ComfyUI metadata
|
||||
|
||||
- **Video Metadata Improvements**
|
||||
- Added `comment` tag parsing in ffprobe fallback for videos that store metadata as JSON wrapper
|
||||
|
||||
### version 1.21.2
|
||||
- **Improved Thumbnail Extraction**
|
||||
- prompt extractor: enhance video thumbnail extraction and error handling for unsupported formats
|
||||
|
||||
- **Improve llama-server**
|
||||
- Increase server startup timeout from 30s to 120s for large models
|
||||
- Detect early server crashes and show stderr output to user
|
||||
- Fix _get_model_keywords docstring to reflect version preservation (qwen3.5)
|
||||
|
||||
### version 1.21.1
|
||||
- **Bug Fix** - Fixed issues caused by restructure
|
||||
|
||||
### version 1.21.0
|
||||
- **Removed miscellaneous tools** — Switch Any, Save Video H26x, Apply LoRA Stack, Better Image Loader, and Animated Latent Preview have been moved to a dedicated repository: [ComfyUI-FBnodes](https://github.com/FranckyB/ComfyUI-FBnodes)
|
||||
- **Project restructure** — Organized node files into `nodes/` and utility modules into `py/` for cleaner codebase
|
||||
|
||||
### version 1.20.0
|
||||
- **New Node: Better Image Loader**
|
||||
- Streamlined image and video loader with the same file browser as Prompt Extractor
|
||||
- Browse input or output folders, preview images and videos, scrub through video frames
|
||||
- Drag-and-drop support, single IMAGE output — no metadata extraction or LoRA processing
|
||||
- **Prompt Extractor: Input/Output Folder Switching**
|
||||
- New `source_folder` toggle to browse files from either your input or output directory
|
||||
- File browser, thumbnails, and previews all respect the selected source folder
|
||||
- **Switch Any Bug Fix**
|
||||
- Fixed SwitchAnyBool not triggering upstream node execution
|
||||
- Fixed SwitchAny input names reverting to defaults after execution
|
||||
|
||||
### version 1.19.0
|
||||
- **True Switch Any Node**
|
||||
- Added a 10 input 'True' Switch any node, that takes any inputs, doesn't lock in the type.
|
||||
- Allows rename of inputs using a simple string with all names split using , or ;
|
||||
- True lazy support, any Non selected input is disconnected internally.
|
||||
- **Metadata Json**
|
||||
- Added metadata output, so workflow found can be visualized
|
||||
- **Bug Fix**
|
||||
- Fixed bug where page reload and switching workflow would needlessly refetch the prompt.
|
||||
|
||||
### version 1.18.0
|
||||
- **Thumbnail Hover Preview**
|
||||
- Intelligent delay system: 1000ms initial, then 50ms for fast browsing (resets after 2s inactivity)
|
||||
- Preference toggle in ComfyUI Settings and browser UI (🔍 Preview / 🔍 Off)
|
||||
- Auto-scroll to selected prompt when browser opens
|
||||
- **Improved Thumbnail Quality**
|
||||
- Increased resolution to 200x200 (up from 128x128) with aspect ratio preservation
|
||||
- Optimized JSON storage format
|
||||
|
||||
### version 1.17.6
|
||||
- **Swap LoRA Stack Outputs**
|
||||
- Added `swap_lora_outputs` toggle to swap LoRA Stack A and B outputs
|
||||
- Useful for quickly testing different LoRA configurations in dual-stack workflows
|
||||
- **LoRA Input Handling Fixes**
|
||||
- Fixed issue when no LoRA input was connected: toggling LoRAs off would cause the list to refresh and revert the toggle state
|
||||
- Fixed inability to set LoRA strength to 0 (zero values were incorrectly replaced with 1.0)
|
||||
- Fixed saving prompts to use current displayed state instead of re-querying connected inputs
|
||||
- Added automatic cleanup of input-derived LoRAs when they're no longer present in the connected input
|
||||
- Improving `use_lora_input` toggle behavior to properly remove input-derived LoRAs when switching OFF while preserving preset LoRA toggle states
|
||||
|
||||
### version 1.17.5
|
||||
- **Browser Context Menu Enhancements**
|
||||
- Added "Delete Prompt", "Rename and Move Prompt" option to prompt right-click menu in the thumbnail browser
|
||||
- Added "Delete Category", "Rename Category" options to category right-click menu
|
||||
- Added "+" button at the end of the category list to create new categories directly from the browser
|
||||
- All browser operations preserve unsaved prompt state (text, loras, trigger words are not reset)
|
||||
- **Streamlined More Dropdown**
|
||||
- Removed Rename Category, New Category, Delete Category, and Delete Prompt from the "More" dropdown (now accessible via browser context menus)
|
||||
|
||||
### version 1.17.0
|
||||
- **NSFW Tagging & Filtering**
|
||||
- Mark entire categories or individual prompts as NSFW
|
||||
- Visual red "NSFW" badge on the Prompt Manager node title bar and on the Advanced prompt selector
|
||||
- NSFW badge appears on all prompts within an NSFW-tagged category in the thumbnail browser
|
||||
- Category buttons show red border for NSFW categories in the thumbnail browser
|
||||
- Global preference to hide/show NSFW content — filters dropdowns, navigation arrows, and browser
|
||||
- Session-persistent NSFW toggle button in the Advanced thumbnail browser
|
||||
- Toggle NSFW on categories and prompts via context menu or the save/new category dialogs
|
||||
- **List View Mode**
|
||||
- New compact list view alternative to the thumbnail grid in the Advanced prompt browser
|
||||
- Toggle between grid and list view with a button in the browser controls bar
|
||||
- View mode preference is session-persistent
|
||||
- Default view mode configurable in ComfyUI settings
|
||||
- **UI Improvements**
|
||||
- Search input moved into the controls bar with a clear (×) button
|
||||
- Separator line between category buttons and prompt content
|
||||
|
||||
### version 1.16.0
|
||||
- **Ollama Support**
|
||||
- Added Ollama as an alternative LLM backend alongside llama.cpp
|
||||
- Auto-discovers available Ollama models when no model is explicitly configured
|
||||
- Keep-alive duration setting controls how long Ollama keeps the model loaded in memory
|
||||
- "Stop server after" toggle unloads the model from Ollama memory to free VRAM
|
||||
- **Upgraded to Qwen3.5 Models**
|
||||
- Replaced Qwen3/Qwen3VL models with unified Qwen3.5-9B (vision+text in one model)
|
||||
- Three download options: UD-Q4_K_XL (~6GB), Q8_0 (~9.5GB), UD-Q8_K_XL (~13GB)
|
||||
- Thinking mode is now a runtime toggle — no separate model variant needed
|
||||
- **mmproj-Based Vision Detection**
|
||||
- Vision model detection no longer relies on "VL" in the filename
|
||||
- Models are identified as vision-capable based on the presence of an mmproj file
|
||||
- Heuristic matching supports user-provided models outside the predefined registry
|
||||
- Backward compatible with existing Qwen3VL models and their mmproj files
|
||||
- **Bug Fixes**
|
||||
- Fixed seed control_after_generate not working (increment/decrement/randomize)
|
||||
- Improved Prompt Extractor detection logic
|
||||
|
||||
### version 1.15.9
|
||||
- **Bug Fixes**
|
||||
- Improved Prompt Extractor, enhanced detection logic
|
||||
|
||||
### version 1.15.7
|
||||
- **Added Rename Category Option**
|
||||
- **Bug Fixes**
|
||||
|
||||
### version 1.15.6
|
||||
- **Video Metadata Reader - VHS Compatible**
|
||||
- Added capability to read metadata from VideoHelperSuite generated videos.
|
||||
|
||||
### version 1.15.5
|
||||
- **Added get video components+ node**
|
||||
- Since our save video node can saves latents, this also returns the matching latent (if found) and filepath.
|
||||
- **Video Preview in Prompt Extractor**
|
||||
- Added the option to preview in fullscreen with dark overlay for both images and video on the Prompt Extractor node.
|
||||
|
||||
### version 1.15.0
|
||||
- **Added Animated Latent Preview**
|
||||
- Added Similar option to VideoHelperSuite, to display animated Latent preview. With the addition that it works in TAESD mode.
|
||||
- Check for VideoHelperSuite node, so not to conflict with it. (Will do nothing if installed)
|
||||
|
||||
### version 1.14.5
|
||||
- **Added Save Latent support to Save Video node**
|
||||
- allows to save the full data of a generation to then experiment without the need to regenerate.
|
||||
- added some very quick workflow examples.
|
||||
-A simplified version of my Wan workflow
|
||||
-A basic Z-Image base workflow with Prompt Generator.
|
||||
- Small bug fixes
|
||||
|
||||
### version 1.14.0
|
||||
- **Addition of a "Save Video H264/H265" node, that replicates ComfyUI's Video Node**
|
||||
- Adds choice between H264/H265
|
||||
- Choice of Chroma Subsampling between yuv420, yuv422, yuv444
|
||||
- Can set Constant Rate Factor (compression level)
|
||||
- Generates a quick proxy video if chosen format could not play in browser (H265 + yuv422 or H265 + yuv444)
|
||||
- Unlike VideoHelperSuite, clip with Audio also include Metadata. Which can then be used with Prompt Extractor.
|
||||
|
||||
### version 1.13.5
|
||||
- Added browse window with thumbnails in Extractor, with cache system for speedup.
|
||||
- Bug fix for issue caused by new additions.
|
||||
|
||||
### version 1.12.7
|
||||
- Quality of life improvements and added option to change the strength of any LoRA in Manager, so we can tweak extracted workflows live.
|
||||
|
||||
### version 1.12.6
|
||||
- Tweak to caching behavior for prompt extractor and prompt manager advanced
|
||||
|
||||
### version 1.12.5
|
||||
- Some dependencies to FFMpeg were still present, remove them and added a frame_position value, so we can specify what frame to get from video.
|
||||
|
||||
### version 1.12.0
|
||||
- Prompt Extractor: Added Lora inputs, so it can be used as a passthrough, with a None Choice at top, to easily deactivate it.
|
||||
- Prompt Extractor: Improved logic for determining positive prompts in workflow.
|
||||
- Prompt Extractor: Improved logic for finding High and Low Lora Stacks
|
||||
- Prompt Manager Advanced: Added Fuzzy Logic to find Loras that might have been renamed
|
||||
- Prompt Manager Advanced: Fixed issue of Lora buttons getting cleared when changing tab.
|
||||
|
||||
### Version 1.11.5
|
||||
- Slight adjustement to extractor node, gets metadata in a method more consistent with ComfyUI, removing need for ffmpeg for videos.
|
||||
|
||||
### Version 1.11.2
|
||||
- Slight adjustement to extractor node to behave exactly like the Load image node, while also supporting Videos. (With extract first frame support)
|
||||
|
||||
### Version 1.11.0
|
||||
- **New Node: Prompt Extractor** - Extract prompts and LoRA configurations from images, videos, and JSON workflows
|
||||
- Loads embedded metadata from PNG, JPEG, WebP images and MP4 videos
|
||||
- Browse and load JSON workflow files directly
|
||||
- Dual LoRA stack output for workflows using two stacks (e.g., Wan video)
|
||||
- Filters inactive LoRAs - only extracts LoRAs marked as active
|
||||
- Supports extraction from CLIP Text Encode, samplers, and LoRA stackers
|
||||
- Compatible with Power Lora Loader, WanMoeKSamplerAdvanced, and other common nodes
|
||||
- **Prompt Thumbnails** - Save thumbnail images with prompts in Prompt Manager Advanced
|
||||
- Visual identification of prompts in the dropdown selector
|
||||
- Thumbnails stored alongside prompt data for easy management
|
||||
- **Simplified "New Prompt" button**
|
||||
- Now clears fields immediately without asking for a name
|
||||
- Enter the name when saving instead of when creating
|
||||
- Keeps you in the current category for faster workflow
|
||||
- **Bug fixes and improvements**
|
||||
- Fixed JSON workflow file path resolution
|
||||
- Improved LoRA extraction for complex workflows
|
||||
|
||||
### Version 1.10.0
|
||||
- **Unified UI for Prompt Manager and Prompt Manager Advanced**
|
||||
- Three-button layout: Save Prompt, New Prompt, and More (dropdown menu)
|
||||
- New Prompt button creates a temporary prompt that isn't saved until you click Save Prompt
|
||||
- Save Prompt opens a modal with category selection (create new or select existing)
|
||||
- More dropdown includes: Import JSON, Export JSON, Delete Prompt, Delete Category
|
||||
- **Import/Export JSON functionality**
|
||||
- Export all prompts to a JSON file
|
||||
- Import prompts with Merge (add to existing) or Replace (overwrite all) options
|
||||
- Proper cancel handling without false success messages
|
||||
- **Multi-tab synchronization**
|
||||
- Changing category or prompt reloads data from server
|
||||
- Prevents conflicts when editing prompts in multiple browser tabs
|
||||
- **Prompt Manager now preserves LoRA data**
|
||||
- LoRA stacks, trigger words, and active states are preserved when saving from basic Prompt Manager
|
||||
- Seamless compatibility between Prompt Manager and Prompt Manager Advanced
|
||||
- **Trigger Words support in Prompt Manager Advanced**
|
||||
- Save and restore trigger words alongside prompts and LoRAs
|
||||
- Trigger words display as editable text when loading saved prompts
|
||||
- **Improved unsaved changes detection**
|
||||
- Warning when switching away from newly created (unsaved) prompts
|
||||
- Cancel button properly reverts dropdown to previous selection
|
||||
|
||||
### Version 1.9.0
|
||||
- **New Node: Prompt Manager Advanced** - Extended prompt manager with LoRA stack support
|
||||
- Dual LoRA stack inputs/outputs for complex workflows (Wan video, etc.)
|
||||
- Visual LoRA tags showing name and editable strength values
|
||||
- Toggle LoRAs on/off by clicking tags
|
||||
- Save LoRA configurations alongside prompts
|
||||
- Override mode to ignore connected inputs and use saved presets
|
||||
- Merge mode combines connected LoRAs with saved presets
|
||||
- Missing LoRA detection with visual warnings
|
||||
- Integration with LoRA Manager for hover previews
|
||||
- **New Node: Apply LoRA Stack** - Simple node to apply LORA_STACK to model/clip
|
||||
- Categories and prompts now display in alphabetical order
|
||||
- Fixed dropdown refresh after saving prompts
|
||||
|
||||
### Version 1.8.3
|
||||
- Added option to leave Llama server running when closing ComfyUI.
|
||||
|
||||
### Version 1.8.2
|
||||
- Added custom model path preference and enhance model management
|
||||
|
||||
### Version 1.8.1
|
||||
- Added option to set a custom Llama path in preferences, for those that have specific installs.
|
||||
|
||||
### Version 1.8.0
|
||||
- Added support for Qwen3VL Thinking model variants, with download options thru the Generator Options node.
|
||||
- Model manager now searches for relevant `mmproj` files using model-name components for more reliable vision-model linking.
|
||||
- Detailed console output options (debug logging)
|
||||
- `enable_thinking` toggle to enable/disable the model's reasoning/thinking mode.
|
||||
- Options node now accepts multiple images for analysis.
|
||||
- Better Llama shutdown behavior to force-close the server when Comfy exits.
|
||||
- Uses model-reported sampling params by default when available; the Options node can override them per-parameter.
|
||||
- Moved preference API endpoints and cache handling into `model_manager.py` for cleaner management and persistence.
|
||||
|
||||
### Version 1.7.0
|
||||
- Added three-mode prompt generator: "Enhance User Prompt", "Analyze Image", "Analyze Image with Prompt"
|
||||
- Enhanced vision model workflow with dedicated image analysis modes
|
||||
- Added custom image analysis with user-provided instructions (e.g., "describe the lighting", "identify objects")
|
||||
- Added model preferences system integrated with ComfyUI Settings
|
||||
- Added automatic model preference management (separate settings for base and vision models)
|
||||
- Improved model selection with preference fallback to smallest model
|
||||
- Filtered mmproj files from model selection dropdowns
|
||||
- Model preferences stored in ComfyUI settings for persistence across updates
|
||||
|
||||
### Version 1.6.0
|
||||
- Added Qwen3VL vision model support for image analysis
|
||||
- Added JSON output format option with structured scene breakdown
|
||||
- Added adjustable context size parameter (512-32768 tokens)
|
||||
- Added automatic mmproj file download for vision models
|
||||
- Added image resizing to ~2MP to optimize token usage
|
||||
- Added token usage logging for monitoring context consumption
|
||||
- Improved model selection logic with automatic VL/non-VL detection
|
||||
- Fixed multiple directory support for model search (gguf + LLM folders)
|
||||
|
||||
### Version 1.5.1
|
||||
- LLM output remains available when use_llm is off, so it can be edited.
|
||||
- Improved caching detection: any change to options will be detected and force a new output.
|
||||
- Improved some UI quirks
|
||||
|
||||
### Version 1.5.0
|
||||
- Added Prompt Generator node with automatic llama.cpp server management
|
||||
- Added Prompt Generator Options node for model selection and parameters
|
||||
- Automatic model detection and auto-download from HuggingFace for Qwen3 models.
|
||||
- VRAM management with optional server shutdown
|
||||
|
||||
### Version 1.1.0
|
||||
- Added LLM input toggle for switching between internal and external text
|
||||
- Made text fields scrollable even when disabled
|
||||
- Fixed reload bugs with toggle state
|
||||
|
||||
### Version 1.0.0
|
||||
- Initial release
|
||||
- Category and prompt management
|
||||
- LLM output integration
|
||||
@@ -0,0 +1,570 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Contract tests for Recipe Builder execute behavior.
|
||||
|
||||
This test file is intentionally self-contained and stubs ComfyUI runtime modules
|
||||
so it can run outside a full ComfyUI session:
|
||||
python tests/test_recipe_builder_contract.py
|
||||
|
||||
Expected flow-of-data contract (maintainer note):
|
||||
1. Builder can run with or without incoming recipe_data.
|
||||
2. When recipe_data is connected, Builder pulls all model slots (A/B/C/D).
|
||||
3. User-authored UI state lives in per-slot profiles and lock flags.
|
||||
4. Connected multi inputs (prompts/loras) may update slot state,
|
||||
but locked sections must be protected from those inputs.
|
||||
5. LoRAs are additive: recipe_data LoRAs plus connected input LoRAs,
|
||||
while preserving user state (active/order/strength) and missing flags.
|
||||
6. If a multi input is disconnected, treat it as an empty list/payload so
|
||||
stale input-derived state does not persist.
|
||||
7. Final rule: after update/merge, execute must emit recipe_data authored from
|
||||
the now-populated Builder state. Prompts/samplers/resolution/LoRAs should
|
||||
reflect what the user has set (subject to locks and connected inputs).
|
||||
"""
|
||||
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
import random
|
||||
import sys
|
||||
import types
|
||||
import unittest
|
||||
from copy import deepcopy
|
||||
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
RECIPE_BUILDER_PATH = os.path.join(ROOT, "nodes", "recipe_builder.py")
|
||||
|
||||
|
||||
def _install_stub_modules():
|
||||
"""Install lightweight runtime stubs required to import recipe_builder.py."""
|
||||
if "server" not in sys.modules:
|
||||
server_mod = types.ModuleType("server")
|
||||
|
||||
class _Routes:
|
||||
def get(self, *_args, **_kwargs):
|
||||
return lambda fn: fn
|
||||
|
||||
def post(self, *_args, **_kwargs):
|
||||
return lambda fn: fn
|
||||
|
||||
class _PromptServerInstance:
|
||||
def __init__(self):
|
||||
self.routes = _Routes()
|
||||
|
||||
def send_sync(self, *_args, **_kwargs):
|
||||
return None
|
||||
|
||||
server_mod.PromptServer = types.SimpleNamespace(instance=_PromptServerInstance())
|
||||
server_mod.web = types.SimpleNamespace(
|
||||
json_response=lambda data, **_kwargs: data,
|
||||
Response=lambda **kwargs: kwargs,
|
||||
)
|
||||
sys.modules["server"] = server_mod
|
||||
|
||||
if "folder_paths" not in sys.modules:
|
||||
folder_paths_mod = types.ModuleType("folder_paths")
|
||||
folder_paths_mod.models_dir = ROOT
|
||||
folder_paths_mod.get_filename_list = lambda _kind=None: []
|
||||
folder_paths_mod.get_full_path = lambda *_args, **_kwargs: ""
|
||||
folder_paths_mod.get_folder_paths = lambda *_args, **_kwargs: []
|
||||
sys.modules["folder_paths"] = folder_paths_mod
|
||||
|
||||
if "comfy" not in sys.modules:
|
||||
comfy_mod = types.ModuleType("comfy")
|
||||
comfy_mod.__path__ = []
|
||||
comfy_samplers = types.ModuleType("comfy.samplers")
|
||||
comfy_samplers.KSampler = types.SimpleNamespace(
|
||||
SAMPLERS=["euler"],
|
||||
SCHEDULERS=["simple"],
|
||||
)
|
||||
comfy_sd = types.ModuleType("comfy.sd")
|
||||
comfy_utils = types.ModuleType("comfy.utils")
|
||||
comfy_sample = types.ModuleType("comfy.sample")
|
||||
comfy_model_mgmt = types.ModuleType("comfy.model_management")
|
||||
comfy_mod.samplers = comfy_samplers
|
||||
comfy_mod.sd = comfy_sd
|
||||
comfy_mod.utils = comfy_utils
|
||||
comfy_mod.sample = comfy_sample
|
||||
comfy_mod.model_management = comfy_model_mgmt
|
||||
sys.modules["comfy"] = comfy_mod
|
||||
sys.modules["comfy.samplers"] = comfy_samplers
|
||||
sys.modules["comfy.sd"] = comfy_sd
|
||||
sys.modules["comfy.utils"] = comfy_utils
|
||||
sys.modules["comfy.sample"] = comfy_sample
|
||||
sys.modules["comfy.model_management"] = comfy_model_mgmt
|
||||
|
||||
if "torch" not in sys.modules:
|
||||
torch_mod = types.ModuleType("torch")
|
||||
torch_mod.cuda = types.SimpleNamespace(is_available=lambda: False)
|
||||
sys.modules["torch"] = torch_mod
|
||||
|
||||
if "numpy" not in sys.modules:
|
||||
numpy_mod = types.ModuleType("numpy")
|
||||
sys.modules["numpy"] = numpy_mod
|
||||
|
||||
if "PIL" not in sys.modules:
|
||||
pil_mod = types.ModuleType("PIL")
|
||||
|
||||
class _DummyImage:
|
||||
@staticmethod
|
||||
def open(*_args, **_kwargs):
|
||||
return None
|
||||
|
||||
pil_mod.Image = _DummyImage
|
||||
pil_mod.ImageOps = types.SimpleNamespace(exif_transpose=lambda img: img)
|
||||
sys.modules["PIL"] = pil_mod
|
||||
|
||||
|
||||
def _install_recipe_builder_dependency_stubs(pkg_root_name):
|
||||
"""Install package-scoped stubs used by recipe_builder imports."""
|
||||
pkg_mod = types.ModuleType(pkg_root_name)
|
||||
pkg_mod.__path__ = [ROOT]
|
||||
sys.modules[pkg_root_name] = pkg_mod
|
||||
|
||||
nodes_pkg_name = f"{pkg_root_name}.nodes"
|
||||
nodes_pkg_mod = types.ModuleType(nodes_pkg_name)
|
||||
nodes_pkg_mod.__path__ = [os.path.join(ROOT, "nodes")]
|
||||
sys.modules[nodes_pkg_name] = nodes_pkg_mod
|
||||
|
||||
py_pkg_name = f"{pkg_root_name}.py"
|
||||
py_pkg_mod = types.ModuleType(py_pkg_name)
|
||||
py_pkg_mod.__path__ = [os.path.join(ROOT, "py")]
|
||||
sys.modules[py_pkg_name] = py_pkg_mod
|
||||
|
||||
prompt_extractor_name = f"{pkg_root_name}.nodes.prompt_extractor"
|
||||
prompt_extractor_mod = types.ModuleType(prompt_extractor_name)
|
||||
prompt_extractor_mod.parse_workflow_for_prompts = lambda *_args, **_kwargs: {}
|
||||
prompt_extractor_mod.extract_metadata_from_png = lambda *_args, **_kwargs: {}
|
||||
prompt_extractor_mod.extract_metadata_from_jpeg = lambda *_args, **_kwargs: {}
|
||||
prompt_extractor_mod.extract_metadata_from_json = lambda *_args, **_kwargs: {}
|
||||
prompt_extractor_mod.extract_metadata_from_video = lambda *_args, **_kwargs: {}
|
||||
prompt_extractor_mod.build_node_map = lambda *_args, **_kwargs: {}
|
||||
prompt_extractor_mod.build_link_map = lambda *_args, **_kwargs: {}
|
||||
prompt_extractor_mod.extract_video_frame_av_to_tensor = lambda *_args, **_kwargs: None
|
||||
prompt_extractor_mod.get_cached_video_frame = lambda *_args, **_kwargs: None
|
||||
prompt_extractor_mod.get_placeholder_image_tensor = lambda *_args, **_kwargs: None
|
||||
sys.modules[prompt_extractor_name] = prompt_extractor_mod
|
||||
|
||||
wf_families_name = f"{pkg_root_name}.py.workflow_families"
|
||||
wf_families_mod = types.ModuleType(wf_families_name)
|
||||
wf_families_mod.MODEL_FAMILIES = {
|
||||
"sdxl": {"label": "SDXL", "checkpoint": True},
|
||||
"wan": {"label": "Wan", "checkpoint": True},
|
||||
}
|
||||
wf_families_mod.get_model_family = lambda *_args, **_kwargs: "sdxl"
|
||||
wf_families_mod.get_family_label = lambda family: str(family or "")
|
||||
wf_families_mod.get_family_sampler_strategy = lambda *_args, **_kwargs: "single"
|
||||
wf_families_mod.get_compatible_families = lambda family: [family] if family else ["sdxl"]
|
||||
wf_families_mod.get_all_family_labels = lambda: ["SDXL", "Wan"]
|
||||
|
||||
def _compat_models(*_args, **kwargs):
|
||||
rows = ["ckpt_a", "ckpt_b", "ckpt_c", "ckpt_d", "standalone_ckpt_c"]
|
||||
if kwargs.get("return_recommended"):
|
||||
return rows, (rows[0] if rows else "")
|
||||
return rows
|
||||
|
||||
def _compat_vaes(*_args, **kwargs):
|
||||
rows = ["vae_default"]
|
||||
if kwargs.get("return_recommended"):
|
||||
return rows, (rows[0] if rows else "")
|
||||
return rows
|
||||
|
||||
def _compat_clips(*_args, **kwargs):
|
||||
rows = ["clip_a"]
|
||||
if kwargs.get("return_recommended"):
|
||||
return rows, list(rows)
|
||||
return rows
|
||||
|
||||
wf_families_mod.list_compatible_models = _compat_models
|
||||
wf_families_mod.list_compatible_vaes = _compat_vaes
|
||||
wf_families_mod.list_compatible_clips = _compat_clips
|
||||
sys.modules[wf_families_name] = wf_families_mod
|
||||
|
||||
wf_extract_name = f"{pkg_root_name}.py.workflow_extraction_utils"
|
||||
wf_extract_mod = types.ModuleType(wf_extract_name)
|
||||
wf_extract_mod.extract_sampler_params = lambda *_args, **_kwargs: {}
|
||||
wf_extract_mod.extract_vae_info = lambda *_args, **_kwargs: {"name": "", "source": ""}
|
||||
wf_extract_mod.extract_clip_info = lambda *_args, **_kwargs: {"names": [], "type": "", "source": ""}
|
||||
wf_extract_mod.extract_resolution = lambda *_args, **_kwargs: {"width": 768, "height": 1280, "batch_size": 1, "length": None}
|
||||
wf_extract_mod.resolve_model_name = lambda name, _family=None: (name or "", bool(name))
|
||||
wf_extract_mod.resolve_vae_name = lambda name, _family=None: (name or "", bool(name))
|
||||
wf_extract_mod.resolve_clip_names = lambda names, _family=None: (list(names or []), bool(names))
|
||||
|
||||
def _build_simplified(extracted, wf_overrides, sampler_params):
|
||||
return {
|
||||
"_source": "RecipeBuilder",
|
||||
"positive_prompt": wf_overrides.get("positive_prompt", extracted.get("positive_prompt", "")),
|
||||
"negative_prompt": wf_overrides.get("negative_prompt", extracted.get("negative_prompt", "")),
|
||||
"model_a": wf_overrides.get("model_a", extracted.get("model_a", "")),
|
||||
"model_b": wf_overrides.get("model_b", extracted.get("model_b", "")),
|
||||
"family": extracted.get("model_family", ""),
|
||||
"vae": wf_overrides.get("vae", extracted.get("vae", {}).get("name", "")),
|
||||
"clip": wf_overrides.get("clip_names", extracted.get("clip", {}).get("names", [])),
|
||||
"loras_a": list(extracted.get("loras_a", [])),
|
||||
"loras_b": list(extracted.get("loras_b", [])),
|
||||
"sampler": dict(sampler_params or {}),
|
||||
"resolution": dict(extracted.get("resolution", {})),
|
||||
"clip_type": extracted.get("clip", {}).get("type", ""),
|
||||
"loader_type": extracted.get("loader_type", ""),
|
||||
}
|
||||
|
||||
wf_extract_mod.build_simplified_workflow_data = _build_simplified
|
||||
sys.modules[wf_extract_name] = wf_extract_mod
|
||||
|
||||
wf_data_name = f"{pkg_root_name}.py.workflow_data_utils"
|
||||
wf_data_mod = types.ModuleType(wf_data_name)
|
||||
wf_data_mod.ensure_v2_recipe_data = lambda data: data
|
||||
wf_data_mod.strip_runtime_objects = lambda data: data
|
||||
wf_data_mod.to_json_safe_workflow_data = lambda data: data
|
||||
sys.modules[wf_data_name] = wf_data_mod
|
||||
|
||||
lora_utils_name = f"{pkg_root_name}.py.lora_utils"
|
||||
lora_utils_mod = types.ModuleType(lora_utils_name)
|
||||
|
||||
def _resolve_lora_path(name):
|
||||
if not name:
|
||||
return "", False
|
||||
return (f"/loras/{name}", name != "missing_lora")
|
||||
|
||||
lora_utils_mod.resolve_lora_path = _resolve_lora_path
|
||||
lora_utils_mod.strip_lora_extension = lambda n: str(n or "").replace(".safetensors", "")
|
||||
sys.modules[lora_utils_name] = lora_utils_mod
|
||||
|
||||
|
||||
def _load_recipe_builder_module():
|
||||
_install_stub_modules()
|
||||
pkg_root_name = "cpm_testpkg"
|
||||
_install_recipe_builder_dependency_stubs(pkg_root_name)
|
||||
|
||||
module_name = f"{pkg_root_name}.nodes.recipe_builder"
|
||||
spec = importlib.util.spec_from_file_location(module_name, RECIPE_BUILDER_PATH)
|
||||
if spec is None or spec.loader is None:
|
||||
raise RuntimeError("Failed to create module spec for recipe_builder.py")
|
||||
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
sys.modules[module_name] = module
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
def _make_model_block(name="", positive="", negative="", loras=None):
|
||||
return {
|
||||
"positive_prompt": positive,
|
||||
"negative_prompt": negative,
|
||||
"family": "sdxl",
|
||||
"model": name,
|
||||
"loras": list(loras or []),
|
||||
"clip_type": "",
|
||||
"loader_type": "",
|
||||
"vae": "",
|
||||
"clip": [],
|
||||
"sampler": {
|
||||
"steps": 20,
|
||||
"cfg": 5.0,
|
||||
"denoise": 1.0,
|
||||
"seed": 0,
|
||||
"sampler_name": "euler",
|
||||
"scheduler": "simple",
|
||||
},
|
||||
"resolution": {"width": 768, "height": 1280, "batch_size": 1, "length": None},
|
||||
}
|
||||
|
||||
|
||||
def _make_base_recipe():
|
||||
return {
|
||||
"version": 2,
|
||||
"models": {
|
||||
"model_a": _make_model_block("ckpt_a", "pos_a", "neg_a", [{"name": "recipe_lora", "model_strength": 0.8, "clip_strength": 0.7, "active": True}]),
|
||||
"model_b": _make_model_block("ckpt_b", "pos_b", "neg_b"),
|
||||
"model_c": _make_model_block("ckpt_c", "pos_c", "neg_c"),
|
||||
"model_d": _make_model_block("ckpt_d", "pos_d", "neg_d"),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _default_slot_profile(model_name="", pos="", neg=""):
|
||||
return {
|
||||
"ov": {
|
||||
"positive_prompt": pos,
|
||||
"negative_prompt": neg,
|
||||
"model_a": model_name,
|
||||
"_family": "sdxl",
|
||||
"clip_type": "",
|
||||
"loader_type": "",
|
||||
"vae": "",
|
||||
"clip_names": [],
|
||||
"loras_a": [],
|
||||
"steps_a": 20,
|
||||
"cfg": 5.0,
|
||||
"denoise": 1.0,
|
||||
"seed_a": 0,
|
||||
"sampler_name": "euler",
|
||||
"scheduler": "simple",
|
||||
"_seed_auto": False,
|
||||
"width": 768,
|
||||
"height": 1280,
|
||||
"batch_size": 1,
|
||||
"length": None,
|
||||
"_section_locks": {
|
||||
"prompt": False,
|
||||
"model": False,
|
||||
"loras": False,
|
||||
"sampler": False,
|
||||
"resolution": False,
|
||||
"seed": False,
|
||||
"positive": False,
|
||||
"negative": False,
|
||||
},
|
||||
},
|
||||
"ls": {},
|
||||
}
|
||||
|
||||
|
||||
class RecipeBuilderContractTests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.rb_module = _load_recipe_builder_module()
|
||||
cls.builder = cls.rb_module.WorkflowBuilder()
|
||||
|
||||
def _exec(self, **kwargs):
|
||||
defaults = {
|
||||
"recipe_data": None,
|
||||
"multi_pos_prompts": "",
|
||||
"multi_neg_prompts": "",
|
||||
"multi_lora_stack": {},
|
||||
"override_data": "{}",
|
||||
"lora_state": "{}",
|
||||
"unique_id": "contract-test",
|
||||
}
|
||||
defaults.update(kwargs)
|
||||
result = self.builder.execute(**defaults)
|
||||
self.assertIn("result", result)
|
||||
self.assertIn("ui", result)
|
||||
return result
|
||||
|
||||
def test_recipe_data_pull_preserves_all_four_models(self):
|
||||
recipe = _make_base_recipe()
|
||||
slot_profiles = {
|
||||
"model_a": _default_slot_profile(),
|
||||
"model_b": _default_slot_profile(),
|
||||
"model_c": _default_slot_profile(),
|
||||
"model_d": _default_slot_profile(),
|
||||
}
|
||||
override_data = json.dumps({"_model_slot": "model_a", "_slot_profiles": slot_profiles})
|
||||
|
||||
out = self._exec(recipe_data=deepcopy(recipe), override_data=override_data)
|
||||
output_wf = out["result"][0]
|
||||
models = output_wf.get("models", {})
|
||||
|
||||
self.assertEqual(set(models.keys()), {"model_a", "model_b", "model_c", "model_d"})
|
||||
self.assertEqual(models["model_a"]["model"], "ckpt_a")
|
||||
self.assertEqual(models["model_b"]["model"], "ckpt_b")
|
||||
self.assertEqual(models["model_c"]["model"], "ckpt_c")
|
||||
self.assertEqual(models["model_d"]["model"], "ckpt_d")
|
||||
|
||||
# UI payload should also carry all slots so switching model view is consistent.
|
||||
extracted = out["ui"]["workflow_info"][0]["extracted"]
|
||||
slot_profiles = extracted.get("_slot_profiles", {})
|
||||
self.assertEqual(set(slot_profiles.keys()), {"model_a", "model_b", "model_c", "model_d"})
|
||||
|
||||
def test_standalone_mode_creates_all_slots_and_applies_slot_profile(self):
|
||||
slot_profiles = {
|
||||
"model_a": _default_slot_profile(),
|
||||
"model_b": _default_slot_profile(),
|
||||
"model_c": _default_slot_profile(model_name="standalone_ckpt_c", pos="standalone_pos_c", neg="standalone_neg_c"),
|
||||
"model_d": _default_slot_profile(),
|
||||
}
|
||||
override_data = json.dumps({"_model_slot": "model_c", "_slot_profiles": slot_profiles})
|
||||
|
||||
out = self._exec(recipe_data=None, override_data=override_data)
|
||||
models = out["result"][0].get("models", {})
|
||||
|
||||
self.assertEqual(set(models.keys()), {"model_a", "model_b", "model_c", "model_d"})
|
||||
self.assertEqual(models["model_c"]["model"], "standalone_ckpt_c")
|
||||
self.assertEqual(models["model_c"]["positive_prompt"], "standalone_pos_c")
|
||||
self.assertEqual(models["model_c"]["negative_prompt"], "standalone_neg_c")
|
||||
|
||||
def test_multi_prompt_overrides_recipe_when_unlocked(self):
|
||||
recipe = _make_base_recipe()
|
||||
slot_profiles = {
|
||||
"model_a": _default_slot_profile(model_name="ckpt_a", pos="slot_pos", neg="slot_neg"),
|
||||
"model_b": _default_slot_profile(),
|
||||
"model_c": _default_slot_profile(),
|
||||
"model_d": _default_slot_profile(),
|
||||
}
|
||||
override_data = json.dumps({"_model_slot": "model_a", "_slot_profiles": slot_profiles})
|
||||
|
||||
out = self._exec(
|
||||
recipe_data=deepcopy(recipe),
|
||||
override_data=override_data,
|
||||
multi_pos_prompts={"model_a": "incoming_multi_pos"},
|
||||
multi_neg_prompts={"model_a": "incoming_multi_neg"},
|
||||
)
|
||||
model_a = out["result"][0]["models"]["model_a"]
|
||||
|
||||
self.assertEqual(model_a["positive_prompt"], "incoming_multi_pos")
|
||||
self.assertEqual(model_a["negative_prompt"], "incoming_multi_neg")
|
||||
|
||||
def test_locked_prompt_sections_ignore_connected_prompt_inputs(self):
|
||||
recipe = _make_base_recipe()
|
||||
profile_a = _default_slot_profile(model_name="ckpt_a", pos="locked_user_pos", neg="locked_user_neg")
|
||||
profile_a["ov"]["_section_locks"]["positive"] = True
|
||||
profile_a["ov"]["_section_locks"]["negative"] = True
|
||||
|
||||
slot_profiles = {
|
||||
"model_a": profile_a,
|
||||
"model_b": _default_slot_profile(),
|
||||
"model_c": _default_slot_profile(),
|
||||
"model_d": _default_slot_profile(),
|
||||
}
|
||||
override_data = json.dumps({"_model_slot": "model_a", "_slot_profiles": slot_profiles})
|
||||
|
||||
out = self._exec(
|
||||
recipe_data=deepcopy(recipe),
|
||||
override_data=override_data,
|
||||
multi_pos_prompts={"model_a": "incoming_multi_pos"},
|
||||
multi_neg_prompts={"model_a": "incoming_multi_neg"},
|
||||
)
|
||||
model_a = out["result"][0]["models"]["model_a"]
|
||||
|
||||
self.assertEqual(model_a["positive_prompt"], "locked_user_pos")
|
||||
self.assertEqual(model_a["negative_prompt"], "locked_user_neg")
|
||||
|
||||
def test_loras_are_additive_and_preserve_state_and_missing_flag(self):
|
||||
recipe = _make_base_recipe()
|
||||
recipe["models"]["model_a"]["loras"] = [
|
||||
{"name": "recipe_lora", "model_strength": 0.8, "clip_strength": 0.7, "active": True},
|
||||
{"name": "missing_lora", "model_strength": 1.0, "clip_strength": 1.0, "active": True},
|
||||
]
|
||||
|
||||
profile_a = _default_slot_profile(model_name="ckpt_a")
|
||||
profile_a["ov"]["loras_a"] = [
|
||||
{"name": "input_lora", "model_strength": 0.25, "clip_strength": 0.2, "active": False, "source_input": True},
|
||||
{"name": "recipe_lora", "model_strength": 0.9, "clip_strength": 0.85, "active": True},
|
||||
]
|
||||
|
||||
slot_profiles = {
|
||||
"model_a": profile_a,
|
||||
"model_b": _default_slot_profile(),
|
||||
"model_c": _default_slot_profile(),
|
||||
"model_d": _default_slot_profile(),
|
||||
}
|
||||
override_data = json.dumps({"_model_slot": "model_a", "_slot_profiles": slot_profiles})
|
||||
|
||||
out = self._exec(
|
||||
recipe_data=deepcopy(recipe),
|
||||
override_data=override_data,
|
||||
multi_lora_stack={"model_a": [["input_lora", 0.75, 0.65]]},
|
||||
)
|
||||
|
||||
model_a = out["result"][0]["models"]["model_a"]
|
||||
loras = model_a["loras"]
|
||||
by_name = {row.get("name"): row for row in loras}
|
||||
|
||||
self.assertIn("recipe_lora", by_name)
|
||||
self.assertIn("input_lora", by_name)
|
||||
self.assertIn("missing_lora", by_name)
|
||||
|
||||
self.assertFalse(by_name["input_lora"].get("active", True))
|
||||
self.assertEqual(float(by_name["input_lora"].get("model_strength", 0)), 0.25)
|
||||
self.assertEqual(float(by_name["input_lora"].get("clip_strength", 0)), 0.2)
|
||||
lora_names = [row.get("name") for row in loras]
|
||||
self.assertLess(lora_names.index("input_lora"), lora_names.index("recipe_lora"))
|
||||
|
||||
extracted = out["ui"]["workflow_info"][0]["extracted"]
|
||||
lora_availability = extracted.get("lora_availability", {})
|
||||
self.assertIn("missing_lora", lora_availability)
|
||||
self.assertFalse(lora_availability["missing_lora"])
|
||||
|
||||
def test_disconnected_multi_loras_behaves_as_empty_list(self):
|
||||
recipe = _make_base_recipe()
|
||||
profile_a = _default_slot_profile(model_name="ckpt_a")
|
||||
profile_a["ov"]["loras_a"] = [
|
||||
{"name": "stale_input_lora", "model_strength": 0.6, "clip_strength": 0.6, "active": True, "source_input": True},
|
||||
{"name": "recipe_lora", "model_strength": 0.8, "clip_strength": 0.7, "active": True},
|
||||
]
|
||||
|
||||
slot_profiles = {
|
||||
"model_a": profile_a,
|
||||
"model_b": _default_slot_profile(),
|
||||
"model_c": _default_slot_profile(),
|
||||
"model_d": _default_slot_profile(),
|
||||
}
|
||||
override_data = json.dumps({"_model_slot": "model_a", "_slot_profiles": slot_profiles})
|
||||
|
||||
out = self._exec(recipe_data=deepcopy(recipe), override_data=override_data, multi_lora_stack={})
|
||||
loras = out["result"][0]["models"]["model_a"].get("loras", [])
|
||||
lora_names = [row.get("name") for row in loras]
|
||||
|
||||
self.assertNotIn("stale_input_lora", lora_names)
|
||||
self.assertIn("recipe_lora", lora_names)
|
||||
|
||||
def test_randomized_prompt_lock_contract(self):
|
||||
rng = random.Random(1337)
|
||||
slots = ("model_a", "model_b", "model_c", "model_d")
|
||||
|
||||
def _tok(prefix):
|
||||
return f"{prefix}_{rng.randint(1000, 9999)}"
|
||||
|
||||
for _ in range(40):
|
||||
recipe = {"version": 2, "models": {}}
|
||||
slot_profiles = {}
|
||||
multi_pos = {}
|
||||
multi_neg = {}
|
||||
expected_pos = {}
|
||||
expected_neg = {}
|
||||
|
||||
for slot in slots:
|
||||
recipe_pos = _tok(f"rpos_{slot}")
|
||||
recipe_neg = _tok(f"rneg_{slot}")
|
||||
recipe_model = _tok(f"rmodel_{slot}")
|
||||
recipe["models"][slot] = _make_model_block(recipe_model, recipe_pos, recipe_neg)
|
||||
|
||||
profile = _default_slot_profile(
|
||||
model_name=recipe_model,
|
||||
pos=_tok(f"upos_{slot}"),
|
||||
neg=_tok(f"uneg_{slot}"),
|
||||
)
|
||||
lock_pos = bool(rng.getrandbits(1))
|
||||
lock_neg = bool(rng.getrandbits(1))
|
||||
profile["ov"]["_section_locks"]["positive"] = lock_pos
|
||||
profile["ov"]["_section_locks"]["negative"] = lock_neg
|
||||
slot_profiles[slot] = profile
|
||||
|
||||
if bool(rng.getrandbits(1)):
|
||||
multi_pos[slot] = _tok(f"inpos_{slot}")
|
||||
if bool(rng.getrandbits(1)):
|
||||
multi_neg[slot] = _tok(f"inneg_{slot}")
|
||||
|
||||
expected_pos[slot] = (
|
||||
profile["ov"]["positive_prompt"]
|
||||
if lock_pos
|
||||
else multi_pos.get(slot, recipe_pos)
|
||||
)
|
||||
expected_neg[slot] = (
|
||||
profile["ov"]["negative_prompt"]
|
||||
if lock_neg
|
||||
else multi_neg.get(slot, recipe_neg)
|
||||
)
|
||||
|
||||
override_data = json.dumps({"_model_slot": "model_a", "_slot_profiles": slot_profiles})
|
||||
out = self._exec(
|
||||
recipe_data=deepcopy(recipe),
|
||||
override_data=override_data,
|
||||
multi_pos_prompts=multi_pos,
|
||||
multi_neg_prompts=multi_neg,
|
||||
)
|
||||
|
||||
models = out["result"][0].get("models", {})
|
||||
self.assertEqual(set(models.keys()), set(slots))
|
||||
|
||||
for slot in slots:
|
||||
self.assertEqual(models[slot].get("positive_prompt"), expected_pos[slot])
|
||||
self.assertEqual(models[slot].get("negative_prompt"), expected_neg[slot])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
suite = unittest.defaultTestLoader.loadTestsFromTestCase(RecipeBuilderContractTests)
|
||||
runner = unittest.TextTestRunner(verbosity=2)
|
||||
result = runner.run(suite)
|
||||
raise SystemExit(0 if result.wasSuccessful() else 1)
|
||||
@@ -0,0 +1,210 @@
|
||||
#!/usr/bin/env node
|
||||
/*
|
||||
JS contract tests for Recipe Builder UI lock/persistence logic.
|
||||
Runs directly with Node and evaluates real functions from js/recipe_builder.js.
|
||||
|
||||
Usage:
|
||||
node tests/test_recipe_builder_js_contract.js
|
||||
*/
|
||||
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const vm = require("vm");
|
||||
const assert = require("assert/strict");
|
||||
|
||||
const SOURCE_PATH = path.join(__dirname, "..", "js", "recipe_builder.js");
|
||||
const SOURCE = fs.readFileSync(SOURCE_PATH, "utf8");
|
||||
|
||||
function extractFunction(name) {
|
||||
const marker = `function ${name}(`;
|
||||
const start = SOURCE.indexOf(marker);
|
||||
if (start < 0) {
|
||||
throw new Error(`Could not find function ${name} in ${SOURCE_PATH}`);
|
||||
}
|
||||
|
||||
const bodyStart = SOURCE.indexOf("{", start);
|
||||
if (bodyStart < 0) {
|
||||
throw new Error(`Could not find function body start for ${name}`);
|
||||
}
|
||||
|
||||
let depth = 0;
|
||||
let end = -1;
|
||||
for (let i = bodyStart; i < SOURCE.length; i += 1) {
|
||||
const ch = SOURCE[i];
|
||||
if (ch === "{") depth += 1;
|
||||
if (ch === "}") {
|
||||
depth -= 1;
|
||||
if (depth === 0) {
|
||||
end = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (end < 0) {
|
||||
throw new Error(`Could not find function body end for ${name}`);
|
||||
}
|
||||
|
||||
return SOURCE.slice(start, end + 1);
|
||||
}
|
||||
|
||||
const context = {
|
||||
console,
|
||||
requestAnimationFrame: (cb) => {
|
||||
if (typeof cb === "function") cb();
|
||||
},
|
||||
reflowNode: () => {},
|
||||
C: { textMuted: "#aaa", text: "#ccc" },
|
||||
cleanModelName: (v) => String(v ?? ""),
|
||||
normalizeSelectableFamily: (v) => String(v || "sdxl"),
|
||||
updateLoras: () => {},
|
||||
checkLoraAvailability: () => {},
|
||||
updateWanVisibility: () => {},
|
||||
_normalizeModelSlotKey: (v) => {
|
||||
const s = String(v || "model_a").toLowerCase();
|
||||
return ["model_a", "model_b", "model_c", "model_d"].includes(s) ? s : "model_a";
|
||||
},
|
||||
_normalizeSlotProfiles: (x) => (x && typeof x === "object" ? x : {}),
|
||||
document: {
|
||||
createElement: () => ({
|
||||
value: "",
|
||||
textContent: "",
|
||||
appendChild: () => {},
|
||||
}),
|
||||
},
|
||||
};
|
||||
|
||||
vm.createContext(context);
|
||||
vm.runInContext(extractFunction("mergeSlotProfileWithLocks"), context);
|
||||
vm.runInContext(extractFunction("applyOverrides"), context);
|
||||
vm.runInContext(extractFunction("syncHidden"), context);
|
||||
|
||||
function testMergeSlotProfileWithLocks() {
|
||||
const current = {
|
||||
ov: {
|
||||
model_a: "locked_model",
|
||||
positive_prompt: "locked_pos",
|
||||
negative_prompt: "unlocked_neg",
|
||||
steps_a: 77,
|
||||
loras_a: [{ name: "kept_lora" }],
|
||||
_section_locks: {
|
||||
model: true,
|
||||
sampler: true,
|
||||
positive: true,
|
||||
negative: false,
|
||||
loras: true,
|
||||
},
|
||||
},
|
||||
ls: { "a:kept_lora": { active: false, model_strength: 0.2, clip_strength: 0.2 } },
|
||||
};
|
||||
|
||||
const incoming = {
|
||||
ov: {
|
||||
model_a: "incoming_model",
|
||||
positive_prompt: "incoming_pos",
|
||||
negative_prompt: "incoming_neg",
|
||||
steps_a: 10,
|
||||
loras_a: [{ name: "incoming_lora" }],
|
||||
},
|
||||
ls: { "a:incoming_lora": { active: true, model_strength: 1.0, clip_strength: 1.0 } },
|
||||
};
|
||||
|
||||
const out = context.mergeSlotProfileWithLocks(current, incoming);
|
||||
|
||||
assert.equal(out.ov.model_a, "locked_model", "model lock should preserve current model");
|
||||
assert.equal(out.ov.steps_a, 77, "sampler lock should preserve current sampler values");
|
||||
assert.equal(out.ov.positive_prompt, "locked_pos", "positive lock should preserve current positive prompt");
|
||||
assert.equal(out.ov.negative_prompt, "incoming_neg", "unlocked negative should adopt incoming value");
|
||||
assert.equal(
|
||||
JSON.stringify(out.ov.loras_a),
|
||||
JSON.stringify([{ name: "kept_lora" }]),
|
||||
"LoRA lock should preserve current LoRA list",
|
||||
);
|
||||
assert.equal(
|
||||
JSON.stringify(out.ls),
|
||||
JSON.stringify(current.ls),
|
||||
"LoRA lock should preserve current LoRA state map",
|
||||
);
|
||||
}
|
||||
|
||||
function testApplyOverridesRestoresSectionLocks() {
|
||||
const calls = [];
|
||||
const node = {
|
||||
_weExtracted: {},
|
||||
_weUseSlotProfiles: false,
|
||||
_weSetSectionLock: (key, locked, options) => {
|
||||
calls.push({ key, locked, options });
|
||||
},
|
||||
};
|
||||
|
||||
const ov = {
|
||||
_section_locks: {
|
||||
resolution: true,
|
||||
positive: true,
|
||||
loras: false,
|
||||
},
|
||||
};
|
||||
|
||||
context.applyOverrides(node, JSON.stringify(ov), "{}");
|
||||
|
||||
const byKey = Object.fromEntries(calls.map((c) => [c.key, c]));
|
||||
assert.equal(byKey.resolution.locked, true, "resolution lock should restore to true");
|
||||
assert.equal(byKey.positive.locked, true, "positive lock should restore to true");
|
||||
assert.equal(byKey.loras.locked, false, "loras lock should restore to false");
|
||||
}
|
||||
|
||||
function testSyncHiddenPersistsLocksAndPrompts() {
|
||||
const widgets = [
|
||||
{ name: "override_data", value: "" },
|
||||
{ name: "lora_state", value: "" },
|
||||
];
|
||||
|
||||
const node = {
|
||||
widgets,
|
||||
properties: {},
|
||||
_weOverrides: {},
|
||||
_weSectionLocks: {
|
||||
resolution: true,
|
||||
positive: true,
|
||||
loras: false,
|
||||
},
|
||||
_weCollapsedSections: {
|
||||
resolution: false,
|
||||
model: true,
|
||||
sampler: false,
|
||||
positive: true,
|
||||
negative: false,
|
||||
loras: true,
|
||||
},
|
||||
_weUseSlotProfiles: false,
|
||||
_wePosBox: { value: "user_pos" },
|
||||
_weNegBox: { value: "user_neg" },
|
||||
_weExtracted: {
|
||||
loras_a: [],
|
||||
loras_b: [],
|
||||
lora_availability: {},
|
||||
},
|
||||
};
|
||||
|
||||
context.syncHidden(node);
|
||||
|
||||
const overrideJson = widgets.find((w) => w.name === "override_data").value;
|
||||
const ov = JSON.parse(overrideJson || "{}");
|
||||
|
||||
assert.equal(ov.positive_prompt, "user_pos", "syncHidden should persist positive prompt from UI");
|
||||
assert.equal(ov.negative_prompt, "user_neg", "syncHidden should persist negative prompt from UI");
|
||||
assert.equal(ov._section_locks.resolution, true, "syncHidden should persist resolution lock");
|
||||
assert.equal(ov._section_locks.positive, true, "syncHidden should persist positive lock");
|
||||
assert.equal(Object.prototype.hasOwnProperty.call(ov._section_locks, "loras"), false, "unlocked section should not be persisted in non-slot mode");
|
||||
assert.equal(ov._section_collapsed.model, true, "syncHidden should persist global collapsed section state");
|
||||
assert.equal(ov._section_collapsed.positive, true, "syncHidden should persist positive collapsed state");
|
||||
}
|
||||
|
||||
function run() {
|
||||
testMergeSlotProfileWithLocks();
|
||||
testApplyOverridesRestoresSectionLocks();
|
||||
testSyncHiddenPersistsLocksAndPrompts();
|
||||
console.log("JS contract tests passed");
|
||||
}
|
||||
|
||||
run();
|
||||