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 | ||
|
|
f748246801 | ||
|
|
b7905b81da | ||
|
|
dd78c417ba | ||
|
|
eb9dc96631 | ||
|
|
5beaf8e501 | ||
|
|
bf2ad422d7 | ||
|
|
89825a747d | ||
|
|
0d8e9192f1 | ||
|
|
763a340488 | ||
|
|
7362da49d9 | ||
|
|
9f4bac5f30 | ||
|
|
f36411aac5 | ||
|
|
0d3216d0e9 | ||
|
|
834aff18da | ||
|
|
bae6df106a | ||
|
|
07b428767e | ||
|
|
6a58f9ce95 | ||
|
|
bdb1cc4212 | ||
|
|
cbc0efa839 | ||
|
|
119952a51d | ||
|
|
d0e591c24c | ||
|
|
df148d8cd3 | ||
|
|
c76a95adf9 | ||
|
|
00ed3ffd92 | ||
|
|
3d72e8b4ff | ||
|
|
5dd666fe3a | ||
|
|
4fd7070c97 | ||
|
|
9fcf4ef1a7 | ||
|
|
cb8b7e7205 | ||
|
|
661a35f971 | ||
|
|
27eca5ba94 | ||
|
|
e7fece763c | ||
|
|
56bdb9e98a | ||
|
|
24f6f8ad65 | ||
|
|
bd8ffdca8a | ||
|
|
3906e87e19 | ||
|
|
376a58e27c | ||
|
|
711cd87567 | ||
|
|
00f23b4590 | ||
|
|
e8639a5050 | ||
|
|
54c9d98e85 | ||
|
|
c78cbd6913 | ||
|
|
adf5766f48 | ||
|
|
8accd26d94 | ||
|
|
7c2dc8248b | ||
|
|
7eb21c918a | ||
|
|
3d528c2997 | ||
|
|
6c11ec52de | ||
|
|
07fd152e84 | ||
|
|
a950ebfa92 | ||
|
|
3effd8f1e8 | ||
|
|
a1c496ed4c | ||
|
|
504b2dce40 | ||
|
|
f8d228b42c | ||
|
|
69912c724c | ||
|
|
0db278723d | ||
|
|
a498a5e7f3 | ||
|
|
f3607303af | ||
|
|
173328bf2d | ||
|
|
214f653d4e | ||
|
|
74005592e8 | ||
|
|
0939ae11ec | ||
|
|
b0ea8f6faf | ||
|
|
cf11bfc9d0 | ||
|
|
0a757baa9b | ||
|
|
944759a05a | ||
|
|
92bb954fc2 | ||
|
|
9fb3ffc6fb | ||
|
|
557152ae96 | ||
|
|
de2c5cd295 | ||
|
|
d2323da13c | ||
|
|
7be4ea4748 | ||
|
|
6e9595a594 | ||
|
|
f5a66e1995 | ||
|
|
28e6299bec | ||
|
|
8cbe4943a1 | ||
|
|
09597becc5 | ||
|
|
0fa7eec08d | ||
|
|
3df92b0509 | ||
|
|
1556a07653 | ||
|
|
64bcb706ae | ||
|
|
61a7f6bf45 | ||
|
|
2f2be6c075 | ||
|
|
f4fa4bebff | ||
|
|
bac173134b | ||
|
|
04e403d93b | ||
|
|
e4d58e59ee | ||
|
|
ee2047cac6 | ||
|
|
6e79a82596 | ||
|
|
b0fdbf1a97 | ||
|
|
d12d8bb484 | ||
|
|
b4a41e2340 | ||
|
|
9ccfc23f66 | ||
|
|
55b59f876e | ||
|
|
1f348ea4e8 | ||
|
|
c3b912aa76 | ||
|
|
d154fab852 | ||
|
|
10e3998230 | ||
|
|
30428e3e20 | ||
|
|
b171e97a08 | ||
|
|
866ca71053 | ||
|
|
3aa373be3b | ||
|
|
1db335d88b | ||
|
|
ec4cf272ce | ||
|
|
2e195cfa01 | ||
|
|
2a3ed8c52c | ||
|
|
41cdfa16c3 | ||
|
|
7b87283fcd | ||
|
|
e9d0797d67 | ||
|
|
bfa92d7007 | ||
|
|
1c12d99a33 | ||
|
|
173b2aceed | ||
|
|
a0a886c8a8 | ||
|
|
7c4c1f9172 | ||
|
|
5224d650e8 | ||
|
|
02246e0612 | ||
|
|
323ece55e8 | ||
|
|
2419567353 | ||
|
|
2ce93a326a | ||
|
|
32400171de | ||
|
|
516a226f5f | ||
|
|
d6a75f2d70 | ||
|
|
84bf5065d9 | ||
|
|
9ec65b7d8b | ||
|
|
08d21b0961 | ||
|
|
e7c727f102 | ||
|
|
639091fd17 | ||
|
|
977ec9785b | ||
|
|
ca06e1273b | ||
|
|
c2c38e5b9d | ||
|
|
6ddf0108be | ||
|
|
52990491f3 | ||
|
|
3a49fdfa97 | ||
|
|
b98155543b | ||
|
|
74716182ce | ||
|
|
d7adb9f5c0 | ||
|
|
c8e103152b | ||
|
|
1c3aa77889 | ||
|
|
501b962408 | ||
|
|
34df0b0675 | ||
|
|
a7bdec56d3 | ||
|
|
41e4c27416 | ||
|
|
c34fda023c | ||
|
|
6de8bddea5 | ||
|
|
1fea03858e | ||
|
|
16c01efb0d | ||
|
|
f9b7c601f9 | ||
|
|
cb6276ded0 | ||
|
|
894f44d4b5 | ||
|
|
7e1a45fa3c | ||
|
|
616746e07f | ||
|
|
4cdb3a0d68 | ||
|
|
c4eb347b56 | ||
|
|
356f3af597 | ||
|
|
9be7636d61 | ||
|
|
6ddf7321a0 | ||
|
|
0af9387da5 | ||
|
|
e08f295c25 | ||
|
|
ae5e46fccc | ||
|
|
32a54c4ff0 | ||
|
|
cca1753f10 | ||
|
|
81362756b4 | ||
|
|
fb1d32d503 | ||
|
|
ea21779258 | ||
|
|
6ad2986746 | ||
|
|
e80c5bce0e | ||
|
|
88f2e1b109 | ||
|
|
6aa194ff95 | ||
|
|
3731b4c228 | ||
|
|
8062ede1cd | ||
|
|
7496c8fd65 | ||
|
|
f82ff068e1 | ||
|
|
1029c79881 | ||
|
|
f20af63926 | ||
|
|
82b19c71de | ||
|
|
76c30404a8 | ||
|
|
10cb9d2bb0 | ||
|
|
e20f6523d9 | ||
|
|
d7fde3cce4 | ||
|
|
bf0edbabc9 | ||
|
|
ed78a1bf05 | ||
|
|
698cd7b725 | ||
|
|
d93c2713d5 | ||
|
|
dc971491d1 | ||
|
|
f5391da99a | ||
|
|
539828c8af | ||
|
|
16192ad6dd | ||
|
|
4dad2816d0 | ||
|
|
d1967d8395 | ||
|
|
ad1a4290bc | ||
|
|
e800b272cc | ||
|
|
4b93b7902d | ||
|
|
04808107c2 | ||
|
|
376e973ba0 | ||
|
|
0e4ca673fc | ||
|
|
70dc0e38e0 | ||
|
|
0297da28e6 | ||
|
|
f72bbc35cd | ||
|
|
052b88c33f | ||
|
|
6d6f09f82d | ||
|
|
0239663a38 | ||
|
|
958658f2c3 | ||
|
|
186a4fc7e4 | ||
|
|
2de7c3c9a3 | ||
|
|
55b6f2f94e | ||
|
|
a1c3b59bad | ||
|
|
3342d843e5 | ||
|
|
482f5c182d | ||
|
|
88dadfd4d5 | ||
|
|
e4868e1ea1 | ||
|
|
30246eb831 | ||
|
|
c97c290dba | ||
|
|
2da9b2813b | ||
|
|
aadb396151 | ||
|
|
96c9248135 | ||
|
|
695d7421d4 | ||
|
|
9d8137281e | ||
|
|
546b2f697b | ||
|
|
2d262999a3 | ||
|
|
e36d0fb15f | ||
|
|
d92a6c1872 | ||
|
|
67df4c6e53 | ||
|
|
e08d18c783 | ||
|
|
769d40f9f5 | ||
|
|
eef07948ac | ||
|
|
bf847e9639 | ||
|
|
39c8b5f3b8 | ||
|
|
cf810ca921 | ||
|
|
422607ec8d | ||
|
|
f9e26c8bbd | ||
|
|
be52d65de9 | ||
|
|
1d6021a916 | ||
|
|
6f0ac2674b | ||
|
|
6ba1f3f346 | ||
|
|
27ab751796 | ||
|
|
e2a9b25978 | ||
|
|
9b8016821c | ||
|
|
4811f21255 | ||
|
|
ca645721ec |
@@ -0,0 +1,15 @@
|
||||
# These are supported funding model platforms
|
||||
|
||||
github: franckyb # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
|
||||
patreon: # Replace with a single Patreon username
|
||||
open_collective: # Replace with a single Open Collective username
|
||||
ko_fi: # Replace with a single Ko-fi username
|
||||
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
|
||||
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
|
||||
liberapay: # Replace with a single Liberapay username
|
||||
issuehunt: # Replace with a single IssueHunt username
|
||||
lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry
|
||||
polar: # Replace with a single Polar username
|
||||
buy_me_a_coffee: # Replace with a single Buy Me a Coffee username
|
||||
thanks_dev: # Replace with a single thanks.dev username
|
||||
custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
|
||||
@@ -3,6 +3,7 @@ __pycache__/
|
||||
*.pyc
|
||||
*.pyo
|
||||
*.pyd
|
||||
.venv/
|
||||
.Python
|
||||
build/
|
||||
develop-eggs/
|
||||
@@ -26,6 +27,7 @@ wheels/
|
||||
# IDE files
|
||||
.vscode/
|
||||
.idea/
|
||||
ComfyUI-Prompt-Manager.code-workspace
|
||||
|
||||
# OS files
|
||||
.DS_Store
|
||||
|
||||
@@ -1,86 +1,137 @@
|
||||
# ComfyUI Prompt Manager
|
||||
## A custom [ComfyUI](https://github.com/comfyanonymous/ComfyUI) node for Organizing, Generating or Enhancing prompts.
|
||||
## A comprehensive prompt and recipe toolkit for [ComfyUI](https://github.com/comfyanonymous/ComfyUI)
|
||||
|
||||
This addon started off as a simple prompt Manager, to help save and retrieve prompts.
|
||||
But has since evolved to allow generating prompts for Images, video and Image analysis.
|
||||
The new advanced version of the manager, now allows the user to save the entire recipe,
|
||||
as it allows saving the Lora Stacks as well as trigger words that goes with a prompt. Supporting Dual Stack for Wan.
|
||||
Once saved, they can be toggled on or off or be adjusted without the need of the lora stacker.
|
||||
___
|
||||
For Prompt Generation, it uses an existing install of [llama.cpp](https://github.com/ggerganov/llama.cpp), preventing install conflicts with ComfyUI.
|
||||
Provides options to automatically download Qwen3 and Qwen3VL models.
|
||||
Supports prompt enhancing, image analysis, or custom image processing, with up to 5 images at once.
|
||||
Custom GGUF models can be used if supported by llama.cpp; simply drop them in the models/gguf folder.
|
||||
Users can now set a custom Llama-server path as well as a custom Model Path in ComfyUI's preferences.
|
||||
If a Custom Model Path is added, it will become the default download folder.
|
||||
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.
|
||||
|
||||
> **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.
|
||||
|
||||
> **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.
|
||||
|
||||
## What This Provides
|
||||
|
||||
- **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>Simple Prompt Generator Usage</figcaption>
|
||||
<img src="docs/prompt_manager.png" alt="Prompt Manager">
|
||||
</div>
|
||||
|
||||
|
||||
<div align="center">
|
||||
<figcaption>Advanced Prompt Generator Usage</figcaption>
|
||||
<img src="docs/prompt_generator_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 Manager Advanced, with Lora and trigger word support</figcaption>
|
||||
<img src="docs/prompt_manager_advanced.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 Generation using Multiple Images</figcaption>
|
||||
<img src="docs/images/prompt_generator_advanced.png" alt="Prompt Generator">
|
||||
</div>
|
||||
|
||||
<div align="center">
|
||||
<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>Easily find saved Prompts & Recipe using the Built-in File Browser</figcaption>
|
||||
<img src="docs/images/prompt_selector.png" alt="Recipe Builder">
|
||||
</div>
|
||||
|
||||
<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>
|
||||
|
||||
|
||||
### 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
|
||||
- **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 integration
|
||||
- **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
|
||||
- **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
|
||||
## v2.0 Introduces The Recipe Toolset
|
||||
|
||||
Version 2.x introduces a Recipe toolset that can be used on its own, or in combination with the Prompt toolset.
|
||||
|
||||
### Apply LoRA Stack:
|
||||
- **Simple LoRA Application**: Takes a LORA_STACK and applies it to your model/clip
|
||||
- **Works with Any Stacker**: Compatible with LoRA Manager's stacker or any node outputting LORA_STACK
|
||||
- **Optional CLIP**: CLIP input is optional for workflows that don't need it
|
||||
- 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.
|
||||
|
||||
### Prompt Generator
|
||||
- **Three Generation Modes**: Enhance text prompts, analyze images, or analyze images with custom instructions
|
||||
- **Prompt Enhancement**: Transform basic prompts into detailed descriptions using local LLMs
|
||||
- **Vision Analysis**: Analyze images with Qwen3VL 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 (vision or text) based on mode or Thinking mode.
|
||||
In short: Prompt tools help you author and manage Prompts + LoRA intent, while Recipe tools help you build, execute and reuse full generation configurations.
|
||||
|
||||
### Prompt Generator Options
|
||||
- **Model Selection**: Choose from local models or download Qwen3, Qwen3VL and Qwen3VL Thinking 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 outputing the entire process to the console for debugging purposes.
|
||||
## Toolset Overview
|
||||
|
||||
### Preference Options
|
||||
- Set choices for prefered Model for both base mode and VL model.
|
||||
- Set new default model location, previous folder (gguf and llm) will still be scanned, but model will save in new default.
|
||||
- Set custom Location for Llama.cpp. If Llama.cpp was not added to the system Path, this option let's you specify it's location.
|
||||
### 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
|
||||
|
||||
@@ -88,7 +139,6 @@ If a Custom Model Path is added, it will become the default download folder.
|
||||
```
|
||||
cd ComfyUI/custom_nodes/
|
||||
```
|
||||
|
||||
2. Clone this repository:
|
||||
```bash
|
||||
git clone https://github.com/FranckyB/ComfyUI-Prompt-Manager.git
|
||||
@@ -98,228 +148,27 @@ If a Custom Model Path is added, it will become the default download folder.
|
||||
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 in prererences your preferred folder path.
|
||||
|
||||
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. **Override Mode**: Enable "Override Lora" checkbox to ignore connected inputs and use only the saved preset LoRAs
|
||||
8. **Connect Outputs**: Use `lora_stack_a` and `lora_stack_b` outputs with the Apply LoRA Stack node
|
||||
|
||||
### Apply LoRA Stack
|
||||
|
||||
1. **Add the Node**: Add Node → Prompt Manager → Apply LoRA Stack
|
||||
2. **Connect Model**: Connect your model (e.g., from Load Checkpoint) to the `model` input
|
||||
3. **Connect LoRA Stack**: Connect a `LORA_STACK` output (from Prompt Manager Advanced or LoRA Manager's stacker)
|
||||
4. **Optional CLIP**: Connect CLIP if your workflow needs it (some video workflows don't)
|
||||
5. **Use Outputs**: Connect the modified model/clip to your sampler or other nodes
|
||||
|
||||
|
||||
### 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.
|
||||
4. **Save memory**: Toggle "stop_server_after" ON to free VRAM after generation
|
||||
5. **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-1.7B-Q8_0.gguf: Fastest, lowest VRAM (~2GB)
|
||||
- Qwen3-4B-Q8_0.gguf: Balanced performance (~4GB VRAM)
|
||||
- Qwen3-8B-Q8_0.gguf: Best quality, highest VRAM (~8GB)
|
||||
- Qwen3VL-4B-Instruct-Q8_0.gguf: Vision model, balanced performance (~5GB VRAM)
|
||||
- Qwen3VL-8B-Instruct-Q8_0.gguf: Vision model, best quality (~9GB VRAM)
|
||||
- Qwen3VL-4B-Thinking-Q8_0.gguf: Vision model, Thinking variant, balanced performance (~5GB VRAM)
|
||||
- Qwen3VL-8B-Thinking-Q8_0.gguf: Vision model, Thinking variant, best quality (~9GB VRAM)
|
||||
|
||||
**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 (text-only models)
|
||||
- **Preferred Vision Model**: Name of model Used for "Analyze Image" modes (Qwen3VL models)
|
||||
- **Set Default Port** You can set the port used by Llama.cpp
|
||||
- **Close Llama on Exit** By default Llama.cpp with be close on exit.
|
||||
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
|
||||
|
||||
- ComfyUI
|
||||
- Python 3.8+
|
||||
- requests >= 2.31.0
|
||||
- huggingface_hub >= 0.20.0
|
||||
- psutil >= 5.9.0
|
||||
- tqdm >= 4.66.0
|
||||
- Pillow >= 10.0.0
|
||||
- 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 Option 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**: Either, Use a smaller quantized model (Q4 instead of Q8) or toggle 'stop_server_after' to quit llama.cpp after generating 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 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,37 +1,65 @@
|
||||
"""
|
||||
ComfyUI Prompt Manager - A comprehensive prompt and workflow management system for ComfyUI.
|
||||
Features: prompt & workflow management, LoRA stacks, workflow extraction, workflow generation.
|
||||
"""
|
||||
ComfyUI Prompt Manager - A simple custom node for saving and reusing prompts
|
||||
A prompt management system for ComfyUI with LLM input support
|
||||
"""
|
||||
__version__ = "1.10.0"
|
||||
__version__ = "2.5.1"
|
||||
__author__ = "François Beaudry"
|
||||
__license__ = "MIT"
|
||||
|
||||
from .prompt_manager import PromptManager
|
||||
from .prompt_manager_advanced import PromptManagerAdvanced
|
||||
from .prompt_generator import PromptGenerator
|
||||
from .prompt_generator_options import PromptGenOptions
|
||||
from .apply_lora_stack import ApplyLoRAStack
|
||||
from .model_manager import get_local_models
|
||||
from server import PromptServer
|
||||
from .nodes.apply_lora import ApplyLoraPlusPlus
|
||||
from .nodes.prompt_manager_adv import PromptManagerAdvanced
|
||||
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 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 = {
|
||||
"PromptManager": PromptManager,
|
||||
"PromptManagerAdvanced": PromptManagerAdvanced,
|
||||
"PromptGenerator": PromptGenerator,
|
||||
"PromptGenOptions": PromptGenOptions,
|
||||
"ApplyLoRAStack": ApplyLoRAStack
|
||||
"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 = {
|
||||
"PromptManager": "Prompt Manager",
|
||||
"PromptManagerAdvanced": "Prompt Manager Advanced",
|
||||
"PromptGenerator": "Prompt Generator",
|
||||
"PromptGenOptions": "Prompt Generator Options",
|
||||
"ApplyLoRAStack": "Apply LoRA Stack"
|
||||
"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] Node registered successfully")
|
||||
print("[PromptManager] Nodes registered: Apply LoRA++, Prompt Manager, Prompt Generator, Prompt Extractor, Recipe Extractor, Recipe Builder, Recipe Renderer, Recipe Relay, Recipe Manager")
|
||||
|
||||
@@ -1,58 +0,0 @@
|
||||
"""
|
||||
ComfyUI Apply LoRA Stack - Apply a LORA_STACK to model and clip
|
||||
"""
|
||||
import folder_paths
|
||||
import comfy.sd
|
||||
import comfy.utils
|
||||
|
||||
|
||||
class ApplyLoRAStack:
|
||||
"""
|
||||
Apply a LoRA stack to a model and optionally a CLIP.
|
||||
Takes a LORA_STACK (list of tuples) and applies each LoRA sequentially.
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {
|
||||
"required": {
|
||||
"model": ("MODEL",),
|
||||
"lora_stack": ("LORA_STACK",),
|
||||
},
|
||||
"optional": {
|
||||
"clip": ("CLIP",),
|
||||
},
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("MODEL", "CLIP")
|
||||
RETURN_NAMES = ("model", "clip")
|
||||
FUNCTION = "apply_stack"
|
||||
CATEGORY = "Prompt Manager"
|
||||
|
||||
def apply_stack(self, model, lora_stack, clip=None):
|
||||
if not lora_stack:
|
||||
return (model, clip)
|
||||
|
||||
model_out = model
|
||||
clip_out = clip
|
||||
|
||||
for lora_name, model_strength, clip_strength in lora_stack:
|
||||
# Skip if no strength
|
||||
if model_strength == 0 and clip_strength == 0:
|
||||
continue
|
||||
|
||||
# Get the LoRA path
|
||||
lora_path = folder_paths.get_full_path("loras", lora_name)
|
||||
if lora_path is None:
|
||||
print(f"[ApplyLoRAStack] Warning: LoRA not found: {lora_name}")
|
||||
continue
|
||||
|
||||
# Load the LoRA
|
||||
lora = comfy.utils.load_torch_file(lora_path, safe_load=True)
|
||||
|
||||
# Apply to model and clip
|
||||
model_out, clip_out = comfy.sd.load_lora_for_models(
|
||||
model_out, clip_out, lora, model_strength, clip_strength
|
||||
)
|
||||
|
||||
return (model_out, clip_out)
|
||||
@@ -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: 450 KiB |
|
Before Width: | Height: | Size: 159 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 |
|
After Width: | Height: | Size: 40 KiB |
@@ -0,0 +1,767 @@
|
||||
/**
|
||||
* File Browser Modal for PromptExtractor
|
||||
* Shows thumbnails of files in input directory
|
||||
*/
|
||||
import { PM_UI_PALETTE as UI } from './ui_palette.js';
|
||||
|
||||
// Track current subfolder for navigation
|
||||
let currentSubfolder = '';
|
||||
// Track current source folder (input or output)
|
||||
let currentSourceFolder = 'input';
|
||||
|
||||
export function createFileBrowserModal(currentFile, onFileSelect, sourceFolder) {
|
||||
// Store source folder
|
||||
currentSourceFolder = sourceFolder || 'input';
|
||||
// If a file is currently selected and lives in a subfolder, open in that folder
|
||||
if (currentFile && currentFile.includes('/')) {
|
||||
currentSubfolder = currentFile.substring(0, currentFile.lastIndexOf('/'));
|
||||
} else {
|
||||
currentSubfolder = '';
|
||||
}
|
||||
|
||||
// Create modal overlay
|
||||
const overlay = document.createElement('div');
|
||||
overlay.className = 'prompt-extractor-browser-overlay';
|
||||
overlay.style.cssText = `
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background: ${UI.overlay};
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
z-index: 10000;
|
||||
`;
|
||||
|
||||
// Create modal container (match PromptManagerAdvanced styling)
|
||||
const modal = document.createElement('div');
|
||||
modal.className = 'prompt-extractor-browser-modal';
|
||||
modal.style.cssText = `
|
||||
background: ${UI.panel};
|
||||
border: 1px solid ${UI.panelBorder};
|
||||
border-radius: 6px;
|
||||
width: 90%;
|
||||
max-width: 1200px;
|
||||
height: 80%;
|
||||
max-height: 800px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
`;
|
||||
|
||||
// Create header
|
||||
const header = document.createElement('div');
|
||||
header.style.cssText = `
|
||||
padding: 15px 20px;
|
||||
border-bottom: 1px solid ${UI.sectionBorder};
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
`;
|
||||
|
||||
const topRow = document.createElement('div');
|
||||
topRow.style.cssText = 'display: flex; justify-content: space-between; align-items: center;';
|
||||
topRow.innerHTML = `
|
||||
<h3 style="margin: 0; color: #d3d7de;">Select File from ${currentSourceFolder === 'output' ? 'Output' : 'Input'} Folder</h3>
|
||||
<div style="display: flex; gap: 10px; align-items: center;">
|
||||
<button class="regenerate-cache-btn" style="
|
||||
background: ${UI.buttonBg};
|
||||
border: 1px solid ${UI.inputBorder};
|
||||
border-radius: 6px;
|
||||
color: #ccc;
|
||||
padding: 5px 12px;
|
||||
cursor: pointer;
|
||||
font-size: 12px;
|
||||
">Regenerate Cache</button>
|
||||
<button class="close-btn" style="
|
||||
background: none;
|
||||
border: none;
|
||||
color: #aaa;
|
||||
font-size: 24px;
|
||||
cursor: pointer;
|
||||
padding: 0;
|
||||
width: 30px;
|
||||
height: 30px;
|
||||
">×</button>
|
||||
</div>
|
||||
`;
|
||||
|
||||
const breadcrumb = document.createElement('div');
|
||||
breadcrumb.className = 'folder-breadcrumb';
|
||||
breadcrumb.style.cssText = `font-size: 12px; color: ${UI.textHint}; cursor: pointer;`;
|
||||
breadcrumb.textContent = `${currentSourceFolder}/`;
|
||||
breadcrumb.onclick = () => {
|
||||
if (currentSubfolder) {
|
||||
currentSubfolder = '';
|
||||
loadFileThumbnails(gridContainer, currentFile, onFileSelect, overlay, breadcrumb);
|
||||
}
|
||||
};
|
||||
|
||||
header.appendChild(topRow);
|
||||
header.appendChild(breadcrumb);
|
||||
|
||||
// Create search/filter bar
|
||||
const filterBar = document.createElement('div');
|
||||
filterBar.style.cssText = `
|
||||
padding: 10px 20px;
|
||||
border-bottom: 1px solid ${UI.sectionBorder};
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
`;
|
||||
filterBar.innerHTML = `
|
||||
<input type="text" placeholder="Search files..." class="search-input" style="
|
||||
flex: 1;
|
||||
padding: 8px 12px;
|
||||
background: ${UI.inputBg};
|
||||
border: 1px solid ${UI.inputBorder};
|
||||
border-radius: 6px;
|
||||
color: #ccc;
|
||||
">
|
||||
<select class="filter-type" style="
|
||||
padding: 8px 12px;
|
||||
background: ${UI.inputBg};
|
||||
border: 1px solid ${UI.inputBorder};
|
||||
border-radius: 6px;
|
||||
color: #ccc;
|
||||
">
|
||||
<option value="all">All Files</option>
|
||||
<option value="image">Images</option>
|
||||
<option value="video">Videos</option>
|
||||
<option value="json">JSON</option>
|
||||
</select>
|
||||
`;
|
||||
|
||||
// Create thumbnail grid container
|
||||
const gridContainer = document.createElement('div');
|
||||
gridContainer.className = 'thumbnail-grid';
|
||||
gridContainer.style.cssText = `
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
padding: 20px;
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
|
||||
gap: 15px;
|
||||
align-content: start;
|
||||
`;
|
||||
|
||||
// Create loading indicator
|
||||
const loading = document.createElement('div');
|
||||
loading.style.cssText = `
|
||||
text-align: center;
|
||||
padding: 40px;
|
||||
color: #aaa;
|
||||
`;
|
||||
loading.textContent = 'Loading files...';
|
||||
gridContainer.appendChild(loading);
|
||||
|
||||
// Assemble modal
|
||||
modal.appendChild(header);
|
||||
modal.appendChild(filterBar);
|
||||
modal.appendChild(gridContainer);
|
||||
overlay.appendChild(modal);
|
||||
|
||||
// Prevent right-click context menu everywhere in the browser
|
||||
// (video thumbnails have their own handler that will show the refresh menu)
|
||||
overlay.oncontextmenu = (e) => {
|
||||
e.preventDefault();
|
||||
return false;
|
||||
};
|
||||
|
||||
// Close button handler
|
||||
const closeBtn = topRow.querySelector('.close-btn');
|
||||
closeBtn.onclick = () => document.body.removeChild(overlay);
|
||||
overlay.onclick = (e) => {
|
||||
if (e.target === overlay) document.body.removeChild(overlay);
|
||||
};
|
||||
|
||||
// Regenerate cache button handler
|
||||
const regenerateCacheBtn = topRow.querySelector('.regenerate-cache-btn');
|
||||
regenerateCacheBtn.onclick = () => {
|
||||
clearThumbnailCache();
|
||||
// Reload thumbnails to regenerate them
|
||||
loadFileThumbnails(gridContainer, currentFile, onFileSelect, overlay, breadcrumb);
|
||||
};
|
||||
|
||||
// Add to DOM
|
||||
document.body.appendChild(overlay);
|
||||
|
||||
// Load files
|
||||
loadFileThumbnails(gridContainer, currentFile, onFileSelect, overlay, breadcrumb);
|
||||
|
||||
// Setup search/filter
|
||||
const searchInput = filterBar.querySelector('.search-input');
|
||||
const filterType = filterBar.querySelector('.filter-type');
|
||||
|
||||
searchInput.oninput = () => filterThumbnails(gridContainer, searchInput.value, filterType.value);
|
||||
filterType.onchange = () => filterThumbnails(gridContainer, searchInput.value, filterType.value);
|
||||
}
|
||||
|
||||
async function loadFileThumbnails(container, currentFile, onFileSelect, overlay, breadcrumbElement) {
|
||||
try {
|
||||
// Update breadcrumb
|
||||
if (!currentSubfolder) {
|
||||
breadcrumbElement.textContent = `${currentSourceFolder}/`;
|
||||
} else {
|
||||
breadcrumbElement.textContent = `${currentSourceFolder}/${currentSubfolder}/`;
|
||||
}
|
||||
|
||||
// Fetch file list from server
|
||||
const response = await fetch(`/prompt-extractor/list-files?source=${encodeURIComponent(currentSourceFolder)}`);
|
||||
const data = await response.json();
|
||||
|
||||
container.innerHTML = '';
|
||||
|
||||
if (!data.files || data.files.length === 0) {
|
||||
container.innerHTML = '<div style="text-align: center; padding: 40px; color: #aaa;">No files found in ' + currentSourceFolder + ' directory</div>';
|
||||
return;
|
||||
}
|
||||
|
||||
// Get all files with their full paths
|
||||
const allFiles = data.files.filter(f => f !== '(none)');
|
||||
|
||||
// Filter files/folders for current directory
|
||||
const currentFiles = [];
|
||||
const subfolders = new Set();
|
||||
|
||||
const prefix = currentSubfolder ? currentSubfolder + '/' : '';
|
||||
|
||||
allFiles.forEach(filepath => {
|
||||
if (filepath.startsWith(prefix)) {
|
||||
const remainder = filepath.substring(prefix.length);
|
||||
const slashIndex = remainder.indexOf('/');
|
||||
|
||||
if (slashIndex === -1) {
|
||||
// It's a file in current directory
|
||||
currentFiles.push(filepath);
|
||||
} else {
|
||||
// It's in a subdirectory - extract folder name
|
||||
const folderName = remainder.substring(0, slashIndex);
|
||||
subfolders.add(folderName);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Add "back" button if in subfolder
|
||||
if (currentSubfolder) {
|
||||
const backItem = createBackItem(container, currentFile, onFileSelect, overlay, breadcrumbElement);
|
||||
container.appendChild(backItem);
|
||||
}
|
||||
|
||||
// Add folder items
|
||||
Array.from(subfolders).sort().forEach(folderName => {
|
||||
const folderItem = createFolderItem(folderName, container, currentFile, onFileSelect, overlay, breadcrumbElement);
|
||||
container.appendChild(folderItem);
|
||||
});
|
||||
|
||||
// Create thumbnail for each file
|
||||
currentFiles.forEach(filename => {
|
||||
const item = createThumbnailItem(filename, currentFile, onFileSelect, overlay);
|
||||
container.appendChild(item);
|
||||
});
|
||||
|
||||
// Scroll to the currently selected file
|
||||
if (currentFile) {
|
||||
const selectedItem = container.querySelector(`.thumbnail-item[data-filename="${CSS.escape(currentFile)}"]`);
|
||||
if (selectedItem) {
|
||||
// Use requestAnimationFrame to ensure layout is complete before scrolling
|
||||
requestAnimationFrame(() => {
|
||||
selectedItem.scrollIntoView({ block: 'center', behavior: 'instant' });
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('[FileBrowser] Error loading files:', error);
|
||||
container.innerHTML = '<div style="text-align: center; padding: 40px; color: rgba(220, 53, 69, 0.9);">Error loading files</div>';
|
||||
}
|
||||
}
|
||||
|
||||
function createBackItem(container, currentFile, onFileSelect, overlay, breadcrumbElement) {
|
||||
const item = document.createElement('div');
|
||||
item.className = 'folder-item';
|
||||
item.style.cssText = `
|
||||
background: ${UI.cardBg};
|
||||
border: 1px solid ${UI.panelBorder};
|
||||
border-radius: 6px;
|
||||
padding: 8px;
|
||||
cursor: pointer;
|
||||
transition: all 0.15s ease;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
`;
|
||||
|
||||
const preview = document.createElement('div');
|
||||
preview.style.cssText = `
|
||||
width: 100%;
|
||||
height: 150px;
|
||||
background: rgba(16, 18, 22, 0.6);
|
||||
border-radius: 4px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 64px;
|
||||
`;
|
||||
preview.textContent = '←';
|
||||
|
||||
const label = document.createElement('div');
|
||||
label.textContent = 'Back';
|
||||
label.style.cssText = `
|
||||
font-size: 12px;
|
||||
color: #ccc;
|
||||
text-align: center;
|
||||
`;
|
||||
|
||||
item.appendChild(preview);
|
||||
item.appendChild(label);
|
||||
|
||||
item.onmouseenter = () => {
|
||||
item.style.borderColor = UI.accentBorder;
|
||||
item.style.transform = 'translateY(-2px)';
|
||||
item.style.background = UI.accentSoft;
|
||||
};
|
||||
item.onmouseleave = () => {
|
||||
item.style.borderColor = UI.panelBorder;
|
||||
item.style.transform = 'translateY(0)';
|
||||
item.style.background = UI.cardBg;
|
||||
};
|
||||
|
||||
item.onclick = () => {
|
||||
// Go up one level
|
||||
const parts = currentSubfolder.split('/');
|
||||
parts.pop();
|
||||
currentSubfolder = parts.join('/');
|
||||
loadFileThumbnails(container, currentFile, onFileSelect, overlay, breadcrumbElement);
|
||||
};
|
||||
|
||||
return item;
|
||||
}
|
||||
|
||||
function createFolderItem(folderName, container, currentFile, onFileSelect, overlay, breadcrumbElement) {
|
||||
const item = document.createElement('div');
|
||||
item.className = 'folder-item';
|
||||
item.style.cssText = `
|
||||
background: rgba(45, 55, 72, 0.7);
|
||||
border: 1px solid rgba(226, 232, 240, 0.2);
|
||||
border-radius: 6px;
|
||||
padding: 8px;
|
||||
cursor: pointer;
|
||||
transition: all 0.15s ease;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
`;
|
||||
|
||||
const preview = document.createElement('div');
|
||||
preview.style.cssText = `
|
||||
width: 100%;
|
||||
height: 150px;
|
||||
background: rgba(0, 0, 0, 0.5);
|
||||
border-radius: 4px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 64px;
|
||||
`;
|
||||
preview.textContent = '📁';
|
||||
|
||||
const label = document.createElement('div');
|
||||
label.textContent = folderName;
|
||||
label.style.cssText = `
|
||||
font-size: 12px;
|
||||
color: #ccc;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
text-align: center;
|
||||
`;
|
||||
label.title = folderName;
|
||||
|
||||
item.appendChild(preview);
|
||||
item.appendChild(label);
|
||||
|
||||
item.onmouseenter = () => {
|
||||
item.style.borderColor = 'rgba(66, 153, 225, 0.9)';
|
||||
item.style.transform = 'translateY(-2px)';
|
||||
item.style.background = 'rgba(50, 112, 163, 0.5)';
|
||||
};
|
||||
item.onmouseleave = () => {
|
||||
item.style.borderColor = 'rgba(226, 232, 240, 0.2)';
|
||||
item.style.transform = 'translateY(0)';
|
||||
item.style.background = 'rgba(45, 55, 72, 0.7)';
|
||||
};
|
||||
|
||||
item.onclick = () => {
|
||||
// Navigate into folder
|
||||
currentSubfolder = currentSubfolder ? `${currentSubfolder}/${folderName}` : folderName;
|
||||
loadFileThumbnails(container, currentFile, onFileSelect, overlay, breadcrumbElement);
|
||||
};
|
||||
|
||||
return item;
|
||||
}
|
||||
|
||||
function createThumbnailItem(filename, currentFile, onFileSelect, overlay) {
|
||||
const item = document.createElement('div');
|
||||
item.className = 'thumbnail-item';
|
||||
item.dataset.filename = filename;
|
||||
item.dataset.type = getFileType(filename);
|
||||
|
||||
const isSelected = filename === currentFile;
|
||||
|
||||
item.style.cssText = `
|
||||
background: ${UI.cardBg};
|
||||
border: 1px solid ${isSelected ? UI.accent : UI.panelBorder};
|
||||
border-radius: 6px;
|
||||
padding: 8px;
|
||||
cursor: pointer;
|
||||
transition: all 0.15s ease;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
`;
|
||||
|
||||
// Thumbnail preview
|
||||
const preview = document.createElement('div');
|
||||
preview.style.cssText = `
|
||||
width: 100%;
|
||||
height: 150px;
|
||||
background: rgba(16, 18, 22, 0.6);
|
||||
border-radius: 4px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
overflow: hidden;
|
||||
position: relative;
|
||||
`;
|
||||
|
||||
const ext = filename.split('.').pop().toLowerCase();
|
||||
const imageExts = ['png', 'jpg', 'jpeg', 'webp'];
|
||||
const videoExts = ['mp4', 'webm', 'mov', 'avi'];
|
||||
|
||||
if (imageExts.includes(ext)) {
|
||||
const img = document.createElement('img');
|
||||
// Handle subfolder paths: split filename into folder and basename
|
||||
let subfolder = '';
|
||||
let basename = filename;
|
||||
if (filename.includes('/')) {
|
||||
const lastSlash = filename.lastIndexOf('/');
|
||||
subfolder = filename.substring(0, lastSlash);
|
||||
basename = filename.substring(lastSlash + 1);
|
||||
}
|
||||
img.src = `/view?filename=${encodeURIComponent(basename)}&type=${currentSourceFolder}&subfolder=${encodeURIComponent(subfolder)}`;
|
||||
img.style.cssText = 'max-width: 100%; max-height: 100%; object-fit: contain;';
|
||||
img.onerror = () => {
|
||||
// Use placeholder image
|
||||
img.src = new URL("./placeholder.png", import.meta.url).href;
|
||||
};
|
||||
preview.appendChild(img);
|
||||
} else if (videoExts.includes(ext)) {
|
||||
// Extract video thumbnail via server-side PyAV
|
||||
extractVideoThumbnailServer(filename, preview);
|
||||
} else if (ext === 'json') {
|
||||
// Use placeholder for JSON
|
||||
const img = document.createElement('img');
|
||||
img.src = new URL("./placeholder.png", import.meta.url).href;
|
||||
img.style.cssText = 'max-width: 100%; max-height: 100%; object-fit: contain;';
|
||||
preview.appendChild(img);
|
||||
} else {
|
||||
// Use placeholder for unknown types
|
||||
const img = document.createElement('img');
|
||||
img.src = new URL("./placeholder.png", import.meta.url).href;
|
||||
img.style.cssText = 'max-width: 100%; max-height: 100%; object-fit: contain;';
|
||||
preview.appendChild(img);
|
||||
}
|
||||
|
||||
// Filename label (show only basename, not full path)
|
||||
const label = document.createElement('div');
|
||||
const basename = filename.includes('/') ? filename.split('/').pop() : filename;
|
||||
label.textContent = basename;
|
||||
label.style.cssText = `
|
||||
font-size: 12px;
|
||||
color: ${isSelected ? '#fff' : '#ccc'};
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
text-align: center;
|
||||
`;
|
||||
label.title = filename; // Full path in tooltip
|
||||
|
||||
item.appendChild(preview);
|
||||
item.appendChild(label);
|
||||
|
||||
// Hover effect
|
||||
item.onmouseenter = () => {
|
||||
if (!isSelected) {
|
||||
item.style.borderColor = UI.accentBorder;
|
||||
item.style.transform = 'translateY(-2px)';
|
||||
item.style.background = UI.accentSoft;
|
||||
}
|
||||
};
|
||||
item.onmouseleave = () => {
|
||||
if (!isSelected) {
|
||||
item.style.borderColor = UI.panelBorder;
|
||||
item.style.transform = 'translateY(0)';
|
||||
item.style.background = UI.cardBg;
|
||||
}
|
||||
};
|
||||
|
||||
// Click handler
|
||||
item.onclick = (e) => {
|
||||
// Don't select if clicking to close context menu
|
||||
if (document.querySelector('.thumbnail-context-menu')) {
|
||||
return;
|
||||
}
|
||||
onFileSelect(filename);
|
||||
document.body.removeChild(overlay);
|
||||
};
|
||||
|
||||
// Right-click context menu - only for video thumbnails
|
||||
if (videoExts.includes(ext)) {
|
||||
item.oncontextmenu = (e) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
showThumbnailContextMenu(e, filename, preview);
|
||||
return false;
|
||||
};
|
||||
}
|
||||
|
||||
return item;
|
||||
}
|
||||
|
||||
function getFileType(filename) {
|
||||
const ext = filename.split('.').pop().toLowerCase();
|
||||
const imageExts = ['png', 'jpg', 'jpeg', 'webp'];
|
||||
const videoExts = ['mp4', 'webm', 'mov', 'avi'];
|
||||
|
||||
if (imageExts.includes(ext)) return 'image';
|
||||
if (videoExts.includes(ext)) return 'video';
|
||||
if (ext === 'json') return 'json';
|
||||
return 'other';
|
||||
}
|
||||
|
||||
/**
|
||||
* Show context menu for thumbnail with refresh option
|
||||
*/
|
||||
function showThumbnailContextMenu(event, filename, previewElement) {
|
||||
// Remove any existing context menu
|
||||
const existingMenu = document.querySelector('.thumbnail-context-menu');
|
||||
if (existingMenu) {
|
||||
existingMenu.remove();
|
||||
}
|
||||
|
||||
// Create context menu
|
||||
const menu = document.createElement('div');
|
||||
menu.className = 'thumbnail-context-menu';
|
||||
menu.style.cssText = `
|
||||
position: fixed;
|
||||
left: ${event.pageX}px;
|
||||
top: ${event.pageY}px;
|
||||
background: ${UI.panel};
|
||||
border: 1px solid ${UI.panelBorder};
|
||||
border-radius: 6px;
|
||||
padding: 4px;
|
||||
z-index: 10001;
|
||||
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.5);
|
||||
min-width: 160px;
|
||||
`;
|
||||
|
||||
// Refresh option
|
||||
const refreshBtn = document.createElement('div');
|
||||
refreshBtn.textContent = '🔄 Refresh Thumbnail';
|
||||
refreshBtn.style.cssText = `
|
||||
padding: 8px 12px;
|
||||
color: #ccc;
|
||||
cursor: pointer;
|
||||
border-radius: 4px;
|
||||
font-size: 13px;
|
||||
transition: background 0.15s ease;
|
||||
`;
|
||||
refreshBtn.onmouseenter = () => {
|
||||
refreshBtn.style.background = UI.accentSoft;
|
||||
};
|
||||
refreshBtn.onmouseleave = () => {
|
||||
refreshBtn.style.background = 'transparent';
|
||||
};
|
||||
refreshBtn.onclick = () => {
|
||||
refreshIndividualThumbnail(filename, previewElement);
|
||||
menu.remove();
|
||||
};
|
||||
|
||||
menu.appendChild(refreshBtn);
|
||||
document.body.appendChild(menu);
|
||||
|
||||
// Close menu when clicking outside
|
||||
const closeMenu = (e) => {
|
||||
if (!menu.contains(e.target)) {
|
||||
e.stopPropagation(); // Prevent click from going through to elements below
|
||||
menu.remove();
|
||||
document.removeEventListener('click', closeMenu, true); // Remove from capture phase
|
||||
}
|
||||
};
|
||||
// Use capture phase to catch the click before it reaches other elements
|
||||
setTimeout(() => {
|
||||
document.addEventListener('click', closeMenu, true);
|
||||
}, 10);
|
||||
}
|
||||
|
||||
/**
|
||||
* Refresh thumbnail for a single file
|
||||
*/
|
||||
function refreshIndividualThumbnail(filename, previewElement) {
|
||||
console.log(`[FileBrowser] Refreshing thumbnail for: ${filename}`);
|
||||
|
||||
// Clear cache for this specific file
|
||||
const cacheKey = `video_thumb_pyav_${filename.replace(/[\/\\]/g, '_')}`;
|
||||
|
||||
try {
|
||||
localStorage.removeItem(cacheKey);
|
||||
console.log(`[FileBrowser] Cleared cache for: ${filename}`);
|
||||
} catch (error) {
|
||||
console.error('[FileBrowser] Error clearing cache:', error);
|
||||
}
|
||||
|
||||
// Re-extract thumbnail via server-side PyAV
|
||||
extractVideoThumbnailServer(filename, previewElement);
|
||||
}
|
||||
|
||||
function filterThumbnails(container, searchText, fileType) {
|
||||
const items = container.querySelectorAll('.thumbnail-item');
|
||||
const search = searchText.toLowerCase();
|
||||
|
||||
items.forEach(item => {
|
||||
const filename = item.dataset.filename.toLowerCase();
|
||||
const type = item.dataset.type;
|
||||
|
||||
const matchesSearch = !searchText || filename.includes(search);
|
||||
const matchesType = fileType === 'all' || type === fileType;
|
||||
|
||||
item.style.display = (matchesSearch && matchesType) ? 'flex' : 'none';
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract thumbnail using server-side PyAV for all videos.
|
||||
* Fetches a JPEG frame from /prompt-extractor/video-frame and caches to localStorage.
|
||||
*/
|
||||
function extractVideoThumbnailServer(filename, previewElement) {
|
||||
const cacheKey = `video_thumb_pyav_${filename.replace(/[\/\\]/g, '_')}`;
|
||||
try {
|
||||
const cached = localStorage.getItem(cacheKey);
|
||||
if (cached) {
|
||||
const img = document.createElement('img');
|
||||
img.style.cssText = 'max-width: 100%; max-height: 100%; object-fit: contain;';
|
||||
img.src = cached;
|
||||
previewElement.innerHTML = '';
|
||||
previewElement.appendChild(img);
|
||||
return;
|
||||
}
|
||||
} catch (e) { /* ignore */ }
|
||||
|
||||
// Show placeholder while loading
|
||||
const placeholderImg = document.createElement('img');
|
||||
placeholderImg.src = new URL("./placeholder.png", import.meta.url).href;
|
||||
placeholderImg.style.cssText = 'max-width: 100%; max-height: 100%; object-fit: contain;';
|
||||
previewElement.innerHTML = '';
|
||||
previewElement.appendChild(placeholderImg);
|
||||
|
||||
const frameUrl = `/prompt-extractor/video-frame?filename=${encodeURIComponent(filename)}&source=${currentSourceFolder}&position=0`;
|
||||
const img = document.createElement('img');
|
||||
img.onload = () => {
|
||||
// Scale down to thumbnail size
|
||||
const maxW = 180, maxH = 150;
|
||||
const ar = img.naturalWidth / img.naturalHeight;
|
||||
let w, h;
|
||||
if (ar > maxW / maxH) { w = maxW; h = maxW / ar; }
|
||||
else { h = maxH; w = maxH * ar; }
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = w;
|
||||
canvas.height = h;
|
||||
const ctx = canvas.getContext('2d', { alpha: false });
|
||||
ctx.drawImage(img, 0, 0, w, h);
|
||||
const dataUrl = canvas.toDataURL('image/jpeg', 0.6);
|
||||
const result = document.createElement('img');
|
||||
result.style.cssText = 'max-width: 100%; max-height: 100%; object-fit: contain;';
|
||||
result.src = dataUrl;
|
||||
previewElement.innerHTML = '';
|
||||
previewElement.appendChild(result);
|
||||
try { localStorage.setItem(cacheKey, dataUrl); } catch (e) { /* ignore */ }
|
||||
};
|
||||
img.onerror = () => {
|
||||
previewElement.innerHTML = `
|
||||
<div style="text-align: center; color: #888; font-size: 11px; padding: 10px;">
|
||||
<div style="font-size: 24px; margin-bottom: 6px;">🎬</div>
|
||||
<div>Preview unavailable</div>
|
||||
</div>`;
|
||||
};
|
||||
img.src = frameUrl;
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear all video thumbnail cache
|
||||
*/
|
||||
function clearThumbnailCache() {
|
||||
try {
|
||||
const cachePrefix = 'video_thumb_';
|
||||
const keysToRemove = [];
|
||||
|
||||
// Find all cache keys in localStorage
|
||||
for (let i = 0; i < localStorage.length; i++) {
|
||||
const key = localStorage.key(i);
|
||||
if (key && key.startsWith(cachePrefix)) {
|
||||
keysToRemove.push(key);
|
||||
}
|
||||
}
|
||||
|
||||
// Remove all cache entries
|
||||
keysToRemove.forEach(key => {
|
||||
localStorage.removeItem(key);
|
||||
});
|
||||
|
||||
console.log(`[FileBrowser] Cleared ${keysToRemove.length} cache entries`);
|
||||
} catch (error) {
|
||||
console.error('[FileBrowser] Error clearing cache:', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Clean up orphaned thumbnail cache entries
|
||||
* Removes cache for files that no longer exist in the input directory
|
||||
*/
|
||||
function cleanupOrphanedThumbnailCache(currentFiles) {
|
||||
try {
|
||||
const cachePrefix = 'video_thumb_';
|
||||
const timePrefix = 'video_thumb_time_';
|
||||
const keysToRemove = [];
|
||||
|
||||
// Find all cache keys in localStorage
|
||||
for (let i = 0; i < localStorage.length; i++) {
|
||||
const key = localStorage.key(i);
|
||||
|
||||
// Check if it's a video thumbnail cache key
|
||||
if (key && key.startsWith(cachePrefix)) {
|
||||
// Extract filename from cache key
|
||||
const filename = key.substring(cachePrefix.length);
|
||||
|
||||
// If this filename is not in current files list, mark for removal
|
||||
if (!currentFiles.includes(filename)) {
|
||||
keysToRemove.push(key);
|
||||
keysToRemove.push(timePrefix + filename);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Remove orphaned cache entries
|
||||
keysToRemove.forEach(key => {
|
||||
localStorage.removeItem(key);
|
||||
});
|
||||
|
||||
if (keysToRemove.length > 0) {
|
||||
console.log(`[FileBrowser] Cleaned up ${keysToRemove.length / 2} orphaned thumbnail cache entries`);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('[FileBrowser] Error cleaning up cache:', error);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
};
|
||||
},
|
||||
});
|
||||
|
After Width: | Height: | Size: 747 B |
@@ -106,20 +106,116 @@ app.registerExtension({
|
||||
console.error("[PromptManager] Error saving Close Llama preference:", error);
|
||||
});
|
||||
}
|
||||
},
|
||||
{
|
||||
id: "PromptManager.WarnUnsavedChanges",
|
||||
category: ["Prompt Manager", "4. Advanced Preferences", "Warn Unsaved Changes"],
|
||||
name: "Warn about unsaved prompt changes",
|
||||
tooltip: "Show a warning when switching prompts if there are unsaved changes to the current prompt text, LoRAs, or trigger words.",
|
||||
type: "boolean",
|
||||
defaultValue: true
|
||||
},
|
||||
{
|
||||
id: "PromptManager.DefaultHideNSFW",
|
||||
category: ["Prompt Manager", "4. Advanced Preferences", "Hide NSFW by Default"],
|
||||
name: "Hide NSFW prompts by default",
|
||||
tooltip: "When enabled, NSFW categories and prompts are hidden in the prompt browser on startup. Can be toggled per session.",
|
||||
type: "boolean",
|
||||
defaultValue: true
|
||||
},
|
||||
{
|
||||
id: "PromptManager.DefaultViewMode",
|
||||
category: ["Prompt Manager", "4. Advanced Preferences", "Prompt Browser View Mode"],
|
||||
name: "Default prompt browser view mode",
|
||||
tooltip: "Choose the default display mode for the prompt browser: thumbnails grid or compact list view.",
|
||||
type: "combo",
|
||||
options: ["thumbnails", "list"],
|
||||
defaultValue: "thumbnails"
|
||||
},
|
||||
{
|
||||
id: "PromptManager.EnableThumbnailPreview",
|
||||
category: ["Prompt Manager", "4. Advanced Preferences", "Enable Thumbnail Hover Preview"],
|
||||
name: "Enable thumbnail hover preview",
|
||||
tooltip: "When enabled, hovering over thumbnails in the prompt browser shows a larger preview after a short delay.",
|
||||
type: "boolean",
|
||||
defaultValue: true
|
||||
},
|
||||
{
|
||||
id: "PromptManager.ThumbnailCheckpoint",
|
||||
category: ["Prompt Manager", "4. Advanced Preferences", "Thumbnail Generation Checkpoint"],
|
||||
name: "Checkpoint for thumbnail generation",
|
||||
tooltip: "The checkpoint model used when generating thumbnails via right-click menu. Can also be changed from the prompt context menu.",
|
||||
type: "text",
|
||||
defaultValue: ""
|
||||
},
|
||||
{
|
||||
id: "PromptManager.LLMBackend",
|
||||
category: ["Prompt Manager", "5. Ollama Settings", "LLM Backend"],
|
||||
name: "LLM Backend",
|
||||
tooltip: "Choose the LLM backend: llama.cpp (local server, default) or Ollama",
|
||||
type: "combo",
|
||||
options: ["llama.cpp", "ollama"],
|
||||
defaultValue: "llama.cpp",
|
||||
onChange(value) {
|
||||
fetch("/prompt-manager/save-preference", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ key: "llm_backend", value: value })
|
||||
}).catch(error => {
|
||||
console.error("[PromptManager] Error saving LLM backend preference:", error);
|
||||
});
|
||||
}
|
||||
},
|
||||
{
|
||||
id: "PromptManager.OllamaUrl",
|
||||
category: ["Prompt Manager", "5. Ollama Settings", "Ollama URL"],
|
||||
name: "Ollama URL",
|
||||
tooltip: "URL of the Ollama server (default: http://127.0.0.1:11434)",
|
||||
type: "text",
|
||||
defaultValue: "http://127.0.0.1:11434",
|
||||
onChange(value) {
|
||||
fetch("/prompt-manager/save-preference", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ key: "ollama_url", value: value })
|
||||
}).catch(error => {
|
||||
console.error("[PromptManager] Error saving Ollama URL preference:", error);
|
||||
});
|
||||
}
|
||||
},
|
||||
{
|
||||
id: "PromptManager.OllamaKeepAlive",
|
||||
category: ["Prompt Manager", "5. Ollama Settings", "Keep Alive Duration"],
|
||||
name: "Keep Alive Duration",
|
||||
tooltip: "How long Ollama keeps the model loaded in memory after a request. Examples: '5m' (5 minutes), '30m', '1h', '0' (unload immediately), '-1' (keep forever). Default: 5m",
|
||||
type: "text",
|
||||
defaultValue: "5m",
|
||||
onChange(value) {
|
||||
fetch("/prompt-manager/save-preference", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ key: "ollama_keep_alive", value: value })
|
||||
}).catch(error => {
|
||||
console.error("[PromptManager] Error saving Ollama keep alive preference:", error);
|
||||
});
|
||||
}
|
||||
}
|
||||
],
|
||||
async setup() {
|
||||
// Load settings from ComfyUI and sync to Python cache
|
||||
try {
|
||||
// Sync current values to Python cache first
|
||||
const baseModel = app.ui.settings.getSettingValue("PromptManager.PreferredBaseModel", "");
|
||||
const visionModel = app.ui.settings.getSettingValue("PromptManager.PreferredVisionModel", "");
|
||||
const llamaPath = app.ui.settings.getSettingValue("PromptManager.LlamaPath", "");
|
||||
const modelPath = app.ui.settings.getSettingValue("PromptManager.ModelPath", "");
|
||||
const port = app.ui.settings.getSettingValue("PromptManager.Port", "8080");
|
||||
const CloseLlama = app.ui.settings.getSettingValue("PromptManager.CloseLlama", true);
|
||||
const baseModel = app.ui.settings.getSettingValue("PromptManager.PreferredBaseModel");
|
||||
const visionModel = app.ui.settings.getSettingValue("PromptManager.PreferredVisionModel");
|
||||
const llamaPath = app.ui.settings.getSettingValue("PromptManager.LlamaPath");
|
||||
const modelPath = app.ui.settings.getSettingValue("PromptManager.ModelPath");
|
||||
const port = app.ui.settings.getSettingValue("PromptManager.Port");
|
||||
const CloseLlama = app.ui.settings.getSettingValue("PromptManager.CloseLlama");
|
||||
const llmBackend = app.ui.settings.getSettingValue("PromptManager.LLMBackend");
|
||||
const ollamaUrl = app.ui.settings.getSettingValue("PromptManager.OllamaUrl");
|
||||
const ollamaKeepAlive = app.ui.settings.getSettingValue("PromptManager.OllamaKeepAlive");
|
||||
|
||||
console.log("[PromptManager] Syncing preferences:", { baseModel, visionModel, llamaPath, modelPath, port, CloseLlama });
|
||||
console.log("[PromptManager] Syncing preferences:", { baseModel, visionModel, llamaPath, modelPath, port, CloseLlama, llmBackend, ollamaUrl, ollamaKeepAlive });
|
||||
await fetch("/prompt-manager/save-preference", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
@@ -150,6 +246,21 @@ app.registerExtension({
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ key: "close_llama_on_exit", value: CloseLlama })
|
||||
});
|
||||
await fetch("/prompt-manager/save-preference", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ key: "llm_backend", value: llmBackend })
|
||||
});
|
||||
await fetch("/prompt-manager/save-preference", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ key: "ollama_url", value: ollamaUrl })
|
||||
});
|
||||
await fetch("/prompt-manager/save-preference", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ key: "ollama_keep_alive", value: ollamaKeepAlive })
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("[PromptManager] Error syncing preferences:", error);
|
||||
}
|
||||
@@ -228,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(() => {
|
||||
@@ -251,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);
|
||||
@@ -269,6 +387,53 @@ app.registerExtension({
|
||||
return result;
|
||||
};
|
||||
|
||||
// Draw red NSFW badge at the top of the node when NSFW content is selected
|
||||
const onDrawForeground = nodeType.prototype.onDrawForeground;
|
||||
nodeType.prototype.onDrawForeground = function(ctx) {
|
||||
if (onDrawForeground) onDrawForeground.apply(this, arguments);
|
||||
|
||||
const hideNSFW = app.ui.settings.getSettingValue("PromptManager.DefaultHideNSFW");
|
||||
if (hideNSFW || !this.prompts) return;
|
||||
|
||||
const categoryWidget = this.widgets?.find(w => w.name === "category");
|
||||
const promptWidget = this.widgets?.find(w => w.name === "name");
|
||||
if (!categoryWidget || !promptWidget) return;
|
||||
|
||||
const category = categoryWidget.value;
|
||||
const promptName = promptWidget.value;
|
||||
const catIsNSFW = this.prompts[category]?.["__meta__"]?.nsfw === true;
|
||||
const promptIsNSFW = this.prompts[category]?.[promptName]?.nsfw === true;
|
||||
|
||||
if (catIsNSFW || promptIsNSFW) {
|
||||
ctx.save();
|
||||
// Draw red "NSFW" badge at top-right of node
|
||||
const text = "NSFW";
|
||||
ctx.font = "bold 8px sans-serif";
|
||||
const textWidth = ctx.measureText(text).width;
|
||||
const badgeW = textWidth + 8;
|
||||
const badgeH = 12;
|
||||
const badgeX = this.size[0] - badgeW - 4;
|
||||
const badgeY = -LiteGraph.NODE_TITLE_HEIGHT + (LiteGraph.NODE_TITLE_HEIGHT - badgeH) / 2;
|
||||
|
||||
// Badge background
|
||||
ctx.fillStyle = "rgba(204, 50, 50, 0.85)";
|
||||
ctx.beginPath();
|
||||
if (ctx.roundRect) {
|
||||
ctx.roundRect(badgeX, badgeY, badgeW, badgeH, 2);
|
||||
} else {
|
||||
ctx.rect(badgeX, badgeY, badgeW, badgeH);
|
||||
}
|
||||
ctx.fill();
|
||||
|
||||
// Badge text
|
||||
ctx.fillStyle = "#fff";
|
||||
ctx.textAlign = "center";
|
||||
ctx.textBaseline = "middle";
|
||||
ctx.fillText(text, badgeX + badgeW / 2, badgeY + badgeH / 2);
|
||||
ctx.restore();
|
||||
}
|
||||
};
|
||||
|
||||
// Enforce minimum node width
|
||||
const onResize = nodeType.prototype.onResize;
|
||||
nodeType.prototype.onResize = function(size) {
|
||||
@@ -365,15 +530,52 @@ 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");
|
||||
|
||||
if (categoryWidget && promptWidget) {
|
||||
const hideNSFW = app.ui.settings.getSettingValue("PromptManager.DefaultHideNSFW");
|
||||
|
||||
// Filter NSFW categories from the category dropdown
|
||||
if (node.prompts) {
|
||||
let categories = Object.keys(node.prompts).sort((a, b) => a.localeCompare(b));
|
||||
const currentCategoryValue = String(categoryWidget.value || "");
|
||||
|
||||
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];
|
||||
}
|
||||
}
|
||||
|
||||
const currentCategory = categoryWidget.value;
|
||||
if (node.prompts[currentCategory]) {
|
||||
const promptNames = Object.keys(node.prompts[currentCategory]).sort((a, b) => a.localeCompare(b));
|
||||
let promptNames = Object.keys(node.prompts[currentCategory]).filter(k => k !== '__meta__').sort((a, b) => a.localeCompare(b));
|
||||
if (hideNSFW) {
|
||||
const catIsNSFW = node.prompts[currentCategory]?.["__meta__"]?.nsfw === true;
|
||||
if (catIsNSFW) {
|
||||
promptNames = [];
|
||||
} else {
|
||||
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("");
|
||||
}
|
||||
@@ -391,13 +593,16 @@ function addButtonBar(node) {
|
||||
const categoryWidget = node.widgets.find(w => w.name === "category");
|
||||
const promptWidget = node.widgets.find(w => w.name === "name");
|
||||
|
||||
// Create button container
|
||||
// Create button container with proper styling for DOM widget
|
||||
const buttonContainer = document.createElement("div");
|
||||
buttonContainer.style.display = "flex";
|
||||
buttonContainer.style.gap = "4px";
|
||||
buttonContainer.style.padding = "2px 4px 4px 4px";
|
||||
buttonContainer.style.flexWrap = "nowrap";
|
||||
buttonContainer.style.marginTop = "-10px";
|
||||
buttonContainer.style.width = "100%";
|
||||
buttonContainer.style.boxSizing = "border-box";
|
||||
buttonContainer.style.position = "relative";
|
||||
|
||||
// Save Prompt button with category selection
|
||||
const savePromptBtn = createButton("Save Prompt", async () => {
|
||||
@@ -425,7 +630,7 @@ function addButtonBar(node) {
|
||||
// Case-insensitive check for existing prompt
|
||||
let existingPromptName = null;
|
||||
if (node.prompts[targetCategory]) {
|
||||
const existingNames = Object.keys(node.prompts[targetCategory]);
|
||||
const existingNames = Object.keys(node.prompts[targetCategory]).filter(k => k !== '__meta__');
|
||||
existingPromptName = existingNames.find(name => name.toLowerCase() === promptName.toLowerCase());
|
||||
}
|
||||
|
||||
@@ -457,16 +662,16 @@ function addButtonBar(node) {
|
||||
}
|
||||
});
|
||||
|
||||
// New Prompt button with category selection
|
||||
// New Prompt button - simply clears fields for a fresh start
|
||||
const newPromptBtn = createButton("New Prompt", async () => {
|
||||
// Check for unsaved changes before creating new prompt
|
||||
const hasUnsaved = hasUnsavedChanges(node);
|
||||
const warnEnabled = app.ui.settings.getSettingValue("PromptManager.warnUnsavedChanges", true);
|
||||
const warnEnabled = app.ui.settings.getSettingValue("PromptManager.warnUnsavedChanges");
|
||||
|
||||
if (hasUnsaved && warnEnabled) {
|
||||
const confirmed = await showConfirm(
|
||||
"Unsaved Changes",
|
||||
"You have unsaved changes to the current prompt. Do you want to discard them and create a new prompt?",
|
||||
"You have unsaved changes to the current prompt. Do you want to discard them and start fresh?",
|
||||
"Discard & Continue",
|
||||
"#f80"
|
||||
);
|
||||
@@ -475,59 +680,27 @@ function addButtonBar(node) {
|
||||
}
|
||||
}
|
||||
|
||||
const categories = Object.keys(node.prompts || {}).sort((a, b) => a.localeCompare(b));
|
||||
// Keep the current category, just clear the prompt selection and content
|
||||
const currentCategory = categoryWidget.value;
|
||||
|
||||
const result = await showPromptWithCategory(
|
||||
"New Prompt",
|
||||
"Enter new prompt name:",
|
||||
"",
|
||||
categories,
|
||||
currentCategory
|
||||
);
|
||||
// Clear prompt selection (set to empty/placeholder)
|
||||
promptWidget.value = "";
|
||||
textWidget.value = "";
|
||||
|
||||
if (result && result.name && result.name.trim()) {
|
||||
const promptName = result.name.trim();
|
||||
const targetCategory = result.category;
|
||||
|
||||
// Check for existing prompt
|
||||
let existingPromptName = null;
|
||||
if (node.prompts[targetCategory]) {
|
||||
const existingNames = Object.keys(node.prompts[targetCategory]);
|
||||
existingPromptName = existingNames.find(name => name.toLowerCase() === promptName.toLowerCase());
|
||||
}
|
||||
|
||||
if (existingPromptName) {
|
||||
await showInfo(
|
||||
"Prompt Exists",
|
||||
`Prompt "${existingPromptName}" already exists in category "${targetCategory}".`
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// Set up UI for new prompt (temporary, not saved yet)
|
||||
// User must click "Save Prompt" to persist it
|
||||
categoryWidget.value = targetCategory;
|
||||
|
||||
// Add prompt name to dropdown temporarily so it can be selected
|
||||
if (!promptWidget.options.values.includes(promptName)) {
|
||||
promptWidget.options.values = [...promptWidget.options.values, promptName].sort((a, b) => a.localeCompare(b));
|
||||
}
|
||||
promptWidget.value = promptName;
|
||||
textWidget.value = "";
|
||||
|
||||
// Mark as unsaved/new prompt
|
||||
node.isNewUnsavedPrompt = true;
|
||||
node.newPromptCategory = targetCategory;
|
||||
node.newPromptName = promptName;
|
||||
|
||||
// Update previous values so cancel/revert works correctly
|
||||
node._previousCategory = targetCategory;
|
||||
node._previousPrompt = promptName;
|
||||
|
||||
node.serialize_widgets = true;
|
||||
app.graph.setDirtyCanvas(true, true);
|
||||
}
|
||||
// Update previous values for cancel/revert
|
||||
node._previousCategory = currentCategory;
|
||||
node._previousPrompt = "";
|
||||
|
||||
// Mark as new unsaved prompt state
|
||||
node.isNewUnsavedPrompt = true;
|
||||
node.newPromptCategory = currentCategory;
|
||||
node.newPromptName = null;
|
||||
|
||||
// Clear the last saved state since this is a brand new prompt
|
||||
node.lastSavedState = null;
|
||||
|
||||
node.serialize_widgets = true;
|
||||
app.graph.setDirtyCanvas(true, true);
|
||||
});
|
||||
|
||||
// More dropdown button
|
||||
@@ -591,8 +764,11 @@ function addButtonBar(node) {
|
||||
buttonContainer.appendChild(newPromptBtn);
|
||||
buttonContainer.appendChild(moreBtn);
|
||||
|
||||
// Add button bar to node
|
||||
const htmlWidget = node.addDOMWidget("buttons", "div", buttonContainer);
|
||||
// Add button bar to node with proper options to avoid clipping issues
|
||||
const htmlWidget = node.addDOMWidget("buttons", "div", buttonContainer, {
|
||||
hideOnZoom: true,
|
||||
serialize: false
|
||||
});
|
||||
htmlWidget.computeSize = function(width) {
|
||||
return [width, 36];
|
||||
};
|
||||
@@ -612,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);
|
||||
}
|
||||
@@ -621,7 +804,11 @@ function setupCategoryChangeHandler(node) {
|
||||
|
||||
const category = value;
|
||||
if (node.prompts && node.prompts[category]) {
|
||||
const promptNames = Object.keys(node.prompts[category]).sort((a, b) => a.localeCompare(b));
|
||||
const hideNSFW = app.ui.settings.getSettingValue("PromptManager.DefaultHideNSFW");
|
||||
let promptNames = Object.keys(node.prompts[category]).filter(k => k !== '__meta__').sort((a, b) => a.localeCompare(b));
|
||||
if (hideNSFW) {
|
||||
promptNames = promptNames.filter(name => !node.prompts[category][name]?.nsfw);
|
||||
}
|
||||
promptWidget.options.values = promptNames;
|
||||
|
||||
if (promptNames.length > 0) {
|
||||
@@ -648,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);
|
||||
}
|
||||
@@ -659,7 +853,11 @@ function setupCategoryChangeHandler(node) {
|
||||
|
||||
// Update prompt dropdown options in case prompts were deleted/added in another tab
|
||||
if (node.prompts && node.prompts[category]) {
|
||||
const promptNames = Object.keys(node.prompts[category]).sort((a, b) => a.localeCompare(b));
|
||||
const hideNSFW = app.ui.settings.getSettingValue("PromptManager.DefaultHideNSFW");
|
||||
let promptNames = Object.keys(node.prompts[category]).filter(k => k !== '__meta__').sort((a, b) => a.localeCompare(b));
|
||||
if (hideNSFW) {
|
||||
promptNames = promptNames.filter(name => !node.prompts[category][name]?.nsfw);
|
||||
}
|
||||
promptWidget.options.values = promptNames.length > 0 ? promptNames : [""];
|
||||
|
||||
// Check if selected prompt still exists after reload
|
||||
@@ -695,14 +893,14 @@ function setupCategoryChangeHandler(node) {
|
||||
if (node.prompts && categoryWidget && newValues && newValues.length > 0) {
|
||||
const currentCategory = categoryWidget.value;
|
||||
if (node.prompts[currentCategory]) {
|
||||
const categoryPrompts = Object.keys(node.prompts[currentCategory]);
|
||||
const categoryPrompts = Object.keys(node.prompts[currentCategory]).filter(k => k !== '__meta__');
|
||||
const hasOtherCategoryPrompts = newValues.some(val =>
|
||||
val !== "" && !categoryPrompts.includes(val)
|
||||
);
|
||||
|
||||
if (hasOtherCategoryPrompts) {
|
||||
setTimeout(() => {
|
||||
filterPromptDropdown(node);
|
||||
filterPromptDropdown(node, { preserveDanglingSelection: node._restoringFromWorkflow === true });
|
||||
}, 50);
|
||||
}
|
||||
}
|
||||
@@ -1437,8 +1635,12 @@ function updateDropdowns(node) {
|
||||
if (!categoryWidget || !promptWidget || !textWidget) return;
|
||||
|
||||
// Update category dropdown (sorted alphabetically)
|
||||
const categories = Object.keys(node.prompts).sort((a, b) => a.localeCompare(b));
|
||||
categoryWidget.options.values = categories;
|
||||
const hideNSFW = app.ui.settings.getSettingValue("PromptManager.DefaultHideNSFW");
|
||||
let categories = Object.keys(node.prompts).sort((a, b) => a.localeCompare(b));
|
||||
if (hideNSFW) {
|
||||
categories = categories.filter(cat => node.prompts[cat]?.["__meta__"]?.nsfw !== true);
|
||||
}
|
||||
categoryWidget.options.values = categories.length > 0 ? categories : ["Default"];
|
||||
|
||||
if (!node.prompts[categoryWidget.value] && categories.length > 0) {
|
||||
categoryWidget.value = categories[0];
|
||||
@@ -1447,7 +1649,10 @@ function updateDropdowns(node) {
|
||||
// Update prompt dropdown for current category (sorted alphabetically)
|
||||
const currentCategory = categoryWidget.value;
|
||||
if (node.prompts[currentCategory]) {
|
||||
const promptNames = Object.keys(node.prompts[currentCategory]).sort((a, b) => a.localeCompare(b));
|
||||
let promptNames = Object.keys(node.prompts[currentCategory]).filter(k => k !== '__meta__').sort((a, b) => a.localeCompare(b));
|
||||
if (hideNSFW) {
|
||||
promptNames = promptNames.filter(name => !node.prompts[currentCategory][name]?.nsfw);
|
||||
}
|
||||
|
||||
if (promptNames.length === 0) {
|
||||
promptNames.push("");
|
||||
|
||||
@@ -0,0 +1,227 @@
|
||||
/**
|
||||
* PromptModelLoader Extension for ComfyUI
|
||||
* Displays model type and name info on the node.
|
||||
* Dynamically shows/hides Model B outputs when two models are found.
|
||||
* Hides CLIP/VAE slots for non-checkpoint models.
|
||||
*/
|
||||
|
||||
import { app } from "../../scripts/app.js";
|
||||
|
||||
// --- Draw model info (shared between single and dual) ---
|
||||
const TYPE_COLORS = {
|
||||
"Checkpoint": "#4CAF50",
|
||||
"Diffusion": "#2196F3",
|
||||
"GGUF": "#FF9800",
|
||||
"NOT FOUND": "#F44336",
|
||||
"Unknown": "#9E9E9E"
|
||||
};
|
||||
|
||||
function drawModelRow(ctx, typeText, modelName, yOffset, label, widgetWidth) {
|
||||
const padding = 8;
|
||||
const badgeColor = TYPE_COLORS[typeText] || TYPE_COLORS["Unknown"];
|
||||
const badgeLabel = label ? `${label} ${typeText}` : typeText;
|
||||
|
||||
// Badge pill
|
||||
ctx.font = "bold 11px Arial";
|
||||
const typeWidth = ctx.measureText(badgeLabel).width + 14;
|
||||
ctx.fillStyle = badgeColor;
|
||||
ctx.beginPath();
|
||||
ctx.roundRect(padding, yOffset + 4, typeWidth, 16, 8);
|
||||
ctx.fill();
|
||||
|
||||
// Badge text
|
||||
ctx.fillStyle = "#FFFFFF";
|
||||
ctx.textAlign = "left";
|
||||
ctx.textBaseline = "middle";
|
||||
ctx.fillText(badgeLabel, padding + 7, yOffset + 12);
|
||||
|
||||
// Model name to the right of badge
|
||||
ctx.font = "12px Arial";
|
||||
ctx.fillStyle = typeText === "NOT FOUND" ? "#F44336" : "#CCCCCC";
|
||||
const nameX = padding + typeWidth + 8;
|
||||
const maxNameWidth = widgetWidth - nameX - padding;
|
||||
let displayName = modelName || "";
|
||||
while (ctx.measureText(displayName).width > maxNameWidth && displayName.length > 5) {
|
||||
displayName = displayName.slice(0, -4) + "...";
|
||||
}
|
||||
ctx.fillText(displayName, nameX, yOffset + 12);
|
||||
}
|
||||
|
||||
app.registerExtension({
|
||||
name: "PromptManager.ModelLoader",
|
||||
|
||||
async beforeRegisterNodeDef(nodeType, nodeData) {
|
||||
if (nodeData.name !== "PromptModelLoader") return;
|
||||
|
||||
// Hook into onExecuted to receive UI data from Python
|
||||
const origOnExecuted = nodeType.prototype.onExecuted;
|
||||
nodeType.prototype.onExecuted = function (message) {
|
||||
origOnExecuted?.apply(this, arguments);
|
||||
|
||||
const info = message?.model_info?.[0];
|
||||
if (!info) return;
|
||||
|
||||
this._applyModelInfo(info);
|
||||
};
|
||||
|
||||
// Central method to apply model info
|
||||
nodeType.prototype._applyModelInfo = function (info) {
|
||||
const typeA = info.model_type_a || "Unknown";
|
||||
const nameA = info.model_name_a || "";
|
||||
const hasB = !!info.has_model_b;
|
||||
const typeB = info.model_type_b || "";
|
||||
const nameB = info.model_name_b || "";
|
||||
const isCheckpointA = typeA === "Checkpoint";
|
||||
const isCheckpointB = typeB === "Checkpoint";
|
||||
|
||||
// Store for display and serialization
|
||||
this._modelInfo = info;
|
||||
|
||||
// Update title
|
||||
this.title = hasB
|
||||
? `Prompt Model Loader [${typeA} + ${typeB}]`
|
||||
: `Prompt Model Loader [${typeA}]`;
|
||||
|
||||
// Update output slots
|
||||
this._updateOutputSlots(hasB, isCheckpointA, isCheckpointB);
|
||||
|
||||
// Create/update info widget
|
||||
this._ensureInfoWidget();
|
||||
this.setDirtyCanvas(true, true);
|
||||
};
|
||||
|
||||
// Save state into the workflow JSON
|
||||
const origOnSerialize = nodeType.prototype.onSerialize;
|
||||
nodeType.prototype.onSerialize = function (o) {
|
||||
origOnSerialize?.apply(this, arguments);
|
||||
if (this._modelInfo) {
|
||||
o._modelLoaderState = this._modelInfo;
|
||||
}
|
||||
};
|
||||
|
||||
// Restore state when workflow is loaded / tab is switched back
|
||||
const origOnConfigure = nodeType.prototype.onConfigure;
|
||||
nodeType.prototype.onConfigure = function (info) {
|
||||
origOnConfigure?.apply(this, arguments);
|
||||
const state = info?._modelLoaderState;
|
||||
if (state) {
|
||||
requestAnimationFrame(() => {
|
||||
this._applyModelInfo(state);
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// Manage output slot visibility
|
||||
// Full outputs: model_a(0), clip_a(1), vae_a(2), model_b(3), clip_b(4), vae_b(5)
|
||||
nodeType.prototype._updateOutputSlots = function (hasB, isCheckpointA, isCheckpointB) {
|
||||
if (!this._originalOutputs) {
|
||||
this._originalOutputs = this.outputs.map(o => ({ ...o }));
|
||||
}
|
||||
|
||||
// Build desired output list
|
||||
const desired = [];
|
||||
|
||||
// Model A always present
|
||||
desired.push(this._originalOutputs[0]); // model_a
|
||||
|
||||
// CLIP A / VAE A only for checkpoints
|
||||
if (isCheckpointA) {
|
||||
desired.push(this._originalOutputs[1]); // clip_a
|
||||
desired.push(this._originalOutputs[2]); // vae_a
|
||||
}
|
||||
|
||||
// Model B outputs only when two models found
|
||||
if (hasB) {
|
||||
desired.push(this._originalOutputs[3]); // model_b
|
||||
if (isCheckpointB) {
|
||||
desired.push(this._originalOutputs[4]); // clip_b
|
||||
desired.push(this._originalOutputs[5]); // vae_b
|
||||
}
|
||||
}
|
||||
|
||||
// Disconnect outputs that will be removed
|
||||
for (let i = this.outputs.length - 1; i >= desired.length; i--) {
|
||||
if (this.outputs[i]?.links?.length > 0) {
|
||||
for (const linkId of [...this.outputs[i].links]) {
|
||||
this.disconnectOutput(i);
|
||||
}
|
||||
}
|
||||
this.removeOutput(i);
|
||||
}
|
||||
|
||||
// Add/update outputs to match desired
|
||||
for (let i = 0; i < desired.length; i++) {
|
||||
if (i < this.outputs.length) {
|
||||
this.outputs[i].name = desired[i].name;
|
||||
this.outputs[i].type = desired[i].type;
|
||||
} else {
|
||||
this.addOutput(desired[i].name, desired[i].type);
|
||||
}
|
||||
}
|
||||
|
||||
this.computeSize();
|
||||
};
|
||||
|
||||
// Info widget helper
|
||||
nodeType.prototype._ensureInfoWidget = function () {
|
||||
const info = this._modelInfo;
|
||||
if (!info) return;
|
||||
|
||||
const hasB = !!info.has_model_b;
|
||||
const widgetHeight = hasB ? 50 : 26;
|
||||
|
||||
let widget = this.widgets?.find(w => w.name === "_model_info_display");
|
||||
if (!widget) {
|
||||
widget = {
|
||||
name: "_model_info_display",
|
||||
type: "custom",
|
||||
y: 0,
|
||||
computeSize: () => [0, widgetHeight],
|
||||
draw: function (ctx, node, widgetWidth, y) {
|
||||
const info = node._modelInfo;
|
||||
if (!info) return;
|
||||
const hasB = !!info.has_model_b;
|
||||
if (hasB) {
|
||||
drawModelRow(ctx, info.model_type_a || "Unknown", info.model_name_a || "", y, "A:", widgetWidth);
|
||||
drawModelRow(ctx, info.model_type_b || "Unknown", info.model_name_b || "", y + 24, "B:", widgetWidth);
|
||||
} else {
|
||||
drawModelRow(ctx, info.model_type_a || "Unknown", info.model_name_a || "", y, "", widgetWidth);
|
||||
}
|
||||
}
|
||||
};
|
||||
if (!this.widgets) this.widgets = [];
|
||||
this.widgets.push(widget);
|
||||
}
|
||||
// Update height for single vs dual model
|
||||
widget.computeSize = () => [0, widgetHeight];
|
||||
this.computeSize();
|
||||
};
|
||||
|
||||
// Reset display on clear/reconnect
|
||||
const origOnConnectionsChange = nodeType.prototype.onConnectionsChange;
|
||||
nodeType.prototype.onConnectionsChange = function () {
|
||||
origOnConnectionsChange?.apply(this, arguments);
|
||||
// Reset info when input connection changes
|
||||
if (arguments[1] === 0 && arguments[0] === 1) {
|
||||
this._modelInfo = null;
|
||||
this.title = "Prompt Model Loader";
|
||||
// Restore all outputs
|
||||
if (this._originalOutputs) {
|
||||
while (this.outputs.length < this._originalOutputs.length) {
|
||||
const orig = this._originalOutputs[this.outputs.length];
|
||||
this.addOutput(orig.name, orig.type);
|
||||
}
|
||||
}
|
||||
// Remove info widget
|
||||
if (this.widgets) {
|
||||
const idx = this.widgets.findIndex(w => w.name === "_model_info_display");
|
||||
if (idx >= 0) {
|
||||
this.widgets.splice(idx, 1);
|
||||
this.computeSize();
|
||||
}
|
||||
}
|
||||
this.setDirtyCanvas(true, true);
|
||||
}
|
||||
};
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,456 @@
|
||||
/**
|
||||
* RecipeModelLoader extension.
|
||||
* Shows color-coded loaded assets (Model/VAE/CLIP) from workflow_data.
|
||||
*/
|
||||
|
||||
import { app } from "../../scripts/app.js";
|
||||
|
||||
const MODEL_CHOICES = ["model_a", "model_b"];
|
||||
const WEIGHT_DTYPE_CHOICES = ["default", "fp8_e4m3fn", "fp8_e4m3fn_fast", "fp8_e5m2"];
|
||||
|
||||
function _trimMiddle(text, maxLen) {
|
||||
const s = String(text || "");
|
||||
if (s.length <= maxLen) return s;
|
||||
const left = Math.ceil((maxLen - 3) / 2);
|
||||
const right = Math.floor((maxLen - 3) / 2);
|
||||
return `${s.slice(0, left)}...${s.slice(s.length - right)}`;
|
||||
}
|
||||
|
||||
function _shortName(name) {
|
||||
const raw = String(name || "").trim();
|
||||
if (!raw) return "";
|
||||
const normalized = raw.replace(/\\/g, "/");
|
||||
const base = normalized.split("/").pop() || normalized;
|
||||
return base.replace(/\.(safetensors|ckpt|pt|pth|bin|gguf|sft)$/i, "");
|
||||
}
|
||||
|
||||
function _shortList(names) {
|
||||
const list = Array.isArray(names) ? names : [];
|
||||
return list.map(_shortName).filter(Boolean);
|
||||
}
|
||||
|
||||
const COLORS = {
|
||||
modelCheckpoint: "#4CAF50",
|
||||
modelDiffusion: "#2196F3",
|
||||
modelGguf: "#FF9800",
|
||||
vae: "#FF6B6B",
|
||||
clip: "#C4A300",
|
||||
notFound: "#F44336",
|
||||
muted: "#B0B0B0",
|
||||
missing: "#E57373",
|
||||
};
|
||||
|
||||
function _buildRows(info) {
|
||||
const status = String(info.status || "").toLowerCase();
|
||||
if (!info || status === "idle") {
|
||||
return [
|
||||
{ label: "Model", labelColor: COLORS.modelDiffusion, value: "(awaiting execution)", valueColor: COLORS.muted },
|
||||
{ label: "Clip", labelColor: COLORS.clip, value: "(awaiting execution)", valueColor: COLORS.muted },
|
||||
{ label: "Vae", labelColor: COLORS.vae, value: "(awaiting execution)", valueColor: COLORS.muted },
|
||||
];
|
||||
}
|
||||
|
||||
const modelKind = String(info.model_kind || info.loader_type || "").toLowerCase();
|
||||
const modelColor = modelKind === "checkpoint"
|
||||
? COLORS.modelCheckpoint
|
||||
: (modelKind === "gguf" ? COLORS.modelGguf : COLORS.modelDiffusion);
|
||||
|
||||
const rows = [];
|
||||
const modelShort = _shortName(info.model_name || "");
|
||||
rows.push({
|
||||
label: "Model",
|
||||
labelColor: modelColor,
|
||||
value: modelShort || "(none)",
|
||||
valueColor: modelShort ? "#CCCCCC" : COLORS.missing,
|
||||
});
|
||||
|
||||
const loaderType = String(info.loader_type || "").toLowerCase();
|
||||
const vaeShort = _shortName(info.vae_name || "");
|
||||
const clipShort = _shortList(info.clip_names);
|
||||
|
||||
if (loaderType === "checkpoint") {
|
||||
// Keep all tags visible; show source explicitly for checkpoint-provided assets.
|
||||
const usingInternalVae = !!info.uses_checkpoint_vae;
|
||||
const usingInternalClip = !!info.uses_checkpoint_clip;
|
||||
rows.push({
|
||||
label: "Clip",
|
||||
labelColor: COLORS.clip,
|
||||
value: usingInternalClip ? "From Checkpoint" : (clipShort.length > 0 ? clipShort.join(", ") : "(none provided)"),
|
||||
valueColor: usingInternalClip ? COLORS.muted : (clipShort.length > 0 ? "#CCCCCC" : COLORS.missing),
|
||||
});
|
||||
rows.push({
|
||||
label: "Vae",
|
||||
labelColor: COLORS.vae,
|
||||
value: usingInternalVae ? "From Checkpoint" : (vaeShort || "(none provided)"),
|
||||
valueColor: usingInternalVae ? COLORS.muted : (vaeShort ? "#CCCCCC" : COLORS.missing),
|
||||
});
|
||||
} else {
|
||||
// Diffusion/UNet: always show Clip + Vae lines.
|
||||
rows.push({
|
||||
label: "Clip",
|
||||
labelColor: COLORS.clip,
|
||||
value: clipShort.length > 0 ? clipShort.join(", ") : "(none provided)",
|
||||
valueColor: clipShort.length > 0 ? "#CCCCCC" : COLORS.missing,
|
||||
});
|
||||
rows.push({
|
||||
label: "Vae",
|
||||
labelColor: COLORS.vae,
|
||||
value: vaeShort || "(none provided)",
|
||||
valueColor: vaeShort ? "#CCCCCC" : COLORS.missing,
|
||||
});
|
||||
}
|
||||
|
||||
return rows;
|
||||
}
|
||||
|
||||
function _drawPillRow(ctx, row, y, widgetWidth) {
|
||||
const left = 8;
|
||||
const badgeText = String(row.label || "");
|
||||
const value = String(row.value || "");
|
||||
const badgeW = 68;
|
||||
const valueX = left + badgeW + 10;
|
||||
const valueMax = Math.max(16, Math.floor((widgetWidth - valueX - 8) / 6));
|
||||
const displayValue = _trimMiddle(value, valueMax);
|
||||
|
||||
ctx.font = "bold 11px Arial";
|
||||
const badgeH = 16;
|
||||
const badgeY = y - Math.floor(badgeH / 2);
|
||||
|
||||
ctx.fillStyle = row.labelColor || COLORS.muted;
|
||||
ctx.beginPath();
|
||||
ctx.roundRect(left, badgeY, badgeW, badgeH, 8);
|
||||
ctx.fill();
|
||||
|
||||
ctx.fillStyle = "#FFFFFF";
|
||||
ctx.textAlign = "left";
|
||||
ctx.textBaseline = "middle";
|
||||
ctx.fillText(badgeText, left + 8, y + 0.5);
|
||||
|
||||
ctx.font = "12px Arial";
|
||||
ctx.fillStyle = row.valueColor || "#CCCCCC";
|
||||
ctx.fillText(displayValue, valueX, y + 0.5);
|
||||
}
|
||||
|
||||
function _getWidgetValue(node, name, fallback = "") {
|
||||
const w = node?.widgets?.find((x) => x.name === name);
|
||||
if (!w || w.value == null) return fallback;
|
||||
return String(w.value);
|
||||
}
|
||||
|
||||
function _widgetByNames(node, names) {
|
||||
const arr = Array.isArray(names) ? names : [names];
|
||||
return node?.widgets?.find((w) => arr.includes(w.name));
|
||||
}
|
||||
|
||||
function _sanitizeChoice(value, allowed, fallback) {
|
||||
const v = String(value ?? "");
|
||||
return allowed.includes(v) ? v : fallback;
|
||||
}
|
||||
|
||||
function _selectedModelSlot(node) {
|
||||
return _sanitizeChoice(
|
||||
_getWidgetValue(node, "model", "model_a"),
|
||||
MODEL_CHOICES,
|
||||
"model_a"
|
||||
);
|
||||
}
|
||||
|
||||
function _readWidgetState(node) {
|
||||
const modelWidget = _widgetByNames(node, ["model"]);
|
||||
const dtypeWidget = _widgetByNames(node, ["weight_dtype"]);
|
||||
return {
|
||||
model: _sanitizeChoice(modelWidget?.value, MODEL_CHOICES, "model_a"),
|
||||
weight_dtype: _sanitizeChoice(dtypeWidget?.value, WEIGHT_DTYPE_CHOICES, "default"),
|
||||
};
|
||||
}
|
||||
|
||||
function _applyWidgetState(node, state, { persist = true } = {}) {
|
||||
const modelWidget = _widgetByNames(node, ["model"]);
|
||||
const dtypeWidget = _widgetByNames(node, ["weight_dtype"]);
|
||||
const modelVal = _sanitizeChoice(state?.model, MODEL_CHOICES, "model_a");
|
||||
const dtypeVal = _sanitizeChoice(state?.weight_dtype, WEIGHT_DTYPE_CHOICES, "default");
|
||||
|
||||
if (modelWidget) modelWidget.value = modelVal;
|
||||
if (dtypeWidget) dtypeWidget.value = dtypeVal;
|
||||
|
||||
if (persist) {
|
||||
node.properties = node.properties || {};
|
||||
node.properties.wfml_model = modelVal;
|
||||
node.properties.wfml_weight_dtype = dtypeVal;
|
||||
}
|
||||
}
|
||||
|
||||
function _restoreOrNormalizeWidgetState(node) {
|
||||
node.properties = node.properties || {};
|
||||
const live = _readWidgetState(node);
|
||||
|
||||
const savedModel = _sanitizeChoice(node.properties.wfml_model, MODEL_CHOICES, "");
|
||||
const savedDtype = _sanitizeChoice(node.properties.wfml_weight_dtype, WEIGHT_DTYPE_CHOICES, "");
|
||||
|
||||
_applyWidgetState(node, {
|
||||
model: savedModel || live.model || "model_a",
|
||||
weight_dtype: savedDtype || live.weight_dtype || "default",
|
||||
}, { persist: true });
|
||||
}
|
||||
|
||||
function _isRerouteNode(n) {
|
||||
const t = String(n?.type || "").toLowerCase();
|
||||
const c = String(n?.comfyClass || "").toLowerCase();
|
||||
return t.includes("reroute") || c.includes("reroute");
|
||||
}
|
||||
|
||||
function _resolveWorkflowUpstreamLink(node) {
|
||||
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;
|
||||
|
||||
const graph = node.graph;
|
||||
const seen = new Set();
|
||||
for (let hop = 0; hop < 24; hop++) {
|
||||
if (linkId == null || seen.has(linkId)) break;
|
||||
seen.add(linkId);
|
||||
|
||||
const li = graph?.links?.[linkId];
|
||||
if (!li) break;
|
||||
const src = graph?.getNodeById?.(li.origin_id);
|
||||
if (!src) break;
|
||||
if (!_isRerouteNode(src)) {
|
||||
return { sourceNode: src, sourceSlot: li.origin_slot };
|
||||
}
|
||||
const in0 = src.inputs?.[0];
|
||||
linkId = in0?.link ?? null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function _tryParseWorkflowData(value) {
|
||||
if (!value) return null;
|
||||
if (typeof value === "object") return value;
|
||||
if (typeof value === "string") {
|
||||
try {
|
||||
const p = JSON.parse(value);
|
||||
if (p && typeof p === "object") return p;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function _clipListFromWf(wf) {
|
||||
const c = wf?.clip;
|
||||
if (Array.isArray(c)) return c.filter(Boolean);
|
||||
if (typeof c === "string" && c) return [c];
|
||||
if (c && Array.isArray(c.names)) return c.names.filter(Boolean);
|
||||
return [];
|
||||
}
|
||||
|
||||
function _vaeFromWf(wf) {
|
||||
const v = wf?.vae;
|
||||
if (typeof v === "string") return v;
|
||||
if (v && typeof v === "object" && typeof v.name === "string") return v.name;
|
||||
return "";
|
||||
}
|
||||
|
||||
function _inferInfoFromWorkflowData(node, wf) {
|
||||
const modelKey = _selectedModelSlot(node);
|
||||
const modelName = typeof wf?.[modelKey] === "string" ? wf[modelKey] : "";
|
||||
if (!modelName) return null;
|
||||
|
||||
const loaderType = String(wf?.loader_type || "").toLowerCase();
|
||||
const selectedLower = modelName.toLowerCase();
|
||||
const modelKind = loaderType === "checkpoint"
|
||||
? "checkpoint"
|
||||
: (selectedLower.endsWith(".gguf") ? "gguf" : "diffusion");
|
||||
|
||||
const vaeName = _vaeFromWf(wf);
|
||||
const clipNames = _clipListFromWf(wf);
|
||||
return {
|
||||
model: modelKey,
|
||||
model_name: _shortName(modelName),
|
||||
loader_type: loaderType,
|
||||
model_kind: modelKind,
|
||||
vae_name: vaeName,
|
||||
clip_names: clipNames,
|
||||
status: "ok",
|
||||
error_message: "",
|
||||
missing_name: "",
|
||||
uses_checkpoint_vae: (loaderType === "checkpoint" && !vaeName),
|
||||
uses_checkpoint_clip: (loaderType === "checkpoint" && clipNames.length === 0),
|
||||
};
|
||||
}
|
||||
|
||||
function _refreshInfoFromUpstream(node) {
|
||||
const resolved = _resolveWorkflowUpstreamLink(node);
|
||||
if (!resolved) return false;
|
||||
const { sourceNode, sourceSlot } = resolved;
|
||||
|
||||
const out = sourceNode?.outputs?.[sourceSlot];
|
||||
const wfFromOutput = _tryParseWorkflowData(out?._data) || _tryParseWorkflowData(out?.value);
|
||||
const wfFromBuilderCache = _tryParseWorkflowData(sourceNode?.properties?.we_extracted_cache);
|
||||
const wf = wfFromOutput || wfFromBuilderCache;
|
||||
if (!wf) return false;
|
||||
|
||||
const inferred = _inferInfoFromWorkflowData(node, wf);
|
||||
if (!inferred) return false;
|
||||
node._applyRecipeModelLoaderInfo(inferred);
|
||||
return true;
|
||||
}
|
||||
|
||||
function _defaultInfoFromWidgets(node) {
|
||||
const selected = _selectedModelSlot(node);
|
||||
return {
|
||||
model: selected,
|
||||
model_name: "",
|
||||
loader_type: "",
|
||||
model_kind: "",
|
||||
vae_name: "",
|
||||
clip_names: [],
|
||||
status: "idle",
|
||||
error_message: "",
|
||||
missing_name: "",
|
||||
uses_checkpoint_vae: false,
|
||||
uses_checkpoint_clip: false,
|
||||
};
|
||||
}
|
||||
|
||||
app.registerExtension({
|
||||
name: "PromptManager.RecipeModelLoader",
|
||||
|
||||
async beforeRegisterNodeDef(nodeType, nodeData) {
|
||||
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._applyRecipeModelLoaderInfo(info);
|
||||
};
|
||||
|
||||
nodeType.prototype._applyRecipeModelLoaderInfo = function (info) {
|
||||
const selected = _sanitizeChoice(info.model, MODEL_CHOICES, "model_a");
|
||||
this._recipeModelLoaderInfo = {
|
||||
model: selected,
|
||||
model_name: info.model_name || "",
|
||||
loader_type: info.loader_type || "",
|
||||
model_kind: info.model_kind || "",
|
||||
vae_name: info.vae_name || "",
|
||||
clip_names: Array.isArray(info.clip_names) ? info.clip_names : [],
|
||||
status: info.status || "ok",
|
||||
error_message: info.error_message || "",
|
||||
missing_name: info.missing_name || "",
|
||||
uses_checkpoint_vae: !!info.uses_checkpoint_vae,
|
||||
uses_checkpoint_clip: !!info.uses_checkpoint_clip,
|
||||
};
|
||||
this._ensureRecipeModelInfoWidget();
|
||||
this.setDirtyCanvas(true, true);
|
||||
};
|
||||
|
||||
const origOnNodeCreated = nodeType.prototype.onNodeCreated;
|
||||
nodeType.prototype.onNodeCreated = function () {
|
||||
const r = origOnNodeCreated?.apply(this, arguments);
|
||||
_restoreOrNormalizeWidgetState(this);
|
||||
if (!this._recipeModelLoaderInfo) {
|
||||
this._recipeModelLoaderInfo = _defaultInfoFromWidgets(this);
|
||||
}
|
||||
this._ensureRecipeModelInfoWidget();
|
||||
_refreshInfoFromUpstream(this);
|
||||
this.setDirtyCanvas(true, true);
|
||||
return r;
|
||||
};
|
||||
|
||||
const origOnConnectionsChange = nodeType.prototype.onConnectionsChange;
|
||||
nodeType.prototype.onConnectionsChange = function () {
|
||||
const r = origOnConnectionsChange?.apply(this, arguments);
|
||||
_refreshInfoFromUpstream(this);
|
||||
this.setDirtyCanvas(true, true);
|
||||
return r;
|
||||
};
|
||||
|
||||
const origOnWidgetChanged = nodeType.prototype.onWidgetChanged;
|
||||
nodeType.prototype.onWidgetChanged = function (name, value, oldValue, w) {
|
||||
const r = origOnWidgetChanged?.apply(this, arguments);
|
||||
if (name === "model" || name === "weight_dtype") {
|
||||
_restoreOrNormalizeWidgetState(this);
|
||||
_refreshInfoFromUpstream(this);
|
||||
this.setDirtyCanvas(true, true);
|
||||
}
|
||||
return r;
|
||||
};
|
||||
|
||||
const origOnSerialize = nodeType.prototype.onSerialize;
|
||||
nodeType.prototype.onSerialize = function (o) {
|
||||
origOnSerialize?.apply(this, arguments);
|
||||
const ws = _readWidgetState(this);
|
||||
this.properties = this.properties || {};
|
||||
this.properties.wfml_model = ws.model;
|
||||
this.properties.wfml_weight_dtype = ws.weight_dtype;
|
||||
if (this._recipeModelLoaderInfo) {
|
||||
o._recipeModelLoaderInfo = this._recipeModelLoaderInfo;
|
||||
o._workflowModelLoaderInfo = this._recipeModelLoaderInfo;
|
||||
}
|
||||
if (o) {
|
||||
o.properties = o.properties || {};
|
||||
o.properties.wfml_model = ws.model;
|
||||
o.properties.wfml_weight_dtype = ws.weight_dtype;
|
||||
}
|
||||
};
|
||||
|
||||
const origOnConfigure = nodeType.prototype.onConfigure;
|
||||
nodeType.prototype.onConfigure = function (info) {
|
||||
origOnConfigure?.apply(this, arguments);
|
||||
_restoreOrNormalizeWidgetState(this);
|
||||
const state = info?._recipeModelLoaderInfo || info?._workflowModelLoaderInfo;
|
||||
if (state) {
|
||||
requestAnimationFrame(() => {
|
||||
this._applyRecipeModelLoaderInfo(state);
|
||||
_refreshInfoFromUpstream(this);
|
||||
});
|
||||
} else {
|
||||
requestAnimationFrame(() => {
|
||||
this._recipeModelLoaderInfo = _defaultInfoFromWidgets(this);
|
||||
this._ensureRecipeModelInfoWidget();
|
||||
_refreshInfoFromUpstream(this);
|
||||
this.setDirtyCanvas(true, true);
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
nodeType.prototype._ensureRecipeModelInfoWidget = function () {
|
||||
let widget = this.widgets?.find(w => w.name === "_recipe_model_loader_info");
|
||||
if (!widget) {
|
||||
widget = {
|
||||
name: "_recipe_model_loader_info",
|
||||
type: "custom",
|
||||
y: 0,
|
||||
computeSize: () => {
|
||||
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._recipeModelLoaderInfo;
|
||||
if (!info) return;
|
||||
|
||||
const rows = _buildRows(info);
|
||||
|
||||
ctx.save();
|
||||
ctx.textAlign = "left";
|
||||
ctx.textBaseline = "middle";
|
||||
for (let i = 0; i < rows.length; i++) {
|
||||
const rowY = y + 12 + (i * 22);
|
||||
const row = rows[i];
|
||||
_drawPillRow(ctx, row, rowY, widgetWidth);
|
||||
}
|
||||
ctx.restore();
|
||||
},
|
||||
};
|
||||
if (!this.widgets) this.widgets = [];
|
||||
this.widgets.push(widget);
|
||||
}
|
||||
this.computeSize();
|
||||
};
|
||||
},
|
||||
});
|
||||
@@ -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);
|
||||
});
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,15 @@
|
||||
/**
|
||||
* Recipe Renderer — Set initial node size to match Recipe Builder width.
|
||||
*/
|
||||
import { app } from "../../scripts/app.js";
|
||||
|
||||
app.registerExtension({
|
||||
name: "prompt-manager.recipe-renderer",
|
||||
async nodeCreated(node) {
|
||||
if (node.comfyClass !== "RecipeRenderer") return;
|
||||
requestAnimationFrame(() => {
|
||||
node.setSize([320, node.size[1]]);
|
||||
app.graph.setDirtyCanvas(true, true);
|
||||
});
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,43 @@
|
||||
// Shared UI palette used by Prompt Manager modals.
|
||||
// Keep this aligned with Workflow Builder's neutral + blue accent styling.
|
||||
export const PM_UI_PALETTE = {
|
||||
// Backdrop behind modal dialogs
|
||||
overlay: "hsl(0 0% 0% / 0.8)",
|
||||
// Main modal surface
|
||||
panel: "hsl(216 11% 15%)",
|
||||
// Outer border of modal containers
|
||||
panelBorder: "hsl(216 20% 65% / 0.24)",
|
||||
// Dividers between modal sections (header/body/footer)
|
||||
sectionBorder: "hsl(216 20% 65% / 0.20)",
|
||||
|
||||
// Text input/select control surface
|
||||
inputBg: "hsl(220 15% 10%)",
|
||||
// Input/select/button neutral stroke
|
||||
inputBorder: "hsl(218 10% 41%)",
|
||||
// Neutral button/chip background
|
||||
buttonBg: "hsl(219 16% 18%)",
|
||||
|
||||
// Primary foreground text
|
||||
textPrimary: "hsl(0 0% 87%)",
|
||||
// Titles and important labels
|
||||
textHeading: "hsl(220 13% 85%)",
|
||||
// Secondary text
|
||||
textMuted: "hsl(0 0% 67%)",
|
||||
// Hints and helper text
|
||||
textHint: "hsl(216 15% 65%)",
|
||||
|
||||
// Card/tile background (thumbnails, prompt cards)
|
||||
cardBg: "hsl(219 16% 18%)",
|
||||
// Card default border
|
||||
cardBorder: "hsl(217 12% 22%)",
|
||||
|
||||
// Exact Builder accent family (from workflow_builder.js)
|
||||
// Primary blue accent (focus/selected)
|
||||
accent: "hsl(208 73% 57% / 0.9)",
|
||||
// Slightly dimmed accent (hover/secondary accent)
|
||||
accentDim: "hsl(208 73% 57% / 0.7)",
|
||||
// Soft accent fill for selected backgrounds
|
||||
accentSoft: "hsl(208 73% 57% / 0.16)",
|
||||
// Accent border used on selected elements
|
||||
accentBorder: "hsl(208 73% 57% / 0.65)",
|
||||
};
|
||||
@@ -0,0 +1,116 @@
|
||||
"""
|
||||
ComfyUI Prompt Apply LoRA - Apply a LORA_STACK to model
|
||||
"""
|
||||
import ast
|
||||
import json
|
||||
import os
|
||||
|
||||
import comfy.sd
|
||||
import comfy.utils
|
||||
|
||||
from ..py.lora_utils import resolve_lora_path
|
||||
|
||||
|
||||
def parse_lora_stack_text(text):
|
||||
"""Parse a lora stack from a text string.
|
||||
|
||||
Accepts formats:
|
||||
JSON: [["lora_name", 1.0, 1.0], ...]
|
||||
Python: [("lora_name", 1.0, 1.0), ...]
|
||||
Plain: One path/name per line (strength defaults to 1.0)
|
||||
Returns a list of (name, model_strength, clip_strength) tuples.
|
||||
"""
|
||||
text = text.strip()
|
||||
if not text:
|
||||
return []
|
||||
|
||||
# Try JSON first
|
||||
try:
|
||||
data = json.loads(text)
|
||||
return [(str(item[0]), float(item[1]), float(item[2])) for item in data]
|
||||
except (json.JSONDecodeError, ValueError, IndexError, TypeError):
|
||||
pass
|
||||
|
||||
# Fall back to Python literal (handles tuples)
|
||||
try:
|
||||
data = ast.literal_eval(text)
|
||||
return [(str(item[0]), float(item[1]), float(item[2])) for item in data]
|
||||
except (ValueError, SyntaxError, IndexError, TypeError):
|
||||
pass
|
||||
|
||||
# Fall back to newline-separated paths/names (strength defaults to 1.0)
|
||||
lines = [line.strip() for line in text.splitlines() if line.strip()]
|
||||
if lines:
|
||||
return [(line, 1.0, 1.0) for line in lines]
|
||||
|
||||
return []
|
||||
|
||||
|
||||
class ApplyLoraPlusPlus:
|
||||
"""
|
||||
Apply a LoRA stack to a model.
|
||||
Takes a LORA_STACK (list of tuples) and applies each LoRA sequentially.
|
||||
Uses fuzzy matching to find LoRAs on disk — LoRAs not found are skipped.
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {
|
||||
"required": {
|
||||
"model": ("MODEL",),
|
||||
},
|
||||
"optional": {
|
||||
"clip_optional": ("CLIP",),
|
||||
"lora_stack": ("LORA_STACK",),
|
||||
"lora_stack_text": ("STRING", {"default": "", "multiline": True}),
|
||||
},
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("MODEL", "CLIP")
|
||||
RETURN_NAMES = ("model", "clip")
|
||||
FUNCTION = "apply_stack"
|
||||
CATEGORY = "Prompt Manager"
|
||||
DESCRIPTION = "Apply a LoRA stack to a model. You can connect LORA_STACK or input LoRA path as text\none LoRA per line (Full paths can reference any location on disk.)"
|
||||
|
||||
def apply_stack(self, model, clip_optional=None, lora_stack=None, lora_stack_text=""):
|
||||
clip = clip_optional
|
||||
|
||||
# If no stack input and no text, return early
|
||||
if not lora_stack and (not lora_stack_text or not lora_stack_text.strip()):
|
||||
return (model, clip)
|
||||
|
||||
# Merge both sources
|
||||
stack = list(lora_stack) if lora_stack else []
|
||||
if lora_stack_text:
|
||||
stack.extend(parse_lora_stack_text(lora_stack_text))
|
||||
|
||||
if not stack:
|
||||
return (model, clip)
|
||||
|
||||
model_out = model
|
||||
clip_out = clip
|
||||
|
||||
for lora_name, model_strength, clip_strength in stack:
|
||||
# Skip if no strength
|
||||
if model_strength == 0 and clip_strength == 0:
|
||||
continue
|
||||
|
||||
# If it looks like a full path and exists on disk, use it directly
|
||||
if os.path.isabs(lora_name) and os.path.isfile(lora_name):
|
||||
lora_path = lora_name
|
||||
else:
|
||||
# Resolve LoRA using fuzzy matching (handles renamed LoRAs, WAN tokens, etc.)
|
||||
lora_path, found = resolve_lora_path(lora_name)
|
||||
if not found:
|
||||
print(f"[PromptApplyLora] Warning: LoRA not found, skipping: {lora_name}")
|
||||
continue
|
||||
|
||||
# Load the LoRA
|
||||
lora = comfy.utils.load_torch_file(lora_path, safe_load=True)
|
||||
|
||||
# Apply to model + clip
|
||||
model_out, clip_out = comfy.sd.load_lora_for_models(
|
||||
model_out, clip_out, lora, model_strength, clip_strength
|
||||
)
|
||||
|
||||
return (model_out, clip_out)
|
||||
@@ -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),)
|
||||
@@ -3,6 +3,7 @@ import subprocess
|
||||
import time
|
||||
import os
|
||||
import sys
|
||||
import gc
|
||||
import atexit
|
||||
import signal
|
||||
import psutil
|
||||
@@ -10,17 +11,21 @@ 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
|
||||
from .model_manager import get_local_models, get_model_path, is_model_local, download_model, get_mmproj_path
|
||||
from ..py.model_manager import get_local_models, get_model_path, is_model_local, download_model, get_mmproj_path, has_vision_support
|
||||
|
||||
# Ollama integration
|
||||
from ..py.ollama_wrapper import generate_chat as ollama_generate_chat, unload_model as ollama_unload_model
|
||||
|
||||
# ComfyUI interrupt helper
|
||||
import comfy.model_management
|
||||
|
||||
# Try to import preferences cache, fallback to empty dict if not available
|
||||
try:
|
||||
from .model_manager import _preferences_cache
|
||||
from ..py.model_manager import _preferences_cache
|
||||
except ImportError:
|
||||
_preferences_cache = {}
|
||||
|
||||
@@ -174,7 +179,7 @@ signal.signal(signal.SIGINT, _signal_handler)
|
||||
signal.signal(signal.SIGTERM, _signal_handler)
|
||||
|
||||
# --- Prompt Loading Helpers ---
|
||||
_PROMPTS_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "prompts")
|
||||
_PROMPTS_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "prompts")
|
||||
_prompts_cache = {}
|
||||
|
||||
def load_prompt(filename):
|
||||
@@ -229,7 +234,7 @@ class PromptGenerator:
|
||||
|
||||
@staticmethod
|
||||
def get_image_system_prompt():
|
||||
"""Load the system prompt for image description (used with Qwen3VL)."""
|
||||
"""Load the system prompt for image description (used with vision models)."""
|
||||
return load_prompt("image_default_system_prompt.txt")
|
||||
|
||||
@staticmethod
|
||||
@@ -248,63 +253,54 @@ class PromptGenerator:
|
||||
return load_prompt("json_system_prompt.txt")
|
||||
|
||||
@staticmethod
|
||||
def find_qwen3vl_model(available_models, thinking):
|
||||
"""Find the preferred or smallest available Qwen3VL model
|
||||
def find_vision_model(available_models):
|
||||
"""Find the preferred or first available vision-capable model.
|
||||
|
||||
First checks user preferences, then falls back to smallest model (4B preferred over 8B)
|
||||
A model is considered vision-capable if it has an mmproj file
|
||||
(either in the registry or on disk).
|
||||
"""
|
||||
|
||||
qwen3vl_models = [m for m in available_models if 'qwen3vl' in m.lower()]
|
||||
if not qwen3vl_models:
|
||||
vision_models = [m for m in available_models if has_vision_support(m)]
|
||||
if not vision_models:
|
||||
return None
|
||||
|
||||
# Check user preference first
|
||||
preferred = _preferences_cache.get("preferred_vision_model", "")
|
||||
if preferred and preferred in qwen3vl_models and is_model_local(preferred):
|
||||
if thinking:
|
||||
if 'thinking' in preferred.lower():
|
||||
return preferred
|
||||
else:
|
||||
if 'thinking' not in preferred.lower():
|
||||
return preferred
|
||||
if preferred and preferred in vision_models and is_model_local(preferred):
|
||||
return preferred
|
||||
|
||||
# Let's filter models based on thinking mode
|
||||
if thinking:
|
||||
filtered_models = [model for model in qwen3vl_models if 'thinking' in model.lower()]
|
||||
else:
|
||||
filtered_models = [model for model in qwen3vl_models if 'thinking' not in model.lower()]
|
||||
if filtered_models:
|
||||
qwen3vl_models = filtered_models
|
||||
|
||||
# Fall back to smaller model (prefer 4B over 8B)
|
||||
for model in qwen3vl_models:
|
||||
if '4b' in model.lower():
|
||||
# Fall back to smallest model
|
||||
for model in vision_models:
|
||||
if '4b' in model.lower() or '3b' in model.lower():
|
||||
return model
|
||||
|
||||
return qwen3vl_models[0]
|
||||
return vision_models[0]
|
||||
|
||||
@staticmethod
|
||||
def find_non_vl_model(available_models):
|
||||
"""Find the preferred or smallest available non-vision model by file size
|
||||
def find_text_model(available_models):
|
||||
"""Find the preferred or smallest available model for text enhancement.
|
||||
|
||||
First checks user preferences, then falls back to smallest model by file size
|
||||
Any model can be used for text (vision models work too),
|
||||
but we prefer non-vision models when available to save resources.
|
||||
Falls back to vision-capable models if that's all there is.
|
||||
"""
|
||||
# Prefer models without mmproj (lighter weight)
|
||||
text_only = [m for m in available_models if not has_vision_support(m)]
|
||||
|
||||
non_vl_models = [m for m in available_models if 'qwen3vl' not in m.lower()]
|
||||
if not non_vl_models:
|
||||
candidates = text_only if text_only else available_models
|
||||
if not candidates:
|
||||
return None
|
||||
|
||||
# Check user preference first
|
||||
preferred = _preferences_cache.get("preferred_base_model", "")
|
||||
if preferred and preferred in non_vl_models and is_model_local(preferred):
|
||||
if preferred and preferred in candidates and is_model_local(preferred):
|
||||
return preferred
|
||||
|
||||
# Fall back to smaller model (prefer 4B over 8B)
|
||||
for model in non_vl_models:
|
||||
if '4b' in model.lower():
|
||||
# Fall back to smallest model
|
||||
for model in candidates:
|
||||
if '4b' in model.lower() or '3b' in model.lower():
|
||||
return model
|
||||
|
||||
return non_vl_models[0]
|
||||
return candidates[0]
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
@@ -314,7 +310,8 @@ class PromptGenerator:
|
||||
"default": 0,
|
||||
"min": 0,
|
||||
"max": 0xffffffffffffffff,
|
||||
"tooltip": "Seed for reproducible generation."
|
||||
"tooltip": "Seed for reproducible generation.",
|
||||
"control_after_generate": True
|
||||
}),
|
||||
},
|
||||
"optional": {
|
||||
@@ -340,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", {
|
||||
@@ -350,6 +347,7 @@ class PromptGenerator:
|
||||
}
|
||||
|
||||
CATEGORY = "Prompt Manager"
|
||||
DESCRIPTION = "Generate or enhance prompts using a local LLM via llama.cpp or Ollama."
|
||||
RETURN_TYPES = ("STRING", "STRING")
|
||||
RETURN_NAMES = ("output", "thoughts")
|
||||
FUNCTION = "convert_prompt"
|
||||
@@ -368,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:
|
||||
@@ -441,17 +439,16 @@ 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 VL models
|
||||
# Add vision flags for models with mmproj
|
||||
if use_vision_model:
|
||||
mmproj_path = get_mmproj_path(model_name)
|
||||
if mmproj_path:
|
||||
# Only print if mmproj is used
|
||||
print_pg(f"Vision model: using mmproj: {os.path.basename(mmproj_path)}")
|
||||
cmd_args.extend(["--mmproj", mmproj_path])
|
||||
else:
|
||||
error_msg = f"Error: Vision model requires mmproj file for '{model_name}' but it was not found. \nPlease ensure it exists, or use the Generator Options node to download the Qwen3VL model and its mmproj file."
|
||||
error_msg = f"Error: Vision mode requires an mmproj file for '{model_name}' but none was found.\nPlease ensure an mmproj file exists, or use the Generator Options node to download a vision-capable model."
|
||||
print_pg(error_msg, RED)
|
||||
return (False, error_msg)
|
||||
|
||||
@@ -502,17 +499,33 @@ class PromptGenerator:
|
||||
_current_context_size = context_size
|
||||
|
||||
# Wait for server to be ready
|
||||
for i in range(30): # Wait up to 30 seconds
|
||||
for i in range(60): # Wait up to 60 seconds
|
||||
time.sleep(1)
|
||||
try:
|
||||
comfy.model_management.throw_exception_if_processing_interrupted()
|
||||
except Exception:
|
||||
# Propagate interrupt up to caller
|
||||
raise
|
||||
# Check if process has crashed
|
||||
if _server_process.poll() is not None:
|
||||
stderr_output = ""
|
||||
try:
|
||||
stderr_output = _server_process.stderr.read().decode("utf-8", errors="replace").strip()
|
||||
except Exception:
|
||||
pass
|
||||
error_msg = f"Error: llama-server exited with code {_server_process.returncode}"
|
||||
if stderr_output:
|
||||
# Show last 5 lines of stderr for context
|
||||
last_lines = "\n".join(stderr_output.splitlines()[-5:])
|
||||
error_msg += f"\n{last_lines}"
|
||||
print_pg(error_msg, RED)
|
||||
_server_process = None
|
||||
_current_model = None
|
||||
return (False, error_msg)
|
||||
if PromptGenerator.is_server_alive():
|
||||
return (True, None)
|
||||
|
||||
error_msg = "Error: Server did not start in time"
|
||||
error_msg = "Error: Server did not start in time (60s)"
|
||||
print_pg(error_msg, RED)
|
||||
PromptGenerator.stop_server()
|
||||
return (False, error_msg)
|
||||
@@ -623,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
|
||||
@@ -649,11 +662,57 @@ 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:
|
||||
"""Convert prompt using llama.cpp server, with caching for repeated requests."""
|
||||
@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"
|
||||
)
|
||||
|
||||
# Extract console option from connected options node
|
||||
show_everything_in_console = False # Default to False when options not connected
|
||||
@@ -674,61 +733,73 @@ class PromptGenerator:
|
||||
if (mode == "Enhance Prompt (Image)" or mode == "Enhance Prompt (Video)") and not prompt.strip():
|
||||
error_msg = "Did you perhaps forget to enter a User Prompt?"
|
||||
print_pg(error_msg, RED)
|
||||
return (error_msg,)
|
||||
raise RuntimeError(error_msg)
|
||||
|
||||
# Always determine a valid model filename before running server
|
||||
model_to_use = None
|
||||
available_models = get_local_models()
|
||||
|
||||
if use_vision_model:
|
||||
# Check if options specifies a Qwen3VL model
|
||||
if options and "model" in options and "vl" in options["model"].lower() and is_model_local(options["model"]):
|
||||
if use_ollama:
|
||||
# ── Ollama model selection ──
|
||||
# Priority: Options node > auto-discover from Ollama
|
||||
if options and "model" in options:
|
||||
model_to_use = options["model"]
|
||||
elif options and "model" in options and is_model_local(options["model"]):
|
||||
# Non-VL model selected but in vision mode
|
||||
print_pg(f"Warning: Non-vision model '{options['model']}' selected but '{mode}' mode is active.\nIgnoring model selection and using a Vision Model instead.")
|
||||
model_to_use = self.find_qwen3vl_model(available_models, enable_thinking)
|
||||
if model_to_use is None:
|
||||
error_msg = f"Error: '{mode}' mode requires a Qwen3VL model. Please connect the Options node and select a Qwen3VL model (Qwen3VL-4B or Qwen3VL-8B) to use vision capabilities."
|
||||
print_pg(error_msg, RED)
|
||||
return (error_msg,)
|
||||
else:
|
||||
# Try to find a Qwen3VL model automatically
|
||||
model_to_use = self.find_qwen3vl_model(available_models, enable_thinking)
|
||||
if model_to_use is None:
|
||||
error_msg = f"Error: '{mode}' mode requires a Qwen3VL model. Please connect the Options node and select a Qwen3VL model (Qwen3VL-4B or Qwen3VL-8B) to use vision capabilities."
|
||||
print_pg(error_msg, RED)
|
||||
return (error_msg,)
|
||||
else:
|
||||
# Enhance Prompt mode - use regular model selection logic (exclude Qwen3VL models)
|
||||
if options and "model" in options and is_model_local(options["model"]):
|
||||
# If user explicitly selected a Qwen3VL model but in Enhance mode, use first non-VL model instead
|
||||
if "qwen3vl" in options["model"].lower():
|
||||
model_to_use = self.find_non_vl_model(available_models)
|
||||
if model_to_use:
|
||||
print_pg(f"Warning: Qwen3VL model '{options['model']}' selected but 'Enhance Prompt' mode is active. Ignoring model selection and using {model_to_use} instead.")
|
||||
else:
|
||||
error_msg = "Error: Only Qwen3VL models available but 'Enhance Prompt' mode is active. Please add a .gguf model or use Generator Options to add a non-vision model."
|
||||
print_pg(error_msg, RED)
|
||||
return (error_msg,)
|
||||
# Auto-discover available models from Ollama
|
||||
from ..py.ollama_wrapper import discover_ollama_models
|
||||
discovered, status = discover_ollama_models(_preferences_cache)
|
||||
if discovered:
|
||||
model_to_use = discovered[0]
|
||||
print_pg(f"Auto-selected Ollama model: {model_to_use}")
|
||||
else:
|
||||
model_to_use = options["model"]
|
||||
else:
|
||||
if not available_models:
|
||||
error_msg = "Error: No models found in models/ folder. Please add a .gguf model or use Generator Options node to download one."
|
||||
error_msg = (f"Error: No Ollama model available. {status}\n"
|
||||
"Pull a model first (e.g. `ollama pull llama3.1`).")
|
||||
print_pg(error_msg, RED)
|
||||
return (error_msg,)
|
||||
# Find smallest non-VL model
|
||||
model_to_use = self.find_non_vl_model(available_models)
|
||||
if not model_to_use:
|
||||
error_msg = "Error: Only Qwen3VL models available but 'Enhance Prompt' mode is active. Please add a non-vision model or switch to 'Describe Image' mode."
|
||||
print_pg(error_msg, RED)
|
||||
return (error_msg,)
|
||||
raise RuntimeError(error_msg)
|
||||
|
||||
# let's make sure thinking is disabled for non-thinking versions of Qwen3VL
|
||||
if enable_thinking and "qwen3vl" in model_to_use.lower() and "thinking" not in model_to_use.lower():
|
||||
print_pg("Warning: Thinking disabled - model does not support it.")
|
||||
enable_thinking = False
|
||||
print_pg("Backend : Ollama")
|
||||
|
||||
else:
|
||||
# ── llama.cpp model selection ──
|
||||
print_pg("Backend : llama.cpp")
|
||||
available_models = get_local_models()
|
||||
|
||||
if use_vision_model:
|
||||
# Check if the selected model supports vision (has mmproj)
|
||||
if options and "model" in options and has_vision_support(options["model"]) and is_model_local(options["model"]):
|
||||
model_to_use = options["model"]
|
||||
elif options and "model" in options and is_model_local(options["model"]):
|
||||
# Selected model doesn't support vision
|
||||
print_pg(f"Warning: Model '{options['model']}' has no mmproj (no vision support) but '{mode}' mode is active.\nIgnoring model selection and searching for a vision-capable model.")
|
||||
model_to_use = self.find_vision_model(available_models)
|
||||
if model_to_use is None:
|
||||
error_msg = f"Error: '{mode}' mode requires a vision model (one with an mmproj file). Please download a vision-capable model via the Options node."
|
||||
print_pg(error_msg, RED)
|
||||
raise RuntimeError(error_msg)
|
||||
else:
|
||||
# Try to find a vision model automatically
|
||||
model_to_use = self.find_vision_model(available_models)
|
||||
if model_to_use is None:
|
||||
error_msg = f"Error: '{mode}' mode requires a vision model (one with an mmproj file). Please download a vision-capable model via the Options node."
|
||||
print_pg(error_msg, RED)
|
||||
raise RuntimeError(error_msg)
|
||||
else:
|
||||
# Enhance Prompt mode - any model works, prefer text-only for efficiency
|
||||
if options and "model" in options and is_model_local(options["model"]):
|
||||
model_to_use = options["model"]
|
||||
else:
|
||||
if not available_models:
|
||||
error_msg = "Error: No models found in models/ folder. Please add a .gguf model or use Generator Options node to download one."
|
||||
print_pg(error_msg, RED)
|
||||
raise RuntimeError(error_msg)
|
||||
model_to_use = self.find_text_model(available_models)
|
||||
if not model_to_use:
|
||||
error_msg = "Error: No suitable model found. Please add a .gguf model or use the Generator Options node to download one."
|
||||
print_pg(error_msg, RED)
|
||||
raise RuntimeError(error_msg)
|
||||
|
||||
# Thinking mode is only meaningful if the model explicitly supports it
|
||||
# (no longer tied to Qwen3VL naming — generic check)
|
||||
# Users can always enable thinking; the model will simply ignore it if unsupported.
|
||||
|
||||
print_pg(f"Vision mode : {'ON' if use_vision_model else 'OFF'}")
|
||||
print_pg(f"Thinking mode : {'ON' if enable_thinking else 'OFF'}")
|
||||
@@ -750,18 +821,19 @@ class PromptGenerator:
|
||||
|
||||
if not images:
|
||||
error_msg = f"Error: '{mode}' mode requires at least one image to be connected. Please connect an image or switch to 'Enhance Prompt' mode."
|
||||
print_pg(error_msg)
|
||||
return (error_msg,)
|
||||
print_pg(error_msg, RED)
|
||||
raise RuntimeError(error_msg)
|
||||
|
||||
# If the current model is not the one we want, or server is not running, restart
|
||||
# Also restart if context_size has changed
|
||||
context_size = options.get("context_size", 4096) if options else 4096
|
||||
if _current_model != model_to_use or _current_context_size != context_size or not self.is_server_alive():
|
||||
self.stop_server()
|
||||
# Get context_size from options or use default
|
||||
success, error_msg = self.start_server(model_to_use, context_size, use_vision_model)
|
||||
if not success:
|
||||
return (error_msg,)
|
||||
# Also restart if context_size has changed (llama.cpp only)
|
||||
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()
|
||||
# Get context_size from options or use default
|
||||
success, error_msg = self.start_server(model_to_use, context_size, use_vision_model)
|
||||
if not success:
|
||||
raise RuntimeError(error_msg)
|
||||
|
||||
# Build the endpoint URL
|
||||
full_url = f"http://localhost:{self.SERVER_PORT}/v1/chat/completions"
|
||||
@@ -795,9 +867,9 @@ class PromptGenerator:
|
||||
else:
|
||||
user_content = prompt
|
||||
|
||||
# === TOKENIZATION (only for non-cached requests) ===
|
||||
# === TOKENIZATION (only for non-cached requests, llama.cpp only) ===
|
||||
cached_token_counts = None
|
||||
if show_everything_in_console:
|
||||
if show_everything_in_console and not use_ollama:
|
||||
cached_token_counts = self._get_token_counts_parallel(system_prompt, user_content)
|
||||
|
||||
# If in vision mode, encode images for the request
|
||||
@@ -830,7 +902,7 @@ class PromptGenerator:
|
||||
img_base64 = base64.b64encode(buffered.getvalue()).decode('utf-8')
|
||||
image_contents.append({"type": "image_url", "image_url": {"url": f"data:image/png;base64,{img_base64}"}})
|
||||
|
||||
# Qwen3VL format for vision messages: all images, then text
|
||||
# Vision format: all images first, then text
|
||||
user_message = {
|
||||
"role": "user",
|
||||
"content": image_contents + [{"type": "text", "text": user_content}]
|
||||
@@ -838,6 +910,29 @@ class PromptGenerator:
|
||||
else:
|
||||
user_message = {"role": "user", "content": user_content}
|
||||
|
||||
# ================================================================
|
||||
# Ollama generation path
|
||||
# ================================================================
|
||||
if use_ollama:
|
||||
return self._generate_via_ollama(
|
||||
model_to_use=model_to_use,
|
||||
system_prompt=system_prompt,
|
||||
user_message=user_message,
|
||||
user_content=user_content,
|
||||
seed=seed,
|
||||
enable_thinking=enable_thinking,
|
||||
use_model_default_sampling=use_model_default_sampling,
|
||||
show_everything_in_console=show_everything_in_console,
|
||||
stop_server_after=stop_server_after,
|
||||
options=options,
|
||||
images=images,
|
||||
context_size=context_size,
|
||||
prompt=prompt,
|
||||
)
|
||||
|
||||
# ================================================================
|
||||
# llama.cpp generation path (existing)
|
||||
# ================================================================
|
||||
payload = {
|
||||
"messages": [
|
||||
{"role": "system", "content": system_prompt},
|
||||
@@ -897,7 +992,7 @@ class PromptGenerator:
|
||||
stream=True
|
||||
)
|
||||
else:
|
||||
return (error_msg,)
|
||||
raise RuntimeError(error_msg)
|
||||
|
||||
response.raise_for_status()
|
||||
|
||||
@@ -1008,18 +1103,192 @@ class PromptGenerator:
|
||||
except requests.exceptions.ConnectionError:
|
||||
error_msg = f"Error: Could not connect to server at {full_url}. Server may have crashed."
|
||||
print_pg(error_msg, RED)
|
||||
return (error_msg,)
|
||||
raise RuntimeError(error_msg)
|
||||
except requests.exceptions.Timeout:
|
||||
error_msg = "Error: Request timed out (>120s)"
|
||||
print_pg(error_msg, RED)
|
||||
return (error_msg,)
|
||||
raise RuntimeError(error_msg)
|
||||
except Exception as e:
|
||||
error_msg = f"Error: {e}"
|
||||
print_pg(error_msg, RED)
|
||||
if response.status_code == 400:
|
||||
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."
|
||||
return (error_msg,)
|
||||
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
|
||||
# ================================================================
|
||||
def _generate_via_ollama(self, model_to_use, system_prompt, user_message,
|
||||
user_content, seed, enable_thinking,
|
||||
use_model_default_sampling, show_everything_in_console,
|
||||
stop_server_after, options, images, context_size, prompt):
|
||||
"""Generate text using Ollama's OpenAI-compatible endpoint with streaming."""
|
||||
|
||||
messages = [
|
||||
{"role": "system", "content": system_prompt},
|
||||
user_message,
|
||||
]
|
||||
|
||||
# Sampling parameters
|
||||
temperature = 0.8
|
||||
top_k = 40
|
||||
top_p = 0.95
|
||||
min_p = 0.05
|
||||
repeat_penalty = 1.0
|
||||
if options and not use_model_default_sampling:
|
||||
temperature = options.get("temperature", temperature)
|
||||
top_k = options.get("top_k", top_k)
|
||||
top_p = options.get("top_p", top_p)
|
||||
min_p = options.get("min_p", min_p)
|
||||
repeat_penalty = options.get("repeat_penalty", repeat_penalty)
|
||||
|
||||
if show_everything_in_console:
|
||||
print_pg(f"{'=' * 60}", GREEN)
|
||||
print_pg(" DETAILED INFORMATION ENABLED (Ollama)", GREEN)
|
||||
print_pg(f"{'=' * 60}", GREEN)
|
||||
if not use_model_default_sampling:
|
||||
print_pg("------ GENERATION PARAMETERS ------", GREEN)
|
||||
for name, val in [("seed", seed), ("temperature", temperature),
|
||||
("top_k", top_k), ("top_p", top_p),
|
||||
("min_p", min_p), ("repeat_penalty", repeat_penalty)]:
|
||||
print_pg(f"{name} = {val}", GREEN)
|
||||
else:
|
||||
print_pg("Using model default sampling parameters", GREEN)
|
||||
print_pg("\n--------- SYSTEM PROMPT ---------", GREEN)
|
||||
print_pg(f"{system_prompt}", GREEN)
|
||||
print_pg("\n--------- USER PROMPT ---------", GREEN)
|
||||
print_pg(f"{user_content}", GREEN)
|
||||
|
||||
# Call Ollama (streaming)
|
||||
result = ollama_generate_chat(
|
||||
user_config=_preferences_cache,
|
||||
model_name=model_to_use,
|
||||
messages=messages,
|
||||
temperature=temperature,
|
||||
top_k=top_k,
|
||||
top_p=top_p,
|
||||
min_p=min_p,
|
||||
repeat_penalty=repeat_penalty,
|
||||
seed=seed,
|
||||
stream=True,
|
||||
timeout=120,
|
||||
use_model_defaults=use_model_default_sampling,
|
||||
enable_thinking=enable_thinking,
|
||||
)
|
||||
|
||||
# result is (response_obj, error_msg) for streaming
|
||||
if result[1] is not None:
|
||||
print_pg(f"Ollama error: {result[1]}", RED)
|
||||
return (result[1],)
|
||||
|
||||
response = result[0]
|
||||
|
||||
try:
|
||||
full_response = ""
|
||||
thinking_content = ""
|
||||
usage_stats = None
|
||||
first_thinking = True
|
||||
first_content = True
|
||||
|
||||
for line in response.iter_lines():
|
||||
# Check for user interrupt
|
||||
try:
|
||||
comfy.model_management.throw_exception_if_processing_interrupted()
|
||||
except Exception:
|
||||
try:
|
||||
response.close()
|
||||
except Exception:
|
||||
pass
|
||||
raise
|
||||
|
||||
if line:
|
||||
line = line.decode('utf-8')
|
||||
if line.startswith('data: '):
|
||||
data = line[6:]
|
||||
if data == '[DONE]':
|
||||
break
|
||||
try:
|
||||
chunk = json.loads(data)
|
||||
|
||||
if "usage" in chunk:
|
||||
usage_stats = chunk["usage"]
|
||||
|
||||
if 'choices' in chunk and len(chunk['choices']) > 0:
|
||||
delta = chunk['choices'][0].get('delta', {})
|
||||
if 'reasoning_content' in delta:
|
||||
reasoning_delta = delta['reasoning_content']
|
||||
if reasoning_delta is not None:
|
||||
thinking_content += str(reasoning_delta)
|
||||
if show_everything_in_console:
|
||||
if first_thinking:
|
||||
print_pg("\n--------- THINKING ---------", GREEN)
|
||||
first_thinking = False
|
||||
print(f"{GREEN}{str(reasoning_delta)}{RESET}", end='', flush=True)
|
||||
if 'content' in delta:
|
||||
content_delta = delta['content']
|
||||
if content_delta is not None:
|
||||
full_response += str(content_delta)
|
||||
if show_everything_in_console:
|
||||
if first_content:
|
||||
print_pg("\n\n--------- FINAL ANSWER ---------", CYAN)
|
||||
first_content = False
|
||||
print(f"{CYAN}{str(content_delta)}{RESET}", end='', flush=True)
|
||||
except json.JSONDecodeError:
|
||||
continue
|
||||
|
||||
if show_everything_in_console:
|
||||
print('') # Final newline
|
||||
|
||||
if not show_everything_in_console:
|
||||
print_pg("Prompt generation complete (Ollama).")
|
||||
|
||||
if show_everything_in_console and usage_stats:
|
||||
self.print_token_stats(usage_stats, None, thinking_content, full_response, images)
|
||||
else:
|
||||
print_pg_footer()
|
||||
|
||||
if not full_response:
|
||||
print_pg("Warning: Empty response from Ollama")
|
||||
full_response = prompt
|
||||
|
||||
# "stop_server_after" → unload model from Ollama memory immediately
|
||||
# (This overrides the keep_alive duration for this request)
|
||||
if stop_server_after:
|
||||
print_pg("Unloading model from Ollama memory...")
|
||||
ok, msg = ollama_unload_model(_preferences_cache, model_to_use)
|
||||
print_pg(msg, GREEN if ok else RED)
|
||||
else:
|
||||
keep_alive = _preferences_cache.get("ollama_keep_alive", "5m")
|
||||
if keep_alive and str(keep_alive) != "0":
|
||||
print_pg(f"Model will stay loaded for: {keep_alive}")
|
||||
|
||||
return (full_response, thinking_content)
|
||||
|
||||
except comfy.model_management.InterruptProcessingException:
|
||||
try:
|
||||
response.close()
|
||||
except Exception:
|
||||
pass
|
||||
raise
|
||||
except requests.exceptions.ConnectionError:
|
||||
error_msg = "Error: Lost connection to Ollama during generation."
|
||||
print_pg(error_msg, RED)
|
||||
raise RuntimeError(error_msg)
|
||||
except requests.exceptions.Timeout:
|
||||
error_msg = "Error: Ollama request timed out (>120s)"
|
||||
print_pg(error_msg, RED)
|
||||
raise RuntimeError(error_msg)
|
||||
except Exception as e:
|
||||
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"""
|
||||
@@ -1,4 +1,5 @@
|
||||
from .model_manager import get_all_models, is_model_local, download_model, get_mmproj_for_model, get_mmproj_path
|
||||
from ..py.model_manager import get_all_models, is_model_local, download_model, get_mmproj_for_model, get_mmproj_path, _preferences_cache
|
||||
from ..py.ollama_wrapper import discover_ollama_models, is_ollama_available
|
||||
import time
|
||||
|
||||
# Global timestamp to track when models were last updated
|
||||
@@ -14,17 +15,25 @@ class PromptGenOptions:
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
available_models = get_all_models()
|
||||
backend = _preferences_cache.get("llm_backend", "llama.cpp")
|
||||
|
||||
# If no models found, show a placeholder
|
||||
if not available_models:
|
||||
available_models = ["No models found - check HuggingFace"]
|
||||
if backend == "ollama":
|
||||
# Discover models from Ollama
|
||||
ollama_models, _status = discover_ollama_models(_preferences_cache)
|
||||
if not ollama_models:
|
||||
available_models = ["No Ollama models found - run 'ollama pull <model>'"]
|
||||
else:
|
||||
available_models = ollama_models
|
||||
else:
|
||||
available_models = get_all_models()
|
||||
if not available_models:
|
||||
available_models = ["No models found - check HuggingFace"]
|
||||
|
||||
return {
|
||||
"optional": {
|
||||
"model": (available_models, {
|
||||
"default": available_models[0] if available_models else "",
|
||||
"tooltip": "Select model to use (local models listed first, then HuggingFace models)"
|
||||
"tooltip": "Select model to use (local models listed first, then HuggingFace models)\nDownload sizes: UD-Q4_K_XL ~6GB | Q8_0 ~9.5GB | UD-Q8_K_XL ~13GB"
|
||||
}),
|
||||
"image2": ("IMAGE", {
|
||||
"tooltip": "Connect an image (required for 'Analyze Image' and 'Analyze Image with Prompt' modes)"
|
||||
@@ -49,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,
|
||||
@@ -98,6 +107,7 @@ class PromptGenOptions:
|
||||
}
|
||||
|
||||
CATEGORY = "Prompt Manager"
|
||||
DESCRIPTION = "Configure LLM model, sampling parameters, and system prompt for the Prompt Generator."
|
||||
RETURN_TYPES = ("OPTIONS",)
|
||||
RETURN_NAMES = ("options",)
|
||||
FUNCTION = "create_options"
|
||||
@@ -117,16 +127,23 @@ class PromptGenOptions:
|
||||
options = {}
|
||||
|
||||
# Handle model selection and download if needed
|
||||
if model and model != "No models found - check HuggingFace":
|
||||
backend = _preferences_cache.get("llm_backend", "llama.cpp")
|
||||
|
||||
if backend == "ollama":
|
||||
# Ollama mode — no download needed, just validate the selection
|
||||
if model and model != "No Ollama models found - run 'ollama pull <model>'":
|
||||
options["model"] = model
|
||||
options["llm_backend"] = "ollama"
|
||||
elif model and model != "No models found - check HuggingFace":
|
||||
# Check if model is local
|
||||
model_exists = is_model_local(model)
|
||||
|
||||
# For VL models, also check if mmproj exists
|
||||
# For vision models, also check if mmproj exists
|
||||
needs_download = not model_exists
|
||||
if model_exists:
|
||||
mmproj_name = get_mmproj_for_model(model)
|
||||
if mmproj_name:
|
||||
# This is a VL model, check if mmproj is present
|
||||
# This is a vision model, check if mmproj is present
|
||||
mmproj_path = get_mmproj_path(model)
|
||||
if not mmproj_path:
|
||||
print(f"[Prompt Generator Options] Vision model found but mmproj missing, downloading: {mmproj_name}")
|
||||
@@ -1,11 +1,35 @@
|
||||
import os
|
||||
import json
|
||||
import shutil
|
||||
import time
|
||||
import folder_paths
|
||||
import server
|
||||
|
||||
|
||||
class PromptManager:
|
||||
|
||||
@staticmethod
|
||||
def get_weekly_backup_path():
|
||||
"""Get the path to the weekly rotating backup file."""
|
||||
return PromptManager.get_prompts_path() + "_bak"
|
||||
|
||||
@staticmethod
|
||||
def _refresh_weekly_backup_if_due(source_path, backup_path, interval_days=7):
|
||||
"""Refresh backup only when missing or older than interval_days."""
|
||||
if not os.path.exists(source_path):
|
||||
return
|
||||
|
||||
should_refresh = not os.path.exists(backup_path)
|
||||
if not should_refresh:
|
||||
try:
|
||||
age_seconds = time.time() - os.path.getmtime(backup_path)
|
||||
should_refresh = age_seconds >= (interval_days * 24 * 60 * 60)
|
||||
except Exception:
|
||||
should_refresh = True
|
||||
|
||||
if should_refresh:
|
||||
shutil.copy2(source_path, backup_path)
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
prompts_data = PromptManager.load_prompts()
|
||||
@@ -13,7 +37,7 @@ class PromptManager:
|
||||
|
||||
all_prompts = set()
|
||||
for category_prompts in prompts_data.values():
|
||||
all_prompts.update(category_prompts.keys())
|
||||
all_prompts.update(k for k in category_prompts.keys() if k != "__meta__")
|
||||
|
||||
all_prompts.add("")
|
||||
all_prompts_list = sorted(list(all_prompts))
|
||||
@@ -24,7 +48,7 @@ class PromptManager:
|
||||
first_prompt = ""
|
||||
first_prompt_text = ""
|
||||
if prompts_data and first_category in prompts_data and prompts_data[first_category]:
|
||||
first_category_prompts = list(prompts_data[first_category].keys())
|
||||
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", "")
|
||||
@@ -45,6 +69,7 @@ class PromptManager:
|
||||
}
|
||||
|
||||
CATEGORY = "Prompt Manager"
|
||||
DESCRIPTION = "Simple prompt manager for saving and loading prompts by category. Prompt-only, no LoRA support."
|
||||
RETURN_TYPES = ("STRING",)
|
||||
RETURN_NAMES = ("prompt",)
|
||||
FUNCTION = "get_prompt"
|
||||
@@ -64,7 +89,7 @@ class PromptManager:
|
||||
@staticmethod
|
||||
def get_default_prompts_path():
|
||||
"""Get the path to the default prompts JSON file"""
|
||||
return os.path.join(os.path.dirname(__file__), "default_prompts.json")
|
||||
return os.path.join(os.path.dirname(os.path.dirname(__file__)), "default_prompts.json")
|
||||
|
||||
@classmethod
|
||||
def load_prompts(cls):
|
||||
@@ -78,6 +103,26 @@ class PromptManager:
|
||||
return json.load(f)
|
||||
except Exception as e:
|
||||
print(f"[PromptManager] Error loading user prompts: {e}")
|
||||
# Try backup variants before falling back to defaults.
|
||||
# Never overwrite a user file just because parsing failed.
|
||||
backup_candidates = [
|
||||
cls.get_weekly_backup_path(),
|
||||
user_path + ".bak",
|
||||
user_path + ".backup",
|
||||
user_path + ".tmp",
|
||||
]
|
||||
for backup_path in backup_candidates:
|
||||
if not os.path.exists(backup_path):
|
||||
continue
|
||||
try:
|
||||
with open(backup_path, 'r', encoding='utf-8') as f:
|
||||
backup_data = json.load(f)
|
||||
print(f"[PromptManager] Recovered prompts from backup: {backup_path}")
|
||||
return backup_data
|
||||
except Exception as be:
|
||||
print(f"[PromptManager] Backup load failed ({backup_path}): {be}")
|
||||
print("[PromptManager] User prompt file exists but could not be parsed; not overwriting with defaults.")
|
||||
return {}
|
||||
|
||||
if os.path.exists(default_path):
|
||||
try:
|
||||
@@ -94,10 +139,19 @@ class PromptManager:
|
||||
|
||||
@staticmethod
|
||||
def sort_prompts_data(data):
|
||||
"""Sort categories and prompts alphabetically (case-insensitive)"""
|
||||
"""Sort categories and prompts alphabetically (case-insensitive), preserving __meta__"""
|
||||
sorted_data = {}
|
||||
for category in sorted(data.keys(), key=str.lower):
|
||||
sorted_data[category] = dict(sorted(data[category].items(), key=lambda item: item[0].lower()))
|
||||
cat_data = data[category]
|
||||
meta = cat_data.get("__meta__")
|
||||
sorted_prompts = dict(sorted(
|
||||
((k, v) for k, v in cat_data.items() if k != "__meta__"),
|
||||
key=lambda item: item[0].lower()
|
||||
))
|
||||
if meta is not None:
|
||||
sorted_prompts["__meta__"] = meta
|
||||
sorted_data[category] = sorted_prompts
|
||||
return sorted_data
|
||||
return sorted_data
|
||||
|
||||
@classmethod
|
||||
@@ -105,13 +159,25 @@ class PromptManager:
|
||||
"""Save prompts to user folder"""
|
||||
user_path = cls.get_prompts_path()
|
||||
sorted_data = cls.sort_prompts_data(data)
|
||||
tmp_path = user_path + ".tmp"
|
||||
bak_path = cls.get_weekly_backup_path()
|
||||
|
||||
try:
|
||||
os.makedirs(os.path.dirname(user_path), exist_ok=True)
|
||||
with open(user_path, 'w', encoding='utf-8') as f:
|
||||
# Weekly rotating backup: refresh at most once every 7 days.
|
||||
cls._refresh_weekly_backup_if_due(user_path, bak_path)
|
||||
|
||||
# Atomic write: write temp then replace to avoid truncated/corrupt files.
|
||||
with open(tmp_path, 'w', encoding='utf-8') as f:
|
||||
json.dump(sorted_data, f, indent=2, ensure_ascii=False)
|
||||
os.replace(tmp_path, user_path)
|
||||
except Exception as e:
|
||||
print(f"[PromptManager] Error saving prompts: {e}")
|
||||
try:
|
||||
if os.path.exists(tmp_path):
|
||||
os.remove(tmp_path)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def get_prompt(self, category, name, use_external, text="", llm_input="", unique_id=None):
|
||||
"""Return the appropriate text based on use_external toggle and broadcast update"""
|
||||
@@ -203,14 +269,18 @@ async def save_prompt(request):
|
||||
print(f"[PromptManager] Removing old casing '{old_name}' before saving as '{name}'")
|
||||
del prompts[category][old_name]
|
||||
|
||||
# Save prompt in dict, preserving any existing lora data and trigger words from PromptManagerAdvanced
|
||||
# Save prompt in dict, preserving any existing lora data, trigger words, thumbnail, and nsfw from PromptManagerAdvanced
|
||||
existing_data = prompts[category].get(name, {})
|
||||
prompts[category][name] = {
|
||||
"prompt": text,
|
||||
"loras_a": existing_data.get("loras_a", []),
|
||||
"loras_b": existing_data.get("loras_b", []),
|
||||
"trigger_words": existing_data.get("trigger_words", [])
|
||||
"trigger_words": existing_data.get("trigger_words", []),
|
||||
"thumbnail": existing_data.get("thumbnail")
|
||||
}
|
||||
# Preserve nsfw flag if it was set
|
||||
if existing_data.get("nsfw"):
|
||||
prompts[category][name]["nsfw"] = existing_data["nsfw"]
|
||||
PromptManager.save_prompts(prompts)
|
||||
|
||||
return server.web.json_response({"success": True, "prompts": prompts})
|
||||
@@ -286,14 +356,14 @@ async def import_prompts(request):
|
||||
else:
|
||||
# Merge with existing prompts
|
||||
prompts = PromptManager.load_prompts()
|
||||
|
||||
|
||||
for category, category_prompts in imported_data.items():
|
||||
if not isinstance(category_prompts, dict):
|
||||
continue
|
||||
|
||||
|
||||
if category not in prompts:
|
||||
prompts[category] = {}
|
||||
|
||||
|
||||
for prompt_name, prompt_data in category_prompts.items():
|
||||
# Merge prompt data, preserving structure
|
||||
if isinstance(prompt_data, dict):
|
||||
@@ -307,4 +377,4 @@ async def import_prompts(request):
|
||||
|
||||
except Exception as e:
|
||||
print(f"[PromptManager] Error in import_prompts API: {e}")
|
||||
return server.web.json_response({"success": False, "error": str(e)}, status=500)
|
||||
return server.web.json_response({"success": False, "error": str(e)}, status=500)
|
||||
@@ -0,0 +1,362 @@
|
||||
"""
|
||||
Workflow Manager - stripped-down workflow_data editor based on PromptManagerAdvanced.
|
||||
|
||||
Differences from PromptManagerAdvanced:
|
||||
- workflow_data input/output only (no prompt/lora stack outputs)
|
||||
- no use_* switches
|
||||
- no trigger words pipeline
|
||||
"""
|
||||
|
||||
import json
|
||||
import base64
|
||||
from io import BytesIO
|
||||
|
||||
import server
|
||||
|
||||
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:
|
||||
import numpy as np
|
||||
from PIL import Image
|
||||
IMAGE_SUPPORT = True
|
||||
except ImportError:
|
||||
IMAGE_SUPPORT = False
|
||||
|
||||
|
||||
def _image_to_base64_thumbnail(image_tensor, max_size=200):
|
||||
if not IMAGE_SUPPORT or image_tensor is None:
|
||||
return None
|
||||
|
||||
try:
|
||||
img_array = image_tensor[0] if len(image_tensor.shape) == 4 else image_tensor
|
||||
if hasattr(img_array, "cpu"):
|
||||
img_array = img_array.cpu().numpy()
|
||||
img_array = (img_array * 255).astype(np.uint8)
|
||||
img = Image.fromarray(img_array)
|
||||
|
||||
width, height = img.size
|
||||
min_dim = min(width, height)
|
||||
if min_dim > max_size:
|
||||
scale = max_size / min_dim
|
||||
img = img.resize((int(width * scale), int(height * scale)), Image.LANCZOS)
|
||||
|
||||
buffer = BytesIO()
|
||||
img.save(buffer, format="JPEG", quality=85)
|
||||
base64_str = base64.b64encode(buffer.getvalue()).decode("utf-8")
|
||||
return f"data:image/jpeg;base64,{base64_str}"
|
||||
except Exception as e:
|
||||
print(f"[RecipeManager] Thumbnail generation failed: {e}")
|
||||
return None
|
||||
|
||||
|
||||
class WorkflowManager(PromptManagerAdvanced):
|
||||
"""Workflow-focused manager that edits and forwards RECIPE_DATA."""
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
prompts_data = cls.load_prompts()
|
||||
categories = list(prompts_data.keys()) if prompts_data else ["Default"]
|
||||
|
||||
all_prompts = set()
|
||||
for category_prompts in prompts_data.values():
|
||||
all_prompts.update(k for k in category_prompts.keys() if k != "__meta__")
|
||||
|
||||
all_prompts.add("")
|
||||
all_prompts_list = sorted(list(all_prompts))
|
||||
|
||||
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 = ""
|
||||
|
||||
return {
|
||||
"required": {
|
||||
"category": (categories, {"default": first_category}),
|
||||
"name": (all_prompts_list, {"default": first_prompt}),
|
||||
"text": ("STRING", {
|
||||
"multiline": True,
|
||||
"default": first_prompt_text,
|
||||
"placeholder": "Enter prompt text",
|
||||
"dynamicPrompts": False,
|
||||
"tooltip": "Edit prompt text directly",
|
||||
}),
|
||||
},
|
||||
"optional": {
|
||||
"recipe_data": ("RECIPE_DATA", {"forceInput": True, "tooltip": "Connected recipe_data to edit/forward"}),
|
||||
},
|
||||
"hidden": {
|
||||
"unique_id": "UNIQUE_ID",
|
||||
"loras_a_toggle": "STRING",
|
||||
"loras_b_toggle": "STRING",
|
||||
"saved_workflow_data": "STRING",
|
||||
},
|
||||
}
|
||||
|
||||
CATEGORY = "Prompt Manager"
|
||||
DESCRIPTION = "Workflow-data focused manager (no use switches, no trigger words)."
|
||||
RETURN_TYPES = ("RECIPE_DATA",)
|
||||
RETURN_NAMES = ("recipe_data",)
|
||||
FUNCTION = "get_workflow"
|
||||
OUTPUT_NODE = True
|
||||
|
||||
@classmethod
|
||||
def IS_CHANGED(cls, category, name, text="", **kwargs):
|
||||
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", "")
|
||||
return (
|
||||
category,
|
||||
name,
|
||||
text,
|
||||
str(recipe_data) if recipe_data else None,
|
||||
loras_a_toggle or "",
|
||||
loras_b_toggle or "",
|
||||
saved_workflow_data or "",
|
||||
)
|
||||
|
||||
def get_workflow(
|
||||
self,
|
||||
category,
|
||||
name,
|
||||
text="",
|
||||
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 {}
|
||||
# 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
|
||||
|
||||
stored_prompt_wf = _as_workflow_dict(prompt_entry.get("workflow_data")) if isinstance(prompt_entry, dict) else 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 = 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 = 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 = 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
|
||||
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 (
|
||||
generated_thumbnail if isinstance(generated_thumbnail, str) and generated_thumbnail else (
|
||||
incoming_wf.get("thumbnail") if isinstance(incoming_wf, dict) and isinstance(incoming_wf.get("thumbnail"), str) else (
|
||||
wf.get("thumbnail") if isinstance(wf.get("thumbnail"), str) else None
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
# 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 (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 (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_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: 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)
|
||||
|
||||
loras_a_display = self._format_loras_for_display_with_unavailable(merged_stack_a, all_preset_loras_a)
|
||||
loras_b_display = self._format_loras_for_display_with_unavailable(merged_stack_b, all_preset_loras_b)
|
||||
|
||||
unavailable_loras_a = [lora["name"] for lora in all_preset_loras_a if not lora.get("available", False)]
|
||||
unavailable_loras_b = [lora["name"] for lora in all_preset_loras_b if not lora.get("available", False)]
|
||||
|
||||
if unique_id is not None:
|
||||
server.PromptServer.instance.send_sync("prompt-manager-advanced-update", {
|
||||
"node_id": unique_id,
|
||||
"prompt": output_text,
|
||||
"use_prompt_input": False,
|
||||
"use_workflow_data": True,
|
||||
"prompt_input": "",
|
||||
"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,
|
||||
"loras_b": loras_b_display,
|
||||
"input_loras_a": self._format_loras_for_display(wf_loras_a) if wf_loras_a else [],
|
||||
"input_loras_b": self._format_loras_for_display(wf_loras_b) if wf_loras_b else [],
|
||||
"unavailable_loras_a": unavailable_loras_a,
|
||||
"unavailable_loras_b": unavailable_loras_b,
|
||||
"trigger_words": [],
|
||||
"connected_thumbnail": workflow_thumbnail,
|
||||
"should_reset": False,
|
||||
"original_strengths_a": {
|
||||
lora_item.get("name", ""): lora_item.get("strength", lora_item.get("model_strength", 1.0))
|
||||
for lora_item in loras_a_display
|
||||
if lora_item.get("name")
|
||||
},
|
||||
"original_strengths_b": {
|
||||
lora_item.get("name", ""): lora_item.get("strength", lora_item.get("model_strength", 1.0))
|
||||
for lora_item in loras_b_display
|
||||
if lora_item.get("name")
|
||||
},
|
||||
})
|
||||
|
||||
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),
|
||||
}
|
||||
for lora in loras_a_display
|
||||
if isinstance(lora, dict) and lora.get("name")
|
||||
]
|
||||
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),
|
||||
}
|
||||
for lora in loras_b_display
|
||||
if isinstance(lora, dict) and lora.get("name")
|
||||
]
|
||||
|
||||
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,)
|
||||
|
||||
def check_lazy_status(self, category, name, text="", **kwargs):
|
||||
return []
|
||||
@@ -0,0 +1,534 @@
|
||||
import os
|
||||
import sys
|
||||
import inspect
|
||||
|
||||
import folder_paths
|
||||
import nodes
|
||||
import comfy.sd
|
||||
import comfy.utils
|
||||
import torch
|
||||
|
||||
from comfy_execution.graph import ExecutionBlocker
|
||||
|
||||
|
||||
# =========================================================
|
||||
# GGUF support
|
||||
# =========================================================
|
||||
|
||||
def _get_gguf_module():
|
||||
"""Get the ComfyUI-GGUF module if available, otherwise None."""
|
||||
try:
|
||||
gguf_cls = nodes.NODE_CLASS_MAPPINGS.get("UnetLoaderGGUF")
|
||||
if gguf_cls is None:
|
||||
return None
|
||||
|
||||
mod = sys.modules.get(gguf_cls.__module__)
|
||||
if mod is None:
|
||||
return None
|
||||
|
||||
package = gguf_cls.__module__.rsplit(".", 1)[0]
|
||||
ops_mod = sys.modules.get(f"{package}.ops")
|
||||
loader_mod = sys.modules.get(f"{package}.loader")
|
||||
|
||||
if ops_mod is None or loader_mod is None:
|
||||
return None
|
||||
|
||||
return {
|
||||
"GGMLOps": ops_mod.GGMLOps,
|
||||
"gguf_sd_loader": loader_mod.gguf_sd_loader,
|
||||
"GGUFModelPatcher": mod.GGUFModelPatcher,
|
||||
}
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def _load_gguf_unet(unet_path):
|
||||
"""Load a GGUF diffusion model and return MODEL."""
|
||||
gguf = _get_gguf_module()
|
||||
if gguf is None:
|
||||
raise RuntimeError(
|
||||
"[RecipeModelLoader] This workflow requires ComfyUI-GGUF, "
|
||||
"but UnetLoaderGGUF is not available."
|
||||
)
|
||||
|
||||
ops = gguf["GGMLOps"]()
|
||||
sd, extra = gguf["gguf_sd_loader"](unet_path)
|
||||
|
||||
kwargs = {}
|
||||
valid_params = inspect.signature(comfy.sd.load_diffusion_model_state_dict).parameters
|
||||
if "metadata" in valid_params:
|
||||
kwargs["metadata"] = extra.get("metadata", {})
|
||||
|
||||
model = comfy.sd.load_diffusion_model_state_dict(
|
||||
sd,
|
||||
model_options={"custom_operations": ops},
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
if model is None:
|
||||
raise RuntimeError(
|
||||
f"[RecipeModelLoader] Could not detect model type of GGUF: {unet_path}"
|
||||
)
|
||||
|
||||
model = gguf["GGUFModelPatcher"].clone(model)
|
||||
model.patch_on_device = False
|
||||
return model
|
||||
|
||||
|
||||
# =========================================================
|
||||
# Generic loading helpers
|
||||
# =========================================================
|
||||
|
||||
MODEL_EXTENSIONS = ['.safetensors', '.ckpt', '.pt', '.pth', '.bin', '.gguf', '.sft']
|
||||
|
||||
WEIGHT_DTYPE_OPTIONS = ["default", "fp8_e4m3fn", "fp8_e4m3fn_fast", "fp8_e5m2"]
|
||||
|
||||
|
||||
def _short_display_name(name):
|
||||
"""Return basename without known model extension for compact UI/text output."""
|
||||
raw = str(name or "").strip()
|
||||
if not raw:
|
||||
return ""
|
||||
base = os.path.basename(raw.replace("\\", "/"))
|
||||
lower = base.lower()
|
||||
for ext in MODEL_EXTENSIONS:
|
||||
if lower.endswith(ext):
|
||||
return base[:-len(ext)]
|
||||
return os.path.splitext(base)[0]
|
||||
|
||||
|
||||
def _build_model_options(weight_dtype):
|
||||
"""Build model_options dict from weight_dtype selection."""
|
||||
model_options = {}
|
||||
if weight_dtype == "fp8_e4m3fn":
|
||||
model_options["dtype"] = torch.float8_e4m3fn
|
||||
elif weight_dtype == "fp8_e4m3fn_fast":
|
||||
model_options["dtype"] = torch.float8_e4m3fn
|
||||
model_options["fp8_optimizations"] = True
|
||||
elif weight_dtype == "fp8_e5m2":
|
||||
model_options["dtype"] = torch.float8_e5m2
|
||||
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.
|
||||
|
||||
Tries get_full_path first (exact / relative path), then falls back to
|
||||
scanning get_filename_list and matching by basename (with or without
|
||||
extension). This handles models stored in subdirectories.
|
||||
|
||||
Returns full path or None.
|
||||
"""
|
||||
if not name:
|
||||
return None
|
||||
|
||||
raw = str(name).strip()
|
||||
if not raw:
|
||||
return None
|
||||
|
||||
normalized = raw.replace("\\", "/")
|
||||
base = os.path.basename(normalized).lower()
|
||||
|
||||
# Strip extension for fuzzy matching
|
||||
base_no_ext = base
|
||||
for ext in MODEL_EXTENSIONS:
|
||||
if base_no_ext.endswith(ext):
|
||||
base_no_ext = base_no_ext[:-len(ext)]
|
||||
break
|
||||
|
||||
# Pass 1: try get_full_path (works when name is already a valid relative path)
|
||||
for candidate in (raw, os.path.basename(normalized)):
|
||||
for key in folder_key_candidates:
|
||||
try:
|
||||
path = folder_paths.get_full_path(key, candidate)
|
||||
if path:
|
||||
return path
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# Pass 2: scan filename lists and match by basename (handles subdirectories)
|
||||
for key in folder_key_candidates:
|
||||
try:
|
||||
file_list = folder_paths.get_filename_list(key)
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
for f in file_list:
|
||||
f_normalized = f.replace("\\", "/")
|
||||
|
||||
# Exact relative-path match
|
||||
if f_normalized == normalized:
|
||||
return folder_paths.get_full_path(key, f)
|
||||
|
||||
f_base = os.path.basename(f_normalized).lower()
|
||||
|
||||
# Basename match (with extension)
|
||||
if f_base == base:
|
||||
return folder_paths.get_full_path(key, f)
|
||||
|
||||
# Basename match (without extension)
|
||||
f_no_ext = f_base
|
||||
for ext in MODEL_EXTENSIONS:
|
||||
if f_no_ext.endswith(ext):
|
||||
f_no_ext = f_no_ext[:-len(ext)]
|
||||
break
|
||||
if f_no_ext == base_no_ext:
|
||||
return folder_paths.get_full_path(key, f)
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def _load_checkpoint_by_name(ckpt_name):
|
||||
"""
|
||||
Load checkpoint and return (MODEL, CLIP, VAE).
|
||||
Uses standard checkpoint loading semantics.
|
||||
"""
|
||||
ckpt_path = _resolve_path(ckpt_name, ["checkpoints", "diffusion_models", "unet"])
|
||||
if not ckpt_path:
|
||||
raise FileNotFoundError(f"[RecipeModelLoader] Checkpoint not found: {ckpt_name}")
|
||||
|
||||
out = comfy.sd.load_checkpoint_guess_config(
|
||||
ckpt_path,
|
||||
output_vae=True,
|
||||
output_clip=True,
|
||||
embedding_directory=folder_paths.get_folder_paths("embeddings"),
|
||||
)
|
||||
|
||||
model, clip, vae = out[:3]
|
||||
return model, clip, vae
|
||||
|
||||
|
||||
def _load_diffusion_model_by_name(model_name, weight_dtype="default"):
|
||||
"""
|
||||
Load a diffusion/UNet model and return MODEL.
|
||||
If the name ends with .gguf, use the GGUF loader path.
|
||||
"""
|
||||
model_path = _resolve_path(model_name, ["diffusion_models", "unet", "unet_gguf", "checkpoints"])
|
||||
if not model_path:
|
||||
raise FileNotFoundError(f"[RecipeModelLoader] Diffusion model not found: {model_name}")
|
||||
|
||||
if model_name.lower().endswith(".gguf"):
|
||||
return _load_gguf_unet(model_path)
|
||||
|
||||
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"[RecipeModelLoader] Could not load diffusion model: {model_name}")
|
||||
return model
|
||||
|
||||
|
||||
def _load_vae_by_name(vae_name):
|
||||
"""
|
||||
Load a VAE and return VAE.
|
||||
"""
|
||||
vae_path = _resolve_path(vae_name, ["vae", "checkpoints"])
|
||||
if not vae_path:
|
||||
raise FileNotFoundError(f"[RecipeModelLoader] VAE not found: {vae_name}")
|
||||
|
||||
sd = comfy.utils.load_torch_file(vae_path)
|
||||
return comfy.sd.VAE(sd=sd)
|
||||
|
||||
|
||||
def _load_clip_by_names(clip_names, clip_type=""):
|
||||
"""
|
||||
Load CLIP from one or more filenames.
|
||||
clip_names should be a list[str].
|
||||
"""
|
||||
if not clip_names:
|
||||
return None
|
||||
|
||||
clip_paths = []
|
||||
for name in clip_names:
|
||||
clip_path = _resolve_path(name, ["text_encoders", "clip", "checkpoints"])
|
||||
if not clip_path:
|
||||
raise FileNotFoundError(f"[RecipeModelLoader] CLIP not found: {name}")
|
||||
clip_paths.append(clip_path)
|
||||
|
||||
clip_type = (clip_type or "").strip().lower()
|
||||
|
||||
# Map a few common values. If unknown, let Comfy infer/default.
|
||||
clip_type_map = {
|
||||
"stable_diffusion": comfy.sd.CLIPType.STABLE_DIFFUSION,
|
||||
"sd": comfy.sd.CLIPType.STABLE_DIFFUSION,
|
||||
"sdxl": comfy.sd.CLIPType.STABLE_DIFFUSION,
|
||||
"wan": comfy.sd.CLIPType.WAN,
|
||||
"flux": comfy.sd.CLIPType.FLUX,
|
||||
"hunyuan_video": comfy.sd.CLIPType.HUNYUAN_VIDEO,
|
||||
}
|
||||
|
||||
load_kwargs = {
|
||||
"ckpt_paths": clip_paths,
|
||||
"embedding_directory": folder_paths.get_folder_paths("embeddings"),
|
||||
}
|
||||
|
||||
if clip_type in clip_type_map:
|
||||
load_kwargs["clip_type"] = clip_type_map[clip_type]
|
||||
|
||||
return comfy.sd.load_clip(**load_kwargs)
|
||||
|
||||
|
||||
# =========================================================
|
||||
# Node
|
||||
# =========================================================
|
||||
|
||||
class WorkflowModelLoader:
|
||||
CATEGORY = "Prompt Manager"
|
||||
RETURN_TYPES = ("MODEL", "CLIP", "VAE")
|
||||
RETURN_NAMES = ("model", "clip", "vae")
|
||||
FUNCTION = "get_model"
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {
|
||||
"recipe_data": ("RECIPE_DATA", {
|
||||
"tooltip": "Recipe data containing model name strings to load.",
|
||||
"forceInput": True,
|
||||
}),
|
||||
"model": (["model_a", "model_b", "model_c", "model_d"], {
|
||||
"default": "model_a",
|
||||
"tooltip": "Which model slot to load from recipe_data.",
|
||||
}),
|
||||
"weight_dtype": (WEIGHT_DTYPE_OPTIONS, {
|
||||
"default": "default",
|
||||
"tooltip": "Weight precision override for diffusion/UNet models. Ignored for checkpoints.",
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
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", "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"[RecipeModelLoader] Unsupported loader_type: {spec.get('loader_type')}"
|
||||
)
|
||||
|
||||
result = core_result
|
||||
|
||||
clip_names = spec.get("clip") or []
|
||||
vae_name = spec.get("vae", "")
|
||||
selected_lower = selected_name.lower()
|
||||
if loader_type == "checkpoint":
|
||||
model_kind = "checkpoint"
|
||||
elif selected_lower.endswith(".gguf"):
|
||||
model_kind = "gguf"
|
||||
else:
|
||||
model_kind = "diffusion"
|
||||
|
||||
ui_info = {
|
||||
"model": selected_model_slot,
|
||||
"model_name": selected_display_name,
|
||||
"loader_type": loader_type,
|
||||
"model_kind": model_kind,
|
||||
"vae_name": vae_name,
|
||||
"clip_names": clip_names,
|
||||
"status": "ok",
|
||||
"error_message": "",
|
||||
"missing_name": "",
|
||||
"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,
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def _is_placeholder(value):
|
||||
"""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()
|
||||
|
||||
# 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
|
||||
|
||||
clip = spec.get("clip") or []
|
||||
spec["clip"] = [c for c in clip if c and not self._is_placeholder(c)]
|
||||
|
||||
return spec
|
||||
|
||||
def _load_checkpoint_mode(self, spec):
|
||||
ckpt_name = spec.get(self._model_key, "")
|
||||
if not ckpt_name:
|
||||
return (
|
||||
ExecutionBlocker(f"Missing checkpoint in '{self._model_key}'"),
|
||||
ExecutionBlocker("No CLIP available"),
|
||||
ExecutionBlocker("No VAE available"),
|
||||
)
|
||||
|
||||
model, clip, vae = _load_checkpoint_by_name(ckpt_name)
|
||||
|
||||
clip_override = self._maybe_load_clip_override(spec)
|
||||
if clip_override is not None:
|
||||
clip = clip_override
|
||||
|
||||
vae_override = self._maybe_load_vae_override(spec)
|
||||
if vae_override is not None:
|
||||
vae = vae_override
|
||||
|
||||
if clip is None:
|
||||
clip = ExecutionBlocker(f"No CLIP available for checkpoint '{ckpt_name}'")
|
||||
if vae is None:
|
||||
vae = ExecutionBlocker(f"No VAE available for checkpoint '{ckpt_name}'")
|
||||
|
||||
return (model, clip, vae)
|
||||
|
||||
def _load_unet_mode(self, spec):
|
||||
model_name = spec.get(self._model_key, "")
|
||||
if not model_name:
|
||||
return (
|
||||
ExecutionBlocker(f"Missing model in '{self._model_key}'"),
|
||||
ExecutionBlocker("No CLIP available"),
|
||||
ExecutionBlocker("No VAE available"),
|
||||
)
|
||||
|
||||
model = _load_diffusion_model_by_name(model_name, self._weight_dtype)
|
||||
|
||||
clip = self._maybe_load_clip_override(spec)
|
||||
vae = self._maybe_load_vae_override(spec)
|
||||
|
||||
if clip is None:
|
||||
clip = ExecutionBlocker(
|
||||
f"No explicit CLIP provided for diffusion model '{model_name}'"
|
||||
)
|
||||
if vae is None:
|
||||
vae = ExecutionBlocker(
|
||||
f"No explicit VAE provided for diffusion model '{model_name}'"
|
||||
)
|
||||
|
||||
return (model, clip, vae)
|
||||
|
||||
def _maybe_load_clip_override(self, spec):
|
||||
clip_list = spec.get("clip") or []
|
||||
if len(clip_list) == 0:
|
||||
return None
|
||||
return _load_clip_by_names(clip_list, spec.get("clip_type", ""))
|
||||
|
||||
def _maybe_load_vae_override(self, spec):
|
||||
vae_name = spec.get("vae", "")
|
||||
if not vae_name:
|
||||
return None
|
||||
return _load_vae_by_name(vae_name)
|
||||
@@ -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,809 +0,0 @@
|
||||
"""
|
||||
ComfyUI Prompt Manager Advanced - Extended prompt management with LoRA stack support
|
||||
Saves prompts along with associated LoRA configurations
|
||||
"""
|
||||
import os
|
||||
import json
|
||||
import folder_paths
|
||||
import server
|
||||
|
||||
|
||||
def get_available_loras():
|
||||
"""Get all available LoRAs from ComfyUI's folder system"""
|
||||
lora_files = folder_paths.get_filename_list("loras")
|
||||
return lora_files
|
||||
|
||||
|
||||
def resolve_lora_path(lora_name):
|
||||
"""
|
||||
Resolve a LoRA name to its full path using ComfyUI's folder system.
|
||||
Returns (full_path, found) tuple.
|
||||
"""
|
||||
lora_files = get_available_loras()
|
||||
|
||||
# Try exact match first (with extension)
|
||||
for lora_file in lora_files:
|
||||
if lora_file == lora_name:
|
||||
return folder_paths.get_full_path("loras", lora_file), True
|
||||
|
||||
# Try matching by name without extension
|
||||
lora_name_lower = lora_name.lower()
|
||||
for lora_file in lora_files:
|
||||
file_name_no_ext = os.path.splitext(os.path.basename(lora_file))[0]
|
||||
if file_name_no_ext.lower() == lora_name_lower:
|
||||
return folder_paths.get_full_path("loras", lora_file), True
|
||||
|
||||
# Try partial match (lora_name might be just the filename, lora_file might have subdirs)
|
||||
for lora_file in lora_files:
|
||||
file_name = os.path.basename(lora_file)
|
||||
file_name_no_ext = os.path.splitext(file_name)[0]
|
||||
if file_name_no_ext.lower() == lora_name_lower or file_name.lower() == lora_name_lower:
|
||||
return folder_paths.get_full_path("loras", lora_file), True
|
||||
|
||||
# Not found
|
||||
return None, False
|
||||
|
||||
|
||||
def get_lora_relative_path(lora_name):
|
||||
"""
|
||||
Get the relative path for a LoRA that ComfyUI expects for loading.
|
||||
Returns (relative_path, found) tuple.
|
||||
"""
|
||||
lora_files = get_available_loras()
|
||||
|
||||
lora_name_lower = lora_name.lower()
|
||||
for lora_file in lora_files:
|
||||
file_name_no_ext = os.path.splitext(os.path.basename(lora_file))[0]
|
||||
if file_name_no_ext.lower() == lora_name_lower:
|
||||
return lora_file, True
|
||||
|
||||
# Not found
|
||||
return lora_name, False
|
||||
|
||||
|
||||
class PromptManagerAdvanced:
|
||||
"""
|
||||
Advanced Prompt Manager with LoRA stack integration.
|
||||
Supports saving/loading prompts with associated LoRA configurations.
|
||||
Features two LoRA stack inputs/outputs for dual LoRA workflows (e.g., Wan video).
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
prompts_data = PromptManagerAdvanced.load_prompts()
|
||||
categories = list(prompts_data.keys()) if prompts_data else ["Default"]
|
||||
|
||||
all_prompts = set()
|
||||
for category_prompts in prompts_data.values():
|
||||
all_prompts.update(category_prompts.keys())
|
||||
|
||||
all_prompts.add("")
|
||||
all_prompts_list = sorted(list(all_prompts))
|
||||
|
||||
first_category = categories[0] if categories else "Default"
|
||||
|
||||
# Get first prompt from first category
|
||||
first_prompt = ""
|
||||
first_prompt_text = ""
|
||||
if prompts_data and first_category in prompts_data and prompts_data[first_category]:
|
||||
first_category_prompts = list(prompts_data[first_category].keys())
|
||||
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_external": ("BOOLEAN", {"default": False, "label_on": "on", "label_off": "off", "tooltip": "Toggle to use LLM input instead of internal text"}),
|
||||
"override_lora": ("BOOLEAN", {
|
||||
"default": False,
|
||||
"tooltip": "When enabled, ignore connected LoRA stacks and use only the saved preset values"
|
||||
}),
|
||||
"text": ("STRING", {
|
||||
"multiline": True,
|
||||
"default": first_prompt_text,
|
||||
"placeholder": "Enter prompt text",
|
||||
"dynamicPrompts": False,
|
||||
"tooltip": "Enter prompt text directly"
|
||||
}),
|
||||
},
|
||||
"optional": {
|
||||
"llm_input": ("STRING", {"multiline": True, "forceInput": True, "lazy": True, "tooltip": "Connect LLM text input here"}),
|
||||
"lora_stack_a": ("LORA_STACK", {"tooltip": "First LoRA stack input (e.g., for base model)"}),
|
||||
"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"}),
|
||||
},
|
||||
"hidden": {
|
||||
"unique_id": "UNIQUE_ID",
|
||||
"loras_a_toggle": "STRING",
|
||||
"loras_b_toggle": "STRING",
|
||||
"trigger_words_toggle": "STRING",
|
||||
}
|
||||
}
|
||||
|
||||
CATEGORY = "Prompt Manager"
|
||||
RETURN_TYPES = ("STRING", "LORA_STACK", "LORA_STACK")
|
||||
RETURN_NAMES = ("prompt", "lora_stack_a", "lora_stack_b")
|
||||
FUNCTION = "get_prompt"
|
||||
OUTPUT_NODE = True
|
||||
|
||||
@classmethod
|
||||
def VALIDATE_INPUTS(cls, name, **kwargs):
|
||||
"""Allow any name value, including temporary unsaved prompts"""
|
||||
# Return True to accept any value - this allows new prompts to be tested before saving
|
||||
return True
|
||||
|
||||
@staticmethod
|
||||
def get_prompts_path():
|
||||
"""Get the path to the prompts JSON file in user/default folder (shared with standard PromptManager)"""
|
||||
return os.path.join(folder_paths.get_user_directory(), "default", "prompt_manager_data.json")
|
||||
|
||||
@staticmethod
|
||||
def get_default_prompts_path():
|
||||
"""Get the path to the default prompts JSON file"""
|
||||
return os.path.join(os.path.dirname(__file__), "default_prompts.json")
|
||||
|
||||
@classmethod
|
||||
def load_prompts(cls):
|
||||
"""Load prompts from user folder or default (shared with standard PromptManager)"""
|
||||
user_path = cls.get_prompts_path()
|
||||
default_path = cls.get_default_prompts_path()
|
||||
|
||||
if os.path.exists(user_path):
|
||||
try:
|
||||
with open(user_path, 'r', encoding='utf-8') as f:
|
||||
return json.load(f)
|
||||
except Exception as e:
|
||||
print(f"[PromptManagerAdvanced] Error loading user prompts: {e}")
|
||||
|
||||
if os.path.exists(default_path):
|
||||
try:
|
||||
with open(default_path, 'r', encoding='utf-8') as f:
|
||||
data = json.load(f)
|
||||
cls.save_prompts(data)
|
||||
return data
|
||||
except Exception as e:
|
||||
print(f"[PromptManagerAdvanced] Error loading default prompts: {e}")
|
||||
|
||||
# Return empty structure if all else fails
|
||||
print("[PromptManagerAdvanced] Warning: No prompt files found, starting with empty data")
|
||||
return {}
|
||||
|
||||
@staticmethod
|
||||
def sort_prompts_data(data):
|
||||
"""Sort categories and prompts alphabetically (case-insensitive)"""
|
||||
sorted_data = {}
|
||||
for category in sorted(data.keys(), key=str.lower):
|
||||
sorted_data[category] = dict(sorted(data[category].items(), key=lambda item: item[0].lower()))
|
||||
return sorted_data
|
||||
|
||||
@classmethod
|
||||
def save_prompts(cls, data):
|
||||
"""Save prompts to user folder"""
|
||||
user_path = cls.get_prompts_path()
|
||||
sorted_data = cls.sort_prompts_data(data)
|
||||
|
||||
try:
|
||||
os.makedirs(os.path.dirname(user_path), exist_ok=True)
|
||||
with open(user_path, 'w', encoding='utf-8') as f:
|
||||
json.dump(sorted_data, f, indent=2, ensure_ascii=False)
|
||||
except Exception as e:
|
||||
print(f"[PromptManagerAdvanced] Error saving prompts: {e}")
|
||||
|
||||
def _merge_lora_stacks(self, preset_stack, connected_stack):
|
||||
"""
|
||||
Merge preset loras with connected loras, avoiding duplicates.
|
||||
Preset loras come first, then connected loras that aren't already in preset.
|
||||
|
||||
Args:
|
||||
preset_stack: List of tuples from saved preset
|
||||
connected_stack: List of tuples from connected input
|
||||
|
||||
Returns:
|
||||
Combined lora stack with no duplicates (by lora name)
|
||||
"""
|
||||
if not connected_stack:
|
||||
return preset_stack if preset_stack else []
|
||||
if not preset_stack:
|
||||
return list(connected_stack)
|
||||
|
||||
# Build set of lora names from preset
|
||||
preset_names = set()
|
||||
for lora_path, _, _ in preset_stack:
|
||||
lora_name = os.path.splitext(os.path.basename(lora_path))[0]
|
||||
preset_names.add(lora_name)
|
||||
|
||||
# Start with preset, add non-duplicate connected loras
|
||||
merged = list(preset_stack)
|
||||
for lora_path, model_strength, clip_strength in connected_stack:
|
||||
lora_name = os.path.splitext(os.path.basename(lora_path))[0]
|
||||
if lora_name not in preset_names:
|
||||
merged.append((lora_path, model_strength, clip_strength))
|
||||
|
||||
return merged
|
||||
|
||||
def _process_lora_toggle(self, lora_stack, toggle_data):
|
||||
"""
|
||||
Process lora stack with toggle data to filter active loras and apply strength adjustments.
|
||||
|
||||
Args:
|
||||
lora_stack: List of tuples (lora_path, model_strength, clip_strength)
|
||||
toggle_data: JSON string or list of toggle states [{name, active, strength}, ...]
|
||||
|
||||
Returns:
|
||||
Filtered lora stack with adjusted strengths
|
||||
"""
|
||||
if not lora_stack:
|
||||
return []
|
||||
|
||||
if not toggle_data:
|
||||
return list(lora_stack)
|
||||
|
||||
# Parse toggle data if it's a string
|
||||
try:
|
||||
if isinstance(toggle_data, str):
|
||||
toggle_data = json.loads(toggle_data)
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
return list(lora_stack)
|
||||
|
||||
if not isinstance(toggle_data, list):
|
||||
return list(lora_stack)
|
||||
|
||||
# Create a map of toggle states by lora name
|
||||
toggle_map = {}
|
||||
for item in toggle_data:
|
||||
if isinstance(item, dict):
|
||||
name = item.get('name', '')
|
||||
toggle_map[name] = {
|
||||
'active': item.get('active', True),
|
||||
'strength': item.get('strength')
|
||||
}
|
||||
|
||||
# Filter and adjust lora stack
|
||||
filtered_stack = []
|
||||
for lora_path, model_strength, clip_strength in lora_stack:
|
||||
# Extract lora name from path
|
||||
lora_name = os.path.splitext(os.path.basename(lora_path))[0]
|
||||
|
||||
# Check toggle state
|
||||
toggle_state = toggle_map.get(lora_name, {'active': True, 'strength': None})
|
||||
|
||||
if not toggle_state['active']:
|
||||
continue # Skip inactive loras
|
||||
|
||||
# Apply strength adjustment if provided
|
||||
if toggle_state['strength'] is not None:
|
||||
adjusted_strength = float(toggle_state['strength'])
|
||||
# Scale both model and clip strength proportionally
|
||||
ratio = adjusted_strength / model_strength if model_strength != 0 else 1.0
|
||||
model_strength = adjusted_strength
|
||||
clip_strength = clip_strength * ratio
|
||||
|
||||
filtered_stack.append((lora_path, model_strength, clip_strength))
|
||||
|
||||
return filtered_stack
|
||||
|
||||
def get_prompt(self, category, name, use_external, text="", override_lora=False, llm_input="",
|
||||
lora_stack_a=None, lora_stack_b=None, trigger_words=None,
|
||||
unique_id=None, loras_a_toggle=None, loras_b_toggle=None, trigger_words_toggle=None):
|
||||
"""Return the prompt text and filtered lora stacks based on toggle states"""
|
||||
|
||||
# Choose which text to use based on the toggle
|
||||
if use_external and llm_input:
|
||||
output_text = llm_input
|
||||
else:
|
||||
output_text = text
|
||||
|
||||
# Process trigger words
|
||||
trigger_words_display = self._process_trigger_words(
|
||||
trigger_words, trigger_words_toggle
|
||||
)
|
||||
active_trigger_words = self._get_active_trigger_words(trigger_words_toggle)
|
||||
|
||||
# Build preset stacks from saved toggle data (these are what we display/manage)
|
||||
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 []
|
||||
|
||||
# When override_lora is enabled, ignore connected stacks and use only saved loras
|
||||
if override_lora:
|
||||
lora_stack_a = preset_stack_a
|
||||
lora_stack_b = preset_stack_b
|
||||
else:
|
||||
# Merge: preset loras + connected loras (avoiding duplicates by lora name)
|
||||
lora_stack_a = self._merge_lora_stacks(preset_stack_a, lora_stack_a)
|
||||
lora_stack_b = self._merge_lora_stacks(preset_stack_b, lora_stack_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)
|
||||
|
||||
# Display logic depends on override mode:
|
||||
# - Override ON: Show only preset loras (what will actually be used)
|
||||
# - Override OFF: Show merged loras (preset + connected) so user sees full picture
|
||||
if override_lora:
|
||||
loras_a_display = self._format_loras_for_display(preset_stack_a) if preset_stack_a else []
|
||||
loras_b_display = self._format_loras_for_display(preset_stack_b) if preset_stack_b else []
|
||||
else:
|
||||
loras_a_display = self._format_loras_for_display(lora_stack_a) if lora_stack_a else []
|
||||
loras_b_display = self._format_loras_for_display(lora_stack_b) if lora_stack_b else []
|
||||
|
||||
# Broadcast update to frontend
|
||||
if unique_id is not None:
|
||||
server.PromptServer.instance.send_sync("prompt-manager-advanced-update", {
|
||||
"node_id": unique_id,
|
||||
"prompt": output_text,
|
||||
"use_external": use_external,
|
||||
"llm_input": llm_input,
|
||||
"loras_a": loras_a_display,
|
||||
"loras_b": loras_b_display,
|
||||
"trigger_words": trigger_words_display
|
||||
})
|
||||
|
||||
# Append active trigger words to output
|
||||
final_output = self._append_trigger_words_to_prompt(output_text, active_trigger_words)
|
||||
|
||||
return (final_output, processed_stack_a if processed_stack_a else [], processed_stack_b if processed_stack_b else [])
|
||||
|
||||
def check_lazy_status(self, category, name, use_external, text, override_lora=False, llm_input=None,
|
||||
lora_stack_a=None, lora_stack_b=None, trigger_words=None,
|
||||
unique_id=None, loras_a_toggle=None, loras_b_toggle=None, trigger_words_toggle=None):
|
||||
"""Tell ComfyUI which lazy inputs are needed based on current settings"""
|
||||
needed = []
|
||||
if use_external:
|
||||
needed.append("llm_input")
|
||||
return needed
|
||||
|
||||
def _build_stack_from_toggle(self, toggle_data):
|
||||
"""
|
||||
Build a lora stack from toggle data by resolving paths at runtime.
|
||||
This is used when no input stack is connected but we have saved lora data.
|
||||
"""
|
||||
if not toggle_data:
|
||||
return []
|
||||
|
||||
# Parse toggle data if it's a string
|
||||
try:
|
||||
if isinstance(toggle_data, str):
|
||||
toggle_data = json.loads(toggle_data)
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
return []
|
||||
|
||||
if not isinstance(toggle_data, list):
|
||||
return []
|
||||
|
||||
stack = []
|
||||
missing_loras = []
|
||||
|
||||
for item in toggle_data:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
|
||||
lora_name = item.get('name', '')
|
||||
if not lora_name:
|
||||
continue
|
||||
|
||||
# Skip inactive loras
|
||||
if item.get('active', True) is False:
|
||||
continue
|
||||
|
||||
# Resolve the path at runtime
|
||||
relative_path, found = get_lora_relative_path(lora_name)
|
||||
|
||||
if not found:
|
||||
missing_loras.append(lora_name)
|
||||
continue # Skip missing loras
|
||||
|
||||
strength = float(item.get('strength', 1.0))
|
||||
clip_strength = float(item.get('clip_strength', strength))
|
||||
|
||||
stack.append((relative_path, strength, clip_strength))
|
||||
|
||||
# Log warning for missing loras
|
||||
if missing_loras:
|
||||
print(f"[PromptManagerAdvanced] Warning: Could not find LoRAs: {', '.join(missing_loras)}")
|
||||
|
||||
return stack
|
||||
|
||||
def _format_loras_for_display(self, lora_stack):
|
||||
"""Format lora stack for frontend display"""
|
||||
if not lora_stack:
|
||||
return []
|
||||
|
||||
display_list = []
|
||||
for lora_path, model_strength, clip_strength in lora_stack:
|
||||
lora_name = os.path.splitext(os.path.basename(lora_path))[0]
|
||||
display_list.append({
|
||||
"name": lora_name,
|
||||
"path": lora_path,
|
||||
"model_strength": model_strength,
|
||||
"clip_strength": clip_strength,
|
||||
"active": True,
|
||||
"strength": model_strength
|
||||
})
|
||||
return display_list
|
||||
|
||||
def _process_trigger_words(self, connected_trigger_words, toggle_data):
|
||||
"""
|
||||
Process trigger words from connected input and saved toggle states.
|
||||
Returns list of trigger word objects for display.
|
||||
"""
|
||||
# Parse saved toggle data
|
||||
saved_words = {}
|
||||
if toggle_data:
|
||||
try:
|
||||
if isinstance(toggle_data, str):
|
||||
toggle_data = json.loads(toggle_data)
|
||||
if isinstance(toggle_data, list):
|
||||
for item in toggle_data:
|
||||
if isinstance(item, dict) and item.get('text'):
|
||||
word = item['text'].strip()
|
||||
saved_words[word.lower()] = {
|
||||
'text': word,
|
||||
'active': item.get('active', True)
|
||||
}
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
pass
|
||||
|
||||
# Parse connected trigger words (comma-separated)
|
||||
connected_words = []
|
||||
if connected_trigger_words and isinstance(connected_trigger_words, str):
|
||||
connected_words = [w.strip() for w in connected_trigger_words.split(',') if w.strip()]
|
||||
|
||||
# Merge: saved words + new connected words (no duplicates)
|
||||
result = []
|
||||
seen = set()
|
||||
|
||||
# First, add all saved words (preserving their state)
|
||||
for word_lower, data in saved_words.items():
|
||||
if word_lower not in seen:
|
||||
result.append({
|
||||
'text': data['text'],
|
||||
'active': data['active'],
|
||||
'source': 'saved'
|
||||
})
|
||||
seen.add(word_lower)
|
||||
|
||||
# Then add connected words that aren't already saved
|
||||
for word in connected_words:
|
||||
word_lower = word.lower()
|
||||
if word_lower not in seen:
|
||||
result.append({
|
||||
'text': word,
|
||||
'active': True,
|
||||
'source': 'connected'
|
||||
})
|
||||
seen.add(word_lower)
|
||||
|
||||
return result
|
||||
|
||||
def _get_active_trigger_words(self, toggle_data):
|
||||
"""
|
||||
Get list of active trigger word strings from toggle data.
|
||||
"""
|
||||
active_words = []
|
||||
if toggle_data:
|
||||
try:
|
||||
if isinstance(toggle_data, str):
|
||||
toggle_data = json.loads(toggle_data)
|
||||
if isinstance(toggle_data, list):
|
||||
for item in toggle_data:
|
||||
if isinstance(item, dict) and item.get('active', True):
|
||||
word = item.get('text', '').strip()
|
||||
if word:
|
||||
active_words.append(word)
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
pass
|
||||
return active_words
|
||||
|
||||
def _append_trigger_words_to_prompt(self, prompt, trigger_words):
|
||||
"""
|
||||
Append trigger words to the end of the prompt.
|
||||
Adds a period before trigger words if prompt doesn't end with comma or period.
|
||||
"""
|
||||
if not trigger_words:
|
||||
return prompt
|
||||
|
||||
prompt = prompt.rstrip()
|
||||
if not prompt:
|
||||
return ', '.join(trigger_words)
|
||||
|
||||
# Check if prompt ends with punctuation
|
||||
if not prompt.endswith((',', '.')):
|
||||
prompt += '.'
|
||||
|
||||
# Add space if needed
|
||||
if not prompt.endswith(' '):
|
||||
prompt += ' '
|
||||
|
||||
return prompt + ', '.join(trigger_words)
|
||||
|
||||
|
||||
# API Routes for Advanced Prompt Manager
|
||||
|
||||
@server.PromptServer.instance.routes.get("/prompt-manager-advanced/get-prompts")
|
||||
async def get_prompts_advanced(request):
|
||||
"""API endpoint to get all advanced prompts"""
|
||||
try:
|
||||
prompts = PromptManagerAdvanced.load_prompts()
|
||||
return server.web.json_response(prompts)
|
||||
except Exception as e:
|
||||
print(f"[PromptManagerAdvanced] Error in get_prompts API: {e}")
|
||||
return server.web.json_response({"error": str(e)}, status=500)
|
||||
|
||||
|
||||
@server.PromptServer.instance.routes.post("/prompt-manager-advanced/save-category")
|
||||
async def save_category_advanced(request):
|
||||
"""API endpoint to create a new category"""
|
||||
try:
|
||||
data = await request.json()
|
||||
category_name = data.get("category_name", "").strip()
|
||||
|
||||
if not category_name:
|
||||
return server.web.json_response({"success": False, "error": "Category name is required"})
|
||||
|
||||
prompts = PromptManagerAdvanced.load_prompts()
|
||||
|
||||
# Case-insensitive check for existing category
|
||||
existing_categories_lower = {k.lower(): k for k in prompts.keys()}
|
||||
if category_name.lower() in existing_categories_lower:
|
||||
return server.web.json_response({
|
||||
"success": False,
|
||||
"error": f"Category already exists as '{existing_categories_lower[category_name.lower()]}'"
|
||||
})
|
||||
|
||||
prompts[category_name] = {}
|
||||
PromptManagerAdvanced.save_prompts(prompts)
|
||||
|
||||
return server.web.json_response({"success": True, "prompts": prompts})
|
||||
except Exception as e:
|
||||
print(f"[PromptManagerAdvanced] Error in save_category API: {e}")
|
||||
return server.web.json_response({"success": False, "error": str(e)}, status=500)
|
||||
|
||||
|
||||
@server.PromptServer.instance.routes.post("/prompt-manager-advanced/save-prompt")
|
||||
async def save_prompt_advanced(request):
|
||||
"""API endpoint to save a prompt with lora configurations"""
|
||||
try:
|
||||
data = await request.json()
|
||||
category = data.get("category", "").strip()
|
||||
name = data.get("name", "").strip()
|
||||
text = data.get("text", "").strip()
|
||||
loras_a = data.get("loras_a", [])
|
||||
loras_b = data.get("loras_b", [])
|
||||
trigger_words = data.get("trigger_words", [])
|
||||
|
||||
if not category or not name:
|
||||
return server.web.json_response({"success": False, "error": "Category and name are required"})
|
||||
|
||||
prompts = PromptManagerAdvanced.load_prompts()
|
||||
|
||||
if category not in prompts:
|
||||
prompts[category] = {}
|
||||
|
||||
# Case-insensitive check for existing prompt
|
||||
existing_prompts_lower = {k.lower(): k for k in prompts[category].keys()}
|
||||
if name.lower() in existing_prompts_lower:
|
||||
old_name = existing_prompts_lower[name.lower()]
|
||||
if old_name != name:
|
||||
# Delete the old casing version
|
||||
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
|
||||
def normalize_lora_data(loras):
|
||||
normalized = []
|
||||
for lora in loras:
|
||||
if isinstance(lora, dict) and lora.get('name'):
|
||||
normalized.append({
|
||||
"name": 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)
|
||||
})
|
||||
return normalized
|
||||
|
||||
# Normalize trigger words data
|
||||
def normalize_trigger_words(words):
|
||||
normalized = []
|
||||
seen = set()
|
||||
for word in words:
|
||||
if isinstance(word, dict) and word.get('text'):
|
||||
text = word['text'].strip()
|
||||
text_lower = text.lower()
|
||||
if text and text_lower not in seen:
|
||||
normalized.append({
|
||||
"text": text,
|
||||
"active": word.get('active', True)
|
||||
})
|
||||
seen.add(text_lower)
|
||||
elif isinstance(word, str) and word.strip():
|
||||
text = word.strip()
|
||||
text_lower = text.lower()
|
||||
if text_lower not in seen:
|
||||
normalized.append({"text": text, "active": True})
|
||||
seen.add(text_lower)
|
||||
return normalized
|
||||
|
||||
# Save prompt with normalized lora data (no paths - they're resolved at runtime)
|
||||
prompts[category][name] = {
|
||||
"prompt": text,
|
||||
"loras_a": normalize_lora_data(loras_a),
|
||||
"loras_b": normalize_lora_data(loras_b),
|
||||
"trigger_words": normalize_trigger_words(trigger_words)
|
||||
}
|
||||
PromptManagerAdvanced.save_prompts(prompts)
|
||||
|
||||
return server.web.json_response({"success": True, "prompts": prompts})
|
||||
except Exception as e:
|
||||
print(f"[PromptManagerAdvanced] Error in save_prompt API: {e}")
|
||||
return server.web.json_response({"success": False, "error": str(e)}, status=500)
|
||||
|
||||
|
||||
@server.PromptServer.instance.routes.post("/prompt-manager-advanced/delete-category")
|
||||
async def delete_category_advanced(request):
|
||||
"""API endpoint to delete a category"""
|
||||
try:
|
||||
data = await request.json()
|
||||
category = data.get("category", "").strip()
|
||||
|
||||
if not category:
|
||||
return server.web.json_response({"success": False, "error": "Category name is required"})
|
||||
|
||||
prompts = PromptManagerAdvanced.load_prompts()
|
||||
|
||||
if category not in prompts:
|
||||
return server.web.json_response({"success": False, "error": "Category not found"})
|
||||
|
||||
del prompts[category]
|
||||
PromptManagerAdvanced.save_prompts(prompts)
|
||||
|
||||
return server.web.json_response({"success": True, "prompts": prompts})
|
||||
except Exception as e:
|
||||
print(f"[PromptManagerAdvanced] Error in delete_category API: {e}")
|
||||
return server.web.json_response({"success": False, "error": str(e)}, status=500)
|
||||
|
||||
|
||||
@server.PromptServer.instance.routes.post("/prompt-manager-advanced/delete-prompt")
|
||||
async def delete_prompt_advanced(request):
|
||||
"""API endpoint to delete a prompt"""
|
||||
try:
|
||||
data = await request.json()
|
||||
category = data.get("category", "").strip()
|
||||
name = data.get("name", "").strip()
|
||||
|
||||
if not category or not name:
|
||||
return server.web.json_response({"success": False, "error": "Category and prompt name are required"})
|
||||
|
||||
prompts = PromptManagerAdvanced.load_prompts()
|
||||
|
||||
if category not in prompts or name not in prompts[category]:
|
||||
return server.web.json_response({"success": False, "error": "Prompt not found"})
|
||||
|
||||
del prompts[category][name]
|
||||
PromptManagerAdvanced.save_prompts(prompts)
|
||||
|
||||
return server.web.json_response({"success": True, "prompts": prompts})
|
||||
except Exception as e:
|
||||
print(f"[PromptManagerAdvanced] Error in delete_prompt API: {e}")
|
||||
return server.web.json_response({"success": False, "error": str(e)}, status=500)
|
||||
|
||||
|
||||
@server.PromptServer.instance.routes.post("/prompt-manager-advanced/check-loras")
|
||||
async def check_loras_advanced(request):
|
||||
"""API endpoint to check which LoRAs are available in the system"""
|
||||
try:
|
||||
data = await request.json()
|
||||
lora_names = data.get("lora_names", [])
|
||||
|
||||
results = {}
|
||||
for lora_name in lora_names:
|
||||
_, found = get_lora_relative_path(lora_name)
|
||||
results[lora_name] = found
|
||||
|
||||
return server.web.json_response({"success": True, "results": results})
|
||||
except Exception as e:
|
||||
print(f"[PromptManagerAdvanced] Error in check_loras API: {e}")
|
||||
return server.web.json_response({"success": False, "error": str(e)}, status=500)
|
||||
|
||||
|
||||
@server.PromptServer.instance.routes.get("/prompt-manager-advanced/available-loras")
|
||||
async def get_available_loras_api(request):
|
||||
"""API endpoint to get list of all available LoRA names"""
|
||||
try:
|
||||
lora_files = get_available_loras()
|
||||
# Return just the names without extensions for easier matching
|
||||
lora_names = [os.path.splitext(os.path.basename(f))[0] for f in lora_files]
|
||||
return server.web.json_response({"success": True, "loras": sorted(set(lora_names))})
|
||||
except Exception as e:
|
||||
print(f"[PromptManagerAdvanced] Error in available_loras API: {e}")
|
||||
return server.web.json_response({"success": False, "error": str(e)}, status=500)
|
||||
|
||||
|
||||
@server.PromptServer.instance.routes.post("/prompt-manager-advanced/get-prompt-data")
|
||||
async def get_prompt_data_advanced(request):
|
||||
"""API endpoint to get specific prompt data including loras with availability check"""
|
||||
try:
|
||||
data = await request.json()
|
||||
category = data.get("category", "").strip()
|
||||
name = data.get("name", "").strip()
|
||||
|
||||
if not category or not name:
|
||||
return server.web.json_response({"success": False, "error": "Category and name are required"})
|
||||
|
||||
prompts = PromptManagerAdvanced.load_prompts()
|
||||
|
||||
if category not in prompts or name not in prompts[category]:
|
||||
return server.web.json_response({"success": False, "error": "Prompt not found"})
|
||||
|
||||
prompt_data = prompts[category][name]
|
||||
|
||||
# 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
|
||||
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", [])
|
||||
}
|
||||
})
|
||||
except Exception as e:
|
||||
print(f"[PromptManagerAdvanced] Error in get_prompt_data API: {e}")
|
||||
return server.web.json_response({"success": False, "error": str(e)}, status=500)
|
||||
|
||||
|
||||
@server.PromptServer.instance.routes.post("/prompt-manager-advanced/import-prompts")
|
||||
async def import_prompts_advanced(request):
|
||||
"""API endpoint to import prompts from JSON"""
|
||||
try:
|
||||
data = await request.json()
|
||||
imported_data = data.get("data", {})
|
||||
mode = data.get("mode", "merge") # "merge" or "replace"
|
||||
|
||||
if not isinstance(imported_data, dict):
|
||||
return server.web.json_response({"success": False, "error": "Invalid data format"})
|
||||
|
||||
if mode == "replace":
|
||||
# Replace all existing prompts
|
||||
prompts = {}
|
||||
else:
|
||||
# Merge with existing prompts
|
||||
prompts = PromptManagerAdvanced.load_prompts()
|
||||
|
||||
# Process imported data
|
||||
for category, category_prompts in imported_data.items():
|
||||
if not isinstance(category_prompts, dict):
|
||||
continue
|
||||
|
||||
if category not in prompts:
|
||||
prompts[category] = {}
|
||||
|
||||
for prompt_name, prompt_data in category_prompts.items():
|
||||
if not isinstance(prompt_data, dict):
|
||||
continue
|
||||
|
||||
# Normalize the prompt data structure
|
||||
prompts[category][prompt_name] = {
|
||||
"prompt": prompt_data.get("prompt", ""),
|
||||
"loras_a": prompt_data.get("loras_a", []),
|
||||
"loras_b": prompt_data.get("loras_b", []),
|
||||
"trigger_words": prompt_data.get("trigger_words", [])
|
||||
}
|
||||
|
||||
PromptManagerAdvanced.save_prompts(prompts)
|
||||
|
||||
return server.web.json_response({"success": True, "prompts": prompts})
|
||||
except Exception as e:
|
||||
print(f"[PromptManagerAdvanced] Error in import_prompts API: {e}")
|
||||
return server.web.json_response({"success": False, "error": str(e)}, status=500)
|
||||
@@ -0,0 +1,422 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
convert_to_api.py — Convert ComfyUI UI-format workflow JSON to API format + _map.json
|
||||
|
||||
Usage:
|
||||
python tools/convert_to_api.py
|
||||
# Reads from workflows/*.json, writes to workflows/api/*_api.json + *_map.json
|
||||
|
||||
API format: dict keyed by node ID (string), each value = {"class_type": ..., "inputs": {...}}
|
||||
Map format: dict of semantic field -> [node_id_str, input_field_name]
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
|
||||
# ── Path setup ──────────────────────────────────────────────────────────────
|
||||
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
|
||||
REPO_ROOT = os.path.dirname(SCRIPT_DIR)
|
||||
SRC_DIR = os.path.join(REPO_ROOT, "workflows")
|
||||
DST_DIR = os.path.join(REPO_ROOT, "workflows", "api")
|
||||
os.makedirs(DST_DIR, exist_ok=True)
|
||||
|
||||
|
||||
# ── UI → API conversion ──────────────────────────────────────────────────────
|
||||
|
||||
def ui_to_api(ui_data):
|
||||
"""
|
||||
Convert a UI-format workflow dict to API-format.
|
||||
|
||||
UI format: { nodes: [...], links: [...], ... }
|
||||
- nodes have id, type, inputs (with link IDs), outputs (with link IDs), widgets_values
|
||||
API format: { "NODE_ID": { class_type, inputs: {field: value_or_[src_id, slot]} } }
|
||||
|
||||
Widget values are embedded directly; linked inputs reference the source node+slot.
|
||||
"""
|
||||
nodes = ui_data.get("nodes", [])
|
||||
links = ui_data.get("links", [])
|
||||
|
||||
# Build link map: link_id -> (src_node_id, src_slot_index)
|
||||
# Links: [link_id, src_node_id, src_slot, dst_node_id, dst_slot, type]
|
||||
link_map = {}
|
||||
for lk in links:
|
||||
if len(lk) >= 4:
|
||||
link_map[lk[0]] = (str(lk[1]), lk[2])
|
||||
|
||||
api = {}
|
||||
for node in nodes:
|
||||
node_id = str(node["id"])
|
||||
class_type = node["type"]
|
||||
inputs_def = node.get("inputs", []) # [{name, type, link, widget?}]
|
||||
widgets_val = node.get("widgets_values", [])
|
||||
|
||||
# We need to figure out which inputs are widget-backed vs link-backed.
|
||||
# ComfyUI heuristic:
|
||||
# - If input has a "widget" key, it is widget-backed (value from widgets_values)
|
||||
# - If input has a "link" key (non-null), it is link-backed
|
||||
# - Some inputs can be either (widget overridable by link)
|
||||
|
||||
api_inputs = {}
|
||||
widget_idx = 0 # index into widgets_values
|
||||
|
||||
for inp in inputs_def:
|
||||
name = inp["name"]
|
||||
link = inp.get("link")
|
||||
has_widget = "widget" in inp
|
||||
|
||||
if link is not None:
|
||||
# Link wins
|
||||
src = link_map.get(link)
|
||||
if src:
|
||||
api_inputs[name] = [src[0], src[1]]
|
||||
else:
|
||||
# Dangling link — fall back to widget value if available
|
||||
if has_widget and widget_idx < len(widgets_val):
|
||||
api_inputs[name] = widgets_val[widget_idx]
|
||||
widget_idx += 1
|
||||
elif has_widget:
|
||||
if widget_idx < len(widgets_val):
|
||||
api_inputs[name] = widgets_val[widget_idx]
|
||||
widget_idx += 1
|
||||
# else: pure output-only input — skip
|
||||
|
||||
# Any remaining widgets_values beyond named widget inputs are for
|
||||
# implicit widget-only nodes (e.g. seed control extra slot "control_after_generate")
|
||||
# We inject them by matching known extra widget names per class_type
|
||||
_inject_extra_widgets(class_type, api_inputs, widgets_val, widget_idx)
|
||||
|
||||
api[node_id] = {
|
||||
"class_type": class_type,
|
||||
"inputs": api_inputs,
|
||||
}
|
||||
|
||||
return api
|
||||
|
||||
|
||||
def _inject_extra_widgets(class_type, api_inputs, widgets_val, start_idx):
|
||||
"""
|
||||
Some nodes have implicit extra widget slots not reflected in the inputs list.
|
||||
The most common: KSampler seed has a hidden 'control_after_generate' slot
|
||||
inserted after noise_seed in widgets_values, but it is NOT in the inputs
|
||||
definition — so our widget_idx counter goes off by 1 after consuming seed.
|
||||
|
||||
We fully re-map widgets_values for known node types that have hidden slots,
|
||||
overwriting anything the loop may have set incorrectly.
|
||||
"""
|
||||
# KSampler: [seed, control_after_generate, steps, cfg, sampler_name, scheduler, denoise]
|
||||
# inputs list has: seed, steps, cfg, sampler_name, scheduler, denoise (no control_after_generate)
|
||||
if class_type == "KSampler" and len(widgets_val) >= 7:
|
||||
api_inputs["seed"] = widgets_val[0]
|
||||
# widgets_val[1] = control_after_generate -- skip
|
||||
api_inputs["steps"] = widgets_val[2]
|
||||
api_inputs["cfg"] = widgets_val[3]
|
||||
api_inputs["sampler_name"] = widgets_val[4]
|
||||
api_inputs["scheduler"] = widgets_val[5]
|
||||
api_inputs["denoise"] = widgets_val[6]
|
||||
|
||||
# KSamplerAdvanced: [add_noise, noise_seed, control_after_generate, steps, cfg,
|
||||
# sampler_name, scheduler, start_at_step, end_at_step, return_with_leftover_noise]
|
||||
elif class_type == "KSamplerAdvanced" and len(widgets_val) >= 10:
|
||||
api_inputs["add_noise"] = widgets_val[0]
|
||||
api_inputs["noise_seed"] = widgets_val[1]
|
||||
# widgets_val[2] = control_after_generate -- skip
|
||||
api_inputs["steps"] = widgets_val[3]
|
||||
api_inputs["cfg"] = widgets_val[4]
|
||||
api_inputs["sampler_name"] = widgets_val[5]
|
||||
api_inputs["scheduler"] = widgets_val[6]
|
||||
api_inputs["start_at_step"] = widgets_val[7]
|
||||
api_inputs["end_at_step"] = widgets_val[8]
|
||||
api_inputs["return_with_leftover_noise"] = widgets_val[9]
|
||||
|
||||
# RandomNoise: [noise_seed, control_after_generate]
|
||||
elif class_type == "RandomNoise" and len(widgets_val) >= 1:
|
||||
api_inputs["noise_seed"] = widgets_val[0]
|
||||
# widgets_val[1] = control_after_generate -- skip
|
||||
|
||||
|
||||
# ── Map generation ───────────────────────────────────────────────────────────
|
||||
|
||||
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 RecipeRenderer to patch values before execution.
|
||||
"""
|
||||
m = {}
|
||||
|
||||
for nid, node in api.items():
|
||||
ct = node["class_type"]
|
||||
inp = node["inputs"]
|
||||
|
||||
# ── Positive / Negative prompts ──────────────────────────────────
|
||||
if ct == "CLIPTextEncode":
|
||||
# Determine pos vs neg by looking at what this feeds into
|
||||
# We'll do a two-pass approach after the loop
|
||||
pass
|
||||
|
||||
# ── Checkpoint loader ─────────────────────────────────────────────
|
||||
if ct in ("CheckpointLoaderSimple", "CheckpointLoader"):
|
||||
m["checkpoint"] = [nid, "ckpt_name"]
|
||||
|
||||
# ── UNET loaders ─────────────────────────────────────────────────
|
||||
if ct in ("UNETLoader", "UNETLoaderGGUF"):
|
||||
if "model_a" not in m:
|
||||
m["model_a"] = [nid, "unet_name"]
|
||||
else:
|
||||
m["model_b"] = [nid, "unet_name"]
|
||||
|
||||
# ── VAE ───────────────────────────────────────────────────────────
|
||||
if ct == "VAELoader":
|
||||
m["vae"] = [nid, "vae_name"]
|
||||
|
||||
# ── CLIP / text encoder ───────────────────────────────────────────
|
||||
if ct in ("CLIPLoader", "DualCLIPLoader"):
|
||||
if ct == "DualCLIPLoader":
|
||||
m["clip_1"] = [nid, "clip_name1"]
|
||||
m["clip_2"] = [nid, "clip_name2"]
|
||||
else:
|
||||
m["clip"] = [nid, "clip_name"]
|
||||
|
||||
# ── Latent size ───────────────────────────────────────────────────
|
||||
if ct in ("EmptyLatentImage", "EmptySD3LatentImage", "EmptyHunyuanLatentVideo"):
|
||||
m["latent_width"] = [nid, "width"]
|
||||
m["latent_height"] = [nid, "height"]
|
||||
if ct == "EmptyHunyuanLatentVideo":
|
||||
m["latent_length"] = [nid, "length"]
|
||||
|
||||
# ── WanImageToVideo latent (i2v) — size comes from Resize node ───
|
||||
if ct == "WanImageToVideo":
|
||||
m["wan_i2v_latent"] = [nid, "start_image"] # image input
|
||||
# width/height fed from resize node — mapped separately
|
||||
|
||||
# ── Resize node (used in i2v for size control) ────────────────────
|
||||
if ct in ("ImageResizeKJv2", "ImageScale", "ImageResize"):
|
||||
if "resize_width" not in m:
|
||||
m["resize_width"] = [nid, "width"]
|
||||
m["resize_height"] = [nid, "height"]
|
||||
|
||||
# ── KSampler (standard) ───────────────────────────────────────────
|
||||
if ct == "KSampler":
|
||||
m["ksampler_seed"] = [nid, "seed"]
|
||||
m["ksampler_steps"] = [nid, "steps"]
|
||||
m["ksampler_cfg"] = [nid, "cfg"]
|
||||
m["ksampler_sampler"] = [nid, "sampler_name"]
|
||||
m["ksampler_scheduler"] = [nid, "scheduler"]
|
||||
m["ksampler_denoise"] = [nid, "denoise"]
|
||||
|
||||
# ── KSamplerAdvanced (WAN dual) ───────────────────────────────────
|
||||
if ct == "KSamplerAdvanced":
|
||||
if "ksampler_high_seed" not in m:
|
||||
m["ksampler_high_seed"] = [nid, "noise_seed"]
|
||||
m["ksampler_high_steps"] = [nid, "steps"]
|
||||
m["ksampler_high_start"] = [nid, "start_at_step"]
|
||||
m["ksampler_high_end"] = [nid, "end_at_step"]
|
||||
m["ksampler_high_cfg"] = [nid, "cfg"]
|
||||
m["ksampler_high_sampler"] = [nid, "sampler_name"]
|
||||
m["ksampler_high_scheduler"] = [nid, "scheduler"]
|
||||
else:
|
||||
m["ksampler_low_seed"] = [nid, "noise_seed"]
|
||||
m["ksampler_low_steps"] = [nid, "steps"]
|
||||
m["ksampler_low_start"] = [nid, "start_at_step"]
|
||||
m["ksampler_low_end"] = [nid, "end_at_step"]
|
||||
m["ksampler_low_cfg"] = [nid, "cfg"]
|
||||
m["ksampler_low_sampler"] = [nid, "sampler_name"]
|
||||
m["ksampler_low_scheduler"] = [nid, "scheduler"]
|
||||
|
||||
# ── Flux / custom samplers ────────────────────────────────────────
|
||||
if ct == "KSamplerSelect":
|
||||
m["flux_sampler"] = [nid, "sampler_name"]
|
||||
if ct in ("BasicScheduler",):
|
||||
m["flux_scheduler"] = [nid, "scheduler"]
|
||||
m["flux_steps"] = [nid, "steps"]
|
||||
m["flux_denoise"] = [nid, "denoise"]
|
||||
if ct == "Flux2Scheduler":
|
||||
m["flux2_steps"] = [nid, "steps"]
|
||||
m["flux2_width"] = [nid, "width"]
|
||||
m["flux2_height"] = [nid, "height"]
|
||||
if ct == "CFGGuider":
|
||||
m["flux2_cfg"] = [nid, "cfg"]
|
||||
if ct == "FluxGuidance":
|
||||
m["flux_guidance"] = [nid, "guidance"]
|
||||
if ct == "RandomNoise":
|
||||
m["flux_seed"] = [nid, "noise_seed"]
|
||||
|
||||
# ── PromptApplyLora ───────────────────────────────────────────────
|
||||
if ct == "PromptApplyLora":
|
||||
if "lora_stack_a" not in m:
|
||||
m["lora_stack_a"] = [nid, "lora_stack_text"]
|
||||
else:
|
||||
m["lora_stack_b"] = [nid, "lora_stack_text"]
|
||||
|
||||
# ── VAEDecode (output image) ───────────────────────────────────────
|
||||
if ct == "VAEDecode":
|
||||
m["vae_decode"] = [nid, None] # source of output IMAGE tensor
|
||||
|
||||
# ── SaveImage → mark for removal ─────────────────────────────────
|
||||
if ct == "SaveImage":
|
||||
m.setdefault("_save_nodes", []).append(nid)
|
||||
|
||||
# ── ModelSamplingSD3 (WAN shift) ──────────────────────────────────
|
||||
if ct == "ModelSamplingSD3":
|
||||
if "wan_shift_a" not in m:
|
||||
m["wan_shift_a"] = [nid, "shift"]
|
||||
else:
|
||||
m["wan_shift_b"] = [nid, "shift"]
|
||||
|
||||
# ── Two-pass: resolve CLIPTextEncode pos/neg by tracing links ────────
|
||||
_resolve_clip_text_encode(api, m)
|
||||
|
||||
return m
|
||||
|
||||
|
||||
def _resolve_clip_text_encode(api, m):
|
||||
"""
|
||||
For CLIPTextEncode nodes, determine which is positive and which is negative
|
||||
by checking what node/slot they feed into.
|
||||
"""
|
||||
# Build reverse link map: (dst_node_id, dst_slot) -> src_node_id
|
||||
# We look at each node's inputs and find CLIPTextEncode sources
|
||||
text_encode_nodes = [nid for nid, n in api.items() if n["class_type"] == "CLIPTextEncode"]
|
||||
if not text_encode_nodes:
|
||||
return
|
||||
|
||||
# For each CLIPTextEncode, check what uses its output
|
||||
# In API format, inputs reference sources as [src_node_id, src_slot]
|
||||
pos_node = None
|
||||
neg_node = None
|
||||
|
||||
for nid, node in api.items():
|
||||
for field, val in node["inputs"].items():
|
||||
if isinstance(val, list) and len(val) == 2:
|
||||
src_nid = str(val[0])
|
||||
if src_nid in text_encode_nodes:
|
||||
if field == "positive" and pos_node is None:
|
||||
pos_node = src_nid
|
||||
elif field == "negative" and neg_node is None:
|
||||
neg_node = src_nid
|
||||
# WanImageToVideo also has positive/negative
|
||||
elif field == "positive":
|
||||
pass
|
||||
elif field == "negative":
|
||||
pass
|
||||
|
||||
# Also handle FluxGuidance — positive goes into conditioning input
|
||||
if pos_node is None:
|
||||
for nid, node in api.items():
|
||||
if node["class_type"] == "FluxGuidance":
|
||||
for field, val in node["inputs"].items():
|
||||
if field == "conditioning" and isinstance(val, list):
|
||||
src = str(val[0])
|
||||
if src in text_encode_nodes:
|
||||
pos_node = src
|
||||
break
|
||||
|
||||
# For ConditioningZeroOut — that's the negative for Flux
|
||||
for nid, node in api.items():
|
||||
if node["class_type"] == "ConditioningZeroOut":
|
||||
neg_node = nid # The output of ConditioningZeroOut is the negative
|
||||
|
||||
if pos_node:
|
||||
m["positive_prompt"] = [pos_node, "text"]
|
||||
if neg_node and api.get(neg_node, {}).get("class_type") == "CLIPTextEncode":
|
||||
m["negative_prompt"] = [neg_node, "text"]
|
||||
elif neg_node and api.get(neg_node, {}).get("class_type") == "ConditioningZeroOut":
|
||||
# For Flux, negative is zero — we patch the CLIPTextEncode feeding into it
|
||||
for nid, node in api.items():
|
||||
if node["class_type"] == "ConditioningZeroOut":
|
||||
for field, val in node["inputs"].items():
|
||||
if isinstance(val, list):
|
||||
src = str(val[0])
|
||||
if api.get(src, {}).get("class_type") == "CLIPTextEncode":
|
||||
m["negative_prompt"] = [src, "text"]
|
||||
break
|
||||
|
||||
# Fallback: if only one CLIPTextEncode, it's positive
|
||||
if pos_node is None and len(text_encode_nodes) >= 1:
|
||||
m["positive_prompt"] = [text_encode_nodes[0], "text"]
|
||||
if neg_node is None and len(text_encode_nodes) >= 2:
|
||||
m["negative_prompt"] = [text_encode_nodes[1], "text"]
|
||||
|
||||
|
||||
# ── Strip SaveImage nodes from API ───────────────────────────────────────────
|
||||
|
||||
def strip_save_nodes(api, map_data):
|
||||
"""Remove SaveImage nodes from the API dict (not needed for in-process execution)."""
|
||||
save_ids = set(map_data.pop("_save_nodes", []))
|
||||
for nid in save_ids:
|
||||
api.pop(nid, None)
|
||||
# Also remove any references to these nodes from other nodes' inputs
|
||||
for node in api.values():
|
||||
node["inputs"] = {
|
||||
k: v for k, v in node["inputs"].items()
|
||||
if not (isinstance(v, list) and len(v) == 2 and str(v[0]) in save_ids)
|
||||
}
|
||||
|
||||
|
||||
# ── Main ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
FAMILY_HINTS = {
|
||||
"sdxl": "sdxl",
|
||||
"flux_1": "flux1",
|
||||
"flux_2": "flux2",
|
||||
"z_image": "zimage",
|
||||
"wan_image": "wan_image",
|
||||
"wan_video_t2v": "wan_video_t2v",
|
||||
"wan_video_i2v": "wan_video_i2v",
|
||||
"qwen_image": "qwen_image",
|
||||
}
|
||||
|
||||
def convert_file(src_path, dst_api_path, dst_map_path, family_hint):
|
||||
with open(src_path, "r", encoding="utf-8") as f:
|
||||
ui_data = json.load(f)
|
||||
|
||||
api = ui_to_api(ui_data)
|
||||
map_data = build_map(api, family_hint)
|
||||
strip_save_nodes(api, map_data)
|
||||
|
||||
with open(dst_api_path, "w", encoding="utf-8") as f:
|
||||
json.dump(api, f, indent=2)
|
||||
|
||||
with open(dst_map_path, "w", encoding="utf-8") as f:
|
||||
json.dump(map_data, f, indent=2)
|
||||
|
||||
print(f" {os.path.basename(src_path)} -> {os.path.basename(dst_api_path)} (map: {os.path.basename(dst_map_path)})")
|
||||
return api, map_data
|
||||
|
||||
|
||||
def main():
|
||||
print(f"Source: {SRC_DIR}")
|
||||
print(f"Destination: {DST_DIR}")
|
||||
print()
|
||||
|
||||
for fname in sorted(os.listdir(SRC_DIR)):
|
||||
if not fname.endswith(".json"):
|
||||
continue
|
||||
stem = fname[:-5] # strip .json
|
||||
if stem in FAMILY_HINTS:
|
||||
hint = FAMILY_HINTS[stem]
|
||||
else:
|
||||
hint = stem
|
||||
|
||||
src_path = os.path.join(SRC_DIR, fname)
|
||||
dst_api_path = os.path.join(DST_DIR, f"{stem}_api.json")
|
||||
dst_map_path = os.path.join(DST_DIR, f"{stem}_map.json")
|
||||
|
||||
try:
|
||||
api, map_data = convert_file(src_path, dst_api_path, dst_map_path, hint)
|
||||
# Print key mappings for review
|
||||
for k, v in sorted(map_data.items()):
|
||||
print(f" {k}: {v}")
|
||||
print()
|
||||
except Exception as e:
|
||||
print(f" ERROR converting {fname}: {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
|
||||
print("Done.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,171 @@
|
||||
"""
|
||||
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, RecipeBuilder, RecipeRenderer.
|
||||
"""
|
||||
import os
|
||||
import re
|
||||
import folder_paths
|
||||
|
||||
|
||||
# Known LoRA file extensions
|
||||
LORA_EXTENSIONS = ['.safetensors', '.ckpt', '.pt', '.bin', '.pth']
|
||||
|
||||
# Tokens to remove for fuzzy matching (case-insensitive)
|
||||
# Order matters: remove longer tokens first to avoid partial matches
|
||||
WAN_TOKENS = ['wan_2_2', 'wan22', 'wan2.2', '20epoc', 'a14b', '14b', 'i2v', 't2v']
|
||||
|
||||
|
||||
def get_available_loras():
|
||||
"""Get all available LoRAs from ComfyUI's folder system."""
|
||||
return folder_paths.get_filename_list("loras")
|
||||
|
||||
|
||||
def normalize_path_separators(path):
|
||||
"""Normalize path separators based on OS - for basename extraction only."""
|
||||
if os.name == 'nt': # Windows
|
||||
return path.replace('/', '\\')
|
||||
else: # Linux/Mac
|
||||
return path.replace('\\', '/')
|
||||
|
||||
|
||||
def strip_lora_extension(name):
|
||||
"""Remove only known LoRA file extensions, not arbitrary dots in names."""
|
||||
name_lower = name.lower()
|
||||
for ext in LORA_EXTENSIONS:
|
||||
if name_lower.endswith(ext):
|
||||
return name[:-len(ext)]
|
||||
return name
|
||||
|
||||
|
||||
def _normalize_name_for_fuzzy(name):
|
||||
"""
|
||||
Remove WAN tokens from name, treating underscores and hyphens as separators.
|
||||
Also removes content in parentheses (e.g., "MyLora (1)" becomes "MyLora").
|
||||
Returns list of remaining non-empty parts in lowercase.
|
||||
"""
|
||||
name_lower = name.lower()
|
||||
|
||||
# Remove anything in parentheses (e.g., " (1)", "(copy)", etc.)
|
||||
name_lower = re.sub(r'\s*\([^)]*\)', '', name_lower)
|
||||
|
||||
# Replace each token with a placeholder to preserve boundaries
|
||||
for token in WAN_TOKENS:
|
||||
# Use word boundary-aware replacement with _ or - as delimiter
|
||||
pattern = rf'(?:^|[_-]){re.escape(token)}(?:[_-]|$)'
|
||||
name_lower = re.sub(pattern, '_', name_lower)
|
||||
|
||||
# Split by underscore or hyphen and filter out empty strings
|
||||
parts = [p for p in re.split(r'[_-]', name_lower) if p]
|
||||
return parts
|
||||
|
||||
|
||||
def fuzzy_match_lora(lora_name, lora_files):
|
||||
"""
|
||||
Attempt to find a matching LoRA using fuzzy matching.
|
||||
Handles renamed LoRAs by removing common WAN-related tokens.
|
||||
|
||||
Example: "DR34LAY_HIGH_V2" can match "DR34LAY_I2V_14B_HIGH_V2"
|
||||
|
||||
Returns (matched_file, True) if available, (None, False) otherwise.
|
||||
"""
|
||||
# Normalize the search name
|
||||
search_parts = _normalize_name_for_fuzzy(strip_lora_extension(lora_name))
|
||||
search_set = set(search_parts)
|
||||
|
||||
# If search_set is empty after normalization, we can't do fuzzy matching
|
||||
if not search_set:
|
||||
return None, False
|
||||
|
||||
candidates = []
|
||||
for lora_file in lora_files:
|
||||
file_name_no_ext = strip_lora_extension(os.path.basename(lora_file))
|
||||
file_parts = _normalize_name_for_fuzzy(file_name_no_ext)
|
||||
file_set = set(file_parts)
|
||||
|
||||
# Check if all search parts are present in the file parts
|
||||
if search_set.issubset(file_set):
|
||||
# Calculate how well this matches (prefer closer matches)
|
||||
extra_parts = len(file_set - search_set)
|
||||
candidates.append((lora_file, file_name_no_ext, extra_parts))
|
||||
|
||||
if not candidates:
|
||||
return None, False
|
||||
|
||||
# If only one match, return it
|
||||
if len(candidates) == 1:
|
||||
return candidates[0][0], True
|
||||
|
||||
# Multiple matches - prefer ones that match i2v/t2v from original if present
|
||||
lora_name_lower = lora_name.lower()
|
||||
has_i2v = 'i2v' in lora_name_lower
|
||||
has_t2v = 't2v' in lora_name_lower
|
||||
|
||||
if has_i2v:
|
||||
i2v_matches = [c for c in candidates if 'i2v' in c[1].lower()]
|
||||
if i2v_matches:
|
||||
candidates = i2v_matches
|
||||
elif has_t2v:
|
||||
t2v_matches = [c for c in candidates if 't2v' in c[1].lower()]
|
||||
if t2v_matches:
|
||||
candidates = t2v_matches
|
||||
|
||||
# Return the match with fewest extra parts (closest match)
|
||||
candidates.sort(key=lambda x: x[2])
|
||||
return candidates[0][0], True
|
||||
|
||||
|
||||
def get_lora_relative_path(lora_name):
|
||||
"""
|
||||
Get the relative path for a LoRA that ComfyUI expects for loading.
|
||||
Returns (relative_path, available) tuple.
|
||||
Supports fuzzy matching for renamed LoRAs.
|
||||
"""
|
||||
lora_files = get_available_loras()
|
||||
|
||||
lora_name_lower = lora_name.lower()
|
||||
|
||||
# Try exact match first
|
||||
for lora_file in lora_files:
|
||||
file_name_no_ext = strip_lora_extension(os.path.basename(lora_file))
|
||||
if file_name_no_ext.lower() == lora_name_lower:
|
||||
return lora_file, True
|
||||
|
||||
# Try fuzzy match for renamed LoRAs
|
||||
fuzzy_match, available = fuzzy_match_lora(lora_name, lora_files)
|
||||
if available:
|
||||
return fuzzy_match, True
|
||||
|
||||
# Not available
|
||||
return lora_name, False
|
||||
|
||||
|
||||
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, available) tuple.
|
||||
"""
|
||||
lora_files = get_available_loras()
|
||||
|
||||
# Try exact match first (with extension, as-is from workflow)
|
||||
for lora_file in lora_files:
|
||||
if lora_file == lora_name:
|
||||
return folder_paths.get_full_path("loras", lora_file), True
|
||||
|
||||
# Try matching by name without extension
|
||||
lora_name_lower = lora_name.lower()
|
||||
for lora_file in lora_files:
|
||||
file_name_no_ext = strip_lora_extension(os.path.basename(lora_file))
|
||||
if file_name_no_ext.lower() == lora_name_lower:
|
||||
return folder_paths.get_full_path("loras", lora_file), True
|
||||
|
||||
# Fuzzy match for renamed LoRAs
|
||||
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
|
||||
@@ -17,33 +17,32 @@ _preferences_cache = {
|
||||
"custom_llama_path": "",
|
||||
"custom_llama_model_path": "",
|
||||
"close_llama_on_exit": True,
|
||||
"custom_llama_port": 8080
|
||||
"custom_llama_port": 8080,
|
||||
"llm_backend": "llama.cpp", # "llama.cpp" or "ollama"
|
||||
"ollama_url": "http://127.0.0.1:11434",
|
||||
"ollama_keep_alive": "5m", # How long Ollama keeps model loaded after request
|
||||
}
|
||||
|
||||
# Predefined models - use real filenames as keys
|
||||
# Qwen3.5 models are unified vision+text — every model supports vision via its mmproj.
|
||||
# "mmproj" is the LOCAL filename we store on disk.
|
||||
# "mmproj_repo_filename" is the filename in the HuggingFace repo (may differ).
|
||||
QWEN_MODELS = {
|
||||
"Qwen3-4B-Q8_0.gguf": {
|
||||
"repo": "Qwen/Qwen3-4B-GGUF"
|
||||
"Qwen3.5-9B-UD-Q4_K_XL.gguf": {
|
||||
"repo": "unsloth/Qwen3.5-9B-GGUF",
|
||||
"mmproj": "mmproj-Qwen3.5-9B-F16.gguf",
|
||||
"mmproj_repo_filename": "mmproj-F16.gguf"
|
||||
},
|
||||
"Qwen3-8B-Q8_0.gguf": {
|
||||
"repo": "Qwen/Qwen3-8B-GGUF"
|
||||
"Qwen3.5-9B-Q8_0.gguf": {
|
||||
"repo": "unsloth/Qwen3.5-9B-GGUF",
|
||||
"mmproj": "mmproj-Qwen3.5-9B-F16.gguf",
|
||||
"mmproj_repo_filename": "mmproj-F16.gguf"
|
||||
},
|
||||
"Qwen3VL-4B-Instruct-Q8_0.gguf": {
|
||||
"repo": "Qwen/Qwen3-VL-4B-Instruct-GGUF",
|
||||
"mmproj": "mmproj-Qwen3VL-4B-Instruct-Q8_0.gguf"
|
||||
"Qwen3.5-9B-UD-Q8_K_XL.gguf": {
|
||||
"repo": "unsloth/Qwen3.5-9B-GGUF",
|
||||
"mmproj": "mmproj-Qwen3.5-9B-F16.gguf",
|
||||
"mmproj_repo_filename": "mmproj-F16.gguf"
|
||||
},
|
||||
"Qwen3VL-8B-Instruct-Q8_0.gguf": {
|
||||
"repo": "Qwen/Qwen3-VL-8B-Instruct-GGUF",
|
||||
"mmproj": "mmproj-Qwen3VL-8B-Instruct-Q8_0.gguf"
|
||||
},
|
||||
"Qwen3VL-4B-Thinking-Q8_0.gguf": {
|
||||
"repo": "Qwen/Qwen3-VL-4B-Thinking-GGUF",
|
||||
"mmproj": "mmproj-Qwen3VL-4B-Thinking-Q8_0.gguf"
|
||||
},
|
||||
"Qwen3VL-8B-Thinking-Q8_0.gguf": {
|
||||
"repo": "Qwen/Qwen3-VL-8B-Thinking-GGUF",
|
||||
"mmproj": "mmproj-Qwen3VL-8B-Thinking-Q8_0.gguf"
|
||||
}
|
||||
}
|
||||
|
||||
@server.PromptServer.instance.routes.get("/prompt-manager/load-preferences")
|
||||
@@ -65,7 +64,10 @@ async def save_preference(request):
|
||||
"custom_llama_path",
|
||||
"custom_llama_model_path",
|
||||
"close_llama_on_exit",
|
||||
"custom_llama_port"]:
|
||||
"custom_llama_port",
|
||||
"llm_backend",
|
||||
"ollama_url",
|
||||
"ollama_keep_alive"]:
|
||||
return server.web.json_response({"success": False, "error": "Invalid preference key"})
|
||||
|
||||
# Update in-memory cache
|
||||
@@ -76,6 +78,18 @@ async def save_preference(request):
|
||||
print(f"[Model Manager] Error saving preference: {e}")
|
||||
return server.web.json_response({"success": False, "error": str(e)}, status=500)
|
||||
|
||||
|
||||
@server.PromptServer.instance.routes.get("/prompt-manager/ollama-models")
|
||||
async def list_ollama_models(request):
|
||||
"""API endpoint to discover available Ollama models."""
|
||||
try:
|
||||
from .ollama_wrapper import discover_ollama_models
|
||||
models, status = discover_ollama_models(_preferences_cache)
|
||||
return server.web.json_response({"models": models, "status": status})
|
||||
except Exception as e:
|
||||
return server.web.json_response({"models": [], "status": f"Error: {e}"}, status=500)
|
||||
|
||||
|
||||
def get_models_directory():
|
||||
"""Get the path to the primary models directory (ComfyUI/models/gguf) for downloads"""
|
||||
# Register both gguf and LLM folders
|
||||
@@ -176,41 +190,117 @@ def get_model_path(model_name):
|
||||
models_dir = get_models_directory()
|
||||
return os.path.join(models_dir, model_name)
|
||||
|
||||
# Quantization-related filename parts — stripped when matching models to mmproj files
|
||||
_QUANT_PARTS = frozenset({
|
||||
"Q2", "Q3", "Q4", "Q5", "Q6", "Q8",
|
||||
"K", "M", "S", "L", "XS", "XL", "XXS", "XXL",
|
||||
"IQ1", "IQ2", "IQ3", "IQ4", "NL",
|
||||
"BF16", "F16", "F32",
|
||||
"0", "1", "UD",
|
||||
})
|
||||
|
||||
|
||||
def _get_model_keywords(name):
|
||||
"""Extract normalised keyword set from a model filename for fuzzy matching.
|
||||
|
||||
Splits on hyphens, underscores, dots, and spaces, lowercases everything,
|
||||
and strips quantisation tags + the literal 'mmproj' token.
|
||||
|
||||
Example: 'qwen3.5-9b-nsfw-captioning-v3.Q8_0.gguf'
|
||||
→ {'qwen3.5', '9b', 'nsfw', 'captioning', 'v3'}
|
||||
'qwen3.5-9b-nsfw-captioning-v3.mmproj-Q8_0.gguf'
|
||||
→ {'qwen3.5', '9b', 'nsfw', 'captioning', 'v3'}
|
||||
"""
|
||||
base = os.path.splitext(os.path.basename(name))[0]
|
||||
# First split on hyphens, underscores, spaces (not dots)
|
||||
raw_parts = [p for p in re.split(r"[-_ ]", base) if p]
|
||||
# Then split tokens on dots, UNLESS the token is a version string like 'qwen3.5'
|
||||
parts = []
|
||||
for token in raw_parts:
|
||||
if re.match(r'^[a-zA-Z]+\d+\.\d+$', token):
|
||||
# Version string (e.g. 'qwen3.5') — keep intact
|
||||
parts.append(token)
|
||||
elif '.' in token:
|
||||
# Split other dotted tokens (e.g. 'v3.Q8' → 'v3', 'Q8')
|
||||
parts.extend(p for p in token.split('.') if p)
|
||||
else:
|
||||
parts.append(token)
|
||||
lc_quant = {q.lower() for q in _QUANT_PARTS}
|
||||
return {p.lower() for p in parts if p.lower() not in lc_quant and p.lower() != "mmproj" and p.lower() != "gguf"}
|
||||
|
||||
|
||||
def get_mmproj_for_model(model_name):
|
||||
"""Get the mmproj filename for a given vision model"""
|
||||
"""Get the mmproj filename for a given model from the predefined registry."""
|
||||
if model_name in QWEN_MODELS and "mmproj" in QWEN_MODELS[model_name]:
|
||||
return QWEN_MODELS[model_name]["mmproj"]
|
||||
return None
|
||||
|
||||
|
||||
def get_mmproj_path(model_name):
|
||||
"""Get the path to the mmproj file for a vision model, if it exists
|
||||
Searches for mmproj files that contain all parts of the model name
|
||||
"""Get the path to the mmproj file for a model, if it exists.
|
||||
|
||||
1. Check the explicit QWEN_MODELS mapping first.
|
||||
2. Fall back to heuristic matching by model identity (strips quant parts).
|
||||
"""
|
||||
# Get all parts of the model name (excluding .gguf)
|
||||
model_parts = [part for part in re.split(r"[-.]", os.path.splitext(os.path.basename(model_name))[0]) if part]
|
||||
# --- 1. Explicit mapping ---
|
||||
mmproj_name = get_mmproj_for_model(model_name)
|
||||
if mmproj_name:
|
||||
all_dirs = get_all_model_directories()
|
||||
for d in all_dirs:
|
||||
p = os.path.join(d, mmproj_name)
|
||||
if os.path.exists(p):
|
||||
return p
|
||||
# Mapped but file not found on disk
|
||||
return None
|
||||
|
||||
# --- 2. Heuristic: keyword-based matching ---
|
||||
# Split the model name into normalised keywords (no quant tags, no 'mmproj')
|
||||
# and find the mmproj file that shares the most keywords (minimum 4).
|
||||
model_keywords = _get_model_keywords(model_name)
|
||||
if len(model_keywords) < 2:
|
||||
return None
|
||||
|
||||
MIN_KEYWORD_MATCH = min(4, len(model_keywords)) # at least 4, or all if fewer
|
||||
|
||||
# Get all local mmproj files
|
||||
all_dirs = get_all_model_directories()
|
||||
mmproj_files = []
|
||||
best_match = None
|
||||
best_match_count = 0
|
||||
for models_dir in all_dirs:
|
||||
if os.path.exists(models_dir):
|
||||
for f in os.listdir(models_dir):
|
||||
if 'mmproj' in f.lower() and f.endswith('.gguf'):
|
||||
mmproj_files.append(f)
|
||||
if not os.path.exists(models_dir):
|
||||
continue
|
||||
for f in os.listdir(models_dir):
|
||||
if 'mmproj' not in f.lower() or not f.endswith('.gguf'):
|
||||
continue
|
||||
mmproj_keywords = _get_model_keywords(f)
|
||||
common = model_keywords & mmproj_keywords
|
||||
if len(common) >= MIN_KEYWORD_MATCH and len(common) > best_match_count:
|
||||
best_match = os.path.join(models_dir, f)
|
||||
best_match_count = len(common)
|
||||
|
||||
# Find mmproj that contains all model parts
|
||||
for mmproj_file in mmproj_files:
|
||||
# Let's split the mmproj filename to check for matching bits, we remove extension and mmproj
|
||||
mmproj_parts = [part for part in re.split(r"[-.]", os.path.splitext(os.path.basename(mmproj_file))[0].replace('mmproj', '')) if part]
|
||||
if all(part in mmproj_parts for part in model_parts):
|
||||
return get_model_path(mmproj_file)
|
||||
return best_match
|
||||
|
||||
|
||||
def has_vision_support(model_name):
|
||||
"""Check whether a model has vision capabilities.
|
||||
|
||||
Returns True if an mmproj file is available (on disk or in the registry).
|
||||
"""
|
||||
# Check explicit registry first (even if not yet downloaded)
|
||||
if get_mmproj_for_model(model_name):
|
||||
return True
|
||||
# Check if a matching mmproj file already exists on disk
|
||||
return get_mmproj_path(model_name) is not None
|
||||
|
||||
def download_model(model_name):
|
||||
"""Download a model from HuggingFace with automatic progress display
|
||||
For VL models, also downloads the matching mmproj file if needed
|
||||
"""Download a model from HuggingFace with automatic progress display.
|
||||
Also downloads the matching mmproj file if one is defined.
|
||||
|
||||
The mmproj file in the repo may have a generic name (e.g. 'mmproj-F16.gguf').
|
||||
We rename it on download to a model-specific name to avoid conflicts when
|
||||
multiple model sizes are installed side-by-side.
|
||||
|
||||
Args:
|
||||
model_name: Filename of the model (e.g., "Qwen3-4B-Q8_0.gguf")
|
||||
model_name: Filename of the model (e.g., 'Qwen3.5-9B-Q8_0.gguf')
|
||||
|
||||
Returns:
|
||||
Path to downloaded model or None on error
|
||||
@@ -224,38 +314,44 @@ def download_model(model_name):
|
||||
models_dir = get_models_directory()
|
||||
|
||||
# Build list of files to download
|
||||
# Each entry: repo_filename (name in the HF repo), local_filename (name on disk), desc
|
||||
files_to_download = [
|
||||
{"filename": model_name, "desc": "Downloading model"}
|
||||
{"repo_filename": model_name, "local_filename": model_name, "desc": "Downloading model"}
|
||||
]
|
||||
|
||||
# Add mmproj file if this is a VL model
|
||||
mmproj_name = get_mmproj_for_model(model_name)
|
||||
if mmproj_name:
|
||||
# Add mmproj file if this model has one
|
||||
mmproj_local = get_mmproj_for_model(model_name)
|
||||
if mmproj_local:
|
||||
mmproj_repo = model_info.get("mmproj_repo_filename", mmproj_local)
|
||||
files_to_download.append({
|
||||
"filename": mmproj_name,
|
||||
"repo_filename": mmproj_repo,
|
||||
"local_filename": mmproj_local,
|
||||
"desc": "Downloading mmproj"
|
||||
})
|
||||
|
||||
# Download each file if it doesn't exist
|
||||
for file_info in files_to_download:
|
||||
filename = file_info["filename"]
|
||||
local_path = os.path.join(models_dir, filename)
|
||||
repo_filename = file_info["repo_filename"]
|
||||
local_filename = file_info["local_filename"]
|
||||
local_path = os.path.join(models_dir, local_filename)
|
||||
|
||||
if os.path.exists(local_path):
|
||||
print(f"[Model Manager] File already exists: {filename}")
|
||||
print(f"[Model Manager] File already exists: {local_filename}")
|
||||
continue
|
||||
|
||||
# Download the file
|
||||
try:
|
||||
print(f"[Model Manager] Downloading {filename} from {repo_id}...")
|
||||
print(f"[Model Manager] Downloading {repo_filename} from {repo_id}...")
|
||||
api = HfApi()
|
||||
repo_info = api.repo_info(repo_id=repo_id, files_metadata=True)
|
||||
file_metadata = next((f for f in repo_info.siblings if f.rfilename == filename), None)
|
||||
repo_info_obj = api.repo_info(repo_id=repo_id, files_metadata=True)
|
||||
file_metadata = next((f for f in repo_info_obj.siblings if f.rfilename == repo_filename), None)
|
||||
if not file_metadata or file_metadata.size is None:
|
||||
print(f"[Model Manager] Could not find file size for {filename} in {repo_id}")
|
||||
print(f"[Model Manager] Could not find file size for {repo_filename} in {repo_id}")
|
||||
return None
|
||||
total_size = file_metadata.size
|
||||
download_url = f"https://huggingface.co/{repo_id}/resolve/main/{filename}"
|
||||
download_url = f"https://huggingface.co/{repo_id}/resolve/main/{repo_filename}"
|
||||
if local_filename != repo_filename:
|
||||
print(f"[Model Manager] Will save as: {local_filename}")
|
||||
pbar = tqdm(total=total_size, unit="B", unit_scale=True, desc=file_info["desc"])
|
||||
with requests.get(download_url, stream=True) as r, open(local_path, "wb") as f:
|
||||
r.raise_for_status()
|
||||
@@ -264,9 +360,9 @@ def download_model(model_name):
|
||||
f.write(chunk)
|
||||
pbar.update(len(chunk))
|
||||
pbar.close()
|
||||
print(f"[Model Manager] Successfully downloaded {filename}")
|
||||
print(f"[Model Manager] Successfully downloaded {local_filename}")
|
||||
except Exception as e:
|
||||
print(f"[Model Manager] Error downloading {filename}: {e}")
|
||||
print(f"[Model Manager] Error downloading {repo_filename}: {e}")
|
||||
return None
|
||||
|
||||
return os.path.join(models_dir, model_name)
|
||||
@@ -0,0 +1,198 @@
|
||||
"""
|
||||
Ollama integration for ComfyUI Prompt Manager.
|
||||
|
||||
Provides model discovery, generation, and memory management
|
||||
via Ollama's native API and OpenAI-compatible endpoint.
|
||||
"""
|
||||
import requests
|
||||
import json
|
||||
|
||||
# ============================================================================
|
||||
# Default endpoints
|
||||
# ============================================================================
|
||||
|
||||
DEFAULT_OLLAMA_URL = "http://127.0.0.1:11434"
|
||||
|
||||
|
||||
def _get_ollama_base(user_config):
|
||||
"""Resolve Ollama base URL (without /v1 or /api) from config."""
|
||||
url = str(user_config.get("ollama_url", DEFAULT_OLLAMA_URL)).strip().rstrip("/")
|
||||
if not url:
|
||||
url = DEFAULT_OLLAMA_URL
|
||||
# Strip trailing /v1 or /api paths so we always have the root
|
||||
for suffix in ("/v1", "/api", "/api/tags", "/api/chat"):
|
||||
if url.endswith(suffix):
|
||||
url = url[: -len(suffix)]
|
||||
break
|
||||
return url
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Model discovery
|
||||
# ============================================================================
|
||||
|
||||
def discover_ollama_models(user_config):
|
||||
"""Query Ollama for available models.
|
||||
|
||||
Returns:
|
||||
(list_of_model_names, status_message)
|
||||
"""
|
||||
base = _get_ollama_base(user_config)
|
||||
tags_url = f"{base}/api/tags"
|
||||
timeout = 12
|
||||
|
||||
try:
|
||||
response = requests.get(tags_url, timeout=timeout)
|
||||
if response.status_code == 200:
|
||||
payload = response.json()
|
||||
names = []
|
||||
if isinstance(payload, dict):
|
||||
for item in payload.get("models", []):
|
||||
if isinstance(item, dict):
|
||||
name = item.get("model") or item.get("name")
|
||||
if isinstance(name, str) and name.strip():
|
||||
names.append(name.strip())
|
||||
if names:
|
||||
unique = sorted(set(names), key=lambda x: x.lower())
|
||||
return unique, f"Found {len(unique)} Ollama model(s)."
|
||||
return [], "Ollama responded but no models were found. Pull one first, e.g. `ollama pull llama3.1`."
|
||||
return [], f"Ollama returned HTTP {response.status_code}."
|
||||
except requests.exceptions.ConnectionError:
|
||||
return [], f"Could not connect to Ollama at {base}. Start `ollama serve` and retry."
|
||||
except requests.exceptions.Timeout:
|
||||
return [], f"Timed out querying Ollama at {base}."
|
||||
except Exception as e:
|
||||
return [], f"Failed to query Ollama models: {e}"
|
||||
|
||||
|
||||
def is_ollama_available(user_config):
|
||||
"""Check if Ollama is reachable."""
|
||||
base = _get_ollama_base(user_config)
|
||||
try:
|
||||
resp = requests.get(f"{base}/api/tags", timeout=5)
|
||||
return resp.status_code == 200
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Generation (OpenAI-compatible chat/completions via Ollama)
|
||||
# ============================================================================
|
||||
|
||||
def generate_chat(user_config, model_name, messages, temperature=0.8,
|
||||
top_k=40, top_p=0.95, min_p=0.05, repeat_penalty=1.0,
|
||||
seed=None, stream=True, timeout=120,
|
||||
use_model_defaults=True, enable_thinking=False):
|
||||
"""Send a chat completion request to Ollama's OpenAI-compatible endpoint.
|
||||
|
||||
Args:
|
||||
user_config: preferences dict with ollama_url, ollama_keep_alive, etc.
|
||||
model_name: Ollama model tag (e.g. "llama3.1:latest")
|
||||
messages: list of {role, content} dicts (OpenAI format)
|
||||
stream: if True, returns a streaming response iterator
|
||||
timeout: request timeout in seconds
|
||||
|
||||
Returns:
|
||||
If stream=False: (response_text, thinking_text, usage_stats, error_msg)
|
||||
If stream=True: (response_object, error_msg) — caller handles streaming
|
||||
"""
|
||||
base = _get_ollama_base(user_config)
|
||||
url = f"{base}/v1/chat/completions"
|
||||
|
||||
payload = {
|
||||
"model": model_name,
|
||||
"messages": messages,
|
||||
"stream": stream,
|
||||
}
|
||||
|
||||
# Set keep_alive to control how long the model stays loaded after this request
|
||||
keep_alive = user_config.get("ollama_keep_alive", "5m")
|
||||
if keep_alive:
|
||||
payload["keep_alive"] = keep_alive
|
||||
|
||||
if stream:
|
||||
payload["stream_options"] = {"include_usage": True}
|
||||
|
||||
if seed is not None:
|
||||
payload["seed"] = seed
|
||||
|
||||
if enable_thinking:
|
||||
payload["chat_template_kwargs"] = {"enable_thinking": True}
|
||||
|
||||
if not use_model_defaults:
|
||||
payload["temperature"] = temperature
|
||||
payload["top_k"] = top_k
|
||||
payload["top_p"] = top_p
|
||||
payload["min_p"] = min_p
|
||||
payload["repeat_penalty"] = repeat_penalty
|
||||
|
||||
try:
|
||||
response = requests.post(url, json=payload, timeout=timeout, stream=stream)
|
||||
if response.status_code != 200:
|
||||
detail = _extract_error(response)
|
||||
return (None, f"Ollama request failed ({response.status_code}): {detail}")
|
||||
if stream:
|
||||
return (response, None)
|
||||
else:
|
||||
result = response.json()
|
||||
text = result["choices"][0]["message"]["content"]
|
||||
usage = result.get("usage")
|
||||
return (text.strip(), "", usage, None)
|
||||
except requests.exceptions.ConnectionError:
|
||||
return (None, "Could not connect to Ollama. Start 'ollama serve' and retry.")
|
||||
except requests.exceptions.Timeout:
|
||||
return (None, f"Ollama request timed out ({timeout}s). Try a shorter prompt or smaller model.")
|
||||
except (KeyError, IndexError):
|
||||
return (None, "Unexpected response format from Ollama.")
|
||||
except Exception as e:
|
||||
return (None, f"Ollama generation failed: {e}")
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Memory management — unload model from Ollama VRAM
|
||||
# ============================================================================
|
||||
|
||||
def unload_model(user_config, model_name):
|
||||
"""Tell Ollama to unload a model from memory (free VRAM).
|
||||
|
||||
Uses the /api/generate endpoint with keep_alive=0 to immediately
|
||||
evict the model from GPU memory.
|
||||
"""
|
||||
base = _get_ollama_base(user_config)
|
||||
url = f"{base}/api/generate"
|
||||
|
||||
try:
|
||||
response = requests.post(url, json={
|
||||
"model": model_name,
|
||||
"keep_alive": 0,
|
||||
}, timeout=15)
|
||||
if response.status_code == 200:
|
||||
return True, f"Model '{model_name}' unloaded from Ollama memory."
|
||||
return False, f"Ollama returned HTTP {response.status_code} while unloading model."
|
||||
except requests.exceptions.ConnectionError:
|
||||
return False, "Could not connect to Ollama to unload model."
|
||||
except Exception as e:
|
||||
return False, f"Failed to unload model from Ollama: {e}"
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Helpers
|
||||
# ============================================================================
|
||||
|
||||
def _extract_error(response):
|
||||
"""Extract error message from an Ollama error response."""
|
||||
try:
|
||||
payload = response.json()
|
||||
except ValueError:
|
||||
text = (response.text or "").strip()
|
||||
return text[:300] if text else f"HTTP {response.status_code}"
|
||||
|
||||
if isinstance(payload, dict):
|
||||
err = payload.get("error")
|
||||
if isinstance(err, str) and err.strip():
|
||||
return err.strip()
|
||||
msg = payload.get("message")
|
||||
if isinstance(msg, str) and msg.strip():
|
||||
return msg.strip()
|
||||
|
||||
return f"HTTP {response.status_code}"
|
||||
@@ -0,0 +1,385 @@
|
||||
"""
|
||||
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.
|
||||
"""
|
||||
|
||||
import json
|
||||
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",
|
||||
"VAE",
|
||||
"LATENT",
|
||||
"IMAGE",
|
||||
"MASK",
|
||||
"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."""
|
||||
if isinstance(value, dict):
|
||||
return {
|
||||
k: _strip_runtime_keys_deep(v)
|
||||
for k, v in value.items()
|
||||
if k not in RUNTIME_OBJECT_KEYS
|
||||
}
|
||||
if isinstance(value, list):
|
||||
return [_strip_runtime_keys_deep(v) for v in value]
|
||||
if isinstance(value, tuple):
|
||||
return [_strip_runtime_keys_deep(v) for v in value]
|
||||
if isinstance(value, set):
|
||||
return [_strip_runtime_keys_deep(v) for v in value]
|
||||
return value
|
||||
|
||||
|
||||
def strip_runtime_objects(wf):
|
||||
"""Return a deep copy of wf with all runtime object keys removed.
|
||||
|
||||
Use before JSON serialization (saving prompts, send_sync to JS, etc.).
|
||||
"""
|
||||
if not isinstance(wf, dict):
|
||||
return wf
|
||||
return _strip_runtime_keys_deep(wf)
|
||||
|
||||
|
||||
def _json_default(value):
|
||||
"""Best-effort fallback for objects that JSON cannot encode directly."""
|
||||
if isinstance(value, (set, tuple)):
|
||||
return list(value)
|
||||
if isinstance(value, bytes):
|
||||
return value.decode("utf-8", errors="replace")
|
||||
return str(value)
|
||||
|
||||
|
||||
def to_json_safe_workflow_data(wf):
|
||||
"""Return a deep JSON-safe copy of workflow data with runtime keys removed.
|
||||
|
||||
This is stricter than strip_runtime_objects(): it also sanitizes nested
|
||||
containers and unknown object types so metadata embedding cannot fail
|
||||
during Save Image serialization.
|
||||
"""
|
||||
if not isinstance(wf, dict):
|
||||
return {}
|
||||
|
||||
stripped = strip_runtime_objects(wf)
|
||||
|
||||
# Normalize NaN/Inf because Python's json allows them by default but strict
|
||||
# JSON consumers may reject them.
|
||||
def _normalize_numbers(value):
|
||||
if isinstance(value, float) and (math.isnan(value) or math.isinf(value)):
|
||||
return None
|
||||
if isinstance(value, dict):
|
||||
return {k: _normalize_numbers(v) for k, v in value.items()}
|
||||
if isinstance(value, list):
|
||||
return [_normalize_numbers(v) for v in value]
|
||||
if isinstance(value, tuple):
|
||||
return [_normalize_numbers(v) for v in value]
|
||||
if isinstance(value, set):
|
||||
return [_normalize_numbers(v) for v in value]
|
||||
return value
|
||||
|
||||
normalized = _normalize_numbers(stripped)
|
||||
|
||||
try:
|
||||
return json.loads(json.dumps(normalized, default=_json_default, allow_nan=False))
|
||||
except Exception:
|
||||
# Last-resort safety: stringify opaque values while preserving structure.
|
||||
return json.loads(json.dumps(str(normalized)))
|
||||
@@ -0,0 +1,502 @@
|
||||
"""
|
||||
Model family definitions and compatibility helpers for ComfyUI Prompt Manager.
|
||||
|
||||
Shared by workflow_builder, workflow_renderer, and workflow_extraction_utils.
|
||||
|
||||
Each family dict specifies:
|
||||
"label" — human-readable name shown in UI dropdowns
|
||||
"folders" — lowercase path prefixes (matched against relative model path)
|
||||
"names" — lowercase substrings matched against filename only
|
||||
"vae" — VAE filename substrings compatible with this family
|
||||
"vae_exact" — VAE exact basenames (full filename match, e.g. "ae.safetensors")
|
||||
"clip" — CLIP/text-encoder filename substrings compatible with this family
|
||||
"clip_exact" — CLIP exact basenames (full filename match)
|
||||
"clip_exclude" — substrings that DISQUALIFY a CLIP match (applied after include patterns)
|
||||
"clip_type" — CLIPType key passed to comfy.sd.load_clip (e.g. "flux", "wan")
|
||||
"clip_slots" — number of distinct CLIP files needed (default 1; flux1/sdxl need 2)
|
||||
"sampler" — internal sampling strategy key (see SAMPLER_STRATEGIES below)
|
||||
|
||||
Matching rules:
|
||||
VAE: vae_exact checked first (full basename), then vae substring patterns.
|
||||
CLIP: clip_exclude applied first — any match disqualifies the file.
|
||||
Then clip_exact checked (full basename), then clip substring patterns.
|
||||
Folder prefixes checked before name patterns. First match wins for family detection.
|
||||
To add a new family: add a dict entry and handle its "sampler" key in workflow_builder.
|
||||
"""
|
||||
import os
|
||||
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",
|
||||
"folders": ["klein/", "flux2/"],
|
||||
"names": ["flux2", "flux-2", "flux_2", "klein", "flux.2"],
|
||||
# Flux2/Klein uses its own VAE — NOT ae.safetensors
|
||||
"vae": ["flux2-vae", "flux2_vae"],
|
||||
# Klein uses Qwen text encoders (NOT T5/CLIP-L):
|
||||
# 4B model → qwen_3_4b.safetensors
|
||||
# 9B model → qwen_3_8b_fp8mixed.safetensors
|
||||
# CLIPLoader type must be "flux2" so CLIPType.FLUX2 is used.
|
||||
"clip": ["qwen_3_8b"],
|
||||
"clip_exclude": ["qwen_2.5", "qwen_2_5", "qwen_3_4b", "t5xxl", "umt5", "clip_l", "clip_g", "gemma"],
|
||||
"clip_type": "flux2",
|
||||
"sampler": "flux2",
|
||||
},
|
||||
# ── Flux 1 (Dev + Schnell merged) ────────────────────────────────────────
|
||||
"flux1": {
|
||||
"label": "Flux 1",
|
||||
"folders": ["flux/", "flux1/"],
|
||||
"names": ["flux-dev", "flux_dev", "fluxdev", "flux1-dev", "flux1_dev",
|
||||
"flux-schnell", "flux_schnell", "fluxschnell", "flux1-schnell",
|
||||
"flux1_schnell", "flux1-", "flux1_", "flux.1"],
|
||||
# ae.safetensors is the canonical Flux1 VAE — exact match required to
|
||||
# avoid catching "mae.safetensors" or other short-named files.
|
||||
"vae": [],
|
||||
"vae_exact": ["ae.safetensors"],
|
||||
# Flux1 uses T5-XXL + CLIP-L dual encoders.
|
||||
# umt5_xxl also contains "t5xxl" as substring — exclude it explicitly.
|
||||
"clip": ["t5xxl"],
|
||||
"clip_exclude": ["umt5", "clip_l", "clip_g", "qwen", "gemma", "awq-int"],
|
||||
"clip_type": "flux",
|
||||
"clip_slots": 2,
|
||||
"sampler": "flux",
|
||||
},
|
||||
# ── Z-Image (Base + Turbo merged) ────────────────────────────────────────
|
||||
"zimage": {
|
||||
"label": "Z-Image",
|
||||
"folders": ["zib/", "zit/", "zimage/"],
|
||||
"names": ["z_image", "z-image", "zimage", "blitz"],
|
||||
# Z-Image shares ae.safetensors with Flux1 for its base VAE.
|
||||
"vae": ["zimageturbo_vae"],
|
||||
"vae_exact": ["ae.safetensors"],
|
||||
# Z-Image uses Qwen 3 4B as its text encoder (not the larger 8B,
|
||||
# not T5, not CLIP-L). The 4B file is typically named
|
||||
# "qwen-4b-zimage.safetensors" or "qwen_3_4b.safetensors".
|
||||
"clip": ["qwen-4b-zimage", "qwen_3_4b"],
|
||||
"clip_exclude": ["qwen_3_8b", "qwen_2.5", "qwen_2_5", "t5xxl", "umt5",
|
||||
"clip_l", "clip_g", "gemma"],
|
||||
"clip_type": "lumina2",
|
||||
"sampler": "zimage",
|
||||
},
|
||||
# ── WAN 2.x Video — Image-to-Video (dual KSampler + i2v latent) ──────────
|
||||
"wan_video_i2v": {
|
||||
"label": "WAN Video (i2v)",
|
||||
"folders": ["wan2_2/i2v/", "wan2_1/i2v/"],
|
||||
"names": ["wan2.2_i2v", "wan2.1_i2v", "wan_i2v", "i2v"],
|
||||
"vae": ["wan_2.1_vae", "wan2.1_vae", "wan2.1-vae", "wan_2.1-vae"],
|
||||
"clip": ["umt5_xxl", "umt5-xxl"],
|
||||
"clip_exclude": ["t5xxl", "clip_l", "clip_g", "qwen", "gemma"],
|
||||
"clip_type": "wan",
|
||||
"sampler": "wan_video",
|
||||
},
|
||||
# ── WAN 2.x Video — Text-to-Video (dual KSampler) ────────────────────────
|
||||
# DETECTION PRIORITY: must appear before wan_image — they share the same
|
||||
# folders/names, so first-match wins. Auto-detected T2V models land here;
|
||||
# user selects wan_image explicitly from the family dropdown.
|
||||
"wan_video_t2v": {
|
||||
"label": "WAN Video (t2v)",
|
||||
"folders": ["wan2_2/", "wan2_1/", "wan/"],
|
||||
"names": ["wan2.2", "wan2.1", "wan2_2", "wan2_1", "wanvideo", "wan_t2v",
|
||||
"wan2.2_t2v", "wan2.1_t2v"],
|
||||
"vae": ["wan_2.1_vae", "wan2.1_vae", "wan2.1-vae", "wan_2.1-vae"],
|
||||
"clip": ["umt5_xxl", "umt5-xxl"],
|
||||
"clip_exclude": ["t5xxl", "clip_l", "clip_g", "qwen", "gemma"],
|
||||
"clip_type": "wan",
|
||||
"sampler": "wan_video",
|
||||
},
|
||||
# ── WAN 2.x Image (single KSampler, text-to-image) ──────────────────────
|
||||
# Same model files as WAN Video T2V — identical folders/names/vae/clip.
|
||||
# Must appear AFTER wan_video_t2v so auto-detection resolves T2V models
|
||||
# to wan_video_t2v. User picks this family explicitly for still images.
|
||||
# Sampler stays wan_image (single KSampler, no dual Steps rows).
|
||||
"wan_image": {
|
||||
"label": "WAN Image",
|
||||
"folders": ["wan2_2/", "wan2_1/", "wan/"],
|
||||
"names": ["wan2.2", "wan2.1", "wan2_2", "wan2_1", "wanvideo", "wan_t2v",
|
||||
"wan2.2_t2v", "wan2.1_t2v"],
|
||||
"vae": ["wan_2.1_vae", "wan2.1_vae", "wan2.1-vae", "wan_2.1-vae"],
|
||||
# WAN uses UMT5-XXL exclusively — NOT t5xxl, NOT clip_l/g.
|
||||
"clip": ["umt5_xxl", "umt5-xxl"],
|
||||
"clip_exclude": ["t5xxl", "clip_l", "clip_g", "qwen", "gemma"],
|
||||
"clip_type": "wan",
|
||||
"sampler": "wan_image",
|
||||
},
|
||||
# ── LTX-Video ────────────────────────────────────────────────────────────
|
||||
"ltxv": {
|
||||
"label": "LTX-Video",
|
||||
"folders": ["ltx/"],
|
||||
"names": ["ltxv", "ltx-video", "ltx-2", "ltx2"],
|
||||
# LTX has its own VAE — NOT ae.safetensors, NOT SDXL/SD VAE.
|
||||
# taeltx* are TAE-based approximation VAEs for LTX.
|
||||
"vae": ["ltx23_video_vae", "ltxv_vae", "ltx_vae", "taeltx"],
|
||||
# LTX-Video uses T5-XXL only (same encoder family as Flux1 but
|
||||
# NOT the dual CLIP-L+T5 combo — single T5 only).
|
||||
# umt5_xxl contains "t5xxl" → must exclude it.
|
||||
"clip": ["t5xxl"],
|
||||
"clip_exclude": ["umt5", "clip_l", "clip_g", "qwen", "gemma"],
|
||||
"clip_type": "sd3",
|
||||
"sampler": "flux",
|
||||
},
|
||||
# ── SDXL (+ Pony, Illustrious, Turbo merged) ────────────────────────────
|
||||
"sdxl": {
|
||||
"label": "SDXL",
|
||||
"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 variant.
|
||||
"vae": ["sdxl_vae", "sdxl-vae", "vae-ft-mse"],
|
||||
# SDXL uses dual text encoders: CLIP-L + CLIP-G.
|
||||
"clip": ["clip_l", "clip_g"],
|
||||
"clip_exclude": ["t5xxl", "umt5", "qwen", "gemma"],
|
||||
"sampler": "standard",
|
||||
"checkpoint": True,
|
||||
},
|
||||
# ── Qwen Image ───────────────────────────────────────────────────────────
|
||||
"qwen_image": {
|
||||
"label": "Qwen Image",
|
||||
"folders": ["qwen/"],
|
||||
"names": ["qwen_image"],
|
||||
"vae": ["qwen_image_vae"],
|
||||
"clip": ["qwen_2.5_vl", "qwen_2_5_vl"],
|
||||
"clip_exclude": ["qwen_3", "t5xxl", "umt5", "clip_l", "clip_g", "gemma"],
|
||||
"clip_type": "qwen_image",
|
||||
"sampler": "standard",
|
||||
},
|
||||
}
|
||||
|
||||
# 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
|
||||
{"flux2"}, # Flux2 — all merged
|
||||
{"wan_image", "wan_video_t2v"}, # WAN Image shares T2V model files
|
||||
]
|
||||
|
||||
# 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 — 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)
|
||||
}
|
||||
|
||||
# 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",
|
||||
"flux1": "flux_1",
|
||||
"flux2": "flux_2",
|
||||
"zimage": "z_image",
|
||||
"wan_image": "wan_image",
|
||||
"wan_video_i2v": "wan_video_i2v",
|
||||
"wan_video_t2v": "wan_video_t2v",
|
||||
"ltxv": None, # No template yet
|
||||
"qwen_image": "qwen_image",
|
||||
}
|
||||
|
||||
|
||||
# ─── Family lookup ───────────────────────────────────────────────────────────
|
||||
|
||||
def get_model_family(model_path):
|
||||
"""
|
||||
Return the family key for a model, or None if unknown.
|
||||
Accepts a relative path like 'Illustrious/Anime/illustrij_v20.safetensors'.
|
||||
"""
|
||||
if not model_path:
|
||||
return None
|
||||
path_lower = model_path.lower().replace("\\", "/")
|
||||
name_lower = os.path.basename(path_lower)
|
||||
|
||||
for family, spec in MODEL_FAMILIES.items():
|
||||
for prefix in spec.get("folders", []):
|
||||
if path_lower.startswith(prefix.lower().replace("\\", "/")):
|
||||
return family
|
||||
for pat in spec.get("names", []):
|
||||
if pat in name_lower:
|
||||
return family
|
||||
return None
|
||||
|
||||
|
||||
def get_family_label(family):
|
||||
"""Return the human-readable label for a family, or the key itself."""
|
||||
if not family:
|
||||
return "Unknown"
|
||||
return MODEL_FAMILIES.get(family, {}).get("label", family)
|
||||
|
||||
|
||||
def get_family_sampler_strategy(family):
|
||||
"""Return the sampler strategy key for a family (default: 'standard')."""
|
||||
if not family:
|
||||
return "standard"
|
||||
return MODEL_FAMILIES.get(family, {}).get("sampler", "standard")
|
||||
|
||||
|
||||
def get_compatible_families(family):
|
||||
"""Return the set of all checkpoint-families compatible with the given one."""
|
||||
if not family:
|
||||
return set()
|
||||
result = {family}
|
||||
for group in MODEL_COMPAT_GROUPS:
|
||||
if family in group:
|
||||
result |= group
|
||||
return result
|
||||
|
||||
|
||||
def get_all_family_labels():
|
||||
"""Return a dict of {family_key: label} for all known families."""
|
||||
hidden = {"ltxv"}
|
||||
return {k: v.get("label", k) for k, v in MODEL_FAMILIES.items() if k not in hidden}
|
||||
|
||||
|
||||
# ─── Model listing ───────────────────────────────────────────────────────────
|
||||
|
||||
def _model_keywords(model_name):
|
||||
"""Extract meaningful keywords from a model filename for fuzzy matching.
|
||||
Strips extension, path, and GGUF quantization tokens (Q8_0, Q4_K_M, etc.)."""
|
||||
import re
|
||||
base = os.path.splitext(os.path.basename(model_name))[0].lower()
|
||||
# Remove GGUF quant suffixes: Q8_0, Q4_K_M, Q5_K_S, Q6_K, etc.
|
||||
base = re.sub(r'[-_]?q\d[_\w]*$', '', base, flags=re.IGNORECASE)
|
||||
# Also strip common precision suffixes: fp8, fp16, bf16, fp32
|
||||
base = re.sub(r'[-_]?(?:fp8|fp16|bf16|fp32)(?:mixed)?$', '', base, flags=re.IGNORECASE)
|
||||
# Split on _ and - to get keywords, filter empties
|
||||
return set(tok for tok in re.split(r'[-_]', base) if tok)
|
||||
|
||||
|
||||
def list_compatible_models(reference_model, family_override=None):
|
||||
"""
|
||||
Given a reference model name/path, return a list of compatible
|
||||
models found on disk, sorted by keyword similarity to the reference.
|
||||
|
||||
The best keyword match is first, so callers can use [0] as a fallback.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
reference_model : str — model path/name to derive family from
|
||||
family_override : str | None — explicit family key (takes priority)
|
||||
"""
|
||||
family = family_override or get_model_family(reference_model)
|
||||
compat = get_compatible_families(family)
|
||||
|
||||
all_models = []
|
||||
for folder_name in ['checkpoints', 'diffusion_models', 'unet', 'unet_gguf']:
|
||||
try:
|
||||
all_models.extend(folder_paths.get_filename_list(folder_name))
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
# Deduplicate preserving order
|
||||
seen = set()
|
||||
unique = []
|
||||
for m in all_models:
|
||||
if m not in seen:
|
||||
seen.add(m)
|
||||
unique.append(m)
|
||||
|
||||
if not compat:
|
||||
return []
|
||||
|
||||
compatible = []
|
||||
for m in unique:
|
||||
m_family = get_model_family(m)
|
||||
if m_family and m_family in compat:
|
||||
compatible.append(m)
|
||||
|
||||
if not compatible:
|
||||
return []
|
||||
|
||||
# Sort by keyword similarity to reference model (best match first)
|
||||
ref_keywords = _model_keywords(reference_model)
|
||||
if ref_keywords:
|
||||
def _match_score(m):
|
||||
m_keywords = _model_keywords(m)
|
||||
shared = len(ref_keywords & m_keywords)
|
||||
# Tie-break: prefer fewer extra keywords (closer match)
|
||||
extra = len(m_keywords - ref_keywords)
|
||||
return (-shared, extra, m.lower())
|
||||
compatible.sort(key=_match_score)
|
||||
else:
|
||||
compatible.sort()
|
||||
|
||||
return compatible
|
||||
|
||||
|
||||
def list_all_models():
|
||||
"""Return all models from all known model folder types (deduplicated, sorted)."""
|
||||
all_models = []
|
||||
seen = set()
|
||||
for folder_name in ['checkpoints', 'diffusion_models', 'unet', 'unet_gguf']:
|
||||
try:
|
||||
for m in folder_paths.get_filename_list(folder_name):
|
||||
if m not in seen:
|
||||
seen.add(m)
|
||||
all_models.append(m)
|
||||
except Exception:
|
||||
continue
|
||||
return sorted(all_models)
|
||||
|
||||
|
||||
def list_compatible_vaes(family, return_recommended=False):
|
||||
"""Return sorted list of VAE files compatible with the given family.
|
||||
If return_recommended=True, returns (list, recommended_str_or_None).
|
||||
|
||||
Matching order:
|
||||
1. vae_exact — full basename match (e.g. "ae.safetensors"), case-insensitive
|
||||
2. vae — substring match against basename or full relative path
|
||||
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)
|
||||
|
||||
if not family:
|
||||
try:
|
||||
return _ret(folder_paths.get_filename_list("vae"), None)
|
||||
except Exception:
|
||||
return _ret([], None)
|
||||
|
||||
spec = MODEL_FAMILIES.get(family, {})
|
||||
exact_names = [e.lower() for e in spec.get("vae_exact", [])]
|
||||
patterns = [p.lower() for p in spec.get("vae", [])]
|
||||
|
||||
if not exact_names and not patterns:
|
||||
try:
|
||||
all_vaes = folder_paths.get_filename_list("vae")
|
||||
return _ret(all_vaes if spec.get("checkpoint", False) else [], None)
|
||||
except Exception:
|
||||
return _ret([], None)
|
||||
|
||||
try:
|
||||
all_vaes = folder_paths.get_filename_list("vae")
|
||||
except Exception:
|
||||
return _ret([], None)
|
||||
|
||||
matched = []
|
||||
recommended = None
|
||||
is_checkpoint = spec.get("checkpoint", False)
|
||||
|
||||
for v in all_vaes:
|
||||
v_lower = v.lower().replace("\\", "/")
|
||||
v_name = os.path.basename(v_lower)
|
||||
|
||||
# 1. Exact basename match (e.g. "ae.safetensors")
|
||||
if v_name in exact_names:
|
||||
matched.append(v)
|
||||
if recommended is None and not is_checkpoint:
|
||||
recommended = v
|
||||
continue
|
||||
|
||||
# 2. Substring patterns
|
||||
for pat in patterns:
|
||||
if pat in v_name or pat in v_lower:
|
||||
matched.append(v)
|
||||
if recommended is None and not is_checkpoint:
|
||||
recommended = v
|
||||
break
|
||||
|
||||
if matched:
|
||||
return _ret(matched, recommended)
|
||||
return _ret(all_vaes if is_checkpoint else [], None)
|
||||
|
||||
|
||||
def list_compatible_clips(family, return_recommended=False):
|
||||
"""Return sorted list of CLIP/text-encoder files compatible with the given family.
|
||||
If return_recommended=True, returns (list, recommended_str_or_None).
|
||||
|
||||
Matching order:
|
||||
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
|
||||
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)
|
||||
|
||||
if not family:
|
||||
clips = _gather_all_clips()
|
||||
return _ret(clips, None)
|
||||
|
||||
spec = MODEL_FAMILIES.get(family, {})
|
||||
exclude_pats = [e.lower() for e in spec.get("clip_exclude", [])]
|
||||
exact_names = [e.lower() for e in spec.get("clip_exact", [])]
|
||||
patterns = [p.lower() for p in spec.get("clip", [])]
|
||||
|
||||
if not exact_names and not patterns:
|
||||
clips = _gather_all_clips()
|
||||
return _ret(clips if spec.get("checkpoint", False) else [], None)
|
||||
|
||||
all_clips = _gather_all_clips()
|
||||
|
||||
matched = []
|
||||
recommended = None
|
||||
is_checkpoint = spec.get("checkpoint", False)
|
||||
|
||||
for c in all_clips:
|
||||
c_lower = c.lower().replace("\\", "/")
|
||||
c_name = os.path.basename(c_lower)
|
||||
|
||||
# 1. Exclusion check — disqualify if any exclude pattern is present
|
||||
if any(ex in c_name or ex in c_lower for ex in exclude_pats):
|
||||
continue
|
||||
|
||||
# 2. Exact basename match
|
||||
if c_name in exact_names:
|
||||
matched.append(c)
|
||||
if recommended is None and not is_checkpoint:
|
||||
recommended = c
|
||||
continue
|
||||
|
||||
# 3. Substring include patterns
|
||||
for pat in patterns:
|
||||
if pat in c_name or pat in c_lower:
|
||||
matched.append(c)
|
||||
if recommended is None and not is_checkpoint:
|
||||
recommended = c
|
||||
break
|
||||
|
||||
if matched:
|
||||
return _ret(matched, recommended)
|
||||
return _ret(all_clips if is_checkpoint else [], None)
|
||||
|
||||
|
||||
def _gather_all_clips():
|
||||
"""Gather CLIP files from text_encoders and clip folders."""
|
||||
clips = []
|
||||
seen = set()
|
||||
for folder in ['text_encoders', 'clip']:
|
||||
try:
|
||||
for c in folder_paths.get_filename_list(folder):
|
||||
if c not in seen:
|
||||
seen.add(c)
|
||||
clips.append(c)
|
||||
except Exception:
|
||||
pass
|
||||
return clips
|
||||
@@ -0,0 +1,8 @@
|
||||
"""
|
||||
Thin re-exports of node-graph helpers from prompt_extractor.
|
||||
Placed in py/ so workflow_extraction_utils can import without a circular dep.
|
||||
Uses relative import since both py/ and nodes/ are siblings under the package root.
|
||||
"""
|
||||
from ..nodes.prompt_extractor import build_node_map, build_link_map
|
||||
|
||||
__all__ = ['build_node_map', 'build_link_map']
|
||||
@@ -1,7 +1,7 @@
|
||||
[project]
|
||||
name = "prompt-manager"
|
||||
description = "Prompt Manager extension for ComfyUI, allowing user to both save and generate prompts, as well as save matching loras for each prompt."
|
||||
version = "1.10.0"
|
||||
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.5.1"
|
||||
license = {file = "LICENSE"}
|
||||
# classifiers = [
|
||||
# # For OS-independent nodes (works on all operating systems)
|
||||
@@ -20,7 +20,7 @@ license = {file = "LICENSE"}
|
||||
# "Environment :: GPU :: Apple Metal", # Apple Metal support
|
||||
# ]
|
||||
|
||||
dependencies = ["requests>=2.31.0", "huggingface_hub>=0.20.0", "psutil>=5.9.0", "tqdm>=4.66.0", "Pillow>=10.0.0", "torch>=2.0.0", "numpy>=1.24.0", "colorama"]
|
||||
dependencies = ["requests", "huggingface_hub", "psutil", "tqdm", "Pillow", "torch", "numpy", "colorama"]
|
||||
|
||||
[project.urls]
|
||||
Repository = "https://github.com/FranckyB/ComfyUI-Prompt-Manager"
|
||||
@@ -34,4 +34,3 @@ DisplayName = "ComfyUI-Prompt-Manager"
|
||||
Icon = ""
|
||||
includes = []
|
||||
# "requires-comfyui" = ">=1.0.0" # ComfyUI version compatibility
|
||||
|
||||
|
||||
@@ -1,8 +1,2 @@
|
||||
requests>=2.31.0
|
||||
huggingface_hub>=0.20.0
|
||||
psutil>=5.9.0
|
||||
tqdm>=4.66.0
|
||||
Pillow>=10.0.0
|
||||
torch>=2.0.0
|
||||
numpy>=1.24.0
|
||||
huggingface_hub
|
||||
colorama
|
||||
@@ -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,38 @@
|
||||
import sys, io, json
|
||||
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace')
|
||||
from PIL import Image
|
||||
|
||||
img = Image.open(r'D:\ComfyUI-Dev\output\ComfyUI_00006_.png')
|
||||
print('=== Keys in info ===')
|
||||
for k in img.info:
|
||||
print(f' {k}: {len(str(img.info[k]))} chars')
|
||||
|
||||
# Check workflow for extracted_data
|
||||
wf = json.loads(img.info.get('workflow', '{}'))
|
||||
for node in wf.get('nodes', []):
|
||||
ntype = node.get('type', '')
|
||||
nid = node.get('id', '?')
|
||||
if ntype == 'PromptExtractor':
|
||||
print(f'\n=== PromptExtractor node {nid} ===')
|
||||
ext = node.get('extracted_data')
|
||||
if ext:
|
||||
print('extracted_data FOUND:')
|
||||
print(json.dumps(ext, indent=2, ensure_ascii=False)[:2000])
|
||||
else:
|
||||
print('extracted_data: MISSING')
|
||||
print('Node keys:', list(node.keys()))
|
||||
# Show widgets_values
|
||||
wv = node.get('widgets_values', [])
|
||||
print(f'widgets_values ({len(wv)} items): {str(wv)[:500]}')
|
||||
|
||||
# Also check prompt (API format) for PromptExtractor
|
||||
prompt = json.loads(img.info.get('prompt', '{}'))
|
||||
for nid, ndata in prompt.items():
|
||||
if isinstance(ndata, dict) and ndata.get('class_type') == 'PromptExtractor':
|
||||
print(f'\n=== API PromptExtractor node {nid} ===')
|
||||
inputs = ndata.get('inputs', {})
|
||||
print('Input keys:', list(inputs.keys()))
|
||||
for k in ['loras_a_toggle', 'loras_b_toggle', 'lora_stack_a', 'lora_stack_b']:
|
||||
if k in inputs:
|
||||
val = inputs[k]
|
||||
print(f' {k}: {str(val)[:300]}')
|
||||
@@ -0,0 +1,189 @@
|
||||
# ComfyUI Tab Switch & State Persistence
|
||||
|
||||
## How ComfyUI handles tab switches
|
||||
|
||||
When a user switches browser tabs (or ComfyUI workflow tabs) and returns, ComfyUI **destroys and recreates all nodes**. The sequence is:
|
||||
|
||||
1. `onNodeCreated` fires (synchronous — rebuilds all DOM, widgets, state variables from scratch)
|
||||
2. `onConfigure` fires immediately after (synchronous — receives serialized `info` with `properties` and `widgets_values`)
|
||||
|
||||
This means **any JS variable stored on the node object is lost**. Only data serialized into the workflow JSON survives.
|
||||
|
||||
## What gets serialized in workflow JSON
|
||||
|
||||
Each node in the workflow JSON has:
|
||||
- `properties` — an object directly on the node, serialized as-is
|
||||
- `widgets_values` — an array of widget values (index-based, fragile if widget order changes)
|
||||
- `pos`, `size`, `flags` — layout info
|
||||
|
||||
## The correct pattern (node.properties)
|
||||
|
||||
### Store durable state in `node.properties`
|
||||
|
||||
```js
|
||||
// In syncHidden (called on every user interaction):
|
||||
node.properties ||= {};
|
||||
node.properties.my_state_key = JSON.stringify(stateObject);
|
||||
```
|
||||
|
||||
`node.properties` is **directly serialized** in the workflow JSON `"properties"` field. It survives:
|
||||
- Tab switches
|
||||
- Page refreshes
|
||||
- Workflow save/load
|
||||
- Copy/paste
|
||||
|
||||
### Restore in onConfigure (synchronously)
|
||||
|
||||
```js
|
||||
nodeType.prototype.onConfigure = function (info) {
|
||||
origConfigure?.apply(this, arguments);
|
||||
const node = this;
|
||||
|
||||
// Set flag SYNCHRONOUSLY — blocks onNodeCreated's async callbacks
|
||||
node._configuredFromWorkflow = true;
|
||||
|
||||
// Read from node.properties (already restored by LiteGraph)
|
||||
const props = node.properties || {};
|
||||
const savedState = props.my_state_key;
|
||||
|
||||
// Restore UI synchronously — no setTimeout, no API calls
|
||||
if (savedState) {
|
||||
const state = JSON.parse(savedState);
|
||||
restoreUI(node, state);
|
||||
}
|
||||
|
||||
// Recalculate heights AFTER restoring UI
|
||||
if (node._weRecalc) node._weRecalc();
|
||||
node.setDirtyCanvas(true, true);
|
||||
};
|
||||
```
|
||||
|
||||
### Guard onNodeCreated's async work
|
||||
|
||||
```js
|
||||
nodeType.prototype.onNodeCreated = function () {
|
||||
// ... build DOM, create widgets ...
|
||||
|
||||
// Async init — only for FRESH node creation
|
||||
const initImg = getWidgetValue("image");
|
||||
if (initImg) {
|
||||
setTimeout(() => {
|
||||
// _configuredFromWorkflow was set synchronously by onConfigure
|
||||
// before this setTimeout fires
|
||||
if (!node._configuredFromWorkflow) doInitialLoad(initImg);
|
||||
}, 300);
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
## Critical rules
|
||||
|
||||
1. **NEVER use setTimeout in onConfigure** — it creates race conditions with onNodeCreated's async work
|
||||
2. **NEVER make API/network calls in onConfigure** — restore purely from serialized data
|
||||
3. **NEVER reload images/thumbnails in onConfigure** — causes DOM flash and height reset
|
||||
4. **ALWAYS call recalcHeight after restore** — otherwise the node stays at its empty initial size
|
||||
5. **ALWAYS persist state on every user interaction** — syncHidden must write to node.properties immediately
|
||||
6. **ALWAYS persist state after doExtract** — so even before user changes anything, the extracted data is saved
|
||||
7. **Use a permanent flag** (`_configuredFromWorkflow`) — set it in onConfigure, never clear it. It only needs to block the initial async load in onNodeCreated.
|
||||
|
||||
## Why widgets_values is unreliable
|
||||
|
||||
- Index-based: if you splice widgets (e.g., adding a Browse button), indices shift
|
||||
- DOM widgets with `serialize: false` still take a slot
|
||||
- Widget order depends on Python INPUT_TYPES + JS modifications
|
||||
- `node.properties` is a named key-value store — no index alignment issues
|
||||
|
||||
## What we store in properties
|
||||
|
||||
For the Workflow Extractor node:
|
||||
- `we_override_data` — JSON of all user overrides (model, sampler, prompts, section states, family)
|
||||
- `we_lora_state` — JSON of LoRA toggle states
|
||||
- `we_extracted_cache` — JSON of the full extracted data (avoids API call on restore)
|
||||
|
||||
We also write to the hidden widgets (`override_data`, `lora_state`, `extracted_cache`) for Python execution, but `node.properties` is the source of truth for tab persistence.
|
||||
|
||||
## Reference: PM Advanced pattern
|
||||
|
||||
The Prompt Manager Advanced node uses this exact pattern:
|
||||
- `_configuredFromWorkflow = true` set synchronously in onConfigure
|
||||
- State restored from `info.widgets_values` (works for PM Advanced because it doesn't splice widgets)
|
||||
- DOM widgets reattached synchronously
|
||||
- Only async work is data loading (not state restoration)
|
||||
- The flag permanently blocks onNodeCreated's async `loadPromptData` callback
|
||||
|
||||
## Do NOT use visibilitychange
|
||||
|
||||
The `visibilitychange` event is NOT needed. PM Advanced doesn't use it. ComfyUI's own lifecycle (onNodeCreated → onConfigure) handles everything. Adding `visibilitychange` listeners causes extra work that fights against the restore flow.
|
||||
|
||||
## DOM Widget Sizing — Critical Rules
|
||||
|
||||
When a node uses `addDOMWidget` with a container holding sections/content, sizing is the #1 source of bugs. Follow these rules:
|
||||
|
||||
### The Problem: Flex Shrinking
|
||||
|
||||
LiteGraph constrains widget containers to the node's current height. If your root container uses `display: flex; flex-direction: column`, child elements will **shrink to fit** inside the constrained container. Then `scrollHeight` / `offsetHeight` report the *compressed* height, `computeSize` returns that small value to LiteGraph, and the node collapses to nothing in a feedback loop.
|
||||
|
||||
### The Fix: `flexShrink: "0"` on all children
|
||||
|
||||
Every direct child of the root flex container (sections, cards, etc.) must have `flexShrink: "0"`. This prevents compression, forces overflow, and makes `scrollHeight` report the **true** content height.
|
||||
|
||||
```js
|
||||
// In makeSection():
|
||||
const wrap = makeEl("div", {
|
||||
borderRadius: "6px", overflow: "hidden", marginTop: "2px",
|
||||
backgroundColor: C.bgCard, flexShrink: "0", // ← CRITICAL
|
||||
});
|
||||
```
|
||||
|
||||
### computeSize must use scrollHeight, not offsetHeight
|
||||
|
||||
- `offsetHeight` — reports the *clipped* height (what the parent container allows)
|
||||
- `scrollHeight` — reports the full *intrinsic* content height (what the content actually needs)
|
||||
|
||||
```js
|
||||
domW.computeSize = function (nodeWidth) {
|
||||
const h = root.scrollHeight || 800;
|
||||
return [nodeWidth, h];
|
||||
};
|
||||
```
|
||||
|
||||
### Use requestAnimationFrame, not setTimeout
|
||||
|
||||
After DOM mutations (adding LoRA tags, showing/hiding rows), call `_resizeNode` via `requestAnimationFrame` — not `setTimeout`. RAF guarantees the browser has reflowed the DOM, so `scrollHeight` is accurate.
|
||||
|
||||
```js
|
||||
if (node._weRecalc) requestAnimationFrame(() => node._weRecalc());
|
||||
```
|
||||
|
||||
### Reference: PMA's approach
|
||||
|
||||
PMA avoids this problem entirely by using **multiple separate DOM widgets** (one per section), each with their own `computeSize`. LiteGraph sums them naturally. WG uses a single DOM widget with a flex container, so the `flexShrink: "0"` + `scrollHeight` approach is required instead.
|
||||
|
||||
### _resizeNode pattern
|
||||
|
||||
```js
|
||||
function _resizeNode() {
|
||||
const domH = root.scrollHeight || 800;
|
||||
const needed = domH + NATIVE_H;
|
||||
if (node.size) {
|
||||
const w = Math.max(MIN_W, node.size[0]);
|
||||
const h = Math.max(needed, MIN_H);
|
||||
if (node.size[0] !== w || node.size[1] !== h) {
|
||||
node.setSize([w, h]);
|
||||
}
|
||||
}
|
||||
app.graph.setDirtyCanvas(true, true);
|
||||
}
|
||||
```
|
||||
|
||||
### onResize for enforcing minimums
|
||||
|
||||
```js
|
||||
const origOnResize = node.onResize;
|
||||
node.onResize = function (size) {
|
||||
const domH = root.scrollHeight || 800;
|
||||
size[0] = Math.max(MIN_W, size[0]);
|
||||
size[1] = Math.max(domH + NATIVE_H, MIN_H, size[1]);
|
||||
if (origOnResize) return origOnResize.apply(this, arguments);
|
||||
};
|
||||
```
|
||||
@@ -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();
|
||||
@@ -0,0 +1,97 @@
|
||||
import sys, json, types, os, glob, io
|
||||
|
||||
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace')
|
||||
|
||||
sys.path.insert(0, r'D:\ComfyUI-Dev')
|
||||
mock_server = types.ModuleType('server')
|
||||
mock_server.web = types.SimpleNamespace(json_response=lambda *a, **k: None)
|
||||
class FakePromptServer:
|
||||
class instance:
|
||||
class routes:
|
||||
@staticmethod
|
||||
def post(path): return lambda f: f
|
||||
@staticmethod
|
||||
def get(path): return lambda f: f
|
||||
mock_server.PromptServer = FakePromptServer
|
||||
sys.modules['server'] = mock_server
|
||||
|
||||
sys.path.insert(0, r'D:\ComfyUI\custom_nodes\ComfyUI-Prompt-Manager')
|
||||
from nodes.prompt_extractor import parse_workflow_for_prompts, MODEL_LOADER_TYPES, parse_a1111_parameters
|
||||
from PIL import Image
|
||||
|
||||
pics_dir = r'D:\ComfyUI-Dev\input\Workflow\Pics'
|
||||
no_model_count = 0
|
||||
ok_count = 0
|
||||
|
||||
for f in sorted(glob.glob(os.path.join(pics_dir, '*.png'))):
|
||||
try:
|
||||
img = Image.open(f)
|
||||
prompt_str = img.info.get('prompt', '')
|
||||
workflow_str = img.info.get('workflow', '')
|
||||
parameters_str = img.info.get('parameters', '')
|
||||
if not prompt_str and not workflow_str and not parameters_str:
|
||||
continue
|
||||
|
||||
# Handle A1111 parameters format
|
||||
if not prompt_str and not workflow_str and parameters_str:
|
||||
parsed_a1111 = parse_a1111_parameters(parameters_str)
|
||||
prompt_data = parsed_a1111 if parsed_a1111 else {}
|
||||
workflow_data = {}
|
||||
else:
|
||||
prompt_data = json.loads(prompt_str) if prompt_str else {}
|
||||
workflow_data = json.loads(workflow_str) if workflow_str else {}
|
||||
|
||||
# Check what model loaders exist
|
||||
api_loaders = []
|
||||
if prompt_data:
|
||||
for nid, ndata in prompt_data.items():
|
||||
if isinstance(ndata, dict):
|
||||
ct = ndata.get('class_type', '')
|
||||
if ct in MODEL_LOADER_TYPES:
|
||||
api_loaders.append((nid, ct))
|
||||
|
||||
wf_loaders = []
|
||||
wf_loader_types = set()
|
||||
if workflow_data and 'nodes' in workflow_data:
|
||||
for node in workflow_data['nodes']:
|
||||
if isinstance(node, dict):
|
||||
ntype = node.get('type', '')
|
||||
if ntype in MODEL_LOADER_TYPES:
|
||||
wid = node.get('widgets_values', [])
|
||||
wf_loaders.append((node.get('id'), ntype, wid[:2] if wid else []))
|
||||
# Also check for checkpoint-like types not in our list
|
||||
nt_lower = ntype.lower()
|
||||
if any(k in nt_lower for k in ['checkpoint', 'unet', 'diffusion', 'model_loader']):
|
||||
wf_loader_types.add(ntype)
|
||||
|
||||
parsed = parse_workflow_for_prompts(prompt_data, workflow_data)
|
||||
models_a = parsed.get('models_a', [])
|
||||
models_b = parsed.get('models_b', [])
|
||||
|
||||
basename = os.path.basename(f)
|
||||
if not models_a and not models_b:
|
||||
no_model_count += 1
|
||||
print(f"\nNO MODELS: {basename}")
|
||||
if api_loaders:
|
||||
print(f" API loaders found: {api_loaders}")
|
||||
if wf_loaders:
|
||||
print(f" WF loaders found: {wf_loaders}")
|
||||
if wf_loader_types:
|
||||
print(f" Checkpoint-like types in WF: {wf_loader_types}")
|
||||
if not api_loaders and not wf_loaders and not wf_loader_types:
|
||||
all_types = set()
|
||||
if prompt_data:
|
||||
for ndata in prompt_data.values():
|
||||
if isinstance(ndata, dict):
|
||||
all_types.add(ndata.get('class_type', ''))
|
||||
if workflow_data and 'nodes' in workflow_data:
|
||||
for node in workflow_data['nodes']:
|
||||
if isinstance(node, dict):
|
||||
all_types.add(node.get('type', ''))
|
||||
print(f" ALL types: {sorted(all_types)}")
|
||||
else:
|
||||
ok_count += 1
|
||||
except Exception as e:
|
||||
print(f"ERROR: {os.path.basename(f)}: {e}")
|
||||
|
||||
print(f"\n=== SUMMARY: {ok_count} OK, {no_model_count} no models ===")
|
||||
@@ -0,0 +1,82 @@
|
||||
import sys, json, types, os, glob, io
|
||||
|
||||
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace')
|
||||
|
||||
sys.path.insert(0, r'D:\ComfyUI-Dev')
|
||||
mock_server = types.ModuleType('server')
|
||||
mock_server.web = types.SimpleNamespace(json_response=lambda *a, **k: None)
|
||||
class FakePromptServer:
|
||||
class instance:
|
||||
class routes:
|
||||
@staticmethod
|
||||
def post(path): return lambda f: f
|
||||
@staticmethod
|
||||
def get(path): return lambda f: f
|
||||
mock_server.PromptServer = FakePromptServer
|
||||
sys.modules['server'] = mock_server
|
||||
|
||||
sys.path.insert(0, r'D:\ComfyUI\custom_nodes\ComfyUI-Prompt-Manager')
|
||||
from nodes.prompt_extractor import parse_workflow_for_prompts, extract_metadata_from_video, MODEL_LOADER_TYPES, resolve_model_path
|
||||
|
||||
vids_dir = r'D:\ComfyUI-Dev\input\Workflow\Vids'
|
||||
ok_count = 0
|
||||
no_model_count = 0
|
||||
no_metadata_count = 0
|
||||
error_count = 0
|
||||
|
||||
for f in sorted(glob.glob(os.path.join(vids_dir, '*.mp4'))):
|
||||
basename = os.path.basename(f)
|
||||
try:
|
||||
result = extract_metadata_from_video(f)
|
||||
if not result or (not result[0] and not result[1]):
|
||||
no_metadata_count += 1
|
||||
continue
|
||||
|
||||
prompt_str, workflow_str = result
|
||||
prompt_data = json.loads(prompt_str) if isinstance(prompt_str, str) else (prompt_str or {})
|
||||
workflow_data = json.loads(workflow_str) if isinstance(workflow_str, str) else (workflow_str or {})
|
||||
|
||||
if not prompt_data and not workflow_data:
|
||||
no_metadata_count += 1
|
||||
continue
|
||||
|
||||
parsed = parse_workflow_for_prompts(prompt_data, workflow_data)
|
||||
models_a = parsed.get('models_a', [])
|
||||
models_b = parsed.get('models_b', [])
|
||||
|
||||
if models_a or models_b:
|
||||
ok_count += 1
|
||||
a_resolved = resolve_model_path(models_a[0])[0] if models_a else ""
|
||||
b_resolved = resolve_model_path(models_b[0])[0] if models_b else ""
|
||||
print(f"OK: {basename} -> A={a_resolved}, B={b_resolved}")
|
||||
else:
|
||||
no_model_count += 1
|
||||
# Check what loader types exist
|
||||
all_types = set()
|
||||
loader_types = set()
|
||||
if prompt_data:
|
||||
for ndata in prompt_data.values():
|
||||
if isinstance(ndata, dict):
|
||||
ct = ndata.get('class_type', '')
|
||||
all_types.add(ct)
|
||||
ct_lower = ct.lower()
|
||||
if any(k in ct_lower for k in ['checkpoint', 'unet', 'diffusion', 'model', 'loader']):
|
||||
loader_types.add(ct)
|
||||
if workflow_data and 'nodes' in workflow_data:
|
||||
for node in workflow_data['nodes']:
|
||||
if isinstance(node, dict):
|
||||
nt = node.get('type', '')
|
||||
all_types.add(nt)
|
||||
nt_lower = nt.lower()
|
||||
if any(k in nt_lower for k in ['checkpoint', 'unet', 'diffusion', 'model', 'loader']):
|
||||
loader_types.add(nt)
|
||||
print(f"NO MODELS: {basename}")
|
||||
if loader_types:
|
||||
print(f" Loader-like types: {sorted(loader_types)}")
|
||||
else:
|
||||
print(f" ALL types: {sorted(all_types)}")
|
||||
except Exception as e:
|
||||
error_count += 1
|
||||
print(f"ERROR: {basename}: {type(e).__name__}: {e}")
|
||||
|
||||
print(f"\n=== SUMMARY: {ok_count} OK, {no_model_count} no models, {no_metadata_count} no metadata, {error_count} errors ===")
|
||||