Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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 |
@@ -1,25 +1,46 @@
|
||||
# ComfyUI Prompt Manager
|
||||
## A comprehensive prompt toolkit for [ComfyUI](https://github.com/comfyanonymous/ComfyUI) — Save, Generate, and Extract prompts with full LoRA support.
|
||||
## 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 management solution featuring three core capabilities:
|
||||
A complete prompt and workflow management suite featuring:
|
||||
|
||||
**Prompt Manager** — Save and organize prompts with categories, simple UI with minimal feature.
|
||||
## v2.0 Introduces: Workflow Extractor + Workflow Builder + Workflow Renderer + Workflow Manager
|
||||
|
||||
**Prompt Manager Advanced** — 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. Will also remap Loras if path differs.
|
||||
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 and LoRA configurations from existing images, videos, or JSON workflow files. Will extract first frame from any video. Automatically parses embedded metadata and outputs active LoRA as Lora stacks. When used in conjunction with Prompt Manager Advanced, Loras will be automatically found if available, regardless of path. For those that aren't, right click offers the option to look for them on Civitai.
|
||||
**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>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">
|
||||
</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">
|
||||
@@ -28,6 +49,18 @@ ___
|
||||
<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:
|
||||
@@ -40,7 +73,7 @@ ___
|
||||
- **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
|
||||
- **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
|
||||
@@ -49,27 +82,38 @@ ___
|
||||
- **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.
|
||||
- **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
|
||||
|
||||
|
||||
### Prompt Apply LoRA:
|
||||
- **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
|
||||
- **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 extraction from CLIP Text Encode, various sampler nodes, and LoRA stackers including Power Lora Loader
|
||||
- **Preview in Manager**: View extracted data and repathed loras using Manager Advanced.
|
||||
- **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
|
||||
@@ -88,31 +132,15 @@ ___
|
||||
- **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.
|
||||
- **Console Debugging**: Enable outputting the entire process to the console for debugging purposes.
|
||||
|
||||
### Preference Options
|
||||
- Set choices for prefered Model for both base mode and vision 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.
|
||||
- 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.
|
||||
|
||||
### Save Video H264/H265
|
||||
- **Codec Selection**: Choose between H.264 (8-bit, better compatibility) or H.265/HEVC (10-bit, better compression and gradients)
|
||||
- **Chroma Subsampling**: Select yuv420 (most compatible), yuv422 (better for video editing), or yuv444 (best color, no chroma loss)
|
||||
- **Quality Control**: Constant Rate Factor (CRF) from 0-51 for fine-tuned quality vs file size balance
|
||||
- **Preview Mode**: Quick preview encoding to temp folder without saving to output
|
||||
- **Save Latent**: Optionally save the latent alongside the video for later experimentation without regeneration
|
||||
- **Audio Support**: Preserves audio from VIDEO input with proper sync
|
||||
- **Workflow Metadata**: Embeds full workflow metadata in MP4 (unlike VideoHelperSuite which strips it from audio clips)
|
||||
- **Browser Preview**: Automatically generates browser-compatible preview for H.265 + yuv422/444 combinations
|
||||
|
||||
### Animated Latent Preview
|
||||
- **Video Sampling Preview**: Display animated previews during KSampler execution for video models
|
||||
- **TAESD Support**: Works with both Latent2RGB and TAESD preview methods (including high-quality video TAESD)
|
||||
- **Auto Frame Rate**: Automatically detects optimal playback rate based on video model (Wan, Mochi, LTXV, HunyuanVideo, etc.)
|
||||
- **Manual Rate Override**: Optional playback rate override in preferences
|
||||
- **VHS Compatible**: Automatically defers to VideoHelperSuite if installed to avoid conflicts
|
||||
|
||||
## Installation
|
||||
|
||||
@@ -139,7 +167,7 @@ ___
|
||||
```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.
|
||||
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
|
||||
|
||||
@@ -160,25 +188,20 @@ ___
|
||||
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
|
||||
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. **Load Media**: Select an image or video from your input folder or use the upload button to access file from anywhere.
|
||||
3. **JSON Workflows**: Support extracting from JSON, by importing workflow files directly using the upload button.
|
||||
4. **Extract Data**: The node automatically extracts prompts, LoRAs, and trigger words from embedded metadata
|
||||
5. **View Results**: Extracted positive/negative prompts display in the text outputs, LoRA stacks output as LORA_STACK
|
||||
6. **Use with Manager**: Connect the LoRA stack outputs to Prompt Manager Advanced to view and save the extracted configuration
|
||||
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
|
||||
|
||||
@@ -191,8 +214,8 @@ ___
|
||||
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
|
||||
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
|
||||
@@ -226,26 +249,6 @@ Preference settings can be found in ComfyUI Settings → Prompt Manager
|
||||
- **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)
|
||||
|
||||
### Save Video H264/H265
|
||||
|
||||
1. **Add the Node**: Add Node → Prompt Manager → Save Video H264/H265
|
||||
2. **Connect VIDEO**: Connect a VIDEO output (e.g., from VAE Decode for video models)
|
||||
3. **Choose Codec**: Select h264 for compatibility or h265 for better quality/compression
|
||||
4. **Set Quality**: Adjust CRF (18-23 recommended for high quality, lower = better quality but larger files)
|
||||
5. **Chroma Options**: Use yuv420 for maximum compatibility, yuv444 for best color preservation
|
||||
6. **Save Latent**: Connect a LATENT input and enable "save_latent" to save the latent alongside your video
|
||||
7. **Preview Mode**: Set "save" to false for quick preview encoding without saving to output folder
|
||||
|
||||
### Animated Latent Preview
|
||||
|
||||
1. **Enable in Settings**: Go to ComfyUI Settings → Prompt Manager → 5. Video Sampling
|
||||
2. **Toggle On**: Enable "Display animated previews when sampling"
|
||||
3. **Optional Rate**: Set "Playback rate override" to force a specific FPS (0 = auto-detect from model)
|
||||
4. **Run Video Workflow**: During KSampler execution, you'll see an animated preview of the video being generated
|
||||
5. **Works with TAESD**: Enable TAESD in ComfyUI preview settings for higher quality previews
|
||||
|
||||
**Note**: If VideoHelperSuite is installed and enabled, its latent preview takes priority to avoid conflicts.
|
||||
|
||||
## Requirements
|
||||
|
||||
- ComfyUI
|
||||
@@ -273,7 +276,7 @@ Preference settings can be found in ComfyUI Settings → Prompt Manager
|
||||
- **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
|
||||
- **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.
|
||||
@@ -282,17 +285,156 @@ Preference settings can be found in ComfyUI Settings → Prompt Manager
|
||||
- **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.
|
||||
- **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
|
||||
**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" option to prompt right-click menu in the thumbnail browser
|
||||
- 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)
|
||||
@@ -380,7 +522,7 @@ Preference settings can be found in ComfyUI Settings → Prompt Manager
|
||||
- Bug fix for issue caused by new additions.
|
||||
|
||||
### version 1.12.7
|
||||
- Quality of life improvements and added option to change the Strenght of any Lora in Manager, so we can tweak Extracted Workflows Live.
|
||||
- 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
|
||||
@@ -390,7 +532,7 @@ Preference settings can be found in ComfyUI Settings → Prompt Manager
|
||||
|
||||
### 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 Worfklow.
|
||||
- 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.
|
||||
|
||||
+39
-36
@@ -1,53 +1,56 @@
|
||||
"""
|
||||
ComfyUI Prompt Manager - A simple custom node for saving and reusing prompts
|
||||
A prompt management system for ComfyUI with LLM input support
|
||||
ComfyUI Prompt Manager - A comprehensive prompt and workflow management system for ComfyUI.
|
||||
Features: prompt & workflow management, LoRA stacks, workflow extraction, workflow generation.
|
||||
"""
|
||||
__version__ = "1.17.5"
|
||||
__version__ = "2.0.0"
|
||||
__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 .prompt_apply_lora import PromptApplyLora
|
||||
from .prompt_extractor import PromptExtractor
|
||||
from .model_manager import get_local_models
|
||||
from .save_video_h26x import SaveVideoH26x, LoadLatentFile, MonoToStereo, GetVideoComponentsPlus
|
||||
from server import PromptServer
|
||||
|
||||
# Initialize latent preview hook (with VHS conflict detection)
|
||||
from .latent_preview import install_latent_preview_hook
|
||||
install_latent_preview_hook()
|
||||
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
|
||||
from .nodes.workflow_builder import WorkflowBuilder
|
||||
from .nodes.workflow_renderer import WorkflowRenderer
|
||||
from .nodes.workflow_bridge import WorkflowBridge
|
||||
from .nodes.workflow_model_loader import WorkflowModelLoader
|
||||
from .nodes.workflow_manager import WorkflowManager
|
||||
|
||||
NODE_CLASS_MAPPINGS = {
|
||||
"PromptManager": PromptManager,
|
||||
"PromptApplyLora": ApplyLoraPlusPlus,
|
||||
"PromptManagerAdvanced": PromptManagerAdvanced,
|
||||
"PromptGenerator": PromptGenerator,
|
||||
"PromptGenOptions": PromptGenOptions,
|
||||
"PromptApplyLora": PromptApplyLora,
|
||||
"PromptExtractor": PromptExtractor,
|
||||
"SaveVideoH26x": SaveVideoH26x,
|
||||
"LoadLatentFile": LoadLatentFile,
|
||||
"AudioMonoToStereo": MonoToStereo,
|
||||
"GetVideoComponentsPlus": GetVideoComponentsPlus,
|
||||
"PromptManager": PromptManager,
|
||||
"PromptGenerator": PromptGenerator,
|
||||
"PromptGenOptions": PromptGenOptions,
|
||||
"PromptExtractor": PromptExtractor,
|
||||
"WorkflowExtractor": WorkflowExtractor,
|
||||
"WorkflowBuilder": WorkflowBuilder,
|
||||
"WorkflowRenderer": WorkflowRenderer,
|
||||
"WorkflowBridge": WorkflowBridge,
|
||||
"WorkflowModelLoader": WorkflowModelLoader,
|
||||
"WorkflowManager": WorkflowManager,
|
||||
}
|
||||
|
||||
NODE_DISPLAY_NAME_MAPPINGS = {
|
||||
"PromptManager": "Prompt Manager",
|
||||
"PromptManagerAdvanced": "Prompt Manager Advanced",
|
||||
"PromptGenerator": "Prompt Generator",
|
||||
"PromptGenOptions": "Prompt Generator Options",
|
||||
"PromptApplyLora": "Prompt Apply LoRA",
|
||||
"PromptExtractor": "Prompt Extractor",
|
||||
"SaveVideoH26x": "Save Video H264/H265",
|
||||
"LoadLatentFile": "Load Latent File",
|
||||
"AudioMonoToStereo": "Audio Mono to Stereo",
|
||||
"GetVideoComponentsPlus": "Get Video Components+",
|
||||
"PromptApplyLora": "Apply LoRA++",
|
||||
"PromptManagerAdvanced": "Prompt Manager",
|
||||
"PromptManager": "Prompt Manager (Basic)",
|
||||
"PromptGenerator": "Prompt Generator",
|
||||
"PromptGenOptions": "Prompt Generator Options",
|
||||
"PromptExtractor": "Prompt Extractor",
|
||||
"WorkflowExtractor": "Workflow Extractor",
|
||||
"WorkflowBuilder": "Workflow Builder",
|
||||
"WorkflowRenderer": "Workflow Renderer",
|
||||
"WorkflowBridge": "Workflow Bridge",
|
||||
"WorkflowModelLoader": "Workflow Model Loader",
|
||||
"WorkflowManager": "Workflow Manager",
|
||||
}
|
||||
|
||||
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 (Basic), Prompt Manager, Prompt Generator, Prompt Generator Options, Prompt Extractor, Workflow Extractor, Workflow Builder, Workflow Renderer, Workflow Bridge, Workflow Model Loader, Workflow Manager")
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import sys, json, subprocess, io
|
||||
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace')
|
||||
|
||||
# Check videos with missing loader types
|
||||
test_files = {
|
||||
'DiffusionModelLoaderKJ': r'D:\ComfyUI-Dev\input\Workflow\Vids\2026_01_08_60FPS_00002.mp4',
|
||||
'WanVideoModelLoader': r'D:\ComfyUI-Dev\input\Workflow\Vids\vid_00061.mp4',
|
||||
'SeaArtUnetLoader': r'D:\ComfyUI-Dev\input\Workflow\Vids\25439d30-d0d7-4dd4-b64c-b46345c76351.mp4',
|
||||
'CyberdyneModelHub': r'D:\ComfyUI-Dev\input\Workflow\Vids\d39dbdc3-f08c-44e1-bd4c-410ecb08d3c9.mp4',
|
||||
'CheckpointInNum': r'D:\ComfyUI-Dev\input\Workflow\Vids\num__00168.mp4',
|
||||
}
|
||||
|
||||
for label, f in test_files.items():
|
||||
print(f"\n=== {label} ===")
|
||||
r = subprocess.run(['ffprobe','-v','quiet','-print_format','json','-show_format',f], capture_output=True, text=True, timeout=10)
|
||||
data = json.loads(r.stdout)
|
||||
tags = data['format']['tags']
|
||||
|
||||
# Try direct tags first, then comment
|
||||
prompt = tags.get('prompt')
|
||||
if not prompt:
|
||||
comment = tags.get('comment', '{}')
|
||||
comment_data = json.loads(comment)
|
||||
prompt = comment_data.get('prompt', '{}')
|
||||
|
||||
if isinstance(prompt, str):
|
||||
prompt = json.loads(prompt)
|
||||
|
||||
targets = ['Diffusion', 'Wan', 'SeaArt', 'Cyberdyne', 'Checkpoint', 'UNET', 'Unet', 'Model']
|
||||
for nid, ndata in prompt.items():
|
||||
ct = ndata.get('class_type', '')
|
||||
if 'Cyberdyne' in ct or ct == 'Wan_Cyberdyne_Genisys':
|
||||
inputs = ndata.get('inputs', {})
|
||||
inp_str = json.dumps(inputs)
|
||||
if len(inp_str) > 800:
|
||||
inp_str = inp_str[:800] + '...'
|
||||
print(f" Node {nid}: {ct}")
|
||||
print(f" inputs: {inp_str}")
|
||||
@@ -0,0 +1,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);
|
||||
};
|
||||
```
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 229 KiB |
File diff suppressed because one or more lines are too long
Binary file not shown.
|
After Width: | Height: | Size: 254 KiB |
File diff suppressed because one or more lines are too long
Binary file not shown.
|
After Width: | Height: | Size: 229 KiB |
File diff suppressed because one or more lines are too long
+203
-146
@@ -2,13 +2,22 @@
|
||||
* 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) {
|
||||
// Reset to root on open
|
||||
currentSubfolder = '';
|
||||
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');
|
||||
@@ -19,7 +28,7 @@ export function createFileBrowserModal(currentFile, onFileSelect) {
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background: rgba(0, 0, 0, 0.8);
|
||||
background: ${UI.overlay};
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
@@ -30,8 +39,8 @@ export function createFileBrowserModal(currentFile, onFileSelect) {
|
||||
const modal = document.createElement('div');
|
||||
modal.className = 'prompt-extractor-browser-modal';
|
||||
modal.style.cssText = `
|
||||
background: rgba(40, 44, 52, 0.98);
|
||||
border: 1px solid rgba(255,255,255,0.1);
|
||||
background: ${UI.panel};
|
||||
border: 1px solid ${UI.panelBorder};
|
||||
border-radius: 6px;
|
||||
width: 90%;
|
||||
max-width: 1200px;
|
||||
@@ -46,7 +55,7 @@ export function createFileBrowserModal(currentFile, onFileSelect) {
|
||||
const header = document.createElement('div');
|
||||
header.style.cssText = `
|
||||
padding: 15px 20px;
|
||||
border-bottom: 1px solid rgba(255,255,255,0.1);
|
||||
border-bottom: 1px solid ${UI.sectionBorder};
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
@@ -55,11 +64,11 @@ export function createFileBrowserModal(currentFile, onFileSelect) {
|
||||
const topRow = document.createElement('div');
|
||||
topRow.style.cssText = 'display: flex; justify-content: space-between; align-items: center;';
|
||||
topRow.innerHTML = `
|
||||
<h3 style="margin: 0; color: #aaa;">Select File from Input Folder</h3>
|
||||
<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: #333;
|
||||
border: 1px solid #555;
|
||||
background: ${UI.buttonBg};
|
||||
border: 1px solid ${UI.inputBorder};
|
||||
border-radius: 6px;
|
||||
color: #ccc;
|
||||
padding: 5px 12px;
|
||||
@@ -81,8 +90,8 @@ export function createFileBrowserModal(currentFile, onFileSelect) {
|
||||
|
||||
const breadcrumb = document.createElement('div');
|
||||
breadcrumb.className = 'folder-breadcrumb';
|
||||
breadcrumb.style.cssText = 'font-size: 12px; color: #888; cursor: pointer;';
|
||||
breadcrumb.textContent = 'input/';
|
||||
breadcrumb.style.cssText = `font-size: 12px; color: ${UI.textHint}; cursor: pointer;`;
|
||||
breadcrumb.textContent = `${currentSourceFolder}/`;
|
||||
breadcrumb.onclick = () => {
|
||||
if (currentSubfolder) {
|
||||
currentSubfolder = '';
|
||||
@@ -97,7 +106,7 @@ export function createFileBrowserModal(currentFile, onFileSelect) {
|
||||
const filterBar = document.createElement('div');
|
||||
filterBar.style.cssText = `
|
||||
padding: 10px 20px;
|
||||
border-bottom: 1px solid rgba(255,255,255,0.1);
|
||||
border-bottom: 1px solid ${UI.sectionBorder};
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
`;
|
||||
@@ -105,15 +114,15 @@ export function createFileBrowserModal(currentFile, onFileSelect) {
|
||||
<input type="text" placeholder="Search files..." class="search-input" style="
|
||||
flex: 1;
|
||||
padding: 8px 12px;
|
||||
background: rgba(45, 55, 72, 0.7);
|
||||
border: 1px solid rgba(226, 232, 240, 0.2);
|
||||
background: ${UI.inputBg};
|
||||
border: 1px solid ${UI.inputBorder};
|
||||
border-radius: 6px;
|
||||
color: #ccc;
|
||||
">
|
||||
<select class="filter-type" style="
|
||||
padding: 8px 12px;
|
||||
background: rgba(45, 55, 72, 0.7);
|
||||
border: 1px solid rgba(226, 232, 240, 0.2);
|
||||
background: ${UI.inputBg};
|
||||
border: 1px solid ${UI.inputBorder};
|
||||
border-radius: 6px;
|
||||
color: #ccc;
|
||||
">
|
||||
@@ -153,6 +162,13 @@ export function createFileBrowserModal(currentFile, onFileSelect) {
|
||||
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);
|
||||
@@ -186,19 +202,19 @@ async function loadFileThumbnails(container, currentFile, onFileSelect, overlay,
|
||||
try {
|
||||
// Update breadcrumb
|
||||
if (!currentSubfolder) {
|
||||
breadcrumbElement.textContent = 'input/';
|
||||
breadcrumbElement.textContent = `${currentSourceFolder}/`;
|
||||
} else {
|
||||
breadcrumbElement.textContent = `input/${currentSubfolder}/`;
|
||||
breadcrumbElement.textContent = `${currentSourceFolder}/${currentSubfolder}/`;
|
||||
}
|
||||
|
||||
// Fetch file list from server
|
||||
const response = await fetch('/prompt-extractor/list-files');
|
||||
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 input directory</div>';
|
||||
container.innerHTML = '<div style="text-align: center; padding: 40px; color: #aaa;">No files found in ' + currentSourceFolder + ' directory</div>';
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -245,6 +261,17 @@ async function loadFileThumbnails(container, 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>';
|
||||
@@ -255,8 +282,8 @@ function createBackItem(container, currentFile, onFileSelect, overlay, breadcrum
|
||||
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);
|
||||
background: ${UI.cardBg};
|
||||
border: 1px solid ${UI.panelBorder};
|
||||
border-radius: 6px;
|
||||
padding: 8px;
|
||||
cursor: pointer;
|
||||
@@ -270,7 +297,7 @@ function createBackItem(container, currentFile, onFileSelect, overlay, breadcrum
|
||||
preview.style.cssText = `
|
||||
width: 100%;
|
||||
height: 150px;
|
||||
background: rgba(0, 0, 0, 0.5);
|
||||
background: rgba(16, 18, 22, 0.6);
|
||||
border-radius: 4px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
@@ -291,14 +318,14 @@ function createBackItem(container, currentFile, onFileSelect, overlay, breadcrum
|
||||
item.appendChild(label);
|
||||
|
||||
item.onmouseenter = () => {
|
||||
item.style.borderColor = 'rgba(66, 153, 225, 0.9)';
|
||||
item.style.borderColor = UI.accentBorder;
|
||||
item.style.transform = 'translateY(-2px)';
|
||||
item.style.background = 'rgba(50, 112, 163, 0.5)';
|
||||
item.style.background = UI.accentSoft;
|
||||
};
|
||||
item.onmouseleave = () => {
|
||||
item.style.borderColor = 'rgba(226, 232, 240, 0.2)';
|
||||
item.style.borderColor = UI.panelBorder;
|
||||
item.style.transform = 'translateY(0)';
|
||||
item.style.background = 'rgba(45, 55, 72, 0.7)';
|
||||
item.style.background = UI.cardBg;
|
||||
};
|
||||
|
||||
item.onclick = () => {
|
||||
@@ -384,8 +411,8 @@ function createThumbnailItem(filename, currentFile, onFileSelect, overlay) {
|
||||
const isSelected = filename === currentFile;
|
||||
|
||||
item.style.cssText = `
|
||||
background: rgba(45, 55, 72, 0.7);
|
||||
border: 1px solid ${isSelected ? 'rgba(66, 153, 225, 0.9)' : 'rgba(226, 232, 240, 0.2)'};
|
||||
background: ${UI.cardBg};
|
||||
border: 1px solid ${isSelected ? UI.accent : UI.panelBorder};
|
||||
border-radius: 6px;
|
||||
padding: 8px;
|
||||
cursor: pointer;
|
||||
@@ -400,7 +427,7 @@ function createThumbnailItem(filename, currentFile, onFileSelect, overlay) {
|
||||
preview.style.cssText = `
|
||||
width: 100%;
|
||||
height: 150px;
|
||||
background: rgba(0, 0, 0, 0.5);
|
||||
background: rgba(16, 18, 22, 0.6);
|
||||
border-radius: 4px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
@@ -423,7 +450,7 @@ function createThumbnailItem(filename, currentFile, onFileSelect, overlay) {
|
||||
subfolder = filename.substring(0, lastSlash);
|
||||
basename = filename.substring(lastSlash + 1);
|
||||
}
|
||||
img.src = `/view?filename=${encodeURIComponent(basename)}&type=input&subfolder=${encodeURIComponent(subfolder)}`;
|
||||
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
|
||||
@@ -431,8 +458,8 @@ function createThumbnailItem(filename, currentFile, onFileSelect, overlay) {
|
||||
};
|
||||
preview.appendChild(img);
|
||||
} else if (videoExts.includes(ext)) {
|
||||
// Extract video thumbnail with caching
|
||||
extractVideoThumbnailCached(filename, preview);
|
||||
// Extract video thumbnail via server-side PyAV
|
||||
extractVideoThumbnailServer(filename, preview);
|
||||
} else if (ext === 'json') {
|
||||
// Use placeholder for JSON
|
||||
const img = document.createElement('img');
|
||||
@@ -467,25 +494,39 @@ function createThumbnailItem(filename, currentFile, onFileSelect, overlay) {
|
||||
// Hover effect
|
||||
item.onmouseenter = () => {
|
||||
if (!isSelected) {
|
||||
item.style.borderColor = 'rgba(66, 153, 225, 0.9)';
|
||||
item.style.borderColor = UI.accentBorder;
|
||||
item.style.transform = 'translateY(-2px)';
|
||||
item.style.background = 'rgba(50, 112, 163, 0.5)';
|
||||
item.style.background = UI.accentSoft;
|
||||
}
|
||||
};
|
||||
item.onmouseleave = () => {
|
||||
if (!isSelected) {
|
||||
item.style.borderColor = 'rgba(226, 232, 240, 0.2)';
|
||||
item.style.borderColor = UI.panelBorder;
|
||||
item.style.transform = 'translateY(0)';
|
||||
item.style.background = 'rgba(45, 55, 72, 0.7)';
|
||||
item.style.background = UI.cardBg;
|
||||
}
|
||||
};
|
||||
|
||||
// Click handler
|
||||
item.onclick = () => {
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -500,6 +541,91 @@ function getFileType(filename) {
|
||||
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();
|
||||
@@ -516,130 +642,60 @@ function filterThumbnails(container, searchText, fileType) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract thumbnail from video file with caching
|
||||
* Caches thumbnails in browser's localStorage
|
||||
* Extract thumbnail using server-side PyAV for all videos.
|
||||
* Fetches a JPEG frame from /prompt-extractor/video-frame and caches to localStorage.
|
||||
*/
|
||||
async function extractVideoThumbnailCached(filename, previewElement) {
|
||||
// Use full path as cache key to avoid conflicts between subfolders
|
||||
const cacheKey = `video_thumb_${filename.replace(/[\/\\]/g, '_')}`;
|
||||
|
||||
function extractVideoThumbnailServer(filename, previewElement) {
|
||||
const cacheKey = `video_thumb_pyav_${filename.replace(/[\/\\]/g, '_')}`;
|
||||
try {
|
||||
// Check if we have a cached thumbnail
|
||||
const cachedThumb = localStorage.getItem(cacheKey);
|
||||
|
||||
// If cache exists, use it (trust localStorage until manual regeneration)
|
||||
if (cachedThumb) {
|
||||
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 = cachedThumb;
|
||||
img.src = cached;
|
||||
previewElement.innerHTML = '';
|
||||
previewElement.appendChild(img);
|
||||
return;
|
||||
}
|
||||
} catch (error) {
|
||||
console.log('[FileBrowser] Cache check failed, generating new thumbnail:', error);
|
||||
}
|
||||
|
||||
// No cache, extract new thumbnail
|
||||
extractVideoThumbnail(filename, previewElement, cacheKey);
|
||||
}
|
||||
} catch (e) { /* ignore */ }
|
||||
|
||||
/**
|
||||
* Extract thumbnail from video file
|
||||
* Fast, lightweight version for preview purposes only
|
||||
*/
|
||||
async function extractVideoThumbnail(filename, previewElement, cacheKey = null) {
|
||||
// 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);
|
||||
|
||||
// Create video element with minimal settings for fast loading
|
||||
const video = document.createElement('video');
|
||||
video.crossOrigin = 'anonymous';
|
||||
video.preload = 'metadata';
|
||||
video.muted = true;
|
||||
video.playsInline = true;
|
||||
video.style.display = 'none';
|
||||
|
||||
video.onloadedmetadata = () => {
|
||||
// Use absolute first frame (no seeking = fastest)
|
||||
video.currentTime = 0;
|
||||
|
||||
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 */ }
|
||||
};
|
||||
|
||||
video.onseeked = async () => {
|
||||
try {
|
||||
// Create small canvas for fast rendering (thumbnail size)
|
||||
const maxWidth = 180;
|
||||
const maxHeight = 150;
|
||||
const aspectRatio = video.videoWidth / video.videoHeight;
|
||||
|
||||
let width, height;
|
||||
if (aspectRatio > maxWidth / maxHeight) {
|
||||
width = maxWidth;
|
||||
height = maxWidth / aspectRatio;
|
||||
} else {
|
||||
height = maxHeight;
|
||||
width = maxHeight * aspectRatio;
|
||||
}
|
||||
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = width;
|
||||
canvas.height = height;
|
||||
const ctx = canvas.getContext('2d', { alpha: false });
|
||||
|
||||
// Draw video frame to small canvas
|
||||
ctx.drawImage(video, 0, 0, width, height);
|
||||
|
||||
// Create image from canvas with lower quality for speed
|
||||
const dataUrl = canvas.toDataURL('image/jpeg', 0.6);
|
||||
const img = document.createElement('img');
|
||||
img.style.cssText = 'max-width: 100%; max-height: 100%; object-fit: contain;';
|
||||
img.src = dataUrl;
|
||||
|
||||
// Replace placeholder with thumbnail (display first, cache later)
|
||||
previewElement.innerHTML = '';
|
||||
previewElement.appendChild(img);
|
||||
|
||||
// Cache the thumbnail asynchronously after display (non-blocking)
|
||||
if (cacheKey) {
|
||||
setTimeout(() => {
|
||||
try {
|
||||
localStorage.setItem(cacheKey, dataUrl);
|
||||
console.log(`[FileBrowser] Cached thumbnail for: ${filename}`);
|
||||
} catch (cacheError) {
|
||||
console.log('[FileBrowser] Failed to cache thumbnail:', cacheError);
|
||||
}
|
||||
}, 0);
|
||||
}
|
||||
|
||||
// Clean up
|
||||
video.remove();
|
||||
} catch (error) {
|
||||
console.error('[FileBrowser] Error extracting video thumbnail:', error);
|
||||
// Keep placeholder on error
|
||||
video.remove();
|
||||
}
|
||||
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>`;
|
||||
};
|
||||
|
||||
video.onerror = () => {
|
||||
console.error('[FileBrowser] Error loading video for thumbnail:', filename);
|
||||
// Keep placeholder on error
|
||||
video.remove();
|
||||
};
|
||||
|
||||
// Load video from input directory
|
||||
// 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);
|
||||
}
|
||||
video.src = `/view?filename=${encodeURIComponent(basename)}&type=input&subfolder=${encodeURIComponent(subfolder)}&${Date.now()}`;
|
||||
img.src = frameUrl;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -708,3 +764,4 @@ function cleanupOrphanedThumbnailCache(currentFiles) {
|
||||
console.error('[FileBrowser] Error cleaning up cache:', error);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,316 +0,0 @@
|
||||
import { app } from "../../scripts/app.js";
|
||||
import { api } from "../../scripts/api.js";
|
||||
|
||||
/**
|
||||
* Latent Preview Extension for Prompt Manager
|
||||
* Provides animated previews during video model sampling.
|
||||
* Compatible with VideoHelperSuite - will defer to VHS if installed.
|
||||
*/
|
||||
|
||||
// Track nodes that have latent preview widgets
|
||||
let latentPreviewNodes = new Set();
|
||||
|
||||
// Store preview images per node
|
||||
let previewImagesDict = {};
|
||||
|
||||
// Animation intervals for each node
|
||||
let animateIntervals = {};
|
||||
|
||||
// Text decoder for binary messages
|
||||
const textDecoder = new TextDecoder();
|
||||
|
||||
/**
|
||||
* Get a node by ID, handling subgraphs
|
||||
*/
|
||||
function getNodeById(id) {
|
||||
// Try main graph first
|
||||
let node = app.graph.getNodeById(id);
|
||||
if (node) return node;
|
||||
|
||||
// Try subgraphs if available
|
||||
if (app.graph.subgraphs) {
|
||||
for (const subgraph of app.graph.subgraphs.values()) {
|
||||
node = subgraph.getNodeById(id);
|
||||
if (node) return node;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fit the node height to accommodate the preview widget
|
||||
*/
|
||||
function fitHeight(node) {
|
||||
node.setSize([node.size[0], node.computeSize()[1]]);
|
||||
node.graph?.setDirtyCanvas(true, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Allow drag from the preview widget
|
||||
*/
|
||||
function allowDragFromWidget(widget) {
|
||||
widget.element.addEventListener('pointerdown', (e) => {
|
||||
if (e.button === 0) {
|
||||
// Prevent default to allow canvas interaction
|
||||
e.stopPropagation();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Get or create the canvas context for latent preview
|
||||
*/
|
||||
function getLatentPreviewCtx(id, width, height) {
|
||||
const node = getNodeById(id);
|
||||
if (!node) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
let previewWidget = node.widgets?.find((w) => w.name === "pmlatentpreview");
|
||||
|
||||
if (!previewWidget) {
|
||||
// Check for and remove any native preview
|
||||
const nativePreview = node.widgets?.findIndex((w) => w.name === '$$canvas-image-preview');
|
||||
if (nativePreview >= 0) {
|
||||
node.imgs = [];
|
||||
node.widgets.splice(nativePreview, 1);
|
||||
}
|
||||
|
||||
// Create canvas element
|
||||
const canvasEl = document.createElement("canvas");
|
||||
canvasEl.style.width = "100%";
|
||||
|
||||
previewWidget = node.addDOMWidget("pmlatentpreview", "pmcanvas", canvasEl, {
|
||||
serialize: false,
|
||||
hideOnZoom: false,
|
||||
});
|
||||
previewWidget.serialize = false;
|
||||
|
||||
allowDragFromWidget(previewWidget);
|
||||
|
||||
// Forward mouse events to canvas for interaction
|
||||
const forwardEvent = (eventName, handler) => {
|
||||
canvasEl.addEventListener(eventName, (e) => {
|
||||
e.preventDefault();
|
||||
return handler(e);
|
||||
}, true);
|
||||
};
|
||||
|
||||
forwardEvent('contextmenu', (e) => app.canvas._mousedown_callback(e));
|
||||
forwardEvent('pointerdown', (e) => app.canvas._mousedown_callback(e));
|
||||
forwardEvent('mousewheel', (e) => app.canvas._mousewheel_callback(e));
|
||||
forwardEvent('pointermove', (e) => app.canvas._mousemove_callback(e));
|
||||
forwardEvent('pointerup', (e) => app.canvas._mouseup_callback(e));
|
||||
|
||||
previewWidget.computeSize = function(width) {
|
||||
if (this.aspectRatio) {
|
||||
let height = (node.size[0] - 20) / this.aspectRatio + 10;
|
||||
if (!(height > 0)) {
|
||||
height = 0;
|
||||
}
|
||||
this.computedHeight = height + 10;
|
||||
return [width, height];
|
||||
}
|
||||
return [width, -4]; // No loaded src, widget should not display
|
||||
};
|
||||
}
|
||||
|
||||
const canvasEl = previewWidget.element;
|
||||
if (!previewWidget.ctx || canvasEl.width !== width || canvasEl.height !== height) {
|
||||
previewWidget.aspectRatio = width / height;
|
||||
canvasEl.width = width;
|
||||
canvasEl.height = height;
|
||||
fitHeight(node);
|
||||
}
|
||||
|
||||
return canvasEl.getContext("2d");
|
||||
}
|
||||
|
||||
/**
|
||||
* Begin animated latent preview for a node
|
||||
*/
|
||||
function beginLatentPreview(id, previewImages, rate) {
|
||||
latentPreviewNodes.add(id);
|
||||
|
||||
if (animateIntervals[id]) {
|
||||
clearInterval(animateIntervals[id]);
|
||||
}
|
||||
|
||||
let displayIndex = 0;
|
||||
const node = getNodeById(id);
|
||||
|
||||
// Initialize progress to avoid race condition
|
||||
if (node) {
|
||||
node.progress = 0;
|
||||
}
|
||||
|
||||
animateIntervals[id] = setInterval(() => {
|
||||
const currentNode = getNodeById(id);
|
||||
if (!currentNode?.progress && currentNode?.progress !== 0) {
|
||||
clearInterval(animateIntervals[id]);
|
||||
delete animateIntervals[id];
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if we're still on the right graph
|
||||
if (app.canvas.graph.rootGraph !== currentNode.graph?.rootGraph) {
|
||||
clearInterval(animateIntervals[id]);
|
||||
delete animateIntervals[id];
|
||||
return;
|
||||
}
|
||||
|
||||
if (!previewImages[displayIndex]) {
|
||||
return;
|
||||
}
|
||||
|
||||
const ctx = getLatentPreviewCtx(
|
||||
id,
|
||||
previewImages[displayIndex].width,
|
||||
previewImages[displayIndex].height
|
||||
);
|
||||
ctx?.drawImage?.(previewImages[displayIndex], 0, 0);
|
||||
|
||||
displayIndex = (displayIndex + 1) % previewImages.length;
|
||||
}, 1000 / rate);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if VideoHelperSuite is providing latent preview
|
||||
*/
|
||||
function isVHSLatentPreviewActive() {
|
||||
// Check if VHS extension is registered and has latent preview enabled
|
||||
const vhsExtension = app.extensions.find(ext => ext.name === "VideoHelperSuite.Core");
|
||||
if (vhsExtension) {
|
||||
try {
|
||||
const vhsSetting = app.ui.settings.getSettingValue("VHS.LatentPreview");
|
||||
return vhsSetting === true;
|
||||
} catch (e) {
|
||||
// Setting doesn't exist or error
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
app.registerExtension({
|
||||
name: "PromptManager.LatentPreview",
|
||||
settings: [
|
||||
{
|
||||
id: "PromptManager.LatentPreview",
|
||||
category: ["Prompt Manager", "5. Video Sampling", "1. Animated Latent Preview"],
|
||||
name: "Display animated previews when sampling",
|
||||
tooltip: "Enable animated preview during video model sampling (KSampler). Will be disabled if VideoHelperSuite provides this feature.",
|
||||
type: "boolean",
|
||||
defaultValue: false,
|
||||
onChange(value) {
|
||||
if (!value) {
|
||||
// Remove any preview widgets when disabled
|
||||
for (const id of latentPreviewNodes) {
|
||||
const node = app.graph?.getNodeById(id);
|
||||
const widgetIndex = node?.widgets?.findIndex((w) => w.name === 'pmlatentpreview');
|
||||
if (widgetIndex >= 0) {
|
||||
const widget = node.widgets.splice(widgetIndex, 1)[0];
|
||||
widget.onRemove?.();
|
||||
}
|
||||
}
|
||||
latentPreviewNodes = new Set();
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "PromptManager.LatentPreviewRate",
|
||||
category: ["Prompt Manager", "5. Video Sampling", "2. Playback Rate Override"],
|
||||
name: "Playback rate override",
|
||||
tooltip: "Force a specific frame rate for latent preview playback. Set to 0 for auto-detect based on video model. This is the preview FPS, not the output video FPS.",
|
||||
type: "number",
|
||||
attrs: {
|
||||
min: 0,
|
||||
step: 1,
|
||||
max: 60,
|
||||
},
|
||||
defaultValue: 0,
|
||||
},
|
||||
],
|
||||
|
||||
async setup() {
|
||||
// Hook into graphToPrompt to pass our settings to the backend
|
||||
const originalGraphToPrompt = app.graphToPrompt;
|
||||
|
||||
app.graphToPrompt = async function() {
|
||||
const res = await originalGraphToPrompt.apply(this, arguments);
|
||||
|
||||
// Check if VHS is handling latent preview
|
||||
const vhsActive = isVHSLatentPreviewActive();
|
||||
|
||||
if (!vhsActive) {
|
||||
// Add our settings to the workflow extra data
|
||||
res.workflow.extra['PM_latentpreview'] = app.ui.settings.getSettingValue("PromptManager.LatentPreview");
|
||||
res.workflow.extra['PM_latentpreviewrate'] = app.ui.settings.getSettingValue("PromptManager.LatentPreviewRate");
|
||||
}
|
||||
|
||||
return res;
|
||||
};
|
||||
|
||||
console.log("[PromptManager] Latent preview extension loaded");
|
||||
},
|
||||
|
||||
async init() {
|
||||
// Clear preview nodes on execution complete
|
||||
api.addEventListener('executing', ({ detail }) => {
|
||||
if (detail === null) {
|
||||
// Execution complete - clean up progress indicators
|
||||
for (const id of latentPreviewNodes) {
|
||||
const node = getNodeById(id);
|
||||
if (node) {
|
||||
delete node.progress;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Listen for latent preview initialization from backend
|
||||
api.addEventListener('PM_latentpreview', ({ detail }) => {
|
||||
if (detail.id == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Skip if VHS is active
|
||||
if (isVHSLatentPreviewActive()) {
|
||||
return;
|
||||
}
|
||||
|
||||
const previewImages = previewImagesDict[detail.id] = [];
|
||||
previewImages.length = detail.length;
|
||||
|
||||
// Handle node ID parts (for subgraphs)
|
||||
const idParts = detail.id.split(':');
|
||||
for (let i = 1; i <= idParts.length; i++) {
|
||||
const id = idParts.slice(0, i).join(':');
|
||||
beginLatentPreview(id, previewImages, detail.rate);
|
||||
}
|
||||
});
|
||||
|
||||
// Listen for binary preview images
|
||||
api.addEventListener('b_preview', async (e) => {
|
||||
// Only handle if we have active animations and VHS isn't handling it
|
||||
if (Object.keys(animateIntervals).length === 0 || isVHSLatentPreviewActive()) {
|
||||
return;
|
||||
}
|
||||
|
||||
e.preventDefault();
|
||||
e.stopImmediatePropagation();
|
||||
e.stopPropagation();
|
||||
|
||||
const dv = new DataView(await e.detail.slice(0, 24).arrayBuffer());
|
||||
const index = dv.getUint32(4);
|
||||
const idlen = dv.getUint8(8);
|
||||
const id = textDecoder.decode(dv.buffer.slice(9, 9 + idlen));
|
||||
|
||||
// Only process if this is our preview (PM_ prefix in the workflow extra)
|
||||
if (previewImagesDict[id]) {
|
||||
previewImagesDict[id][index] = await window.createImageBitmap(e.detail.slice(24));
|
||||
}
|
||||
|
||||
return false;
|
||||
}, true);
|
||||
},
|
||||
});
|
||||
+465
-69
@@ -1,4 +1,4 @@
|
||||
/**
|
||||
/**
|
||||
* PromptExtractor Extension for ComfyUI
|
||||
* Adds image preview functionality for the extractor node
|
||||
*/
|
||||
@@ -10,6 +10,9 @@ import { createFileBrowserModal } from "./file_browser.js";
|
||||
// Placeholder image path - loaded from static PNG file
|
||||
const PLACEHOLDER_IMAGE_PATH = new URL("./placeholder.png", import.meta.url).href;
|
||||
|
||||
// Track videos that the browser cannot decode (H265/yuv444) - skip browser attempts on scrub
|
||||
const _nonBrowserDecodableVideos = new Set();
|
||||
|
||||
/**
|
||||
* Extract metadata from PNG file
|
||||
* Reads tEXt/iTXt chunks for prompt and workflow (ComfyUI native approach)
|
||||
@@ -165,9 +168,47 @@ function parseA1111Parameters(parametersText) {
|
||||
result.negative_prompt = remainder.trim();
|
||||
}
|
||||
|
||||
// Extract model name from settings line (e.g. "Model: modelName")
|
||||
const modelMatch = parametersText.match(/\bModel:\s*([^,\n]+)/);
|
||||
if (modelMatch) {
|
||||
result.model = modelMatch[1].trim();
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
function _isLoraAvailableForSort(lora) {
|
||||
if (!lora) return true;
|
||||
if (lora.available === false) return false;
|
||||
if (lora.found === false) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
function _sortLorasMissingLast(loras) {
|
||||
const src = Array.isArray(loras) ? [...loras] : [];
|
||||
return src.sort((a, b) => {
|
||||
const aAvailable = _isLoraAvailableForSort(a);
|
||||
const bAvailable = _isLoraAvailableForSort(b);
|
||||
if (aAvailable !== bAvailable) return aAvailable ? -1 : 1;
|
||||
return String(a?.name || "").localeCompare(String(b?.name || ""));
|
||||
});
|
||||
}
|
||||
|
||||
function _normalizeExtractedLoraOrder(extracted) {
|
||||
if (!extracted || typeof extracted !== "object") return extracted;
|
||||
const normalized = { ...extracted };
|
||||
if (Array.isArray(normalized.loras)) {
|
||||
normalized.loras = _sortLorasMissingLast(normalized.loras);
|
||||
}
|
||||
if (Array.isArray(normalized.loras_a)) {
|
||||
normalized.loras_a = _sortLorasMissingLast(normalized.loras_a);
|
||||
}
|
||||
if (Array.isArray(normalized.loras_b)) {
|
||||
normalized.loras_b = _sortLorasMissingLast(normalized.loras_b);
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract metadata from JPEG/WebP file
|
||||
* Reads EXIF UserComment field (0x9286) for workflow metadata
|
||||
@@ -228,38 +269,58 @@ async function getJPEGMetadata(file) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse EXIF IFD (Image File Directory) for UserComment
|
||||
* Parse EXIF IFD (Image File Directory) for ComfyUI metadata
|
||||
* ComfyUI stores metadata in:
|
||||
* - 0x010e (ImageDescription): "Workflow: {json}"
|
||||
* - 0x010f (Make): "Prompt: {json}"
|
||||
* - 0x9286 (UserComment): direct JSON (some tools)
|
||||
*/
|
||||
function parseIFD(imageData, ifdOffset, tiffOffset, littleEndian, decoder) {
|
||||
const dataView = new DataView(imageData.buffer);
|
||||
const numEntries = dataView.getUint16(ifdOffset, littleEndian);
|
||||
|
||||
// Collect workflow and prompt from separate EXIF tags
|
||||
let workflow = null;
|
||||
let prompt = null;
|
||||
|
||||
for (let i = 0; i < numEntries; i++) {
|
||||
const entryOffset = ifdOffset + 2 + (i * 12);
|
||||
const tag = dataView.getUint16(entryOffset, littleEndian);
|
||||
|
||||
// UserComment tag (0x9286)
|
||||
if (tag === 0x9286) {
|
||||
const format = dataView.getUint16(entryOffset + 2, littleEndian);
|
||||
// Tags that store string data: 0x010e (ImageDescription), 0x010f (Make), 0x9286 (UserComment)
|
||||
if (tag === 0x010e || tag === 0x010f || tag === 0x9286) {
|
||||
const count = dataView.getUint32(entryOffset + 4, littleEndian);
|
||||
const valueOffset = dataView.getUint32(entryOffset + 8, littleEndian);
|
||||
|
||||
// Get actual data offset
|
||||
// Get actual data offset (values > 4 bytes are stored at an offset)
|
||||
const dataOffset = count > 4 ? tiffOffset + valueOffset : entryOffset + 8;
|
||||
|
||||
// Read comment data
|
||||
const commentData = imageData.slice(dataOffset, dataOffset + count);
|
||||
let comment = decoder.decode(commentData);
|
||||
// Read the raw string data
|
||||
const rawData = imageData.slice(dataOffset, dataOffset + count);
|
||||
let text = decoder.decode(rawData);
|
||||
|
||||
// Remove ASCII/UNICODE prefix and null bytes
|
||||
comment = comment.replace(/^(ASCII|UNICODE)\x00*/, '').replace(/\x00/g, '');
|
||||
// Remove ASCII/UNICODE prefix and null bytes (for UserComment tag)
|
||||
text = text.replace(/^(ASCII|UNICODE)\x00*/, '').replace(/\x00/g, '').trim();
|
||||
|
||||
// Try to parse as JSON
|
||||
try {
|
||||
const json = JSON.parse(comment);
|
||||
return json;
|
||||
} catch (e) {
|
||||
console.error('[PromptExtractor] Failed to parse JPEG EXIF metadata:', e);
|
||||
// ComfyUI format: "Workflow: {json}" or "Prompt: {json}" with prefix
|
||||
if (text.startsWith('Workflow:')) {
|
||||
const jsonStr = text.substring('Workflow:'.length).trim();
|
||||
try { workflow = JSON.parse(jsonStr); } catch (e) {
|
||||
console.error('[PromptExtractor] Failed to parse Workflow from EXIF:', e);
|
||||
}
|
||||
} else if (text.startsWith('Prompt:')) {
|
||||
const jsonStr = text.substring('Prompt:'.length).trim();
|
||||
try { prompt = JSON.parse(jsonStr); } catch (e) {
|
||||
console.error('[PromptExtractor] Failed to parse Prompt from EXIF:', e);
|
||||
}
|
||||
} else {
|
||||
// Try parsing as direct JSON (UserComment from some tools)
|
||||
try {
|
||||
const json = JSON.parse(text);
|
||||
return json;
|
||||
} catch (e) {
|
||||
// Not JSON, skip
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -271,9 +332,79 @@ function parseIFD(imageData, ifdOffset, tiffOffset, littleEndian, decoder) {
|
||||
}
|
||||
}
|
||||
|
||||
// Return collected workflow/prompt if found
|
||||
if (workflow || prompt) {
|
||||
return { workflow, prompt };
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract metadata from WebP file
|
||||
* WebP uses RIFF container format with EXIF data stored in an "EXIF" chunk
|
||||
*/
|
||||
async function getWebPMetadata(file) {
|
||||
return new Promise((resolve) => {
|
||||
const reader = new FileReader();
|
||||
reader.onload = (event) => {
|
||||
const data = new Uint8Array(event.target.result);
|
||||
const dataView = new DataView(data.buffer);
|
||||
const decoder = new TextDecoder();
|
||||
|
||||
// Verify RIFF + WEBP signature
|
||||
if (data.length < 12) { resolve(null); return; }
|
||||
const riff = String.fromCharCode(data[0], data[1], data[2], data[3]);
|
||||
const webp = String.fromCharCode(data[8], data[9], data[10], data[11]);
|
||||
if (riff !== 'RIFF' || webp !== 'WEBP') {
|
||||
resolve(null);
|
||||
return;
|
||||
}
|
||||
|
||||
// Walk RIFF chunks looking for EXIF chunk
|
||||
let offset = 12;
|
||||
while (offset < data.length - 8) {
|
||||
const chunkId = String.fromCharCode(data[offset], data[offset + 1], data[offset + 2], data[offset + 3]);
|
||||
const chunkSize = dataView.getUint32(offset + 4, true); // RIFF uses little-endian
|
||||
|
||||
if (chunkId === 'EXIF') {
|
||||
// EXIF chunk data starts after the chunk header (8 bytes)
|
||||
let exifStart = offset + 8;
|
||||
|
||||
// Some WebP files include "Exif\0\0" prefix before TIFF header, some don't
|
||||
const possibleExif = String.fromCharCode(data[exifStart], data[exifStart + 1], data[exifStart + 2], data[exifStart + 3]);
|
||||
if (possibleExif === 'Exif') {
|
||||
exifStart += 6; // Skip "Exif\0\0"
|
||||
}
|
||||
|
||||
// Parse TIFF header
|
||||
if (exifStart + 8 <= data.length) {
|
||||
const byteOrder = dataView.getUint16(exifStart);
|
||||
const littleEndian = byteOrder === 0x4949;
|
||||
|
||||
// Verify TIFF magic number (42)
|
||||
const tiffMagic = dataView.getUint16(exifStart + 2, littleEndian);
|
||||
if (tiffMagic === 42) {
|
||||
const ifd0Offset = exifStart + dataView.getUint32(exifStart + 4, littleEndian);
|
||||
const metadata = parseIFD(data, ifd0Offset, exifStart, littleEndian, decoder);
|
||||
if (metadata) {
|
||||
resolve(metadata);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Move to next chunk (pad to even size per RIFF spec)
|
||||
offset += 8 + chunkSize + (chunkSize % 2);
|
||||
}
|
||||
|
||||
resolve(null);
|
||||
};
|
||||
reader.readAsArrayBuffer(file);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract metadata from JSON file
|
||||
*/
|
||||
@@ -362,13 +493,13 @@ async function getVideoMetadata(file) {
|
||||
/**
|
||||
* Request Python to extract video metadata using ffprobe (fallback)
|
||||
*/
|
||||
async function extractVideoMetadataWithPython(filename) {
|
||||
async function extractVideoMetadataWithPython(filename, source = 'input') {
|
||||
try {
|
||||
console.log(`[PromptExtractor] Requesting Python ffprobe extraction for: ${filename}`);
|
||||
const response = await api.fetchApi("/prompt-extractor/extract-video-metadata", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ filename })
|
||||
body: JSON.stringify({ filename, source })
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
@@ -438,7 +569,7 @@ async function cacheVideoFrame(filename, frameData, framePosition) {
|
||||
/**
|
||||
* Create and show image preview modal
|
||||
*/
|
||||
function showImagePreviewModal(filename) {
|
||||
function showImagePreviewModal(filename, viewType) {
|
||||
// Build image URL
|
||||
let actualFilename = filename;
|
||||
let subfolder = "";
|
||||
@@ -449,7 +580,7 @@ function showImagePreviewModal(filename) {
|
||||
actualFilename = filename.substring(lastSlash + 1);
|
||||
}
|
||||
|
||||
let imageUrl = `/view?filename=${encodeURIComponent(actualFilename)}&type=input`;
|
||||
let imageUrl = `/view?filename=${encodeURIComponent(actualFilename)}&type=${viewType || 'input'}`;
|
||||
if (subfolder) {
|
||||
imageUrl += `&subfolder=${encodeURIComponent(subfolder)}`;
|
||||
}
|
||||
@@ -497,7 +628,7 @@ function showImagePreviewModal(filename) {
|
||||
`;
|
||||
|
||||
const closeBtn = document.createElement('button');
|
||||
closeBtn.textContent = '✕';
|
||||
closeBtn.textContent = '?';
|
||||
closeBtn.style.cssText = `
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
border: none;
|
||||
@@ -543,7 +674,7 @@ function showImagePreviewModal(filename) {
|
||||
img.onerror = () => {
|
||||
imageContainer.innerHTML = `
|
||||
<div style="color: #ff6666; font-family: sans-serif; text-align: center;">
|
||||
<div style="font-size: 48px; margin-bottom: 10px;">⚠️</div>
|
||||
<div style="font-size: 48px; margin-bottom: 10px;">??</div>
|
||||
<div>Failed to load image</div>
|
||||
<div style="font-size: 12px; margin-top: 5px; opacity: 0.7;">${filename}</div>
|
||||
</div>
|
||||
@@ -590,7 +721,7 @@ function showImagePreviewModal(filename) {
|
||||
/**
|
||||
* Create and show video preview modal
|
||||
*/
|
||||
function showVideoPreviewModal(filename) {
|
||||
function showVideoPreviewModal(filename, viewType) {
|
||||
// Build video URL
|
||||
let actualFilename = filename;
|
||||
let subfolder = "";
|
||||
@@ -601,7 +732,7 @@ function showVideoPreviewModal(filename) {
|
||||
actualFilename = filename.substring(lastSlash + 1);
|
||||
}
|
||||
|
||||
let videoUrl = `/view?filename=${encodeURIComponent(actualFilename)}&type=input`;
|
||||
let videoUrl = `/view?filename=${encodeURIComponent(actualFilename)}&type=${viewType || 'input'}`;
|
||||
if (subfolder) {
|
||||
videoUrl += `&subfolder=${encodeURIComponent(subfolder)}`;
|
||||
}
|
||||
@@ -649,7 +780,7 @@ function showVideoPreviewModal(filename) {
|
||||
`;
|
||||
|
||||
const closeBtn = document.createElement('button');
|
||||
closeBtn.textContent = '✕';
|
||||
closeBtn.textContent = '?';
|
||||
closeBtn.style.cssText = `
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
border: none;
|
||||
@@ -694,15 +825,39 @@ function showVideoPreviewModal(filename) {
|
||||
box-shadow: 0 10px 40px rgba(0, 0, 0, 0.5);
|
||||
`;
|
||||
|
||||
// Error handling
|
||||
// Error handling - browser can't decode (H265/yuv444)
|
||||
video.onerror = () => {
|
||||
videoContainer.innerHTML = `
|
||||
<div style="color: #ff6666; font-family: sans-serif; text-align: center;">
|
||||
<div style="font-size: 48px; margin-bottom: 10px;">⚠️</div>
|
||||
<div>Failed to load video</div>
|
||||
<div style="font-size: 12px; margin-top: 5px; opacity: 0.7;">${filename}</div>
|
||||
</div>
|
||||
// Fall back to server-extracted frame with overlay
|
||||
const frameUrl = `/prompt-extractor/video-frame?filename=${encodeURIComponent(filename)}&source=${viewType || 'input'}&position=0`;
|
||||
const fallbackImg = document.createElement('img');
|
||||
fallbackImg.style.cssText = `
|
||||
max-width: 100%; max-height: 80vh; border-radius: 8px;
|
||||
box-shadow: 0 10px 40px rgba(0, 0, 0, 0.5);
|
||||
`;
|
||||
fallbackImg.onload = () => {
|
||||
videoContainer.innerHTML = '';
|
||||
videoContainer.style.position = 'relative';
|
||||
videoContainer.appendChild(fallbackImg);
|
||||
const msgOverlay = document.createElement('div');
|
||||
msgOverlay.style.cssText = `
|
||||
position: absolute; bottom: 20px; left: 50%; transform: translateX(-50%);
|
||||
background: rgba(0, 0, 0, 0.75); color: #ccc; padding: 8px 16px;
|
||||
border-radius: 6px; font-family: sans-serif; font-size: 13px;
|
||||
pointer-events: none; white-space: nowrap;
|
||||
`;
|
||||
msgOverlay.textContent = 'H265/yuv444 \u2014 browser playback not supported';
|
||||
videoContainer.appendChild(msgOverlay);
|
||||
};
|
||||
fallbackImg.onerror = () => {
|
||||
videoContainer.innerHTML = `
|
||||
<div style="color: #aaa; font-family: sans-serif; text-align: center;">
|
||||
<div style="font-size: 48px; margin-bottom: 10px;">\uD83C\uDFAC</div>
|
||||
<div>This video format cannot be played in the browser</div>
|
||||
<div style="font-size: 12px; margin-top: 5px; opacity: 0.7;">H265 or yuv444 encoded</div>
|
||||
</div>
|
||||
`;
|
||||
};
|
||||
fallbackImg.src = frameUrl;
|
||||
};
|
||||
|
||||
videoContainer.appendChild(video);
|
||||
@@ -777,7 +932,7 @@ app.registerExtension({
|
||||
// Find the node with this filename
|
||||
if (app.graph && app.graph._nodes) {
|
||||
for (const node of app.graph._nodes) {
|
||||
if (node.type === "PromptExtractor") {
|
||||
if (node.type === "PromptExtractor" || node.type === "WorkflowExtractor") {
|
||||
const imageWidget = node.widgets?.find(w => w.name === "image");
|
||||
const frameWidget = node.widgets?.find(w => w.name === "frame_position");
|
||||
|
||||
@@ -799,7 +954,7 @@ app.registerExtension({
|
||||
},
|
||||
|
||||
async beforeRegisterNodeDef(nodeType, nodeData, app) {
|
||||
if (nodeData.name === "PromptExtractor") {
|
||||
if (nodeData.name === "PromptExtractor" || nodeData.name === "WorkflowExtractor") {
|
||||
const onNodeCreated = nodeType.prototype.onNodeCreated;
|
||||
|
||||
nodeType.prototype.onNodeCreated = function () {
|
||||
@@ -812,10 +967,38 @@ app.registerExtension({
|
||||
// Track the currently loaded image filename and frame position to prevent unnecessary reloads
|
||||
node._loadedImageFilename = null;
|
||||
node._loadedFramePosition = null;
|
||||
|
||||
// Track source folder for URL type
|
||||
node._sourceFolder = 'input';
|
||||
// Find the frame_position widget (slider) early so we can reference it
|
||||
const framePositionWidget = this.widgets?.find(w => w.name === "frame_position");
|
||||
|
||||
// Find the source_folder widget
|
||||
const sourceFolderWidget = this.widgets?.find(w => w.name === "source_folder");
|
||||
if (sourceFolderWidget) {
|
||||
node._sourceFolder = sourceFolderWidget.value || 'input';
|
||||
const origSourceFolderCb = sourceFolderWidget.callback;
|
||||
sourceFolderWidget.callback = async function(value) {
|
||||
if (origSourceFolderCb) origSourceFolderCb.apply(this, arguments);
|
||||
node._sourceFolder = value || 'input';
|
||||
// Refresh file list for the new source folder
|
||||
try {
|
||||
const listResponse = await api.fetchApi(`/prompt-extractor/list-files?source=${encodeURIComponent(value)}`);
|
||||
if (listResponse.ok) {
|
||||
const result = await listResponse.json();
|
||||
if (imageWidget) {
|
||||
imageWidget.options.values = ["(none)", ...(result.files || [])];
|
||||
// Reset selection since files are from a different folder
|
||||
imageWidget.value = "(none)";
|
||||
if (imageWidget.callback) imageWidget.callback("(none)");
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn('[PromptExtractor] Could not fetch file list for source folder:', err);
|
||||
}
|
||||
node.setDirtyCanvas(true);
|
||||
};
|
||||
}
|
||||
|
||||
// Find the image widget (combo dropdown)
|
||||
const imageWidget = this.widgets?.find(w => w.name === "image");
|
||||
if (imageWidget) {
|
||||
@@ -832,6 +1015,18 @@ app.registerExtension({
|
||||
originalCallback.apply(this, arguments);
|
||||
}
|
||||
|
||||
// Reset metadata cache when selecting a new file
|
||||
node._metadataCached = false;
|
||||
|
||||
// Reset frame position to 0 when selecting a new video
|
||||
if (value && framePositionWidget) {
|
||||
const ext = value.split('.').pop().toLowerCase();
|
||||
const videoExtensions = ['mp4', 'webm', 'mov', 'avi'];
|
||||
if (videoExtensions.includes(ext)) {
|
||||
framePositionWidget.value = 0;
|
||||
}
|
||||
}
|
||||
|
||||
// Load and display the image/video (handles all display logic)
|
||||
loadAndDisplayImage(node, value);
|
||||
};
|
||||
@@ -857,10 +1052,11 @@ app.registerExtension({
|
||||
const imageWidgetIndex = this.widgets.indexOf(imageWidget);
|
||||
const browseButton = {
|
||||
type: "button",
|
||||
name: "📁 Browse Files",
|
||||
name: "\uD83D\uDCC1 Browse Files",
|
||||
value: null,
|
||||
callback: () => {
|
||||
const currentFile = imageWidget.value === "(none)" ? null : imageWidget.value;
|
||||
const sourceFolder = node._sourceFolder || 'input';
|
||||
|
||||
// Open file browser modal
|
||||
createFileBrowserModal(currentFile, (selectedFile) => {
|
||||
@@ -874,7 +1070,7 @@ app.registerExtension({
|
||||
|
||||
// Mark node as needing update
|
||||
node.setDirtyCanvas(true);
|
||||
});
|
||||
}, sourceFolder);
|
||||
},
|
||||
serialize: false // Don't save button state
|
||||
};
|
||||
@@ -958,6 +1154,69 @@ app.registerExtension({
|
||||
node.onConfigure = function(info) {
|
||||
const result = onConfigure ? onConfigure.apply(this, arguments) : undefined;
|
||||
|
||||
// ── Migration: remove stale inputs/outputs from old workflows ──
|
||||
const isWorkflowExtractor = this.type === "WorkflowExtractor";
|
||||
const VALID_INPUTS = isWorkflowExtractor
|
||||
? new Set([])
|
||||
: new Set(["lora_stack_a", "lora_stack_b"]);
|
||||
if (this.inputs) {
|
||||
for (let i = this.inputs.length - 1; i >= 0; i--) {
|
||||
if (!VALID_INPUTS.has(this.inputs[i].name)) {
|
||||
this.removeInput(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
const VALID_OUTPUTS = isWorkflowExtractor
|
||||
? [
|
||||
{ name: "workflow_data", type: "WORKFLOW_DATA" },
|
||||
{ name: "image", type: "IMAGE" },
|
||||
]
|
||||
: [
|
||||
{ name: "positive_prompt", type: "STRING" },
|
||||
{ name: "negative_prompt", type: "STRING" },
|
||||
{ name: "lora_stack_a", type: "LORA_STACK" },
|
||||
{ name: "lora_stack_b", type: "LORA_STACK" },
|
||||
{ name: "workflow_data", type: "WORKFLOW_DATA" },
|
||||
{ name: "image", type: "IMAGE" },
|
||||
];
|
||||
if (this.outputs) {
|
||||
const namesMatch = this.outputs.length === VALID_OUTPUTS.length &&
|
||||
VALID_OUTPUTS.every((v, i) => this.outputs[i]?.name === v.name && this.outputs[i]?.type === v.type);
|
||||
if (!namesMatch) {
|
||||
// Preserve existing links before resetting
|
||||
const savedLinks = this.outputs.map(o => o.links ? [...o.links] : null);
|
||||
this.outputs.length = 0;
|
||||
for (let i = 0; i < VALID_OUTPUTS.length; i++) {
|
||||
this.addOutput(VALID_OUTPUTS[i].name, VALID_OUTPUTS[i].type);
|
||||
// Restore links for slots that existed at the same index
|
||||
if (savedLinks[i]) this.outputs[i].links = savedLinks[i];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Restore source_folder from widget value
|
||||
const sfWidget = this.widgets?.find(w => w.name === "source_folder");
|
||||
if (sfWidget) {
|
||||
node._sourceFolder = sfWidget.value || 'input';
|
||||
}
|
||||
|
||||
// Refresh file list if source folder is not the default (input)
|
||||
// INPUT_TYPES only lists input files, so output files need to be fetched
|
||||
if (node._sourceFolder === 'output' && imageWidget) {
|
||||
api.fetchApi(`/prompt-extractor/list-files?source=output`).then(resp => {
|
||||
if (resp.ok) return resp.json();
|
||||
}).then(data => {
|
||||
if (data && data.files) {
|
||||
const savedValue = imageWidget.value;
|
||||
imageWidget.options.values = ["(none)", ...data.files];
|
||||
// Restore saved value if it exists in the new list
|
||||
if (savedValue && data.files.includes(savedValue)) {
|
||||
imageWidget.value = savedValue;
|
||||
}
|
||||
}
|
||||
}).catch(() => {});
|
||||
}
|
||||
|
||||
// Restore frame_position if it exists in the workflow data
|
||||
if (info && info.widgets_values && framePositionWidget) {
|
||||
// Find the frame_position widget's index
|
||||
@@ -1055,7 +1314,8 @@ app.registerExtension({
|
||||
if (imageWidget) {
|
||||
// Fetch updated file list from server
|
||||
try {
|
||||
const listResponse = await api.fetchApi('/prompt-extractor/list-files');
|
||||
const sourceFolder = node._sourceFolder || 'input';
|
||||
const listResponse = await api.fetchApi(`/prompt-extractor/list-files?source=${encodeURIComponent(sourceFolder)}`);
|
||||
if (listResponse.ok) {
|
||||
const result = await listResponse.json();
|
||||
if (result.files && result.files.length > 0) {
|
||||
@@ -1196,11 +1456,12 @@ app.registerExtension({
|
||||
localPos[1] >= bounds.y && localPos[1] <= bounds.y + bounds.height) {
|
||||
// Open preview modal
|
||||
const imageWidget = node.widgets?.find(w => w.name === "image");
|
||||
const viewType = node._sourceFolder || 'input';
|
||||
if (imageWidget && imageWidget.value) {
|
||||
if (node._isVideoFile) {
|
||||
showVideoPreviewModal(imageWidget.value);
|
||||
showVideoPreviewModal(imageWidget.value, viewType);
|
||||
} else {
|
||||
showImagePreviewModal(imageWidget.value);
|
||||
showImagePreviewModal(imageWidget.value, viewType);
|
||||
}
|
||||
}
|
||||
return true; // Consume the event
|
||||
@@ -1228,6 +1489,7 @@ async function extractAndUpdateMetadata(node, filename) {
|
||||
|
||||
try {
|
||||
const ext = filename.split('.').pop().toLowerCase();
|
||||
const viewType = node._sourceFolder || 'input';
|
||||
|
||||
// Split path into filename and subfolder for proper URL handling
|
||||
let actualFilename = filename;
|
||||
@@ -1240,7 +1502,7 @@ async function extractAndUpdateMetadata(node, filename) {
|
||||
}
|
||||
|
||||
// Build URL with subfolder parameter if present
|
||||
let fileUrl = `/view?filename=${encodeURIComponent(actualFilename)}&type=input`;
|
||||
let fileUrl = `/view?filename=${encodeURIComponent(actualFilename)}&type=${viewType}`;
|
||||
if (subfolder) {
|
||||
fileUrl += `&subfolder=${encodeURIComponent(subfolder)}`;
|
||||
}
|
||||
@@ -1260,7 +1522,9 @@ async function extractAndUpdateMetadata(node, filename) {
|
||||
// Extract based on file type
|
||||
if (ext === 'png') {
|
||||
metadata = await getPNGMetadata(fileBlob);
|
||||
} else if (['jpg', 'jpeg', 'webp'].includes(ext)) {
|
||||
} else if (ext === 'webp') {
|
||||
metadata = await getWebPMetadata(fileBlob);
|
||||
} else if (['jpg', 'jpeg'].includes(ext)) {
|
||||
metadata = await getJPEGMetadata(fileBlob);
|
||||
} else if (ext === 'json') {
|
||||
metadata = await getJSONMetadata(fileBlob);
|
||||
@@ -1271,7 +1535,7 @@ async function extractAndUpdateMetadata(node, filename) {
|
||||
// If JavaScript parser failed, ask Python to try with ffprobe
|
||||
if (metadata === null) {
|
||||
console.log(`[PromptExtractor] JavaScript parser returned null, trying Python ffprobe for: ${filename}`);
|
||||
metadata = await extractVideoMetadataWithPython(filename);
|
||||
metadata = await extractVideoMetadataWithPython(filename, viewType);
|
||||
|
||||
if (metadata) {
|
||||
console.log(`[PromptExtractor] Successfully got metadata from Python for: ${filename}`);
|
||||
@@ -1299,6 +1563,29 @@ async function extractAndUpdateMetadata(node, filename) {
|
||||
// Force canvas redraw to update indicator
|
||||
node.setDirtyCanvas(true, true);
|
||||
app.graph.setDirtyCanvas(true, true);
|
||||
|
||||
// Extract full preview data for WorkflowBuilder's "Update Workflow" button.
|
||||
// Runs the Python parse+build pipeline on the cached metadata so WB can
|
||||
// pull it without executing PromptExtractor (live-menu pattern).
|
||||
if (node.hasWorkflow) {
|
||||
try {
|
||||
const sourceFolder = node._sourceFolder || 'input';
|
||||
const previewResp = await fetch(
|
||||
`/prompt-extractor/extract-preview?filename=${encodeURIComponent(filename)}&source=${encodeURIComponent(sourceFolder)}`
|
||||
);
|
||||
if (previewResp.ok) {
|
||||
const previewData = await previewResp.json();
|
||||
if (previewData.extracted) {
|
||||
const normalizedExtracted = _normalizeExtractedLoraOrder(previewData.extracted);
|
||||
node.properties = node.properties || {};
|
||||
node.properties.pe_extracted_data = JSON.stringify(normalizedExtracted);
|
||||
console.log(`[PromptExtractor] Cached extracted preview data for: ${filename}`);
|
||||
}
|
||||
}
|
||||
} catch (previewErr) {
|
||||
console.warn('[PromptExtractor] Could not cache preview data:', previewErr);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("[PromptExtractor] Error extracting metadata:", error);
|
||||
node.hasWorkflow = false;
|
||||
@@ -1347,9 +1634,23 @@ async function loadAndDisplayImage(node, filename) {
|
||||
*/
|
||||
async function loadImageFile(node, filename) {
|
||||
try {
|
||||
const viewType = node._sourceFolder || 'input';
|
||||
|
||||
// Fetch the image file to extract metadata
|
||||
const imageBlob = await fetch(`/view?filename=${encodeURIComponent(filename)}&type=input`)
|
||||
.then(res => res.blob());
|
||||
// Handle subfolder paths
|
||||
let actualFilename = filename;
|
||||
let subfolder = "";
|
||||
if (filename.includes('/')) {
|
||||
const lastSlash = filename.lastIndexOf('/');
|
||||
subfolder = filename.substring(0, lastSlash);
|
||||
actualFilename = filename.substring(lastSlash + 1);
|
||||
}
|
||||
let fileUrl = `/view?filename=${encodeURIComponent(actualFilename)}&type=${viewType}`;
|
||||
if (subfolder) {
|
||||
fileUrl += `&subfolder=${encodeURIComponent(subfolder)}`;
|
||||
}
|
||||
|
||||
const imageBlob = await fetch(fileUrl).then(res => res.blob());
|
||||
|
||||
// Extract metadata from image file (PNG or JPEG/WebP)
|
||||
const ext = filename.split('.').pop().toLowerCase();
|
||||
@@ -1357,7 +1658,9 @@ async function loadImageFile(node, filename) {
|
||||
|
||||
if (ext === 'png') {
|
||||
metadata = await getPNGMetadata(imageBlob);
|
||||
} else if (['jpg', 'jpeg', 'webp'].includes(ext)) {
|
||||
} else if (ext === 'webp') {
|
||||
metadata = await getWebPMetadata(imageBlob);
|
||||
} else if (['jpg', 'jpeg'].includes(ext)) {
|
||||
metadata = await getJPEGMetadata(imageBlob);
|
||||
}
|
||||
|
||||
@@ -1393,8 +1696,8 @@ async function loadImageFile(node, filename) {
|
||||
showPlaceholder(node);
|
||||
};
|
||||
|
||||
// Load from input directory
|
||||
img.src = `/view?filename=${encodeURIComponent(filename)}&type=input&${Date.now()}`;
|
||||
// Load from input/output directory
|
||||
img.src = `${fileUrl}&${Date.now()}`;
|
||||
} catch (error) {
|
||||
console.error("[PromptExtractor] Error loading image:", error);
|
||||
showPlaceholder(node);
|
||||
@@ -1406,9 +1709,22 @@ async function loadImageFile(node, filename) {
|
||||
*/
|
||||
async function loadJSONFile(node, filename) {
|
||||
try {
|
||||
const viewType = node._sourceFolder || 'input';
|
||||
|
||||
// Fetch the JSON file
|
||||
const jsonBlob = await fetch(`/view?filename=${encodeURIComponent(filename)}&type=input`)
|
||||
.then(res => res.blob());
|
||||
let actualFilename = filename;
|
||||
let subfolder = "";
|
||||
if (filename.includes('/')) {
|
||||
const lastSlash = filename.lastIndexOf('/');
|
||||
subfolder = filename.substring(0, lastSlash);
|
||||
actualFilename = filename.substring(lastSlash + 1);
|
||||
}
|
||||
let fileUrl = `/view?filename=${encodeURIComponent(actualFilename)}&type=${viewType}`;
|
||||
if (subfolder) {
|
||||
fileUrl += `&subfolder=${encodeURIComponent(subfolder)}`;
|
||||
}
|
||||
|
||||
const jsonBlob = await fetch(fileUrl).then(res => res.blob());
|
||||
|
||||
// Extract metadata from JSON file
|
||||
const metadata = await getJSONMetadata(jsonBlob);
|
||||
@@ -1433,6 +1749,42 @@ async function loadJSONFile(node, filename) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Load a video frame from the server-side PyAV endpoint (for H265/yuv444 videos).
|
||||
*/
|
||||
function loadVideoFrameFromServer(node, filename, framePosition, viewType) {
|
||||
const frameUrl = `/prompt-extractor/video-frame?filename=${encodeURIComponent(filename)}&source=${viewType}&position=${framePosition}`;
|
||||
const img = new Image();
|
||||
img.onload = () => {
|
||||
node.imgs = [img];
|
||||
node.imageIndex = 0;
|
||||
node._loadedImageFilename = filename;
|
||||
node._loadedFramePosition = framePosition;
|
||||
|
||||
// Cache as base64 for Python backend
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = img.naturalWidth;
|
||||
canvas.height = img.naturalHeight;
|
||||
const ctx = canvas.getContext('2d');
|
||||
ctx.drawImage(img, 0, 0);
|
||||
const frameData = canvas.toDataURL('image/png');
|
||||
cacheVideoFrame(filename, frameData, framePosition);
|
||||
|
||||
// Resize node to fit image
|
||||
const targetWidth = Math.max(node.size[0], 256);
|
||||
const targetHeight = Math.max(node.size[1], img.naturalHeight * (targetWidth / img.naturalWidth) + 100);
|
||||
node.setSize([targetWidth, targetHeight]);
|
||||
|
||||
node.setDirtyCanvas(true, true);
|
||||
app.graph.setDirtyCanvas(true, true);
|
||||
};
|
||||
img.onerror = () => {
|
||||
console.error(`[PromptExtractor] Server-side frame extraction failed for: ${filename}`);
|
||||
showPlaceholder(node);
|
||||
};
|
||||
img.src = frameUrl;
|
||||
}
|
||||
|
||||
/**
|
||||
* Load frame from a video file at specified position and extract metadata
|
||||
*/
|
||||
@@ -1441,6 +1793,7 @@ async function loadVideoFrame(node, filename) {
|
||||
// Get frame position from the widget (0.0 to 1.0)
|
||||
const framePositionWidget = node.widgets?.find(w => w.name === "frame_position");
|
||||
const framePosition = framePositionWidget ? framePositionWidget.value : 0.0;
|
||||
const viewType = node._sourceFolder || 'input';
|
||||
|
||||
// Split path into filename and subfolder for ComfyUI's /view endpoint
|
||||
let actualFilename = filename;
|
||||
@@ -1453,31 +1806,67 @@ async function loadVideoFrame(node, filename) {
|
||||
}
|
||||
|
||||
// Build URL with subfolder parameter if present
|
||||
let videoUrl = `/view?filename=${encodeURIComponent(actualFilename)}&type=input`;
|
||||
let videoUrl = `/view?filename=${encodeURIComponent(actualFilename)}&type=${viewType}`;
|
||||
if (subfolder) {
|
||||
videoUrl += `&subfolder=${encodeURIComponent(subfolder)}`;
|
||||
}
|
||||
|
||||
// Fetch the video file to extract metadata
|
||||
const videoBlob = await fetch(videoUrl)
|
||||
.then(res => res.blob());
|
||||
// If this video is already known to be non-browser-decodable, go straight to server
|
||||
if (_nonBrowserDecodableVideos.has(filename)) {
|
||||
// Still fetch metadata on first load (not on scrub)
|
||||
if (!node._metadataCached) {
|
||||
try {
|
||||
const videoBlob = await fetch(videoUrl).then(res => res.blob());
|
||||
const metadata = await getVideoMetadata(videoBlob);
|
||||
await cacheFileMetadata(filename, metadata);
|
||||
node.hasWorkflow = !!(metadata && (metadata.workflow || metadata.parameters));
|
||||
node._metadataCached = true;
|
||||
node.setDirtyCanvas(true, true);
|
||||
} catch (e) {
|
||||
console.warn("[PromptExtractor] Metadata extraction failed:", e);
|
||||
}
|
||||
}
|
||||
loadVideoFrameFromServer(node, filename, framePosition, viewType);
|
||||
return;
|
||||
}
|
||||
|
||||
// Extract metadata from video file
|
||||
const metadata = await getVideoMetadata(videoBlob);
|
||||
// Cache metadata (or lack thereof) for Python backend
|
||||
await cacheFileMetadata(filename, metadata);
|
||||
// Fetch metadata only once per video (not on every scrub)
|
||||
if (!node._metadataCached) {
|
||||
try {
|
||||
const videoBlob = await fetch(videoUrl).then(res => res.blob());
|
||||
|
||||
// Update workflow status flag - check for workflow or parameters
|
||||
node.hasWorkflow = !!(metadata && (metadata.workflow || metadata.parameters));
|
||||
|
||||
// Force canvas redraw to update indicator immediately
|
||||
node.setDirtyCanvas(true, true);
|
||||
app.graph.setDirtyCanvas(true, true);
|
||||
// Extract metadata from video file
|
||||
const metadata = await getVideoMetadata(videoBlob);
|
||||
// Cache metadata (or lack thereof) for Python backend
|
||||
await cacheFileMetadata(filename, metadata);
|
||||
node._metadataCached = true;
|
||||
|
||||
// Update workflow status flag - check for workflow or parameters
|
||||
node.hasWorkflow = !!(metadata && (metadata.workflow || metadata.parameters));
|
||||
|
||||
// Force canvas redraw to update indicator immediately
|
||||
node.setDirtyCanvas(true, true);
|
||||
app.graph.setDirtyCanvas(true, true);
|
||||
} catch (e) {
|
||||
console.warn("[PromptExtractor] Metadata extraction failed:", e);
|
||||
}
|
||||
}
|
||||
|
||||
// Create a video element for frame extraction
|
||||
const video = document.createElement('video');
|
||||
video.crossOrigin = 'anonymous';
|
||||
video.preload = 'metadata';
|
||||
video.preload = 'auto';
|
||||
video.muted = true;
|
||||
video.playsInline = true;
|
||||
video.style.cssText = 'position:fixed;top:-9999px;left:-9999px;width:1px;height:1px;opacity:0;pointer-events:none;';
|
||||
|
||||
const cleanupVideo = () => {
|
||||
video.onloadedmetadata = null;
|
||||
video.onseeked = null;
|
||||
video.onerror = null;
|
||||
try { video.src = ''; video.load(); } catch (e) { /* ignore */ }
|
||||
if (video.parentNode) video.parentNode.removeChild(video);
|
||||
};
|
||||
|
||||
video.onloadedmetadata = () => {
|
||||
// Calculate frame time based on position (0.0 = start, 1.0 = end)
|
||||
@@ -1516,10 +1905,12 @@ async function loadVideoFrame(node, filename) {
|
||||
|
||||
node.setDirtyCanvas(true, true);
|
||||
app.graph.setDirtyCanvas(true, true);
|
||||
cleanupVideo();
|
||||
};
|
||||
|
||||
img.onerror = () => {
|
||||
console.error(`[PromptExtractor] Failed to create image from video frame at position ${framePosition.toFixed(2)}`);
|
||||
cleanupVideo();
|
||||
showPlaceholder(node);
|
||||
};
|
||||
|
||||
@@ -1527,11 +1918,15 @@ async function loadVideoFrame(node, filename) {
|
||||
};
|
||||
|
||||
video.onerror = () => {
|
||||
console.error(`[PromptExtractor] Failed to load video: ${filename}`);
|
||||
showPlaceholder(node);
|
||||
console.log(`[PromptExtractor] Browser cannot decode video, using server-side extraction: ${filename}`);
|
||||
// Remember this video can't be decoded by browser - skip browser attempt on future scrubs
|
||||
_nonBrowserDecodableVideos.add(filename);
|
||||
cleanupVideo();
|
||||
loadVideoFrameFromServer(node, filename, framePosition, viewType);
|
||||
};
|
||||
|
||||
// Load video from input directory (using same URL with subfolder support)
|
||||
// Append to DOM (some browsers require this for decoding) and load
|
||||
document.body.appendChild(video);
|
||||
video.src = videoUrl + `&${Date.now()}`;
|
||||
} catch (error) {
|
||||
console.error("[PromptExtractor] Error loading video:", error);
|
||||
@@ -1546,6 +1941,7 @@ function showPlaceholder(node) {
|
||||
// Clear the loaded filename and frame position since we're showing a placeholder
|
||||
node._loadedImageFilename = null;
|
||||
node._loadedFramePosition = null;
|
||||
node._metadataCached = false;
|
||||
|
||||
const placeholderImg = new Image();
|
||||
placeholderImg.src = PLACEHOLDER_IMAGE_PATH;
|
||||
|
||||
@@ -132,6 +132,22 @@ app.registerExtension({
|
||||
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"],
|
||||
|
||||
+3295
-380
File diff suppressed because it is too large
Load Diff
@@ -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,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)",
|
||||
};
|
||||
@@ -1,197 +0,0 @@
|
||||
/**
|
||||
* Video Metadata Reader - VHS Compatible
|
||||
* Enables drag-and-drop workflow loading from videos saved by VideoHelperSuite
|
||||
* without needing VHS installed.
|
||||
*
|
||||
* Based on VideoHelperSuite's videoinfo.js implementation.
|
||||
*/
|
||||
|
||||
import { app } from '../../../scripts/app.js'
|
||||
|
||||
/**
|
||||
* Parse video file bytes to extract embedded workflow/prompt metadata.
|
||||
* Supports webm/mkv (EBML/Matroska) and mp4 (QuickTime) formats.
|
||||
*/
|
||||
function getVideoMetadata(file) {
|
||||
return new Promise((resolve) => {
|
||||
const reader = new FileReader();
|
||||
reader.onload = (event) => {
|
||||
const videoData = new Uint8Array(event.target.result);
|
||||
const dataView = new DataView(videoData.buffer);
|
||||
const decoder = new TextDecoder();
|
||||
|
||||
// Check for known valid magic bytes
|
||||
if (dataView.getUint32(0) === 0x1A45DFA3) {
|
||||
// webm/mkv - EBML/Matroska format
|
||||
// Metadata stored in COMMENT tags
|
||||
// See: http://wiki.webmproject.org/webm-metadata/global-metadata
|
||||
// See: https://www.matroska.org/technical/elements.html
|
||||
let offset = 4 + 8; // Skip header, COMMENT is 7 chars + 1 to realign
|
||||
|
||||
while (offset < videoData.length - 16) {
|
||||
// Check for text tags (0x4487 = TagString element)
|
||||
if (dataView.getUint16(offset) === 0x4487) {
|
||||
// Check that name of tag is COMMENT
|
||||
const name = String.fromCharCode(...videoData.slice(offset - 7, offset));
|
||||
if (name === "COMMENT") {
|
||||
// Parse EBML variable-length integer
|
||||
// See: https://github.com/ietf-wg-cellar/ebml-specification/blob/master/specification.markdown
|
||||
let vint = dataView.getUint32(offset + 2);
|
||||
let n_octets = Math.clz32(vint) + 1;
|
||||
if (n_octets < 4) { // 250MB sanity cutoff
|
||||
let length = (vint >> (8 * (4 - n_octets))) & ~(1 << (7 * n_octets));
|
||||
const content = decoder.decode(videoData.slice(offset + 2 + n_octets, offset + 2 + n_octets + length));
|
||||
try {
|
||||
const json = JSON.parse(content);
|
||||
resolve(json);
|
||||
return;
|
||||
} catch (e) {
|
||||
console.warn("[VideoMetadata] Failed to parse COMMENT JSON:", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
offset += 1;
|
||||
}
|
||||
} else if (dataView.getUint32(4) === 0x66747970) {
|
||||
// mp4 - QuickTime/ISO format
|
||||
// See: https://developer.apple.com/documentation/quicktime-file-format
|
||||
// Metadata can be in various locations, search from end
|
||||
|
||||
// First try: Look for ©cmt (comment) atom - VHS style
|
||||
let offset = videoData.length - 4;
|
||||
while (offset > 16) {
|
||||
if (dataView.getUint32(offset) === 0x64617461) { // 'data' tag
|
||||
if (dataView.getUint32(offset - 8) === 0xa9636d74) { // '©cmt' (comment) tag
|
||||
let size = dataView.getUint32(offset - 4) - 4 * 4;
|
||||
const content = decoder.decode(videoData.slice(offset + 12, offset + 12 + size));
|
||||
try {
|
||||
const json = JSON.parse(content);
|
||||
resolve(json);
|
||||
return;
|
||||
} catch (e) {
|
||||
console.warn("[VideoMetadata] Failed to parse ©cmt JSON:", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
offset -= 1;
|
||||
}
|
||||
|
||||
// Second try: Look for 'prompt' or 'workflow' tags in metadata
|
||||
// These are stored by our SaveVideoH26x node using movflags=use_metadata_tags
|
||||
offset = 0;
|
||||
while (offset < videoData.length - 100) {
|
||||
// Look for 'prompt' or 'workflow' strings followed by JSON
|
||||
const slice = decoder.decode(videoData.slice(offset, offset + 20));
|
||||
if (slice.includes('prompt') || slice.includes('workflow')) {
|
||||
// Try to find JSON starting after the key
|
||||
for (let i = 0; i < 50 && offset + i < videoData.length - 1; i++) {
|
||||
if (videoData[offset + i] === 0x7B) { // '{'
|
||||
// Found potential JSON start, try to parse
|
||||
let jsonEnd = offset + i;
|
||||
let braceCount = 0;
|
||||
for (let j = jsonEnd; j < Math.min(jsonEnd + 1000000, videoData.length); j++) {
|
||||
if (videoData[j] === 0x7B) braceCount++;
|
||||
if (videoData[j] === 0x7D) braceCount--;
|
||||
if (braceCount === 0) {
|
||||
jsonEnd = j + 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
const jsonStr = decoder.decode(videoData.slice(offset + i, jsonEnd));
|
||||
try {
|
||||
const json = JSON.parse(jsonStr);
|
||||
if (json.workflow || json.prompt || json.nodes) {
|
||||
resolve(json.workflow ? json : { workflow: json });
|
||||
return;
|
||||
}
|
||||
} catch (e) {
|
||||
// Not valid JSON, continue searching
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
offset += 100; // Skip ahead in larger chunks
|
||||
}
|
||||
}
|
||||
|
||||
// No metadata found
|
||||
resolve(undefined);
|
||||
};
|
||||
|
||||
reader.onerror = () => {
|
||||
console.error("[VideoMetadata] Failed to read file");
|
||||
resolve(undefined);
|
||||
};
|
||||
|
||||
reader.readAsArrayBuffer(file);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if file is a video by extension
|
||||
*/
|
||||
function isVideoFile(file) {
|
||||
const videoExtensions = ['.webm', '.mp4', '.mkv', '.mov', '.avi'];
|
||||
const name = file?.name?.toLowerCase() || '';
|
||||
return videoExtensions.some(ext => name.endsWith(ext));
|
||||
}
|
||||
|
||||
// Store original handler
|
||||
let originalHandleFile = null;
|
||||
|
||||
/**
|
||||
* Custom file handler that intercepts video files to extract workflow metadata
|
||||
*/
|
||||
async function handleFile(file) {
|
||||
// Check if this is a video file
|
||||
if (file?.type?.startsWith("video/") || isVideoFile(file)) {
|
||||
console.log("[VideoMetadata] Processing video file:", file.name);
|
||||
|
||||
try {
|
||||
const videoInfo = await getVideoMetadata(file);
|
||||
|
||||
if (videoInfo?.workflow) {
|
||||
console.log("[VideoMetadata] Found workflow in video, loading...");
|
||||
await app.loadGraphData(videoInfo.workflow);
|
||||
return;
|
||||
} else {
|
||||
console.log("[VideoMetadata] No workflow metadata found in video");
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("[VideoMetadata] Error extracting metadata:", e);
|
||||
}
|
||||
}
|
||||
|
||||
// Fall through to original handler
|
||||
if (originalHandleFile) {
|
||||
return await originalHandleFile.apply(this, arguments);
|
||||
}
|
||||
}
|
||||
|
||||
// Register extension
|
||||
app.registerExtension({
|
||||
name: "PromptManager.VideoMetadata",
|
||||
|
||||
async setup() {
|
||||
// Only hijack if not already done by VHS
|
||||
if (!window._vhsVideoMetadataRegistered) {
|
||||
// Store and replace the file handler
|
||||
originalHandleFile = app.handleFile;
|
||||
app.handleFile = handleFile;
|
||||
|
||||
// Add video formats to file input accept attribute
|
||||
const fileInput = document.getElementById("comfy-file-input");
|
||||
if (fileInput && !fileInput.accept.includes("video/")) {
|
||||
fileInput.accept += ",video/webm,video/mp4,video/x-matroska";
|
||||
}
|
||||
|
||||
// Mark as registered to avoid double-registration if VHS loads later
|
||||
window._vhsVideoMetadataRegistered = true;
|
||||
|
||||
console.log("[VideoMetadata] VHS-compatible video metadata reader registered");
|
||||
} else {
|
||||
console.log("[VideoMetadata] Video metadata handler already registered (likely by VHS)");
|
||||
}
|
||||
}
|
||||
});
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,455 @@
|
||||
/**
|
||||
* WorkflowModelLoader 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 === "workflow_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._applyWorkflowModelLoaderInfo(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.WorkflowModelLoader",
|
||||
|
||||
async beforeRegisterNodeDef(nodeType, nodeData) {
|
||||
if (nodeData.name !== "WorkflowModelLoader") return;
|
||||
|
||||
const origOnExecuted = nodeType.prototype.onExecuted;
|
||||
nodeType.prototype.onExecuted = function (message) {
|
||||
origOnExecuted?.apply(this, arguments);
|
||||
const info = message?.workflow_model_loader_info?.[0];
|
||||
if (!info) return;
|
||||
this._applyWorkflowModelLoaderInfo(info);
|
||||
};
|
||||
|
||||
nodeType.prototype._applyWorkflowModelLoaderInfo = function (info) {
|
||||
const selected = _sanitizeChoice(info.model, MODEL_CHOICES, "model_a");
|
||||
this._workflowModelLoaderInfo = {
|
||||
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._ensureWorkflowModelInfoWidget();
|
||||
this.setDirtyCanvas(true, true);
|
||||
};
|
||||
|
||||
const origOnNodeCreated = nodeType.prototype.onNodeCreated;
|
||||
nodeType.prototype.onNodeCreated = function () {
|
||||
const r = origOnNodeCreated?.apply(this, arguments);
|
||||
_restoreOrNormalizeWidgetState(this);
|
||||
if (!this._workflowModelLoaderInfo) {
|
||||
this._workflowModelLoaderInfo = _defaultInfoFromWidgets(this);
|
||||
}
|
||||
this._ensureWorkflowModelInfoWidget();
|
||||
_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._workflowModelLoaderInfo) {
|
||||
o._workflowModelLoaderInfo = this._workflowModelLoaderInfo;
|
||||
}
|
||||
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?._workflowModelLoaderInfo;
|
||||
if (state) {
|
||||
requestAnimationFrame(() => {
|
||||
this._applyWorkflowModelLoaderInfo(state);
|
||||
_refreshInfoFromUpstream(this);
|
||||
});
|
||||
} else {
|
||||
requestAnimationFrame(() => {
|
||||
this._workflowModelLoaderInfo = _defaultInfoFromWidgets(this);
|
||||
this._ensureWorkflowModelInfoWidget();
|
||||
_refreshInfoFromUpstream(this);
|
||||
this.setDirtyCanvas(true, true);
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
nodeType.prototype._ensureWorkflowModelInfoWidget = function () {
|
||||
let widget = this.widgets?.find(w => w.name === "_workflow_model_loader_info");
|
||||
if (!widget) {
|
||||
widget = {
|
||||
name: "_workflow_model_loader_info",
|
||||
type: "custom",
|
||||
y: 0,
|
||||
computeSize: () => {
|
||||
const rows = _buildRows(this._workflowModelLoaderInfo || {});
|
||||
const h = Math.max(26, (rows.length * 22) + 6);
|
||||
return [0, h];
|
||||
},
|
||||
draw: function (ctx, node, widgetWidth, y) {
|
||||
const info = node._workflowModelLoaderInfo;
|
||||
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,15 @@
|
||||
/**
|
||||
* Workflow Renderer — Set initial node size to match Workflow Builder width.
|
||||
*/
|
||||
import { app } from "../../scripts/app.js";
|
||||
|
||||
app.registerExtension({
|
||||
name: "prompt-manager.workflow-renderer",
|
||||
async nodeCreated(node) {
|
||||
if (node.comfyClass !== "WorkflowRenderer") return;
|
||||
requestAnimationFrame(() => {
|
||||
node.setSize([320, node.size[1]]);
|
||||
app.graph.setDirtyCanvas(true, true);
|
||||
});
|
||||
},
|
||||
});
|
||||
@@ -1,352 +0,0 @@
|
||||
"""
|
||||
Latent Preview for Video Sampling - Provides animated previews during KSampler execution for video models.
|
||||
Based on VideoHelperSuite implementation, with compatibility checks to avoid conflicts.
|
||||
"""
|
||||
|
||||
from PIL import Image
|
||||
import time
|
||||
import io
|
||||
import struct
|
||||
from threading import Thread
|
||||
import functools
|
||||
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
|
||||
# Rates table for different video models (frames per second / temporal compression)
|
||||
RATES_TABLE = {
|
||||
'Mochi': 24 // 6,
|
||||
'LTXV': 24 // 8,
|
||||
'HunyuanVideo': 24 // 4,
|
||||
'Cosmos1CV8x8x8': 24 // 8,
|
||||
'Wan21': 16 // 4,
|
||||
'Wan22': 24 // 4
|
||||
}
|
||||
|
||||
# Global flag to track if we've hooked the previewer
|
||||
_hook_installed = False
|
||||
_original_get_previewer = None
|
||||
|
||||
|
||||
def hook(obj, attr):
|
||||
"""Decorator to hook/wrap an existing function on an object."""
|
||||
def dec(f):
|
||||
f = functools.update_wrapper(f, getattr(obj, attr))
|
||||
setattr(obj, attr, f)
|
||||
return f
|
||||
return dec
|
||||
|
||||
|
||||
# Import latent_preview at module level for proper inheritance
|
||||
import latent_preview as _latent_preview_module
|
||||
|
||||
|
||||
class WrappedPreviewer(_latent_preview_module.LatentPreviewer):
|
||||
"""
|
||||
Wraps the standard latent previewer to provide animated video previews.
|
||||
This class intercepts preview requests and sends frames as an animation
|
||||
instead of static images.
|
||||
"""
|
||||
|
||||
def __init__(self, previewer, rate=8, server_instance=None, model_name=None):
|
||||
# Don't call super().__init__() as we're wrapping an existing previewer
|
||||
self.first_preview = True
|
||||
self.last_time = 0
|
||||
self.c_index = 0
|
||||
self.rate = rate
|
||||
self.server = server_instance
|
||||
self.is_video_taesd = False
|
||||
self.model_name = model_name
|
||||
|
||||
# Copy decoder attributes from the original previewer
|
||||
# Check what type of previewer we have
|
||||
if hasattr(previewer, 'taesd'):
|
||||
self.taesd = previewer.taesd
|
||||
# Detect if this is a video TAESD (VAE-based) vs regular TAESD
|
||||
# Video TAESDs use a full VAE with first_stage_model
|
||||
if hasattr(self.taesd, 'first_stage_model'):
|
||||
self.is_video_taesd = True
|
||||
elif hasattr(previewer, 'latent_rgb_factors'):
|
||||
self.latent_rgb_factors = previewer.latent_rgb_factors
|
||||
self.latent_rgb_factors_bias = previewer.latent_rgb_factors_bias
|
||||
self.latent_rgb_factors_reshape = getattr(previewer, 'latent_rgb_factors_reshape', None)
|
||||
else:
|
||||
raise Exception('Unsupported preview type for animated latent previews')
|
||||
|
||||
def decode_latent_to_preview_image(self, preview_format, x0):
|
||||
"""
|
||||
Main preview method - intercepts the standard preview call and
|
||||
converts it to animated frame previews for video latents.
|
||||
"""
|
||||
import server
|
||||
|
||||
if x0.ndim == 5:
|
||||
# Keep batch major for video tensors
|
||||
x0 = x0.movedim(2, 1)
|
||||
x0 = x0.reshape((-1,) + x0.shape[-3:])
|
||||
|
||||
num_images = x0.size(0)
|
||||
new_time = time.time()
|
||||
num_previews = int((new_time - self.last_time) * self.rate)
|
||||
self.last_time = self.last_time + num_previews / self.rate
|
||||
|
||||
if num_previews > num_images:
|
||||
num_previews = num_images
|
||||
elif num_previews <= 0:
|
||||
return None
|
||||
|
||||
if self.first_preview:
|
||||
self.first_preview = False
|
||||
# Send initialization message to frontend
|
||||
self.server.send_sync('PM_latentpreview', {
|
||||
'length': num_images,
|
||||
'rate': self.rate,
|
||||
'id': self.server.last_node_id
|
||||
})
|
||||
self.last_time = new_time + 1 / self.rate
|
||||
|
||||
if self.c_index + num_previews > num_images:
|
||||
x0 = x0.roll(-self.c_index, 0)[:num_previews]
|
||||
else:
|
||||
x0 = x0[self.c_index:self.c_index + num_previews]
|
||||
|
||||
# Process previews in a thread
|
||||
if hasattr(self, 'latent_rgb_factors'):
|
||||
Thread(target=self._process_latent2rgb_batch, args=(x0, self.c_index, num_images)).run()
|
||||
else:
|
||||
Thread(target=self._process_taesd_batch, args=(x0, self.c_index, num_images)).run()
|
||||
self.c_index = (self.c_index + num_previews) % num_images
|
||||
return None
|
||||
|
||||
def _process_taesd_batch(self, latent_frames, ind, leng):
|
||||
"""Process and send preview frames to the frontend.
|
||||
|
||||
Args:
|
||||
latent_frames: Latent tensor, shape (N, C, H, W) where N is number of frames
|
||||
ind: Current frame index
|
||||
leng: Total number of frames
|
||||
"""
|
||||
import server
|
||||
|
||||
# For TAESD, decode each frame (don't change this - it works)
|
||||
for i in range(latent_frames.size(0)):
|
||||
frame_latent = latent_frames[i:i + 1] # Keep batch dim: (1, C, H, W)
|
||||
|
||||
# Decode single frame to PIL Image (same as ComfyUI does)
|
||||
preview_image = self.decode_single_frame(frame_latent)
|
||||
|
||||
if preview_image is None:
|
||||
continue
|
||||
|
||||
# Resize if needed
|
||||
if preview_image.width > 512 or preview_image.height > 512:
|
||||
if preview_image.width > preview_image.height:
|
||||
new_width = 512
|
||||
new_height = int(512 * preview_image.height / preview_image.width)
|
||||
else:
|
||||
new_height = 512
|
||||
new_width = int(512 * preview_image.width / preview_image.height)
|
||||
preview_image = preview_image.resize((new_width, new_height), Image.LANCZOS)
|
||||
|
||||
# Send to frontend
|
||||
message = io.BytesIO()
|
||||
message.write((1).to_bytes(length=4, byteorder='big') * 2)
|
||||
message.write(ind.to_bytes(length=4, byteorder='big'))
|
||||
message.write(struct.pack('16p', self.server.last_node_id.encode('ascii')))
|
||||
preview_image.save(message, format="JPEG", quality=95)
|
||||
|
||||
self.server.send_sync(
|
||||
server.BinaryEventTypes.PREVIEW_IMAGE,
|
||||
message.getvalue(),
|
||||
self.server.client_id
|
||||
)
|
||||
ind = (ind + 1) % leng
|
||||
|
||||
def _process_latent2rgb_batch(self, x0, ind, leng):
|
||||
"""Process Latent2RGB previews using batch decode (VHS style)."""
|
||||
import server
|
||||
|
||||
# Apply reshape if needed
|
||||
if self.latent_rgb_factors_reshape is not None:
|
||||
x0 = self.latent_rgb_factors_reshape(x0)
|
||||
|
||||
self.latent_rgb_factors = self.latent_rgb_factors.to(dtype=x0.dtype, device=x0.device)
|
||||
if self.latent_rgb_factors_bias is not None:
|
||||
self.latent_rgb_factors_bias = self.latent_rgb_factors_bias.to(dtype=x0.dtype, device=x0.device)
|
||||
|
||||
# Batch decode: x0 is (N, C, H, W), output is (N, H, W, 3)
|
||||
image_tensor = F.linear(x0.movedim(1, -1), self.latent_rgb_factors,
|
||||
bias=self.latent_rgb_factors_bias)
|
||||
|
||||
# Resize if needed
|
||||
if image_tensor.size(1) > 512 or image_tensor.size(2) > 512:
|
||||
image_tensor = image_tensor.movedim(-1, 0)
|
||||
if image_tensor.size(2) < image_tensor.size(3):
|
||||
height = (512 * image_tensor.size(2)) // image_tensor.size(3)
|
||||
image_tensor = F.interpolate(image_tensor, (height, 512), mode='bilinear')
|
||||
else:
|
||||
width = (512 * image_tensor.size(3)) // image_tensor.size(2)
|
||||
image_tensor = F.interpolate(image_tensor, (512, width), mode='bilinear')
|
||||
image_tensor = image_tensor.movedim(0, -1)
|
||||
|
||||
# Convert to uint8 (scale from -1..1 to 0..255)
|
||||
previews_ubyte = (((image_tensor + 1.0) / 2.0).clamp(0, 1).mul(0xFF)).to(device="cpu", dtype=torch.uint8)
|
||||
|
||||
# Send each frame
|
||||
for preview in previews_ubyte:
|
||||
i = Image.fromarray(preview.numpy())
|
||||
message = io.BytesIO()
|
||||
message.write((1).to_bytes(length=4, byteorder='big') * 2)
|
||||
message.write(ind.to_bytes(length=4, byteorder='big'))
|
||||
message.write(struct.pack('16p', self.server.last_node_id.encode('ascii')))
|
||||
i.save(message, format="JPEG", quality=95)
|
||||
self.server.send_sync(
|
||||
server.BinaryEventTypes.PREVIEW_IMAGE,
|
||||
message.getvalue(),
|
||||
self.server.client_id
|
||||
)
|
||||
ind = (ind + 1) % leng
|
||||
|
||||
def decode_single_frame(self, x0):
|
||||
"""Decode a single TAESD latent frame to PIL Image.
|
||||
Only used by _process_taesd_batch().
|
||||
|
||||
Args:
|
||||
x0: Latent tensor, shape (1, C, H, W) for images or (1, C, T, H, W) for video
|
||||
|
||||
Returns:
|
||||
PIL.Image
|
||||
"""
|
||||
if self.is_video_taesd:
|
||||
# TAEHVPreviewerImpl style: x0[:1, :, :1] then [0][0]
|
||||
if x0.ndim == 4:
|
||||
x0 = x0.unsqueeze(2) # (1, C, H, W) -> (1, C, 1, H, W)
|
||||
|
||||
x_sample = self.taesd.decode(x0[:1, :, :1])[0][0]
|
||||
|
||||
# # Apply contrast boost for Wan models (TAESD looks washed out)
|
||||
# if self.model_name and self.model_name.startswith('Wan'):
|
||||
# x_sample = self._apply_contrast(x_sample, contrast=1.2, brightness=1.0)
|
||||
|
||||
# Video TAEs output 0-1 range, not -1 to 1
|
||||
return self._tensor_to_image(x_sample, do_scale=False)
|
||||
else:
|
||||
# TAESDPreviewerImpl style: decode(x0[:1])[0].movedim(0, 2)
|
||||
x_sample = self.taesd.decode(x0[:1])[0].movedim(0, 2)
|
||||
return self._tensor_to_image(x_sample, do_scale=True)
|
||||
|
||||
def _apply_contrast(self, tensor, contrast=1.0, brightness=1.0):
|
||||
"""Apply contrast and brightness adjustment to a tensor in 0-1 range."""
|
||||
# Contrast: (x - 0.5) * contrast + 0.5
|
||||
# Brightness: x * brightness
|
||||
tensor = (tensor - 0.5) * contrast + 0.5
|
||||
tensor = tensor * brightness
|
||||
return tensor.clamp(0, 1)
|
||||
|
||||
def _tensor_to_image(self, tensor, do_scale=True):
|
||||
"""Convert tensor to PIL Image, matching ComfyUI's preview_to_image."""
|
||||
import comfy.model_management
|
||||
|
||||
if do_scale:
|
||||
latents_ubyte = (((tensor + 1.0) / 2.0).clamp(0, 1).mul(0xFF))
|
||||
else:
|
||||
latents_ubyte = (tensor.clamp(0, 1).mul(0xFF))
|
||||
|
||||
if comfy.model_management.directml_enabled:
|
||||
latents_ubyte = latents_ubyte.to(dtype=torch.uint8)
|
||||
|
||||
latents_ubyte = latents_ubyte.to(
|
||||
device="cpu",
|
||||
dtype=torch.uint8,
|
||||
non_blocking=comfy.model_management.device_supports_non_blocking(tensor.device)
|
||||
)
|
||||
|
||||
return Image.fromarray(latents_ubyte.numpy())
|
||||
|
||||
|
||||
def is_vhs_installed():
|
||||
"""Check if VideoHelperSuite is installed and has latent preview enabled."""
|
||||
try:
|
||||
# Check if VHS module is loaded
|
||||
import sys
|
||||
for module_name in sys.modules:
|
||||
if 'videohelpersuite' in module_name.lower():
|
||||
# VHS is installed, check if it has hooked the previewer
|
||||
func = getattr(_latent_preview_module, 'get_previewer', None)
|
||||
if func and hasattr(func, '__wrapped__'):
|
||||
# VHS has already hooked the previewer
|
||||
return True
|
||||
return False
|
||||
except:
|
||||
return False
|
||||
|
||||
|
||||
def install_latent_preview_hook():
|
||||
"""
|
||||
Install the latent preview hook if:
|
||||
1. It's not already installed by us
|
||||
2. VideoHelperSuite hasn't already installed it
|
||||
"""
|
||||
global _hook_installed, _original_get_previewer
|
||||
|
||||
if _hook_installed:
|
||||
print("[PromptManager] Latent preview hook already installed")
|
||||
return True
|
||||
|
||||
if is_vhs_installed():
|
||||
print("[PromptManager] VideoHelperSuite detected with latent preview - skipping to avoid conflict")
|
||||
return False
|
||||
|
||||
try:
|
||||
import server
|
||||
serv = server.PromptServer.instance
|
||||
|
||||
# Store original function
|
||||
_original_get_previewer = _latent_preview_module.get_previewer
|
||||
|
||||
@hook(_latent_preview_module, 'get_previewer')
|
||||
def get_latent_video_previewer(device, latent_format, *args, **kwargs):
|
||||
"""Wrapped previewer that checks settings and returns animated previewer if enabled."""
|
||||
previewer = get_latent_video_previewer.__wrapped__(device, latent_format, *args, **kwargs)
|
||||
|
||||
try:
|
||||
extra_info = next(serv.prompt_queue.currently_running.values().__iter__())[3]['extra_pnginfo']['workflow']['extra']
|
||||
prev_setting = extra_info.get('PM_latentpreview', False)
|
||||
|
||||
if extra_info.get('PM_latentpreviewrate', 0) != 0:
|
||||
rate_setting = extra_info['PM_latentpreviewrate']
|
||||
else:
|
||||
rate_setting = RATES_TABLE.get(latent_format.__class__.__name__, 8)
|
||||
except:
|
||||
# For safety since there's lots of keys, any of which can fail
|
||||
prev_setting = False
|
||||
|
||||
if not prev_setting or not hasattr(previewer, "decode_latent_to_preview"):
|
||||
return previewer
|
||||
|
||||
model_name = latent_format.__class__.__name__
|
||||
return WrappedPreviewer(previewer, rate_setting, serv, model_name)
|
||||
|
||||
_hook_installed = True
|
||||
print("[PromptManager] Latent preview hook installed successfully")
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
print(f"[PromptManager] Failed to install latent preview hook: {e}")
|
||||
return False
|
||||
|
||||
|
||||
def uninstall_latent_preview_hook():
|
||||
"""Restore the original get_previewer function."""
|
||||
global _hook_installed, _original_get_previewer
|
||||
|
||||
if not _hook_installed or _original_get_previewer is None:
|
||||
return
|
||||
|
||||
try:
|
||||
_latent_preview_module.get_previewer = _original_get_previewer
|
||||
_hook_installed = False
|
||||
_original_get_previewer = None
|
||||
print("[PromptManager] Latent preview hook uninstalled")
|
||||
except Exception as e:
|
||||
print(f"[PromptManager] Failed to uninstall latent preview hook: {e}")
|
||||
@@ -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)
|
||||
File diff suppressed because it is too large
Load Diff
@@ -13,17 +13,17 @@ import numpy as np
|
||||
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, has_vision_support
|
||||
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 .ollama_wrapper import generate_chat as ollama_generate_chat, unload_model as ollama_unload_model
|
||||
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 = {}
|
||||
|
||||
@@ -177,7 +177,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):
|
||||
@@ -345,6 +345,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"
|
||||
@@ -496,17 +497,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)
|
||||
@@ -674,7 +691,7 @@ 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
|
||||
@@ -686,7 +703,7 @@ class PromptGenerator:
|
||||
model_to_use = options["model"]
|
||||
else:
|
||||
# Auto-discover available models from Ollama
|
||||
from .ollama_wrapper import discover_ollama_models
|
||||
from ..py.ollama_wrapper import discover_ollama_models
|
||||
discovered, status = discover_ollama_models(_preferences_cache)
|
||||
if discovered:
|
||||
model_to_use = discovered[0]
|
||||
@@ -695,7 +712,7 @@ class PromptGenerator:
|
||||
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,)
|
||||
raise RuntimeError(error_msg)
|
||||
|
||||
print_pg("Backend : Ollama")
|
||||
|
||||
@@ -715,14 +732,14 @@ class PromptGenerator:
|
||||
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)
|
||||
return (error_msg,)
|
||||
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)
|
||||
return (error_msg,)
|
||||
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"]):
|
||||
@@ -731,12 +748,12 @@ class PromptGenerator:
|
||||
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)
|
||||
return (error_msg,)
|
||||
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)
|
||||
return (error_msg,)
|
||||
raise RuntimeError(error_msg)
|
||||
|
||||
# Thinking mode is only meaningful if the model explicitly supports it
|
||||
# (no longer tied to Qwen3VL naming — generic check)
|
||||
@@ -762,8 +779,8 @@ 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 (llama.cpp only)
|
||||
@@ -774,7 +791,7 @@ class PromptGenerator:
|
||||
# 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,)
|
||||
raise RuntimeError(error_msg)
|
||||
|
||||
# Build the endpoint URL
|
||||
full_url = f"http://localhost:{self.SERVER_PORT}/v1/chat/completions"
|
||||
@@ -933,7 +950,7 @@ class PromptGenerator:
|
||||
stream=True
|
||||
)
|
||||
else:
|
||||
return (error_msg,)
|
||||
raise RuntimeError(error_msg)
|
||||
|
||||
response.raise_for_status()
|
||||
|
||||
@@ -1044,18 +1061,18 @@ 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)
|
||||
|
||||
# ================================================================
|
||||
# Ollama generation helper
|
||||
@@ -1215,15 +1232,15 @@ class PromptGenerator:
|
||||
except requests.exceptions.ConnectionError:
|
||||
error_msg = "Error: Lost connection to Ollama during generation."
|
||||
print_pg(error_msg, RED)
|
||||
return (error_msg,)
|
||||
raise RuntimeError(error_msg)
|
||||
except requests.exceptions.Timeout:
|
||||
error_msg = "Error: Ollama request timed out (>120s)"
|
||||
print_pg(error_msg, RED)
|
||||
return (error_msg,)
|
||||
raise RuntimeError(error_msg)
|
||||
except Exception as e:
|
||||
error_msg = f"Error (Ollama): {e}"
|
||||
print_pg(error_msg, RED)
|
||||
return (error_msg,)
|
||||
raise RuntimeError(error_msg)
|
||||
|
||||
def print_token_stats(self, usage_stats, cached_token_counts, thinking_content, full_response, images):
|
||||
"""Print token statistics using pre-cached counts"""
|
||||
@@ -1,5 +1,5 @@
|
||||
from .model_manager import get_all_models, is_model_local, download_model, get_mmproj_for_model, get_mmproj_path, _preferences_cache
|
||||
from .ollama_wrapper import discover_ollama_models, is_ollama_available
|
||||
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
|
||||
@@ -107,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"
|
||||
@@ -4,10 +4,14 @@ Saves prompts along with associated LoRA configurations
|
||||
"""
|
||||
import os
|
||||
import json
|
||||
import shutil
|
||||
import time
|
||||
import base64
|
||||
from datetime import datetime
|
||||
from io import BytesIO
|
||||
import folder_paths
|
||||
import server
|
||||
from ..py.workflow_data_utils import to_json_safe_workflow_data
|
||||
|
||||
# Import numpy and PIL for image processing (available in ComfyUI environment)
|
||||
try:
|
||||
@@ -19,13 +23,13 @@ except ImportError:
|
||||
print("[PromptManagerAdvanced] Warning: PIL/numpy not available, thumbnail from image input disabled")
|
||||
|
||||
|
||||
def image_to_base64_thumbnail(image_tensor, max_size=128):
|
||||
def image_to_base64_thumbnail(image_tensor, max_size=200):
|
||||
"""
|
||||
Convert a ComfyUI image tensor to a base64 thumbnail string.
|
||||
|
||||
Args:
|
||||
image_tensor: ComfyUI image tensor (B, H, W, C) in float32 0-1 range
|
||||
max_size: Maximum dimension for the thumbnail
|
||||
max_size: Minimum dimension for the thumbnail (default 200px for smallest side)
|
||||
|
||||
Returns:
|
||||
Base64 encoded JPEG string or None if conversion fails
|
||||
@@ -48,18 +52,15 @@ def image_to_base64_thumbnail(image_tensor, max_size=128):
|
||||
# Create PIL Image
|
||||
img = Image.fromarray(img_array)
|
||||
|
||||
# Resize maintaining aspect ratio
|
||||
# Resize maintaining aspect ratio, limiting smallest dimension to max_size
|
||||
width, height = img.size
|
||||
if width > height:
|
||||
if width > max_size:
|
||||
new_height = int((height * max_size) / width)
|
||||
new_width = max_size
|
||||
img = img.resize((new_width, new_height), Image.LANCZOS)
|
||||
else:
|
||||
if height > max_size:
|
||||
new_width = int((width * max_size) / height)
|
||||
new_height = max_size
|
||||
img = img.resize((new_width, new_height), Image.LANCZOS)
|
||||
min_dim = min(width, height)
|
||||
|
||||
if min_dim > max_size:
|
||||
scale = max_size / min_dim
|
||||
new_width = int(width * scale)
|
||||
new_height = int(height * scale)
|
||||
img = img.resize((new_width, new_height), Image.LANCZOS)
|
||||
|
||||
# Convert to JPEG base64
|
||||
buffer = BytesIO()
|
||||
@@ -72,136 +73,14 @@ def image_to_base64_thumbnail(image_tensor, max_size=128):
|
||||
return None
|
||||
|
||||
|
||||
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 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."""
|
||||
lora_extensions = ['.safetensors', '.ckpt', '.pt', '.bin', '.pth']
|
||||
name_lower = name.lower()
|
||||
for ext in lora_extensions:
|
||||
if name_lower.endswith(ext):
|
||||
return name[:-len(ext)]
|
||||
return name
|
||||
|
||||
|
||||
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 found, (None, False) otherwise.
|
||||
"""
|
||||
import re
|
||||
|
||||
# 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 normalize_name(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
|
||||
# Replace [_-]token[_-], [_-]token, token[_-], or standalone token
|
||||
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
|
||||
|
||||
# Normalize the search name - use our extension stripper, not splitext
|
||||
search_parts = normalize_name(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(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, found) 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, found = fuzzy_match_lora(lora_name, lora_files)
|
||||
if found:
|
||||
return fuzzy_match, True
|
||||
|
||||
# Not found
|
||||
return lora_name, False
|
||||
# ── Shared LoRA utilities ─────────────────────────────────────────────────────
|
||||
from ..py.lora_utils import (
|
||||
get_available_loras,
|
||||
normalize_path_separators,
|
||||
strip_lora_extension,
|
||||
fuzzy_match_lora,
|
||||
get_lora_relative_path,
|
||||
)
|
||||
|
||||
|
||||
class PromptManagerAdvanced:
|
||||
@@ -211,6 +90,28 @@ class PromptManagerAdvanced:
|
||||
Features two LoRA stack inputs/outputs for dual LoRA workflows (e.g., Wan video).
|
||||
"""
|
||||
|
||||
@staticmethod
|
||||
def get_weekly_backup_path():
|
||||
"""Get the path to the weekly rotating backup file."""
|
||||
return PromptManagerAdvanced.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 = PromptManagerAdvanced.load_prompts()
|
||||
@@ -245,6 +146,12 @@ class PromptManagerAdvanced:
|
||||
"label_off": "off",
|
||||
"tooltip": "When enabled, use LoRAs from connected inputs. When off, use only prompt LoRAs."
|
||||
}),
|
||||
"use_workflow_data": ("BOOLEAN", {
|
||||
"default": False,
|
||||
"label_on": "on",
|
||||
"label_off": "off",
|
||||
"tooltip": "When enabled, use connected workflow_data prompt/LoRAs at execution."
|
||||
}),
|
||||
"text": ("STRING", {
|
||||
"multiline": True,
|
||||
"default": first_prompt_text,
|
||||
@@ -252,52 +159,65 @@ class PromptManagerAdvanced:
|
||||
"dynamicPrompts": False,
|
||||
"tooltip": "Enter prompt text directly"
|
||||
}),
|
||||
"swap_lora_outputs": ("BOOLEAN", {
|
||||
"default": False,
|
||||
"label_on": "swapped",
|
||||
"label_off": "normal",
|
||||
"tooltip": "Swap the lora_stack_a and lora_stack_b outputs."
|
||||
}),
|
||||
},
|
||||
"optional": {
|
||||
"prompt_input": ("STRING", {"multiline": True, "forceInput": True, "lazy": True, "tooltip": "Connect prompt text input here"}),
|
||||
"prompt": ("STRING", {"multiline": True, "forceInput": True, "lazy": True, "tooltip": "Connect prompt 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"}),
|
||||
"thumbnail_image": ("IMAGE", {"tooltip": "Connect an image to use as thumbnail when saving the prompt"}),
|
||||
"workflow_data": ("WORKFLOW_DATA", {"forceInput": True, "tooltip": "Connect workflow_data from WorkflowBuilder or PromptExtractor"}),
|
||||
},
|
||||
"hidden": {
|
||||
"unique_id": "UNIQUE_ID",
|
||||
"loras_a_toggle": "STRING",
|
||||
"loras_b_toggle": "STRING",
|
||||
"trigger_words_toggle": "STRING",
|
||||
"saved_workflow_data": "STRING",
|
||||
}
|
||||
}
|
||||
|
||||
CATEGORY = "Prompt Manager"
|
||||
RETURN_TYPES = ("STRING", "LORA_STACK", "LORA_STACK")
|
||||
RETURN_NAMES = ("prompt", "lora_stack_a", "lora_stack_b")
|
||||
DESCRIPTION = "Full-featured prompt manager with dual LoRA stack support, trigger words, and thumbnail browser."
|
||||
RETURN_TYPES = ("STRING", "LORA_STACK", "LORA_STACK", "WORKFLOW_DATA")
|
||||
RETURN_NAMES = ("prompt", "lora_stack_a", "lora_stack_b", "workflow_data")
|
||||
FUNCTION = "get_prompt"
|
||||
OUTPUT_NODE = True
|
||||
|
||||
@classmethod
|
||||
def IS_CHANGED(cls, category, name, text, use_prompt_input, use_lora_input, **kwargs):
|
||||
def IS_CHANGED(cls, category, name, use_prompt_input, use_lora_input=True, use_workflow_data=False, text="", swap_lora_outputs=False,
|
||||
**kwargs):
|
||||
"""
|
||||
Track changes to the node's inputs to determine if re-execution is needed.
|
||||
Returns a tuple of relevant values that should trigger re-execution when changed.
|
||||
"""
|
||||
# Get optional inputs
|
||||
prompt_input = kwargs.get('prompt_input', None)
|
||||
prompt_input = kwargs.get('prompt', None)
|
||||
lora_stack_a = kwargs.get('lora_stack_a', None)
|
||||
lora_stack_b = kwargs.get('lora_stack_b', None)
|
||||
trigger_words = kwargs.get('trigger_words', None)
|
||||
|
||||
workflow_data = kwargs.get('workflow_data', None)
|
||||
# Return tuple of all values that should trigger re-execution when changed
|
||||
# Convert lists/objects to strings for hashable comparison
|
||||
return (
|
||||
category,
|
||||
name,
|
||||
text,
|
||||
use_prompt_input,
|
||||
use_lora_input,
|
||||
use_workflow_data,
|
||||
text,
|
||||
swap_lora_outputs,
|
||||
str(prompt_input) if prompt_input else None,
|
||||
str(lora_stack_a) if lora_stack_a else None,
|
||||
str(lora_stack_b) if lora_stack_b else None,
|
||||
trigger_words
|
||||
trigger_words,
|
||||
str(workflow_data) if workflow_data else None,
|
||||
)
|
||||
|
||||
@classmethod
|
||||
@@ -314,7 +234,7 @@ class PromptManagerAdvanced:
|
||||
@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):
|
||||
@@ -328,6 +248,26 @@ class PromptManagerAdvanced:
|
||||
return json.load(f)
|
||||
except Exception as e:
|
||||
print(f"[PromptManagerAdvanced] 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"[PromptManagerAdvanced] Recovered prompts from backup: {backup_path}")
|
||||
return backup_data
|
||||
except Exception as be:
|
||||
print(f"[PromptManagerAdvanced] Backup load failed ({backup_path}): {be}")
|
||||
print("[PromptManagerAdvanced] User prompt file exists but could not be parsed; not overwriting with defaults.")
|
||||
return {}
|
||||
|
||||
if os.path.exists(default_path):
|
||||
try:
|
||||
@@ -364,13 +304,25 @@ class PromptManagerAdvanced:
|
||||
"""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"[PromptManagerAdvanced] Error saving prompts: {e}")
|
||||
try:
|
||||
if os.path.exists(tmp_path):
|
||||
os.remove(tmp_path)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def _merge_lora_stacks(self, preset_stack, connected_stack):
|
||||
"""
|
||||
@@ -469,9 +421,6 @@ class PromptManagerAdvanced:
|
||||
# Check toggle state (case-insensitive lookup)
|
||||
toggle_state = toggle_map.get(lora_name.lower(), {'active': True, 'strength': None})
|
||||
|
||||
# Debug logging
|
||||
print(f"[PromptManagerAdvanced] Processing LoRA: {lora_name}, original_strength={model_strength}, toggle_strength={toggle_state.get('strength')}, active={toggle_state.get('active')}")
|
||||
|
||||
if not toggle_state['active']:
|
||||
continue # Skip inactive loras
|
||||
|
||||
@@ -487,8 +436,6 @@ class PromptManagerAdvanced:
|
||||
resolved_path, found = self._resolve_lora_path_with_status(lora_path, lora_files)
|
||||
if found:
|
||||
filtered_stack.append((resolved_path, model_strength, clip_strength))
|
||||
else:
|
||||
print(f"[PromptManagerAdvanced] Skipping unfound LoRA: {lora_name}")
|
||||
|
||||
return filtered_stack
|
||||
|
||||
@@ -517,9 +464,11 @@ class PromptManagerAdvanced:
|
||||
# Not found
|
||||
return lora_path, False
|
||||
|
||||
def get_prompt(self, category, name, use_prompt_input, text="", use_lora_input=True, prompt_input=None,
|
||||
lora_stack_a=None, lora_stack_b=None, trigger_words=None, thumbnail_image=None,
|
||||
unique_id=None, loras_a_toggle=None, loras_b_toggle=None, trigger_words_toggle=None):
|
||||
def get_prompt(self, category, name, use_prompt_input, use_lora_input=True, use_workflow_data=False, text="", swap_lora_outputs=False,
|
||||
prompt=None, lora_stack_a=None, lora_stack_b=None,
|
||||
trigger_words=None, thumbnail_image=None, workflow_data=None,
|
||||
unique_id=None, loras_a_toggle=None, loras_b_toggle=None, trigger_words_toggle=None,
|
||||
saved_workflow_data=None):
|
||||
"""Return the prompt text and filtered lora stacks based on toggle states"""
|
||||
|
||||
# ========================================
|
||||
@@ -546,7 +495,7 @@ class PromptManagerAdvanced:
|
||||
current_prompt_key = f"{category}|{name}"
|
||||
current_input_loras_a = [lora_path for lora_path, _, _ in lora_stack_a] if lora_stack_a else []
|
||||
current_input_loras_b = [lora_path for lora_path, _, _ in lora_stack_b] if lora_stack_b else []
|
||||
current_prompt_input_text = prompt_input if prompt_input else ""
|
||||
current_prompt_input_text = prompt if prompt else ""
|
||||
current_toggle_data_a = loras_a_toggle if loras_a_toggle else ""
|
||||
current_toggle_data_b = loras_b_toggle if loras_b_toggle else ""
|
||||
|
||||
@@ -583,10 +532,52 @@ class PromptManagerAdvanced:
|
||||
# CONTINUE WITH NORMAL PROCESSING
|
||||
# ========================================
|
||||
|
||||
# Choose which text to use based on the toggle
|
||||
# When use_prompt_input is OFF, always use the internal text widget regardless of what's connected
|
||||
if use_prompt_input and prompt_input:
|
||||
output_text = prompt_input
|
||||
# Resolve workflow payload candidates.
|
||||
# IMPORTANT: when use_workflow_data is OFF, do not pass through live
|
||||
# upstream workflow_data updates to this node's workflow_data output.
|
||||
prompts_data = self.load_prompts()
|
||||
prompt_entry = prompts_data.get(category, {}).get(name, {}) if isinstance(prompts_data, dict) else {}
|
||||
stored_prompt_wf = prompt_entry.get("workflow_data") if isinstance(prompt_entry, dict) else None
|
||||
|
||||
live_workflow_data = None
|
||||
if isinstance(workflow_data, dict):
|
||||
live_workflow_data = workflow_data
|
||||
elif isinstance(workflow_data, str) and workflow_data.strip():
|
||||
try:
|
||||
parsed = json.loads(workflow_data)
|
||||
if isinstance(parsed, dict):
|
||||
live_workflow_data = parsed
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
live_workflow_data = None
|
||||
|
||||
hidden_saved_wf = None
|
||||
if isinstance(saved_workflow_data, str) and saved_workflow_data.strip():
|
||||
try:
|
||||
parsed_saved = json.loads(saved_workflow_data)
|
||||
if isinstance(parsed_saved, dict):
|
||||
hidden_saved_wf = parsed_saved
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
hidden_saved_wf = None
|
||||
|
||||
if use_workflow_data:
|
||||
# Workflow mode ON: keep local manager state authoritative.
|
||||
# Priority: hidden saved widget -> prompt-stored workflow_data -> live upstream fallback.
|
||||
resolved_workflow_data = hidden_saved_wf
|
||||
if resolved_workflow_data is None and isinstance(stored_prompt_wf, dict):
|
||||
resolved_workflow_data = stored_prompt_wf
|
||||
if resolved_workflow_data is None:
|
||||
resolved_workflow_data = live_workflow_data
|
||||
else:
|
||||
# Workflow mode OFF: never source from connected/hidden live payload.
|
||||
resolved_workflow_data = stored_prompt_wf if isinstance(stored_prompt_wf, dict) else None
|
||||
|
||||
# Choose which text to use based on the toggles
|
||||
# Priority: use_prompt_input > use_workflow_data > internal text
|
||||
if use_prompt_input and prompt:
|
||||
output_text = prompt
|
||||
elif use_workflow_data and resolved_workflow_data:
|
||||
wf = resolved_workflow_data if isinstance(resolved_workflow_data, dict) else {}
|
||||
output_text = wf.get('positive_prompt', '') or text or ""
|
||||
else:
|
||||
output_text = text if text else ""
|
||||
|
||||
@@ -639,10 +630,24 @@ class PromptManagerAdvanced:
|
||||
all_preset_loras_a = self._get_all_loras_from_toggle(loras_a_toggle) if loras_a_toggle else []
|
||||
all_preset_loras_b = self._get_all_loras_from_toggle(loras_b_toggle) if loras_b_toggle else []
|
||||
|
||||
wf_loras_a = []
|
||||
wf_loras_b = []
|
||||
if use_workflow_data and resolved_workflow_data and isinstance(resolved_workflow_data, dict):
|
||||
wf_loras_a = [
|
||||
(wf_lora['name'], wf_lora.get('model_strength', 1.0), wf_lora.get('clip_strength', 1.0))
|
||||
for wf_lora in resolved_workflow_data.get('loras_a', []) if isinstance(wf_lora, dict) and wf_lora.get('name')
|
||||
]
|
||||
wf_loras_b = [
|
||||
(wf_lora['name'], wf_lora.get('model_strength', 1.0), wf_lora.get('clip_strength', 1.0))
|
||||
for wf_lora in resolved_workflow_data.get('loras_b', []) if isinstance(wf_lora, dict) and wf_lora.get('name')
|
||||
]
|
||||
|
||||
# When use_lora_input is disabled, ignore connected stacks and use only saved loras
|
||||
if not use_lora_input:
|
||||
lora_stack_a = preset_stack_a
|
||||
lora_stack_b = preset_stack_b
|
||||
# If workflow mode is enabled and workflow_data carries LoRAs, show/use those.
|
||||
# Otherwise, fall back to saved preset LoRAs.
|
||||
lora_stack_a = wf_loras_a if wf_loras_a else preset_stack_a
|
||||
lora_stack_b = wf_loras_b if wf_loras_b else preset_stack_b
|
||||
else:
|
||||
# Merge: preset loras + connected loras (avoiding duplicates by lora name)
|
||||
# Handle case where connected stack might be None or empty
|
||||
@@ -656,6 +661,12 @@ class PromptManagerAdvanced:
|
||||
else:
|
||||
lora_stack_b = preset_stack_b if preset_stack_b else []
|
||||
|
||||
# Merge workflow_data loras (lowest priority — existing stacks take precedence)
|
||||
if wf_loras_a:
|
||||
lora_stack_a = self._merge_lora_stacks(lora_stack_a, wf_loras_a)
|
||||
if wf_loras_b:
|
||||
lora_stack_b = self._merge_lora_stacks(lora_stack_b, wf_loras_b)
|
||||
|
||||
# Process lora stacks with toggle data (filter inactive, apply strength)
|
||||
processed_stack_a = self._process_lora_toggle(lora_stack_a, loras_a_toggle)
|
||||
processed_stack_b = self._process_lora_toggle(lora_stack_b, loras_b_toggle)
|
||||
@@ -663,8 +674,13 @@ class PromptManagerAdvanced:
|
||||
# Display logic: Include ALL loras (available + unavailable) so UI shows complete picture
|
||||
# Build display from available loras first, then add unavailable ones
|
||||
if not use_lora_input:
|
||||
loras_a_display = self._format_loras_for_display_with_unavailable(preset_stack_a, all_preset_loras_a)
|
||||
loras_b_display = self._format_loras_for_display_with_unavailable(preset_stack_b, all_preset_loras_b)
|
||||
if use_workflow_data and (wf_loras_a or wf_loras_b):
|
||||
# Workflow mode: display workflow LoRAs directly.
|
||||
loras_a_display = self._format_loras_for_display(lora_stack_a)
|
||||
loras_b_display = self._format_loras_for_display(lora_stack_b)
|
||||
else:
|
||||
loras_a_display = self._format_loras_for_display_with_unavailable(preset_stack_a, all_preset_loras_a)
|
||||
loras_b_display = self._format_loras_for_display_with_unavailable(preset_stack_b, all_preset_loras_b)
|
||||
else:
|
||||
loras_a_display = self._format_loras_for_display_with_unavailable(lora_stack_a, all_preset_loras_a)
|
||||
loras_b_display = self._format_loras_for_display_with_unavailable(lora_stack_b, all_preset_loras_b)
|
||||
@@ -687,7 +703,9 @@ class PromptManagerAdvanced:
|
||||
"node_id": unique_id,
|
||||
"prompt": output_text,
|
||||
"use_prompt_input": use_prompt_input,
|
||||
"prompt_input": prompt_input,
|
||||
"use_workflow_data": use_workflow_data,
|
||||
"prompt_input": prompt,
|
||||
"workflow_data": to_json_safe_workflow_data(resolved_workflow_data) if isinstance(resolved_workflow_data, dict) else None,
|
||||
"loras_a": loras_a_display,
|
||||
"loras_b": loras_b_display,
|
||||
"input_loras_a": input_loras_a, # Original input loras for change detection
|
||||
@@ -704,11 +722,51 @@ class PromptManagerAdvanced:
|
||||
# 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 [])
|
||||
# Swap outputs if requested
|
||||
out_stack_a = processed_stack_a if processed_stack_a else []
|
||||
out_stack_b = processed_stack_b if processed_stack_b else []
|
||||
if swap_lora_outputs:
|
||||
out_stack_a, out_stack_b = out_stack_b, out_stack_a
|
||||
|
||||
def check_lazy_status(self, category, name, use_prompt_input, text, use_lora_input=True, prompt_input=None,
|
||||
lora_stack_a=None, lora_stack_b=None, trigger_words=None, thumbnail_image=None,
|
||||
unique_id=None, loras_a_toggle=None, loras_b_toggle=None, trigger_words_toggle=None):
|
||||
# Build workflow_data output — start from incoming or saved data, update with PMA state
|
||||
if isinstance(resolved_workflow_data, dict):
|
||||
out_workflow_data = dict(resolved_workflow_data)
|
||||
else:
|
||||
out_workflow_data = {}
|
||||
out_workflow_data['positive_prompt'] = final_output
|
||||
out_workflow_data['loras_a'] = [
|
||||
{
|
||||
'name': lora.get('name', ''),
|
||||
'model_strength': lora.get('model_strength', lora.get('strength', 1.0)),
|
||||
'clip_strength': lora.get('clip_strength', lora.get('strength', 1.0)),
|
||||
'active': lora.get('active', True),
|
||||
'available': lora.get('available', True),
|
||||
'found': lora.get('available', True),
|
||||
}
|
||||
for lora in loras_a_display
|
||||
if isinstance(lora, dict) and lora.get('name')
|
||||
]
|
||||
out_workflow_data['loras_b'] = [
|
||||
{
|
||||
'name': lora.get('name', ''),
|
||||
'model_strength': lora.get('model_strength', lora.get('strength', 1.0)),
|
||||
'clip_strength': lora.get('clip_strength', lora.get('strength', 1.0)),
|
||||
'active': lora.get('active', True),
|
||||
'available': lora.get('available', True),
|
||||
'found': lora.get('available', True),
|
||||
}
|
||||
for lora in loras_b_display
|
||||
if isinstance(lora, dict) and lora.get('name')
|
||||
]
|
||||
out_workflow_data['_source'] = 'PromptManagerAdvanced'
|
||||
|
||||
return (final_output, out_stack_a, out_stack_b, out_workflow_data)
|
||||
|
||||
def check_lazy_status(self, category, name, use_prompt_input, use_lora_input=True, use_workflow_data=False, text="", swap_lora_outputs=False,
|
||||
prompt=None, lora_stack_a=None, lora_stack_b=None,
|
||||
trigger_words=None, thumbnail_image=None, workflow_data=None,
|
||||
unique_id=None, loras_a_toggle=None, loras_b_toggle=None,
|
||||
trigger_words_toggle=None, saved_workflow_data=None):
|
||||
"""Tell ComfyUI which lazy inputs are needed based on current settings.
|
||||
|
||||
When use_prompt_input is enabled, we need to request the prompt_input
|
||||
@@ -716,7 +774,7 @@ class PromptManagerAdvanced:
|
||||
"""
|
||||
needed = []
|
||||
if use_prompt_input:
|
||||
needed.append("prompt_input")
|
||||
needed.append("prompt")
|
||||
return needed
|
||||
|
||||
def _build_stack_from_toggle(self, toggle_data):
|
||||
@@ -812,7 +870,8 @@ class PromptManagerAdvanced:
|
||||
"clip_strength": clip_strength,
|
||||
"active": True,
|
||||
"strength": model_strength,
|
||||
"available": available
|
||||
"available": available,
|
||||
"found": available
|
||||
})
|
||||
seen_names.add(lora_name_lower)
|
||||
|
||||
@@ -854,7 +913,8 @@ class PromptManagerAdvanced:
|
||||
"strength": float(item.get('strength', 1.0)),
|
||||
"clip_strength": float(item.get('clip_strength', item.get('strength', 1.0))),
|
||||
"active": item.get('active', True),
|
||||
"available": found
|
||||
"available": found,
|
||||
"found": found
|
||||
})
|
||||
|
||||
return all_loras
|
||||
@@ -879,7 +939,8 @@ class PromptManagerAdvanced:
|
||||
"clip_strength": lora['clip_strength'],
|
||||
"active": lora['active'],
|
||||
"strength": lora['strength'],
|
||||
"available": lora['available']
|
||||
"available": lora['available'],
|
||||
"found": lora.get('found', lora['available'])
|
||||
})
|
||||
seen_names.add(lora_name_lower)
|
||||
|
||||
@@ -1116,14 +1177,43 @@ async def save_prompt_advanced(request):
|
||||
normalized = []
|
||||
for lora in loras:
|
||||
if isinstance(lora, dict) and lora.get('name'):
|
||||
available = lora.get('available', lora.get('found', True))
|
||||
found = lora.get('found', available)
|
||||
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)
|
||||
"active": lora.get('active', True),
|
||||
"available": bool(available),
|
||||
"found": bool(found),
|
||||
})
|
||||
return normalized
|
||||
|
||||
def normalize_workflow_lora_data(wf_loras):
|
||||
"""Normalize LoRAs coming from workflow_data payload structure."""
|
||||
normalized = []
|
||||
if not isinstance(wf_loras, list):
|
||||
return normalized
|
||||
for lora in wf_loras:
|
||||
if not isinstance(lora, dict):
|
||||
continue
|
||||
name = str(lora.get('name', '')).strip()
|
||||
if not name:
|
||||
continue
|
||||
strength = lora.get('strength', lora.get('model_strength', 1.0))
|
||||
clip_strength = lora.get('clip_strength', strength)
|
||||
available = lora.get('available', lora.get('found', True))
|
||||
found = lora.get('found', available)
|
||||
normalized.append({
|
||||
"name": name,
|
||||
"strength": strength,
|
||||
"clip_strength": clip_strength,
|
||||
"active": lora.get('active', True),
|
||||
"available": bool(available),
|
||||
"found": bool(found),
|
||||
})
|
||||
return normalized
|
||||
|
||||
# Normalize trigger words data
|
||||
def normalize_trigger_words(words):
|
||||
normalized = []
|
||||
@@ -1151,13 +1241,71 @@ async def save_prompt_advanced(request):
|
||||
if thumbnail is None:
|
||||
thumbnail = existing_prompt.get("thumbnail")
|
||||
|
||||
# Save workflow_data if provided.
|
||||
workflow_data = data.get("workflow_data")
|
||||
wf_to_save = None
|
||||
if isinstance(workflow_data, dict):
|
||||
wf_to_save = to_json_safe_workflow_data(workflow_data)
|
||||
elif isinstance(workflow_data, str) and workflow_data.strip():
|
||||
try:
|
||||
parsed_wf = json.loads(workflow_data)
|
||||
if isinstance(parsed_wf, dict):
|
||||
wf_to_save = to_json_safe_workflow_data(parsed_wf)
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
wf_to_save = None
|
||||
|
||||
# Save prompt with normalized lora data (no paths - they're resolved at runtime)
|
||||
normalized_loras_a = normalize_lora_data(loras_a)
|
||||
normalized_loras_b = normalize_lora_data(loras_b)
|
||||
|
||||
# Workflow Saver parity: when workflow_data is present, treat its LoRA lists
|
||||
# as authoritative for persistence.
|
||||
wf_loras_a = normalize_workflow_lora_data((wf_to_save or {}).get("loras_a", []))
|
||||
wf_loras_b = normalize_workflow_lora_data((wf_to_save or {}).get("loras_b", []))
|
||||
if isinstance(wf_to_save, dict):
|
||||
if "loras_a" in wf_to_save:
|
||||
normalized_loras_a = wf_loras_a
|
||||
elif not normalized_loras_a and wf_loras_a:
|
||||
normalized_loras_a = wf_loras_a
|
||||
|
||||
if "loras_b" in wf_to_save:
|
||||
normalized_loras_b = wf_loras_b
|
||||
elif not normalized_loras_b and wf_loras_b:
|
||||
normalized_loras_b = wf_loras_b
|
||||
|
||||
# Guard against accidental empty-stack overwrites from transient UI state.
|
||||
# If the incoming payload has no LoRAs for a side, preserve existing saved
|
||||
# LoRAs for that side instead of silently erasing them.
|
||||
if not normalized_loras_a and isinstance(existing_prompt.get("loras_a"), list):
|
||||
normalized_loras_a = existing_prompt.get("loras_a", [])
|
||||
if not normalized_loras_b and isinstance(existing_prompt.get("loras_b"), list):
|
||||
normalized_loras_b = existing_prompt.get("loras_b", [])
|
||||
|
||||
prompt_data = {
|
||||
"prompt": text,
|
||||
"loras_a": normalize_lora_data(loras_a),
|
||||
"loras_b": normalize_lora_data(loras_b),
|
||||
"loras_a": normalized_loras_a,
|
||||
"loras_b": normalized_loras_b,
|
||||
"trigger_words": normalize_trigger_words(trigger_words)
|
||||
}
|
||||
|
||||
# Persist prompt fields from workflow_data snapshot when available.
|
||||
if isinstance(wf_to_save, dict):
|
||||
if isinstance(wf_to_save.get("positive_prompt"), str):
|
||||
prompt_data["prompt"] = wf_to_save.get("positive_prompt", "")
|
||||
if isinstance(wf_to_save.get("negative_prompt"), str):
|
||||
prompt_data["negative_prompt"] = wf_to_save.get("negative_prompt", "")
|
||||
prompt_data["saved_from"] = "WorkflowManager"
|
||||
prompt_data["saved_at"] = datetime.utcnow().isoformat() + "Z"
|
||||
|
||||
if wf_to_save:
|
||||
prompt_data["workflow_data"] = wf_to_save
|
||||
else:
|
||||
# Preserve previously saved workflow_data when user saves prompt/LoRA
|
||||
# edits without a currently connected workflow_data source.
|
||||
existing_wf = existing_prompt.get("workflow_data")
|
||||
if isinstance(existing_wf, dict):
|
||||
prompt_data["workflow_data"] = to_json_safe_workflow_data(existing_wf)
|
||||
|
||||
if thumbnail:
|
||||
prompt_data["thumbnail"] = thumbnail
|
||||
|
||||
@@ -1168,6 +1316,14 @@ async def save_prompt_advanced(request):
|
||||
elif existing_prompt.get("nsfw"):
|
||||
prompt_data["nsfw"] = existing_prompt["nsfw"]
|
||||
|
||||
# Preserve any extra fields from an existing prompt that this node does not manage.
|
||||
# This includes workflow_config (added by WorkflowManager) and any future extensions.
|
||||
# Known managed keys — everything else is preserved verbatim.
|
||||
_MANAGED_KEYS = {"prompt", "negative_prompt", "loras_a", "loras_b", "trigger_words", "thumbnail", "nsfw", "workflow_data", "saved_from", "saved_at"}
|
||||
for extra_key, extra_val in existing_prompt.items():
|
||||
if extra_key not in _MANAGED_KEYS and extra_key not in prompt_data:
|
||||
prompt_data[extra_key] = extra_val
|
||||
|
||||
prompts[category][name] = prompt_data
|
||||
PromptManagerAdvanced.save_prompts(prompts)
|
||||
|
||||
@@ -1226,6 +1382,51 @@ async def delete_prompt_advanced(request):
|
||||
return server.web.json_response({"success": False, "error": str(e)}, status=500)
|
||||
|
||||
|
||||
@server.PromptServer.instance.routes.post("/prompt-manager-advanced/rename-prompt")
|
||||
async def rename_prompt_advanced(request):
|
||||
"""API endpoint to rename/move a prompt, optionally to a different category"""
|
||||
try:
|
||||
data = await request.json()
|
||||
category = data.get("category", "").strip()
|
||||
old_name = data.get("old_name", "").strip()
|
||||
new_name = data.get("new_name", "").strip()
|
||||
new_category = data.get("new_category", "").strip() or category
|
||||
|
||||
if not category or not old_name or not new_name:
|
||||
return server.web.json_response({"success": False, "error": "Category, old name, and new name are required"})
|
||||
|
||||
prompts = PromptManagerAdvanced.load_prompts()
|
||||
|
||||
if category not in prompts or old_name not in prompts[category]:
|
||||
return server.web.json_response({"success": False, "error": "Prompt not found"})
|
||||
|
||||
if new_category not in prompts:
|
||||
return server.web.json_response({"success": False, "error": f"Category '{new_category}' not found"})
|
||||
|
||||
# Check for name conflicts in the target category
|
||||
# If same category, exclude the old name from conflict check
|
||||
target_prompts = prompts[new_category]
|
||||
if category == new_category:
|
||||
existing_lower = {k.lower(): k for k in target_prompts.keys() if k != "__meta__" and k.lower() != old_name.lower()}
|
||||
else:
|
||||
existing_lower = {k.lower(): k for k in target_prompts.keys() if k != "__meta__"}
|
||||
|
||||
if new_name.lower() in existing_lower:
|
||||
return server.web.json_response({
|
||||
"success": False,
|
||||
"error": f"A prompt named '{existing_lower[new_name.lower()]}' already exists in '{new_category}'"
|
||||
})
|
||||
|
||||
prompts[new_category][new_name] = prompts[category][old_name]
|
||||
del prompts[category][old_name]
|
||||
PromptManagerAdvanced.save_prompts(prompts)
|
||||
|
||||
return server.web.json_response({"success": True, "prompts": prompts, "new_name": new_name, "new_category": new_category})
|
||||
except Exception as e:
|
||||
print(f"[PromptManagerAdvanced] Error in rename_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"""
|
||||
@@ -1291,7 +1492,8 @@ async def get_prompt_data_advanced(request):
|
||||
"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", [])
|
||||
"trigger_words": prompt_data.get("trigger_words", []),
|
||||
"workflow_data": prompt_data.get("workflow_data")
|
||||
}
|
||||
})
|
||||
except Exception as e:
|
||||
@@ -1425,3 +1627,38 @@ async def toggle_nsfw_advanced(request):
|
||||
except Exception as e:
|
||||
print(f"[PromptManagerAdvanced] Error in toggle_nsfw API: {e}")
|
||||
return server.web.json_response({"success": False, "error": str(e)}, status=500)
|
||||
|
||||
|
||||
@server.PromptServer.instance.routes.get("/prompt-manager-advanced/list-checkpoints")
|
||||
async def list_checkpoints(request):
|
||||
"""API endpoint to list available checkpoints for thumbnail generation"""
|
||||
try:
|
||||
checkpoints = folder_paths.get_filename_list("checkpoints")
|
||||
return server.web.json_response({"success": True, "checkpoints": checkpoints})
|
||||
except Exception as e:
|
||||
print(f"[PromptManagerAdvanced] Error listing checkpoints: {e}")
|
||||
return server.web.json_response({"success": False, "error": str(e)}, status=500)
|
||||
|
||||
|
||||
@server.PromptServer.instance.routes.post("/prompt-manager-advanced/resolve-loras")
|
||||
async def resolve_loras(request):
|
||||
"""API endpoint to resolve LoRA names to paths for thumbnail generation workflow"""
|
||||
try:
|
||||
data = await request.json()
|
||||
lora_names = data.get("lora_names", [])
|
||||
|
||||
resolved = []
|
||||
for lora in lora_names:
|
||||
name = lora.get("name", "")
|
||||
path, found = get_lora_relative_path(name)
|
||||
if found:
|
||||
resolved.append({
|
||||
"path": path,
|
||||
"strength": lora.get("strength", 1.0),
|
||||
"clip_strength": lora.get("clip_strength", 1.0)
|
||||
})
|
||||
|
||||
return server.web.json_response({"success": True, "loras": resolved})
|
||||
except Exception as e:
|
||||
print(f"[PromptManagerAdvanced] Error resolving LoRAs: {e}")
|
||||
return server.web.json_response({"success": False, "error": str(e)}, status=500)
|
||||
@@ -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()
|
||||
@@ -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:
|
||||
@@ -114,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"""
|
||||
@@ -0,0 +1,443 @@
|
||||
"""
|
||||
ComfyUI Workflow Bridge - Pure passthrough node.
|
||||
Unpacks workflow_data into individual typed outputs.
|
||||
Any connected optional input overrides the corresponding field before output.
|
||||
Models (MODEL/CLIP/VAE) are passed through only - use WorkflowModelLoader for loading.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import folder_paths
|
||||
import comfy.samplers
|
||||
from ..py.lora_utils import resolve_lora_path
|
||||
from ..py.workflow_extraction_utils import resolve_model_name
|
||||
from ..py.workflow_families import get_model_family, MODEL_FAMILIES
|
||||
|
||||
|
||||
MODEL_EXTENSIONS = (".safetensors", ".ckpt", ".pt", ".pth", ".gguf")
|
||||
|
||||
|
||||
class _AnyType(str):
|
||||
"""Comfy wildcard type that can connect to any socket type."""
|
||||
|
||||
def __ne__(self, _other):
|
||||
return False
|
||||
|
||||
|
||||
ANY_TYPE = _AnyType("ANY")
|
||||
|
||||
|
||||
def _strip_model_ext(name):
|
||||
base = os.path.basename(str(name or "").replace("\\", "/"))
|
||||
lower = base.lower()
|
||||
for ext in MODEL_EXTENSIONS:
|
||||
if lower.endswith(ext):
|
||||
return base[:-len(ext)]
|
||||
return os.path.splitext(base)[0]
|
||||
|
||||
|
||||
def _resolve_rel_path(raw_name, folder_keys):
|
||||
"""Resolve a model-like name to a relative Comfy path in the provided folder keys."""
|
||||
if not raw_name:
|
||||
return "", False
|
||||
|
||||
raw = str(raw_name).strip().replace("\\", "/")
|
||||
if not raw:
|
||||
return "", False
|
||||
|
||||
base = os.path.basename(raw).lower()
|
||||
base_no_ext = _strip_model_ext(base).lower()
|
||||
|
||||
for key in folder_keys:
|
||||
try:
|
||||
file_list = folder_paths.get_filename_list(key)
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
for rel in file_list:
|
||||
rel_norm = rel.replace("\\", "/")
|
||||
if rel_norm == raw:
|
||||
return rel, True
|
||||
|
||||
rel_base = os.path.basename(rel_norm).lower()
|
||||
if rel_base == base:
|
||||
return rel, True
|
||||
|
||||
if _strip_model_ext(rel_base).lower() == base_no_ext:
|
||||
return rel, True
|
||||
|
||||
return os.path.basename(raw), False
|
||||
|
||||
|
||||
def _get_live_ksampler_combo_types():
|
||||
"""Mirror the active KSampler enum sockets to avoid stale type mismatches."""
|
||||
default_samplers = comfy.samplers.KSampler.SAMPLERS
|
||||
default_schedulers = comfy.samplers.KSampler.SCHEDULERS
|
||||
try:
|
||||
from nodes import KSampler as CoreKSampler
|
||||
required = CoreKSampler.INPUT_TYPES().get("required", {})
|
||||
samplers = required.get("sampler_name", (default_samplers,))[0]
|
||||
schedulers = required.get("scheduler", (default_schedulers,))[0]
|
||||
return samplers, schedulers
|
||||
except Exception:
|
||||
return default_samplers, default_schedulers
|
||||
|
||||
|
||||
_LIVE_SAMPLERS, _LIVE_SCHEDULERS = _get_live_ksampler_combo_types()
|
||||
|
||||
|
||||
DEFAULT_WORKFLOW_DATA = {
|
||||
"_source": "WorkflowBridge",
|
||||
"family": "",
|
||||
"model_a": "",
|
||||
"model_b": "",
|
||||
"positive_prompt": "",
|
||||
"negative_prompt": "",
|
||||
"loras_a": [],
|
||||
"loras_b": [],
|
||||
"vae": "",
|
||||
"clip": [],
|
||||
"clip_type": "",
|
||||
"loader_type": "",
|
||||
"sampler": {
|
||||
"steps_a": 10,
|
||||
"steps_b": 10,
|
||||
"cfg": 5,
|
||||
"seed_a": 0,
|
||||
"seed_b": 0,
|
||||
"sampler_name": "euler",
|
||||
"scheduler": "simple",
|
||||
},
|
||||
"resolution": {
|
||||
"width": 512,
|
||||
"height": 512,
|
||||
"batch_size": 1,
|
||||
"length": 1,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
class WorkflowBridge:
|
||||
"""
|
||||
Pure passthrough bridge node.
|
||||
Unpacks workflow_data into individual typed outputs and forwards
|
||||
any connected MODEL/CLIP/VAE inputs. No model loading.
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def _sync_combo_types(cls):
|
||||
samplers, schedulers = _get_live_ksampler_combo_types()
|
||||
cls._SAMPLER_ENUM = samplers
|
||||
cls._SCHEDULER_ENUM = schedulers
|
||||
cls.RETURN_TYPES = (
|
||||
"WORKFLOW_DATA",
|
||||
"MODEL", "MODEL", "CLIP", "CONDITIONING", "CONDITIONING", "VAE", "LATENT", "IMAGE", "MASK", ANY_TYPE,
|
||||
"INT", "INT", "INT", "INT", "FLOAT",
|
||||
cls._SAMPLER_ENUM, cls._SCHEDULER_ENUM,
|
||||
"STRING", "STRING",
|
||||
"LORA_STACK", "LORA_STACK",
|
||||
"INT", "INT", "INT", "INT",
|
||||
"STRING", "STRING", "STRING", "STRING",
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
cls._sync_combo_types()
|
||||
return {
|
||||
"required": {},
|
||||
"optional": {
|
||||
"workflow_data": ("WORKFLOW_DATA", {"forceInput": True, "tooltip": "Optional workflow data input. If omitted, bridge starts from an empty workflow_data dict."}),
|
||||
"model_a": ("MODEL", {"tooltip": "Pass-through Model A"}),
|
||||
"model_b": ("MODEL", {"tooltip": "Pass-through Model B"}),
|
||||
"clip": ("CLIP", {"tooltip": "Pass-through CLIP"}),
|
||||
"positive": ("CONDITIONING", {"tooltip": "Pass-through positive conditioning"}),
|
||||
"negative": ("CONDITIONING", {"tooltip": "Pass-through negative conditioning"}),
|
||||
"vae": ("VAE", {"tooltip": "Pass-through VAE"}),
|
||||
"latent": ("LATENT", {"tooltip": "Pass-through latent"}),
|
||||
"image": ("IMAGE", {"tooltip": "Pass-through image"}),
|
||||
"mask": ("MASK", {"tooltip": "Pass-through mask"}),
|
||||
"extra": (ANY_TYPE, {"tooltip": "Pass-through extra data (any type)"}),
|
||||
"seed_a": ("INT", {"forceInput": True, "tooltip": "Override seed A"}),
|
||||
"seed_b": ("INT", {"forceInput": True, "tooltip": "Override seed B (dual-sampler)"}),
|
||||
"steps_a": ("INT", {"forceInput": True, "tooltip": "Override sampling steps A"}),
|
||||
"steps_b": ("INT", {"forceInput": True, "tooltip": "Override sampling steps B (dual-sampler)"}),
|
||||
"cfg": ("FLOAT", {"forceInput": True, "tooltip": "Override CFG scale"}),
|
||||
"sampler_name": (cls._SAMPLER_ENUM, {"forceInput": True, "tooltip": "Override sampler name"}),
|
||||
"scheduler": (cls._SCHEDULER_ENUM, {"forceInput": True, "tooltip": "Override scheduler"}),
|
||||
"pos_prompt": ("STRING", {"forceInput": True, "tooltip": "Override positive prompt"}),
|
||||
"neg_prompt": ("STRING", {"forceInput": True, "tooltip": "Override negative prompt"}),
|
||||
"lora_stack_a": ("LORA_STACK", {"tooltip": "Override LoRA stack A"}),
|
||||
"lora_stack_b": ("LORA_STACK", {"tooltip": "Override LoRA stack B"}),
|
||||
"width": ("INT", {"forceInput": True, "tooltip": "Override width"}),
|
||||
"height": ("INT", {"forceInput": True, "tooltip": "Override height"}),
|
||||
"batch_size": ("INT", {"forceInput": True, "tooltip": "Override batch size"}),
|
||||
"length": ("INT", {"forceInput": True, "tooltip": "Override video length"}),
|
||||
"model_a_name": ("STRING", {"forceInput": True, "tooltip": "Optional Model A name/path. Resolves and writes workflow_data['model_a']."}),
|
||||
"model_b_name": ("STRING", {"forceInput": True, "tooltip": "Optional Model B name/path. Resolves and writes workflow_data['model_b']."}),
|
||||
"clip_name": ("STRING", {"forceInput": True, "tooltip": "Optional CLIP name/path. Resolves and writes workflow_data['clip']."}),
|
||||
"vae_name": ("STRING", {"forceInput": True, "tooltip": "Optional VAE name/path. Resolves and writes workflow_data['vae']."}),
|
||||
},
|
||||
}
|
||||
|
||||
RETURN_TYPES = (
|
||||
"WORKFLOW_DATA",
|
||||
"MODEL", "MODEL", "CLIP", "CONDITIONING", "CONDITIONING", "VAE", "LATENT", "IMAGE", "MASK", ANY_TYPE,
|
||||
"INT", "INT", "INT", "INT", "FLOAT",
|
||||
_LIVE_SAMPLERS, _LIVE_SCHEDULERS,
|
||||
"STRING", "STRING",
|
||||
"LORA_STACK", "LORA_STACK",
|
||||
"INT", "INT", "INT", "INT",
|
||||
"STRING", "STRING", "STRING", "STRING",
|
||||
)
|
||||
RETURN_NAMES = (
|
||||
"workflow_data",
|
||||
"model_a", "model_b", "clip", "positive", "negative", "vae", "latent", "image", "mask", "extra",
|
||||
"seed_a", "seed_b", "steps_a", "steps_b", "cfg",
|
||||
"sampler_name", "scheduler",
|
||||
"pos_prompt", "neg_prompt",
|
||||
"lora_stack_a", "lora_stack_b",
|
||||
"width", "height", "batch_size", "length",
|
||||
"model_a_name", "model_b_name", "clip_name", "vae_name",
|
||||
)
|
||||
FUNCTION = "unpack"
|
||||
CATEGORY = "Prompt Manager"
|
||||
DESCRIPTION = (
|
||||
"Pure passthrough bridge node. Unpacks workflow_data into individual "
|
||||
"typed outputs. Models are forwarded from connected inputs only."
|
||||
)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def unpack(self, workflow_data=None, **kwargs):
|
||||
def _short_display_name(name):
|
||||
raw = str(name or "").strip()
|
||||
if not raw:
|
||||
return ""
|
||||
base = os.path.basename(raw.replace("\\", "/"))
|
||||
return os.path.splitext(base)[0]
|
||||
|
||||
# Accept both dict and JSON string
|
||||
if isinstance(workflow_data, str):
|
||||
try:
|
||||
incoming_wf = json.loads(workflow_data)
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
incoming_wf = {}
|
||||
elif isinstance(workflow_data, dict):
|
||||
incoming_wf = dict(workflow_data)
|
||||
else:
|
||||
incoming_wf = {}
|
||||
|
||||
# Start from a full empty-workflow template, then layer incoming values.
|
||||
wf = dict(DEFAULT_WORKFLOW_DATA)
|
||||
if isinstance(incoming_wf, dict):
|
||||
wf.update(incoming_wf)
|
||||
|
||||
incoming_sampler = incoming_wf.get('sampler')
|
||||
if isinstance(incoming_sampler, dict):
|
||||
wf['sampler'] = dict(DEFAULT_WORKFLOW_DATA['sampler'])
|
||||
wf['sampler'].update(incoming_sampler)
|
||||
|
||||
incoming_resolution = incoming_wf.get('resolution')
|
||||
if isinstance(incoming_resolution, dict):
|
||||
wf['resolution'] = dict(DEFAULT_WORKFLOW_DATA['resolution'])
|
||||
wf['resolution'].update(incoming_resolution)
|
||||
|
||||
sampler = dict(wf.get('sampler', DEFAULT_WORKFLOW_DATA['sampler']))
|
||||
resolution = dict(wf.get('resolution', DEFAULT_WORKFLOW_DATA['resolution']))
|
||||
|
||||
# -- Apply top-level overrides -------------------------------
|
||||
pos_text = kwargs.get('pos_prompt')
|
||||
if pos_text is not None:
|
||||
wf['positive_prompt'] = pos_text
|
||||
|
||||
neg_text = kwargs.get('neg_prompt')
|
||||
if neg_text is not None:
|
||||
wf['negative_prompt'] = neg_text
|
||||
|
||||
# -- LoRA stack overrides ------------------------------------
|
||||
if kwargs.get('lora_stack_a') is not None:
|
||||
wf['loras_a'] = [
|
||||
{'name': n, 'model_strength': ms, 'clip_strength': cs}
|
||||
for n, ms, cs in kwargs['lora_stack_a']
|
||||
]
|
||||
if kwargs.get('lora_stack_b') is not None:
|
||||
wf['loras_b'] = [
|
||||
{'name': n, 'model_strength': ms, 'clip_strength': cs}
|
||||
for n, ms, cs in kwargs['lora_stack_b']
|
||||
]
|
||||
|
||||
# -- Resolution overrides ------------------------------------
|
||||
for key in ('width', 'height', 'batch_size', 'length'):
|
||||
if kwargs.get(key) is not None:
|
||||
resolution[key] = kwargs[key]
|
||||
wf['resolution'] = resolution
|
||||
|
||||
# -- Sampler overrides ---------------------------------------
|
||||
for key in ('steps_a', 'steps_b', 'cfg', 'seed_a', 'seed_b', 'sampler_name', 'scheduler'):
|
||||
if kwargs.get(key) is not None:
|
||||
sampler[key] = kwargs[key]
|
||||
wf['sampler'] = sampler
|
||||
|
||||
# -- Model/CLIP/VAE name overrides ---------------------------
|
||||
model_a_name_in = kwargs.get('model_a_name')
|
||||
model_b_name_in = kwargs.get('model_b_name')
|
||||
clip_name_in = kwargs.get('clip_name')
|
||||
vae_name_in = kwargs.get('vae_name')
|
||||
|
||||
if isinstance(model_a_name_in, str) and model_a_name_in.strip():
|
||||
resolved_a, _ = resolve_model_name(model_a_name_in)
|
||||
wf['model_a'] = resolved_a or os.path.basename(model_a_name_in.strip().replace("\\", "/"))
|
||||
|
||||
family = get_model_family(wf['model_a'])
|
||||
if family:
|
||||
wf['family'] = family
|
||||
family_spec = MODEL_FAMILIES.get(family, {})
|
||||
wf['clip_type'] = family_spec.get('clip_type', '')
|
||||
wf['loader_type'] = 'checkpoint' if family_spec.get('checkpoint', False) else 'unet'
|
||||
|
||||
if isinstance(model_b_name_in, str) and model_b_name_in.strip():
|
||||
resolved_b, _ = resolve_model_name(model_b_name_in)
|
||||
wf['model_b'] = resolved_b or os.path.basename(model_b_name_in.strip().replace("\\", "/"))
|
||||
|
||||
if isinstance(clip_name_in, str) and clip_name_in.strip():
|
||||
resolved_clip, _ = _resolve_rel_path(clip_name_in, ["text_encoders", "clip", "checkpoints"])
|
||||
wf['clip'] = [resolved_clip] if resolved_clip else []
|
||||
|
||||
if isinstance(vae_name_in, str) and vae_name_in.strip():
|
||||
resolved_vae, _ = _resolve_rel_path(vae_name_in, ["vae", "checkpoints"])
|
||||
wf['vae'] = resolved_vae
|
||||
|
||||
# -- Pass-through MODEL / CLIP / VAE -------------------------
|
||||
# Priority: explicit connected inputs > embedded objects in workflow_data.
|
||||
model_a = kwargs.get('model_a')
|
||||
if model_a is None:
|
||||
model_a = wf.get('MODEL_A')
|
||||
|
||||
model_b = kwargs.get('model_b')
|
||||
if model_b is None:
|
||||
model_b = wf.get('MODEL_B')
|
||||
|
||||
clip = kwargs.get('clip')
|
||||
if clip is None:
|
||||
clip = wf.get('CLIP')
|
||||
|
||||
vae = kwargs.get('vae')
|
||||
if vae is None:
|
||||
vae = wf.get('VAE')
|
||||
|
||||
positive = kwargs.get('positive')
|
||||
if positive is None:
|
||||
positive = wf.get('POSITIVE')
|
||||
|
||||
negative = kwargs.get('negative')
|
||||
if negative is None:
|
||||
negative = wf.get('NEGATIVE')
|
||||
|
||||
latent = kwargs.get('latent')
|
||||
if latent is None:
|
||||
latent = wf.get('LATENT')
|
||||
|
||||
image = kwargs.get('image')
|
||||
if image is None:
|
||||
image = wf.get('IMAGE')
|
||||
|
||||
mask = kwargs.get('mask')
|
||||
if mask is None:
|
||||
mask = wf.get('MASK')
|
||||
|
||||
extra = kwargs.get('extra')
|
||||
if extra is None:
|
||||
extra = wf.get('EXTRA')
|
||||
|
||||
if model_a is not None:
|
||||
wf['MODEL_A'] = model_a
|
||||
if model_b is not None:
|
||||
wf['MODEL_B'] = model_b
|
||||
if clip is not None:
|
||||
wf['CLIP'] = clip
|
||||
if vae is not None:
|
||||
wf['VAE'] = vae
|
||||
if positive is not None:
|
||||
wf['POSITIVE'] = positive
|
||||
if negative is not None:
|
||||
wf['NEGATIVE'] = negative
|
||||
if latent is not None:
|
||||
wf['LATENT'] = latent
|
||||
if image is not None:
|
||||
wf['IMAGE'] = image
|
||||
if mask is not None:
|
||||
wf['MASK'] = mask
|
||||
if extra is not None:
|
||||
wf['EXTRA'] = extra
|
||||
|
||||
# -- Build lora stacks as tuples for LORA_STACK output -------
|
||||
# Filter not-found LoRAs here so downstream nodes receiving
|
||||
# LORA_STACK don't get unavailable entries. Keep wf['loras_*']
|
||||
# unchanged to preserve authored workflow_data for chaining.
|
||||
_lora_found_cache = {}
|
||||
|
||||
def _lora_is_found(name):
|
||||
if not name:
|
||||
return False
|
||||
if name in _lora_found_cache:
|
||||
return _lora_found_cache[name]
|
||||
_, found = resolve_lora_path(name)
|
||||
_lora_found_cache[name] = bool(found)
|
||||
return _lora_found_cache[name]
|
||||
|
||||
def _is_active_available_found(lora_item):
|
||||
if not isinstance(lora_item, dict):
|
||||
return False
|
||||
lora_name = lora_item.get('name')
|
||||
if not lora_name:
|
||||
return False
|
||||
if lora_item.get('active', True) is False:
|
||||
return False
|
||||
if lora_item.get('available', True) is False:
|
||||
return False
|
||||
return _lora_is_found(lora_name)
|
||||
|
||||
lora_stack_a = [
|
||||
(item['name'], item.get('model_strength', 1.0), item.get('clip_strength', 1.0))
|
||||
for item in wf.get('loras_a', [])
|
||||
if _is_active_available_found(item)
|
||||
]
|
||||
lora_stack_b = [
|
||||
(item['name'], item.get('model_strength', 1.0), item.get('clip_strength', 1.0))
|
||||
for item in wf.get('loras_b', [])
|
||||
if _is_active_available_found(item)
|
||||
]
|
||||
|
||||
# -- Extract all output values -------------------------------
|
||||
model_a_name = _short_display_name(wf.get('model_a', ''))
|
||||
model_b_name = _short_display_name(wf.get('model_b', ''))
|
||||
clip_name = ''
|
||||
clip_field = wf.get('clip', [])
|
||||
if isinstance(clip_field, list) and clip_field:
|
||||
clip_name = _short_display_name(clip_field[0])
|
||||
elif isinstance(clip_field, str):
|
||||
clip_name = _short_display_name(clip_field)
|
||||
vae_name = _short_display_name(wf.get('vae', ''))
|
||||
|
||||
return (
|
||||
wf,
|
||||
model_a, model_b, clip, positive, negative, vae, latent, image, mask, extra,
|
||||
sampler.get('seed_a', sampler.get('seed', 0)),
|
||||
sampler.get('seed_b', 0) or 0,
|
||||
sampler.get('steps_a', sampler.get('steps', 10)),
|
||||
sampler.get('steps_b', sampler.get('steps_a', sampler.get('steps', 10))),
|
||||
sampler.get('cfg', 5.0),
|
||||
sampler.get('sampler_name', 'euler'),
|
||||
sampler.get('scheduler', 'simple'),
|
||||
wf.get('positive_prompt', ''),
|
||||
wf.get('negative_prompt', ''),
|
||||
lora_stack_a,
|
||||
lora_stack_b,
|
||||
resolution.get('width', 512),
|
||||
resolution.get('height', 512),
|
||||
resolution.get('batch_size', 1),
|
||||
resolution.get('length', 0) or 0,
|
||||
model_a_name,
|
||||
model_b_name,
|
||||
clip_name,
|
||||
vae_name,
|
||||
)
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,273 @@
|
||||
"""
|
||||
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 to_json_safe_workflow_data
|
||||
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"[WorkflowManager] Thumbnail generation failed: {e}")
|
||||
return None
|
||||
|
||||
|
||||
class WorkflowManager(PromptManagerAdvanced):
|
||||
"""Workflow-focused manager that edits and forwards WORKFLOW_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"
|
||||
|
||||
first_prompt = ""
|
||||
first_prompt_text = ""
|
||||
if prompts_data and first_category in prompts_data and prompts_data[first_category]:
|
||||
first_category_prompts = [k for k in prompts_data[first_category].keys() if k != "__meta__"]
|
||||
first_prompt = sorted(first_category_prompts, key=str.lower)[0] if first_category_prompts else ""
|
||||
if first_prompt:
|
||||
first_prompt_text = prompts_data[first_category][first_prompt].get("prompt", "")
|
||||
|
||||
return {
|
||||
"required": {
|
||||
"category": (categories, {"default": first_category}),
|
||||
"name": (all_prompts_list, {"default": first_prompt}),
|
||||
"text": ("STRING", {
|
||||
"multiline": True,
|
||||
"default": first_prompt_text,
|
||||
"placeholder": "Enter prompt text",
|
||||
"dynamicPrompts": False,
|
||||
"tooltip": "Edit workflow_data prompt text directly",
|
||||
}),
|
||||
},
|
||||
"optional": {
|
||||
"workflow_data": ("WORKFLOW_DATA", {"forceInput": True, "tooltip": "Connected workflow_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 = ("WORKFLOW_DATA",)
|
||||
RETURN_NAMES = ("workflow_data",)
|
||||
FUNCTION = "get_workflow"
|
||||
OUTPUT_NODE = True
|
||||
|
||||
@classmethod
|
||||
def IS_CHANGED(cls, category, name, text="", **kwargs):
|
||||
workflow_data = kwargs.get("workflow_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(workflow_data) if workflow_data else None,
|
||||
loras_a_toggle or "",
|
||||
loras_b_toggle or "",
|
||||
saved_workflow_data or "",
|
||||
)
|
||||
|
||||
def get_workflow(
|
||||
self,
|
||||
category,
|
||||
name,
|
||||
text="",
|
||||
workflow_data=None,
|
||||
unique_id=None,
|
||||
loras_a_toggle=None,
|
||||
loras_b_toggle=None,
|
||||
saved_workflow_data=None,
|
||||
):
|
||||
prompts_data = self.load_prompts()
|
||||
prompt_entry = prompts_data.get(category, {}).get(name, {}) if isinstance(prompts_data, dict) else {}
|
||||
stored_prompt_wf = prompt_entry.get("workflow_data") if isinstance(prompt_entry, dict) else None
|
||||
|
||||
live_workflow_data = None
|
||||
if isinstance(workflow_data, dict):
|
||||
live_workflow_data = workflow_data
|
||||
elif isinstance(workflow_data, str) and workflow_data.strip():
|
||||
try:
|
||||
parsed = json.loads(workflow_data)
|
||||
if isinstance(parsed, dict):
|
||||
live_workflow_data = parsed
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
live_workflow_data = None
|
||||
|
||||
hidden_saved_wf = None
|
||||
if isinstance(saved_workflow_data, str) and saved_workflow_data.strip():
|
||||
try:
|
||||
parsed_saved = json.loads(saved_workflow_data)
|
||||
if isinstance(parsed_saved, dict):
|
||||
hidden_saved_wf = parsed_saved
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
hidden_saved_wf = None
|
||||
|
||||
# WorkflowManager should prefer live connected workflow_data when present,
|
||||
# then fall back to local serialized state.
|
||||
resolved_workflow_data = live_workflow_data if isinstance(live_workflow_data, dict) else None
|
||||
if resolved_workflow_data is None:
|
||||
resolved_workflow_data = hidden_saved_wf
|
||||
if resolved_workflow_data is None and isinstance(stored_prompt_wf, dict):
|
||||
resolved_workflow_data = stored_prompt_wf
|
||||
|
||||
wf = resolved_workflow_data if isinstance(resolved_workflow_data, dict) else {}
|
||||
incoming_wf = live_workflow_data if isinstance(live_workflow_data, dict) else None
|
||||
output_text = (wf.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 loras_b_toggle else []
|
||||
|
||||
all_preset_loras_a = self._get_all_loras_from_toggle(loras_a_toggle) if loras_a_toggle else []
|
||||
all_preset_loras_b = self._get_all_loras_from_toggle(loras_b_toggle) if loras_b_toggle else []
|
||||
|
||||
wf_loras_a = [
|
||||
(lora["name"], lora.get("model_strength", 1.0), lora.get("clip_strength", 1.0))
|
||||
for lora in wf.get("loras_a", [])
|
||||
if isinstance(lora, dict) and lora.get("name")
|
||||
]
|
||||
wf_loras_b = [
|
||||
(lora["name"], lora.get("model_strength", 1.0), lora.get("clip_strength", 1.0))
|
||||
for lora in wf.get("loras_b", [])
|
||||
if isinstance(lora, dict) and lora.get("name")
|
||||
]
|
||||
|
||||
# WorkflowManager is workflow-data centric: workflow LoRAs are base, preset toggles merge in.
|
||||
merged_stack_a = self._merge_lora_stacks(wf_loras_a, preset_stack_a) if (wf_loras_a or preset_stack_a) else []
|
||||
merged_stack_b = self._merge_lora_stacks(wf_loras_b, preset_stack_b) if (wf_loras_b or preset_stack_b) else []
|
||||
|
||||
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(incoming_wf) if isinstance(incoming_wf, 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 = dict(resolved_workflow_data) if isinstance(resolved_workflow_data, dict) else {}
|
||||
out_workflow_data["positive_prompt"] = output_text
|
||||
out_workflow_data["loras_a"] = [
|
||||
{
|
||||
"name": lora.get("name", ""),
|
||||
"model_strength": lora.get("model_strength", lora.get("strength", 1.0)),
|
||||
"clip_strength": lora.get("clip_strength", lora.get("strength", 1.0)),
|
||||
"active": lora.get("active", True),
|
||||
"available": lora.get("available", True),
|
||||
"found": lora.get("found", lora.get("available", True)),
|
||||
}
|
||||
for lora in loras_a_display
|
||||
if isinstance(lora, dict) and lora.get("name")
|
||||
]
|
||||
out_workflow_data["loras_b"] = [
|
||||
{
|
||||
"name": lora.get("name", ""),
|
||||
"model_strength": lora.get("model_strength", lora.get("strength", 1.0)),
|
||||
"clip_strength": lora.get("clip_strength", lora.get("strength", 1.0)),
|
||||
"active": lora.get("active", True),
|
||||
"available": lora.get("available", True),
|
||||
"found": lora.get("found", lora.get("available", True)),
|
||||
}
|
||||
for lora in loras_b_display
|
||||
if isinstance(lora, dict) and lora.get("name")
|
||||
]
|
||||
out_workflow_data["_source"] = "WorkflowManager"
|
||||
|
||||
return (out_workflow_data,)
|
||||
|
||||
def check_lazy_status(self, category, name, text="", **kwargs):
|
||||
return []
|
||||
@@ -0,0 +1,434 @@
|
||||
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(
|
||||
"[WorkflowModelLoader] 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"[WorkflowModelLoader] 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 _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"[WorkflowModelLoader] 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"[WorkflowModelLoader] 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"[WorkflowModelLoader] 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"[WorkflowModelLoader] 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"[WorkflowModelLoader] 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", "STRING")
|
||||
RETURN_NAMES = ("model", "clip", "vae", "model_name")
|
||||
FUNCTION = "get_model"
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {
|
||||
"workflow_data": ("WORKFLOW_DATA", {
|
||||
"tooltip": "Workflow data containing model name strings to load.",
|
||||
"forceInput": True,
|
||||
}),
|
||||
"model": (["model_a", "model_b"], {
|
||||
"default": "model_a",
|
||||
"tooltip": "Which model slot to load from workflow_data.",
|
||||
}),
|
||||
"weight_dtype": (WEIGHT_DTYPE_OPTIONS, {
|
||||
"default": "default",
|
||||
"tooltip": "Weight precision override for diffusion/UNet models. Ignored for checkpoints.",
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
def get_model(self, workflow_data, model="model_a", weight_dtype="default"):
|
||||
spec = self._normalize_spec(workflow_data)
|
||||
selected_model_slot = model
|
||||
if selected_model_slot not in ("model_a", "model_b"):
|
||||
selected_model_slot = "model_a"
|
||||
|
||||
self._model_key = selected_model_slot
|
||||
self._weight_dtype = weight_dtype
|
||||
loader_type = spec.get("loader_type", "").lower()
|
||||
selected_name = spec.get(selected_model_slot, "")
|
||||
selected_display_name = _short_display_name(selected_name)
|
||||
|
||||
if loader_type == "checkpoint":
|
||||
core_result = self._load_checkpoint_mode(spec)
|
||||
elif loader_type in ("unet", "diffusion"):
|
||||
core_result = self._load_unet_mode(spec)
|
||||
else:
|
||||
raise ValueError(
|
||||
f"[WorkflowModelLoader] Unsupported loader_type: {spec.get('loader_type')}"
|
||||
)
|
||||
|
||||
result = (*core_result, selected_display_name)
|
||||
|
||||
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 '(from checkpoint)', '(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["loader_type"] = (spec.get("loader_type") or "").strip()
|
||||
spec["clip_type"] = (spec.get("clip_type") or "").strip()
|
||||
|
||||
# VAE / CLIP: placeholders like '(from checkpoint)' mean "use what
|
||||
# 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)
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,58 +0,0 @@
|
||||
"""
|
||||
ComfyUI Prompt Apply LoRA - Apply a LORA_STACK to model and clip
|
||||
"""
|
||||
import folder_paths
|
||||
import comfy.sd
|
||||
import comfy.utils
|
||||
|
||||
|
||||
class PromptApplyLora:
|
||||
"""
|
||||
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"[PromptApplyLora] 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,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 WorkflowRenderer 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, WorkflowBuilder, WorkflowRenderer.
|
||||
"""
|
||||
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 found, (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, found) 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, found = fuzzy_match_lora(lora_name, lora_files)
|
||||
if found:
|
||||
return fuzzy_match, True
|
||||
|
||||
# Not found
|
||||
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, found) 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, found = fuzzy_match_lora(lora_name, lora_files)
|
||||
if found:
|
||||
return folder_paths.get_full_path("loras", fuzzy_match), True
|
||||
|
||||
return None, False
|
||||
@@ -200,15 +200,33 @@ _QUANT_PARTS = frozenset({
|
||||
})
|
||||
|
||||
|
||||
def _get_model_identity(name):
|
||||
"""Extract the model's identity parts from a filename, stripping quant info.
|
||||
def _get_model_keywords(name):
|
||||
"""Extract normalised keyword set from a model filename for fuzzy matching.
|
||||
|
||||
Example: 'Qwen3.5-9B-Q4_K_M.gguf' → ('Qwen3', '5', '9B')
|
||||
'mmproj-Qwen3.5-9B-F16.gguf' → ('Qwen3', '5', '9B')
|
||||
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]
|
||||
parts = [p for p in re.split(r"[-._ ]", base) if p]
|
||||
return tuple(p for p in parts if p not in _QUANT_PARTS and p.lower() != "mmproj")
|
||||
# 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):
|
||||
@@ -235,23 +253,31 @@ def get_mmproj_path(model_name):
|
||||
# Mapped but file not found on disk
|
||||
return None
|
||||
|
||||
# --- 2. Heuristic: match by model identity ---
|
||||
model_identity = _get_model_identity(model_name)
|
||||
if not model_identity:
|
||||
# --- 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
|
||||
|
||||
all_dirs = get_all_model_directories()
|
||||
best_match = None
|
||||
best_match_count = 0
|
||||
for models_dir in all_dirs:
|
||||
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_identity = _get_model_identity(f)
|
||||
if mmproj_identity and mmproj_identity == model_identity:
|
||||
return os.path.join(models_dir, f)
|
||||
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)
|
||||
|
||||
return None
|
||||
return best_match
|
||||
|
||||
|
||||
def has_vision_support(model_name):
|
||||
@@ -0,0 +1,96 @@
|
||||
"""
|
||||
Utility functions for WORKFLOW_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_A",
|
||||
"MODEL_B",
|
||||
"CLIP",
|
||||
"VAE",
|
||||
"LATENT",
|
||||
"IMAGE",
|
||||
"MASK",
|
||||
"EXTRA",
|
||||
"POSITIVE",
|
||||
"NEGATIVE",
|
||||
})
|
||||
|
||||
|
||||
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,973 @@
|
||||
"""
|
||||
Shared extraction helpers for ComfyUI Prompt Manager.
|
||||
|
||||
Used by both WorkflowExtractor and WorkflowBuilder / WorkflowRenderer nodes.
|
||||
Handles: sampler params, VAE info, CLIP info, resolution, model resolution,
|
||||
and the full extract_all_from_file() entry point.
|
||||
"""
|
||||
import os
|
||||
import json
|
||||
import folder_paths
|
||||
|
||||
from .workflow_families import get_model_family, get_family_label
|
||||
|
||||
# ─── Constants ────────────────────────────────────────────────────────────────
|
||||
|
||||
MODEL_EXTENSIONS = ['.safetensors', '.ckpt', '.pt', '.pth', '.bin', '.gguf', '.sft']
|
||||
|
||||
# Node types that contain sampler parameters
|
||||
KSAMPLER_TYPES = [
|
||||
'KSampler', 'KSamplerAdvanced', 'KSamplerSelect',
|
||||
'SamplerCustomAdvanced', 'SamplerCustom',
|
||||
'WanMoeKSamplerAdvanced',
|
||||
]
|
||||
|
||||
SCHEDULER_TYPES = ['BasicScheduler', 'Flux2Scheduler', 'SDTurboScheduler', 'KarrasScheduler']
|
||||
GUIDER_TYPES = ['BasicGuider', 'CFGGuider', 'DualCFGGuider']
|
||||
NOISE_TYPES = ['RandomNoise', 'DisableNoise']
|
||||
VAE_LOADER_TYPES = ['VAELoader', 'VAELoaderConsistencyDecoder']
|
||||
CLIP_LOADER_TYPES = ['CLIPLoader', 'DualCLIPLoader', 'TripleCLIPLoader']
|
||||
LATENT_TYPES = ['EmptyLatentImage', 'EmptyFlux2LatentImage', 'EmptySD3LatentImage']
|
||||
VIDEO_LATENT_TYPES = ['WanVideoLatentImage', 'WanImageToVideo', 'EmptyHunyuanLatentVideo']
|
||||
|
||||
CHECKPOINT_TYPES = ('CheckpointLoaderSimple', 'CheckpointLoader', 'CheckpointLoaderNF4')
|
||||
|
||||
# Node types that carry embedded extracted_data.
|
||||
# Keep 'WorkflowGenerator' for backward compat with images generated before rename.
|
||||
# WorkflowBuilder stores authoritative extracted_data for Builder+Renderer graphs.
|
||||
_EMBEDDED_NODE_TYPES = (
|
||||
'WorkflowRenderer',
|
||||
'WorkflowGenerator',
|
||||
'WorkflowBuilder',
|
||||
'PromptExtractor',
|
||||
)
|
||||
|
||||
|
||||
def _get_embedded_extracted_data(workflow_data):
|
||||
"""Return the best ``extracted_data`` dict from a WR/WG or PE node, or *None*.
|
||||
|
||||
Prioritises WorkflowRenderer/WorkflowGenerator over WorkflowBuilder over
|
||||
PromptExtractor, and only returns data that actually contains ``sampler``
|
||||
or ``resolution`` keys.
|
||||
"""
|
||||
if not workflow_data or not isinstance(workflow_data, dict):
|
||||
return None
|
||||
|
||||
best = None
|
||||
best_rank = -1
|
||||
|
||||
for wf_node in workflow_data.get('nodes', []):
|
||||
ntype = wf_node.get('type', '')
|
||||
if ntype not in _EMBEDDED_NODE_TYPES:
|
||||
continue
|
||||
ed = wf_node.get('extracted_data')
|
||||
if not ed or not isinstance(ed, dict):
|
||||
continue
|
||||
has_useful = bool(ed.get('sampler') or ed.get('resolution'))
|
||||
if not has_useful:
|
||||
continue
|
||||
if ntype in ('WorkflowRenderer', 'WorkflowGenerator'):
|
||||
rank = 3
|
||||
elif ntype == 'WorkflowBuilder':
|
||||
rank = 2
|
||||
else:
|
||||
rank = 1
|
||||
|
||||
# Prefer higher-priority source; among same type, first wins.
|
||||
if best is None or rank > best_rank:
|
||||
best = ed
|
||||
best_rank = rank
|
||||
if best_rank == 3:
|
||||
break # WR/WG is highest priority — stop early
|
||||
|
||||
return best
|
||||
|
||||
|
||||
# ─── Sampler extraction ───────────────────────────────────────────────────────
|
||||
|
||||
def extract_sampler_params(prompt_data, workflow_data):
|
||||
"""
|
||||
Extract sampler parameters from KSampler nodes in API or workflow format.
|
||||
Returns a dict with steps_a, steps_b, cfg, seed_a, seed_b, sampler_name, scheduler.
|
||||
"""
|
||||
params = {
|
||||
'steps_a': 20,
|
||||
'steps_b': None, # WAN Video low-pass steps (None = same as steps_a)
|
||||
'cfg': 7.0,
|
||||
'seed_a': 0,
|
||||
'seed_b': None, # WAN Video second-sampler seed (None = use same as seed_a)
|
||||
'sampler_name': 'euler',
|
||||
'scheduler': 'normal',
|
||||
}
|
||||
|
||||
# ── API format ────────────────────────────────────────────────────────────
|
||||
if prompt_data and isinstance(prompt_data, dict):
|
||||
# WAN Video uses two KSamplerAdvanced nodes (high + low pass).
|
||||
# Collect all of them so we can expose both seeds.
|
||||
ksampler_advanced_nodes = []
|
||||
for node_id, node_data in prompt_data.items():
|
||||
if not isinstance(node_data, dict):
|
||||
continue
|
||||
ct = node_data.get('class_type', '')
|
||||
inp = node_data.get('inputs', {})
|
||||
|
||||
if ct == 'KSampler':
|
||||
params['steps_a'] = inp.get('steps', params['steps_a'])
|
||||
params['cfg'] = inp.get('cfg', params['cfg'])
|
||||
seed_val = inp.get('seed', inp.get('noise_seed', params['seed_a']))
|
||||
params['seed_a'] = seed_val if not isinstance(seed_val, list) else params['seed_a']
|
||||
params['sampler_name'] = inp.get('sampler_name', params['sampler_name'])
|
||||
params['scheduler'] = inp.get('scheduler', params['scheduler'])
|
||||
return params # standard KSampler found — done
|
||||
|
||||
if ct == 'KSamplerAdvanced':
|
||||
ksampler_advanced_nodes.append(inp)
|
||||
|
||||
if ct == 'WanMoeKSamplerAdvanced':
|
||||
params['steps_a'] = inp.get('steps', params['steps_a'])
|
||||
params['cfg'] = inp.get('cfg', params['cfg'])
|
||||
seed_val = inp.get('seed', inp.get('noise_seed', params['seed_a']))
|
||||
params['seed_a'] = seed_val if not isinstance(seed_val, list) else params['seed_a']
|
||||
params['sampler_name'] = inp.get('sampler_name', params['sampler_name'])
|
||||
params['scheduler'] = inp.get('scheduler', params['scheduler'])
|
||||
return params
|
||||
|
||||
# Handle KSamplerAdvanced — including WAN Video dual-sampler pattern
|
||||
if ksampler_advanced_nodes:
|
||||
first = ksampler_advanced_nodes[0]
|
||||
params['steps_a'] = first.get('steps', params['steps_a'])
|
||||
params['cfg'] = first.get('cfg', params['cfg'])
|
||||
seed_val = first.get('seed', first.get('noise_seed', params['seed_a']))
|
||||
params['seed_a'] = seed_val if not isinstance(seed_val, list) else params['seed_a']
|
||||
params['sampler_name'] = first.get('sampler_name', params['sampler_name'])
|
||||
params['scheduler'] = first.get('scheduler', params['scheduler'])
|
||||
if len(ksampler_advanced_nodes) >= 2:
|
||||
# Second node = low-pass sampler — expose its seed as seed_b
|
||||
second = ksampler_advanced_nodes[1]
|
||||
seed_b = second.get('seed', second.get('noise_seed', params['seed_a']))
|
||||
params['seed_b'] = seed_b if not isinstance(seed_b, list) else params['seed_a']
|
||||
# Extract steps_b if the second sampler has different steps
|
||||
steps_b_val = second.get('steps')
|
||||
if steps_b_val is not None and not isinstance(steps_b_val, list):
|
||||
params['steps_b'] = int(steps_b_val)
|
||||
return params
|
||||
|
||||
# Second pass for split-node pattern (SamplerCustomAdvanced)
|
||||
for node_id, node_data in prompt_data.items():
|
||||
if not isinstance(node_data, dict):
|
||||
continue
|
||||
ct = node_data.get('class_type', '')
|
||||
inp = node_data.get('inputs', {})
|
||||
|
||||
if ct == 'KSamplerSelect':
|
||||
params['sampler_name'] = inp.get('sampler_name', params['sampler_name'])
|
||||
elif ct in ('BasicScheduler', 'Flux2Scheduler'):
|
||||
params['steps_a'] = inp.get('steps', params['steps_a'])
|
||||
params['scheduler'] = inp.get('scheduler', params['scheduler'])
|
||||
elif ct == 'CFGGuider':
|
||||
params['cfg'] = inp.get('cfg', params['cfg'])
|
||||
elif ct == 'RandomNoise':
|
||||
params['seed_a'] = inp.get('noise_seed', params['seed_a'])
|
||||
|
||||
# ── Workflow (node graph) format fallback ─────────────────────────────────
|
||||
if workflow_data and isinstance(workflow_data, dict):
|
||||
from .workflow_node_utils import build_node_map
|
||||
node_map = build_node_map(workflow_data)
|
||||
for node_id, node in node_map.items():
|
||||
ntype = node.get('type', '')
|
||||
widgets = node.get('widgets_values', [])
|
||||
|
||||
if ntype == 'KSampler' and len(widgets) >= 6:
|
||||
try:
|
||||
params['seed_a'] = int(widgets[0]) if widgets[0] is not None else 0
|
||||
params['steps_a'] = int(widgets[2]) if widgets[2] is not None else 20
|
||||
params['cfg'] = float(widgets[3]) if widgets[3] is not None else 7.0
|
||||
params['sampler_name'] = str(widgets[4]) if widgets[4] else 'euler'
|
||||
params['scheduler'] = str(widgets[5]) if widgets[5] else 'normal'
|
||||
return params
|
||||
except (ValueError, IndexError):
|
||||
pass
|
||||
|
||||
elif ntype == 'KSamplerSelect' and widgets:
|
||||
params['sampler_name'] = str(widgets[0]) if widgets[0] else params['sampler_name']
|
||||
elif ntype in ('BasicScheduler', 'Flux2Scheduler') and len(widgets) >= 2:
|
||||
try:
|
||||
params['scheduler'] = str(widgets[0]) if widgets[0] else params['scheduler']
|
||||
params['steps_a'] = int(widgets[1]) if widgets[1] is not None else params['steps_a']
|
||||
except (ValueError, IndexError):
|
||||
pass
|
||||
elif ntype == 'CFGGuider' and widgets:
|
||||
try:
|
||||
params['cfg'] = float(widgets[0]) if widgets[0] is not None else params['cfg']
|
||||
except (ValueError, IndexError):
|
||||
pass
|
||||
elif ntype == 'RandomNoise' and widgets:
|
||||
try:
|
||||
params['seed_a'] = int(widgets[0]) if widgets[0] is not None else 0
|
||||
except (ValueError, IndexError):
|
||||
pass
|
||||
|
||||
# ── Fallback: embedded extracted_data from WG / PE nodes ──────────────
|
||||
ed = _get_embedded_extracted_data(workflow_data)
|
||||
if ed:
|
||||
s = ed.get('sampler')
|
||||
if s and isinstance(s, dict) and s.get('sampler_name'):
|
||||
params['steps_a'] = s.get('steps_a', s.get('steps', params['steps_a']))
|
||||
params['steps_b'] = s.get('steps_b', params['steps_b'])
|
||||
params['cfg'] = s.get('cfg', params['cfg'])
|
||||
params['seed_a'] = s.get('seed_a', s.get('seed', params['seed_a']))
|
||||
params['sampler_name'] = s.get('sampler_name', params['sampler_name'])
|
||||
params['scheduler'] = s.get('scheduler', params['scheduler'])
|
||||
|
||||
return params
|
||||
|
||||
|
||||
# ─── VAE extraction ───────────────────────────────────────────────────────────
|
||||
|
||||
def extract_vae_info(prompt_data, workflow_data):
|
||||
"""Extract VAE loader information from the workflow. Returns {'name', 'source'}."""
|
||||
vae_info = {'name': '', 'source': 'unknown'}
|
||||
|
||||
if prompt_data and isinstance(prompt_data, dict):
|
||||
for node_id, node_data in prompt_data.items():
|
||||
if not isinstance(node_data, dict):
|
||||
continue
|
||||
ct = node_data.get('class_type', '')
|
||||
inp = node_data.get('inputs', {})
|
||||
|
||||
if ct in VAE_LOADER_TYPES:
|
||||
vae_info['name'] = inp.get('vae_name', '')
|
||||
vae_info['source'] = 'separate'
|
||||
return vae_info
|
||||
|
||||
if ct in CHECKPOINT_TYPES and inp.get('ckpt_name'):
|
||||
if not vae_info['name']:
|
||||
vae_info['name'] = '(from checkpoint)'
|
||||
vae_info['source'] = 'checkpoint'
|
||||
# Don't return — a separate VAE loader later overrides this
|
||||
|
||||
if not vae_info['name'] and workflow_data and isinstance(workflow_data, dict):
|
||||
from .workflow_node_utils import build_node_map
|
||||
node_map = build_node_map(workflow_data)
|
||||
for node_id, node in node_map.items():
|
||||
ntype = node.get('type', '')
|
||||
widgets = node.get('widgets_values', [])
|
||||
|
||||
if ntype in VAE_LOADER_TYPES and widgets:
|
||||
vae_info['name'] = str(widgets[0]) if widgets[0] else ''
|
||||
vae_info['source'] = 'separate'
|
||||
return vae_info
|
||||
|
||||
if ntype in CHECKPOINT_TYPES and widgets and not vae_info['name']:
|
||||
vae_info['name'] = '(from checkpoint)'
|
||||
vae_info['source'] = 'checkpoint'
|
||||
|
||||
# ── Fallback: embedded extracted_data from WG / PE nodes ──────────────
|
||||
if not vae_info['name']:
|
||||
ed = _get_embedded_extracted_data(workflow_data)
|
||||
if ed:
|
||||
vae = ed.get('vae', '')
|
||||
if vae and isinstance(vae, str) and vae not in ('', '\u2014'):
|
||||
vae_info['name'] = vae
|
||||
vae_info['source'] = 'embedded'
|
||||
|
||||
return vae_info
|
||||
|
||||
|
||||
# ─── CLIP extraction ──────────────────────────────────────────────────────────
|
||||
|
||||
def extract_clip_info(prompt_data, workflow_data):
|
||||
"""Extract CLIP loader information. Returns {'names', 'type', 'source'}."""
|
||||
clip_info = {'names': [], 'type': '', 'source': 'unknown'}
|
||||
|
||||
if prompt_data and isinstance(prompt_data, dict):
|
||||
for node_id, node_data in prompt_data.items():
|
||||
if not isinstance(node_data, dict):
|
||||
continue
|
||||
ct = node_data.get('class_type', '')
|
||||
inp = node_data.get('inputs', {})
|
||||
|
||||
if ct == 'CLIPLoader':
|
||||
clip_info['names'] = [inp.get('clip_name', '')]
|
||||
clip_info['type'] = inp.get('type', '')
|
||||
clip_info['source'] = 'separate'
|
||||
return clip_info
|
||||
|
||||
if ct == 'DualCLIPLoader':
|
||||
clip_info['names'] = [inp.get('clip_name1', ''), inp.get('clip_name2', '')]
|
||||
clip_info['type'] = inp.get('type', '')
|
||||
clip_info['source'] = 'separate'
|
||||
return clip_info
|
||||
|
||||
if ct == 'TripleCLIPLoader':
|
||||
clip_info['names'] = [
|
||||
inp.get('clip_name1', ''),
|
||||
inp.get('clip_name2', ''),
|
||||
inp.get('clip_name3', ''),
|
||||
]
|
||||
clip_info['source'] = 'separate'
|
||||
return clip_info
|
||||
|
||||
if ct in CHECKPOINT_TYPES and inp.get('ckpt_name') and not clip_info['names']:
|
||||
clip_info['names'] = ['(from checkpoint)']
|
||||
clip_info['source'] = 'checkpoint'
|
||||
|
||||
if not clip_info['names'] and workflow_data and isinstance(workflow_data, dict):
|
||||
from .workflow_node_utils import build_node_map
|
||||
node_map = build_node_map(workflow_data)
|
||||
for node_id, node in node_map.items():
|
||||
ntype = node.get('type', '')
|
||||
widgets = node.get('widgets_values', [])
|
||||
|
||||
if ntype == 'CLIPLoader' and widgets:
|
||||
clip_info['names'] = [str(widgets[0]) if widgets[0] else '']
|
||||
clip_info['type'] = str(widgets[1]) if len(widgets) > 1 and widgets[1] else ''
|
||||
clip_info['source'] = 'separate'
|
||||
return clip_info
|
||||
|
||||
if ntype == 'DualCLIPLoader' and len(widgets) >= 2:
|
||||
clip_info['names'] = [
|
||||
str(widgets[0]) if widgets[0] else '',
|
||||
str(widgets[1]) if widgets[1] else '',
|
||||
]
|
||||
clip_info['type'] = str(widgets[2]) if len(widgets) > 2 and widgets[2] else ''
|
||||
clip_info['source'] = 'separate'
|
||||
return clip_info
|
||||
|
||||
if ntype in CHECKPOINT_TYPES and widgets and not clip_info['names']:
|
||||
clip_info['names'] = ['(from checkpoint)']
|
||||
clip_info['source'] = 'checkpoint'
|
||||
|
||||
# ── Fallback: embedded extracted_data from WG / PE nodes ──────────────
|
||||
if not clip_info['names']:
|
||||
ed = _get_embedded_extracted_data(workflow_data)
|
||||
if ed:
|
||||
clip = ed.get('clip', [])
|
||||
names = clip if isinstance(clip, list) else ([clip] if clip else [])
|
||||
if any(n for n in names):
|
||||
clip_info['names'] = names
|
||||
clip_info['source'] = 'embedded'
|
||||
|
||||
return clip_info
|
||||
|
||||
|
||||
# ─── Resolution extraction ────────────────────────────────────────────────────
|
||||
|
||||
def extract_resolution(prompt_data, workflow_data, return_source=False):
|
||||
"""Extract image/video resolution from latent nodes.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
return_source : bool
|
||||
If True, returns ``(resolution_dict, source)`` where source is one of:
|
||||
``prompt_graph``, ``workflow_graph``, ``embedded``, ``default``.
|
||||
"""
|
||||
def _ret(res, source):
|
||||
return (res, source) if return_source else res
|
||||
|
||||
resolution = {'width': 512, 'height': 512, 'batch_size': 1, 'length': None}
|
||||
|
||||
if prompt_data and isinstance(prompt_data, dict):
|
||||
for node_id, node_data in prompt_data.items():
|
||||
if not isinstance(node_data, dict):
|
||||
continue
|
||||
ct = node_data.get('class_type', '')
|
||||
inp = node_data.get('inputs', {})
|
||||
|
||||
if ct in LATENT_TYPES + VIDEO_LATENT_TYPES:
|
||||
def _scalar(val, fallback, field_name=None):
|
||||
"""Resolve node-ref lists to scalar by looking up the
|
||||
referenced node in prompt_data, or return fallback."""
|
||||
if isinstance(val, list):
|
||||
# Node reference: [node_id, output_index]
|
||||
ref_id = str(val[0])
|
||||
ref_node = prompt_data.get(ref_id, {})
|
||||
ref_inp = ref_node.get('inputs', {})
|
||||
# PrimitiveInt / ImageResizeKJv2 / similar
|
||||
if 'value' in ref_inp:
|
||||
return int(ref_inp['value'])
|
||||
# ImageResizeKJv2: width is output slot 1, height slot 2
|
||||
if field_name == 'width' and 'width' in ref_inp:
|
||||
v = ref_inp['width']
|
||||
return int(v) if not isinstance(v, list) else fallback
|
||||
if field_name == 'height' and 'height' in ref_inp:
|
||||
v = ref_inp['height']
|
||||
return int(v) if not isinstance(v, list) else fallback
|
||||
return fallback
|
||||
try:
|
||||
return int(val)
|
||||
except (TypeError, ValueError):
|
||||
return fallback
|
||||
|
||||
w = inp.get('width', resolution['width'])
|
||||
h = inp.get('height', resolution['height'])
|
||||
b = inp.get('batch_size', resolution['batch_size'])
|
||||
resolution['width'] = _scalar(w, resolution['width'], 'width')
|
||||
resolution['height'] = _scalar(h, resolution['height'], 'height')
|
||||
if ct in VIDEO_LATENT_TYPES:
|
||||
# For video latent nodes (WanImageToVideo, etc.), batch_size
|
||||
# is the frame count — store it as length, keep batch_size=1.
|
||||
b_val = _scalar(b, resolution['batch_size'])
|
||||
resolution['batch_size'] = 1
|
||||
if 'length' in inp:
|
||||
l = inp.get('length')
|
||||
resolution['length'] = _scalar(l, None) if l is not None else None
|
||||
elif b_val > 1:
|
||||
# batch_size field holds frame count
|
||||
resolution['length'] = b_val
|
||||
else:
|
||||
b_val = _scalar(b, resolution['batch_size'])
|
||||
resolution['batch_size'] = b_val
|
||||
if 'length' in inp:
|
||||
l = inp.get('length')
|
||||
resolution['length'] = _scalar(l, None) if l is not None else None
|
||||
return _ret(resolution, 'prompt_graph')
|
||||
|
||||
if workflow_data and isinstance(workflow_data, dict):
|
||||
from .workflow_node_utils import build_node_map
|
||||
node_map = build_node_map(workflow_data)
|
||||
for node_id, node in node_map.items():
|
||||
ntype = node.get('type', '')
|
||||
widgets = node.get('widgets_values', [])
|
||||
|
||||
if ntype in LATENT_TYPES and len(widgets) >= 3:
|
||||
try:
|
||||
resolution['width'] = int(widgets[0]) if widgets[0] else 512
|
||||
resolution['height'] = int(widgets[1]) if widgets[1] else 512
|
||||
resolution['batch_size'] = int(widgets[2]) if widgets[2] else 1
|
||||
except (ValueError, IndexError):
|
||||
pass
|
||||
return _ret(resolution, 'workflow_graph')
|
||||
|
||||
if ntype in VIDEO_LATENT_TYPES and len(widgets) >= 3:
|
||||
try:
|
||||
resolution['width'] = int(widgets[0]) if widgets[0] else 512
|
||||
resolution['height'] = int(widgets[1]) if widgets[1] else 512
|
||||
if len(widgets) > 2:
|
||||
resolution['length'] = int(widgets[2]) if widgets[2] else 81
|
||||
resolution['batch_size'] = int(widgets[3]) if len(widgets) > 3 and widgets[3] else 1
|
||||
except (ValueError, IndexError):
|
||||
pass
|
||||
return _ret(resolution, 'workflow_graph')
|
||||
|
||||
# ── Fallback: embedded extracted_data from WG / PE nodes ──────────────
|
||||
ed = _get_embedded_extracted_data(workflow_data)
|
||||
if ed:
|
||||
r = ed.get('resolution')
|
||||
if r and isinstance(r, dict) and r.get('width'):
|
||||
resolution['width'] = r.get('width', resolution['width'])
|
||||
resolution['height'] = r.get('height', resolution['height'])
|
||||
resolution['batch_size'] = r.get('batch_size', resolution['batch_size'])
|
||||
if r.get('length') is not None:
|
||||
resolution['length'] = r['length']
|
||||
return _ret(resolution, 'embedded')
|
||||
|
||||
return _ret(resolution, 'default')
|
||||
|
||||
|
||||
# ─── Model resolution ─────────────────────────────────────────────────────────
|
||||
|
||||
def resolve_model_name(model_name):
|
||||
"""Resolve model name to (relative_path, folder_name) or (None, None)."""
|
||||
if not model_name:
|
||||
return None, None
|
||||
|
||||
model_name_clean = model_name.strip().replace('\\', '/')
|
||||
name_base = os.path.basename(model_name_clean).lower()
|
||||
name_no_ext = name_base
|
||||
for ext in MODEL_EXTENSIONS:
|
||||
if name_no_ext.endswith(ext):
|
||||
name_no_ext = name_no_ext[:-len(ext)]
|
||||
break
|
||||
|
||||
for folder_name in ['checkpoints', 'diffusion_models', 'unet', 'unet_gguf']:
|
||||
try:
|
||||
file_list = folder_paths.get_filename_list(folder_name)
|
||||
except Exception:
|
||||
continue
|
||||
for f in file_list:
|
||||
f_normalized = f.replace('\\', '/')
|
||||
if f_normalized == model_name_clean:
|
||||
return f, folder_name
|
||||
f_base = os.path.basename(f_normalized).lower()
|
||||
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_base == name_base or f_no_ext == name_no_ext:
|
||||
return f, folder_name
|
||||
|
||||
return None, None
|
||||
|
||||
|
||||
def resolve_vae_name(vae_name):
|
||||
"""Resolve VAE name to full path, or None if not found / from checkpoint."""
|
||||
if not vae_name or vae_name.startswith('('):
|
||||
return None
|
||||
try:
|
||||
vae_list = folder_paths.get_filename_list("vae")
|
||||
name_lower = os.path.basename(vae_name).lower()
|
||||
for v in vae_list:
|
||||
if v == vae_name or os.path.basename(v).lower() == name_lower:
|
||||
return folder_paths.get_full_path("vae", v)
|
||||
except Exception:
|
||||
pass
|
||||
return None
|
||||
|
||||
|
||||
def resolve_clip_names(clip_names, clip_type=''):
|
||||
"""
|
||||
Resolve a list of CLIP names to full paths.
|
||||
Returns list of paths (None for any not found).
|
||||
"""
|
||||
paths = []
|
||||
for name in clip_names:
|
||||
if not name or name.startswith('('):
|
||||
paths.append(None)
|
||||
continue
|
||||
found = None
|
||||
name_lower = os.path.basename(name).lower()
|
||||
for folder in ['text_encoders', 'clip']:
|
||||
try:
|
||||
for f in folder_paths.get_filename_list(folder):
|
||||
if f == name or os.path.basename(f).lower() == name_lower:
|
||||
found = folder_paths.get_full_path(folder, f)
|
||||
break
|
||||
if found:
|
||||
break
|
||||
except Exception:
|
||||
continue
|
||||
paths.append(found)
|
||||
return paths
|
||||
|
||||
|
||||
# ─── Embedded generation data (WG / PE) ──────────────────────────────────────
|
||||
|
||||
def _find_embedded_generation_data(workflow_data, prompt_data):
|
||||
"""
|
||||
Look for sampler / resolution / model data embedded by WorkflowRenderer
|
||||
(or legacy WorkflowGenerator) or PromptExtractor. Checks (in priority order):
|
||||
|
||||
1. WR/WG/WB node ``extracted_data`` (full dict with sampler + resolution)
|
||||
2. WR/WG/WB node ``widgets_values`` containing the ``override_data`` JSON
|
||||
3. WR/WG/WB ``override_data`` in the prompt API inputs
|
||||
4. PE node ``extracted_data``
|
||||
|
||||
Returns a dict with ``sampler``, ``resolution``, ``vae``, ``clip``,
|
||||
``model_a``, ``model_b`` keys — or *None* if nothing was found.
|
||||
"""
|
||||
out = {}
|
||||
|
||||
# --- Helper: merge extracted_data dict into *out* ---
|
||||
def _apply_extracted(ed, source_label):
|
||||
s = ed.get('sampler')
|
||||
if s and isinstance(s, dict) and s.get('sampler_name'):
|
||||
out['sampler'] = {
|
||||
'steps_a': s.get('steps_a', s.get('steps', 20)),
|
||||
'steps_b': s.get('steps_b'),
|
||||
'cfg': s.get('cfg', 7.0),
|
||||
'seed_a': s.get('seed_a', s.get('seed', 0)),
|
||||
'seed_b': s.get('seed_b'),
|
||||
'sampler_name': s.get('sampler_name', 'euler'),
|
||||
'scheduler': s.get('scheduler', 'normal'),
|
||||
}
|
||||
r = ed.get('resolution')
|
||||
if r and isinstance(r, dict) and r.get('width'):
|
||||
out['resolution'] = {
|
||||
'width': r.get('width', 512),
|
||||
'height': r.get('height', 512),
|
||||
'batch_size': r.get('batch_size', 1),
|
||||
'length': r.get('length'),
|
||||
}
|
||||
vae = ed.get('vae', '')
|
||||
if vae and isinstance(vae, str) and vae not in ('', '\u2014'):
|
||||
out['vae'] = {'name': vae, 'source': source_label}
|
||||
clip = ed.get('clip', [])
|
||||
if clip:
|
||||
names = clip if isinstance(clip, list) else [clip]
|
||||
if any(n for n in names):
|
||||
out['clip'] = {'names': names, 'type': '', 'source': source_label}
|
||||
if ed.get('model_a'):
|
||||
out.setdefault('model_a', ed['model_a'])
|
||||
if ed.get('model_b'):
|
||||
out.setdefault('model_b', ed['model_b'])
|
||||
|
||||
# --- Helper: parse override_data JSON (flat keys) ---
|
||||
def _apply_override_json(ov_str, source_label):
|
||||
try:
|
||||
ov = json.loads(ov_str) if ov_str else {}
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
return
|
||||
if not isinstance(ov, dict):
|
||||
return
|
||||
if ov.get('width') or ov.get('steps_a') or ov.get('steps'):
|
||||
if 'sampler' not in out and ov.get('sampler_name'):
|
||||
out['sampler'] = {
|
||||
'steps_a': ov.get('steps_a', ov.get('steps', 20)),
|
||||
'steps_b': ov.get('steps_b'),
|
||||
'cfg': ov.get('cfg', 7.0),
|
||||
'seed_a': ov.get('seed_a', ov.get('seed', 0)),
|
||||
'seed_b': ov.get('seed_b'),
|
||||
'sampler_name': ov.get('sampler_name', 'euler'),
|
||||
'scheduler': ov.get('scheduler', 'normal'),
|
||||
}
|
||||
if 'resolution' not in out and ov.get('width'):
|
||||
out['resolution'] = {
|
||||
'width': ov.get('width', 512),
|
||||
'height': ov.get('height', 512),
|
||||
'batch_size': ov.get('batch_size', 1),
|
||||
'length': ov.get('length'),
|
||||
}
|
||||
if ov.get('model_a'):
|
||||
out.setdefault('model_a', ov['model_a'])
|
||||
|
||||
# --- 1. Workflow nodes (extracted_data + widgets_values) ---
|
||||
if workflow_data and isinstance(workflow_data, dict):
|
||||
for wf_node in workflow_data.get('nodes', []):
|
||||
ntype = wf_node.get('type', '')
|
||||
if ntype in ('WorkflowRenderer', 'WorkflowGenerator', 'WorkflowBuilder'):
|
||||
# Priority 1: extracted_data
|
||||
ed = wf_node.get('extracted_data')
|
||||
if ed and isinstance(ed, dict):
|
||||
_apply_extracted(ed, ntype)
|
||||
# Priority 2: override_data in widgets_values
|
||||
if 'sampler' not in out or 'resolution' not in out:
|
||||
for v in (wf_node.get('widgets_values') or []):
|
||||
if isinstance(v, str) and len(v) > 5 and v.strip().startswith('{'):
|
||||
_apply_override_json(v, ntype)
|
||||
if 'sampler' in out and 'resolution' in out:
|
||||
break
|
||||
if 'sampler' in out or 'resolution' in out:
|
||||
break # WR/WG/WB found — done
|
||||
|
||||
# Priority 4: PromptExtractor extracted_data (only if WG wasn't found)
|
||||
if 'sampler' not in out and 'resolution' not in out:
|
||||
for wf_node in workflow_data.get('nodes', []):
|
||||
if wf_node.get('type') == 'PromptExtractor':
|
||||
ed = wf_node.get('extracted_data')
|
||||
if ed and isinstance(ed, dict):
|
||||
_apply_extracted(ed, 'PromptExtractor')
|
||||
if 'sampler' in out or 'resolution' in out:
|
||||
break
|
||||
|
||||
# --- 3. Prompt API (WR/WG override_data in inputs) ---
|
||||
if ('sampler' not in out or 'resolution' not in out) and prompt_data and isinstance(prompt_data, dict):
|
||||
for node_id, node_data in prompt_data.items():
|
||||
if not isinstance(node_data, dict):
|
||||
continue
|
||||
if node_data.get('class_type') in ('WorkflowRenderer', 'WorkflowGenerator', 'WorkflowBuilder'):
|
||||
inp = node_data.get('inputs', {})
|
||||
_apply_override_json(inp.get('override_data', ''), node_data['class_type'])
|
||||
break
|
||||
|
||||
return out if out else None
|
||||
|
||||
|
||||
# ─── Full extraction ──────────────────────────────────────────────────────────
|
||||
|
||||
def extract_all_from_file(file_path, source_folder='input'):
|
||||
"""
|
||||
Extract ALL generation parameters from a file.
|
||||
|
||||
Returns a dict with:
|
||||
positive_prompt, negative_prompt,
|
||||
loras_a, loras_b,
|
||||
model_a, model_b,
|
||||
vae {'name', 'source'},
|
||||
clip {'names', 'type', 'source'},
|
||||
sampler {'steps_a', 'steps_b', 'cfg', 'seed_a', 'seed_b', 'sampler_name', 'scheduler'},
|
||||
resolution {'width', 'height', 'batch_size', 'length'},
|
||||
is_video (bool)
|
||||
"""
|
||||
# Import extraction functions from prompt_extractor (lives in nodes/).
|
||||
# Late import to avoid circular deps at module load time.
|
||||
# Relative import works because py/ and nodes/ are siblings in the same package.
|
||||
from ..nodes.prompt_extractor import (
|
||||
parse_workflow_for_prompts,
|
||||
extract_metadata_from_png,
|
||||
extract_metadata_from_jpeg,
|
||||
extract_metadata_from_json,
|
||||
extract_metadata_from_video,
|
||||
)
|
||||
from .lora_utils import resolve_lora_path
|
||||
|
||||
result = {
|
||||
'positive_prompt': '',
|
||||
'negative_prompt': '',
|
||||
'loras_a': [],
|
||||
'loras_b': [],
|
||||
'model_a': '',
|
||||
'model_b': '',
|
||||
'vae': {'name': '', 'source': 'unknown'},
|
||||
'clip': {'names': [], 'type': '', 'source': 'unknown'},
|
||||
'sampler': {
|
||||
'steps_a': 20, 'steps_b': None, 'cfg': 7.0, 'seed_a': 0, 'seed_b': None,
|
||||
'sampler_name': 'euler', 'scheduler': 'normal',
|
||||
},
|
||||
'resolution': {'width': 512, 'height': 512, 'batch_size': 1, 'length': None},
|
||||
'is_video': False,
|
||||
}
|
||||
|
||||
ext = os.path.splitext(file_path)[1].lower()
|
||||
prompt_data = None
|
||||
workflow_data = None
|
||||
|
||||
if ext == '.png':
|
||||
prompt_data, workflow_data = extract_metadata_from_png(file_path)
|
||||
elif ext in ('.jpg', '.jpeg', '.webp'):
|
||||
prompt_data, workflow_data = extract_metadata_from_jpeg(file_path)
|
||||
elif ext == '.json':
|
||||
prompt_data, workflow_data = extract_metadata_from_json(file_path)
|
||||
elif ext in ('.mp4', '.webm', '.mov', '.avi'):
|
||||
prompt_data, workflow_data = extract_metadata_from_video(file_path)
|
||||
result['is_video'] = True
|
||||
|
||||
if not prompt_data and not workflow_data:
|
||||
return result
|
||||
|
||||
extracted = parse_workflow_for_prompts(prompt_data, workflow_data)
|
||||
result['positive_prompt'] = extracted.get('positive_prompt', '')
|
||||
result['negative_prompt'] = extracted.get('negative_prompt', '')
|
||||
result['loras_a'] = extracted.get('loras_a', [])
|
||||
result['loras_b'] = extracted.get('loras_b', [])
|
||||
|
||||
models_a = extracted.get('models_a', [])
|
||||
models_b = extracted.get('models_b', [])
|
||||
result['model_a'] = os.path.basename(models_a[0].replace('\\', '/')) if models_a else ''
|
||||
result['model_b'] = os.path.basename(models_b[0].replace('\\', '/')) if models_b else ''
|
||||
|
||||
result['sampler'] = extract_sampler_params(prompt_data, workflow_data)
|
||||
result['vae'] = extract_vae_info(prompt_data, workflow_data)
|
||||
result['clip'] = extract_clip_info(prompt_data, workflow_data)
|
||||
result['resolution'] = extract_resolution(prompt_data, workflow_data)
|
||||
|
||||
# ── A1111 / Forge override ────────────────────────────────────────────
|
||||
# When prompt_data is a parsed A1111 dict (has 'prompt' + 'loras' keys)
|
||||
# the ComfyUI extraction functions won't find anything. Apply the
|
||||
# values that parse_a1111_parameters() already extracted.
|
||||
if isinstance(prompt_data, dict) and 'prompt' in prompt_data and 'loras' in prompt_data:
|
||||
_s = result['sampler']
|
||||
if prompt_data.get('sampler_name'):
|
||||
_s['sampler_name'] = prompt_data['sampler_name']
|
||||
if prompt_data.get('scheduler'):
|
||||
_s['scheduler'] = prompt_data['scheduler']
|
||||
if prompt_data.get('steps'):
|
||||
_s['steps_a'] = prompt_data['steps']
|
||||
if prompt_data.get('cfg'):
|
||||
_s['cfg'] = prompt_data['cfg']
|
||||
if prompt_data.get('seed'):
|
||||
_s['seed_a'] = prompt_data['seed']
|
||||
_r = result['resolution']
|
||||
if prompt_data.get('width') and prompt_data.get('height'):
|
||||
_r['width'] = prompt_data['width']
|
||||
_r['height'] = prompt_data['height']
|
||||
|
||||
# ── Embedded data override (WorkflowRenderer / PromptExtractor) ──────
|
||||
# When a WorkflowRenderer generated the image there are no standalone
|
||||
# KSampler / EmptyLatentImage nodes. Look for authoritative values in:
|
||||
# 1. extracted_data on the WG or PE node
|
||||
# 2. widgets_values override_data JSON on the WG node
|
||||
# Also check prompt API for WG override_data.
|
||||
_embedded = _find_embedded_generation_data(workflow_data, prompt_data)
|
||||
if _embedded:
|
||||
for key in ('sampler', 'resolution'):
|
||||
if key in _embedded and isinstance(_embedded[key], dict):
|
||||
result[key] = _embedded[key]
|
||||
if _embedded.get('vae'):
|
||||
result['vae'] = _embedded['vae']
|
||||
if _embedded.get('clip'):
|
||||
result['clip'] = _embedded['clip']
|
||||
if not result['model_a'] and _embedded.get('model_a'):
|
||||
result['model_a'] = _embedded['model_a']
|
||||
if not result['model_b'] and _embedded.get('model_b'):
|
||||
result['model_b'] = _embedded['model_b']
|
||||
|
||||
if result['resolution']['length'] is not None:
|
||||
result['is_video'] = True
|
||||
|
||||
return result
|
||||
|
||||
|
||||
def enrich_with_availability(result):
|
||||
"""
|
||||
Add availability flags (lora_availability, model_a_found, etc.)
|
||||
to an extract_all_from_file() result dict in-place.
|
||||
Returns the same dict.
|
||||
"""
|
||||
from .lora_utils import resolve_lora_path
|
||||
|
||||
# LoRA availability
|
||||
lora_availability = {}
|
||||
for loras in [result['loras_a'], result['loras_b']]:
|
||||
for lora in loras:
|
||||
name = lora.get('name', '')
|
||||
if name and name not in lora_availability:
|
||||
_, found = resolve_lora_path(name)
|
||||
lora_availability[name] = found
|
||||
result['lora_availability'] = lora_availability
|
||||
|
||||
# Model A / B availability
|
||||
for key in ['model_a', 'model_b']:
|
||||
model_name = result[key]
|
||||
if model_name:
|
||||
resolved, folder = resolve_model_name(model_name)
|
||||
result[f'{key}_found'] = resolved is not None
|
||||
result[f'{key}_resolved'] = resolved
|
||||
else:
|
||||
result[f'{key}_found'] = True
|
||||
result[f'{key}_resolved'] = None
|
||||
|
||||
# Model family detection (use resolved path — has folder prefix)
|
||||
ref_path = result.get('model_a_resolved') or result.get('model_a', '')
|
||||
family = get_model_family(ref_path)
|
||||
result['model_family'] = family
|
||||
result['model_family_label'] = get_family_label(family)
|
||||
|
||||
# VAE availability
|
||||
vae_name = result['vae'].get('name', '')
|
||||
if vae_name and not vae_name.startswith('('):
|
||||
result['vae_found'] = resolve_vae_name(vae_name) is not None
|
||||
else:
|
||||
result['vae_found'] = True
|
||||
|
||||
# CLIP availability
|
||||
clip_found = []
|
||||
for name in result['clip'].get('names', []):
|
||||
if name and not name.startswith('('):
|
||||
paths = resolve_clip_names([name])
|
||||
clip_found.append(paths[0] is not None)
|
||||
else:
|
||||
clip_found.append(True)
|
||||
result['clip_found'] = clip_found
|
||||
|
||||
return result
|
||||
|
||||
|
||||
def _build_sampler_dict(sampler, family):
|
||||
"""Return sampler dict with steps_a/steps_b for all families."""
|
||||
import math as _math
|
||||
d = {**sampler}
|
||||
# Normalize: if only a plain 'seed' key exists, map it to seed_a
|
||||
if 'seed' in d:
|
||||
d.setdefault('seed_a', d.pop('seed'))
|
||||
d.setdefault('seed_a', 0)
|
||||
d.setdefault('seed_b', sampler.get('seed_b'))
|
||||
# Normalize legacy 'steps' key → steps_a
|
||||
if 'steps' in d and 'steps_a' not in d:
|
||||
d['steps_a'] = d.pop('steps')
|
||||
elif 'steps' in d:
|
||||
d.pop('steps')
|
||||
d.setdefault('steps_a', 20)
|
||||
if family in ('wan_video_i2v', 'wan_video_t2v'):
|
||||
# For WAN dual-sampler: if steps_b not set, split steps_a evenly
|
||||
if d.get('steps_b') is None:
|
||||
total = d['steps_a']
|
||||
d['steps_a'] = _math.ceil(total / 2)
|
||||
d['steps_b'] = total - d['steps_a']
|
||||
# Remove legacy keys
|
||||
d.pop('steps_high', None)
|
||||
d.pop('steps_low', None)
|
||||
return d
|
||||
|
||||
|
||||
def build_simplified_workflow_data(extracted, overrides=None, sampler_params=None):
|
||||
"""
|
||||
Build the shared workflow_data dict that both WorkflowBuilder and PromptExtractor output.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
extracted : dict — result of extract_all_from_file() or an equivalent dict with the same keys
|
||||
overrides : dict — optional JS-side override values (model_a, positive_prompt, …)
|
||||
sampler_params : dict — optional sampler values (already-merged steps/cfg/seed/…)
|
||||
|
||||
Returns a serialisable dict (same schema for both nodes).
|
||||
"""
|
||||
if overrides is None:
|
||||
overrides = {}
|
||||
sampler = sampler_params if sampler_params is not None else extracted.get('sampler', {
|
||||
'steps_a': 20, 'steps_b': None, 'cfg': 7.0, 'seed_a': 0, 'seed_b': None,
|
||||
'sampler_name': 'euler', 'scheduler': 'normal',
|
||||
})
|
||||
|
||||
family = extracted.get('model_family', '')
|
||||
|
||||
# If family is unknown, infer from clip type — each family requires a
|
||||
# specific CLIPLoader type, so this is a reliable signal.
|
||||
clip_info = extracted.get('clip', {})
|
||||
if not family:
|
||||
_clip_type = clip_info.get('type', '').lower()
|
||||
_clip_src = clip_info.get('source', '')
|
||||
if _clip_src == 'checkpoint':
|
||||
family = 'sdxl'
|
||||
elif 'flux2' in _clip_type:
|
||||
family = 'flux2'
|
||||
elif 'flux' in _clip_type:
|
||||
family = 'flux1'
|
||||
elif 'sd3' in _clip_type:
|
||||
family = 'sd3'
|
||||
elif 'wan' in _clip_type:
|
||||
family = 'wan_video_t2v'
|
||||
elif 'qwen_image' in _clip_type:
|
||||
family = 'qwen_image'
|
||||
elif 'lumina2' in _clip_type:
|
||||
family = 'zimage'
|
||||
|
||||
# Determine loader_type: family spec is authoritative when available.
|
||||
# The clip source heuristic ('checkpoint' vs 'separate') is unreliable
|
||||
# when data passes through multiple nodes (e.g. PE → WB → Renderer)
|
||||
# because intermediate steps may set source to 'workflow_data'.
|
||||
from .workflow_families import MODEL_FAMILIES
|
||||
family_spec = MODEL_FAMILIES.get(family, {})
|
||||
if family_spec:
|
||||
is_ckpt = family_spec.get('checkpoint', False)
|
||||
loader_type = 'checkpoint' if is_ckpt else 'unet'
|
||||
else:
|
||||
# No family spec — fall back to clip source heuristic
|
||||
clip_source = clip_info.get('source', '')
|
||||
if clip_source == 'checkpoint':
|
||||
loader_type = 'checkpoint'
|
||||
elif clip_source in ('separate', 'workflow_data'):
|
||||
loader_type = 'unet'
|
||||
else:
|
||||
loader_type = ''
|
||||
|
||||
vae_override_explicit = 'vae' in overrides
|
||||
clip_override_explicit = 'clip_names' in overrides
|
||||
|
||||
vae_val = overrides.get('vae', extracted.get('vae', {}).get('name', ''))
|
||||
clip_val = overrides.get('clip_names', extracted.get('clip', {}).get('names', []))
|
||||
|
||||
# For checkpoint models: if the user didn't explicitly choose a separate
|
||||
# VAE / CLIP file, the checkpoint's own VAE / CLIP should be used.
|
||||
# The extracted values may contain real filenames from the source workflow
|
||||
# (e.g. clip_g.safetensors) but those came from a DualCLIPLoader in the
|
||||
# original graph — they shouldn't override the checkpoint's built-in ones.
|
||||
if loader_type == 'checkpoint':
|
||||
if not vae_override_explicit or not vae_val or vae_val.startswith('('):
|
||||
vae_val = '(from checkpoint)'
|
||||
if not clip_override_explicit or not clip_val or clip_val == [] or \
|
||||
(len(clip_val) == 1 and (not clip_val[0] or clip_val[0].startswith('('))):
|
||||
clip_val = ['(from checkpoint)']
|
||||
|
||||
return {
|
||||
"_source": overrides.get('_source', 'PromptExtractor'),
|
||||
"family": family,
|
||||
"model_a": overrides.get('model_a', extracted.get('model_a', '')),
|
||||
"model_b": overrides.get('model_b', extracted.get('model_b', '')),
|
||||
"positive_prompt": overrides.get('positive_prompt', extracted.get('positive_prompt', '')),
|
||||
"negative_prompt": overrides.get('negative_prompt', extracted.get('negative_prompt', '')),
|
||||
"loras_a": extracted.get('loras_a', []),
|
||||
"loras_b": extracted.get('loras_b', []),
|
||||
"vae": vae_val,
|
||||
"clip": clip_val,
|
||||
"clip_type": clip_info.get('type', '') or family_spec.get('clip_type', ''),
|
||||
"loader_type": loader_type,
|
||||
"sampler": _build_sampler_dict(sampler, family),
|
||||
"resolution": {
|
||||
"width": overrides.get('width', extracted.get('resolution', {}).get('width', 512)),
|
||||
"height": overrides.get('height', extracted.get('resolution', {}).get('height', 512)),
|
||||
"batch_size": overrides.get('batch_size', extracted.get('resolution', {}).get('batch_size', 1)),
|
||||
"length": overrides.get('length', extracted.get('resolution', {}).get('length', None)),
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,494 @@
|
||||
"""
|
||||
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 = {
|
||||
# ── 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 (originally SD1.5 but SDXL-compatible).
|
||||
"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,
|
||||
},
|
||||
# ── SD 1.5 ───────────────────────────────────────────────────────────────
|
||||
"sd15": {
|
||||
"label": "SD 1.5",
|
||||
"folders": [],
|
||||
"names": ["sd-1", "sd_1", "sd1", "v1-5", "v1_5", "v1.5", "dreamshaper", "realistic"],
|
||||
# SD1.5 canonical VAE: vae-ft-mse-840000 or vae-ft-ema-560000.
|
||||
"vae": ["vae-ft-mse-840000", "vae-ft-ema-560000", "orangemix", "blessed2"],
|
||||
# SD1.5 uses a single CLIP-L encoder only (NOT CLIP-G like SDXL).
|
||||
"clip": ["clip_l"],
|
||||
"clip_exclude": ["clip_g", "t5xxl", "umt5", "qwen", "gemma"],
|
||||
"sampler": "standard",
|
||||
"checkpoint": True,
|
||||
},
|
||||
# ── Qwen Image ───────────────────────────────────────────────────────────
|
||||
"qwen_image": {
|
||||
"label": "Qwen Image",
|
||||
"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 = [
|
||||
{"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 — SD1.5, SDXL, Qwen
|
||||
"flux": "flux", # SamplerCustomAdvanced + BasicGuider (Flux1, LTX-Video)
|
||||
"flux2": "flux2", # SamplerCustomAdvanced + CFGGuider (Klein/Flux2)
|
||||
"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 = {
|
||||
"sdxl": "sdxl",
|
||||
"sd15": None, # No template yet — falls back to hardcoded
|
||||
"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
|
||||
Falls back to all VAEs when no patterns are defined or nothing matched.
|
||||
"""
|
||||
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:
|
||||
return _ret(folder_paths.get_filename_list("vae"), 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, 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
|
||||
Falls back to all CLIPs when no patterns are defined or nothing matched.
|
||||
"""
|
||||
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, 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, 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
-1
@@ -1,7 +1,7 @@
|
||||
[project]
|
||||
name = "prompt-manager"
|
||||
description = "A comprehensive prompt management system for ComfyUI that saves complete workflow recipes including prompts, LoRAs, and their settings. Features AI-powered prompt generation, prompt extraction from ComfyUI/A1111 images and videos, and Dual LoRA Stack support for Wan workflows."
|
||||
version = "1.17.5"
|
||||
version = "2.0.0"
|
||||
license = {file = "LICENSE"}
|
||||
# classifiers = [
|
||||
# # For OS-independent nodes (works on all operating systems)
|
||||
|
||||
@@ -1,492 +0,0 @@
|
||||
"""
|
||||
Save Video H264/H265 Node
|
||||
A custom node that saves videos with H.264 or H.265 (HEVC) codec with quality control.
|
||||
Based on ComfyUI's built-in SaveVideo node but with added H.265 codec and CRF quality options.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
import av
|
||||
import json
|
||||
import math
|
||||
import torch
|
||||
import hashlib
|
||||
import safetensors.torch
|
||||
from datetime import datetime
|
||||
import folder_paths
|
||||
import comfy.utils
|
||||
from fractions import Fraction
|
||||
from comfy.cli_args import args
|
||||
|
||||
|
||||
class SaveVideoH26x:
|
||||
"""
|
||||
Save video with H.264 or H.265 codec and quality control.
|
||||
Takes VIDEO input (with audio support) and saves workflow metadata.
|
||||
Clone of ComfyUI's SaveVideo with H.265 and CRF quality control added.
|
||||
"""
|
||||
|
||||
CODECS = ["h264", "h265"]
|
||||
CHROMA_SUBSAMPLING = ["yuv420", "yuv422", "yuv444"]
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {
|
||||
"video": ("VIDEO", {"tooltip": "The video to save."}),
|
||||
"filename_prefix": ("STRING", {
|
||||
"default": "video/vid_%date:yy-MM-dd_hh-mm-ss%",
|
||||
"tooltip": "The prefix for the file to save.\nSupports %date:format% patterns."
|
||||
}),
|
||||
"codec": (cls.CODECS, {
|
||||
"default": "h264",
|
||||
"tooltip": "Video codec.\nh264 = 8-bit, better compatibility.\nh265/HEVC = 10-bit, better compression & gradients."
|
||||
}),
|
||||
"chroma": (cls.CHROMA_SUBSAMPLING, {
|
||||
"default": "yuv420",
|
||||
"tooltip": "Chroma subsampling.\nyuv420 = most compatible.\nyuv422 = better color for video editing.\nyuv444 = best color, no chroma loss.\n"
|
||||
}),
|
||||
"crf": ("INT", {
|
||||
"default": 18,
|
||||
"min": 0,
|
||||
"max": 51,
|
||||
"step": 1,
|
||||
"tooltip": "Constant Rate Factor (quality).\nLower = better quality, larger file.\n0 = lossless\n18-23 = high quality\n28+ = lower quality.\nRecommended: 18-28."
|
||||
}),
|
||||
"save": ("BOOLEAN", {
|
||||
"default": True,
|
||||
"tooltip": "Save to output folder.\nOff = preview only (saves to temp with fast encoding)."
|
||||
}),
|
||||
"save_latent": ("BOOLEAN", {
|
||||
"default": True,
|
||||
"tooltip": "Save latent alongside the video.\nOff = don't save the connected latent."
|
||||
}),
|
||||
},
|
||||
"optional": {
|
||||
"latent": ("LATENT", {"tooltip": "Optional latent to save alongside the video (same filename with .latent extension)."}),
|
||||
},
|
||||
"hidden": {
|
||||
"prompt": "PROMPT",
|
||||
"extra_pnginfo": "EXTRA_PNGINFO"
|
||||
},
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("STRING",)
|
||||
RETURN_NAMES = ("filename",)
|
||||
FUNCTION = "save_video"
|
||||
OUTPUT_NODE = True
|
||||
CATEGORY = "Prompt Manager"
|
||||
DESCRIPTION = "Saves video with H.264 or H.265 codec and quality control. Includes audio and workflow metadata."
|
||||
|
||||
def save_video(self, video, filename_prefix, codec, chroma, crf, save, save_latent, latent=None, prompt=None, extra_pnginfo=None):
|
||||
# Expand %date:format% patterns (e.g., %date:yy-MM-dd_hh-mm%)
|
||||
# This mimics ComfyUI's frontend JS date expansion
|
||||
def expand_date_format(text):
|
||||
def replace_date(match):
|
||||
fmt = match.group(1)
|
||||
now = datetime.now()
|
||||
# Convert common date format tokens to Python strftime
|
||||
fmt = fmt.replace('yyyy', '%Y').replace('yy', '%y')
|
||||
fmt = fmt.replace('MM', '%m').replace('dd', '%d')
|
||||
fmt = fmt.replace('HH', '%H').replace('hh', '%I')
|
||||
fmt = fmt.replace('mm', '%M').replace('ss', '%S')
|
||||
return now.strftime(fmt)
|
||||
return re.sub(r'%date:([^%]+)%', replace_date, text)
|
||||
|
||||
filename_prefix = expand_date_format(filename_prefix)
|
||||
|
||||
# Bit depth determined by codec: h264=8-bit, h265=10-bit
|
||||
is_10bit = (codec == "h265")
|
||||
pixel_format = f"{chroma}p" if not is_10bit else f"{chroma}p10le"
|
||||
|
||||
# Get video components (images, audio, frame_rate)
|
||||
components = video.get_components()
|
||||
images = components.images
|
||||
audio = components.audio
|
||||
frame_rate = components.frame_rate
|
||||
|
||||
# Get dimensions
|
||||
width, height = video.get_dimensions()
|
||||
|
||||
# Preview mode: save to temp with fast encoding
|
||||
if not save:
|
||||
temp_dir = folder_paths.get_temp_directory()
|
||||
# Use filename without subfolders, add counter if needed
|
||||
base_filename = os.path.basename(expand_date_format(filename_prefix))
|
||||
file = f"{base_filename}.mp4"
|
||||
file_path_test = os.path.join(temp_dir, file)
|
||||
if os.path.exists(file_path_test):
|
||||
# Find next available counter
|
||||
pattern = re.compile(rf"^{re.escape(base_filename)}_?(\d+)\.mp4$")
|
||||
existing_counters = []
|
||||
for f in os.listdir(temp_dir):
|
||||
match = pattern.match(f)
|
||||
if match:
|
||||
existing_counters.append(int(match.group(1)))
|
||||
next_counter = max(existing_counters, default=0) + 1
|
||||
file = f"{base_filename}_{next_counter:05}.mp4"
|
||||
file_path = os.path.join(temp_dir, file)
|
||||
subfolder = ""
|
||||
output_type = "temp"
|
||||
# Override to fast settings for preview
|
||||
codec = "h264"
|
||||
codec_name = "libx264"
|
||||
is_10bit = False
|
||||
pixel_format = "yuv420p"
|
||||
crf = 23
|
||||
preset = "veryfast"
|
||||
else:
|
||||
output_type = "output"
|
||||
preset = "medium"
|
||||
codec_name = "libx264" if codec == "h264" else "libx265"
|
||||
|
||||
# Get output path
|
||||
full_output_folder, filename, counter, subfolder, filename_prefix = folder_paths.get_save_image_path(
|
||||
filename_prefix,
|
||||
folder_paths.get_output_directory(),
|
||||
width,
|
||||
height
|
||||
)
|
||||
|
||||
# Build filename - add counter only if file already exists
|
||||
file = f"{filename}.mp4"
|
||||
file_path_test = os.path.join(full_output_folder, file)
|
||||
if os.path.exists(file_path_test):
|
||||
# File exists, find next available counter
|
||||
pattern = re.compile(rf"^{re.escape(filename)}_?(\d+)\.mp4$")
|
||||
existing_counters = []
|
||||
if os.path.isdir(full_output_folder):
|
||||
for f in os.listdir(full_output_folder):
|
||||
match = pattern.match(f)
|
||||
if match:
|
||||
existing_counters.append(int(match.group(1)))
|
||||
# Start from 1 if no counters found, otherwise next available
|
||||
next_counter = max(existing_counters, default=0) + 1
|
||||
file = f"{filename}_{next_counter:05}.mp4"
|
||||
|
||||
file_path = os.path.join(full_output_folder, file)
|
||||
|
||||
# Save latent if connected and enabled (only when saving to output)
|
||||
if save_latent and latent is not None:
|
||||
latent_file = file_path.replace('.mp4', '.latent')
|
||||
# Prepare latent metadata
|
||||
prompt_info = json.dumps(prompt) if prompt else ""
|
||||
latent_metadata = {"prompt": prompt_info}
|
||||
if extra_pnginfo:
|
||||
for x in extra_pnginfo:
|
||||
latent_metadata[x] = json.dumps(extra_pnginfo[x])
|
||||
# Save the latent
|
||||
latent_output = {"latent_tensor": latent["samples"], "latent_format_version_0": torch.tensor([])}
|
||||
if os.path.exists(latent_file):
|
||||
os.remove(latent_file)
|
||||
comfy.utils.save_torch_file(latent_output, latent_file, metadata=latent_metadata)
|
||||
|
||||
# Build metadata
|
||||
metadata = {}
|
||||
if not args.disable_metadata:
|
||||
if extra_pnginfo is not None:
|
||||
metadata.update(extra_pnginfo)
|
||||
if prompt is not None:
|
||||
metadata["prompt"] = prompt
|
||||
|
||||
# Prepare frame rate as fraction
|
||||
frame_rate_frac = Fraction(round(float(frame_rate) * 1000), 1000)
|
||||
|
||||
# Open output container with movflags for metadata
|
||||
with av.open(file_path, mode='w', options={'movflags': 'use_metadata_tags'}) as output:
|
||||
# Add metadata
|
||||
if metadata:
|
||||
for key, value in metadata.items():
|
||||
output.metadata[key] = json.dumps(value) if not isinstance(value, str) else value
|
||||
|
||||
# Create video stream
|
||||
video_stream = output.add_stream(codec_name, rate=frame_rate_frac)
|
||||
video_stream.width = width
|
||||
video_stream.height = height
|
||||
video_stream.pix_fmt = pixel_format
|
||||
|
||||
# Set encoding options
|
||||
video_stream.options = {
|
||||
'crf': str(crf),
|
||||
'preset': preset,
|
||||
}
|
||||
|
||||
# For H.265, add tag for Apple/browser compatibility
|
||||
if codec == "h265":
|
||||
video_stream.options['tag'] = 'hvc1'
|
||||
video_stream.options['x265-params'] = 'log-level=error'
|
||||
|
||||
# Create audio stream if audio is present
|
||||
audio_stream = None
|
||||
audio_sample_rate = 1
|
||||
if audio is not None:
|
||||
audio_sample_rate = int(audio['sample_rate'])
|
||||
audio_stream = output.add_stream('aac', rate=audio_sample_rate)
|
||||
|
||||
# Encode video frames
|
||||
for frame_tensor in images:
|
||||
if is_10bit:
|
||||
# Convert tensor to 16-bit for 10-bit encoding
|
||||
img = (frame_tensor[..., :3] * 65535).clamp(0, 65535).to(torch.int16).cpu().numpy().astype('uint16')
|
||||
frame = av.VideoFrame.from_ndarray(img, format='rgb48le')
|
||||
else:
|
||||
# Convert tensor to 8-bit
|
||||
img = (frame_tensor[..., :3] * 255).clamp(0, 255).byte().cpu().numpy()
|
||||
frame = av.VideoFrame.from_ndarray(img, format='rgb24')
|
||||
|
||||
# IMPORTANT: Explicitly reformat frame to target pixel format
|
||||
# Without this, the encoder may not respect the stream's pix_fmt
|
||||
frame = frame.reformat(format=pixel_format)
|
||||
|
||||
# Encode and mux
|
||||
for packet in video_stream.encode(frame):
|
||||
output.mux(packet)
|
||||
|
||||
# Flush video encoder
|
||||
for packet in video_stream.encode(None):
|
||||
output.mux(packet)
|
||||
|
||||
# Encode audio if present
|
||||
if audio_stream is not None and audio is not None:
|
||||
waveform = audio['waveform']
|
||||
# Trim audio to match video duration
|
||||
waveform = waveform[:, :, :math.ceil((audio_sample_rate / float(frame_rate)) * images.shape[0])]
|
||||
|
||||
# Create audio frame
|
||||
layout = 'mono' if waveform.shape[1] == 1 else 'stereo'
|
||||
frame = av.AudioFrame.from_ndarray(
|
||||
waveform.movedim(2, 1).reshape(1, -1).float().numpy(),
|
||||
format='flt',
|
||||
layout=layout
|
||||
)
|
||||
frame.sample_rate = audio_sample_rate
|
||||
frame.pts = 0
|
||||
|
||||
# Encode audio
|
||||
for packet in audio_stream.encode(frame):
|
||||
output.mux(packet)
|
||||
|
||||
# Flush audio encoder
|
||||
for packet in audio_stream.encode(None):
|
||||
output.mux(packet)
|
||||
|
||||
# h265 + yuv422/444 won't play in browser, so generate a browser-compatible preview in temp
|
||||
if not save or codec == "h264" or (codec == "h265" and chroma == "yuv420"):
|
||||
# Browser can play this directly (or it's already a preview)
|
||||
return {"ui": {"images": [{"filename": file, "subfolder": subfolder, "type": output_type}], "animated": (True,)}, "result": (file_path,)}
|
||||
else:
|
||||
# Create a browser-compatible h264 preview in temp folder
|
||||
temp_dir = folder_paths.get_temp_directory()
|
||||
preview_file = os.path.basename(file)
|
||||
# preview_file = f"preview_{counter:05}_{width}x{height}.mp4"
|
||||
preview_path = os.path.join(temp_dir, preview_file)
|
||||
|
||||
with av.open(preview_path, mode='w', format='mp4') as preview_output:
|
||||
preview_stream = preview_output.add_stream('libx264', rate=frame_rate)
|
||||
preview_stream.width = width
|
||||
preview_stream.height = height
|
||||
preview_stream.pix_fmt = 'yuv420p'
|
||||
preview_stream.options = {'crf': '23', 'preset': 'fast'} # Fast, smaller preview
|
||||
|
||||
# Add audio stream if we have audio
|
||||
preview_audio_stream = None
|
||||
if audio is not None:
|
||||
preview_audio_stream = preview_output.add_stream('aac', rate=int(audio['sample_rate']))
|
||||
|
||||
for img_tensor in images:
|
||||
frame_np = (img_tensor[..., :3] * 255).clamp(0, 255).byte().cpu().numpy()
|
||||
frame = av.VideoFrame.from_ndarray(frame_np, format='rgb24')
|
||||
frame = frame.reformat(format='yuv420p')
|
||||
for packet in preview_stream.encode(frame):
|
||||
preview_output.mux(packet)
|
||||
|
||||
for packet in preview_stream.encode(None):
|
||||
preview_output.mux(packet)
|
||||
|
||||
# Encode audio for preview
|
||||
if audio is not None and preview_audio_stream is not None:
|
||||
waveform = audio['waveform']
|
||||
preview_sample_rate = int(audio['sample_rate'])
|
||||
# Trim audio to match video duration
|
||||
waveform = waveform[:, :, :math.ceil((preview_sample_rate / float(frame_rate)) * images.shape[0])]
|
||||
|
||||
layout = 'mono' if waveform.shape[1] == 1 else 'stereo'
|
||||
frame = av.AudioFrame.from_ndarray(
|
||||
waveform.movedim(2, 1).reshape(1, -1).float().numpy(),
|
||||
format='flt',
|
||||
layout=layout
|
||||
)
|
||||
frame.sample_rate = preview_sample_rate
|
||||
frame.pts = 0
|
||||
for packet in preview_audio_stream.encode(frame):
|
||||
preview_output.mux(packet)
|
||||
for packet in preview_audio_stream.encode(None):
|
||||
preview_output.mux(packet)
|
||||
|
||||
return {"ui": {"images": [{"filename": preview_file, "subfolder": "", "type": "temp"}], "animated": (True,)}, "result": (file_path,)}
|
||||
|
||||
|
||||
class LoadLatentFile:
|
||||
"""
|
||||
Load a latent from a file path.
|
||||
Companion to SaveVideoH26x for loading latents saved alongside videos.
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {
|
||||
"file_path": ("STRING", {
|
||||
"default": "",
|
||||
"tooltip": "Path to the .latent file to load."
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("LATENT",)
|
||||
FUNCTION = "load"
|
||||
CATEGORY = "Prompt Manager"
|
||||
DESCRIPTION = "Load a latent from a file. Use with Save Video H264/H265 to reload saved latents."
|
||||
|
||||
def load(self, file_path):
|
||||
if not file_path or not os.path.exists(file_path):
|
||||
raise FileNotFoundError(f"Latent file not found: {file_path}")
|
||||
|
||||
# Load the latent file
|
||||
latent = safetensors.torch.load_file(file_path, device="cpu")
|
||||
|
||||
# Handle version differences
|
||||
multiplier = 1.0
|
||||
if "latent_format_version_0" not in latent:
|
||||
multiplier = 1.0 / 0.18215
|
||||
|
||||
samples = {"samples": latent["latent_tensor"].float() * multiplier}
|
||||
return (samples,)
|
||||
|
||||
@classmethod
|
||||
def IS_CHANGED(cls, file_path):
|
||||
"""Return hash of file to detect changes."""
|
||||
if not file_path or not os.path.exists(file_path):
|
||||
return ""
|
||||
m = hashlib.sha256()
|
||||
with open(file_path, 'rb') as f:
|
||||
m.update(f.read())
|
||||
return m.digest().hex()
|
||||
|
||||
@classmethod
|
||||
def VALIDATE_INPUTS(cls, file_path):
|
||||
if not file_path:
|
||||
return True # Empty is valid (will error at runtime)
|
||||
if not os.path.exists(file_path):
|
||||
return f"Latent file not found: {file_path}"
|
||||
return True
|
||||
|
||||
|
||||
class MonoToStereo:
|
||||
"""
|
||||
Convert mono audio to stereo by duplicating the channel.
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {
|
||||
"audio": ("AUDIO", {"tooltip": "Mono audio input to convert to stereo."}),
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("AUDIO",)
|
||||
FUNCTION = "convert"
|
||||
CATEGORY = "Prompt Manager"
|
||||
DESCRIPTION = "Convert mono audio to stereo by duplicating the single channel to left and right."
|
||||
|
||||
def convert(self, audio):
|
||||
waveform = audio['waveform']
|
||||
sample_rate = audio['sample_rate']
|
||||
|
||||
# Check if already stereo (or more)
|
||||
if waveform.shape[1] >= 2:
|
||||
# Already stereo, return as-is
|
||||
return (audio,)
|
||||
|
||||
# Duplicate mono channel to create stereo: (batch, 1, samples) -> (batch, 2, samples)
|
||||
stereo_waveform = waveform.repeat(1, 2, 1)
|
||||
|
||||
return ({"waveform": stereo_waveform, "sample_rate": sample_rate},)
|
||||
|
||||
|
||||
class GetVideoComponentsPlus:
|
||||
"""
|
||||
Extract video components (images, audio, fps) plus the filepath.
|
||||
Like ComfyUI's GetVideoComponents but also outputs the file path as a string,
|
||||
and automatically loads a matching .latent file if one exists.
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {
|
||||
"video": ("VIDEO", {"tooltip": "The video to extract components from."}),
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("IMAGE", "AUDIO", "FLOAT", "STRING", "LATENT")
|
||||
RETURN_NAMES = ("images", "audio", "fps", "filepath", "latent")
|
||||
FUNCTION = "get_components"
|
||||
CATEGORY = "Prompt Manager"
|
||||
DESCRIPTION = "Extract video frames, audio, fps, filepath, and matching latent file if found."
|
||||
|
||||
def get_components(self, video):
|
||||
# Get video components using the standard API
|
||||
components = video.get_components()
|
||||
images = components.images
|
||||
audio = components.audio
|
||||
fps = float(components.frame_rate)
|
||||
|
||||
# Try to get the file path from the video object
|
||||
video_path = ""
|
||||
try:
|
||||
source = video.get_stream_source()
|
||||
if isinstance(source, str):
|
||||
video_path = source
|
||||
except Exception as e:
|
||||
print(f"[GetVideoComponentsPlus] Could not get video path: {e}")
|
||||
|
||||
# Check for matching .latent file
|
||||
latent = None
|
||||
if video_path and os.path.exists(video_path):
|
||||
latent_path = os.path.splitext(video_path)[0] + '.latent'
|
||||
if os.path.exists(latent_path):
|
||||
try:
|
||||
# Load the latent file (same logic as LoadLatentFile)
|
||||
latent_data = safetensors.torch.load_file(latent_path, device="cpu")
|
||||
|
||||
# Handle version differences
|
||||
multiplier = 1.0
|
||||
if "latent_format_version_0" not in latent_data:
|
||||
multiplier = 1.0 / 0.18215
|
||||
|
||||
latent = {"samples": latent_data["latent_tensor"].float() * multiplier}
|
||||
print(f"[GetVideoComponentsPlus] Loaded matching latent: {latent_path}")
|
||||
except Exception as e:
|
||||
print(f"[GetVideoComponentsPlus] Could not load latent file: {e}")
|
||||
|
||||
return (images, audio, fps, video_path, latent)
|
||||
|
||||
|
||||
# Node registration
|
||||
NODE_CLASS_MAPPINGS = {
|
||||
"SaveVideoH26x": SaveVideoH26x,
|
||||
"LoadLatentFile": LoadLatentFile,
|
||||
"AudioMonoToStereo": MonoToStereo,
|
||||
"GetVideoComponentsPlus": GetVideoComponentsPlus,
|
||||
}
|
||||
|
||||
NODE_DISPLAY_NAME_MAPPINGS = {
|
||||
"SaveVideoH26x": "Save Video H264/H265",
|
||||
"LoadLatentFile": "Load Latent File",
|
||||
"AudioMonoToStereo": "Audio Mono to Stereo",
|
||||
"GetVideoComponentsPlus": "Get Video Components+",
|
||||
}
|
||||
@@ -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]}')
|
||||
@@ -1,193 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Organize Files by Workflow Presence
|
||||
Standalone script to scan a folder and move files without workflow metadata
|
||||
Defaults to "D:/ComfyUI/input" if no folder is provided.
|
||||
"""
|
||||
|
||||
import json
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
|
||||
try:
|
||||
from PIL import Image
|
||||
HAS_PIL = True
|
||||
except ImportError:
|
||||
HAS_PIL = False
|
||||
print("ERROR: PIL/Pillow is required!")
|
||||
print("Install with: pip install pillow")
|
||||
input("Press Enter to exit...")
|
||||
exit(1)
|
||||
|
||||
|
||||
def check_png_workflow(file_path):
|
||||
"""Check if PNG has workflow metadata (ComfyUI or A1111 format)"""
|
||||
try:
|
||||
with Image.open(file_path) as img:
|
||||
# Check for ComfyUI workflow/prompt or A1111 parameters
|
||||
return 'workflow' in img.info or 'prompt' in img.info or 'parameters' in img.info
|
||||
except:
|
||||
return False
|
||||
|
||||
|
||||
def check_jpeg_workflow(file_path):
|
||||
"""Check if JPEG/WebP has workflow metadata"""
|
||||
try:
|
||||
with Image.open(file_path) as img:
|
||||
exif = img.getexif()
|
||||
if exif and 0x9286 in exif:
|
||||
return True
|
||||
if hasattr(img, 'info'):
|
||||
return any(key in img.info for key in ['workflow', 'prompt', 'parameters'])
|
||||
except:
|
||||
return False
|
||||
|
||||
|
||||
def check_json_workflow(file_path):
|
||||
"""Check if JSON file contains workflow data"""
|
||||
try:
|
||||
with open(file_path, 'r', encoding='utf-8') as f:
|
||||
data = json.load(f)
|
||||
if isinstance(data, dict):
|
||||
return 'nodes' in data or 'workflow' in data or any(
|
||||
isinstance(v, dict) and 'class_type' in v for v in data.values()
|
||||
)
|
||||
except Exception as e:
|
||||
print(f" (JSON parse error: {e})")
|
||||
pass
|
||||
return False
|
||||
|
||||
|
||||
def check_video_workflow(file_path):
|
||||
"""Check if video has workflow metadata using ffprobe executable"""
|
||||
import subprocess
|
||||
|
||||
try:
|
||||
# Use ffprobe to get video metadata in JSON format
|
||||
result = subprocess.run(
|
||||
['ffprobe', '-v', 'quiet', '-print_format', 'json', '-show_format', str(file_path)],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=10
|
||||
)
|
||||
|
||||
if result.returncode == 0:
|
||||
data = json.loads(result.stdout)
|
||||
if 'format' in data and 'tags' in data['format']:
|
||||
tags = data['format']['tags']
|
||||
# Check for common workflow metadata keys
|
||||
return any(key.lower() in ['comment', 'workflow', 'prompt', 'parameters'] for key in tags)
|
||||
return False
|
||||
|
||||
except FileNotFoundError:
|
||||
# ffprobe not found in PATH
|
||||
print(" (Skipping - ffprobe not found in PATH)")
|
||||
return None # Return None to skip
|
||||
except subprocess.TimeoutExpired:
|
||||
print(" (Timeout reading video)")
|
||||
return False
|
||||
except Exception as e:
|
||||
print(f" (Video probe error: {e})")
|
||||
return False
|
||||
|
||||
|
||||
def has_workflow_metadata(file_path):
|
||||
"""Check if file has workflow metadata"""
|
||||
ext = file_path.suffix.lower()
|
||||
|
||||
if ext == '.png':
|
||||
return check_png_workflow(file_path)
|
||||
elif ext in ['.jpg', '.jpeg', '.webp']:
|
||||
return check_jpeg_workflow(file_path)
|
||||
elif ext == '.json':
|
||||
return check_json_workflow(file_path)
|
||||
elif ext in ['.mp4', '.webm', '.mov', '.avi']:
|
||||
return check_video_workflow(file_path)
|
||||
|
||||
return False
|
||||
|
||||
|
||||
def main(folder_path=None):
|
||||
print("=" * 60)
|
||||
print("File Organizer - Separate files by workflow presence")
|
||||
print("=" * 60)
|
||||
|
||||
if folder_path is None:
|
||||
# Get folder from user
|
||||
folder_input = input("\nEnter folder path to scan (default D:/ComfyUI/input): ").strip().strip('"')
|
||||
if folder_input == "":
|
||||
folder_path = Path("D:/ComfyUI/input")
|
||||
else:
|
||||
folder_path = Path(folder_input)
|
||||
|
||||
if not folder_path.exists():
|
||||
print(f"\nERROR: Folder does not exist: {folder_path}")
|
||||
input("Press Enter to exit...")
|
||||
return
|
||||
|
||||
if not folder_path.is_dir():
|
||||
print(f"\nERROR: Not a directory: {folder_path}")
|
||||
input("Press Enter to exit...")
|
||||
return
|
||||
|
||||
# Create no_workflow subfolder
|
||||
no_workflow_path = folder_path / "no_workflow"
|
||||
no_workflow_path.mkdir(exist_ok=True)
|
||||
|
||||
print(f"\nScanning: {folder_path}")
|
||||
print(f"Moving files without workflow to: {no_workflow_path}")
|
||||
print("=" * 60)
|
||||
|
||||
# Supported extensions
|
||||
supported = {'.png', '.jpg', '.jpeg', '.webp', '.json', '.mp4', '.webm', '.mov', '.avi'}
|
||||
|
||||
files_with_workflow = []
|
||||
files_without_workflow = []
|
||||
files_skipped = []
|
||||
|
||||
# Scan only files in this directory (no subdirectories)
|
||||
for file_path in folder_path.iterdir():
|
||||
if not file_path.is_file():
|
||||
continue
|
||||
|
||||
if file_path.suffix.lower() in supported:
|
||||
print(f"Checking: {file_path.name}", end=' ... ')
|
||||
|
||||
try:
|
||||
result = has_workflow_metadata(file_path)
|
||||
if result is None:
|
||||
# Skipped (e.g., video without ffmpeg)
|
||||
files_skipped.append(file_path)
|
||||
elif result:
|
||||
print("✓ Has workflow")
|
||||
files_with_workflow.append(file_path)
|
||||
else:
|
||||
print("✗ No workflow")
|
||||
files_without_workflow.append(file_path)
|
||||
except Exception as e:
|
||||
print(f"ERROR: {e}")
|
||||
|
||||
# Summary
|
||||
print("\n" + "=" * 60)
|
||||
print(f"Files with workflow: {len(files_with_workflow)}")
|
||||
print(f"Files without workflow: {len(files_without_workflow)}")
|
||||
if files_skipped:
|
||||
print(f"Files skipped: {len(files_skipped)}")
|
||||
|
||||
# Move files without workflow
|
||||
if files_without_workflow:
|
||||
print("\nMoving files without workflow...")
|
||||
for file_path in files_without_workflow:
|
||||
dest_path = no_workflow_path / file_path.name
|
||||
try:
|
||||
shutil.move(str(file_path), str(dest_path))
|
||||
print(f" Moved: {file_path.name}")
|
||||
except Exception as e:
|
||||
print(f" ERROR moving {file_path.name}: {e}")
|
||||
|
||||
print("\nDone!")
|
||||
input("Press Enter to exit...")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,269 +0,0 @@
|
||||
"""
|
||||
Test extraction for all LoRA loader types to ensure compatibility
|
||||
"""
|
||||
import sys
|
||||
import os
|
||||
from unittest.mock import Mock
|
||||
|
||||
# Add parent directory to path
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
|
||||
|
||||
# Mock dependencies
|
||||
sys.modules['folder_paths'] = Mock()
|
||||
sys.modules['server'] = Mock()
|
||||
sys.modules['torch'] = Mock()
|
||||
sys.modules['PIL'] = Mock()
|
||||
|
||||
from prompt_extractor import (
|
||||
extract_power_lora_loader,
|
||||
extract_lora_manager_stacker,
|
||||
extract_wan_video_lora_select_multi,
|
||||
extract_lora_loader_stack_rgthree,
|
||||
extract_standard_lora_loader,
|
||||
is_lora_node
|
||||
)
|
||||
|
||||
def test_power_lora_loader():
|
||||
"""Test Power Lora Loader (rgthree) extraction"""
|
||||
print("\n" + "=" * 80)
|
||||
print("TEST: Power Lora Loader (rgthree)")
|
||||
print("=" * 80)
|
||||
|
||||
node = {
|
||||
'type': 'Power Lora Loader (rgthree)',
|
||||
'widgets_values': [
|
||||
{"on": True, "lora": "lora1.safetensors", "strength": 1.0, "strengthTwo": 0.8},
|
||||
{"on": False, "lora": "lora2.safetensors", "strength": 0.5, "strengthTwo": None},
|
||||
{"on": True, "lora": "lora3.safetensors", "strength": 1.2, "strengthTwo": 1.5}
|
||||
]
|
||||
}
|
||||
|
||||
loras = extract_power_lora_loader(node)
|
||||
|
||||
print(f"Extracted {len(loras)} LoRAs:")
|
||||
for lora in loras:
|
||||
active_status = " [ACTIVE]" if lora.get('active', True) else " [INACTIVE]"
|
||||
print(f" - {lora['name']} (model: {lora['model_strength']}, clip: {lora['clip_strength']}){active_status}")
|
||||
|
||||
assert len(loras) == 3, f"Expected 3 LoRAs, got {len(loras)}"
|
||||
assert loras[0]['name'] == 'lora1'
|
||||
assert loras[0]['model_strength'] == 1.0
|
||||
assert loras[0]['clip_strength'] == 0.8
|
||||
assert loras[0]['active'] == True
|
||||
|
||||
assert loras[1]['name'] == 'lora2'
|
||||
assert loras[1]['active'] == False
|
||||
|
||||
assert loras[2]['name'] == 'lora3'
|
||||
assert loras[2]['model_strength'] == 1.2
|
||||
assert loras[2]['clip_strength'] == 1.5
|
||||
|
||||
print("[PASS] Power Lora Loader extraction working correctly!")
|
||||
|
||||
|
||||
def test_lora_manager_stacker():
|
||||
"""Test Lora Stacker (LoraManager) extraction"""
|
||||
print("\n" + "=" * 80)
|
||||
print("TEST: Lora Stacker (LoraManager)")
|
||||
print("=" * 80)
|
||||
|
||||
node = {
|
||||
'type': 'Lora Stacker (LoraManager)',
|
||||
'widgets_values': [
|
||||
None, # First item is usually None
|
||||
[
|
||||
{"name": "stacker_lora1", "strength": 0.33, "active": True, "clipStrength": 0.5},
|
||||
{"name": "stacker_lora2", "strength": "0.8", "active": False, "clipStrength": "0.9"},
|
||||
{"name": "stacker_lora3", "strength": 1.0, "active": True, "clipStrength": 1.0}
|
||||
]
|
||||
]
|
||||
}
|
||||
|
||||
loras = extract_lora_manager_stacker(node)
|
||||
|
||||
print(f"Extracted {len(loras)} LoRAs:")
|
||||
for lora in loras:
|
||||
active_status = " [ACTIVE]" if lora.get('active', True) else " [INACTIVE]"
|
||||
print(f" - {lora['name']} (model: {lora['model_strength']}, clip: {lora['clip_strength']}){active_status}")
|
||||
|
||||
assert len(loras) == 3, f"Expected 3 LoRAs, got {len(loras)}"
|
||||
assert loras[0]['name'] == 'stacker_lora1'
|
||||
assert loras[0]['model_strength'] == 0.33
|
||||
assert loras[0]['clip_strength'] == 0.5
|
||||
|
||||
assert loras[1]['name'] == 'stacker_lora2'
|
||||
assert loras[1]['model_strength'] == 0.8
|
||||
assert loras[1]['active'] == False
|
||||
|
||||
print("[PASS] Lora Stacker extraction working correctly!")
|
||||
|
||||
|
||||
def test_wan_video_lora_select_multi():
|
||||
"""Test WanVideoLoraSelectMulti extraction"""
|
||||
print("\n" + "=" * 80)
|
||||
print("TEST: WanVideoLoraSelectMulti")
|
||||
print("=" * 80)
|
||||
|
||||
node = {
|
||||
'type': 'WanVideoLoraSelectMulti',
|
||||
'widgets_values': [
|
||||
'WanAnimate_relight_lora_fp16.safetensors', 1,
|
||||
'lightx2v_I2V_14B_480p_cfg_step_distill_rank64_bf16.safetensors', 1.2,
|
||||
'NSFW-22-L-e8.safetensors', 1,
|
||||
'WAN-2.2-I2V-Handjob-LOW-v1.safetensors', 2,
|
||||
'none', 1,
|
||||
False, False
|
||||
]
|
||||
}
|
||||
|
||||
loras = extract_wan_video_lora_select_multi(node)
|
||||
|
||||
print(f"Extracted {len(loras)} LoRAs:")
|
||||
for lora in loras:
|
||||
active_status = " [ACTIVE]" if lora.get('active', True) else " [INACTIVE]"
|
||||
print(f" - {lora['name']} (model: {lora['model_strength']}, clip: {lora['clip_strength']}){active_status}")
|
||||
|
||||
assert len(loras) == 4, f"Expected 4 LoRAs, got {len(loras)}"
|
||||
assert loras[0]['name'] == 'WanAnimate_relight_lora_fp16'
|
||||
assert loras[0]['model_strength'] == 1.0
|
||||
|
||||
assert loras[1]['name'] == 'lightx2v_I2V_14B_480p_cfg_step_distill_rank64_bf16'
|
||||
assert loras[1]['model_strength'] == 1.2
|
||||
|
||||
assert loras[3]['name'] == 'WAN-2.2-I2V-Handjob-LOW-v1'
|
||||
assert loras[3]['model_strength'] == 2.0
|
||||
|
||||
print("[PASS] WanVideoLoraSelectMulti extraction working correctly!")
|
||||
|
||||
|
||||
def test_lora_loader_stack_rgthree():
|
||||
"""Test Lora Loader Stack (rgthree) extraction"""
|
||||
print("\n" + "=" * 80)
|
||||
print("TEST: Lora Loader Stack (rgthree)")
|
||||
print("=" * 80)
|
||||
|
||||
node = {
|
||||
'type': 'Lora Loader Stack (rgthree)',
|
||||
'widgets_values': [
|
||||
'SmoothXXXAnimation_High.safetensors', 0.2,
|
||||
'None', 0.8,
|
||||
'None', 1,
|
||||
'None', 1
|
||||
]
|
||||
}
|
||||
|
||||
loras = extract_lora_loader_stack_rgthree(node)
|
||||
|
||||
print(f"Extracted {len(loras)} LoRAs:")
|
||||
for lora in loras:
|
||||
active_status = " [ACTIVE]" if lora.get('active', True) else " [INACTIVE]"
|
||||
print(f" - {lora['name']} (model: {lora['model_strength']}, clip: {lora['clip_strength']}){active_status}")
|
||||
|
||||
assert len(loras) == 1, f"Expected 1 LoRA, got {len(loras)}"
|
||||
assert loras[0]['name'] == 'SmoothXXXAnimation_High'
|
||||
assert loras[0]['model_strength'] == 0.2
|
||||
assert loras[0]['clip_strength'] == 0.2
|
||||
assert loras[0]['active'] == True
|
||||
|
||||
print("[PASS] Lora Loader Stack (rgthree) extraction working correctly!")
|
||||
|
||||
# Test with multiple LoRAs
|
||||
print("\nTesting with multiple LoRAs:")
|
||||
node2 = {
|
||||
'type': 'Lora Loader Stack (rgthree)',
|
||||
'widgets_values': [
|
||||
'lora1.safetensors', 0.5,
|
||||
'lora2.safetensors', 0.7,
|
||||
'lora3.safetensors', 1.0,
|
||||
'None', 1
|
||||
]
|
||||
}
|
||||
|
||||
loras2 = extract_lora_loader_stack_rgthree(node2)
|
||||
|
||||
print(f"Extracted {len(loras2)} LoRAs:")
|
||||
for lora in loras2:
|
||||
print(f" - {lora['name']} (model: {lora['model_strength']}, clip: {lora['clip_strength']})")
|
||||
|
||||
assert len(loras2) == 3, f"Expected 3 LoRAs, got {len(loras2)}"
|
||||
assert loras2[0]['name'] == 'lora1'
|
||||
assert loras2[1]['name'] == 'lora2'
|
||||
assert loras2[2]['name'] == 'lora3'
|
||||
|
||||
print("[PASS] Multiple LoRAs extraction working correctly!")
|
||||
|
||||
|
||||
def test_standard_lora_loader():
|
||||
"""Test standard LoraLoader extraction"""
|
||||
print("\n" + "=" * 80)
|
||||
print("TEST: Standard LoraLoader")
|
||||
print("=" * 80)
|
||||
|
||||
node = {
|
||||
'type': 'LoraLoader',
|
||||
'widgets_values': ['standard_lora.safetensors', 0.7, 0.9]
|
||||
}
|
||||
|
||||
loras = extract_standard_lora_loader(node)
|
||||
|
||||
print(f"Extracted {len(loras)} LoRAs:")
|
||||
for lora in loras:
|
||||
active_status = " [ACTIVE]" if lora.get('active', True) else " [INACTIVE]"
|
||||
print(f" - {lora['name']} (model: {lora['model_strength']}, clip: {lora['clip_strength']}){active_status}")
|
||||
|
||||
assert len(loras) == 1, f"Expected 1 LoRA, got {len(loras)}"
|
||||
assert loras[0]['name'] == 'standard_lora'
|
||||
assert loras[0]['model_strength'] == 0.7
|
||||
assert loras[0]['clip_strength'] == 0.9
|
||||
assert loras[0]['active'] == True
|
||||
|
||||
print("[PASS] Standard LoraLoader extraction working correctly!")
|
||||
|
||||
|
||||
def test_is_lora_node():
|
||||
"""Test that all LoRA node types are recognized"""
|
||||
print("\n" + "=" * 80)
|
||||
print("TEST: is_lora_node recognition")
|
||||
print("=" * 80)
|
||||
|
||||
lora_types = [
|
||||
'Power Lora Loader (rgthree)',
|
||||
'Lora Loader Stack (rgthree)',
|
||||
'Lora Stacker (LoraManager)',
|
||||
'LoRA Stacker',
|
||||
'LoraLoader',
|
||||
'LoraLoaderModelOnly',
|
||||
'WanVideoLoraSelectMulti'
|
||||
]
|
||||
|
||||
non_lora_types = [
|
||||
'KSampler',
|
||||
'CLIPTextEncode',
|
||||
'VAEDecode',
|
||||
'WanVideoModelLoader'
|
||||
]
|
||||
|
||||
print("Testing LoRA node types:")
|
||||
for node_type in lora_types:
|
||||
result = is_lora_node(node_type)
|
||||
status = "✓" if result else "✗"
|
||||
print(f" {status} {node_type}: {result}")
|
||||
assert result, f"{node_type} should be recognized as LoRA node"
|
||||
|
||||
print("\nTesting non-LoRA node types:")
|
||||
for node_type in non_lora_types:
|
||||
result = is_lora_node(node_type)
|
||||
status = "✓" if not result else "✗"
|
||||
print(f" {status} {node_type}: {result}")
|
||||
assert not result, f"{node_type} should NOT be recognized as LoRA node"
|
||||
|
||||
print("[PASS] All node type recognition working correctly!")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_power_lora_loader()
|
||||
test_lora_manager_stacker()
|
||||
test_wan_video_lora_select_multi()
|
||||
test_lora_loader_stack_rgthree()
|
||||
print("ALL TESTS PASSED! ✓")
|
||||
print("=" * 80)
|
||||
@@ -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 ===")
|
||||
Reference in New Issue
Block a user