Compare commits

...
312 Commits
Author SHA1 Message Date
Francois Beaudry 6df8cbef30 Merge pull request #38 from FranckyB/dev
Dev
2026-05-01 20:26:52 -04:00
THE_BEAST\meandCopilot a2d8687993 Refactor code structure for improved readability and maintainability
Co-authored-by: Copilot <copilot@github.com>
2026-05-01 20:25:03 -04:00
THE_BEAST\meandCopilot 6931d4811f refactor: Rename WorkflowBuilderMulti to RecipeBuilder for consistency and clarity
Co-authored-by: Copilot <copilot@github.com>
2026-05-01 18:42:30 -04:00
THE_BEAST\meandCopilot 8b3e7adcf4 feat: Enhance prompt payload validation in WorkflowBuilder for improved data handling
Co-authored-by: Copilot <copilot@github.com>
2026-05-01 17:57:15 -04:00
THE_BEAST\me cc2a66c74a feat: Update version to 2.5.1 and enhance recipe relay with improved handling of EXTRA_1 and EXTRA_2 fields 2026-05-01 17:33:25 -04:00
THE_BEAST\me c3f7c85b9e refactor: Rename EXTRA key to EXTRA_1 and EXTRA_2 for clarity in recipe data handling 2026-04-30 07:35:31 -04:00
THE_BEAST\me 01862135da fix: Update changelog to clarify Recipe Builder is now Multi-model Only 2026-04-29 11:00:23 -04:00
THE_BEAST\meandCopilot 46cbe4266b feat: Update README and changelog for v2.5.0, highlighting Multi Model support and new Multi Lora Stack node
Co-authored-by: Copilot <copilot@github.com>
2026-04-29 10:31:03 -04:00
THE_BEAST\me ecf7472ff5 feat: Update version to 2.5.0 and add MultiLoraCombine class for enhanced LoRA stack management 2026-04-29 10:11:08 -04:00
THE_BEAST\meandCopilot 6b3cbb3268 feat: Sync recipe_data model resolutions with Builder UI on execution
Co-authored-by: Copilot <copilot@github.com>
2026-04-29 01:42:42 -04:00
THE_BEAST\meandCopilot 9771f7e3fb feat: Enhance LoRA path resolution and normalization in recipe handling
Co-authored-by: Copilot <copilot@github.com>
2026-04-29 00:10:34 -04:00
THE_BEAST\meandCopilot 90e4c9e24d feat: Add browser content filter functionality to enhance prompt and recipe visibility options
Co-authored-by: Copilot <copilot@github.com>
2026-04-28 22:51:25 -04:00
THE_BEAST\meandCopilot c96badf1b9 feat: Implement prompt preset payload validation and enhance recipe data building from prompts
Co-authored-by: Copilot <copilot@github.com>
2026-04-28 22:33:02 -04:00
THE_BEAST\meandCopilot b8286a5e51 feat: Capture original strengths for model slots from slot profiles to enhance reset functionality
Co-authored-by: Copilot <copilot@github.com>
2026-04-28 21:05:54 -04:00
THE_BEAST\meandCopilot d030a3b717 feat: Enhance Recipe Builder with v2 hydration and contract tests
- Implemented _hydrate_v2_recipe_models to ensure v2 recipe_data contains dict blocks for model_a to model_d.
- Updated WorkflowBuilder to cache previous recipe_data for change detection and hydration.
- Added comprehensive contract tests for Recipe Builder's execute behavior, covering model slot preservation, prompt overrides, and LoRA state management.
- Introduced JS contract tests for UI lock and persistence logic in recipe_builder.js.

Co-authored-by: Copilot <copilot@github.com>
2026-04-28 16:50:02 -04:00
THE_BEAST\meandCopilot 4bad6fae7e feat: Improve prompt handling by adding locking mechanism for positive and negative prompts; enhance UI state management for effective values
Co-authored-by: Copilot <copilot@github.com>
2026-04-28 09:55:02 -04:00
THE_BEAST\meandCopilot 9a91d30530 feat: Normalize multi-lora stack handling to ensure consistent list returns and improve input processing
Co-authored-by: Copilot <copilot@github.com>
2026-04-28 09:26:08 -04:00
THE_BEAST\meandCopilot c93d4b013c feat: Enhance LoRA path resolution and availability tracking in prompt extraction
Co-authored-by: Copilot <copilot@github.com>
2026-04-28 08:47:09 -04:00
THE_BEAST\meandCopilot a3b0e7eaff feat: Enhance multi-lora stack handling by adding source tracking for candidates and refining empty list treatment
Co-authored-by: Copilot <copilot@github.com>
2026-04-28 02:12:09 -04:00
THE_BEAST\meandCopilot cfb85445fa feat: Refactor multi-prompt handling and replace RecipeBuilderPromptBundle with RecipeBuilderMultiPrompts; update MultiLoraStackerLM to new structure and improve input normalization
Co-authored-by: Copilot <copilot@github.com>
2026-04-28 00:55:30 -04:00
THE_BEAST\meandCopilot 9e875c7a99 feat: Update styling for active slots in MultiLoraStackerLM with new accent colors and box-shadow adjustments
Co-authored-by: Copilot <copilot@github.com>
2026-04-28 00:07:42 -04:00
THE_BEAST\meandCopilot 39b688403d feat: Replace RecipeBuilderDataBundle with RecipeBuilderPromptBundle and update references for multi-prompt integration
Co-authored-by: Copilot <copilot@github.com>
2026-04-28 00:03:06 -04:00
THE_BEAST\meandCopilot 2359960a54 feat: Refactor MultiLoraStackerLM and RecipeBuilder to support multi-lora stack integration and enhance node size constraints
Co-authored-by: Copilot <copilot@github.com>
2026-04-27 22:44:51 -04:00
THE_BEAST\meandCopilot fffcb49c4d feat: Add prompt serialization shim to ensure correct backend class integration for MultiLoraStackerLM
Co-authored-by: Copilot <copilot@github.com>
2026-04-27 22:13:03 -04:00
THE_BEAST\meandCopilot a89b04f81b feat: Enhance scrollbar styling and improve state restoration logic in MultiLoraStackerLM
Co-authored-by: Copilot <copilot@github.com>
2026-04-27 22:07:36 -04:00
THE_BEAST\meandCopilot f137bfc751 feat: Implement dynamic theming using PM_UI_PALETTE in prompt_manager_advanced and recipe_builder
Co-authored-by: Copilot <copilot@github.com>
2026-04-27 21:50:34 -04:00
THE_BEAST\meandCopilot 6cd2c40fb8 feat: Integrate PM_UI_PALETTE for dynamic styling in MultiLoraStackerLM
Co-authored-by: Copilot <copilot@github.com>
2026-04-27 21:21:46 -04:00
THE_BEAST\meandCopilot 0fb68ddd16 feat: Enhance styling for MultiLoraStackerLM with flexible height and layout adjustments
Co-authored-by: Copilot <copilot@github.com>
2026-04-27 21:15:11 -04:00
THE_BEAST\meandCopilot e583c6b529 feat: Refactor height management and slot selection handling in MultiLoraStackerLM
Co-authored-by: Copilot <copilot@github.com>
2026-04-27 21:08:24 -04:00
THE_BEAST\meandCopilot 58b9305a02 First wip of multi Lora Stacker
Co-authored-by: Copilot <copilot@github.com>
2026-04-27 20:34:56 -04:00
THE_BEAST\meandCopilot 654488efd3 feat: Enhance WAN model handling with improved slot resolution and dual-sampler support
Co-authored-by: Copilot <copilot@github.com>
2026-04-27 16:53:50 -04:00
THE_BEAST\me 3e15a45cb8 feat: Refactor visibility handling for family-specific models and enhance error checking for WAN video family consistency 2026-04-27 12:39:57 -04:00
THE_BEAST\meandCopilot 82ea8ce773 feat: Adjust thumbnail preview timing and enhance multi LoRA stack handling for clearer slot management
Co-authored-by: Copilot <copilot@github.com>
2026-04-27 02:55:42 -04:00
THE_BEAST\meandCopilot 8cdf32e3b1 feat: Enhance LoRA handling in WorkflowBuilder and WorkflowRelay for improved state management and path resolution
Co-authored-by: Copilot <copilot@github.com>
2026-04-27 01:21:07 -04:00
THE_BEAST\meandCopilot 1b5eb256f9 feat: Enhance slot profile handling by introducing section locks and effective value resolution in WorkflowBuilder
Co-authored-by: Copilot <copilot@github.com>
2026-04-27 00:33:34 -04:00
THE_BEAST\meandCopilot 545332f43e feat: Update default sampler settings and add family override support in WorkflowRelay
Co-authored-by: Copilot <copilot@github.com>
2026-04-27 00:02:39 -04:00
THE_BEAST\meandCopilot 5ce3248216 feat: Add blank model block function to ensure v2 schema compliance and enhance model slot handling in workflow output
Co-authored-by: Copilot <copilot@github.com>
2026-04-26 23:29:10 -04:00
THE_BEAST\meandCopilot c70894a020 feat: Improve recipe data handling by adding legacy support and normalization for v2 structure
Co-authored-by: Copilot <copilot@github.com>
2026-04-26 23:05:28 -04:00
THE_BEAST\meandCopilot a756747d08 feat: Preserve existing denoise value in WorkflowBuilder when omitted in profile
Co-authored-by: Copilot <copilot@github.com>
2026-04-26 21:50:36 -04:00
THE_BEAST\meandCopilot c93e9eada9 feat: Enhance lora handling by introducing preferred profile loras and maintaining drag/drop order in WorkflowBuilder
Co-authored-by: Copilot <copilot@github.com>
2026-04-26 21:35:12 -04:00
THE_BEAST\meandCopilot 1fb017f772 feat: Add support for lora ghosting in profile handling within WorkflowBuilder
Co-authored-by: Copilot <copilot@github.com>
2026-04-26 20:37:25 -04:00
THE_BEAST\meandCopilot c4cec35a19 feat: Enhance input ghosting logic in WorkflowBuilder and recipe handling
Co-authored-by: Copilot <copilot@github.com>
2026-04-26 20:11:22 -04:00
THE_BEAST\meandCopilot 9ee1a0dd52 Refactor model handling and update placeholder strings
- Simplified model slot normalization by removing unnecessary parameters and checks.
- Updated the logic for determining primary and secondary model slots in the workflow builder.
- Changed placeholder strings from '(from checkpoint)' to '(Default)' across various modules for consistency.
- Removed the WAN-specific builder class and adjusted the multi-slot builder to handle model slots more effectively.
- Enhanced the extraction utilities to ensure proper handling of VAE and CLIP information.

Co-authored-by: Copilot <copilot@github.com>
2026-04-26 19:55:45 -04:00
THE_BEAST\meandCopilot 15587a5d56 feat: Refactor RecipeBuilder to integrate builder_data input and streamline multi-slot handling
Co-authored-by: Copilot <copilot@github.com>
2026-04-26 17:58:25 -04:00
THE_BEAST\meandCopilot 75c2ccc562 feat: Simplify RecipeBuilder by removing WAN and Multi variants, streamlining node interactions
Co-authored-by: Copilot <copilot@github.com>
2026-04-26 17:15:00 -04:00
THE_BEAST\me bcd68b11cd Implement feature X to enhance user experience and optimize performance 2026-04-26 16:46:17 -04:00
THE_BEAST\meandCopilot 83cea8e955 feat: Update recipe handling to ensure empty prompts on new node instances and improve workflow data management
Co-authored-by: Copilot <copilot@github.com>
2026-04-26 16:26:27 -04:00
THE_BEAST\meandCopilot 8417d42ff6 feat: Add multi-slot support with new helper nodes for prompts, seeds, and LoRA stacks in Recipe Builder
Co-authored-by: Copilot <copilot@github.com>
2026-04-26 14:39:02 -04:00
THE_BEAST\me 5188d04b02 feat: Merge incoming slot data while preserving lock states for improved profile management 2026-04-26 12:40:43 -04:00
THE_BEAST\meandCopilot f62ff73d2c feat: Add multi-slot support in Recipe Builder for enhanced model management
Co-authored-by: Copilot <copilot@github.com>
2026-04-26 12:10:46 -04:00
THE_BEAST\meandCopilot d348e71664 feat: Update SVG icons and adjust layout dimensions for improved UI consistency
Co-authored-by: Copilot <copilot@github.com>
2026-04-26 01:07:29 -04:00
THE_BEAST\me 98c6f11904 feat: Implement collapsible and lockable sections in the workflow builder 2026-04-26 00:22:23 -04:00
THE_BEAST\meandCopilot 2d3a4ffe32 feat: Enhance workflow data handling to preserve active states and improve LORA management
Co-authored-by: Copilot <copilot@github.com>
2026-04-25 20:28:18 -04:00
THE_BEAST\meandCopilot 8bd45cb519 Refactor workflow data handling to support v2 model structure
- Updated PromptExtractor to construct workflow data with a new v2 model format, including handling of model_a and model_b blocks.
- Enhanced PromptManagerAdvanced to retain Lora paths during normalization for better data integrity.
- Modified RecipeBuilder to apply preferred Lora order and manage model overrides more effectively.
- Improved RecipeManager to ensure proper handling of model_a and model_b outputs, including conditional logic for model retention.
- Adjusted RecipeRelay to streamline model slot management and ensure compatibility with v2 structure.
- Cleaned up RecipeRenderer to align with new model data handling, removing legacy references.
- Removed deprecated legacy top-level keys and streamlined ensure_v2_recipe_data function for clarity and efficiency.

Co-authored-by: Copilot <copilot@github.com>
2026-04-25 18:19:30 -04:00
THE_BEAST\meandCopilot afb9c567eb feat: Refactor WorkflowRelay to handle v2 recipe structures and maintain legacy support
Co-authored-by: Copilot <copilot@github.com>
2026-04-24 22:43:38 -04:00
THE_BEAST\meandCopilot f2ad940d32 feat: Add RecipeModelPicker node and integrate model data handling in WorkflowRelay
Co-authored-by: Copilot <copilot@github.com>
2026-04-24 22:33:16 -04:00
Francois Beaudry 99b44c1bc2 Merge pull request #37 from FranckyB/dev
Dev
2026-04-24 19:02:20 -04:00
THE_BEAST\meandCopilot f721466c14 Enhance prompt filtering to preserve selections during workflow restoration
- Updated `filterPromptDropdown` function to accept an options parameter for preserving dangling selections.
- Modified calls to `filterPromptDropdown` in both `prompt_manager.js` and `prompt_manager_advanced.js` to maintain user selections when loading prompts asynchronously.
- Introduced flags to manage workflow restoration state, preventing unwanted changes to selections during the restore process.
- Ensured that category and prompt widgets retain their values when the current selection is not present in the filtered options.

Co-authored-by: Copilot <copilot@github.com>
2026-04-24 18:59:49 -04:00
THE_BEAST\meandCopilot 2b3a3bfe45 feat: Update version to 2.2.0 and enhance changelog with new features and improvements
Co-authored-by: Copilot <copilot@github.com>
2026-04-24 17:58:05 -04:00
THE_BEAST\meandCopilot f1cdcfeff5 feat: Add model slot validation in WorkflowRenderer to ensure defined models
Co-authored-by: Copilot <copilot@github.com>
2026-04-24 17:21:16 -04:00
THE_BEAST\meandCopilot 9f4e02c7f5 feat: Improve LoRA input handling and update authoritative state logic in WorkflowBuilder
Co-authored-by: Copilot <copilot@github.com>
2026-04-24 17:03:24 -04:00
THE_BEAST\meandCopilot 05415abf49 feat: Improve update button visibility handling and default selection logic in RecipeBuilder
Co-authored-by: Copilot <copilot@github.com>
2026-04-24 16:45:08 -04:00
THE_BEAST\meandCopilot 946400d441 feat: Enhance model slot handling and improve error messaging in RecipeBuilder
Co-authored-by: Copilot <copilot@github.com>
2026-04-24 16:14:46 -04:00
THE_BEAST\meandCopilot 57c56de26b feat: Add workflow summary info button and enhance preview handling in PromptManagerAdvanced
Co-authored-by: Copilot <copilot@github.com>
2026-04-24 14:23:30 -04:00
THE_BEAST\meandCopilot 8e4c230300 feat: Enhance recipe and prompt management with v2 model slot support and extraction improvements
Co-authored-by: Copilot <copilot@github.com>
2026-04-24 13:33:26 -04:00
THE_BEAST\me d365f7752c feat: Enhance recipe management with improved model slot handling and v2 compatibility 2026-04-24 12:06:31 -04:00
THE_BEAST\me e8e5e5a09e feat: Enhance prompt management with v2 compatibility and fallback mechanisms for LoRA handling 2026-04-24 05:01:00 -04:00
THE_BEAST\meandCopilot 3640df2bf4 feat: Initialize model key and weight dtype before normalization for v2 compatibility
Co-authored-by: Copilot <copilot@github.com>
2026-04-24 03:21:05 -04:00
THE_BEAST\meandCopilot ba7e993888 feat: Update model parameters and enhance recipe handling for v2 compatibility
Co-authored-by: Copilot <copilot@github.com>
2026-04-24 03:16:58 -04:00
THE_BEAST\me 9a22a329f3 feat: Add support for model pair options in recipe builder for WAN mode 2026-04-24 02:03:36 -04:00
THE_BEAST\meandCopilot 32f653e18d Refactor recipe management to support v2 model blocks
- Introduced functions to ensure v2 recipe data structure and retrieve model blocks.
- Updated WorkflowManager to utilize new v2 model block structure for handling model_a and model_b.
- Refactored WorkflowRelay to accommodate model slot selection and improved handling of sampler and resolution settings.
- Enhanced RecipeRenderer to support rendering from specified model slots in v2 recipe data.
- Updated workflow_data_utils to normalize legacy recipe data into the new v2 format, preserving necessary fields.
- Improved handling of LoRA stacks and sampler configurations across different recipe data versions.

Co-authored-by: Copilot <copilot@github.com>
2026-04-24 01:45:38 -04:00
THE_BEAST\meandCopilot 03185836b9 fix: Update README for clarity on recipe extraction and modification
Co-authored-by: Copilot <copilot@github.com>
2026-04-22 15:32:19 -04:00
THE_BEAST\meandCopilot 7812a98ddc feat: Bump version to 2.1.1 and update changelog; remove unused check_loaders.py
Co-authored-by: Copilot <copilot@github.com>
2026-04-22 13:16:15 -04:00
THE_BEAST\meandCopilot 609375766b feat: Ensure backend updates are applied on new prompt reset by clearing execution update signals
Co-authored-by: Copilot <copilot@github.com>
2026-04-22 13:13:25 -04:00
THE_BEAST\meandCopilot 7cc6e8c20a feat: Preserve explicit empty selection in prompt dropdown across tab-switch restore
Co-authored-by: Copilot <copilot@github.com>
2026-04-22 12:55:02 -04:00
THE_BEAST\meandCopilot 5acc0d6e8c feat: Enhance workflow data handling with meaningful checks and improve LoRA availability tracking
Co-authored-by: Copilot <copilot@github.com>
2026-04-22 12:36:01 -04:00
THE_BEAST\me ce6d34b24e Updated provided Workflows 2026-04-22 09:42:24 -04:00
THE_BEAST\me 98b53ddd71 feat: Enhance README with new features and update images; rename workflow data to recipe data 2026-04-22 09:30:56 -04:00
THE_BEAST\me d7347e790c feat: Add comprehensive Prompt Manager and Workflow tools for ComfyUI
- Introduced Prompt Manager, Prompt Generator, Prompt Extractor, and Prompt Model Loader.
- Added Workflow Extractor, Builder, Renderer, and Manager for streamlined workflow management.
- Enhanced prompt saving with LoRA and trigger word support.
- Implemented dual LoRA stack functionality and improved metadata extraction from images and videos.
- Updated documentation to reflect new features and usage instructions.
- Version 2.0.0 release with significant improvements and new capabilities.
2026-04-22 08:53:11 -04:00
THE_BEAST\me 3c101e1b8a fix: update README to clarify model support and custom model path 2026-04-22 06:58:56 -04:00
Francois Beaudry fdd64969ae Merge pull request #35 from FranckyB/dev
Dev
2026-04-21 23:55:51 -04:00
THE_BEAST\me 7135b9e721 bump: update version to 2.1.0 in __init__.py and pyproject.toml 2026-04-21 23:53:44 -04:00
THE_BEAST\me 738dd63182 refactor: remove workflow-related options and streamline prompt management logic 2026-04-21 23:52:16 -04:00
THE_BEAST\me f231989e69 fix: update CivitAI search URL to use the correct domain 2026-04-21 23:23:46 -04:00
THE_BEAST\me c42a963d68 Refactor workflow-related terminology to use "recipe" instead of "workflow"
- Updated variable names, comments, and documentation to replace "workflow_data" with "recipe_data" across multiple files.
- Adjusted input and output types in nodes to reflect the new naming convention.
- Modified the functionality of nodes to ensure compatibility with the new "recipe_data" structure.
- Ensured that all references to workflow extraction and management are now aligned with the recipe terminology.
2026-04-21 23:05:01 -04:00
THE_BEAST\me c701bb5002 Add documentation for ComfyUI tab switch and state persistence
- Outline how ComfyUI handles tab switches and the lifecycle of node creation.
- Detail the serialization of node properties and the correct pattern for storing and restoring state.
- Emphasize critical rules for maintaining state and avoiding common pitfalls.
- Provide guidelines for DOM widget sizing and the use of flex properties to prevent layout issues.
- Include reference patterns and best practices for ensuring reliable UI behavior during tab persistence.
2026-04-21 21:44:03 -04:00
THE_BEAST\me 0196bca21e refactor: update README for clarity and improved structure, emphasizing Recipe terminology 2026-04-21 21:10:33 -04:00
THE_BEAST\me d92fcf436c Refactor code structure for improved readability and maintainability, updated Workflows with new naming 2026-04-21 13:12:33 -04:00
THE_BEAST\me 89dc3a4e94 feat: update terminology from Workflow to Recipe across multiple files 2026-04-21 10:22:02 -04:00
THE_BEAST\me 2e8333a4cc feat: update terminology from Workflow to Recipe across multiple files 2026-04-21 09:58:24 -04:00
THE_BEAST\me cc35c8e4e6 Refactor workflow and prompt extraction nodes for Recipe compatibility
- Updated node types in workflow_builder_simple.json to replace WorkflowGenerator with RecipeExtractor and RecipeBuilder.
- Modified prompt_extractor.py to include RecipeExtractor and RecipeRenderer in prompt handling logic.
- Enhanced workflow_extraction_utils.py to support Recipe nodes alongside Workflow nodes for embedded data extraction.
- Ensured backward compatibility with legacy WorkflowGenerator while transitioning to Recipe-based workflows.
2026-04-21 09:33:09 -04:00
THE_BEAST\me f7789930c1 feat: rename workflow terminology to recipe across documentation and codebase 2026-04-21 02:14:17 -04:00
THE_BEAST\me b775a1d93d feat: enhance workflow data handling and input normalization in WorkflowBuilder 2026-04-21 01:21:45 -04:00
Francois Beaudry 430f7cf276 Merge pull request #34 from FranckyB/dev
feat: Add Ernie family support in workflow components and update model handling
2026-04-20 00:55:24 -04:00
THE_BEAST\me df8f2b57d3 chore: Bump version to 2.0.2 and update README with Ernie support details
feat: Add Ernie family support in workflow components and update model handling
fix: Improve handling of missing injections in select rows and align family defaults
2026-04-20 00:52:03 -04:00
Francois Beaudry 42f3559e8c Merge pull request #32 from FranckyB/dev
Add new workflow configuration for high-resolution image processing
2026-04-19 17:21:03 -04:00
THE_BEAST\me ba301ce39a Add new workflow configuration for high-resolution image processing
- Introduced a new workflow JSON file `workflow_builder_simple-hirez.json`
- Configured nodes for image processing including WorkflowRenderer, SaveImage, and WorkflowManager
- Implemented input and output links for workflow data and image handling
- Defined properties and widgets for user interaction and customization
2026-04-19 17:14:50 -04:00
Francois Beaudry 1c86920d3b Merge pull request #31 from FranckyB/dev
Dev
2026-04-19 15:42:25 -04:00
THE_BEAST\me 39ade25cc2 chore: Bump version to 2.0.1 and update changelog with denoise options for workflow pipeline 2026-04-19 15:37:19 -04:00
THE_BEAST\me 3ff5ff7902 fix: Remove redundant inputs from node in Prompt Selector Widget 2026-04-19 15:30:31 -04:00
THE_BEAST\me f764beef53 fix: Improve formatting of use_prompt_input settings in PromptManagerAdvanced 2026-04-19 14:28:29 -04:00
THE_BEAST\me 1fb0d3dcc7 feat: Add denoise parameter to sampler settings across workflow components
- Introduced 'denoise' parameter in workflow_builder.js, workflow_bridge.py, and workflow_renderer.py to enhance rendering control.
- Updated prompt_extractor.py to include default denoise value in extracted workflow data.
- Modified workflow_extraction_utils.py to handle denoise parameter during extraction and building of sampler dictionaries.
- Ensured denoise parameter is properly managed in various functions to maintain consistency across the workflow.
2026-04-19 13:19:47 -04:00
Francois Beaudry f748246801 Merge pull request #26 from FranckyB/dev
Dev
2026-04-19 02:04:20 -04:00
THE_BEAST\me b7905b81da Refactor code structure for improved readability and maintainability 2026-04-19 02:01:13 -04:00
THE_BEAST\me dd78c417ba Refactor workflow saving and management functionality
- Removed the WorkflowSaver module and integrated its functionality into the PromptManagerAdvanced and WorkflowManager classes.
- Enhanced the createWorkflowSaveBrowserModal function to streamline the workflow saving process, including improved handling of existing prompts and categories.
- Updated the savePrompt function to ensure proper normalization of LoRA data and workflow data persistence.
- Improved the handling of workflow data in the WorkflowManager to prioritize live data over local state.
- Added new utility functions for better management of workflow data serialization, ensuring non-serializable objects are stripped before saving.
- Enhanced error handling and user notifications throughout the workflow saving process.
2026-04-19 01:17:30 -04:00
THE_BEAST\me eb9dc96631 feat: Add WorkflowManager for streamlined workflow_data editing
- Introduced WorkflowManager class, a simplified version of PromptManagerAdvanced, focusing solely on workflow_data input/output.
- Updated workflow_builder.js to include WorkflowManager in node type checks and error messages.
- Enhanced error handling and logging for better debugging.
- Implemented thumbnail generation for workflow_data visualization.
- Refactored input types and return structures to accommodate new workflow management features.
2026-04-18 23:44:00 -04:00
THE_BEAST\me 5beaf8e501 feat: Annotate missing LoRAs in workflow data to maintain authored stack information 2026-04-18 21:19:26 -04:00
THE_BEAST\me bf2ad422d7 feat: Improve LoRA handling by filtering out missing LoRAs from workflow data while maintaining UI visibility 2026-04-18 21:00:08 -04:00
THE_BEAST\me 89825a747d feat: Enhance LoRA management with original strengths caching and UI state protection 2026-04-18 20:32:41 -04:00
THE_BEAST\me 0d8e9192f1 Add shared UI palette for Prompt Manager modals
- Introduced a new JavaScript file `ui_palette.js` containing color definitions for modal dialogs.
- Aligned the palette with Workflow Builder's neutral and blue accent styling.
- Defined colors for overlay, panel, borders, text, and accent elements to ensure consistent UI appearance.
2026-04-18 19:59:26 -04:00
THE_BEAST\me 763a340488 Add PromptManager and WorkflowSaver for managing prompts and workflow snapshots
- Implemented PromptManager for saving and loading prompts by category with backup functionality.
- Added API endpoints for managing prompts, including saving, deleting, and importing prompts.
- Introduced WorkflowSaver to capture and save workflow_data snapshots into prompt library entries.
- Included thumbnail generation from images for saved workflows.
- Enhanced error handling and validation for API requests.
2026-04-18 17:23:22 -04:00
THE_BEAST\me 7362da49d9 feat: Implement weekly rotating backup for prompt data to enhance data safety and recovery 2026-04-17 22:35:49 -04:00
THE_BEAST\me 9f4bac5f30 feat: Refactor workflow data handling and input connections for improved prompt management and seed control 2026-04-17 22:21:33 -04:00
THE_BEAST\me f36411aac5 feat: Add workflow_data input support in Prompt Manager Advanced for enhanced prompt and LoRA stack integration 2026-04-17 21:11:17 -04:00
THE_BEAST\me 0d3216d0e9 feat: Enhance workflow toggle handling with state persistence and restoration 2026-04-17 21:05:35 -04:00
THE_BEAST\me 834aff18da feat: Enhance LoRA management and workflow integration
- Introduced sorting functions for LoRAs to prioritize available ones and sort alphabetically.
- Normalized extracted LoRA order in prompt extraction to ensure consistent display.
- Added support for workflow data in the prompt manager, allowing for dynamic updates based on connected inputs.
- Implemented live workflow data pickup to refresh prompts and LoRAs in real-time.
- Updated UI to reflect the presence of workflow data with visual indicators.
- Enhanced backend logic to handle workflow data more effectively, including extraction from connected nodes.
- Added new configuration options for using workflow data in the prompt manager.
2026-04-17 20:53:16 -04:00
THE_BEAST\me bae6df106a feat: Enhance LoRA management and workflow integration
- Added sorting functionality for LoRA lists to ensure consistent ordering.
- Improved merging of LoRA lists to deduplicate entries and maintain order.
- Updated `PromptManagerAdvanced` to support workflow data integration, allowing for LoRAs to be sourced from saved workflow data.
- Refactored handling of workflow data in `get_prompt` method to prioritize connected inputs and saved data.
- Enhanced error messaging for missing connections in workflow data.
- Updated documentation strings for clarity on functionality.
- Bumped version to 1.25.0 to reflect new features and improvements.
2026-04-17 19:20:16 -04:00
THE_BEAST\me 07b428767e feat: Enhance LoRA state persistence and extraction in WorkflowBuilder and PromptExtractor 2026-04-17 16:37:46 -04:00
THE_BEAST\me 6a58f9ce95 feat: Update help text and button labels in Workflow Builder for clarity 2026-04-17 15:17:00 -04:00
THE_BEAST\me bdb1cc4212 feat: Enhance resolution extraction and media dimension handling in PromptExtractor and WorkflowExtractionUtils 2026-04-17 10:39:24 -04:00
THE_BEAST\me cbc0efa839 feat: Enhance model handling by normalizing family selection and improving resolution extraction 2026-04-17 05:44:17 -04:00
THE_BEAST\me 119952a51d feat: Enhance model selection and prompt persistence in WorkflowBuilder 2026-04-17 04:34:30 -04:00
THE_BEAST\me d0e591c24c feat: Replace WorkflowContext with WorkflowBridge and enhance workflow data handling 2026-04-17 03:36:10 -04:00
THE_BEAST\me df148d8cd3 feat: Update family defaults and enhance extractor handling in WorkflowBuilder and WorkflowRenderer 2026-04-17 01:34:28 -04:00
THE_BEAST\me c76a95adf9 Refactor WorkflowBuilder, WorkflowContext, and WorkflowRenderer for improved handling of overrides and conditioning
- Enhanced WorkflowBuilder to allow conditional overrides based on section locks, ensuring local UI overrides are respected only for locked sections when workflow data is present.
- Updated the handling of model, sampler, and resolution parameters to apply overrides conditionally.
- Modified WorkflowContext to include positive and negative conditioning as optional parameters, passing them through to the workflow data.
- Introduced a new method in WorkflowRenderer to encode positive and negative text conditioning using the CLIP encoder, improving the handling of text prompts.
- Ensured that the workflow output includes the newly encoded conditioning data.
2026-04-17 00:18:40 -04:00
THE_BEAST\me 00ed3ffd92 feat: Implement strict family filtering for WAN video models and enhance show-all models functionality 2026-04-16 02:12:25 -04:00
THE_BEAST\me 3d72e8b4ff feat: Enhance Workflow Model Loader with GGUF support and improved model handling
- Added GGUF model loading capabilities to the WorkflowModelLoader.
- Updated WorkflowRenderer to include WORKFLOW_DATA in return types.
- Removed redundant versioning from workflow extraction utility.
- Deleted obsolete workflow model loader test file.
- Introduced a new JavaScript extension for visualizing loaded models in the UI.
- Improved model resolution and loading logic for checkpoints and diffusion models.
- Enhanced error handling and user feedback for missing models and assets.
2026-04-16 01:36:22 -04:00
THE_BEAST\me 5dd666fe3a Enhance workflow prompt extraction and model listing
- Updated prompt extraction logic to include WorkflowBuilder as a source of extracted data, prioritizing it appropriately alongside WorkflowRenderer and WorkflowGenerator.
- Modified the UI response of PromptExtractor and WorkflowExtractor to prevent displaying preview images in Comfy history/tasks, ensuring cleaner output.
- Improved model listing API to support a 'show_all' query parameter, allowing users to retrieve all models or only compatible ones based on the specified family.
- Enhanced fallback mechanisms for model retrieval to accommodate installations with inconsistent folder structures, ensuring better compatibility and user experience.
2026-04-15 23:50:55 -04:00
THE_BEAST\me 4fd7070c97 feat: Enhance VAE and CLIP handling for checkpoint models and preserve not-found LoRAs in workflow_data 2026-04-15 03:46:05 -04:00
THE_BEAST\me 9fcf4ef1a7 feat: Enhance WorkflowBuilder with caching and extraction data retrieval 2026-04-15 03:35:14 -04:00
THE_BEAST\me cb8b7e7205 feat: Add family_override support to workflow extraction process 2026-04-15 03:10:37 -04:00
THE_BEAST\me 661a35f971 feat: Refactor model loading and enhance UI styles for better usability 2026-04-15 03:01:37 -04:00
THE_BEAST\me 27eca5ba94 feat: Update LoRA stack and model labels for WAN Video visibility handling 2026-04-15 02:01:19 -04:00
THE_BEAST\me e7fece763c feat: Update WAN visibility handling for video mode and enhance resolution row layout 2026-04-15 01:42:55 -04:00
THE_BEAST\me 56bdb9e98a feat: Swap width and height values for landscape orientation in workflow builder 2026-04-15 01:23:56 -04:00
THE_BEAST\me 24f6f8ad65 feat: Enhance workflow model loading and sampler parameter extraction
- Added IS_CHANGED method in WorkflowRenderer to provide a stable fingerprint for workflow data, optimizing re-execution.
- Updated sampler parameter extraction to support new 'steps_a' and 'steps_b' keys, replacing legacy 'steps' handling.
- Refactored workflow extraction utilities to accommodate dual-sampler configurations and removed deprecated parameters.
- Introduced WorkflowGetModel node for streamlined model loading, supporting GGUF format and improved error handling.
- Enhanced model compatibility listing with keyword-based sorting for better user experience.
2026-04-15 01:18:57 -04:00
THE_BEAST\me bd8ffdca8a feat: Add right-click context menu for Lora tags with search functionality 2026-04-14 01:45:50 -04:00
THE_BEAST\me 3906e87e19 feat: Enhance model compatibility checks and default value handling for VAE/CLIP in workflow processing 2026-04-14 01:12:14 -04:00
THE_BEAST\me 376a58e27c feat: Show/hide "Update Workflow" button based on workflow_data connection 2026-04-14 00:37:38 -04:00
THE_BEAST\me 711cd87567 fix: Remove unnecessary workflow_data validation in PromptManagerAdvanced 2026-04-14 00:17:05 -04:00
THE_BEAST\me 00f23b4590 feat: Refactor WorkflowExtractor and WorkflowBuilder to streamline workflow data handling and improve prompt management 2026-04-14 00:09:31 -04:00
THE_BEAST\me e8639a5050 Refactor PromptExtractor and WorkflowBuilder for improved workflow data handling
- Set OUTPUT_NODE to False in PromptExtractor to disable preview display.
- Enhance PromptExtractor to merge final LoRA stacks into workflow_data and update the _last_extracted_info cache.
- Introduce WorkflowExtractor class for simplified extraction of workflow data and images, omitting LoRA inputs/outputs.
- Modify WorkflowBuilder to streamline input handling, removing unnecessary flags and improving LoRA merging logic.
- Ensure connected LoRA inputs are merged with existing workflow LoRAs, prioritizing user intent.
- Update input types and tooltips for clarity in the WorkflowBuilder.
2026-04-13 23:33:32 -04:00
THE_BEAST\me 54c9d98e85 feat: Implement "Update Workflow" functionality in WorkflowBuilder to fetch data from PromptExtractor 2026-04-13 20:20:08 -04:00
THE_BEAST\me c78cbd6913 feat: Enhance WorkflowBuilder and WorkflowRenderer to improve clip and VAE handling 2026-04-13 02:13:24 -04:00
THE_BEAST\me adf5766f48 Fix clip model family configuration by updating exclusions
- Removed "clip_l" from the "clip" model family.
- Added "clip_l" to the "clip_exclude" list to ensure proper filtering.
2026-04-13 01:43:24 -04:00
THE_BEAST\me 8accd26d94 fix: Update import statements to correctly reference workflow_renderer for render functions 2026-04-13 00:48:46 -04:00
THE_BEAST\me 7c2dc8248b feat: Enhance _run_standard_ksampler and rendering functions to support additional latent dict parameters 2026-04-13 00:37:04 -04:00
THE_BEAST\me 7eb21c918a feat: Add Test Render Functions and Workflow Model Loader
- Implemented a self-contained test node for rendering functions that auto-discovers compatible models, VAE, and CLIP, and runs the render pipeline, outputting IMAGE, LATENT, and a report.
- Created a Workflow Model Loader to load MODEL, CLIP, and VAE from workflow_data names, optimizing model loading with caching to prevent redundant operations.
- Introduced a new workflow renderer script to set initial node sizes for better UI alignment.
2026-04-13 00:19:21 -04:00
THE_BEAST\me 3d528c2997 feat: enhance WorkflowBuilder to apply lora overrides and filter inactive loras 2026-04-12 17:15:43 -04:00
THE_BEAST\me 6c11ec52de feat: add override_data support and improve model selection in WorkflowContext 2026-04-12 15:20:19 -04:00
THE_BEAST\me 07fd152e84 feat: enhance workflow data handling by supporting dict and JSON string formats 2026-04-12 13:56:43 -04:00
THE_BEAST\me a950ebfa92 Refactor workflow handling and model loading
- Removed the prompt_model_loader.py file as its functionality is now integrated into workflow_context.py.
- Updated workflow_builder.py to use seed_a instead of seed for sampler parameters.
- Changed category from "FBnodes" to "Prompt Manager" in workflow_builder.py and workflow_renderer.py.
- Enhanced workflow extraction utilities to support seed_a and seed_b for dual-sampler configurations.
- Introduced workflow_context.py to manage unpacking and repacking of workflow_data, including model loading and parameter overrides.
2026-04-12 13:27:51 -04:00
THE_BEAST\me 3effd8f1e8 feat: enhance WorkflowBuilder with positive and negative prompt inputs 2026-04-12 10:46:40 -04:00
THE_BEAST\me a1c496ed4c feat: add WorkflowRenderer for render-only node functionality
- Implemented WorkflowRenderer class to handle rendering from WORKFLOW_DATA.
- Supports model loading, sampling, decoding, and output of IMAGE and LATENT.
- Integrated optional GGUF support for enhanced model handling.
- Added error handling for model and VAE loading.
- Introduced patching mechanism for template-driven workflows.
- Enhanced logging for better traceability during execution.
2026-04-12 10:21:37 -04:00
THE_BEAST\me 504b2dce40 fix: adjust latent tensor dimensions for WAN video processing 2026-04-12 00:37:54 -04:00
THE_BEAST\me f8d228b42c Restored tab Switching fix and fixed Wan Video generation 2026-04-12 00:09:25 -04:00
FranckyBandClaude Opus 4.6 69912c724c fix: clamp resolution patch values to max 1280px for i2v, not the source image tensor
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-12 00:39:33 +00:00
FranckyBandClaude Opus 4.6 0db278723d fix: call WanImageToVideo.execute() classmethod instead of encode()
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-12 00:25:26 +00:00
FranckyBandClaude Opus 4.6 a498a5e7f3 fix: clamp i2v source image resolution to max 1280px keeping aspect ratio
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-12 00:23:54 +00:00
FranckyBandClaude Opus 4.6 f3607303af fix: i2v api template batch_size=1, start_image from resize node, add SaveImage node
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-12 00:18:31 +00:00
FranckyBandClaude Opus 4.6 173328bf2d fix: use patched JSON template for i2v instead of manual Python node execution
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-12 00:11:42 +00:00
FranckyB 214f653d4e fix: preserve steps_high/low and seed overrides in wfOn mode; use explicit values over auto-split 2026-04-11 23:53:37 +00:00
FranckyB 74005592e8 fix: derive steps_high/low from steps split in JS; default 3/3 instead of 4/20 2026-04-11 23:49:26 +00:00
FranckyB 0939ae11ec fix: when wfOn, syncHidden must not capture model/VAE/CLIP from DOM — wf_data is authoritative for all fields 2026-04-11 23:44:15 +00:00
FranckyB b0ea8f6faf fix: pass fromUpdateUI flag to onFamilyChanged to skip auto-select and syncHidden when called from updateUI 2026-04-11 23:42:19 +00:00
FranckyB cf11bfc9d0 fix: split steps_high/low in wf_data for wan_video; don't overwrite model_a override in onFamilyChanged 2026-04-11 23:36:42 +00:00
FranckyB 0a757baa9b fix: fall back to first compatible family model when model_a not found, show red in UI 2026-04-11 23:33:00 +00:00
FranckyB 944759a05a fix: log source_image tensor shape (or None) for i2v debugging 2026-04-11 23:26:25 +00:00
FranckyB 92bb954fc2 fix: prioritize wf_data family over stale JS _family override in execute() 2026-04-11 23:24:19 +00:00
FranckyB 9fb3ffc6fb fix: use wan_i2v_image map key to patch LoadImage node directly for i2v source image 2026-04-11 22:57:28 +00:00
FranckyB 557152ae96 fix: await updateUI in wfToggle to prevent family snapping to SDXL; fix PIL image shape for i2v source 2026-04-11 22:55:17 +00:00
FranckyB de2c5cd295 fix: always split steps evenly for WAN dual-sampler (high=ceil/2, low=floor/2) 2026-04-11 22:42:15 +00:00
FranckyB d2323da13c fix: pre-load families list in updateUI so family dropdown switches correctly 2026-04-11 22:37:36 +00:00
FranckyB 7be4ea4748 fix: WAN i2v dual-sampler steps split, frame count as length, source image forwarding, add template print
- Bug 1: Split total steps evenly between high/low samplers using
  ceil/floor instead of sending the same value to both
- Bug 2: Extract WanImageToVideo batch_size as frame length (not
  batch_size), keep batch_size=1 for video workflows; add latent_length
  mapping to i2v map JSON
- Bug 3: Save source_image tensor to disk and patch LoadImage node in
  i2v template so the source image is forwarded to WanImageToVideo
- Bug 4: Print template name, family, strategy, and file path at the
  start of execute_template() for easier debugging
2026-04-11 22:24:14 +00:00
FranckyBandClaude Opus 4.6 6e9595a594 fix: remove unnecessary skipAutoSelect flag from onFamilyChanged
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-11 22:13:11 +00:00
FranckyB f5a66e1995 fix: updateUI reloads family dropdowns before setting model/VAE/CLIP values
When workflow_data specifies a family different from the current UI state
(e.g. wan_video_i2v fed into a node that defaulted to sdxl), updateUI was
setting sel.value = 'wan_video_i2v' visually but never reloading the model,
VAE, and CLIP dropdown lists. _setOriginal then couldn't find the WAN
model/VAE/CLIP names in the SDXL options list and fell back to (Default).

Fix:
- updateUI is now async
- Stores onFamilyChanged on node as node._onFamilyChanged after definition
- When the incoming family differs from node._weFamily, updateUI awaits
  node._onFamilyChanged(newFamily, { skipAutoSelect: true }) before
  setting model/VAE/CLIP — dropdowns are now populated with the correct
  family's options before _setOriginal runs
- skipAutoSelect option added to onFamilyChanged so the auto-first-model
  logic is skipped when called from updateUI (updateUI sets the correct
  model itself from workflow_data)
2026-04-11 22:08:18 +00:00
FranckyB 28e6299bec fix: NameError 'overrides' not defined in PE resolution fallback
'overrides' is a param of extract_all_from_file(), not in scope inside
PromptExtractor.extract(). Simplified the condition — the _from_node_ref
and bare-512 checks are merged into a single guard, and tensor shape
values are explicitly cast to int.
2026-04-11 21:59:36 +00:00
FranckyB 8cbe4943a1 feat: add Seed B for WAN Video dual-sampler (high/low pass get independent seeds)
WAN Video uses two KSamplerAdvanced nodes (high-pass + low-pass). Previously
both got the same seed value, and extract_sampler_params was returning the
first node it found — the second seed was inaccessible.

Changes:
- extract_sampler_params: collect all KSamplerAdvanced nodes instead of
  returning on first match; expose second node seed as 'seed_b' (None if
  only one node found)
- All seed values are guarded against node-ref lists (isinstance list check)
- build_simplified_workflow_data: includes seed_b in sampler output
- workflow_generator.py (wf_data path): reads seed_b from wf_sampler
- execute(): passes seed_b into patch_params; if seed_b is None for a
  wan_video strategy, falls back to seed (same value for both samplers)
- patch_template: ksampler_high_seed gets seed, ksampler_low_seed gets
  seed_b (falling back to seed if None)
- JS: Seed B row added (hidden by default, shown for WAN Video); Seed row
  label renamed to 'Seed A' when WAN Video is active; seed_b synced,
  applied, and deleted in wfOn mode; _onExecutedSeed applies control mode
  (randomize/increment/decrement) to both seeds independently
2026-04-11 21:52:07 +00:00
FranckyB 09597becc5 fix: PE now reports real source dimensions; propagate node-ref flags through wf_data
Problems:
1. PE showed 512x512 for i2v video — extract_resolution resolved node-refs to
   the ImageResizeKJv2 *input* params (512x512 target), not the actual output.
2. _from_node_ref flags were stripped when building workflow_data JSON output,
   so WorkflowGenerator never saw them from the wf_data path.
3. Defensive guard against list-typed sampler scalars (seed, steps, cfg) that
   could arrive via corrupt override_data JSON.

Fixes:
- prompt_extractor.py: after extract_resolution(), if _from_node_ref is set
  OR resolution is still the bare 512x512 default, overwrite with actual
  image_tensor dimensions (already extracted as the preview frame).
  Applies to any source — videos, images, any file type.
- workflow_extraction_utils.py (build_simplified_workflow_data): propagate
  _width_from_node_ref / _height_from_node_ref into the output resolution
  dict so downstream WorkflowGenerator can use source_image dims.
- workflow_generator.py (wf_data path): pass _from_node_ref flags through
  when building extracted['resolution'] from wf_data.
- workflow_generator.py (sampler_params): guard against list-typed seed/steps/
  cfg values coming through overrides or extracted sampler dict.
2026-04-11 21:44:34 +00:00
FranckyB 0fa7eec08d fix: use source_image dimensions as fallback when template uses node-refs for size
Templates like wan_video_i2v wire WanImageToVideo width/height to the output
of an ImageResizeKJv2 node — these are runtime values, not stored in the JSON.
extract_resolution reads the resize node's *input* params (512x512) which is
the resize target, not the actual output size.

Fix: extract_resolution now sets _width_from_node_ref / _height_from_node_ref
flags when width/height are node references. execute() checks these flags and,
when the user hasn't set an explicit UI override, reads actual dimensions from
the source_image tensor shape ([B, H, W, C]) instead. This correctly handles
i2v (and any future template) where the output size tracks the input image.
2026-04-11 21:37:54 +00:00
FranckyB 3df92b0509 fix: resolve node-ref lists in extract_resolution for i2v/flux2 templates
WanImageToVideo (i2v) and EmptyFlux2LatentImage (flux2) store width/height
as node references (['node_id', output_slot]) instead of scalar ints, because
they're wired to upstream ImageResizeKJv2 / PrimitiveInt nodes. This caused:
  TypeError: int() argument must be a string... not 'list'

Fixes:
- extract_resolution (prompt_data path): resolve node-ref lists by looking up
  the referenced node in prompt_data (handles PrimitiveInt 'value' field and
  ImageResizeKJv2 width/height fields)
- batch_size in WanImageToVideo equals 'length' frames (640) — clamp to 1
  when > 64 to avoid nonsensical batch sizes
- Add EmptyHunyuanLatentVideo to VIDEO_LATENT_TYPES (wan_video_t2v uses it)
- execute(): add _to_int() defensive helper as safety net for any edge cases
  that slip through extract_resolution
2026-04-11 21:25:33 +00:00
FranckyB 1556a07653 fix: add CLIPType mappings for all templates (qwen_image, lumina2/z-image)
Every template's CLIPLoader type now maps to the correct CLIPType enum:
- flux2      → CLIPType.FLUX2
- flux       → CLIPType.FLUX
- sd3        → CLIPType.SD3
- wan        → CLIPType.WAN        (umt5-xxl, vocab 256384)
- qwen_image → CLIPType.QWEN_IMAGE (Qwen2.5-VL image encoder)
- lumina2    → CLIPType.LUMINA2    (z-image / Lumina2 encoder)

Also added qwen_image and zimage to the family detection fallback
in execute() so workflow_data mode picks the right sampler strategy
when the model name isn't found in MODEL_FAMILIES.
2026-04-11 21:21:01 +00:00
FranckyB 64bcb706ae fix: use CLIPType.WAN for wan clip_type to fix umt5-xxl shape mismatch
WAN templates (wan_image, wan_video_t2v, wan_video_i2v) all specify
clip_type='wan' in their CLIPLoader nodes. _load_clip() had no 'wan'
case so it fell through to CLIPType.STABLE_DIFFUSION (vocab 32128),
causing a shape mismatch when loading umt5-xxl (vocab 256384).

Added:
- elif 'wan' in t: CLIPType.WAN in _load_clip()
- elif 'wan' in clip_type: family_key='wan_video_t2v' in execute()
  family fallback (for workflow_data mode with unknown model name)
2026-04-11 21:18:32 +00:00
FranckyB 61a7f6bf45 fix: pass batch_size into patch_template params 2026-04-11 21:11:31 +00:00
FranckyB 2f2be6c075 fix: remove dangling else block that broke node UI rendering 2026-04-11 21:09:31 +00:00
FranckyB f4fa4bebff fix: use class-level model cache so models persist across executions
ComfyUI creates a new node instance on every queue run, so the previous
instance-level _model_cache was always empty. Moving to a class-level
dict keyed by (unique_id, full_path, family_key) makes the cache survive
across runs for the lifetime of the ComfyUI process. Each canvas node
keeps its own slot so multiple WorkflowGenerator nodes don't collide.
2026-04-11 21:07:16 +00:00
FranckyB bac173134b fix: workflow_data mode now always populates all fields from source
syncHidden no longer captures sampler/resolution/prompts as overrides
when use_workflow_data is ON — those values always come from the source.
Stale overrides are cleared on each pre-update. onConfigure no longer
restores overrides in workflow_data mode so cached stale values cannot
block source data from populating the UI.
2026-04-11 21:02:54 +00:00
FranckyB 04e403d93b fix: wan_image now shows wan_video_t2v models via compat group 2026-04-11 20:56:49 +00:00
FranckyBandClaude Opus 4.6 e4d58e59ee feat: detect family from clip_type/loader_type in workflow_data
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-11 20:53:25 +00:00
FranckyB ee2047cac6 Revert "fix: prevent model unloading on every generation"
This reverts commit 6e79a82596.
2026-04-11 20:50:43 +00:00
FranckyBandClaude Opus 4.6 6e79a82596 fix: prevent model unloading on every generation
execute_template() was loading models from disk on every call, bypassing
the WorkflowGenerator's instance-level _model_cache. This caused models
to be fully reloaded (unloaded then loaded from disk) on every generation
run for all template-based families (SDXL, Flux1, Flux2, WAN, etc.).

Pass cached model tuples from WorkflowGenerator._model_cache into
execute_template() so it reuses already-loaded models instead of
reloading from disk each time. Also cache model B in the template
code path (previously only cached in the hardcoded fallback path).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-11 20:36:52 +00:00
FranckyB b0fdbf1a97 fix: move source_image input to last position, matching PromptExtractor 2026-04-11 20:30:38 +00:00
FranckyB d12d8bb484 fix: add bottom padding to prevent selection toolbox overlap
The ComfyUI selection toolbox (~32px tall) renders as a Vue overlay at
the bottom edge of the selected node, covering the last section header.

Fix: paddingBottom: 38px on root div — scrollHeight includes this
padding so computeSize accounts for it automatically, and the toolbox
always has clear space below the last section.
2026-04-11 20:24:48 +00:00
FranckyB b4a41e2340 fix: correct initial node height — defer setSize until DOM is painted
The previous setSize([MIN_W, root.scrollHeight]) fired synchronously at
node creation when the browser hadn't painted yet, so scrollHeight was 0
and the node defaulted to MIN_H=300, clipping the LoRA section.

Fix:
- Defer initial setSize via double rAF so scrollHeight is real
- Add NATIVE_H=90 (title bar ~30px + 2 toggle widgets ~28px each) to
  both the initial setSize and the onResize minimum, so the total node
  height = DOM content + native widgets above it
- onResize now correctly prevents dragging below content + native height
2026-04-11 20:21:30 +00:00
FranckyB 9ccfc23f66 fix: restore collapsible sections, use computeSize pattern for node sizing
The previous session incorrectly replaced the sizing approach with
getHeight/getMinHeight (which is not how ComfyUI works) and removed
collapsible sections as a side-effect.

Root cause of the grey gap was never getHeight — it was that _weRecalc
called setSize() in a loop fighting LiteGraph. The correct pattern
(used by prompt_manager_advanced.js in this very repo) is:

  domW.computeSize = function(width) { return [width, root.scrollHeight]; }
  app.graph.setDirtyCanvas(true, true)  // on any content change

LiteGraph re-queries computeSize on every canvas redraw automatically.
No setSize(), no manual recalc loop, no getHeight/getMinHeight needed.

Changes:
- Restore makeSection() with collapsible chevron + click handler
  (toggle calls setDirtyCanvas so computeSize is re-queried)
- Replace getHeight/getMinHeight with domW.computeSize = f(scrollHeight)
- Restore onResize minimum height enforcement (content height floor)
  so user cannot drag node smaller than visible UI
- Restore initial node.setSize() call to fit content on creation
2026-04-11 20:15:03 +00:00
FranckyB 55b59f876e fix: wan_image now uses same model/vae/clip filtering as wan_video_t2v
WAN 2.2 T2I models are the same files as T2V — same folders, names,
VAE and CLIP patterns.  wan_image was previously a dead stub (names:
["wan_image"]) that matched nothing.

Changes:
- wan_image gets identical folders/names/vae/clip as wan_video_t2v
- Dict order is now i2v → t2v → image so auto-detection hits t2v first
  (first-match wins; user selects wan_image explicitly from dropdown)
- No compat group needed — filtering is identical, model list is the same
- Sampler stays wan_image (single KSampler, no dual Steps rows)
2026-04-11 20:10:32 +00:00
FranckyB 1f348ea4e8 fix: move Sampler section after Model, auto-select first model on family change
- Section order: Resolution → Model → Sampler → Positive → Negative → LoRAs
- onFamilyChanged now auto-selects options[1] (first real model) after reload
  so (none) is never the active selection when models exist
- Also carries forward: collapsible removal, getHeight/getMinHeight resize fix
2026-04-11 20:06:01 +00:00
FranckyB c3b912aa76 fix: UnboundLocalError for has_both_stacks on template path
has_both_stacks was moved into the hardcoded fallback else-block in the
previous VAE/CLIP refactor, but the template path also references it
when calling loras_to_text(). Hoisted the definition above the
if/else split so both paths can use it, and removed the now-duplicate
definition from the else-block.
2026-04-11 19:48:09 +00:00
FranckyB d154fab852 fix: node height cut-off and expand/collapse not resizing
Two related sizing issues:

1. Section expand/collapse did not update node height.
   The toggle handler called _weRecalc() synchronously, so scrollHeight
   was measured before the browser reflowed the newly shown/hidden body.
   Fix: use double-rAF (same pattern as initial setup at line 1445) in
   the click handler AND in _expand/_collapse so the DOM is fully
   reflowed before we measure.

2. Node bottom was cut off (content clipped).
   NATIVE_H=80 underestimated the LiteGraph title bar (~30px) plus the
   two native toggle widgets (~28px each), leaving ~6px short before any
   padding margin. Bumped to 110 to give a small breathing margin.

No structural changes to _resizeNode or the infinite-loop guard.
2026-04-11 19:47:05 +00:00
FranckyB 10e3998230 fix: (Default) VAE/CLIP no longer crashes diffusion model families
Root cause: VAE and CLIP were loaded in Python unconditionally before
the template/fallback branch split. For diffusion model families (flux1,
flux2, wan, ltxv, zimage) _load_model_from_path returns vae_a=None and
clip_a=None (no bundled VAE/CLIP in the diffusion checkpoint). When the
user selected (Default), vae_name was empty / started with '(' and
_load_vae returned None → FileNotFoundError.

Fix in workflow_generator.py:
- Remove the VAE/CLIP load block that was unconditionally before the
  template/fallback branch.
- Template path: execute_template handles its own VAE/CLIP loading from
  the template JSON values, which are already correct (patch_template
  leaves them untouched when (Default) is selected).
- Hardcoded fallback path: VAE/CLIP are now loaded inside the else block
  with a clear, actionable error message if (Default) is used on a
  family that has no bundled VAE.

Fix in workflow_executor.py:
- Improve the VAE not-found error message to tell the user which file
  was expected and where to put it.
2026-04-11 19:39:53 +00:00
FranckyB 30428e3e20 improve: per-family VAE/CLIP compatibility filtering
- Add vae_exact field: exact basename match (prevents ae.safetensors
  matching files like mae.safetensors via substring)
- Add clip_exclude field: disqualifies files matching any exclude pattern
  even when an include pattern also matches (e.g. umt5_xxl contains 't5xxl'
  substring but is excluded from flux1/ltxv via 'umt5' in clip_exclude)
- Add clip_exact field: exact basename match for CLIPs (reserved for future use)

Updated list_compatible_vaes() and list_compatible_clips() to apply
the new fields in priority order (exact → include patterns, with excludes
checked first for CLIPs).

Family-by-family changes:
- flux1:         vae_exact=[ae.safetensors]; clip_exclude=[umt5,clip_g,qwen,gemma]
- flux2:         vae removes ae.safetensors (wrong VAE); clip_exclude=[t5xxl,umt5,clip_l,clip_g,gemma]
- zimage:        vae_exact=[ae.safetensors]; clip narrows to qwen_3_4b only; clip_exclude expanded
- wan_image/i2v/t2v: clip_exclude=[t5xxl,clip_l,clip_g,qwen,gemma]; adds umt5-xxl pattern
- ltxv:          adds ltxv_vae pattern; clip_exclude=[umt5,clip_l,clip_g,qwen,gemma]
- sdxl:          adds vae-ft-mse pattern; clip_exclude=[t5xxl,umt5,qwen,gemma]
- sd15:          expands vae patterns; clip_exclude=[clip_g,t5xxl,umt5,qwen,gemma]
- qwen_image:    clip_exclude=[qwen_3,t5xxl,umt5,clip_l,clip_g,gemma]
2026-04-11 19:34:59 +00:00
FranckyB b171e97a08 fix: preserve user state on execute, VAE/CLIP always (Default) on family switch
BUG 1 — Reset on first execution (manual mode):
  Python was sending ui_info.extracted with the raw empty 'extracted' dict
  (model_a='', positive_prompt='', etc.) instead of the effective values the
  user had set.  In JS the pre-update handler hit sourceChanged=true (since
  prev was null), wiped _weOverrides, and called updateUI() — erasing the
  user's model and prompt.

  Fix (Python): build effective_sampler / effective_resolution / effective_vae /
  effective_clip by merging 'overrides' on top of 'extracted', then send those
  in ui_info so JS always sees what the user actually has set.

  Fix (JS pre-update + onExecuted): when use_workflow_data is OFF, never reset
  UI fields.
  - First execution (no _weExtracted yet): seed _weExtracted with effective info
    but do NOT call updateUI() — user values are already in the DOM.  Just sync
    the family selector and WAN visibility.
  - Subsequent executions: only update metadata (availability, LoRA list) same
    as before.

BUG 2 — VAE/CLIP auto-selected on family change:
  onFamilyChanged was passing d.recommended to reloadGroupedSelect, which
  silently pre-selected a VAE/CLIP file when switching families.  Since all
  families now have workflow templates that embed the correct VAE/CLIP, the
  dropdown must always land on (Default) = empty string so the template value
  is used.

  Fix: always pass null as recommendedValue in reloadVae / reloadClip.
2026-04-11 19:25:36 +00:00
FranckyB 866ca71053 feat: template-driven execution engine + WAN split + collapsible UI
- workflow_executor.py: new in-process template execution engine
  - load_template() / patch_template() / execute_template()
  - WAN Video i2v latent via WanImageToVideo node
  - Dual-step math: total=high+low, high=[0..H], low=[H..100]
  - loras_to_text() for PromptApplyLora JSON serialisation

- workflow_families.py: split wan → wan_image / wan_video_i2v / wan_video_t2v
  - Added FAMILY_WORKFLOW_STEMS mapping family keys to api/ file stems
  - Sampler strategy: wan_image → single KSampler, wan_video → dual KSamplerAdvanced

- tools/convert_to_api.py: UI JSON → API JSON conversion script (8 workflows)

- workflows/api/: 16 new files (api.json + map.json) for:
  flux_1, flux_2, qwen_image, sdxl, wan_image, wan_video_i2v, wan_video_t2v, z_image

- workflow_generator.py:
  - execute() now uses template-driven path first (load_template → patch → execute_template)
  - Falls back to hardcoded samplers when no template exists (sd15, ltxv)
  - Added source_image optional param for WAN i2v
  - Added steps_high / steps_low override parsing from JS
  - Strategy check updated: wan → wan_video for both i2v and t2v

- workflow_generator.js:
  - makeSection(): collapsible with chevron toggle, all start collapsed
  - updateWanVisibility(): handles wan_image / wan_video_i2v / wan_video_t2v
  - Steps (High) / Steps (Low) rows added to SAMPLER section (WAN Video only)
  - Standard Steps row hidden when WAN Video family selected
  - LoRA Stack A title: 'LoRA Stack (High)' for WAN Video, 'LoRA Stack' otherwise
  - LoRA Stack B: visible only for wan_video_i2v / wan_video_t2v
  - Model B row: visible only for WAN Video families
  - syncHidden(), applyOverrides(), updateUI() updated for steps_high/steps_low
  - Section _setNode() wired up after _weRecalc is defined
2026-04-11 19:02:59 +00:00
THE_BEAST\me 3aa373be3b Modified Prompt Apply Lora, so it can take text enties, either traditional Lora list, or simply path to loras on disk. For Testing Lora generation.
Added new workflows for video and image processing
2026-04-11 14:11:01 -04:00
THE_BEAST\me 1db335d88b refactor: improve code readability by restructuring try-except blocks and formatting print statements 2026-04-11 12:03:56 -04:00
THE_BEAST\me ec4cf272ce feat: enhance prompt extraction and workflow generation with A1111 parameter mapping and embedded data handling 2026-04-11 06:48:59 -04:00
THE_BEAST\me 2e195cfa01 feat: implement update functionality to pull data from connected sources in WorkflowGenerator 2026-04-11 04:26:08 -04:00
THE_BEAST\me 2a3ed8c52c fix: adjust minimum width for DOM widget to improve layout consistency 2026-04-11 02:28:22 -04:00
THE_BEAST\me 41cdfa16c3 feat: add critical rules for DOM widget sizing and resizing in ComfyUI 2026-04-11 02:15:18 -04:00
THE_BEAST\me 7b87283fcd feat: improve UI responsiveness by pushing updates before generation and enhance error handling during model loading 2026-04-11 02:09:40 -04:00
THE_BEAST\me e9d0797d67 feat: enhance model loading and workflow generation with improved handling of workflow_data and LoRA inputs 2026-04-11 01:03:41 -04:00
THE_BEAST\me bfa92d7007 feat: enhance workflow data handling with model and LoRA availability checks 2026-04-11 00:27:24 -04:00
THE_BEAST\me 1c12d99a33 Add LoRA utility functions for fuzzy matching and path resolution
- Implemented functions to retrieve available LoRA files and normalize path separators.
- Added fuzzy matching logic to handle renamed LoRAs and WAN-related tokens.
- Created functions to strip file extensions, normalize names, and resolve LoRA paths.
- Enhanced compatibility with ComfyUI's folder structure for loading LoRAs.
2026-04-10 22:42:49 -04:00
THE_BEAST\me 173b2aceed feat: add workflow extraction utilities for ComfyUI Prompt Manager
- Implemented shared extraction helpers for sampler parameters, VAE info, CLIP info, resolution, and model resolution.
- Added functions to extract sampler parameters, VAE loader information, CLIP loader information, and image/video resolution.
- Introduced model name resolution functions for models, VAEs, and CLIPs.
- Created a comprehensive extraction function to gather all generation parameters from various file types.
- Included a function to enrich extraction results with availability flags for LoRAs, models, VAE, and CLIP.
- Built a simplified workflow data structure for use in WorkflowGenerator and PromptExtractor nodes.
2026-04-10 17:48:05 -04:00
FranckyB a0a886c8a8 fix: Klein CLIPType.FLUX2 shape mismatch + model caching
workflow_families.py:
- flux2 family: replace wrong clip list (mistral/clip_l) with correct
  Qwen encoders (qwen_3_4b, qwen_3_8b) per official ComfyUI Klein docs
- Add clip_type: "flux2" to flux2 family spec for fallback when
  extracted workflow doesn't carry a CLIPLoader type field

workflow_extractor.py:
- _load_clip: check 'flux2' BEFORE 'flux' when mapping to CLIPType —
  'flux2' contains 'flux' so the old order always picked CLIPType.FLUX,
  causing the 2048x15360 vs 12288x4096 shape mismatch with Klein's
  Qwen text encoder. CLIPType.FLUX2 is now correctly used for flux2.
- _load_clip call site: if extracted clip has no type, fall back to the
  family spec's clip_type (flux2 family -> 'flux2' -> CLIPType.FLUX2)
- WorkflowGenerator.__init__: add _model_cache dict keyed by
  (full_path, family_key) so models are only loaded from disk once per
  node instance — subsequent generations with the same model reuse the
  cached patcher, matching how standard ComfyUI loader nodes behave
2026-04-10 18:34:01 +00:00
FranckyB 7c4c1f9172 fix: Klein weights_only error + remove Extract button
workflow_extractor.py:
- _load_model_from_path: wrap load_diffusion_model in try/except;
  on weights_only/UnpicklingError (PyTorch >= 2.6 with .pt/.bin Klein
  models), retry with torch.load(weights_only=False) + load_diffusion_
  model_state_dict. Safe since these are trusted local model files.

workflow_extractor.js:
- Remove 'Extract Parameters' button — extraction runs automatically
  on image select, the manual button is redundant
- Remove EXTRACT_BTN_H constant and its contribution to recalcHeight
2026-04-10 18:23:56 +00:00
FranckyB 5224d650e8 fix(workflow-extractor): allow preview expansion + add 4px bottom padding
- computeSize now uses Math.max(node.size[1], _domH+NATIVE_H) so ComfyUI's
  live generation preview can expand the node without being clamped back
- PADDING 16 → 20 to add 4px breathing room at the bottom of the UI
2026-04-10 18:12:52 +00:00
FranckyB 02246e0612 fix(workflow-extractor): remove statusEl + guard computeSize to fix chin
Three changes to eliminate the 'chin' (node growing blank space at bottom
when mouse moves over it):

1. Remove statusEl entirely — it had minHeight:14px that always added space
   even when empty, slightly distorting the constant-based height math.
   Also removes STATUS_H (18px) from recalcHeight calculation.

2. Add no-op guard in recalcHeight: skip setSize when computed height
   hasn't changed (h === _domH). Prevents spurious setSize calls that
   trigger LiteGraph redraws on mouse enter/leave hover state changes.

3. Override node.computeSize to always return the exact stored _domH
   (not the LiteGraph-derived value). LiteGraph calls computeSize on
   every render frame to check node dimensions — the old impl called
   _origComputeSize which may return a slightly larger value due to
   widget spacing math, causing the node to grow one pixel at a time
   on each frame triggered by onMouseMove's setDirtyCanvas call.
2026-04-10 18:04:39 +00:00
FranckyB 323ece55e8 revert(workflow-extractor): restore original recalcHeight, keep onExecuted
Revert JS height calculation to the proven constant-based approach from 516a226.
The scrollHeight and offsetHeight experiments both caused node collapse.

Kept: onExecuted handler (routes generated image into _weThumbEl, blocks
ComfyUI's default preview injection below the node).
2026-04-10 17:57:47 +00:00
FranckyB 2419567353 fix(workflow-extractor): fix chin/gap — offsetHeight per child + guard against no-op setSize
Two issues:
1. Manual constant math (SEC_HEAD_H, BTN_H, etc.) was overcounting because
   section wrap has marginTop:2px which is outside offsetHeight but still
   consumed space, and flex gap interacts with it unpredictably.

   Fix: iterate root.children, use child.offsetHeight (accurate, not constrained
   by parent), count visible children for gap math. Simple and correct.

2. recalcHeight() calling setSize() even when nothing changed caused ComfyUI
   to re-layout the node on every click/focus, which could expand the node
   slightly each time (the 'chin' effect).

   Fix: only call setSize when newH !== _domH.
2026-04-10 17:55:06 +00:00
FranckyB 2ce93a326a fix(workflow-extractor): fix node shrink loop — compute height from children not root
root.scrollHeight causes a feedback loop: ComfyUI constrains root's height,
scrollHeight shrinks, we report smaller, ComfyUI shrinks more → node collapses.

Fix: compute _domH by summing the intrinsic heights of our own child elements
(button + sections + status + thumb). sec._body.scrollHeight IS reliable
because those inner elements are not constrained by ComfyUI.

_domH is the authority — computeSize returns it directly, never root.scrollHeight.
2026-04-10 17:45:06 +00:00
FranckyB 32400171de fix: gap below KSampler + shared workflow_data format for both nodes
js/workflow_extractor.js:
- Replace manual constant-based recalcHeight() with root.scrollHeight
  (source of truth — no more HEADER_H / EXTRACT_BTN_H / STATUS_H / PADDING guessing)
- Same in domW.computeSize and node.computeSize — all read root.scrollHeight
- Add onExecuted handler: intercepts ComfyUI's auto-preview injection,
  routes generated image into our own _weThumbEl, prevents gap below node

py/workflow_extractor_utils.py:
- Add build_simplified_workflow_data() — shared function that builds the
  canonical workflow_data dict schema (same output from both nodes)

nodes/workflow_extractor.py:
- Remove local _build_simplified_workflow_json (replaced by shared util)
- Import and use build_simplified_workflow_data from py/

nodes/prompt_extractor.py:
- Replace raw JSON dump with call to extract_sampler_params / extract_vae_info
  / extract_clip_info / extract_resolution + build_simplified_workflow_data
- PromptExtractor now outputs workflow_data in identical format to WorkflowGenerator
  (can be used as input to PromptManagerAdvanced to save entire workflows)
2026-04-10 17:33:18 +00:00
FranckyB 516a226f5f fix: correct node name prefix + rename metadata_json to workflow_data
- js/workflow_extractor.js: fix extension name from FBnodes.WorkflowGenerator
  to WorkflowGenerator (matches all other nodes in this package)
- nodes/prompt_extractor.py: rename output metadata_json -> workflow_data
  in RETURN_NAMES and all references in extract(), so both PromptExtractor
  and WorkflowGenerator output the same workflow_data type
2026-04-10 17:11:15 +00:00
FranckyB d6a75f2d70 refactor(workflow-extractor): rename to WorkflowGenerator + major refactor
- Rename node class WorkflowExtractor → WorkflowGenerator
- Remove WorkflowManager and WorkflowGenerator nodes (js + py + __init__)
- Set node creation width to 450px
- Rename workflow_json → workflow_data in RETURN_NAMES and execute()
- Fix INPUT_TYPES: source_folder defaults None, image defaults (none)
- Fix list-files endpoint: JS now calls /workflow-extractor/list-files
- Fix image source filter: input-only at startup (like PromptExtractor)
- Add standalone mode: execute() works without an image using defaults
- Remove denoise from UI; always force 1.0 in execute()
- Update __init__.py registrations
2026-04-10 17:00:35 +00:00
FranckyB 84bf5065d9 fix(workflow-extractor): replace broken Flux2Scheduler with BasicScheduler('beta')
Flux2Scheduler.execute(cls, steps, width, height) is a dimension-based class
method that cannot be called as an instance with get_sigmas() — it has no such
method. Replace the entire Flux2Scheduler usage with BasicScheduler using the
'beta' schedule, which is the correct programmatic equivalent for Flux2/Klein.
Scheduler name is read from sampler_params so extracted workflows pass it
through; defaults to 'beta'.
2026-04-10 16:44:17 +00:00
FranckyB 9ec65b7d8b fix(workflow-extractor): true gap fix via marginTop -10px + green/red workflow status dot
- Gap: root element now uses marginTop:-10px (same technique as Prompt Manager
  button container) to cancel the ~10px ComfyUI injects above every DOM widget.
  Removed the previous padding-toggle approach which was fighting the wrong cause.
- Status dot: green/red circle in title bar (identical to Prompt Extractor).
  Shows as soon as an image is selected. Green = workflow found after Extract,
  red = no workflow found or extract failed. Dot is restored from cache on page
  reload. Triangle shifts left 24px to make room when dot is visible.
2026-04-10 16:33:12 +00:00
FranckyB 08d21b0961 fix(workflow-extractor): thumbnail gap, VAE/CLIP filtering + recommended, thumb restore on refresh
- Fix 1: root padding changed to '0 6px 6px 6px'; loadThumbnail toggles
  paddingTop via node._weRoot so thumb sits flush under Browse Files button
- Fix 2: reloadGroupedSelect now prepends (Default)/value='' for VAE/CLIP rows;
  onFamilyChanged uses reloadVae/reloadClip helpers that fetch recommended from
  API and auto-select best matching file on disk
- Fix 3: list_compatible_vaes/clips gain return_recommended param; endpoints
  return {vaes/clips: [...], recommended: str|null} for first pattern match
- Fix 4: onConfigure calls loadThumbnail(node, img) on refresh when thumb not
  already loaded, restoring the preview after page reload
2026-04-10 16:00:14 +00:00
FranckyBandClaude Opus 4.6 e7c727f102 fix(workflow-extractor): thumb gap, node height, Model A/B, LoRA stacks match PMA UI exactly
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-10 15:26:07 +00:00
FranckyBandClaude Opus 4.6 639091fd17 fix(workflow-extractor): wider node, video thumbnail, preview arrow, checkpoint B, VAE/CLIP defaults
- Node width 440→560 to fit LoRA tags properly
- loadThumbnail: video-aware (browser canvas + server fallback via /video-frame API)
- Add /workflow-extractor/video-frame Python endpoint (PyAV + ffmpeg fallback)
- Preview arrow in title bar (triangle icon) → opens image/video modal on click
- Checkpoint B always visible (shows '(none)' when source has no model B)
- VAE/CLIP dropdowns: show '(Default)' sentinel instead of '—', lazy-load filters by family
- Family change reloads model B dropdown unconditionally

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-10 15:00:25 +00:00
FranckyB 977ec9785b refactor: slim down model families, fix sampling strategies per family
- Merge Flux1 variants (dev/schnell/generic) into single 'flux1' family
- Merge Flux2/Klein variants into single 'flux2' family
- Merge SDXL/Pony/Illustrious/SDXLTurbo into single 'sdxl' family
- Merge Z-Image Base/Turbo into single 'zimage' family
- Remove: SD2, SD3, SD3.5, CogVideo, Mochi, HunyuanVideo, Stable Cascade, Kolors, PixArt, AuraFlow
- LTX-Video: correct sampler strategy to flux (SamplerCustomAdvanced)
- WAN: add ModelSamplingSD3 shift=5.0 before dual KSampler passes
- Flux2/Klein: add _run_flux2_sampler() using Flux2Scheduler + CFGGuider
- Fix node sizing: NATIVE_H 104→108 (LiteGraph title bar is 30px not 26px)
- Update PADDING 20→26 to account for flex gaps between sections
2026-04-10 14:30:40 +00:00
FranckyB ca06e1273b feat: add WorkflowManager + WorkflowGenerator nodes, shared py/ layer, family-aware sampling
- Add py/workflow_families.py: MODEL_FAMILIES dict with sampler strategy per family
  (standard, flux, flux2, wan), compatibility groups, model/VAE/CLIP listing helpers

- Add py/workflow_extractor_utils.py: shared extraction helpers used by WorkflowExtractor
  and WorkflowGenerator (extract_sampler_params, extract_vae_info, extract_clip_info,
  extract_resolution, resolve_model_name, resolve_vae_name, resolve_clip_names,
  extract_all_from_file, enrich_with_availability)

- Add py/workflow_node_utils.py: thin re-export of build_node_map/build_link_map

- Refactor nodes/workflow_extractor.py: import from py/, family-aware sampling strategies
  (_run_standard_ksampler, _run_flux_sampler, _run_wan_sampler), WORKFLOW_JSON as
  third output (IMAGE, LATENT, STRING)

- Add nodes/workflow_manager.py: WorkflowManager node - big brother of PM Advanced,
  adds workflow_config key to shared JSON store, outputs prompt + lora_stack_a/b + WORKFLOW_DICT

- Add nodes/workflow_generator.py: WorkflowGenerator node - accepts WORKFLOW_DICT from
  WorkflowManager or manual config, family-aware sampling, outputs IMAGE + LATENT + WORKFLOW_JSON,
  supports WAN dual-sampler, Flux, Flux2, Standard strategies

- Add js/workflow_manager.js: DOM widget panel with family selector, model A/B dropdowns,
  VAE, CLIP, sampler + resolution overrides, Save Config button, state in node.properties

- Add js/workflow_generator.js: status badge (auto vs manual mode), generation feedback

- Patch nodes/prompt_manager_advanced.py: preserve guard in save_prompt_advanced() copies
  any unknown keys (e.g. workflow_config) back into prompt_data so WorkflowManager data
  survives edits from PM Advanced

- Update __init__.py: register WorkflowManager + WorkflowGenerator, bump version to 1.23.0
2026-04-10 13:53:10 +00:00
THE_BEAST\me c2c38e5b9d Merge branch 'dev' of https://github.com/FranckyB/ComfyUI-Prompt-Manager into dev 2026-04-10 08:41:16 -04:00
THE_BEAST\me 6ddf0108be fix: improve LoRA application logic and adjust latent tensor creation parameters 2026-04-10 08:40:04 -04:00
THE_BEAST\me 52990491f3 Improved Tab Switching Code 2026-04-09 21:19:33 -04:00
THE_BEAST\me 3a49fdfa97 First Wip of Workflow Extractor 2026-04-09 15:55:11 -04:00
THE_BEAST\me b98155543b feat: enhance extracted data handling in PromptExtractor and add validation tests 2026-04-08 00:27:17 -04:00
THE_BEAST\me 74716182ce feat: enhance model resolution logic in PromptModelLoader and PromptExtractor 2026-04-07 23:55:44 -04:00
Francois Beaudry d7adb9f5c0 Merge pull request #24 from FranckyB/dev
feat: enhance PromptExtractor to support embedded data extraction and model tracking
2026-04-07 22:28:17 -04:00
THE_BEAST\me c8e103152b feat: enhance PromptExtractor to support embedded data extraction and model tracking 2026-04-07 22:17:40 -04:00
Francois Beaudry 1c3aa77889 Merge pull request #23 from FranckyB/dev
Dev
2026-04-07 01:09:53 -04:00
THE_BEAST\me 501b962408 feat: add thumbnail generation feature in Prompt Manager
- Implement right-click option to generate thumbnails for prompts
- Introduce checkpoint selection for thumbnail generation
- Enhance API endpoints for listing checkpoints and resolving LoRAs
- Update version to 1.22.5
2026-04-07 01:07:05 -04:00
THE_BEAST\me 34df0b0675 fix: enhance prompt extraction logic for low and high model detection 2026-04-06 22:49:01 -04:00
THE_BEAST\me a7bdec56d3 - **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
2026-04-06 21:58:36 -04:00
THE_BEAST\me 41e4c27416 fix: reorder return names in PromptExtractor for consistent output structure 2026-04-06 02:24:16 -04:00
THE_BEAST\me c34fda023c - **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
2026-04-06 02:13:15 -04:00
THE_BEAST\me 6de8bddea5 feat: enhance metadata extraction for JPEG and WebP files in prompt extractor 2026-04-06 00:04:30 -04:00
THE_BEAST\me 1fea03858e refactor: rearrange and update images in README for Prompt Generator usage 2026-04-05 15:53:10 -04:00
THE_BEAST\me 16c01efb0d raise RuntimeError for error handling 2026-04-05 05:52:58 -04:00
THE_BEAST\me f9b7c601f9 prompt extractor:
enhance video thumbnail extraction and error handling for unsupported formats

Prompt Generator:
Improve llama-server startup handling and fix docstring
- 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)
2026-04-05 05:10:32 -04:00
THE_BEAST\me cb6276ded0 Updated workflow 2026-04-02 12:40:38 -04:00
THE_BEAST\me 894f44d4b5 - **Speed Improvement**: Thumbnail generation now uses server-side PyAV instead of browser-based video decoding — substantially faster, especially with many clips. 2026-04-01 02:16:51 -04:00
THE_BEAST\me 7e1a45fa3c feat: update version to 1.21.1 and fix issues caused by restructure 2026-04-01 00:02:12 -04:00
THE_BEAST\me 616746e07f feat: enhance video frame extraction with server-side fallback for H265/yuv444 formats and update prompts path resolution 2026-03-31 23:32:25 -04:00
THE_BEAST\me 4cdb3a0d68 ### 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
2026-03-31 23:16:02 -04:00
THE_BEAST\me c4eb347b56 feat: enhance video metadata extraction to support source folder selection and refresh file list for output 2026-03-28 00:06:01 -04:00
THE_BEAST\me 356f3af597 feat: recheck LoRA availability after restoring state and remove unused condition handling in SwitchAny 2026-03-27 19:48:56 -04:00
THE_BEAST\me 9be7636d61 feat: Add Better Image Loader node and enhance Prompt Extractor
- Introduced a new node: Better Image Loader for streamlined image and video loading without metadata extraction.
- Enhanced Prompt Extractor with input/output folder switching and improved file browsing capabilities.
- Updated README to reflect new features and changes.
- Fixed various bugs related to folder switching and file extraction.
- Updated version to 1.20.0 in all relevant files.
2026-03-27 16:33:21 -04:00
THE_BEAST\me 6ddf7321a0 feat: add refresh functionality to SwitchAny node and enable output node for SwitchAnyBool 2026-03-27 15:33:30 -04:00
THE_BEAST\me 0af9387da5 feat: remove thumbnail preview toggle button and associated functionality from thumbnail browser 2026-03-27 14:24:31 -04:00
THE_BEAST\me e08f295c25 feat: enhance file browser modal to open in selected subfolder and scroll to selected file 2026-03-25 11:19:48 -04:00
THE_BEAST\me ae5e46fccc feat: add SwitchAnyBool node for boolean input handling in Switch Any 2026-03-21 16:06:50 -04:00
THE_BEAST\me 32a54c4ff0 feat: introduce Switch Any node with customizable inputs and lazy evaluation support 2026-03-21 13:17:33 -04:00
THE_BEAST\me cca1753f10 feat: prevent overwriting node state on workflow restore by adding configuration flag 2026-03-21 11:38:36 -04:00
THE_BEAST\me 81362756b4 feat: enhance metadata extraction and update return types in PromptExtractor 2026-03-20 11:54:52 -04:00
THE_BEAST\me fb1d32d503 feat: add option to use only connected LoRA inputs, skipping extraction 2026-03-18 21:36:52 -04:00
THE_BEAST\me ea21779258 fix: allow negative values for Lora strength input 2026-03-18 21:18:30 -04:00
THE_BEAST\me 6ad2986746 feat: update to version 1.18.0 with thumbnail hover preview and improved thumbnail quality 2026-03-17 23:36:34 -04:00
THE_BEAST\me e80c5bce0e feat: add option to enable thumbnail hover preview in advanced preferences 2026-03-17 23:30:56 -04:00
THE_BEAST\me 88f2e1b109 feat: enhance thumbnail preview system and improve image resizing logic 2026-03-17 09:36:03 -04:00
THE_BEAST\me 6aa194ff95 fix: error in variable when logging error 2026-03-16 01:04:28 -04:00
THE_BEAST\me 3731b4c228 feat: add context menu for video thumbnails with refresh option and reset frame position on new video selection 2026-03-10 02:07:46 -04:00
THE_BEAST\me 8062ede1cd feat: update to version 1.17.6 with LoRA stack output swapping and input handling fixes 2026-03-08 21:22:48 -04:00
THE_BEAST\me 7496c8fd65 fix: streamline LoRA input handling by preserving saved loras from presets 2026-03-08 21:13:01 -04:00
THE_BEAST\me f82ff068e1 feat: add swap functionality for LoRA outputs in prompt manager
fix: Issue with disabling loras, when no lora input is used.
2026-03-08 21:04:15 -04:00
THE_BEAST\me 1029c79881 feat: added back delete prompt functionality to the dropdown menu with confirmation dialog 2026-03-08 16:50:31 -04:00
THE_BEAST\me f20af63926 fix: set default category selection in prompt dialog after DOM build 2026-03-08 16:36:44 -04:00
THE_BEAST\me 82b19c71de fix: tweaked LoRA configuration retrieval by using last-executed state from backend. 2026-03-08 16:22:46 -04:00
THE_BEAST\me 76c30404a8 feat: enhance latent preview initialization handling and improve model identity extraction logic 2026-03-07 18:36:52 -05:00
THE_BEAST\me 10cb9d2bb0 feat: add rename and move prompt functionality to context menu and API 2026-03-07 12:48:44 -05:00
Francois Beaudry e20f6523d9 Merge pull request #16 from FranckyB/dev
Dev
2026-03-07 12:26:36 -05:00
THE_BEAST\me d7fde3cce4 chore: update version to 1.17.5 and enhance browser context menu with delete and rename options 2026-03-07 12:21:57 -05:00
THE_BEAST\me bf0edbabc9 fixed Issue with NSFW prompts preventing opening our Prompt Selector in some instances. Added Option to Delete and Create Categories directly in the Selector UI. 2026-03-07 12:11:55 -05:00
THE_BEAST\me ed78a1bf05 ### version 1.17.0
- **NSFW Tagging & Filtering**
  - Mark entire categories or individual prompts as NSFW
  - Visual red "NSFW" badge on the Prompt Manager node title bar and on the Advanced prompt selector
  - NSFW badge appears on all prompts within an NSFW-tagged category in the thumbnail browser
  - Category buttons show red border for NSFW categories in the thumbnail browser
  - Global preference to hide/show NSFW content — filters dropdowns, navigation arrows, and browser
  - Session-persistent NSFW toggle button in the Advanced thumbnail browser
  - Toggle NSFW on categories and prompts via context menu or the save/new category dialogs
- **List View Mode**
  - New compact list view alternative to the thumbnail grid in the Advanced prompt browser
  - Toggle between grid and list view with a button in the browser controls bar
  - View mode preference is session-persistent
  - Default view mode configurable in ComfyUI settings
- **UI Improvements**
  - Search input moved into the controls bar with a clear (×) button
  - Separator line between category buttons and prompt content
2026-03-07 01:39:45 -05:00
THE_BEAST\me 698cd7b725 - **Ollama Support**
- Added Ollama as an alternative LLM backend alongside llama.cpp
  - Auto-discovers available Ollama models when no model is explicitly configured
  - Keep-alive duration setting controls how long Ollama keeps the model loaded in memory
  - "Stop server after" toggle unloads the model from Ollama memory to free VRAM
- **Upgraded to Qwen3.5 Models**
  - Replaced Qwen3/Qwen3VL models with unified Qwen3.5-9B (vision+text in one model)
  - Three download options: UD-Q4_K_XL (~6GB), Q8_0 (~9.5GB), UD-Q8_K_XL (~13GB)
  - Thinking mode is now a runtime toggle — no separate model variant needed
- **mmproj-Based Vision Detection**
  - Vision model detection no longer relies on "VL" in the filename
  - Models are identified as vision-capable based on the presence of an mmproj file
  - Heuristic matching supports user-provided models outside the predefined registry
  - Backward compatible with existing Qwen3VL models and their mmproj files
- **Bug Fixes**
  - Fixed seed control_after_generate not working (increment/decrement/randomize)
  - Improved Prompt Extractor detection logic
2026-03-04 00:45:35 -05:00
THE_BEAST\me d93c2713d5 Fix: Enhance prompt classification logic
(Recent changes introduced error in getting prompt)
Bump version to 1.15.9 and update changelog
2026-02-22 10:55:32 -05:00
THE_BEAST\me dc971491d1 Remove redundant dependencies already provided by ComfyUI 2026-02-18 08:44:50 -05:00
THE_BEAST\me f5391da99a Updated version number 2026-02-18 01:16:52 -05:00
THE_BEAST\me 539828c8af feat: Enhance LoRA extraction logic in workflow parsing 2026-02-18 00:46:01 -05:00
THE_BEAST\me 16192ad6dd Wan Worflow Broke again somehow?! 2026-02-17 22:04:48 -05:00
THE_BEAST\me 4dad2816d0 feat: Add category renaming functionality and improve prompt management UI 2026-02-17 19:58:15 -05:00
THE_BEAST\me d1967d8395 feat: Video Metadata Reader - VHS Compatible 2026-02-16 22:06:44 -05:00
THE_BEAST\me ad1a4290bc Enabled Loras in Wan Worfklow 2026-02-15 22:47:11 -05:00
THE_BEAST\me e800b272cc Fix flipped connectioin on Wan Workflow 2026-02-15 22:41:52 -05:00
THE_BEAST\me 4b93b7902d Merge branch 'main' of https://github.com/FranckyB/ComfyUI-Prompt-Manager 2026-02-15 22:34:25 -05:00
THE_BEAST\me 04808107c2 feat: new video preview features on extractor node 2026-02-15 22:34:22 -05:00
Francois Beaudry 376e973ba0 Delete .github/workflows/FUNDING.yml 2026-02-15 20:47:18 -05:00
THE_BEAST\me 0e4ca673fc feat: Add GetVideoComponentsPlus node for extracting video components and matching latent files 2026-02-15 20:36:45 -05:00
Francois Beaudry 70dc0e38e0 Update GitHub Sponsors username in FUNDING.yml 2026-02-07 10:07:19 -05:00
Francois Beaudry 0297da28e6 Add files via upload 2026-02-07 10:06:21 -05:00
THE_BEAST\me f72bbc35cd chore: Bump version to 1.15.0 in pyproject.toml 2026-02-02 23:15:11 -05:00
THE_BEAST\me 052b88c33f feat: Add video saving and animated latent preview features to README 2026-02-02 23:12:21 -05:00
THE_BEAST\me 6d6f09f82d Reverted to allowing latent_preview to catch all. Allows for better batch display 2026-02-02 23:05:54 -05:00
THE_BEAST\me 0239663a38 added exclusion of non 5D tensors, so so latent preview doest activate on images. Updated Wan Workflow 2026-02-02 22:33:51 -05:00
THE_BEAST\me 958658f2c3 feat: Enhance WrappedPreviewer to support Latent2RGB batch processing for improved video previews 2026-02-02 21:26:52 -05:00
THE_BEAST\me 186a4fc7e4 feat: Add latent preview functionality for animated video sampling and fixed unsaved changes warning preferences 2026-02-02 20:49:27 -05:00
THE_BEAST\me 2de7c3c9a3 Add new WAN workflow configuration for video processing and prompt generation. Small fixes 2026-02-01 18:19:24 -05:00
THE_BEAST\me 55b6f2f94e feat: Add Save Video H264/H265 node with quality control and metadata support 2026-01-16 17:30:15 -05:00
THE_BEAST\me a1c3b59bad feat: Improve image loading by handling placeholder display in Prompt Extractor 2026-01-16 08:27:02 -05:00
THE_BEAST\me 3342d843e5 feat: Enhance prompt management by adding trigger words handling during reset 2026-01-15 00:21:55 -05:00
THE_BEAST\me 482f5c182d feat: Preserve existing thumbnail when saving prompts with case-insensitive names 2026-01-14 23:42:49 -05:00
THE_BEAST\me 88dadfd4d5 feat: Enhance LoRA extraction to support subgraphs 2026-01-14 23:36:58 -05:00
THE_BEAST\me e4868e1ea1 feat: Implement extraction for WanVideoLoraSelectMulti and add tests for all LoRA loader types 2026-01-14 21:19:47 -05:00
81 changed files with 36235 additions and 4204 deletions
+15
View File
@@ -0,0 +1,15 @@
# These are supported funding model platforms
github: franckyb # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
patreon: # Replace with a single Patreon username
open_collective: # Replace with a single Open Collective username
ko_fi: # Replace with a single Ko-fi username
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
liberapay: # Replace with a single Liberapay username
issuehunt: # Replace with a single IssueHunt username
lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry
polar: # Replace with a single Polar username
buy_me_a_coffee: # Replace with a single Buy Me a Coffee username
thanks_dev: # Replace with a single thanks.dev username
custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
+2
View File
@@ -3,6 +3,7 @@ __pycache__/
*.pyc
*.pyo
*.pyd
.venv/
.Python
build/
develop-eggs/
@@ -26,6 +27,7 @@ wheels/
# IDE files
.vscode/
.idea/
ComfyUI-Prompt-Manager.code-workspace
# OS files
.DS_Store
+128 -339
View File
@@ -1,93 +1,137 @@
# 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 recipe toolkit for [ComfyUI](https://github.com/comfyanonymous/ComfyUI)
A complete prompt management solution featuring three core capabilities:
ComfyUI Prompt Manager is an all-in-one prompt and recipe toolkit for ComfyUI, built for creating recipes from scratch or by extracting core workflow elements from Images and Videos with embedded workflows. It includes local LLM-powered prompt generation (llama.cpp or Ollama) with automatic download of Qwen3.5 models, LoRA stack tooling, and end-to-end Recipe nodes to build, edit, render, save, and reuse repeatable generation pipelines. It can extract core metadata from media generated in ComfyUI, A1111, and Forge, supporting Wan Workflows with dual model/stack support.
**Prompt Manager** — Save and organize prompts with categories, simple UI with minimal feature.
> **Naming Update (v2.1):**
> We have shifted from using the term "Workflow" to "Recipe" for this toolset.
> This is an unfortunate but needed naming change to better represent the purpose of this tool.
**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.
> **New in v2.5.0:**
> Recipe Builder can now setup Multi Model all in one Node. Gone is the need to stack multiple Builder nodes when setting multi model workflows.
> You can build and route `model_a` through `model_d` in one node, keep per-slot prompts/LoRAs/sampler data, and extract Builder-authored recipes from media with v2 metadata preserved as the authoritative source.
> Added a New Multi Lora Stack node, that is based on Lora-Manager and works with it. Simply select the column you want to add to and then added loras with be added to it.
> This new Multi Model may break combatibility wirh previous workflows, but this is now MUCH closer to the initial visioin! One node to build the entire Recipe.
**Prompt Generator** — Generate and enhance prompts using local LLMs via [llama.cpp](https://github.com/ggerganov/llama.cpp). Supports text enhancement, image analysis with vision models (Qwen3VL), and thinking mode for deeper reasoning. Analyze up to 5 images at once.
## What This Provides
**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 tools**: Prompt Manager, Prompt Extractor
- **Local LLM support**: Prompt Generator using llama.cpp or Ollama. Supports text enhancement and image analysis with vision models (Qwen3.5)
- **Recipe tools**: Recipe Extractor, Recipe Builder, Recipe Builder (WAN), Recipe Hub, Recipe Relay, Recipe Renderer, Recipe Model Loader, Recipe Manager
- **LoRA workflow support**: Display and modify added Loras. When reusing Saved presets, values can still be changed.
- **Model support**: Recipe Renderer supports: Flux 1/2, Ernie, SDXL, Wan, Qwen, Z-Image, Wan Image, Wan Video (I2V/T2V)
- **Lora Preview**: When [Lora-Manager](https://github.com/willmiao/ComfyUI-Lora-Manager) is installed, LoRAs can be previewed on hover.
- **Prompt Browser**: Includes a Browser to easily find and select your prompts or Recipes.
- **Advance Image Loader**: Extractors can serve as advanced Image loaders, loading from Input or Ouput.
---
<div align="center">
<figcaption>Simple Prompt Generator Usage</figcaption>
<img src="docs/prompt_manager.png" alt="Prompt Manager">
<figcaption>Prompt Creation With Lora and Trigger Words</figcaption>
<img src="docs/images/prompt_generator_text.png" alt="Prompt Manager">
</div>
<div align="center">
<figcaption>Advanced Prompt Generator Usage</figcaption>
<img src="docs/prompt_generator_advanced.png" alt="Prompt Manager">
<figcaption>Generating Prompts based on Images</figcaption>
<img src="docs/images/prompt_generator_image.png" alt="Prompt Generator">
</div>
<div align="center">
<figcaption>Prompt Manager Advanced, with Lora and trigger word support</figcaption>
<img src="docs/prompt_manager_advanced.png" alt="Prompt Manager">
<figcaption>Advanced Prompt Generation using Multiple Images</figcaption>
<img src="docs/images/prompt_generator_advanced.png" alt="Prompt Generator">
</div>
<div align="center">
<figcaption>Prompt Extractor connected to Manager Advanced, so workflow can be saved with Loras</figcaption>
<img src="docs/prompt_extractor.png" alt="Prompt Manager">
<figcaption>Recipe extraction and modifcation (Adding a Style Lora)</figcaption>
<img src="docs/images/workflow_builder.png" alt="Recipe Builder">
</div>
### Key features:
### Prompt Manager:
- **Category Organization**: Create and manage multiple categories to organize your prompts
- **Save & Load Prompts**: Quickly save and recall your favorite prompts with custom names
- **LLM Input Toggle**: Connect text outputs from other nodes and toggle between using them or your internal prompts
- **LLM Input Toggle**: When in use, display of categories and prompt is disabled, allowing user to switch category and save.
- **Persistent Storage**: All prompts saved in your ComfyUI user folder
<div align="center">
<figcaption>Easily find saved Prompts & Recipe using the Built-in File Browser</figcaption>
<img src="docs/images/prompt_selector.png" alt="Recipe Builder">
</div>
### Prompt Manager Advanced:
- **All Prompt Manager Features**: Everything from the basic Prompt Manager, plus LoRA and Trigger word integration
- **Prompt Thumbnails**: Save thumbnail images with your prompts for visual identification in the dropdown
- **Dual LoRA Stack Support**: Two separate LoRA stack inputs/outputs for complex workflows (e.g., Wan video with different LoRAs for image and video)
- **Visual LoRA Tags**: See connected LoRAs as clickable tags with strength values
- **Toggle LoRAs On/Off**: Click any LoRA tag to enable/disable it without disconnecting
- **Editable Strengths**: Click the strength value on any tag to adjust it inline
- **Trigger Words Support**: Save and display trigger words alongside prompts and LoRAs, can use [ComfyUI-Lora-Manager](https://github.com/infantesimone/ComfyUI-Lora-Manager) trigger words.
- **Right-Click to Delete**: Right-click any LoRA or trigger word tag to remove it
- **Save LoRAs with Prompts**: When you save a prompt, the current LoRA configuration is saved with it
- **Override Mode**: Toggle "Override Lora" to ignore connected inputs and use only saved preset LoRAs
- **Merge Mode**: When override is off, connected LoRAs are merged with saved presets
- **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
<div align="center">
<figcaption>Use Extractor Nodes as an Image Loader, allowing browsing from Input and Output folder.</figcaption>
<img src="docs/images/adv_file_loading.png" alt="Recipe Builder">
</div>
### Prompt 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
### Prompt Extractor:
- **Extract from Images/Videos**: Load images or videos and extract embedded prompts, LoRAs, and workflow metadata
- **JSON Workflow Support**: Browse and load JSON workflow files directly to extract prompts and LoRA configurations
- **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.
## v2.0 Introduces The Recipe Toolset
### Prompt Generator
- **Three Generation Modes**: Enhance text prompts, analyze images, or analyze images with custom instructions
- **Prompt Enhancement**: Transform basic prompts into detailed descriptions using local LLMs
- **Vision Analysis**: Analyze images with Qwen3VL models to generate detailed descriptions
- **Custom Image Analysis**: Provide your own instructions for image analysis
- **JSON Output**: Optional structured JSON output with scene breakdown
- **Thinking Support**: Support Thinking models to perform deeper generative reasoning.
- **Automatic Server Management**: Starts/stops llama.cpp server as needed, with automatic shut off at exit.
- **Smart Model Selection**: Auto-selects appropriate model (vision or text) based on mode or Thinking mode.
Version 2.x introduces a Recipe toolset that can be used on its own, or in combination with the Prompt toolset.
### Prompt Generator Options
- **Model Selection**: Choose from local models or download Qwen3, Qwen3VL and Qwen3VL Thinking models from HuggingFace
- **Auto-Download**: Automatically downloads both model and required mmproj files for vision models
- **LLM Parameters**: Fine-tune temperature, top_k, top_p, min_p, repeat_penalty and context size.
- **Custom Instructions**: Override default system prompt for different enhancement styles.
- **Extra Image Inputs**: Combine up to 5 images to generate your prompt.
- **Console Debugging**: Enable outputing the entire process to the console for debugging purposes.
- Use the Recipe toolset when you want repeatable generation pipelines from extracted or hand-edited recipe data.
- Recipe Data includes prompts (pos & neg), LoRA stack, mode used, KSampler settings, resolution, seed, and more.
- This data can be created using Recipe Builder or extracted from existing media with Recipe Extractor.
- Recipe Renderer provides an easy way to render this recipe.
- Recipe data can also be used traditionally with the Recipe Relay node, which can access all of it.
- Use the Prompt toolset when you want fast prompt library management and local LLM-assisted prompt creation.
- Prompt Generator allows creation of new prompts using the LLM model of your choice.
- Prompt Manager can save these to be reusable later.
- Prompt Extractor is similar to Recipe Extractor, but can individually output prompts or LoRAs.
- Use both together when you want to create Recipes, but use different prompts.
### Preference Options
- Set choices for prefered Model for both base mode and VL model.
- Set new default model location, previous folder (gguf and llm) will still be scanned, but model will save in new default.
- Set custom Location for Llama.cpp. If Llama.cpp was not added to the system Path, this option let's you specify it's location.
In short: Prompt tools help you author and manage Prompts + LoRA intent, while Recipe tools help you build, execute and reuse full generation configurations.
## Toolset Overview
### Prompt Toolset
- Prompt Manager: dual LoRA stacks, trigger words, thumbnail workflows, and advanced save flows.
- Prompt Extractor: reads metadata from images/videos/JSON and outputs prompt + LoRA + recipe context.
- Prompt Generator + Options: local LLM prompt creation and enhancement using llama.cpp or Ollama.
- Prompt Manager (Basic): category-based prompt save/load. A no-frills basic version (The OG).
### Recipe Toolset
- Recipe Extractor: normalizes extracted metadata into reusable recipe_data.
- Recipe Builder: edit and validate recipe_data in a cleaner authoring surface.
- Recipe Renderer: execute recipe_data through built-in generation templates.
- Recipe Hub: merge/append model blocks into one `recipe_data` and expose each model block as its own output.
- Recipe Relay: edit one model block (`model_data`) with seed and LoRA stack overrides.
- Recipe Model Loader: resolve and load models from recipe_data.
- Recipe Manager: save and reuse recipe entries.
## Common Pipelines
### Prompt-first Pipeline
1. Write or generate prompts and connect LoRA stacks into Prompt Manager.
2. Generate with your normal ComfyUI graph.
3. Save reusable prompt entries when satisfied.
### Recipe-first Pipeline
1. Create preset in Recipe Builder
- By extracting recipe_data from media or JSON, using Recipe Extractor
- Or by directly modifying Recipe Builder to the values you want.
2. Render in Recipe Renderer.
3. Save reusable recipe entries with Recipe Manager.
- To include Thumbnail, add after the Renderer node.
### Hybrid Pipeline
1. Extract or build recipe_data.
2. Add Prompt Generator or Save prompts into Builder.
3. Add LoRAs, either using LoRA stackers or saved LoRA stacks in Prompt Manager.
4. Render through Recipe Renderer.
5. Save final reusable entries in Recipe Manager.
## Preferences And Settings
- Addon settings are available in ComfyUI Preferences (Settings) under Prompt Manager.
- This is where you set model/backend defaults, NSFW visibility defaults, view preferences, and related addon behavior.
- Prompt Generator backend choices (llama.cpp or Ollama) and related options are configured there.
## Workflow Examples
Workflow examples are provided to help understand the basics.
## Documentation
- Detailed node and feature reference: [docs/feature-reference.md](docs/feature-reference.md)
- Full changelog history: [docs/changelog.md](docs/changelog.md)
## Installation
@@ -95,7 +139,6 @@ ___
```
cd ComfyUI/custom_nodes/
```
2. Clone this repository:
```bash
git clone https://github.com/FranckyB/ComfyUI-Prompt-Manager.git
@@ -105,281 +148,27 @@ ___
cd ComfyUI-Prompt-Manager
pip install -r requirements.txt
```
4. Install [llama.cpp](https://github.com/ggml-org/llama.cpp/tree/master)
Windows:
```bash
winget install llama.cpp
```
Linux:
```bash
brew install llama.cpp
```
5. If you have them, place your .gguf models in the models/gguf folder or set in prererences your preferred folder path.
6. Restart ComfyUI
## Usage
### Prompt Manager
1. **Add the Node**: Add Node → Prompt Manager
2. **Select a Category**: Use the dropdown to choose from your categories
3. **Choose a Prompt**: Select a saved prompt from the name dropdown
4. **Connect prompt output**: Connect Prompt Manager output to your clip text encode node.
### Prompt Manager Advanced
1. **Add the Node**: Add Node → Prompt Manager → Prompt Manager Advanced
2. **Connect LoRA Stackers**: Connect LoRA stacker nodes (e.g., from LoRA Manager) to `lora_stack_a` and/or `lora_stack_b` inputs
3. **View LoRA Tags**: Connected LoRAs appear as clickable tags showing name and strength
4. **Toggle LoRAs**: Click a tag to enable/disable that LoRA (disabled tags turn gray)
5. **Adjust Strength**: Click the strength number on a tag to edit it inline
6. **Save with LoRAs**: Click "Save Prompt" to save both the prompt text and current LoRA configuration
7. **Override Mode**: Enable "Override Lora" checkbox to ignore connected inputs and use only the saved preset LoRAs
8. **Connect Outputs**: Use `lora_stack_a` and `lora_stack_b` outputs with the Apply LoRA Stack node
### Apply LoRA Stack
1. **Add the Node**: Add Node → Prompt Manager → Apply LoRA Stack
2. **Connect Model**: Connect your model (e.g., from Load Checkpoint) to the `model` input
3. **Connect LoRA Stack**: Connect a `LORA_STACK` output (from Prompt Manager Advanced or LoRA Manager's stacker)
4. **Optional CLIP**: Connect CLIP if your workflow needs it (some video workflows don't)
5. **Use Outputs**: Connect the modified model/clip to your sampler or other nodes
### Prompt 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
### Prompt Generator
**Basic Usage** (assuming a model is present in models\gguf):
1. **Add the Node**: Add Node → Prompt Generator
2. **Select Mode**: Choose from:
- "Enhance User Prompt" - Improve text prompts with LLM
- "Analyze Image" - Generate detailed image descriptions
- "Analyze Image with Prompt" - Analyze images with custom instructions
3. **Connect inputs**: Connect image for vision modes, or just use text for enhancement mode
4. **Output as Json**: Use Format_as_Json to experiment with Json prompts.
5. **Push the LLM**: Use enable_thinking to enable the model to perform deeper generative reasoning before producing the final prompt.
4. **Save memory**: Toggle "stop_server_after" ON to free VRAM after generation
5. **Run Workflow**: Generated prompt displays and can be saved to Prompt Manager
**Advanced Usage**:
1. **Add the Options Node**: Add Node → Prompt Generator Options
2. **Connect Options**: Connect the options node to the Prompt Generator Options input
3. **Analyze multiple images**: Connect up to 4 additional images, for a total of 5.
4. **Select from available models**: Select from models found in your models\gguf folder. Qwen models will be available to download.
5. **Adjust settings**: Adjust LLM parameters (temperature, top_k, etc.)
6. **Customize LLM**: Customize the default LLM instructions to modify the responses llama returns.
7. **Enable Debugging**: Enable complete printout of process to console using show_everything_in_console
**Qwen models found in options**
- Qwen3-1.7B-Q8_0.gguf: Fastest, lowest VRAM (~2GB)
- Qwen3-4B-Q8_0.gguf: Balanced performance (~4GB VRAM)
- Qwen3-8B-Q8_0.gguf: Best quality, highest VRAM (~8GB)
- Qwen3VL-4B-Instruct-Q8_0.gguf: Vision model, balanced performance (~5GB VRAM)
- Qwen3VL-8B-Instruct-Q8_0.gguf: Vision model, best quality (~9GB VRAM)
- Qwen3VL-4B-Thinking-Q8_0.gguf: Vision model, Thinking variant, balanced performance (~5GB VRAM)
- Qwen3VL-8B-Thinking-Q8_0.gguf: Vision model, Thinking variant, best quality (~9GB VRAM)
**Model Management**:
- Place gguf files in models/gguf folder
- Downloaded models are also placed in this folder.
**Preferences**:
Preference settings can be found in ComfyUI Settings → Prompt Manager
- **Preferred Base Model**: Name of model used for "Enhance User Prompt" mode (text-only models)
- **Preferred Vision Model**: Name of model Used for "Analyze Image" modes (Qwen3VL models)
- **Set Default Port** You can set the port used by Llama.cpp
- **Close Llama on Exit** By default Llama.cpp with be close on exit.
4. Install [llama.cpp](https://github.com/ggml-org/llama.cpp/tree/master):
- Windows:
```bash
winget install llama.cpp
```
- Linux:
```bash
brew install llama.cpp
```
5. Place custom `.gguf` models in models/gguf.
- Or use preferences to set a custom path.
6. Restart ComfyUI.
## Requirements
- ComfyUI
- Python 3.8+
- requests >= 2.31.0
- huggingface_hub >= 0.20.0
- psutil >= 5.9.0
- tqdm >= 4.66.0
- Pillow >= 10.0.0
- requests
- huggingface_hub
- psutil
- tqdm
- Pillow
- colorama
- llama-server (from llama.cpp)
## Troubleshooting
**Problem**: Prompts don't appear in the dropdown
- **Solution**: Make sure the category has saved prompts. Try creating a new prompt first.
**Problem**: Changes aren't saved
- **Solution**: Click the "Save Prompt" button after making changes. Direct edits in the text field are temporary.
**Problem**: Can't see LLM output in the node
- **Solution**: Make sure the LLM output is connected to the "llm_input" and run the workflow.
**Problem**: "llama-server command not found"
- **Solution**: Install llama.cpp and make sure `llama-server` is available in command line. See [llama.cpp releases](https://github.com/ggerganov/llama.cpp/releases)
**Problem**: "No models found"
- **Solution**: Either place a .gguf file in the `models/` folder, or connect the Prompt Generator Option node and select a model size (1.7B, 4B, or 8B) to download from HuggingFace
**Problem**: Server won't start
- **Solution**: Check that port 8080 is not in use. Close any existing llama-server processes.
**Problem**: Model download fails
- **Solution**: Check your internet connection and HuggingFace availability. Large models may take time to download.
**Problem**: Generation is slow
- **Solution**: Either, Use a smaller quantized model (Q4 instead of Q8) or toggle 'stop_server_after' to quit llama.cpp after generating prompt.
**Problem**: Default Model used is not what I want
- **Solution**: You can set your preferred model in the ComfyUI settings. Simply add its full name, with .gguf extension, for both the VL and base models. Enabling Thinking in the Generator might change what is used for VL models.
## Changelog
### version 1.13.5
- Added browse window with thumbnails in Extractor, with cache system for speedup.
- Bug fix for issue caused by new additions.
### version 1.12.7
- Quality of life improvements and added option to change the Strenght of any Lora in Manager, so we can tweak Extracted Workflows Live.
### version 1.12.6
- Tweak to caching behavior for prompt extractor and prompt manager advanced
### version 1.12.5
- Some dependencies to FFMpeg were still present, remove them and added a frame_position value, so we can specify what frame to get from video.
### version 1.12.0
- Prompt Extractor: Added Lora inputs, so it can be used as a passthrough, with a None Choice at top, to easily deactivate it.
- Prompt Extractor: Improved logic for determining Positive prompts in Worfklow.
- Prompt Extractor: Improved logic for finding High and Low Lora Stacks
- Prompt Manager Advanced: Added Fuzzy Logic to find Loras that might have been renamed
- Prompt Manager Advanced: Fixed issue of Lora buttons getting cleared when changing tab.
### Version 1.11.5
- Slight adjustement to extractor node, gets metadata in a method more consistent with ComfyUI, removing need for ffmpeg for videos.
### Version 1.11.2
- Slight adjustement to extractor node to behave exactly like the Load image node, while also supporting Videos. (With extract first frame support)
### Version 1.11.0
- **New Node: Prompt Extractor** - Extract prompts and LoRA configurations from images, videos, and JSON workflows
- Loads embedded metadata from PNG, JPEG, WebP images and MP4 videos
- Browse and load JSON workflow files directly
- Dual LoRA stack output for workflows using two stacks (e.g., Wan video)
- Filters inactive LoRAs - only extracts LoRAs marked as active
- Supports extraction from CLIP Text Encode, samplers, and LoRA stackers
- Compatible with Power Lora Loader, WanMoeKSamplerAdvanced, and other common nodes
- **Prompt Thumbnails** - Save thumbnail images with prompts in Prompt Manager Advanced
- Visual identification of prompts in the dropdown selector
- Thumbnails stored alongside prompt data for easy management
- **Simplified "New Prompt" button**
- Now clears fields immediately without asking for a name
- Enter the name when saving instead of when creating
- Keeps you in the current category for faster workflow
- **Bug fixes and improvements**
- Fixed JSON workflow file path resolution
- Improved LoRA extraction for complex workflows
### Version 1.10.0
- **Unified UI for Prompt Manager and Prompt Manager Advanced**
- Three-button layout: Save Prompt, New Prompt, and More (dropdown menu)
- New Prompt button creates a temporary prompt that isn't saved until you click Save Prompt
- Save Prompt opens a modal with category selection (create new or select existing)
- More dropdown includes: Import JSON, Export JSON, Delete Prompt, Delete Category
- **Import/Export JSON functionality**
- Export all prompts to a JSON file
- Import prompts with Merge (add to existing) or Replace (overwrite all) options
- Proper cancel handling without false success messages
- **Multi-tab synchronization**
- Changing category or prompt reloads data from server
- Prevents conflicts when editing prompts in multiple browser tabs
- **Prompt Manager now preserves LoRA data**
- LoRA stacks, trigger words, and active states are preserved when saving from basic Prompt Manager
- Seamless compatibility between Prompt Manager and Prompt Manager Advanced
- **Trigger Words support in Prompt Manager Advanced**
- Save and restore trigger words alongside prompts and LoRAs
- Trigger words display as editable text when loading saved prompts
- **Improved unsaved changes detection**
- Warning when switching away from newly created (unsaved) prompts
- Cancel button properly reverts dropdown to previous selection
### Version 1.9.0
- **New Node: Prompt Manager Advanced** - Extended prompt manager with LoRA stack support
- Dual LoRA stack inputs/outputs for complex workflows (Wan video, etc.)
- Visual LoRA tags showing name and editable strength values
- Toggle LoRAs on/off by clicking tags
- Save LoRA configurations alongside prompts
- Override mode to ignore connected inputs and use saved presets
- Merge mode combines connected LoRAs with saved presets
- Missing LoRA detection with visual warnings
- Integration with LoRA Manager for hover previews
- **New Node: Apply LoRA Stack** - Simple node to apply LORA_STACK to model/clip
- Categories and prompts now display in alphabetical order
- Fixed dropdown refresh after saving prompts
### Version 1.8.3
- Added option to leave Llama server running when closing ComfyUI.
### Version 1.8.2
- Added custom model path preference and enhance model management
### Version 1.8.1
- Added option to set a custom Llama path in preferences, for those that have specific installs.
### Version 1.8.0
- Added support for Qwen3VL Thinking model variants, with download options thru the Generator Options node.
- Model manager now searches for relevant `mmproj` files using model-name components for more reliable vision-model linking.
- Detailed console output options (debug logging)
- `enable_thinking` toggle to enable/disable the model's reasoning/thinking mode.
- Options node now accepts multiple images for analysis.
- Better Llama shutdown behavior to force-close the server when Comfy exits.
- Uses model-reported sampling params by default when available; the Options node can override them per-parameter.
- Moved preference API endpoints and cache handling into `model_manager.py` for cleaner management and persistence.
### Version 1.7.0
- Added three-mode prompt generator: "Enhance User Prompt", "Analyze Image", "Analyze Image with Prompt"
- Enhanced vision model workflow with dedicated image analysis modes
- Added custom image analysis with user-provided instructions (e.g., "describe the lighting", "identify objects")
- Added model preferences system integrated with ComfyUI Settings
- Added automatic model preference management (separate settings for base and vision models)
- Improved model selection with preference fallback to smallest model
- Filtered mmproj files from model selection dropdowns
- Model preferences stored in ComfyUI settings for persistence across updates
### Version 1.6.0
- Added Qwen3VL vision model support for image analysis
- Added JSON output format option with structured scene breakdown
- Added adjustable context size parameter (512-32768 tokens)
- Added automatic mmproj file download for vision models
- Added image resizing to ~2MP to optimize token usage
- Added token usage logging for monitoring context consumption
- Improved model selection logic with automatic VL/non-VL detection
- Fixed multiple directory support for model search (gguf + LLM folders)
### Version 1.5.1
- LLM output remains available when use_llm is off, so it can be edited.
- Improved caching detection: any change to options will be detected and force a new output.
- Improved some UI quirks
### Version 1.5.0
- Added Prompt Generator node with automatic llama.cpp server management
- Added Prompt Generator Options node for model selection and parameters
- Automatic model detection and auto-download from HuggingFace for Qwen3 models.
- VRAM management with optional server shutdown
### Version 1.1.0
- Added LLM input toggle for switching between internal and external text
- Made text fields scrollable even when disabled
- Fixed reload bugs with toggle state
### Version 1.0.0
- Initial release
- Category and prompt management
- LLM output integration
+52 -27
View File
@@ -1,40 +1,65 @@
"""
ComfyUI Prompt Manager - A comprehensive prompt and workflow management system for ComfyUI.
Features: prompt & workflow management, LoRA stacks, workflow extraction, workflow generation.
"""
ComfyUI Prompt Manager - A simple custom node for saving and reusing prompts
A prompt management system for ComfyUI with LLM input support
"""
__version__ = "1.13.5"
__version__ = "2.5.1"
__author__ = "François Beaudry"
__license__ = "MIT"
from .prompt_manager import PromptManager
from .prompt_manager_advanced import PromptManagerAdvanced
from .prompt_generator import PromptGenerator
from .prompt_generator_options import PromptGenOptions
from .prompt_apply_lora import PromptApplyLora
from .prompt_extractor import PromptExtractor
from .model_manager import get_local_models
from server import PromptServer
from .nodes.apply_lora import ApplyLoraPlusPlus
from .nodes.prompt_manager_adv import PromptManagerAdvanced
from .nodes.prompt_manager_basic import PromptManager
from .nodes.prompt_generator import PromptGenerator
from .nodes.prompt_generator_options import PromptGenOptions
from .nodes.prompt_extractor import PromptExtractor
from .nodes.prompt_extractor import WorkflowExtractor as RecipeExtractor
from .nodes.recipe_builder import RecipeBuilder
from .nodes.recipe_renderer import WorkflowRenderer as RecipeRenderer
from .nodes.recipe_relay import WorkflowRelay as RecipeRelay
from .nodes.recipe_model_loader import WorkflowModelLoader as RecipeModelLoader
from .nodes.recipe_model_picker import RecipeModelPicker
from .nodes.recipe_manager import WorkflowManager as RecipeManager
from .nodes.multi_prompt import RecipeBuilderMultiPrompts
from .nodes.multi_lora_stacker import MultiLoraStackerLM, MultiLoraCombine
NODE_CLASS_MAPPINGS = {
"PromptManager": PromptManager,
"PromptManagerAdvanced": PromptManagerAdvanced,
"PromptGenerator": PromptGenerator,
"PromptGenOptions": PromptGenOptions,
"PromptApplyLora": PromptApplyLora,
"PromptExtractor": PromptExtractor
"PromptApplyLora": ApplyLoraPlusPlus,
"PromptManagerAdvanced": PromptManagerAdvanced,
"PromptManager": PromptManager,
"PromptGenerator": PromptGenerator,
"PromptGenOptions": PromptGenOptions,
"PromptExtractor": PromptExtractor,
"RecipeExtractor": RecipeExtractor,
"RecipeBuilder": RecipeBuilder,
"RecipeRenderer": RecipeRenderer,
"RecipeRelay": RecipeRelay,
"RecipeModelLoader": RecipeModelLoader,
"RecipeModelPicker": RecipeModelPicker,
"RecipeManager": RecipeManager,
"RecipeBuilderMultiPrompts": RecipeBuilderMultiPrompts,
"MultiLoraStackerLM": MultiLoraStackerLM,
"MultiLoraCombine": MultiLoraCombine,
}
NODE_DISPLAY_NAME_MAPPINGS = {
"PromptManager": "Prompt Manager",
"PromptManagerAdvanced": "Prompt Manager Advanced",
"PromptGenerator": "Prompt Generator",
"PromptGenOptions": "Prompt Generator Options",
"PromptApplyLora": "Prompt Apply LoRA",
"PromptExtractor": "Prompt Extractor"
"PromptApplyLora": "Apply LoRA++",
"PromptManagerAdvanced": "Prompt Manager",
"PromptManager": "Prompt Manager (Basic)",
"PromptGenerator": "Prompt Generator",
"PromptGenOptions": "Prompt Generator Options",
"PromptExtractor": "Prompt Extractor",
"RecipeExtractor": "Recipe Extractor",
"RecipeBuilder": "Recipe Builder",
"RecipeRenderer": "Recipe Renderer",
"RecipeRelay": "Recipe Relay",
"RecipeModelLoader": "Recipe Model Loader",
"RecipeModelPicker": "Recipe Model Picker",
"RecipeManager": "Recipe Manager",
"RecipeBuilderMultiPrompts": "Multi Prompts",
"MultiLoraStackerLM": "Multi LoRA Stack",
"MultiLoraCombine": "Multi LoRA Combine",
}
WEB_DIRECTORY = "./js"
__all__ = ['NODE_CLASS_MAPPINGS', 'NODE_DISPLAY_NAME_MAPPINGS', 'WEB_DIRECTORY']
print("[PromptManager] Node registered successfully")
print("[PromptManager] Nodes registered: Apply LoRA++, Prompt Manager, Prompt Generator, Prompt Extractor, Recipe Extractor, Recipe Builder, Recipe Renderer, Recipe Relay, Recipe Manager")
+92
View File
@@ -0,0 +1,92 @@
# Changelog
## version 2.5.0
- **Recipe Builder is now Multi-model Only**
- Expanded Builder authoring around `recipe_data` with slot-aware model blocks (`model_a`/`model_b`/`model_c`/`model_d`).
- Improved cross-slot behavior for prompts, LoRAs, sampler settings, and resolution handling in multi-model workflows.
- **Authoritative Builder extraction flow**
- Extraction now preserves Builder-authored v2 model data as the source of truth when embedded Builder v2 metadata is present.
- Added compatibility safeguards so legacy/non-v2 workflows continue to use fallback extraction logic.
- **Builder lock/reset and execution consistency**
- Improved update and execute behavior so incoming recipe values, lock states, and current UI values resolve more predictably.
- Strength/reset handling was tightened for better consistency across slot updates and reruns.
- **New LoRA utility node: MultiLoraCombine**
- Added `MultiLoraCombine` to merge optional multi-stack input with optional stack A/B/C/D inputs into a single `MULTI_LORA_STACK` output.
- Helps consolidate mixed LoRA sources for multi-model Builder and downstream recipe flows.
- **New feature: Multi LoRA Stacker with Lora-Manager compatibility**
- Added a new Multi LoRA Stacker for slot-aware and multi-stack recipe flows.
- Compatible with [Lora-Manager](https://github.com/willmiao/ComfyUI-Lora-Manager), including interoperability with managed LoRA selections and previews.
## version 2.2.0
- **Recipe_data v2 expansion and slot-aware workflows**
- Expanded v2 compatibility across Builder, Relay, Renderer, Manager, and extraction utilities.
- Improved model slot behavior for `model_a`/`model_b`/`model_c`/`model_d`, including WAN pair handling.
- **Recipe Builder Update flow and persistence improvements**
- Update Recipe now respects Pull From selection consistently and supports expected clear behavior for empty/none selections.
- Pull From / Send To state persistence improved across tab switches and workflow reloads.
- Update Recipe visibility refined to avoid incomplete Builder-to-Builder pull paths.
- **LoRA synchronization and execution-order fixes**
- Fixed connected LoRA add/remove timing so `recipe_data` reflects changes on first execute.
- Improved LoRA state authority between connected inputs and persisted UI overrides.
- **Renderer validation hardening**
- Renderer now fails fast with a clear error when the selected model slot is undefined.
- Prevents silent renders from empty/non-existent selected model slots.
- **Prompt Generator GPU utilization and VRAM prep**
- Ensured llama.cpp server launch uses `-ngl 100` so generation is pushed to GPU as much as possible.
- Added more aggressive cache/VRAM flushing before generation to reduce memory pressure and improve run reliability.
## version 2.1.1
- Updated Documentation
- Bug fixes
## version 2.1.0
- **Naming Migration: Workflow -> Recipe**
- Renamed node/toolset terminology to Recipe naming across the addon UI and docs.
- Bug fixes.
## version 2.0.2
- Added Ernie family support in Workflow Builder/Renderer.
- Bug fixes.
## version 2.0.1
- **Added Denoise options to Workflow Pipeline**
- Workflow data now contains denoise value (Extractor returns 1 by default).
- Allows mid-run model handoff using KSampler denoise.
- Bug fixes.
## version 2.0.0
- **Prompt Manager becomes Prompt + Workflow Manager**
- Workflow Manager allows saving workflow and integrates with Prompt Manager save/reuse behavior.
- Extractor/Builder/Manager workflow loop focused on simplified reusable workflow cores.
- recipe_data-first persistence improvements.
- Documentation updates.
## version 1.25.0
- **Workflow Tools Release Milestone**
- Workflow Builder / Workflow Renderer / Workflow Bridge / Workflow Model Loader form a complete editable workflow pipeline.
- Improved extractor-to-builder update flow.
- Improved Builder dropdown stability and persistence.
- Improved tab-switch persistence for Builder UI state.
- Improved compatibility with Builder persistence extraction.
- **Wan i2v workflow quality and UX improvements**
- **Prompt Manager Advanced save + thumbnail improvements**
## version 1.22.6
- Prompt Extractor now embeds extracted data in workflow so it can extract itself.
## version 1.22.5
- Thumbnail generation in Prompt Manager Advanced.
- Improved model high/low detection.
## version 1.22.1
- Prompt Model Loader improvements, including GGUF support and persistence improvements.
## version 1.22.0
- New node: Prompt Model Loader.
- Expanded model/checkpoint extraction in Prompt Extractor.
- A1111/Forge image support improvements.
- WebP metadata support improvements.
- Video metadata parsing improvements.
## version 1.21.x to 1.0.0
Older historical entries were previously listed in README and can still be recovered from repository history.
+97
View File
@@ -0,0 +1,97 @@
# Feature Reference
This page contains the detailed feature overview that was moved out of the main README for faster scanning.
## Prompt Toolset
### Prompt Manager
- All Prompt Manager features, plus LoRA and trigger-word integration
- Dual LoRA stack support for complex pipelines (for example Wan video)
- LoRA tags with inline strength editing
- Toggle active state per LoRA without rewiring
- Save LoRAs with prompt entries
- Override/merge behavior for connected vs saved LoRAs
- Optional recipe_data input integration
- Missing LoRA highlighting and LoRA Manager preview support
- Thumbnail generation from saved prompt entries
### Prompt Manager (Basic)
- Category-based prompt organization
- Save/load prompts quickly
- NSFW tagging and filtering
- LLM input toggle
- Persistent storage in your ComfyUI user folder
### Prompt Extractor
- Extract prompt/model/LoRA metadata from image, video, and JSON workflow files
- Supports ComfyUI, A1111/Forge, and WebP metadata formats
- First-frame extraction from videos
- Dual LoRA stack extraction for compatible workflows
- Input/output folder browsing
- Can also be used as an advanced media loader with metadata awareness
### Prompt Generator
- Local LLM generation with llama.cpp or Ollama
- Text enhancement and image analysis modes
- Optional JSON output mode
- Thinking mode support
- Multi-image support (up to 5 total with options node)
- Prompt Generator Options node for model and parameter control
## Recipe Toolset
The Recipe Toolset is designed to build, manage, and rerun reusable generation pipelines. You can author recipes from scratch in Builder, combine recipe logic with Prompt Manager/Prompt Manager Advanced to reuse saved prompts, or import existing metadata via Extractor when you want to bootstrap from prior outputs.
### Recipe Builder
- Central editing surface to build or modify recipes
- Primary authoring path for creating recipes from scratch
- Provides a recipe-focused workspace to inspect, adjust, and refine recipe fields without manually wiring every parameter node-by-node
- Can be used standalone or connected with other recipe/prompt nodes
- Works well with Prompt Manager so saved prompts can be reused as part of recipe-driven pipelines
- Ideal for iterative tuning: extract once, then keep adjusting recipe values and rerendering until the pipeline is where you want it
- Helps standardize presets so repeated jobs start from consistent known-good settings
### Recipe Extractor
- Reads and normalizes workflow metadata into reusable recipe data
- Converts raw generation metadata into a structured recipe format that is easier to edit and pass between nodes
- Helps preserve key settings (for example model family, sampler context, and recipe-specific parameters) when moving from ad-hoc runs to reusable setups
- Useful when you want to recreate a look/style from existing outputs and then iterate from a stable baseline
### Recipe Renderer
- Executes recipe-driven generation for fast reruns after setup
- Interprets recipe data and applies it to generation execution so you can reproduce prior results or batch variants with minimal manual changes
- Reduces setup overhead for repeated jobs by moving configuration logic into reusable recipe data
- Especially useful when you want to test multiple prompt/input variations while keeping the same core generation recipe intact
### Recipe Relay
- Relays recipe data and compatible passthrough context across nodes
- Acts as a clean handoff point for recipe payloads so larger graphs stay modular and easier to reason about
- Preserves compatible context as data moves through the pipeline, reducing brittle copy/paste style wiring patterns
- Helpful when splitting complex graphs into logical stages (extract/build/render/manage) without losing recipe continuity
### Recipe Model Loader
- Loads model/checkpoint assets based on recipe data
- Resolves and applies model selections encoded in recipes so execution follows the intended model path automatically
- Supports model slot selection and loader-specific behavior
- Makes recipe playback more reliable across sessions by tying loader behavior to saved recipe intent instead of manual recollection
- Useful for multi-model pipelines where model choice is part of the recipe contract, not an afterthought
### Recipe Manager
- Save, browse, and reuse recipe entries
- Provides persistent recipe storage so successful setups can be cataloged and recalled quickly
- Works with Builder to quickly review and update saved recipe data
- Encourages a library-style workflow: capture working recipes, name/tag them, and reapply them across projects
- Great for maintaining repeatable production presets while still allowing safe versioned edits over time
## Model Family Support
Built-in support includes:
- Flux 1
- Flux 2
- Ernie
- SDXL
- Wan
- Qwen
- Z-Image
- Wan Image
- Wan Video (I2V and T2V)
Binary file not shown.

After

Width:  |  Height:  |  Size: 531 KiB

Before

Width:  |  Height:  |  Size: 766 KiB

After

Width:  |  Height:  |  Size: 766 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 670 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 743 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 280 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 387 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 450 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 120 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 53 KiB

File diff suppressed because one or more lines are too long
Binary file not shown.

After

Width:  |  Height:  |  Size: 93 KiB

File diff suppressed because one or more lines are too long
Binary file not shown.

After

Width:  |  Height:  |  Size: 50 KiB

File diff suppressed because one or more lines are too long
Binary file not shown.

After

Width:  |  Height:  |  Size: 95 KiB

File diff suppressed because one or more lines are too long
Binary file not shown.

After

Width:  |  Height:  |  Size: 72 KiB

File diff suppressed because one or more lines are too long
Binary file not shown.

After

Width:  |  Height:  |  Size: 102 KiB

File diff suppressed because one or more lines are too long
Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

File diff suppressed because one or more lines are too long
+203 -146
View File
@@ -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);
}
}
+656
View File
@@ -0,0 +1,656 @@
import { app } from "../../scripts/app.js";
import { api } from "../../scripts/api.js";
import { PM_UI_PALETTE } from "./ui_palette.js";
const NODE_CLASS = "MultiLoraStackerLM";
const LM_PROVIDER_CLASS = "Lora Stacker (LoraManager)";
const STYLE_ID = "pm-multi-lm-style";
const MIN_NODE_WIDTH = 1080;
const MIN_NODE_HEIGHT = 320;
const DEFAULT_NODE_WIDTH = 1080;
const DEFAULT_NODE_HEIGHT = 430;
// Height constants mirroring LM's loras_widget_utils.js
const LM_LORA_ENTRY_H = 40;
const LM_HEADER_H = 32;
const LM_CONTAINER_PAD = 12;
const LM_EMPTY_H = 100;
// Per-column chrome: title(22) + search textarea(50) + col padding(16)
const COL_CHROME_H = 88;
let loraCodeListenerAttached = false;
let promptSerializationPatched = false;
const SLOT_DEFS = [
{ key: "model_a", label: "Model A", short: "A", state: "loras_state_a" },
{ key: "model_b", label: "Model B", short: "B", state: "loras_state_b" },
{ key: "model_c", label: "Model C", short: "C", state: "loras_state_c" },
{ key: "model_d", label: "Model D", short: "D", state: "loras_state_d" },
];
let lmBridgePromise = null;
// ---------------------------------------------------------------------------
// Styles
// ---------------------------------------------------------------------------
function ensureStyles() {
if (document.getElementById(STYLE_ID)) return;
const p = PM_UI_PALETTE || {};
const panel = p.panel || "hsl(216 11% 15%)";
const panelBorder = p.panelBorder || "hsl(216 20% 65% / 0.24)";
const inputBg = p.inputBg || "hsl(220 15% 10%)";
const inputBorder = p.inputBorder || "hsl(218 10% 41%)";
const textHeading = p.textHeading || "hsl(220 13% 85%)";
const textPrimary = p.textPrimary || "hsl(0 0% 87%)";
const textHint = p.textHint || "hsl(216 15% 65%)";
const cardBg = p.cardBg || "hsl(219 16% 18%)";
const accentBorder = "rgba(255,255,255,0.98)";
const accentSoft = "rgba(255,255,255,0.42)";
const style = document.createElement("style");
style.id = STYLE_ID;
style.textContent = `
.pm-multi-lm-root {
width: 100%;
height: 100%;
box-sizing: border-box;
padding: 6px 6px 6px 6px;
overflow: hidden;
display: flex;
flex-direction: column;
}
.pm-multi-lm-root,
.pm-multi-lm-root * {
scrollbar-width: none;
-ms-overflow-style: none;
}
.pm-multi-lm-root::-webkit-scrollbar,
.pm-multi-lm-root *::-webkit-scrollbar {
width: 0;
height: 0;
display: none;
}
.pm-multi-lm-grid {
display: grid;
grid-template-columns: repeat(4, minmax(200px, 1fr));
gap: 8px;
flex: 1;
min-height: 0;
align-items: stretch;
}
.pm-multi-lm-col {
border: 1px solid ${panelBorder};
border-radius: 8px;
background: ${panel};
padding: 8px;
min-width: 0;
display: flex;
flex-direction: column;
flex-shrink: 0;
min-height: 0;
height: 100%;
}
.pm-multi-lm-col.active-slot {
border-color: ${accentBorder};
box-shadow: inset 0 0 0 1px ${accentSoft};
}
.pm-multi-lm-col.active-slot .pm-multi-lm-title {
color: ${accentBorder};
}
.pm-multi-lm-title {
font-weight: 700;
font-size: 12px;
letter-spacing: 0.02em;
color: ${textHeading};
margin-bottom: 6px;
flex-shrink: 0;
}
.pm-multi-lm-search {
width: 100%;
min-height: 38px;
resize: vertical;
box-sizing: border-box;
border: 1px solid ${inputBorder};
border-radius: 6px;
padding: 6px 8px;
background: ${inputBg};
color: ${textPrimary};
margin-bottom: 6px;
font-size: 12px;
flex-shrink: 0;
}
.pm-multi-lm-search::placeholder {
color: ${textHint};
}
.pm-multi-lm-list-host {
flex: 1;
min-height: 0;
overflow-y: auto;
overflow-x: hidden;
scrollbar-width: none;
-ms-overflow-style: none;
}
.pm-multi-lm-list-host .lm-loras-container {
height: 100%;
max-height: none;
background: ${cardBg};
scrollbar-width: none;
-ms-overflow-style: none;
}
.pm-multi-lm-list-host::-webkit-scrollbar,
.pm-multi-lm-list-host .lm-loras-container::-webkit-scrollbar {
width: 0;
height: 0;
display: none;
}
`;
document.head.appendChild(style);
}
// ---------------------------------------------------------------------------
// LM bridge loader
// ---------------------------------------------------------------------------
async function loadLmBridge() {
if (lmBridgePromise) return lmBridgePromise;
lmBridgePromise = Promise.all([
import("/extensions/ComfyUI-Lora-Manager/autocomplete.js"),
import("/extensions/ComfyUI-Lora-Manager/loras_widget.js"),
import("/extensions/ComfyUI-Lora-Manager/utils.js"),
import("/extensions/ComfyUI-Lora-Manager/lora_syntax_utils.js"),
]).then(([autocompleteMod, lorasWidgetMod, utilsMod, syntaxMod]) => ({
AutoComplete: autocompleteMod.AutoComplete,
addLorasWidget: lorasWidgetMod.addLorasWidget,
mergeLoras: utilsMod.mergeLoras,
applyLoraValuesToText: syntaxMod.applyLoraValuesToText,
})).catch((err) => {
console.warn("[PromptManager] Failed to load Lora-Manager bridge modules", err);
lmBridgePromise = null;
return null;
});
return lmBridgePromise;
}
// ---------------------------------------------------------------------------
// Widget helpers
// ---------------------------------------------------------------------------
function getWidgetByName(node, name) {
if (!node || !Array.isArray(node.widgets)) return null;
return node.widgets.find((w) => w && w.name === name) ?? null;
}
function ensureStateWidget(node, name) {
let widget = getWidgetByName(node, name);
if (widget) return widget;
if (!node || typeof node.addWidget !== "function") return null;
return node.addWidget("text", name, "[]", null, { multiline: true });
}
function hideWidget(widget) {
if (!widget || widget.__pm_hidden) return;
widget.__pm_hidden = true;
// Keep original widget type (STRING) so graphToPrompt includes state values.
widget.hidden = true;
widget.computeSize = () => [0, -4];
widget.draw = function () {};
if (widget.element) widget.element.style.display = "none";
}
function hideStateWidgets(node) {
if (!node || !Array.isArray(node.widgets)) return;
for (const widget of node.widgets) {
if (!widget || widget.name === "multi_lora_ui") continue;
hideWidget(widget);
}
}
function parseLorasState(value) {
if (Array.isArray(value)) return value;
if (value && typeof value === "object" && Array.isArray(value.__value__)) {
return value.__value__;
}
if (value && typeof value === "object" && typeof value.__value__ === "string") {
try {
const parsed = JSON.parse(value.__value__);
return Array.isArray(parsed) ? parsed : [];
} catch (_e) {
return [];
}
}
if (typeof value !== "string") return [];
const raw = value.trim();
if (!raw || raw === "[]") return [];
try {
const parsed = JSON.parse(raw);
return Array.isArray(parsed) ? parsed : [];
} catch (_e) {
return [];
}
}
function writeLorasState(widget, listValue) {
if (!widget) return;
widget.value = JSON.stringify(Array.isArray(listValue) ? listValue : []);
}
function getSlotByKey(node, slotKey) {
if (!node || !Array.isArray(node.__pmMultiLmSlots)) return null;
return node.__pmMultiLmSlots.find((s) => s && s.key === slotKey) ?? null;
}
// ---------------------------------------------------------------------------
// Apply incoming lora code to a slot
// ---------------------------------------------------------------------------
function applyIncomingLoraCode(node, slotKey, code, mode) {
if (!node || typeof code !== "string") return;
const slot = getSlotByKey(node, slotKey);
if (!slot || !slot.searchInput) return;
const current = String(slot.searchInput.value || "");
slot.searchInput.value = (mode === "replace" || !current) ? code : `${current}\n${code}`;
slot.searchInput.dispatchEvent(new Event("input", { bubbles: true }));
}
// ---------------------------------------------------------------------------
// lora_code_update listener (attached once, synchronously)
// ---------------------------------------------------------------------------
function attachLoraCodeListener() {
if (loraCodeListenerAttached) return;
loraCodeListenerAttached = true;
api.addEventListener("lora_code_update", (event) => {
const detail = event?.detail;
if (!detail) return;
const nodeId = Number(detail.id);
if (!Number.isFinite(nodeId) || nodeId < 0) return;
const loraCode = typeof detail.lora_code === "string" ? detail.lora_code : "";
const mode = typeof detail.mode === "string" ? detail.mode : "append";
// Find our node by integer ID
const nodes = app.graph?._nodes;
if (!Array.isArray(nodes)) return;
const targetNode = nodes.find((n) => Number(n.id) === nodeId && n.type === NODE_CLASS);
if (!targetNode) return;
// Route to the currently-selected active slot
const activeSlot = targetNode.properties?.pmActiveSlot ?? "model_a";
applyIncomingLoraCode(targetNode, activeSlot, loraCode, mode);
});
}
// ---------------------------------------------------------------------------
// Prompt serialization shim:
// Keep LM comfyClass for manager integration, but serialize this node as its
// real backend class so ComfyUI validates against MultiLoraStackerLM inputs.
// ---------------------------------------------------------------------------
function attachPromptSerializationShim() {
if (promptSerializationPatched) return;
if (!app || typeof app.graphToPrompt !== "function") return;
promptSerializationPatched = true;
const originalGraphToPrompt = app.graphToPrompt.bind(app);
app.graphToPrompt = async function (...args) {
const swapped = [];
const nodes = app.graph?._nodes;
if (Array.isArray(nodes)) {
for (const node of nodes) {
if (!node || node.type !== NODE_CLASS) continue;
if (node.comfyClass !== LM_PROVIDER_CLASS) continue;
swapped.push(node);
node.comfyClass = NODE_CLASS;
}
}
try {
return await originalGraphToPrompt(...args);
} finally {
for (const node of swapped) {
node.comfyClass = LM_PROVIDER_CLASS;
}
}
};
}
// ---------------------------------------------------------------------------
// Active-slot selection (click a section to target LM sends)
// ---------------------------------------------------------------------------
function setActiveSlot(node, slotKey) {
if (!node) return;
if (!node.properties) node.properties = {};
node.properties.pmActiveSlot = slotKey;
updateActiveColumnHighlight(node);
}
function updateActiveColumnHighlight(node) {
if (!Array.isArray(node.__pmMultiLmSlots)) return;
const activeSlot = node.properties?.pmActiveSlot ?? "model_a";
for (const slot of node.__pmMultiLmSlots) {
if (slot?.col) slot.col.classList.toggle("active-slot", slot.key === activeSlot);
}
}
// ---------------------------------------------------------------------------
// Embedded loras widget via fakeNode pattern
// ---------------------------------------------------------------------------
function createEmbeddedLorasWidget(node, lm, widgetName, initialValue, onChange) {
const host = document.createElement("div");
host.className = "pm-multi-lm-list-host";
const fakeNode = {
addDOMWidget(name, type, container, options) {
return {
name,
type,
callback: null,
element: container,
get value() {
return typeof options?.getValue === "function" ? options.getValue() : [];
},
set value(v) {
if (typeof options?.setValue === "function") options.setValue(v);
},
};
},
setDirtyCanvas(fg, bg) { node?.setDirtyCanvas?.(fg, bg); },
};
const out = lm.addLorasWidget(fakeNode, widgetName, {}, onChange);
if (out?.widget?.element) host.appendChild(out.widget.element);
if (out?.widget && Array.isArray(initialValue) && initialValue.length > 0) {
out.widget.value = initialValue;
}
return { host, widget: out?.widget ?? null };
}
// ---------------------------------------------------------------------------
// Height management — mirrors LM's updateWidgetHeight approach:
// set CSS vars on the root element so ComfyUI's layout system resizes the node,
// never calling node.setSize() (which would prevent user resize).
// ---------------------------------------------------------------------------
function computeContentHeight(node) {
let maxListH = LM_EMPTY_H;
if (Array.isArray(node.__pmMultiLmSlots)) {
for (const slot of node.__pmMultiLmSlots) {
const count = Array.isArray(slot.lorasWidget?.value) ? slot.lorasWidget.value.length : 0;
const h = count === 0
? LM_EMPTY_H
: LM_CONTAINER_PAD + LM_HEADER_H + Math.min(count, 12) * LM_LORA_ENTRY_H;
if (h > maxListH) maxListH = h;
}
}
return COL_CHROME_H + maxListH + 20;
}
function notifyHeightChange(node) {
const root = node?.__pmMultiLmRoot;
if (!root) return;
const h = computeContentHeight(node);
root.style.setProperty('--comfy-widget-min-height', `${h}px`);
root.style.setProperty('--comfy-widget-height', `${h}px`);
applyNodeSizeConstraints(node);
setTimeout(() => { node?.setDirtyCanvas?.(true, true); }, 10);
}
function applyNodeSizeConstraints(node, useDefaultSize = false) {
if (!node || node.__pmApplyingSizeConstraint) return;
const currentW = Number(node?.size?.[0]) || 0;
const currentH = Number(node?.size?.[1]) || 0;
const targetW = useDefaultSize
? Math.max(DEFAULT_NODE_WIDTH, MIN_NODE_WIDTH, currentW)
: Math.max(MIN_NODE_WIDTH, currentW);
const targetH = useDefaultSize
? Math.max(DEFAULT_NODE_HEIGHT, MIN_NODE_HEIGHT, currentH)
: Math.max(MIN_NODE_HEIGHT, currentH);
if (targetW === currentW && targetH === currentH) return;
node.__pmApplyingSizeConstraint = true;
try {
node.setSize([targetW, targetH]);
} finally {
node.__pmApplyingSizeConstraint = false;
}
}
// ---------------------------------------------------------------------------
// Per-slot column builder
// ---------------------------------------------------------------------------
function buildSlotColumn(node, lm, slotDef) {
const stateWidget = ensureStateWidget(node, slotDef.state);
hideWidget(stateWidget);
const col = document.createElement("div");
col.className = "pm-multi-lm-col";
col.title = `Click to make ${slotDef.label} the LoRA Manager target`;
col.addEventListener("pointerdown", () => setActiveSlot(node, slotDef.key));
const title = document.createElement("div");
title.className = "pm-multi-lm-title";
title.textContent = slotDef.label;
const searchInput = document.createElement("textarea");
searchInput.className = "pm-multi-lm-search";
searchInput.placeholder = "Search LoRAs to add\u2026";
searchInput.rows = 1;
searchInput.addEventListener("focus", () => setActiveSlot(node, slotDef.key));
// Attach LM autocomplete to the search textarea
new lm.AutoComplete(searchInput, "loras", { showPreview: false });
const initialState = parseLorasState(stateWidget?.value ?? "[]");
let isSyncing = false;
const embedded = createEmbeddedLorasWidget(
node, lm, `${slotDef.key}_loras`, initialState,
(value) => {
if (isSyncing) return;
isSyncing = true;
try {
const safe = Array.isArray(value) ? value : [];
writeLorasState(stateWidget, safe);
const nextText = lm.applyLoraValuesToText(searchInput.value || "", safe);
if (searchInput.value !== nextText) searchInput.value = nextText;
} finally {
isSyncing = false;
notifyHeightChange(node);
}
},
);
// When user types or autocomplete fires, merge into the loras list
searchInput.addEventListener("input", () => {
if (isSyncing) return;
isSyncing = true;
try {
const existing = Array.isArray(embedded.widget?.value) ? embedded.widget.value : [];
const merged = lm.mergeLoras(searchInput.value || "", existing);
if (embedded.widget) embedded.widget.value = merged;
writeLorasState(stateWidget, merged);
} finally {
isSyncing = false;
notifyHeightChange(node);
}
});
col.appendChild(title);
col.appendChild(searchInput);
col.appendChild(embedded.host);
embedded.host.addEventListener("pointerdown", () => setActiveSlot(node, slotDef.key));
return { key: slotDef.key, stateWidget, searchInput, lorasWidget: embedded.widget, col };
}
// ---------------------------------------------------------------------------
// Restore widget state from persisted JSON
// ---------------------------------------------------------------------------
function refreshFromStoredValues(node) {
if (!node?.__pmMultiLmSlots || !node.__pmMultiLmBridge) return;
for (const slot of node.__pmMultiLmSlots) {
const state = parseLorasState(slot.stateWidget?.value ?? "[]");
// Restore from persisted JSON directly. Do NOT call mergeLoras here:
// mergeLoras requires syntax in text input, and would drop entries
// during tab-switch/workflow-load when textarea is initially empty.
if (slot.lorasWidget) slot.lorasWidget.value = state;
writeLorasState(slot.stateWidget, state);
// Keep syntax textarea consistent with restored list.
const nextText = node.__pmMultiLmBridge.applyLoraValuesToText(slot.searchInput.value || "", state);
if (slot.searchInput.value !== nextText) slot.searchInput.value = nextText;
}
notifyHeightChange(node);
}
// ---------------------------------------------------------------------------
// Main async UI setup
// ---------------------------------------------------------------------------
async function setupNodeUi(node) {
if (!node || node.__pmMultiLmReady) return;
ensureStyles();
const lm = await loadLmBridge();
if (!lm || node.__pmMultiLmReady) return;
hideStateWidgets(node);
const root = document.createElement("div");
root.className = "pm-multi-lm-root";
// 4-column LoRA grid
const grid = document.createElement("div");
grid.className = "pm-multi-lm-grid";
root.appendChild(grid);
const slots = SLOT_DEFS.map((slotDef) => {
const slot = buildSlotColumn(node, lm, slotDef);
grid.appendChild(slot.col);
return slot;
});
const uiWidget = node.addDOMWidget("multi_lora_ui", "div", root, {
serialize: false,
hideOnZoom: false,
getMinHeight: () => computeContentHeight(node),
getHeight: () => "100%",
});
node.__pmMultiLmBridge = lm;
node.__pmMultiLmSlots = slots;
node.__pmMultiLmRoot = root;
node.__pmMultiLmReady = true;
node.__pmMultiLmRefresh = () => {
refreshFromStoredValues(node);
updateActiveColumnHighlight(node);
};
// comfyClass already set synchronously in onNodeCreated — no registry tricks needed
// Restore any lora data that onConfigure may have written before async completed
refreshFromStoredValues(node);
hideStateWidgets(node);
updateActiveColumnHighlight(node);
notifyHeightChange(node);
applyNodeSizeConstraints(node);
}
// ---------------------------------------------------------------------------
// Extension registration
// ---------------------------------------------------------------------------
app.registerExtension({
name: "PromptManager.MultiLoraStackerLM",
async beforeRegisterNodeDef(nodeType) {
if (nodeType.comfyClass !== NODE_CLASS) return;
// Attach the send-to-node listener once, immediately (synchronous)
attachLoraCodeListener();
// Ensure prompt uses backend class while keeping LM comfyClass at runtime.
attachPromptSerializationShim();
// ── onNodeCreated ──────────────────────────────────────────────────
const onNodeCreated = nodeType.prototype.onNodeCreated;
nodeType.prototype.onNodeCreated = function () {
const result = onNodeCreated ? onNodeCreated.apply(this, arguments) : undefined;
this.serialize_widgets = true;
// Set comfyClass SYNCHRONOUSLY so LM WorkflowRegistry includes us
// on the next lora_registry_refresh sweep
this.comfyClass = LM_PROVIDER_CLASS;
if (!this.properties) this.properties = {};
if (!this.properties.pmActiveSlot) this.properties.pmActiveSlot = "model_a";
applyNodeSizeConstraints(this, true);
void setupNodeUi(this);
return result;
};
// ── onConfigure (workflow load / tab switch) ──────────────────────
const onConfigure = nodeType.prototype.onConfigure;
nodeType.prototype.onConfigure = function (config) {
const result = onConfigure ? onConfigure.apply(this, arguments) : undefined;
// Re-assert comfyClass in case ComfyUI reset it during configure
this.comfyClass = LM_PROVIDER_CLASS;
hideStateWidgets(this);
if (typeof this.__pmMultiLmRefresh === "function") {
this.__pmMultiLmRefresh();
}
applyNodeSizeConstraints(this);
return result;
};
const onModeChange = nodeType.prototype.onModeChange;
nodeType.prototype.onModeChange = function () {
const result = onModeChange ? onModeChange.apply(this, arguments) : undefined;
hideStateWidgets(this);
if (typeof this.__pmMultiLmRefresh === "function") {
this.__pmMultiLmRefresh();
}
applyNodeSizeConstraints(this);
return result;
};
const onResize = nodeType.prototype.onResize;
nodeType.prototype.onResize = function () {
const result = onResize ? onResize.apply(this, arguments) : undefined;
applyNodeSizeConstraints(this);
return result;
};
// ── onRemoved ──────────────────────────────────────────────────────
const onRemoved = nodeType.prototype.onRemoved;
nodeType.prototype.onRemoved = function () {
this.__pmMultiLmSlots = null;
this.__pmMultiLmRoot = null;
this.__pmMultiLmBridge = null;
this.__pmMultiLmReady = false;
this.__pmMultiLmRefresh = null;
return onRemoved ? onRemoved.apply(this, arguments) : undefined;
};
},
});
+1259 -91
View File
File diff suppressed because it is too large Load Diff
+276 -77
View File
@@ -106,20 +106,116 @@ app.registerExtension({
console.error("[PromptManager] Error saving Close Llama preference:", error);
});
}
},
{
id: "PromptManager.WarnUnsavedChanges",
category: ["Prompt Manager", "4. Advanced Preferences", "Warn Unsaved Changes"],
name: "Warn about unsaved prompt changes",
tooltip: "Show a warning when switching prompts if there are unsaved changes to the current prompt text, LoRAs, or trigger words.",
type: "boolean",
defaultValue: true
},
{
id: "PromptManager.DefaultHideNSFW",
category: ["Prompt Manager", "4. Advanced Preferences", "Hide NSFW by Default"],
name: "Hide NSFW prompts by default",
tooltip: "When enabled, NSFW categories and prompts are hidden in the prompt browser on startup. Can be toggled per session.",
type: "boolean",
defaultValue: true
},
{
id: "PromptManager.DefaultViewMode",
category: ["Prompt Manager", "4. Advanced Preferences", "Prompt Browser View Mode"],
name: "Default prompt browser view mode",
tooltip: "Choose the default display mode for the prompt browser: thumbnails grid or compact list view.",
type: "combo",
options: ["thumbnails", "list"],
defaultValue: "thumbnails"
},
{
id: "PromptManager.EnableThumbnailPreview",
category: ["Prompt Manager", "4. Advanced Preferences", "Enable Thumbnail Hover Preview"],
name: "Enable thumbnail hover preview",
tooltip: "When enabled, hovering over thumbnails in the prompt browser shows a larger preview after a short delay.",
type: "boolean",
defaultValue: true
},
{
id: "PromptManager.ThumbnailCheckpoint",
category: ["Prompt Manager", "4. Advanced Preferences", "Thumbnail Generation Checkpoint"],
name: "Checkpoint for thumbnail generation",
tooltip: "The checkpoint model used when generating thumbnails via right-click menu. Can also be changed from the prompt context menu.",
type: "text",
defaultValue: ""
},
{
id: "PromptManager.LLMBackend",
category: ["Prompt Manager", "5. Ollama Settings", "LLM Backend"],
name: "LLM Backend",
tooltip: "Choose the LLM backend: llama.cpp (local server, default) or Ollama",
type: "combo",
options: ["llama.cpp", "ollama"],
defaultValue: "llama.cpp",
onChange(value) {
fetch("/prompt-manager/save-preference", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ key: "llm_backend", value: value })
}).catch(error => {
console.error("[PromptManager] Error saving LLM backend preference:", error);
});
}
},
{
id: "PromptManager.OllamaUrl",
category: ["Prompt Manager", "5. Ollama Settings", "Ollama URL"],
name: "Ollama URL",
tooltip: "URL of the Ollama server (default: http://127.0.0.1:11434)",
type: "text",
defaultValue: "http://127.0.0.1:11434",
onChange(value) {
fetch("/prompt-manager/save-preference", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ key: "ollama_url", value: value })
}).catch(error => {
console.error("[PromptManager] Error saving Ollama URL preference:", error);
});
}
},
{
id: "PromptManager.OllamaKeepAlive",
category: ["Prompt Manager", "5. Ollama Settings", "Keep Alive Duration"],
name: "Keep Alive Duration",
tooltip: "How long Ollama keeps the model loaded in memory after a request. Examples: '5m' (5 minutes), '30m', '1h', '0' (unload immediately), '-1' (keep forever). Default: 5m",
type: "text",
defaultValue: "5m",
onChange(value) {
fetch("/prompt-manager/save-preference", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ key: "ollama_keep_alive", value: value })
}).catch(error => {
console.error("[PromptManager] Error saving Ollama keep alive preference:", error);
});
}
}
],
async setup() {
// Load settings from ComfyUI and sync to Python cache
try {
// Sync current values to Python cache first
const baseModel = app.ui.settings.getSettingValue("PromptManager.PreferredBaseModel", "");
const visionModel = app.ui.settings.getSettingValue("PromptManager.PreferredVisionModel", "");
const llamaPath = app.ui.settings.getSettingValue("PromptManager.LlamaPath", "");
const modelPath = app.ui.settings.getSettingValue("PromptManager.ModelPath", "");
const port = app.ui.settings.getSettingValue("PromptManager.Port", "8080");
const CloseLlama = app.ui.settings.getSettingValue("PromptManager.CloseLlama", true);
const baseModel = app.ui.settings.getSettingValue("PromptManager.PreferredBaseModel");
const visionModel = app.ui.settings.getSettingValue("PromptManager.PreferredVisionModel");
const llamaPath = app.ui.settings.getSettingValue("PromptManager.LlamaPath");
const modelPath = app.ui.settings.getSettingValue("PromptManager.ModelPath");
const port = app.ui.settings.getSettingValue("PromptManager.Port");
const CloseLlama = app.ui.settings.getSettingValue("PromptManager.CloseLlama");
const llmBackend = app.ui.settings.getSettingValue("PromptManager.LLMBackend");
const ollamaUrl = app.ui.settings.getSettingValue("PromptManager.OllamaUrl");
const ollamaKeepAlive = app.ui.settings.getSettingValue("PromptManager.OllamaKeepAlive");
console.log("[PromptManager] Syncing preferences:", { baseModel, visionModel, llamaPath, modelPath, port, CloseLlama });
console.log("[PromptManager] Syncing preferences:", { baseModel, visionModel, llamaPath, modelPath, port, CloseLlama, llmBackend, ollamaUrl, ollamaKeepAlive });
await fetch("/prompt-manager/save-preference", {
method: "POST",
headers: { "Content-Type": "application/json" },
@@ -150,6 +246,21 @@ app.registerExtension({
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ key: "close_llama_on_exit", value: CloseLlama })
});
await fetch("/prompt-manager/save-preference", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ key: "llm_backend", value: llmBackend })
});
await fetch("/prompt-manager/save-preference", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ key: "ollama_url", value: ollamaUrl })
});
await fetch("/prompt-manager/save-preference", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ key: "ollama_keep_alive", value: ollamaKeepAlive })
});
} catch (error) {
console.error("[PromptManager] Error syncing preferences:", error);
}
@@ -228,7 +339,7 @@ app.registerExtension({
// Load prompts asynchronously (data only, not widgets)
loadPrompts(node).then(() => {
filterPromptDropdown(node);
filterPromptDropdown(node, { preserveDanglingSelection: true });
// Ensure height is sufficient after data is loaded
setTimeout(() => {
@@ -251,17 +362,24 @@ app.registerExtension({
const result = onConfigure?.apply(this, arguments);
const node = this;
// Mark workflow restore so async onNodeCreated load does not coerce selection.
node._configuredFromWorkflow = true;
node._restoringFromWorkflow = true;
// Reload prompts from server and reapply filtering
setTimeout(() => {
loadPrompts(node).then(() => {
filterPromptDropdown(node);
try {
filterPromptDropdown(node, { preserveDanglingSelection: true });
// Reattach button bar if needed
if (!node.buttonBarAttached) {
addButtonBar(node);
setupCategoryChangeHandler(node);
setupUseExternalToggleHandler(node);
// Reattach button bar if needed
if (!node.buttonBarAttached) {
addButtonBar(node);
setupCategoryChangeHandler(node);
setupUseExternalToggleHandler(node);
}
} finally {
node._restoringFromWorkflow = false;
}
});
}, 100);
@@ -269,6 +387,53 @@ app.registerExtension({
return result;
};
// Draw red NSFW badge at the top of the node when NSFW content is selected
const onDrawForeground = nodeType.prototype.onDrawForeground;
nodeType.prototype.onDrawForeground = function(ctx) {
if (onDrawForeground) onDrawForeground.apply(this, arguments);
const hideNSFW = app.ui.settings.getSettingValue("PromptManager.DefaultHideNSFW");
if (hideNSFW || !this.prompts) return;
const categoryWidget = this.widgets?.find(w => w.name === "category");
const promptWidget = this.widgets?.find(w => w.name === "name");
if (!categoryWidget || !promptWidget) return;
const category = categoryWidget.value;
const promptName = promptWidget.value;
const catIsNSFW = this.prompts[category]?.["__meta__"]?.nsfw === true;
const promptIsNSFW = this.prompts[category]?.[promptName]?.nsfw === true;
if (catIsNSFW || promptIsNSFW) {
ctx.save();
// Draw red "NSFW" badge at top-right of node
const text = "NSFW";
ctx.font = "bold 8px sans-serif";
const textWidth = ctx.measureText(text).width;
const badgeW = textWidth + 8;
const badgeH = 12;
const badgeX = this.size[0] - badgeW - 4;
const badgeY = -LiteGraph.NODE_TITLE_HEIGHT + (LiteGraph.NODE_TITLE_HEIGHT - badgeH) / 2;
// Badge background
ctx.fillStyle = "rgba(204, 50, 50, 0.85)";
ctx.beginPath();
if (ctx.roundRect) {
ctx.roundRect(badgeX, badgeY, badgeW, badgeH, 2);
} else {
ctx.rect(badgeX, badgeY, badgeW, badgeH);
}
ctx.fill();
// Badge text
ctx.fillStyle = "#fff";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(text, badgeX + badgeW / 2, badgeY + badgeH / 2);
ctx.restore();
}
};
// Enforce minimum node width
const onResize = nodeType.prototype.onResize;
nodeType.prototype.onResize = function(size) {
@@ -365,15 +530,52 @@ function hasUnsavedChanges(node) {
return currentText !== savedText;
}
function filterPromptDropdown(node) {
function filterPromptDropdown(node, options = {}) {
const preserveDanglingSelection = options?.preserveDanglingSelection === true;
// Filter name dropdown to only show prompts from current category
const categoryWidget = node.widgets.find(w => w.name === "category");
const promptWidget = node.widgets.find(w => w.name === "name");
if (categoryWidget && promptWidget) {
const hideNSFW = app.ui.settings.getSettingValue("PromptManager.DefaultHideNSFW");
// Filter NSFW categories from the category dropdown
if (node.prompts) {
let categories = Object.keys(node.prompts).sort((a, b) => a.localeCompare(b));
const currentCategoryValue = String(categoryWidget.value || "");
if (hideNSFW) {
categories = categories.filter(cat => node.prompts[cat]?.["__meta__"]?.nsfw !== true);
}
let categoryOptions = categories.length > 0 ? [...categories] : ["Default"];
if (preserveDanglingSelection && currentCategoryValue && !categoryOptions.includes(currentCategoryValue)) {
categoryOptions = [currentCategoryValue, ...categoryOptions];
}
categoryWidget.options.values = categoryOptions;
// If current category is now hidden, switch only when we are not preserving
// workflow-restored dangling selections.
if (!categoryOptions.includes(categoryWidget.value) && categories.length > 0) {
categoryWidget.value = categories[0];
}
}
const currentCategory = categoryWidget.value;
if (node.prompts[currentCategory]) {
const promptNames = Object.keys(node.prompts[currentCategory]).sort((a, b) => a.localeCompare(b));
let promptNames = Object.keys(node.prompts[currentCategory]).filter(k => k !== '__meta__').sort((a, b) => a.localeCompare(b));
if (hideNSFW) {
const catIsNSFW = node.prompts[currentCategory]?.["__meta__"]?.nsfw === true;
if (catIsNSFW) {
promptNames = [];
} else {
promptNames = promptNames.filter(name => !node.prompts[currentCategory][name]?.nsfw);
}
}
const currentPromptValue = String(promptWidget.value || "");
if (preserveDanglingSelection && currentPromptValue && !promptNames.includes(currentPromptValue)) {
promptNames = [currentPromptValue, ...promptNames];
}
if (promptNames.length === 0) {
promptNames.push("");
}
@@ -428,7 +630,7 @@ function addButtonBar(node) {
// Case-insensitive check for existing prompt
let existingPromptName = null;
if (node.prompts[targetCategory]) {
const existingNames = Object.keys(node.prompts[targetCategory]);
const existingNames = Object.keys(node.prompts[targetCategory]).filter(k => k !== '__meta__');
existingPromptName = existingNames.find(name => name.toLowerCase() === promptName.toLowerCase());
}
@@ -460,16 +662,16 @@ function addButtonBar(node) {
}
});
// New Prompt button with category selection
// New Prompt button - simply clears fields for a fresh start
const newPromptBtn = createButton("New Prompt", async () => {
// Check for unsaved changes before creating new prompt
const hasUnsaved = hasUnsavedChanges(node);
const warnEnabled = app.ui.settings.getSettingValue("PromptManager.warnUnsavedChanges", true);
const warnEnabled = app.ui.settings.getSettingValue("PromptManager.warnUnsavedChanges");
if (hasUnsaved && warnEnabled) {
const confirmed = await showConfirm(
"Unsaved Changes",
"You have unsaved changes to the current prompt. Do you want to discard them and create a new prompt?",
"You have unsaved changes to the current prompt. Do you want to discard them and start fresh?",
"Discard & Continue",
"#f80"
);
@@ -478,59 +680,27 @@ function addButtonBar(node) {
}
}
const categories = Object.keys(node.prompts || {}).sort((a, b) => a.localeCompare(b));
// Keep the current category, just clear the prompt selection and content
const currentCategory = categoryWidget.value;
const result = await showPromptWithCategory(
"New Prompt",
"Enter new prompt name:",
"",
categories,
currentCategory
);
// Clear prompt selection (set to empty/placeholder)
promptWidget.value = "";
textWidget.value = "";
if (result && result.name && result.name.trim()) {
const promptName = result.name.trim();
const targetCategory = result.category;
// Check for existing prompt
let existingPromptName = null;
if (node.prompts[targetCategory]) {
const existingNames = Object.keys(node.prompts[targetCategory]);
existingPromptName = existingNames.find(name => name.toLowerCase() === promptName.toLowerCase());
}
if (existingPromptName) {
await showInfo(
"Prompt Exists",
`Prompt "${existingPromptName}" already exists in category "${targetCategory}".`
);
return;
}
// Set up UI for new prompt (temporary, not saved yet)
// User must click "Save Prompt" to persist it
categoryWidget.value = targetCategory;
// Add prompt name to dropdown temporarily so it can be selected
if (!promptWidget.options.values.includes(promptName)) {
promptWidget.options.values = [...promptWidget.options.values, promptName].sort((a, b) => a.localeCompare(b));
}
promptWidget.value = promptName;
textWidget.value = "";
// Mark as unsaved/new prompt
node.isNewUnsavedPrompt = true;
node.newPromptCategory = targetCategory;
node.newPromptName = promptName;
// Update previous values so cancel/revert works correctly
node._previousCategory = targetCategory;
node._previousPrompt = promptName;
node.serialize_widgets = true;
app.graph.setDirtyCanvas(true, true);
}
// Update previous values for cancel/revert
node._previousCategory = currentCategory;
node._previousPrompt = "";
// Mark as new unsaved prompt state
node.isNewUnsavedPrompt = true;
node.newPromptCategory = currentCategory;
node.newPromptName = null;
// Clear the last saved state since this is a brand new prompt
node.lastSavedState = null;
node.serialize_widgets = true;
app.graph.setDirtyCanvas(true, true);
});
// More dropdown button
@@ -618,6 +788,13 @@ function setupCategoryChangeHandler(node) {
// Update prompt dropdown when category changes
categoryWidget.callback = async function(value) {
if (node._restoringFromWorkflow) {
if (originalCallback) {
originalCallback.apply(this, arguments);
}
return;
}
if (originalCallback) {
originalCallback.apply(this, arguments);
}
@@ -627,7 +804,11 @@ function setupCategoryChangeHandler(node) {
const category = value;
if (node.prompts && node.prompts[category]) {
const promptNames = Object.keys(node.prompts[category]).sort((a, b) => a.localeCompare(b));
const hideNSFW = app.ui.settings.getSettingValue("PromptManager.DefaultHideNSFW");
let promptNames = Object.keys(node.prompts[category]).filter(k => k !== '__meta__').sort((a, b) => a.localeCompare(b));
if (hideNSFW) {
promptNames = promptNames.filter(name => !node.prompts[category][name]?.nsfw);
}
promptWidget.options.values = promptNames;
if (promptNames.length > 0) {
@@ -654,6 +835,13 @@ function setupCategoryChangeHandler(node) {
// Update text widget when prompt selection changes
promptWidget.callback = async function(value) {
if (node._restoringFromWorkflow) {
if (originalPromptCallback) {
originalPromptCallback.apply(this, arguments);
}
return;
}
if (originalPromptCallback) {
originalPromptCallback.apply(this, arguments);
}
@@ -665,7 +853,11 @@ function setupCategoryChangeHandler(node) {
// Update prompt dropdown options in case prompts were deleted/added in another tab
if (node.prompts && node.prompts[category]) {
const promptNames = Object.keys(node.prompts[category]).sort((a, b) => a.localeCompare(b));
const hideNSFW = app.ui.settings.getSettingValue("PromptManager.DefaultHideNSFW");
let promptNames = Object.keys(node.prompts[category]).filter(k => k !== '__meta__').sort((a, b) => a.localeCompare(b));
if (hideNSFW) {
promptNames = promptNames.filter(name => !node.prompts[category][name]?.nsfw);
}
promptWidget.options.values = promptNames.length > 0 ? promptNames : [""];
// Check if selected prompt still exists after reload
@@ -701,14 +893,14 @@ function setupCategoryChangeHandler(node) {
if (node.prompts && categoryWidget && newValues && newValues.length > 0) {
const currentCategory = categoryWidget.value;
if (node.prompts[currentCategory]) {
const categoryPrompts = Object.keys(node.prompts[currentCategory]);
const categoryPrompts = Object.keys(node.prompts[currentCategory]).filter(k => k !== '__meta__');
const hasOtherCategoryPrompts = newValues.some(val =>
val !== "" && !categoryPrompts.includes(val)
);
if (hasOtherCategoryPrompts) {
setTimeout(() => {
filterPromptDropdown(node);
filterPromptDropdown(node, { preserveDanglingSelection: node._restoringFromWorkflow === true });
}, 50);
}
}
@@ -1443,8 +1635,12 @@ function updateDropdowns(node) {
if (!categoryWidget || !promptWidget || !textWidget) return;
// Update category dropdown (sorted alphabetically)
const categories = Object.keys(node.prompts).sort((a, b) => a.localeCompare(b));
categoryWidget.options.values = categories;
const hideNSFW = app.ui.settings.getSettingValue("PromptManager.DefaultHideNSFW");
let categories = Object.keys(node.prompts).sort((a, b) => a.localeCompare(b));
if (hideNSFW) {
categories = categories.filter(cat => node.prompts[cat]?.["__meta__"]?.nsfw !== true);
}
categoryWidget.options.values = categories.length > 0 ? categories : ["Default"];
if (!node.prompts[categoryWidget.value] && categories.length > 0) {
categoryWidget.value = categories[0];
@@ -1453,7 +1649,10 @@ function updateDropdowns(node) {
// Update prompt dropdown for current category (sorted alphabetically)
const currentCategory = categoryWidget.value;
if (node.prompts[currentCategory]) {
const promptNames = Object.keys(node.prompts[currentCategory]).sort((a, b) => a.localeCompare(b));
let promptNames = Object.keys(node.prompts[currentCategory]).filter(k => k !== '__meta__').sort((a, b) => a.localeCompare(b));
if (hideNSFW) {
promptNames = promptNames.filter(name => !node.prompts[currentCategory][name]?.nsfw);
}
if (promptNames.length === 0) {
promptNames.push("");
File diff suppressed because it is too large Load Diff
+227
View File
@@ -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);
}
};
}
});
+4890
View File
File diff suppressed because it is too large Load Diff
+456
View File
@@ -0,0 +1,456 @@
/**
* RecipeModelLoader extension.
* Shows color-coded loaded assets (Model/VAE/CLIP) from workflow_data.
*/
import { app } from "../../scripts/app.js";
const MODEL_CHOICES = ["model_a", "model_b"];
const WEIGHT_DTYPE_CHOICES = ["default", "fp8_e4m3fn", "fp8_e4m3fn_fast", "fp8_e5m2"];
function _trimMiddle(text, maxLen) {
const s = String(text || "");
if (s.length <= maxLen) return s;
const left = Math.ceil((maxLen - 3) / 2);
const right = Math.floor((maxLen - 3) / 2);
return `${s.slice(0, left)}...${s.slice(s.length - right)}`;
}
function _shortName(name) {
const raw = String(name || "").trim();
if (!raw) return "";
const normalized = raw.replace(/\\/g, "/");
const base = normalized.split("/").pop() || normalized;
return base.replace(/\.(safetensors|ckpt|pt|pth|bin|gguf|sft)$/i, "");
}
function _shortList(names) {
const list = Array.isArray(names) ? names : [];
return list.map(_shortName).filter(Boolean);
}
const COLORS = {
modelCheckpoint: "#4CAF50",
modelDiffusion: "#2196F3",
modelGguf: "#FF9800",
vae: "#FF6B6B",
clip: "#C4A300",
notFound: "#F44336",
muted: "#B0B0B0",
missing: "#E57373",
};
function _buildRows(info) {
const status = String(info.status || "").toLowerCase();
if (!info || status === "idle") {
return [
{ label: "Model", labelColor: COLORS.modelDiffusion, value: "(awaiting execution)", valueColor: COLORS.muted },
{ label: "Clip", labelColor: COLORS.clip, value: "(awaiting execution)", valueColor: COLORS.muted },
{ label: "Vae", labelColor: COLORS.vae, value: "(awaiting execution)", valueColor: COLORS.muted },
];
}
const modelKind = String(info.model_kind || info.loader_type || "").toLowerCase();
const modelColor = modelKind === "checkpoint"
? COLORS.modelCheckpoint
: (modelKind === "gguf" ? COLORS.modelGguf : COLORS.modelDiffusion);
const rows = [];
const modelShort = _shortName(info.model_name || "");
rows.push({
label: "Model",
labelColor: modelColor,
value: modelShort || "(none)",
valueColor: modelShort ? "#CCCCCC" : COLORS.missing,
});
const loaderType = String(info.loader_type || "").toLowerCase();
const vaeShort = _shortName(info.vae_name || "");
const clipShort = _shortList(info.clip_names);
if (loaderType === "checkpoint") {
// Keep all tags visible; show source explicitly for checkpoint-provided assets.
const usingInternalVae = !!info.uses_checkpoint_vae;
const usingInternalClip = !!info.uses_checkpoint_clip;
rows.push({
label: "Clip",
labelColor: COLORS.clip,
value: usingInternalClip ? "From Checkpoint" : (clipShort.length > 0 ? clipShort.join(", ") : "(none provided)"),
valueColor: usingInternalClip ? COLORS.muted : (clipShort.length > 0 ? "#CCCCCC" : COLORS.missing),
});
rows.push({
label: "Vae",
labelColor: COLORS.vae,
value: usingInternalVae ? "From Checkpoint" : (vaeShort || "(none provided)"),
valueColor: usingInternalVae ? COLORS.muted : (vaeShort ? "#CCCCCC" : COLORS.missing),
});
} else {
// Diffusion/UNet: always show Clip + Vae lines.
rows.push({
label: "Clip",
labelColor: COLORS.clip,
value: clipShort.length > 0 ? clipShort.join(", ") : "(none provided)",
valueColor: clipShort.length > 0 ? "#CCCCCC" : COLORS.missing,
});
rows.push({
label: "Vae",
labelColor: COLORS.vae,
value: vaeShort || "(none provided)",
valueColor: vaeShort ? "#CCCCCC" : COLORS.missing,
});
}
return rows;
}
function _drawPillRow(ctx, row, y, widgetWidth) {
const left = 8;
const badgeText = String(row.label || "");
const value = String(row.value || "");
const badgeW = 68;
const valueX = left + badgeW + 10;
const valueMax = Math.max(16, Math.floor((widgetWidth - valueX - 8) / 6));
const displayValue = _trimMiddle(value, valueMax);
ctx.font = "bold 11px Arial";
const badgeH = 16;
const badgeY = y - Math.floor(badgeH / 2);
ctx.fillStyle = row.labelColor || COLORS.muted;
ctx.beginPath();
ctx.roundRect(left, badgeY, badgeW, badgeH, 8);
ctx.fill();
ctx.fillStyle = "#FFFFFF";
ctx.textAlign = "left";
ctx.textBaseline = "middle";
ctx.fillText(badgeText, left + 8, y + 0.5);
ctx.font = "12px Arial";
ctx.fillStyle = row.valueColor || "#CCCCCC";
ctx.fillText(displayValue, valueX, y + 0.5);
}
function _getWidgetValue(node, name, fallback = "") {
const w = node?.widgets?.find((x) => x.name === name);
if (!w || w.value == null) return fallback;
return String(w.value);
}
function _widgetByNames(node, names) {
const arr = Array.isArray(names) ? names : [names];
return node?.widgets?.find((w) => arr.includes(w.name));
}
function _sanitizeChoice(value, allowed, fallback) {
const v = String(value ?? "");
return allowed.includes(v) ? v : fallback;
}
function _selectedModelSlot(node) {
return _sanitizeChoice(
_getWidgetValue(node, "model", "model_a"),
MODEL_CHOICES,
"model_a"
);
}
function _readWidgetState(node) {
const modelWidget = _widgetByNames(node, ["model"]);
const dtypeWidget = _widgetByNames(node, ["weight_dtype"]);
return {
model: _sanitizeChoice(modelWidget?.value, MODEL_CHOICES, "model_a"),
weight_dtype: _sanitizeChoice(dtypeWidget?.value, WEIGHT_DTYPE_CHOICES, "default"),
};
}
function _applyWidgetState(node, state, { persist = true } = {}) {
const modelWidget = _widgetByNames(node, ["model"]);
const dtypeWidget = _widgetByNames(node, ["weight_dtype"]);
const modelVal = _sanitizeChoice(state?.model, MODEL_CHOICES, "model_a");
const dtypeVal = _sanitizeChoice(state?.weight_dtype, WEIGHT_DTYPE_CHOICES, "default");
if (modelWidget) modelWidget.value = modelVal;
if (dtypeWidget) dtypeWidget.value = dtypeVal;
if (persist) {
node.properties = node.properties || {};
node.properties.wfml_model = modelVal;
node.properties.wfml_weight_dtype = dtypeVal;
}
}
function _restoreOrNormalizeWidgetState(node) {
node.properties = node.properties || {};
const live = _readWidgetState(node);
const savedModel = _sanitizeChoice(node.properties.wfml_model, MODEL_CHOICES, "");
const savedDtype = _sanitizeChoice(node.properties.wfml_weight_dtype, WEIGHT_DTYPE_CHOICES, "");
_applyWidgetState(node, {
model: savedModel || live.model || "model_a",
weight_dtype: savedDtype || live.weight_dtype || "default",
}, { persist: true });
}
function _isRerouteNode(n) {
const t = String(n?.type || "").toLowerCase();
const c = String(n?.comfyClass || "").toLowerCase();
return t.includes("reroute") || c.includes("reroute");
}
function _resolveWorkflowUpstreamLink(node) {
const wfInputIdx = (node.inputs || []).findIndex((i) => i?.name === "recipe_data");
if (wfInputIdx < 0) return null;
let linkId = node.inputs[wfInputIdx]?.link;
if (linkId == null) return null;
const graph = node.graph;
const seen = new Set();
for (let hop = 0; hop < 24; hop++) {
if (linkId == null || seen.has(linkId)) break;
seen.add(linkId);
const li = graph?.links?.[linkId];
if (!li) break;
const src = graph?.getNodeById?.(li.origin_id);
if (!src) break;
if (!_isRerouteNode(src)) {
return { sourceNode: src, sourceSlot: li.origin_slot };
}
const in0 = src.inputs?.[0];
linkId = in0?.link ?? null;
}
return null;
}
function _tryParseWorkflowData(value) {
if (!value) return null;
if (typeof value === "object") return value;
if (typeof value === "string") {
try {
const p = JSON.parse(value);
if (p && typeof p === "object") return p;
} catch {
return null;
}
}
return null;
}
function _clipListFromWf(wf) {
const c = wf?.clip;
if (Array.isArray(c)) return c.filter(Boolean);
if (typeof c === "string" && c) return [c];
if (c && Array.isArray(c.names)) return c.names.filter(Boolean);
return [];
}
function _vaeFromWf(wf) {
const v = wf?.vae;
if (typeof v === "string") return v;
if (v && typeof v === "object" && typeof v.name === "string") return v.name;
return "";
}
function _inferInfoFromWorkflowData(node, wf) {
const modelKey = _selectedModelSlot(node);
const modelName = typeof wf?.[modelKey] === "string" ? wf[modelKey] : "";
if (!modelName) return null;
const loaderType = String(wf?.loader_type || "").toLowerCase();
const selectedLower = modelName.toLowerCase();
const modelKind = loaderType === "checkpoint"
? "checkpoint"
: (selectedLower.endsWith(".gguf") ? "gguf" : "diffusion");
const vaeName = _vaeFromWf(wf);
const clipNames = _clipListFromWf(wf);
return {
model: modelKey,
model_name: _shortName(modelName),
loader_type: loaderType,
model_kind: modelKind,
vae_name: vaeName,
clip_names: clipNames,
status: "ok",
error_message: "",
missing_name: "",
uses_checkpoint_vae: (loaderType === "checkpoint" && !vaeName),
uses_checkpoint_clip: (loaderType === "checkpoint" && clipNames.length === 0),
};
}
function _refreshInfoFromUpstream(node) {
const resolved = _resolveWorkflowUpstreamLink(node);
if (!resolved) return false;
const { sourceNode, sourceSlot } = resolved;
const out = sourceNode?.outputs?.[sourceSlot];
const wfFromOutput = _tryParseWorkflowData(out?._data) || _tryParseWorkflowData(out?.value);
const wfFromBuilderCache = _tryParseWorkflowData(sourceNode?.properties?.we_extracted_cache);
const wf = wfFromOutput || wfFromBuilderCache;
if (!wf) return false;
const inferred = _inferInfoFromWorkflowData(node, wf);
if (!inferred) return false;
node._applyRecipeModelLoaderInfo(inferred);
return true;
}
function _defaultInfoFromWidgets(node) {
const selected = _selectedModelSlot(node);
return {
model: selected,
model_name: "",
loader_type: "",
model_kind: "",
vae_name: "",
clip_names: [],
status: "idle",
error_message: "",
missing_name: "",
uses_checkpoint_vae: false,
uses_checkpoint_clip: false,
};
}
app.registerExtension({
name: "PromptManager.RecipeModelLoader",
async beforeRegisterNodeDef(nodeType, nodeData) {
if (nodeData.name !== "RecipeModelLoader") return;
const origOnExecuted = nodeType.prototype.onExecuted;
nodeType.prototype.onExecuted = function (message) {
origOnExecuted?.apply(this, arguments);
const info = message?.workflow_model_loader_info?.[0];
if (!info) return;
this._applyRecipeModelLoaderInfo(info);
};
nodeType.prototype._applyRecipeModelLoaderInfo = function (info) {
const selected = _sanitizeChoice(info.model, MODEL_CHOICES, "model_a");
this._recipeModelLoaderInfo = {
model: selected,
model_name: info.model_name || "",
loader_type: info.loader_type || "",
model_kind: info.model_kind || "",
vae_name: info.vae_name || "",
clip_names: Array.isArray(info.clip_names) ? info.clip_names : [],
status: info.status || "ok",
error_message: info.error_message || "",
missing_name: info.missing_name || "",
uses_checkpoint_vae: !!info.uses_checkpoint_vae,
uses_checkpoint_clip: !!info.uses_checkpoint_clip,
};
this._ensureRecipeModelInfoWidget();
this.setDirtyCanvas(true, true);
};
const origOnNodeCreated = nodeType.prototype.onNodeCreated;
nodeType.prototype.onNodeCreated = function () {
const r = origOnNodeCreated?.apply(this, arguments);
_restoreOrNormalizeWidgetState(this);
if (!this._recipeModelLoaderInfo) {
this._recipeModelLoaderInfo = _defaultInfoFromWidgets(this);
}
this._ensureRecipeModelInfoWidget();
_refreshInfoFromUpstream(this);
this.setDirtyCanvas(true, true);
return r;
};
const origOnConnectionsChange = nodeType.prototype.onConnectionsChange;
nodeType.prototype.onConnectionsChange = function () {
const r = origOnConnectionsChange?.apply(this, arguments);
_refreshInfoFromUpstream(this);
this.setDirtyCanvas(true, true);
return r;
};
const origOnWidgetChanged = nodeType.prototype.onWidgetChanged;
nodeType.prototype.onWidgetChanged = function (name, value, oldValue, w) {
const r = origOnWidgetChanged?.apply(this, arguments);
if (name === "model" || name === "weight_dtype") {
_restoreOrNormalizeWidgetState(this);
_refreshInfoFromUpstream(this);
this.setDirtyCanvas(true, true);
}
return r;
};
const origOnSerialize = nodeType.prototype.onSerialize;
nodeType.prototype.onSerialize = function (o) {
origOnSerialize?.apply(this, arguments);
const ws = _readWidgetState(this);
this.properties = this.properties || {};
this.properties.wfml_model = ws.model;
this.properties.wfml_weight_dtype = ws.weight_dtype;
if (this._recipeModelLoaderInfo) {
o._recipeModelLoaderInfo = this._recipeModelLoaderInfo;
o._workflowModelLoaderInfo = this._recipeModelLoaderInfo;
}
if (o) {
o.properties = o.properties || {};
o.properties.wfml_model = ws.model;
o.properties.wfml_weight_dtype = ws.weight_dtype;
}
};
const origOnConfigure = nodeType.prototype.onConfigure;
nodeType.prototype.onConfigure = function (info) {
origOnConfigure?.apply(this, arguments);
_restoreOrNormalizeWidgetState(this);
const state = info?._recipeModelLoaderInfo || info?._workflowModelLoaderInfo;
if (state) {
requestAnimationFrame(() => {
this._applyRecipeModelLoaderInfo(state);
_refreshInfoFromUpstream(this);
});
} else {
requestAnimationFrame(() => {
this._recipeModelLoaderInfo = _defaultInfoFromWidgets(this);
this._ensureRecipeModelInfoWidget();
_refreshInfoFromUpstream(this);
this.setDirtyCanvas(true, true);
});
}
};
nodeType.prototype._ensureRecipeModelInfoWidget = function () {
let widget = this.widgets?.find(w => w.name === "_recipe_model_loader_info");
if (!widget) {
widget = {
name: "_recipe_model_loader_info",
type: "custom",
y: 0,
computeSize: () => {
const rows = _buildRows(this._recipeModelLoaderInfo || {});
const h = Math.max(26, (rows.length * 22) + 6);
return [0, h];
},
draw: function (ctx, node, widgetWidth, y) {
const info = node._recipeModelLoaderInfo;
if (!info) return;
const rows = _buildRows(info);
ctx.save();
ctx.textAlign = "left";
ctx.textBaseline = "middle";
for (let i = 0; i < rows.length; i++) {
const rowY = y + 12 + (i * 22);
const row = rows[i];
_drawPillRow(ctx, row, rowY, widgetWidth);
}
ctx.restore();
},
};
if (!this.widgets) this.widgets = [];
this.widgets.push(widget);
}
this.computeSize();
};
},
});
+120
View File
@@ -0,0 +1,120 @@
/**
* Recipe Model Picker
*
* Keeps Type/Model/VAE/CLIP widgets in sync with Builder family filtering
* and emits a single model_data payload for Recipe Relay.
*/
import { app } from "../../scripts/app.js";
const DEFAULT_ASSET = "(Default)";
const DEFAULT_FAMILY = "sdxl";
function getWidget(node, name) {
return node?.widgets?.find((w) => w.name === name) || null;
}
function setWidgetOptions(widget, values, fallback = "") {
if (!widget?.options) return;
const list = Array.isArray(values) && values.length > 0 ? values : [fallback];
widget.options.values = list;
}
function ensureWidgetValue(widget, preferred, fallback = "") {
if (!widget?.options) return;
const values = Array.isArray(widget.options.values) ? widget.options.values : [];
const candidate = (preferred != null && values.includes(preferred))
? preferred
: (values.includes(widget.value) ? widget.value : null);
widget.value = candidate != null ? candidate : (values[0] ?? fallback);
}
async function fetchJson(url) {
const response = await fetch(url);
return response.json();
}
function familyKeyFromTypeValue(typeValue, familiesMap) {
const raw = String(typeValue || "").trim();
if (!raw) return DEFAULT_FAMILY;
if (familiesMap[raw]) return raw;
for (const [key, label] of Object.entries(familiesMap)) {
if (label === raw) return key;
}
return DEFAULT_FAMILY;
}
async function reloadPickerLists(node) {
const typeWidget = getWidget(node, "type");
const modelWidget = getWidget(node, "model");
const vaeWidget = getWidget(node, "vae");
const clipWidget = getWidget(node, "clip");
if (!typeWidget || !modelWidget || !vaeWidget || !clipWidget) return;
let families = node._recipePickerFamilies;
if (!families) {
try {
const data = await fetchJson("/workflow-extractor/list-families");
families = data?.families || {};
} catch {
families = {};
}
node._recipePickerFamilies = families;
}
const familyKey = familyKeyFromTypeValue(typeWidget.value, families);
const [modelsData, vaesData, clipsData] = await Promise.all([
fetchJson(`/workflow-extractor/list-models?family=${encodeURIComponent(familyKey)}`),
fetchJson(`/workflow-extractor/list-vaes?family=${encodeURIComponent(familyKey)}`),
fetchJson(`/workflow-extractor/list-clips?family=${encodeURIComponent(familyKey)}`),
]).catch(() => [{ models: [] }, { vaes: [] }, { clips: [] }]);
const models = Array.isArray(modelsData?.models) ? modelsData.models : [];
const vaes = Array.isArray(vaesData?.vaes) ? vaesData.vaes : [];
const clips = Array.isArray(clipsData?.clips) ? clipsData.clips : [];
const prevModel = modelWidget.value;
const prevVae = vaeWidget.value;
const prevClip = clipWidget.value;
setWidgetOptions(modelWidget, models, "");
setWidgetOptions(vaeWidget, [DEFAULT_ASSET, ...vaes], DEFAULT_ASSET);
setWidgetOptions(clipWidget, [DEFAULT_ASSET, ...clips], DEFAULT_ASSET);
ensureWidgetValue(modelWidget, prevModel, "");
ensureWidgetValue(vaeWidget, prevVae, DEFAULT_ASSET);
ensureWidgetValue(clipWidget, prevClip, DEFAULT_ASSET);
if (typeof modelWidget.callback === "function") modelWidget.callback(modelWidget.value);
if (typeof vaeWidget.callback === "function") vaeWidget.callback(vaeWidget.value);
if (typeof clipWidget.callback === "function") clipWidget.callback(clipWidget.value);
app.graph.setDirtyCanvas(true, true);
}
app.registerExtension({
name: "prompt-manager.recipe-model-picker",
async nodeCreated(node) {
if (node.comfyClass !== "RecipeModelPicker") return;
const typeWidget = getWidget(node, "type");
if (!typeWidget) return;
const originalTypeCallback = typeWidget.callback;
typeWidget.callback = async function wrappedTypeCallback(value) {
if (typeof originalTypeCallback === "function") {
originalTypeCallback.call(this, value);
}
await reloadPickerLists(node);
};
requestAnimationFrame(() => {
reloadPickerLists(node).catch(() => {
// Keep node usable even if API endpoints are temporarily unavailable.
});
});
},
});
+18
View File
@@ -0,0 +1,18 @@
/**
* Recipe Relay — set a compact default width for newly created nodes.
*/
import { app } from "../../scripts/app.js";
const RELAY_DEFAULT_WIDTH = 220;
app.registerExtension({
name: "prompt-manager.recipe-relay",
async nodeCreated(node) {
if (node.comfyClass !== "RecipeRelay") return;
requestAnimationFrame(() => {
node.setSize([RELAY_DEFAULT_WIDTH, node.size[1]]);
app.graph.setDirtyCanvas(true, true);
});
},
});
+15
View File
@@ -0,0 +1,15 @@
/**
* Recipe Renderer — Set initial node size to match Recipe Builder width.
*/
import { app } from "../../scripts/app.js";
app.registerExtension({
name: "prompt-manager.recipe-renderer",
async nodeCreated(node) {
if (node.comfyClass !== "RecipeRenderer") return;
requestAnimationFrame(() => {
node.setSize([320, node.size[1]]);
app.graph.setDirtyCanvas(true, true);
});
},
});
+43
View File
@@ -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)",
};
View File
+116
View File
@@ -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)
+275
View File
@@ -0,0 +1,275 @@
"""Multi-slot LoRA stacker outputting four independent LORA_STACK outputs (A/B/C/D)."""
import json
import os
import sys
from ..py.lora_utils import resolve_lora_path
try:
from ..py.lora_utils import get_lora_relative_path
except Exception:
def get_lora_relative_path(lora_name):
return str(lora_name or ""), False
def _try_get_lm_get_lora_info():
"""Return LM's get_lora_info function if it is already loaded in sys.modules."""
for mod in sys.modules.values():
fn = getattr(mod, "get_lora_info", None)
if callable(fn):
module_name = getattr(fn, "__module__", "") or ""
if "lora_manager" in module_name.lower():
return fn
return None
def _build_lora_stack(loras_json):
"""
Build a LORA_STACK list from the JSON state persisted by the JS widget.
Each entry: {"name": str, "strength": float, "clipStrength": float, "active": bool}
Returns a list of (lora_path, model_strength, clip_strength) tuples.
"""
if isinstance(loras_json, str):
raw = loras_json.strip()
if not raw or raw == "[]":
return []
try:
loras = json.loads(raw)
except Exception:
return []
elif isinstance(loras_json, dict) and "__value__" in loras_json:
loras = loras_json["__value__"]
elif isinstance(loras_json, list):
loras = loras_json
else:
return []
if not isinstance(loras, list):
return []
get_lora_info = _try_get_lm_get_lora_info()
stack = []
def _normalize_to_relative_lora(raw_value, fallback_name):
candidate = str(raw_value or "").strip()
if candidate:
rel_path, available = get_lora_relative_path(candidate)
if available and rel_path:
return rel_path
candidate_base = os.path.basename(candidate.replace("\\", "/")).strip()
if candidate_base:
rel_path, available = get_lora_relative_path(candidate_base)
if available and rel_path:
return rel_path
fallback = str(fallback_name or "").strip()
if fallback:
rel_path, available = get_lora_relative_path(fallback)
if available and rel_path:
return rel_path
return fallback
for lora in loras:
if not isinstance(lora, dict):
continue
if not lora.get("active", True):
continue
name = str(lora.get("name", "")).strip()
if not name:
continue
try:
strength = float(lora.get("strength", 1.0))
except (TypeError, ValueError):
strength = 1.0
try:
clip_strength = float(lora.get("clipStrength", strength))
except (TypeError, ValueError):
clip_strength = strength
# Prefer LM's path resolver (has full cache); fall back to folder_paths scan.
lora_path = None
if get_lora_info is not None:
try:
result = get_lora_info(name)
if isinstance(result, tuple) and result[0]:
lora_path = _normalize_to_relative_lora(result[0], name)
except Exception:
pass
if not lora_path:
resolved, available = resolve_lora_path(name)
lora_path = _normalize_to_relative_lora(resolved if (available and resolved) else name, name)
stack.append((lora_path, strength, clip_strength))
return stack
class MultiLoraStackerLM:
"""Multi-slot LoRA stacker with four independent stacks (A / B / C / D)."""
NAME = "Multi Lora Stacker (LoraManager)"
CATEGORY = "Prompt Manager"
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
# JSON arrays persisted by the JS loras widget – one per slot.
"loras_state_a": ("STRING", {"default": "[]", "multiline": True}),
"loras_state_b": ("STRING", {"default": "[]", "multiline": True}),
"loras_state_c": ("STRING", {"default": "[]", "multiline": True}),
"loras_state_d": ("STRING", {"default": "[]", "multiline": True}),
},
}
RETURN_TYPES = ("MULTI_LORA_STACK",)
RETURN_NAMES = ("multi_lora_stack",)
FUNCTION = "stack_multi"
DESCRIPTION = (
"Multi-slot LoRA stacker with a visual 4-panel UI (A / B / C / D). "
"Outputs one MULTI_LORA_STACK payload containing all four stacks."
)
def stack_multi(
self,
loras_state_a="[]",
loras_state_b="[]",
loras_state_c="[]",
loras_state_d="[]",
**kwargs,
):
stack_a = _build_lora_stack(loras_state_a)
stack_b = _build_lora_stack(loras_state_b)
stack_c = _build_lora_stack(loras_state_c)
stack_d = _build_lora_stack(loras_state_d)
multi_lora_stack = {
"a": stack_a,
"b": stack_b,
"c": stack_c,
"d": stack_d,
}
return (multi_lora_stack,)
def _coerce_lora_stack(raw_stack):
"""Normalize an incoming LORA_STACK-like payload to list[(path, model, clip)]."""
if raw_stack is None:
return []
if isinstance(raw_stack, dict) and "__value__" in raw_stack:
raw_stack = raw_stack.get("__value__")
if not isinstance(raw_stack, list):
return []
out = []
for item in raw_stack:
if isinstance(item, (list, tuple)) and len(item) >= 1:
path = str(item[0] or "").strip()
if not path:
continue
try:
model_strength = float(item[1]) if len(item) >= 2 else 1.0
except Exception:
model_strength = 1.0
try:
clip_strength = float(item[2]) if len(item) >= 3 else model_strength
except Exception:
clip_strength = model_strength
out.append((path, model_strength, clip_strength))
continue
if isinstance(item, dict):
path = str(item.get("path") or item.get("name") or "").strip()
if not path:
continue
try:
model_strength = float(item.get("model_strength", item.get("strength", 1.0)))
except Exception:
model_strength = 1.0
try:
clip_strength = float(item.get("clip_strength", model_strength))
except Exception:
clip_strength = model_strength
out.append((path, model_strength, clip_strength))
return out
class MultiLoraCombine:
"""Combine optional multi stack + optional A/B/C/D stacks into one MULTI_LORA_STACK."""
NAME = "Multi LoRA Combine"
CATEGORY = "Prompt Manager"
@classmethod
def INPUT_TYPES(cls):
return {
"required": {},
"optional": {
"multi_lora_stack": ("MULTI_LORA_STACK", {
"tooltip": "Optional existing MULTI_LORA_STACK to merge into.",
}),
"lora_stack_a": ("LORA_STACK", {
"tooltip": "Optional stack to append to slot A.",
}),
"lora_stack_b": ("LORA_STACK", {
"tooltip": "Optional stack to append to slot B.",
}),
"lora_stack_c": ("LORA_STACK", {
"tooltip": "Optional stack to append to slot C.",
}),
"lora_stack_d": ("LORA_STACK", {
"tooltip": "Optional stack to append to slot D.",
}),
},
}
RETURN_TYPES = ("MULTI_LORA_STACK",)
RETURN_NAMES = ("multi_lora_stack",)
FUNCTION = "combine_multi"
DESCRIPTION = (
"Combine an optional MULTI_LORA_STACK with optional LORA_STACK A/B/C/D "
"inputs and output one MULTI_LORA_STACK payload."
)
def combine_multi(
self,
multi_lora_stack=None,
lora_stack_a=None,
lora_stack_b=None,
lora_stack_c=None,
lora_stack_d=None,
**kwargs,
):
# Start from empty payload when no multi input is connected.
out_a = []
out_b = []
out_c = []
out_d = []
if isinstance(multi_lora_stack, dict):
out_a = _coerce_lora_stack(multi_lora_stack.get("a"))
out_b = _coerce_lora_stack(multi_lora_stack.get("b"))
out_c = _coerce_lora_stack(multi_lora_stack.get("c"))
out_d = _coerce_lora_stack(multi_lora_stack.get("d"))
# Append separate stack inputs to each slot (if connected).
out_a.extend(_coerce_lora_stack(lora_stack_a))
out_b.extend(_coerce_lora_stack(lora_stack_b))
out_c.extend(_coerce_lora_stack(lora_stack_c))
out_d.extend(_coerce_lora_stack(lora_stack_d))
merged = {
"a": out_a,
"b": out_b,
"c": out_c,
"d": out_d,
}
return (merged,)
+33
View File
@@ -0,0 +1,33 @@
"""Bundled multi-slot helper node for Recipe Builder."""
import json
class RecipeBuilderMultiPrompts:
@classmethod
def INPUT_TYPES(cls):
return {
"required": {},
"optional": {
"model_a": ("STRING", {"forceInput": True}),
"model_b": ("STRING", {"forceInput": True}),
"model_c": ("STRING", {"forceInput": True}),
"model_d": ("STRING", {"forceInput": True}),
},
}
RETURN_TYPES = ("STRING",)
RETURN_NAMES = ("multi_prompt",)
FUNCTION = "bundle"
CATEGORY = "Prompt Manager"
DESCRIPTION = "Bundle model_a/model_b/model_c/model_d prompts into a JSON string payload."
def bundle(self,
model_a="", model_b="", model_c="", model_d=""):
payload = {
"model_a": str(model_a or ""),
"model_b": str(model_b or ""),
"model_c": str(model_c or ""),
"model_d": str(model_d or ""),
}
return (json.dumps(payload, ensure_ascii=True),)
File diff suppressed because it is too large Load Diff
+391 -122
View File
@@ -3,6 +3,7 @@ import subprocess
import time
import os
import sys
import gc
import atexit
import signal
import psutil
@@ -10,17 +11,21 @@ import json
import base64
import ctypes
import numpy as np
import torch
from colorama import Fore, Style
from PIL import Image
from io import BytesIO
from .model_manager import get_local_models, get_model_path, is_model_local, download_model, get_mmproj_path
from ..py.model_manager import get_local_models, get_model_path, is_model_local, download_model, get_mmproj_path, has_vision_support
# Ollama integration
from ..py.ollama_wrapper import generate_chat as ollama_generate_chat, unload_model as ollama_unload_model
# ComfyUI interrupt helper
import comfy.model_management
# Try to import preferences cache, fallback to empty dict if not available
try:
from .model_manager import _preferences_cache
from ..py.model_manager import _preferences_cache
except ImportError:
_preferences_cache = {}
@@ -174,7 +179,7 @@ signal.signal(signal.SIGINT, _signal_handler)
signal.signal(signal.SIGTERM, _signal_handler)
# --- Prompt Loading Helpers ---
_PROMPTS_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "prompts")
_PROMPTS_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "prompts")
_prompts_cache = {}
def load_prompt(filename):
@@ -229,7 +234,7 @@ class PromptGenerator:
@staticmethod
def get_image_system_prompt():
"""Load the system prompt for image description (used with Qwen3VL)."""
"""Load the system prompt for image description (used with vision models)."""
return load_prompt("image_default_system_prompt.txt")
@staticmethod
@@ -248,63 +253,54 @@ class PromptGenerator:
return load_prompt("json_system_prompt.txt")
@staticmethod
def find_qwen3vl_model(available_models, thinking):
"""Find the preferred or smallest available Qwen3VL model
def find_vision_model(available_models):
"""Find the preferred or first available vision-capable model.
First checks user preferences, then falls back to smallest model (4B preferred over 8B)
A model is considered vision-capable if it has an mmproj file
(either in the registry or on disk).
"""
qwen3vl_models = [m for m in available_models if 'qwen3vl' in m.lower()]
if not qwen3vl_models:
vision_models = [m for m in available_models if has_vision_support(m)]
if not vision_models:
return None
# Check user preference first
preferred = _preferences_cache.get("preferred_vision_model", "")
if preferred and preferred in qwen3vl_models and is_model_local(preferred):
if thinking:
if 'thinking' in preferred.lower():
return preferred
else:
if 'thinking' not in preferred.lower():
return preferred
if preferred and preferred in vision_models and is_model_local(preferred):
return preferred
# Let's filter models based on thinking mode
if thinking:
filtered_models = [model for model in qwen3vl_models if 'thinking' in model.lower()]
else:
filtered_models = [model for model in qwen3vl_models if 'thinking' not in model.lower()]
if filtered_models:
qwen3vl_models = filtered_models
# Fall back to smaller model (prefer 4B over 8B)
for model in qwen3vl_models:
if '4b' in model.lower():
# Fall back to smallest model
for model in vision_models:
if '4b' in model.lower() or '3b' in model.lower():
return model
return qwen3vl_models[0]
return vision_models[0]
@staticmethod
def find_non_vl_model(available_models):
"""Find the preferred or smallest available non-vision model by file size
def find_text_model(available_models):
"""Find the preferred or smallest available model for text enhancement.
First checks user preferences, then falls back to smallest model by file size
Any model can be used for text (vision models work too),
but we prefer non-vision models when available to save resources.
Falls back to vision-capable models if that's all there is.
"""
# Prefer models without mmproj (lighter weight)
text_only = [m for m in available_models if not has_vision_support(m)]
non_vl_models = [m for m in available_models if 'qwen3vl' not in m.lower()]
if not non_vl_models:
candidates = text_only if text_only else available_models
if not candidates:
return None
# Check user preference first
preferred = _preferences_cache.get("preferred_base_model", "")
if preferred and preferred in non_vl_models and is_model_local(preferred):
if preferred and preferred in candidates and is_model_local(preferred):
return preferred
# Fall back to smaller model (prefer 4B over 8B)
for model in non_vl_models:
if '4b' in model.lower():
# Fall back to smallest model
for model in candidates:
if '4b' in model.lower() or '3b' in model.lower():
return model
return non_vl_models[0]
return candidates[0]
@classmethod
def INPUT_TYPES(cls):
@@ -314,7 +310,8 @@ class PromptGenerator:
"default": 0,
"min": 0,
"max": 0xffffffffffffffff,
"tooltip": "Seed for reproducible generation."
"tooltip": "Seed for reproducible generation.",
"control_after_generate": True
}),
},
"optional": {
@@ -340,7 +337,7 @@ class PromptGenerator:
"tooltip": "Enable thinking/reasoning mode for compatible models (DeepSeek format)"
}),
"stop_server_after": ("BOOLEAN", {
"default": False,
"default": True,
"tooltip": "Stop the llama.cpp server after each prompt (for resource saving, but slower)."
}),
"options": ("OPTIONS", {
@@ -350,6 +347,7 @@ class PromptGenerator:
}
CATEGORY = "Prompt Manager"
DESCRIPTION = "Generate or enhance prompts using a local LLM via llama.cpp or Ollama."
RETURN_TYPES = ("STRING", "STRING")
RETURN_NAMES = ("output", "thoughts")
FUNCTION = "convert_prompt"
@@ -368,12 +366,12 @@ class PromptGenerator:
return False
@staticmethod
def start_server(model_name, context_size=4096, use_vision_model=False):
def start_server(model_name, context_size=2048, use_vision_model=False):
"""Start llama.cpp server with specified model
Args:
model_name: Name of the model to use
context_size: Context size (default 4096)
context_size: Context size (default 2048)
use_vision_model: Whether to use the vision model's mmproj
Returns:
@@ -441,17 +439,16 @@ class PromptGenerator:
print_pg(error_msg, RED)
# Build command arguments
cmd_args = [server_cmd, "-m", model_path, "--port", str(PromptGenerator.SERVER_PORT), "--no-warmup", "-c", str(context_size)]
cmd_args = [server_cmd, "-m", model_path, "--port", str(PromptGenerator.SERVER_PORT), "--no-warmup", "-ngl", "100", "-c", str(context_size)]
# Add vision flags for VL models
# Add vision flags for models with mmproj
if use_vision_model:
mmproj_path = get_mmproj_path(model_name)
if mmproj_path:
# Only print if mmproj is used
print_pg(f"Vision model: using mmproj: {os.path.basename(mmproj_path)}")
cmd_args.extend(["--mmproj", mmproj_path])
else:
error_msg = f"Error: Vision model requires mmproj file for '{model_name}' but it was not found. \nPlease ensure it exists, or use the Generator Options node to download the Qwen3VL model and its mmproj file."
error_msg = f"Error: Vision mode requires an mmproj file for '{model_name}' but none was found.\nPlease ensure an mmproj file exists, or use the Generator Options node to download a vision-capable model."
print_pg(error_msg, RED)
return (False, error_msg)
@@ -502,17 +499,33 @@ class PromptGenerator:
_current_context_size = context_size
# Wait for server to be ready
for i in range(30): # Wait up to 30 seconds
for i in range(60): # Wait up to 60 seconds
time.sleep(1)
try:
comfy.model_management.throw_exception_if_processing_interrupted()
except Exception:
# Propagate interrupt up to caller
raise
# Check if process has crashed
if _server_process.poll() is not None:
stderr_output = ""
try:
stderr_output = _server_process.stderr.read().decode("utf-8", errors="replace").strip()
except Exception:
pass
error_msg = f"Error: llama-server exited with code {_server_process.returncode}"
if stderr_output:
# Show last 5 lines of stderr for context
last_lines = "\n".join(stderr_output.splitlines()[-5:])
error_msg += f"\n{last_lines}"
print_pg(error_msg, RED)
_server_process = None
_current_model = None
return (False, error_msg)
if PromptGenerator.is_server_alive():
return (True, None)
error_msg = "Error: Server did not start in time"
error_msg = "Error: Server did not start in time (60s)"
print_pg(error_msg, RED)
PromptGenerator.stop_server()
return (False, error_msg)
@@ -623,19 +636,19 @@ class PromptGenerator:
data = response.json()
params = data.get("default_generation_settings", {}).get("params", {})
_model_default_params = {
"temperature": round(params.get("temperature", 0.8), 4),
"top_k": int(params.get("top_k", 40)),
"top_p": round(params.get("top_p", 0.95), 4),
"min_p": round(params.get("min_p", 0.05), 4),
"temperature": round(params.get("temperature", 0.7), 4),
"top_k": int(params.get("top_k", 20)),
"top_p": round(params.get("top_p", 0.9), 4),
"min_p": round(params.get("min_p", 0.0), 4),
"repeat_penalty": round(params.get("repeat_penalty", 1.0), 4),
}
return _model_default_params
except Exception:
_model_default_params = {
"temperature": 0.8,
"top_k": 40,
"top_p": 0.95,
"min_p": 0.05,
"temperature": 0.7,
"top_k": 20,
"top_p": 0.9,
"min_p": 0.0,
"repeat_penalty": 1.0
}
return _model_default_params
@@ -649,11 +662,57 @@ class PromptGenerator:
# Always attempt to fetch defaults; fetch_model_defaults() will fall back to built-in defaults on error, ensuring a dict is
return PromptGenerator.fetch_model_defaults()
def convert_prompt(self, seed: int, mode="Enhance Prompt (Image)", prompt="", image=None, format_as_json=False, enable_thinking=True, stop_server_after=False, options=None, **kwargs) -> str:
"""Convert prompt using llama.cpp server, with caching for repeated requests."""
@staticmethod
def _comfy_cache_cleanup_compat(force=True):
"""Call Comfy cache cleanup with compatibility across versions."""
if hasattr(comfy.model_management, "soft_empty_cache"):
try:
# Newer Comfy builds may accept a force flag.
comfy.model_management.soft_empty_cache(force)
except TypeError:
# Older builds expose no-arg soft_empty_cache.
comfy.model_management.soft_empty_cache()
elif hasattr(comfy.model_management, "cleanup_models"):
comfy.model_management.cleanup_models()
@staticmethod
def flush_vram(unload_models=True):
"""Aggressive VRAM cleanup for low-headroom systems."""
try:
if unload_models and hasattr(comfy.model_management, "unload_all_models"):
comfy.model_management.unload_all_models()
PromptGenerator._comfy_cache_cleanup_compat(force=True)
gc.collect()
if torch.cuda.is_available():
torch.cuda.empty_cache()
try:
torch.cuda.ipc_collect()
except Exception:
pass
print_pg(f"VRAM flush executed (unload_models={'ON' if unload_models else 'OFF'}).")
except Exception as e:
print_pg(f"Warning: VRAM flush failed: {e}", RED)
@staticmethod
def cleanup_vram_before_run():
"""Aggressive pre-run VRAM cleanup before generation starts."""
PromptGenerator.flush_vram(unload_models=True)
def convert_prompt(self, seed: int, mode="Enhance Prompt (Image)", prompt="", image=None, format_as_json=False, enable_thinking=True, stop_server_after=True, options=None, **kwargs) -> str:
"""Convert prompt using llama.cpp server or Ollama, with caching for repeated requests."""
global _current_model
print_pg_header() # Print header for this execution
self.cleanup_vram_before_run()
# Determine LLM backend: "ollama" or "llama.cpp"
use_ollama = (
(options and options.get("llm_backend") == "ollama") or
_preferences_cache.get("llm_backend", "llama.cpp") == "ollama"
)
# Extract console option from connected options node
show_everything_in_console = False # Default to False when options not connected
@@ -674,61 +733,73 @@ class PromptGenerator:
if (mode == "Enhance Prompt (Image)" or mode == "Enhance Prompt (Video)") and not prompt.strip():
error_msg = "Did you perhaps forget to enter a User Prompt?"
print_pg(error_msg, RED)
return (error_msg,)
raise RuntimeError(error_msg)
# Always determine a valid model filename before running server
model_to_use = None
available_models = get_local_models()
if use_vision_model:
# Check if options specifies a Qwen3VL model
if options and "model" in options and "vl" in options["model"].lower() and is_model_local(options["model"]):
if use_ollama:
# ── Ollama model selection ──
# Priority: Options node > auto-discover from Ollama
if options and "model" in options:
model_to_use = options["model"]
elif options and "model" in options and is_model_local(options["model"]):
# Non-VL model selected but in vision mode
print_pg(f"Warning: Non-vision model '{options['model']}' selected but '{mode}' mode is active.\nIgnoring model selection and using a Vision Model instead.")
model_to_use = self.find_qwen3vl_model(available_models, enable_thinking)
if model_to_use is None:
error_msg = f"Error: '{mode}' mode requires a Qwen3VL model. Please connect the Options node and select a Qwen3VL model (Qwen3VL-4B or Qwen3VL-8B) to use vision capabilities."
print_pg(error_msg, RED)
return (error_msg,)
else:
# Try to find a Qwen3VL model automatically
model_to_use = self.find_qwen3vl_model(available_models, enable_thinking)
if model_to_use is None:
error_msg = f"Error: '{mode}' mode requires a Qwen3VL model. Please connect the Options node and select a Qwen3VL model (Qwen3VL-4B or Qwen3VL-8B) to use vision capabilities."
print_pg(error_msg, RED)
return (error_msg,)
else:
# Enhance Prompt mode - use regular model selection logic (exclude Qwen3VL models)
if options and "model" in options and is_model_local(options["model"]):
# If user explicitly selected a Qwen3VL model but in Enhance mode, use first non-VL model instead
if "qwen3vl" in options["model"].lower():
model_to_use = self.find_non_vl_model(available_models)
if model_to_use:
print_pg(f"Warning: Qwen3VL model '{options['model']}' selected but 'Enhance Prompt' mode is active. Ignoring model selection and using {model_to_use} instead.")
else:
error_msg = "Error: Only Qwen3VL models available but 'Enhance Prompt' mode is active. Please add a .gguf model or use Generator Options to add a non-vision model."
print_pg(error_msg, RED)
return (error_msg,)
# Auto-discover available models from Ollama
from ..py.ollama_wrapper import discover_ollama_models
discovered, status = discover_ollama_models(_preferences_cache)
if discovered:
model_to_use = discovered[0]
print_pg(f"Auto-selected Ollama model: {model_to_use}")
else:
model_to_use = options["model"]
else:
if not available_models:
error_msg = "Error: No models found in models/ folder. Please add a .gguf model or use Generator Options node to download one."
error_msg = (f"Error: No Ollama model available. {status}\n"
"Pull a model first (e.g. `ollama pull llama3.1`).")
print_pg(error_msg, RED)
return (error_msg,)
# Find smallest non-VL model
model_to_use = self.find_non_vl_model(available_models)
if not model_to_use:
error_msg = "Error: Only Qwen3VL models available but 'Enhance Prompt' mode is active. Please add a non-vision model or switch to 'Describe Image' mode."
print_pg(error_msg, RED)
return (error_msg,)
raise RuntimeError(error_msg)
# let's make sure thinking is disabled for non-thinking versions of Qwen3VL
if enable_thinking and "qwen3vl" in model_to_use.lower() and "thinking" not in model_to_use.lower():
print_pg("Warning: Thinking disabled - model does not support it.")
enable_thinking = False
print_pg("Backend : Ollama")
else:
# ── llama.cpp model selection ──
print_pg("Backend : llama.cpp")
available_models = get_local_models()
if use_vision_model:
# Check if the selected model supports vision (has mmproj)
if options and "model" in options and has_vision_support(options["model"]) and is_model_local(options["model"]):
model_to_use = options["model"]
elif options and "model" in options and is_model_local(options["model"]):
# Selected model doesn't support vision
print_pg(f"Warning: Model '{options['model']}' has no mmproj (no vision support) but '{mode}' mode is active.\nIgnoring model selection and searching for a vision-capable model.")
model_to_use = self.find_vision_model(available_models)
if model_to_use is None:
error_msg = f"Error: '{mode}' mode requires a vision model (one with an mmproj file). Please download a vision-capable model via the Options node."
print_pg(error_msg, RED)
raise RuntimeError(error_msg)
else:
# Try to find a vision model automatically
model_to_use = self.find_vision_model(available_models)
if model_to_use is None:
error_msg = f"Error: '{mode}' mode requires a vision model (one with an mmproj file). Please download a vision-capable model via the Options node."
print_pg(error_msg, RED)
raise RuntimeError(error_msg)
else:
# Enhance Prompt mode - any model works, prefer text-only for efficiency
if options and "model" in options and is_model_local(options["model"]):
model_to_use = options["model"]
else:
if not available_models:
error_msg = "Error: No models found in models/ folder. Please add a .gguf model or use Generator Options node to download one."
print_pg(error_msg, RED)
raise RuntimeError(error_msg)
model_to_use = self.find_text_model(available_models)
if not model_to_use:
error_msg = "Error: No suitable model found. Please add a .gguf model or use the Generator Options node to download one."
print_pg(error_msg, RED)
raise RuntimeError(error_msg)
# Thinking mode is only meaningful if the model explicitly supports it
# (no longer tied to Qwen3VL naming — generic check)
# Users can always enable thinking; the model will simply ignore it if unsupported.
print_pg(f"Vision mode : {'ON' if use_vision_model else 'OFF'}")
print_pg(f"Thinking mode : {'ON' if enable_thinking else 'OFF'}")
@@ -750,18 +821,19 @@ class PromptGenerator:
if not images:
error_msg = f"Error: '{mode}' mode requires at least one image to be connected. Please connect an image or switch to 'Enhance Prompt' mode."
print_pg(error_msg)
return (error_msg,)
print_pg(error_msg, RED)
raise RuntimeError(error_msg)
# If the current model is not the one we want, or server is not running, restart
# Also restart if context_size has changed
context_size = options.get("context_size", 4096) if options else 4096
if _current_model != model_to_use or _current_context_size != context_size or not self.is_server_alive():
self.stop_server()
# Get context_size from options or use default
success, error_msg = self.start_server(model_to_use, context_size, use_vision_model)
if not success:
return (error_msg,)
# Also restart if context_size has changed (llama.cpp only)
context_size = options.get("context_size", 2048) if options else 2048
if not use_ollama:
if _current_model != model_to_use or _current_context_size != context_size or not self.is_server_alive():
self.stop_server()
# Get context_size from options or use default
success, error_msg = self.start_server(model_to_use, context_size, use_vision_model)
if not success:
raise RuntimeError(error_msg)
# Build the endpoint URL
full_url = f"http://localhost:{self.SERVER_PORT}/v1/chat/completions"
@@ -795,9 +867,9 @@ class PromptGenerator:
else:
user_content = prompt
# === TOKENIZATION (only for non-cached requests) ===
# === TOKENIZATION (only for non-cached requests, llama.cpp only) ===
cached_token_counts = None
if show_everything_in_console:
if show_everything_in_console and not use_ollama:
cached_token_counts = self._get_token_counts_parallel(system_prompt, user_content)
# If in vision mode, encode images for the request
@@ -830,7 +902,7 @@ class PromptGenerator:
img_base64 = base64.b64encode(buffered.getvalue()).decode('utf-8')
image_contents.append({"type": "image_url", "image_url": {"url": f"data:image/png;base64,{img_base64}"}})
# Qwen3VL format for vision messages: all images, then text
# Vision format: all images first, then text
user_message = {
"role": "user",
"content": image_contents + [{"type": "text", "text": user_content}]
@@ -838,6 +910,29 @@ class PromptGenerator:
else:
user_message = {"role": "user", "content": user_content}
# ================================================================
# Ollama generation path
# ================================================================
if use_ollama:
return self._generate_via_ollama(
model_to_use=model_to_use,
system_prompt=system_prompt,
user_message=user_message,
user_content=user_content,
seed=seed,
enable_thinking=enable_thinking,
use_model_default_sampling=use_model_default_sampling,
show_everything_in_console=show_everything_in_console,
stop_server_after=stop_server_after,
options=options,
images=images,
context_size=context_size,
prompt=prompt,
)
# ================================================================
# llama.cpp generation path (existing)
# ================================================================
payload = {
"messages": [
{"role": "system", "content": system_prompt},
@@ -897,7 +992,7 @@ class PromptGenerator:
stream=True
)
else:
return (error_msg,)
raise RuntimeError(error_msg)
response.raise_for_status()
@@ -1008,18 +1103,192 @@ class PromptGenerator:
except requests.exceptions.ConnectionError:
error_msg = f"Error: Could not connect to server at {full_url}. Server may have crashed."
print_pg(error_msg, RED)
return (error_msg,)
raise RuntimeError(error_msg)
except requests.exceptions.Timeout:
error_msg = "Error: Request timed out (>120s)"
print_pg(error_msg, RED)
return (error_msg,)
raise RuntimeError(error_msg)
except Exception as e:
error_msg = f"Error: {e}"
print_pg(error_msg, RED)
if response.status_code == 400:
print_pg("Perhaps your query requires a larger context size.\nConsider increasing it using the Generator Options node.", RED)
error_msg += "\nConsider increasing context size using Generator Options node."
return (error_msg,)
raise RuntimeError(error_msg)
finally:
# Aggressive post-run cleanup to release VRAM pressure for Comfy pipelines.
self.flush_vram(unload_models=True)
# ================================================================
# Ollama generation helper
# ================================================================
def _generate_via_ollama(self, model_to_use, system_prompt, user_message,
user_content, seed, enable_thinking,
use_model_default_sampling, show_everything_in_console,
stop_server_after, options, images, context_size, prompt):
"""Generate text using Ollama's OpenAI-compatible endpoint with streaming."""
messages = [
{"role": "system", "content": system_prompt},
user_message,
]
# Sampling parameters
temperature = 0.8
top_k = 40
top_p = 0.95
min_p = 0.05
repeat_penalty = 1.0
if options and not use_model_default_sampling:
temperature = options.get("temperature", temperature)
top_k = options.get("top_k", top_k)
top_p = options.get("top_p", top_p)
min_p = options.get("min_p", min_p)
repeat_penalty = options.get("repeat_penalty", repeat_penalty)
if show_everything_in_console:
print_pg(f"{'=' * 60}", GREEN)
print_pg(" DETAILED INFORMATION ENABLED (Ollama)", GREEN)
print_pg(f"{'=' * 60}", GREEN)
if not use_model_default_sampling:
print_pg("------ GENERATION PARAMETERS ------", GREEN)
for name, val in [("seed", seed), ("temperature", temperature),
("top_k", top_k), ("top_p", top_p),
("min_p", min_p), ("repeat_penalty", repeat_penalty)]:
print_pg(f"{name} = {val}", GREEN)
else:
print_pg("Using model default sampling parameters", GREEN)
print_pg("\n--------- SYSTEM PROMPT ---------", GREEN)
print_pg(f"{system_prompt}", GREEN)
print_pg("\n--------- USER PROMPT ---------", GREEN)
print_pg(f"{user_content}", GREEN)
# Call Ollama (streaming)
result = ollama_generate_chat(
user_config=_preferences_cache,
model_name=model_to_use,
messages=messages,
temperature=temperature,
top_k=top_k,
top_p=top_p,
min_p=min_p,
repeat_penalty=repeat_penalty,
seed=seed,
stream=True,
timeout=120,
use_model_defaults=use_model_default_sampling,
enable_thinking=enable_thinking,
)
# result is (response_obj, error_msg) for streaming
if result[1] is not None:
print_pg(f"Ollama error: {result[1]}", RED)
return (result[1],)
response = result[0]
try:
full_response = ""
thinking_content = ""
usage_stats = None
first_thinking = True
first_content = True
for line in response.iter_lines():
# Check for user interrupt
try:
comfy.model_management.throw_exception_if_processing_interrupted()
except Exception:
try:
response.close()
except Exception:
pass
raise
if line:
line = line.decode('utf-8')
if line.startswith('data: '):
data = line[6:]
if data == '[DONE]':
break
try:
chunk = json.loads(data)
if "usage" in chunk:
usage_stats = chunk["usage"]
if 'choices' in chunk and len(chunk['choices']) > 0:
delta = chunk['choices'][0].get('delta', {})
if 'reasoning_content' in delta:
reasoning_delta = delta['reasoning_content']
if reasoning_delta is not None:
thinking_content += str(reasoning_delta)
if show_everything_in_console:
if first_thinking:
print_pg("\n--------- THINKING ---------", GREEN)
first_thinking = False
print(f"{GREEN}{str(reasoning_delta)}{RESET}", end='', flush=True)
if 'content' in delta:
content_delta = delta['content']
if content_delta is not None:
full_response += str(content_delta)
if show_everything_in_console:
if first_content:
print_pg("\n\n--------- FINAL ANSWER ---------", CYAN)
first_content = False
print(f"{CYAN}{str(content_delta)}{RESET}", end='', flush=True)
except json.JSONDecodeError:
continue
if show_everything_in_console:
print('') # Final newline
if not show_everything_in_console:
print_pg("Prompt generation complete (Ollama).")
if show_everything_in_console and usage_stats:
self.print_token_stats(usage_stats, None, thinking_content, full_response, images)
else:
print_pg_footer()
if not full_response:
print_pg("Warning: Empty response from Ollama")
full_response = prompt
# "stop_server_after" → unload model from Ollama memory immediately
# (This overrides the keep_alive duration for this request)
if stop_server_after:
print_pg("Unloading model from Ollama memory...")
ok, msg = ollama_unload_model(_preferences_cache, model_to_use)
print_pg(msg, GREEN if ok else RED)
else:
keep_alive = _preferences_cache.get("ollama_keep_alive", "5m")
if keep_alive and str(keep_alive) != "0":
print_pg(f"Model will stay loaded for: {keep_alive}")
return (full_response, thinking_content)
except comfy.model_management.InterruptProcessingException:
try:
response.close()
except Exception:
pass
raise
except requests.exceptions.ConnectionError:
error_msg = "Error: Lost connection to Ollama during generation."
print_pg(error_msg, RED)
raise RuntimeError(error_msg)
except requests.exceptions.Timeout:
error_msg = "Error: Ollama request timed out (>120s)"
print_pg(error_msg, RED)
raise RuntimeError(error_msg)
except Exception as e:
error_msg = f"Error (Ollama): {e}"
print_pg(error_msg, RED)
raise RuntimeError(error_msg)
finally:
# Aggressive post-run cleanup to release VRAM pressure for Comfy pipelines.
self.flush_vram(unload_models=True)
def print_token_stats(self, usage_stats, cached_token_counts, thinking_content, full_response, images):
"""Print token statistics using pre-cached counts"""
@@ -1,4 +1,5 @@
from .model_manager import get_all_models, is_model_local, download_model, get_mmproj_for_model, get_mmproj_path
from ..py.model_manager import get_all_models, is_model_local, download_model, get_mmproj_for_model, get_mmproj_path, _preferences_cache
from ..py.ollama_wrapper import discover_ollama_models, is_ollama_available
import time
# Global timestamp to track when models were last updated
@@ -14,17 +15,25 @@ class PromptGenOptions:
@classmethod
def INPUT_TYPES(cls):
available_models = get_all_models()
backend = _preferences_cache.get("llm_backend", "llama.cpp")
# If no models found, show a placeholder
if not available_models:
available_models = ["No models found - check HuggingFace"]
if backend == "ollama":
# Discover models from Ollama
ollama_models, _status = discover_ollama_models(_preferences_cache)
if not ollama_models:
available_models = ["No Ollama models found - run 'ollama pull <model>'"]
else:
available_models = ollama_models
else:
available_models = get_all_models()
if not available_models:
available_models = ["No models found - check HuggingFace"]
return {
"optional": {
"model": (available_models, {
"default": available_models[0] if available_models else "",
"tooltip": "Select model to use (local models listed first, then HuggingFace models)"
"tooltip": "Select model to use (local models listed first, then HuggingFace models)\nDownload sizes: UD-Q4_K_XL ~6GB | Q8_0 ~9.5GB | UD-Q8_K_XL ~13GB"
}),
"image2": ("IMAGE", {
"tooltip": "Connect an image (required for 'Analyze Image' and 'Analyze Image with Prompt' modes)"
@@ -49,21 +58,21 @@ class PromptGenOptions:
"tooltip": "Use the model's default sampling parameters (overrides temperature, top_p, etc)"
}),
"temperature": ("FLOAT", {
"default": 0.8,
"default": 0.7,
"min": 0.0,
"max": 2.0,
"step": 0.01,
"tooltip": "Controls randomness (0.0 = deterministic, 2.0 = very random)"
}),
"top_k": ("INT", {
"default": 40,
"default": 20,
"min": 0,
"max": 100,
"step": 1,
"tooltip": "Sample from top K most likely tokens (0 = disabled)"
}),
"top_p": ("FLOAT", {
"default": 0.95,
"default": 0.9,
"min": 0.0,
"max": 1.0,
"step": 0.01,
@@ -98,6 +107,7 @@ class PromptGenOptions:
}
CATEGORY = "Prompt Manager"
DESCRIPTION = "Configure LLM model, sampling parameters, and system prompt for the Prompt Generator."
RETURN_TYPES = ("OPTIONS",)
RETURN_NAMES = ("options",)
FUNCTION = "create_options"
@@ -117,16 +127,23 @@ class PromptGenOptions:
options = {}
# Handle model selection and download if needed
if model and model != "No models found - check HuggingFace":
backend = _preferences_cache.get("llm_backend", "llama.cpp")
if backend == "ollama":
# Ollama mode — no download needed, just validate the selection
if model and model != "No Ollama models found - run 'ollama pull <model>'":
options["model"] = model
options["llm_backend"] = "ollama"
elif model and model != "No models found - check HuggingFace":
# Check if model is local
model_exists = is_model_local(model)
# For VL models, also check if mmproj exists
# For vision models, also check if mmproj exists
needs_download = not model_exists
if model_exists:
mmproj_name = get_mmproj_for_model(model)
if mmproj_name:
# This is a VL model, check if mmproj is present
# This is a vision model, check if mmproj is present
mmproj_path = get_mmproj_path(model)
if not mmproj_path:
print(f"[Prompt Generator Options] Vision model found but mmproj missing, downloading: {mmproj_name}")
File diff suppressed because it is too large Load Diff
@@ -1,11 +1,35 @@
import os
import json
import shutil
import time
import folder_paths
import server
class PromptManager:
@staticmethod
def get_weekly_backup_path():
"""Get the path to the weekly rotating backup file."""
return PromptManager.get_prompts_path() + "_bak"
@staticmethod
def _refresh_weekly_backup_if_due(source_path, backup_path, interval_days=7):
"""Refresh backup only when missing or older than interval_days."""
if not os.path.exists(source_path):
return
should_refresh = not os.path.exists(backup_path)
if not should_refresh:
try:
age_seconds = time.time() - os.path.getmtime(backup_path)
should_refresh = age_seconds >= (interval_days * 24 * 60 * 60)
except Exception:
should_refresh = True
if should_refresh:
shutil.copy2(source_path, backup_path)
@classmethod
def INPUT_TYPES(s):
prompts_data = PromptManager.load_prompts()
@@ -13,7 +37,7 @@ class PromptManager:
all_prompts = set()
for category_prompts in prompts_data.values():
all_prompts.update(category_prompts.keys())
all_prompts.update(k for k in category_prompts.keys() if k != "__meta__")
all_prompts.add("")
all_prompts_list = sorted(list(all_prompts))
@@ -24,7 +48,7 @@ class PromptManager:
first_prompt = ""
first_prompt_text = ""
if prompts_data and first_category in prompts_data and prompts_data[first_category]:
first_category_prompts = list(prompts_data[first_category].keys())
first_category_prompts = [k for k in prompts_data[first_category].keys() if k != "__meta__"]
first_prompt = sorted(first_category_prompts, key=str.lower)[0] if first_category_prompts else ""
if first_prompt:
first_prompt_text = prompts_data[first_category][first_prompt].get("prompt", "")
@@ -45,6 +69,7 @@ class PromptManager:
}
CATEGORY = "Prompt Manager"
DESCRIPTION = "Simple prompt manager for saving and loading prompts by category. Prompt-only, no LoRA support."
RETURN_TYPES = ("STRING",)
RETURN_NAMES = ("prompt",)
FUNCTION = "get_prompt"
@@ -64,7 +89,7 @@ class PromptManager:
@staticmethod
def get_default_prompts_path():
"""Get the path to the default prompts JSON file"""
return os.path.join(os.path.dirname(__file__), "default_prompts.json")
return os.path.join(os.path.dirname(os.path.dirname(__file__)), "default_prompts.json")
@classmethod
def load_prompts(cls):
@@ -78,6 +103,26 @@ class PromptManager:
return json.load(f)
except Exception as e:
print(f"[PromptManager] Error loading user prompts: {e}")
# Try backup variants before falling back to defaults.
# Never overwrite a user file just because parsing failed.
backup_candidates = [
cls.get_weekly_backup_path(),
user_path + ".bak",
user_path + ".backup",
user_path + ".tmp",
]
for backup_path in backup_candidates:
if not os.path.exists(backup_path):
continue
try:
with open(backup_path, 'r', encoding='utf-8') as f:
backup_data = json.load(f)
print(f"[PromptManager] Recovered prompts from backup: {backup_path}")
return backup_data
except Exception as be:
print(f"[PromptManager] Backup load failed ({backup_path}): {be}")
print("[PromptManager] User prompt file exists but could not be parsed; not overwriting with defaults.")
return {}
if os.path.exists(default_path):
try:
@@ -94,10 +139,19 @@ class PromptManager:
@staticmethod
def sort_prompts_data(data):
"""Sort categories and prompts alphabetically (case-insensitive)"""
"""Sort categories and prompts alphabetically (case-insensitive), preserving __meta__"""
sorted_data = {}
for category in sorted(data.keys(), key=str.lower):
sorted_data[category] = dict(sorted(data[category].items(), key=lambda item: item[0].lower()))
cat_data = data[category]
meta = cat_data.get("__meta__")
sorted_prompts = dict(sorted(
((k, v) for k, v in cat_data.items() if k != "__meta__"),
key=lambda item: item[0].lower()
))
if meta is not None:
sorted_prompts["__meta__"] = meta
sorted_data[category] = sorted_prompts
return sorted_data
return sorted_data
@classmethod
@@ -105,13 +159,25 @@ class PromptManager:
"""Save prompts to user folder"""
user_path = cls.get_prompts_path()
sorted_data = cls.sort_prompts_data(data)
tmp_path = user_path + ".tmp"
bak_path = cls.get_weekly_backup_path()
try:
os.makedirs(os.path.dirname(user_path), exist_ok=True)
with open(user_path, 'w', encoding='utf-8') as f:
# Weekly rotating backup: refresh at most once every 7 days.
cls._refresh_weekly_backup_if_due(user_path, bak_path)
# Atomic write: write temp then replace to avoid truncated/corrupt files.
with open(tmp_path, 'w', encoding='utf-8') as f:
json.dump(sorted_data, f, indent=2, ensure_ascii=False)
os.replace(tmp_path, user_path)
except Exception as e:
print(f"[PromptManager] Error saving prompts: {e}")
try:
if os.path.exists(tmp_path):
os.remove(tmp_path)
except Exception:
pass
def get_prompt(self, category, name, use_external, text="", llm_input="", unique_id=None):
"""Return the appropriate text based on use_external toggle and broadcast update"""
@@ -203,7 +269,7 @@ async def save_prompt(request):
print(f"[PromptManager] Removing old casing '{old_name}' before saving as '{name}'")
del prompts[category][old_name]
# Save prompt in dict, preserving any existing lora data, trigger words, and thumbnail from PromptManagerAdvanced
# Save prompt in dict, preserving any existing lora data, trigger words, thumbnail, and nsfw from PromptManagerAdvanced
existing_data = prompts[category].get(name, {})
prompts[category][name] = {
"prompt": text,
@@ -212,6 +278,9 @@ async def save_prompt(request):
"trigger_words": existing_data.get("trigger_words", []),
"thumbnail": existing_data.get("thumbnail")
}
# Preserve nsfw flag if it was set
if existing_data.get("nsfw"):
prompts[category][name]["nsfw"] = existing_data["nsfw"]
PromptManager.save_prompts(prompts)
return server.web.json_response({"success": True, "prompts": prompts})
File diff suppressed because it is too large Load Diff
+362
View File
@@ -0,0 +1,362 @@
"""
Workflow Manager - stripped-down workflow_data editor based on PromptManagerAdvanced.
Differences from PromptManagerAdvanced:
- workflow_data input/output only (no prompt/lora stack outputs)
- no use_* switches
- no trigger words pipeline
"""
import json
import base64
from io import BytesIO
import server
from ..py.workflow_data_utils import ensure_v2_recipe_data, get_v2_model_block, to_json_safe_workflow_data, build_v2_recipe_data_from_prompt
from .prompt_manager_adv import PromptManagerAdvanced
try:
import numpy as np
from PIL import Image
IMAGE_SUPPORT = True
except ImportError:
IMAGE_SUPPORT = False
def _image_to_base64_thumbnail(image_tensor, max_size=200):
if not IMAGE_SUPPORT or image_tensor is None:
return None
try:
img_array = image_tensor[0] if len(image_tensor.shape) == 4 else image_tensor
if hasattr(img_array, "cpu"):
img_array = img_array.cpu().numpy()
img_array = (img_array * 255).astype(np.uint8)
img = Image.fromarray(img_array)
width, height = img.size
min_dim = min(width, height)
if min_dim > max_size:
scale = max_size / min_dim
img = img.resize((int(width * scale), int(height * scale)), Image.LANCZOS)
buffer = BytesIO()
img.save(buffer, format="JPEG", quality=85)
base64_str = base64.b64encode(buffer.getvalue()).decode("utf-8")
return f"data:image/jpeg;base64,{base64_str}"
except Exception as e:
print(f"[RecipeManager] Thumbnail generation failed: {e}")
return None
class WorkflowManager(PromptManagerAdvanced):
"""Workflow-focused manager that edits and forwards RECIPE_DATA."""
@classmethod
def INPUT_TYPES(cls):
prompts_data = cls.load_prompts()
categories = list(prompts_data.keys()) if prompts_data else ["Default"]
all_prompts = set()
for category_prompts in prompts_data.values():
all_prompts.update(k for k in category_prompts.keys() if k != "__meta__")
all_prompts.add("")
all_prompts_list = sorted(list(all_prompts))
first_category = categories[0] if categories else "Default"
# Keep new node instances empty until the user explicitly selects a prompt.
first_prompt = ""
first_prompt_text = ""
return {
"required": {
"category": (categories, {"default": first_category}),
"name": (all_prompts_list, {"default": first_prompt}),
"text": ("STRING", {
"multiline": True,
"default": first_prompt_text,
"placeholder": "Enter prompt text",
"dynamicPrompts": False,
"tooltip": "Edit prompt text directly",
}),
},
"optional": {
"recipe_data": ("RECIPE_DATA", {"forceInput": True, "tooltip": "Connected recipe_data to edit/forward"}),
},
"hidden": {
"unique_id": "UNIQUE_ID",
"loras_a_toggle": "STRING",
"loras_b_toggle": "STRING",
"saved_workflow_data": "STRING",
},
}
CATEGORY = "Prompt Manager"
DESCRIPTION = "Workflow-data focused manager (no use switches, no trigger words)."
RETURN_TYPES = ("RECIPE_DATA",)
RETURN_NAMES = ("recipe_data",)
FUNCTION = "get_workflow"
OUTPUT_NODE = True
@classmethod
def IS_CHANGED(cls, category, name, text="", **kwargs):
recipe_data = kwargs.get("recipe_data", None)
loras_a_toggle = kwargs.get("loras_a_toggle", "")
loras_b_toggle = kwargs.get("loras_b_toggle", "")
saved_workflow_data = kwargs.get("saved_workflow_data", "")
return (
category,
name,
text,
str(recipe_data) if recipe_data else None,
loras_a_toggle or "",
loras_b_toggle or "",
saved_workflow_data or "",
)
def get_workflow(
self,
category,
name,
text="",
recipe_data=None,
unique_id=None,
loras_a_toggle=None,
loras_b_toggle=None,
saved_workflow_data=None,
):
prompts_data = self.load_prompts()
def _as_workflow_dict(raw):
if isinstance(raw, dict):
return raw
if isinstance(raw, str) and raw.strip():
try:
parsed = json.loads(raw)
return parsed if isinstance(parsed, dict) else None
except (json.JSONDecodeError, TypeError):
return None
return None
prompt_entry = prompts_data.get(category, {}).get(name, {}) if isinstance(prompts_data, dict) else {}
# On reload, category/name can be temporarily out of sync in the UI.
# If direct lookup misses, find the selected name in any category.
if not isinstance(prompt_entry, dict) or not prompt_entry:
if isinstance(prompts_data, dict) and isinstance(name, str) and name:
for cat_prompts in prompts_data.values():
if isinstance(cat_prompts, dict) and isinstance(cat_prompts.get(name), dict):
prompt_entry = cat_prompts.get(name)
break
stored_prompt_wf = _as_workflow_dict(prompt_entry.get("workflow_data")) if isinstance(prompt_entry, dict) else None
live_workflow_data = _as_workflow_dict(recipe_data)
hidden_saved_wf = _as_workflow_dict(saved_workflow_data)
# WorkflowManager should prefer live connected workflow_data when present,
# then fall back to local serialized state.
resolved_workflow_data = ensure_v2_recipe_data(live_workflow_data, source="RecipeManager") if isinstance(live_workflow_data, dict) else None
if resolved_workflow_data is None:
resolved_workflow_data = ensure_v2_recipe_data(hidden_saved_wf, source="RecipeManager") if isinstance(hidden_saved_wf, dict) else None
if resolved_workflow_data is None and isinstance(stored_prompt_wf, dict):
resolved_workflow_data = ensure_v2_recipe_data(stored_prompt_wf, source="RecipeManager")
# Prompt-only fallback: allow RecipeManager to open saved PMA prompts
# (prompt + lora stacks) by synthesizing minimal v2 recipe_data.
if resolved_workflow_data is None and isinstance(prompt_entry, dict):
prompt_text = str(prompt_entry.get("prompt", "") or text or "")
negative_text = str(prompt_entry.get("negative_prompt", "") or "")
prompt_loras_a = prompt_entry.get("loras_a", []) if isinstance(prompt_entry.get("loras_a"), list) else []
prompt_loras_b = prompt_entry.get("loras_b", []) if isinstance(prompt_entry.get("loras_b"), list) else []
has_prompt_payload = bool(
prompt_text.strip() or
negative_text.strip() or
len(prompt_loras_a) > 0 or
len(prompt_loras_b) > 0
)
if has_prompt_payload:
resolved_workflow_data = build_v2_recipe_data_from_prompt(
prompt_text=prompt_text,
negative_prompt=negative_text,
loras_a=prompt_loras_a,
loras_b=prompt_loras_b,
source="RecipeManager",
)
wf = resolved_workflow_data if isinstance(resolved_workflow_data, dict) else {}
wf_model_a = get_v2_model_block(wf, "model_a") or {}
wf_model_b = get_v2_model_block(wf, "model_b") or {}
wf_has_model_b = isinstance(get_v2_model_block(wf, "model_b"), dict)
incoming_wf = live_workflow_data if isinstance(live_workflow_data, dict) else None
incoming_has_model_b = None
if isinstance(incoming_wf, dict):
incoming_v2 = ensure_v2_recipe_data(incoming_wf, source="RecipeManager")
incoming_models = incoming_v2.get("models", {}) if isinstance(incoming_v2.get("models"), dict) else {}
incoming_has_model_b = isinstance(incoming_models.get("model_b"), dict)
output_text = (wf_model_a.get("positive_prompt", "") or text or "")
generated_thumbnail = _image_to_base64_thumbnail(wf.get("IMAGE")) if isinstance(wf, dict) else None
incoming_thumbnail = _image_to_base64_thumbnail(incoming_wf.get("IMAGE")) if isinstance(incoming_wf, dict) else None
workflow_thumbnail = incoming_thumbnail if isinstance(incoming_thumbnail, str) and incoming_thumbnail else (
generated_thumbnail if isinstance(generated_thumbnail, str) and generated_thumbnail else (
incoming_wf.get("thumbnail") if isinstance(incoming_wf, dict) and isinstance(incoming_wf.get("thumbnail"), str) else (
wf.get("thumbnail") if isinstance(wf.get("thumbnail"), str) else None
)
)
)
# Build preset stacks from saved toggle state.
preset_stack_a = self._build_stack_from_toggle(loras_a_toggle) if loras_a_toggle else []
preset_stack_b = self._build_stack_from_toggle(loras_b_toggle) if (wf_has_model_b and loras_b_toggle) else []
all_preset_loras_a = self._get_all_loras_from_toggle(loras_a_toggle) if loras_a_toggle else []
all_preset_loras_b = self._get_all_loras_from_toggle(loras_b_toggle) if (wf_has_model_b and loras_b_toggle) else []
wf_loras_a = [
(lora["name"], lora.get("model_strength", 1.0), lora.get("clip_strength", 1.0))
for lora in wf_model_a.get("loras", [])
if isinstance(lora, dict) and lora.get("name")
]
wf_loras_b = []
if wf_has_model_b:
wf_loras_b = [
(lora["name"], lora.get("model_strength", 1.0), lora.get("clip_strength", 1.0))
for lora in wf_model_b.get("loras", [])
if isinstance(lora, dict) and lora.get("name")
]
# WorkflowManager is workflow-data centric: preserve connected workflow order
# and use toggles only to modify active/strength state for those entries.
# Fallback to preset stack only when no workflow LoRAs are present.
if wf_loras_a:
merged_stack_a = list(wf_loras_a)
else:
merged_stack_a = list(preset_stack_a) if preset_stack_a else []
if wf_has_model_b:
if wf_loras_b:
merged_stack_b = list(wf_loras_b)
else:
merged_stack_b = list(preset_stack_b) if preset_stack_b else []
else:
merged_stack_b = []
processed_stack_a = self._process_lora_toggle(merged_stack_a, loras_a_toggle)
processed_stack_b = self._process_lora_toggle(merged_stack_b, loras_b_toggle)
loras_a_display = self._format_loras_for_display_with_unavailable(merged_stack_a, all_preset_loras_a)
loras_b_display = self._format_loras_for_display_with_unavailable(merged_stack_b, all_preset_loras_b)
unavailable_loras_a = [lora["name"] for lora in all_preset_loras_a if not lora.get("available", False)]
unavailable_loras_b = [lora["name"] for lora in all_preset_loras_b if not lora.get("available", False)]
if unique_id is not None:
server.PromptServer.instance.send_sync("prompt-manager-advanced-update", {
"node_id": unique_id,
"prompt": output_text,
"use_prompt_input": False,
"use_workflow_data": True,
"prompt_input": "",
"workflow_data": to_json_safe_workflow_data(ensure_v2_recipe_data(recipe_data, source="RecipeManager")) if isinstance(recipe_data, dict) else (
to_json_safe_workflow_data(resolved_workflow_data) if isinstance(resolved_workflow_data, dict) else None
),
"loras_a": loras_a_display,
"loras_b": loras_b_display,
"input_loras_a": self._format_loras_for_display(wf_loras_a) if wf_loras_a else [],
"input_loras_b": self._format_loras_for_display(wf_loras_b) if wf_loras_b else [],
"unavailable_loras_a": unavailable_loras_a,
"unavailable_loras_b": unavailable_loras_b,
"trigger_words": [],
"connected_thumbnail": workflow_thumbnail,
"should_reset": False,
"original_strengths_a": {
lora_item.get("name", ""): lora_item.get("strength", lora_item.get("model_strength", 1.0))
for lora_item in loras_a_display
if lora_item.get("name")
},
"original_strengths_b": {
lora_item.get("name", ""): lora_item.get("strength", lora_item.get("model_strength", 1.0))
for lora_item in loras_b_display
if lora_item.get("name")
},
})
out_workflow_data = ensure_v2_recipe_data(
dict(resolved_workflow_data) if isinstance(resolved_workflow_data, dict) else {},
source="RecipeManager",
)
models_out = out_workflow_data.get("models", {})
if not isinstance(models_out, dict):
models_out = {}
out_workflow_data["models"] = models_out
has_existing_model_b = isinstance(models_out.get("model_b"), dict)
model_a_out = models_out.get("model_a") if isinstance(models_out.get("model_a"), dict) else {}
model_b_out = models_out.get("model_b") if isinstance(models_out.get("model_b"), dict) else {}
model_a_out["positive_prompt"] = output_text
model_a_out["loras"] = [
{
"name": lora.get("name", ""),
"path": lora.get("path", lora.get("name", "")),
"model_strength": lora.get("model_strength", lora.get("strength", 1.0)),
"clip_strength": lora.get("clip_strength", lora.get("strength", 1.0)),
"active": lora.get("active", True),
"available": lora.get("available", True),
}
for lora in loras_a_display
if isinstance(lora, dict) and lora.get("name")
]
model_b_loras = [
{
"name": lora.get("name", ""),
"path": lora.get("path", lora.get("name", "")),
"model_strength": lora.get("model_strength", lora.get("strength", 1.0)),
"clip_strength": lora.get("clip_strength", lora.get("strength", 1.0)),
"active": lora.get("active", True),
"available": lora.get("available", True),
}
for lora in loras_b_display
if isinstance(lora, dict) and lora.get("name")
]
models_out["model_a"] = model_a_out
model_a_name = str(model_a_out.get("model", "") or "").strip()
model_b_name = str(model_b_out.get("model", "") or "").strip()
model_b_pos = str(model_b_out.get("positive_prompt", "") or "").strip()
model_b_neg = str(model_b_out.get("negative_prompt", "") or "").strip()
model_b_has_runtime = any(
model_b_out.get(k) is not None
for k in ("MODEL", "CLIP", "VAE", "POSITIVE", "NEGATIVE")
)
# model_b is considered meaningful when it has authored content
# that is not just a mirrored default of model_a.
keep_model_b = bool(model_b_loras) or bool(model_b_pos) or bool(model_b_neg) or model_b_has_runtime
if model_b_name and model_b_name != model_a_name:
keep_model_b = True
if (has_existing_model_b and model_b_name and model_b_name == model_a_name and
not model_b_loras and not model_b_pos and not model_b_neg and not model_b_has_runtime):
keep_model_b = False
# Canonical rule: if incoming recipe_data had no model_b, scrub model_b from output.
if incoming_has_model_b is False:
keep_model_b = False
if keep_model_b:
model_b_out["loras"] = model_b_loras
models_out["model_b"] = model_b_out
else:
models_out.pop("model_b", None)
out_workflow_data["_source"] = "RecipeManager"
return (out_workflow_data,)
def check_lazy_status(self, category, name, text="", **kwargs):
return []
+534
View File
@@ -0,0 +1,534 @@
import os
import sys
import inspect
import folder_paths
import nodes
import comfy.sd
import comfy.utils
import torch
from comfy_execution.graph import ExecutionBlocker
# =========================================================
# GGUF support
# =========================================================
def _get_gguf_module():
"""Get the ComfyUI-GGUF module if available, otherwise None."""
try:
gguf_cls = nodes.NODE_CLASS_MAPPINGS.get("UnetLoaderGGUF")
if gguf_cls is None:
return None
mod = sys.modules.get(gguf_cls.__module__)
if mod is None:
return None
package = gguf_cls.__module__.rsplit(".", 1)[0]
ops_mod = sys.modules.get(f"{package}.ops")
loader_mod = sys.modules.get(f"{package}.loader")
if ops_mod is None or loader_mod is None:
return None
return {
"GGMLOps": ops_mod.GGMLOps,
"gguf_sd_loader": loader_mod.gguf_sd_loader,
"GGUFModelPatcher": mod.GGUFModelPatcher,
}
except Exception:
return None
def _load_gguf_unet(unet_path):
"""Load a GGUF diffusion model and return MODEL."""
gguf = _get_gguf_module()
if gguf is None:
raise RuntimeError(
"[RecipeModelLoader] This workflow requires ComfyUI-GGUF, "
"but UnetLoaderGGUF is not available."
)
ops = gguf["GGMLOps"]()
sd, extra = gguf["gguf_sd_loader"](unet_path)
kwargs = {}
valid_params = inspect.signature(comfy.sd.load_diffusion_model_state_dict).parameters
if "metadata" in valid_params:
kwargs["metadata"] = extra.get("metadata", {})
model = comfy.sd.load_diffusion_model_state_dict(
sd,
model_options={"custom_operations": ops},
**kwargs,
)
if model is None:
raise RuntimeError(
f"[RecipeModelLoader] Could not detect model type of GGUF: {unet_path}"
)
model = gguf["GGUFModelPatcher"].clone(model)
model.patch_on_device = False
return model
# =========================================================
# Generic loading helpers
# =========================================================
MODEL_EXTENSIONS = ['.safetensors', '.ckpt', '.pt', '.pth', '.bin', '.gguf', '.sft']
WEIGHT_DTYPE_OPTIONS = ["default", "fp8_e4m3fn", "fp8_e4m3fn_fast", "fp8_e5m2"]
def _short_display_name(name):
"""Return basename without known model extension for compact UI/text output."""
raw = str(name or "").strip()
if not raw:
return ""
base = os.path.basename(raw.replace("\\", "/"))
lower = base.lower()
for ext in MODEL_EXTENSIONS:
if lower.endswith(ext):
return base[:-len(ext)]
return os.path.splitext(base)[0]
def _build_model_options(weight_dtype):
"""Build model_options dict from weight_dtype selection."""
model_options = {}
if weight_dtype == "fp8_e4m3fn":
model_options["dtype"] = torch.float8_e4m3fn
elif weight_dtype == "fp8_e4m3fn_fast":
model_options["dtype"] = torch.float8_e4m3fn
model_options["fp8_optimizations"] = True
elif weight_dtype == "fp8_e5m2":
model_options["dtype"] = torch.float8_e5m2
return model_options
def _is_runtime_object(value):
"""True when value looks like a live Comfy runtime object, not workflow metadata."""
return value is not None and not isinstance(value, (str, int, float, bool, list, tuple, dict))
def _extract_preloaded_assets(workflow_data, selected_model_slot):
"""
Reuse already-loaded assets carried in workflow_data (e.g. from RecipeRenderer).
Returns (model, clip, vae) or None when passthrough is unavailable.
"""
if not isinstance(workflow_data, dict):
return None
# v2 recipe_data: runtime assets are model-scoped.
if int(workflow_data.get("version", 0) or 0) >= 2 and isinstance(workflow_data.get("models"), dict):
block = workflow_data.get("models", {}).get(selected_model_slot)
if isinstance(block, dict):
model = block.get("MODEL")
clip = block.get("CLIP")
vae = block.get("VAE")
if _is_runtime_object(model) and _is_runtime_object(clip) and _is_runtime_object(vae):
return (model, clip, vae)
model_key = "MODEL_B" if selected_model_slot == "model_b" else "MODEL_A"
model = workflow_data.get(model_key)
clip = workflow_data.get("CLIP")
vae = workflow_data.get("VAE")
if not _is_runtime_object(model):
return None
if not _is_runtime_object(clip):
return None
if not _is_runtime_object(vae):
return None
return (model, clip, vae)
def _resolve_path(name, folder_key_candidates):
"""
Resolve a model filename against one or more Comfy folder keys.
Tries get_full_path first (exact / relative path), then falls back to
scanning get_filename_list and matching by basename (with or without
extension). This handles models stored in subdirectories.
Returns full path or None.
"""
if not name:
return None
raw = str(name).strip()
if not raw:
return None
normalized = raw.replace("\\", "/")
base = os.path.basename(normalized).lower()
# Strip extension for fuzzy matching
base_no_ext = base
for ext in MODEL_EXTENSIONS:
if base_no_ext.endswith(ext):
base_no_ext = base_no_ext[:-len(ext)]
break
# Pass 1: try get_full_path (works when name is already a valid relative path)
for candidate in (raw, os.path.basename(normalized)):
for key in folder_key_candidates:
try:
path = folder_paths.get_full_path(key, candidate)
if path:
return path
except Exception:
pass
# Pass 2: scan filename lists and match by basename (handles subdirectories)
for key in folder_key_candidates:
try:
file_list = folder_paths.get_filename_list(key)
except Exception:
continue
for f in file_list:
f_normalized = f.replace("\\", "/")
# Exact relative-path match
if f_normalized == normalized:
return folder_paths.get_full_path(key, f)
f_base = os.path.basename(f_normalized).lower()
# Basename match (with extension)
if f_base == base:
return folder_paths.get_full_path(key, f)
# Basename match (without extension)
f_no_ext = f_base
for ext in MODEL_EXTENSIONS:
if f_no_ext.endswith(ext):
f_no_ext = f_no_ext[:-len(ext)]
break
if f_no_ext == base_no_ext:
return folder_paths.get_full_path(key, f)
return None
def _load_checkpoint_by_name(ckpt_name):
"""
Load checkpoint and return (MODEL, CLIP, VAE).
Uses standard checkpoint loading semantics.
"""
ckpt_path = _resolve_path(ckpt_name, ["checkpoints", "diffusion_models", "unet"])
if not ckpt_path:
raise FileNotFoundError(f"[RecipeModelLoader] Checkpoint not found: {ckpt_name}")
out = comfy.sd.load_checkpoint_guess_config(
ckpt_path,
output_vae=True,
output_clip=True,
embedding_directory=folder_paths.get_folder_paths("embeddings"),
)
model, clip, vae = out[:3]
return model, clip, vae
def _load_diffusion_model_by_name(model_name, weight_dtype="default"):
"""
Load a diffusion/UNet model and return MODEL.
If the name ends with .gguf, use the GGUF loader path.
"""
model_path = _resolve_path(model_name, ["diffusion_models", "unet", "unet_gguf", "checkpoints"])
if not model_path:
raise FileNotFoundError(f"[RecipeModelLoader] Diffusion model not found: {model_name}")
if model_name.lower().endswith(".gguf"):
return _load_gguf_unet(model_path)
model_options = _build_model_options(weight_dtype)
model = comfy.sd.load_diffusion_model(model_path, model_options=model_options)
if model is None:
raise RuntimeError(f"[RecipeModelLoader] Could not load diffusion model: {model_name}")
return model
def _load_vae_by_name(vae_name):
"""
Load a VAE and return VAE.
"""
vae_path = _resolve_path(vae_name, ["vae", "checkpoints"])
if not vae_path:
raise FileNotFoundError(f"[RecipeModelLoader] VAE not found: {vae_name}")
sd = comfy.utils.load_torch_file(vae_path)
return comfy.sd.VAE(sd=sd)
def _load_clip_by_names(clip_names, clip_type=""):
"""
Load CLIP from one or more filenames.
clip_names should be a list[str].
"""
if not clip_names:
return None
clip_paths = []
for name in clip_names:
clip_path = _resolve_path(name, ["text_encoders", "clip", "checkpoints"])
if not clip_path:
raise FileNotFoundError(f"[RecipeModelLoader] CLIP not found: {name}")
clip_paths.append(clip_path)
clip_type = (clip_type or "").strip().lower()
# Map a few common values. If unknown, let Comfy infer/default.
clip_type_map = {
"stable_diffusion": comfy.sd.CLIPType.STABLE_DIFFUSION,
"sd": comfy.sd.CLIPType.STABLE_DIFFUSION,
"sdxl": comfy.sd.CLIPType.STABLE_DIFFUSION,
"wan": comfy.sd.CLIPType.WAN,
"flux": comfy.sd.CLIPType.FLUX,
"hunyuan_video": comfy.sd.CLIPType.HUNYUAN_VIDEO,
}
load_kwargs = {
"ckpt_paths": clip_paths,
"embedding_directory": folder_paths.get_folder_paths("embeddings"),
}
if clip_type in clip_type_map:
load_kwargs["clip_type"] = clip_type_map[clip_type]
return comfy.sd.load_clip(**load_kwargs)
# =========================================================
# Node
# =========================================================
class WorkflowModelLoader:
CATEGORY = "Prompt Manager"
RETURN_TYPES = ("MODEL", "CLIP", "VAE")
RETURN_NAMES = ("model", "clip", "vae")
FUNCTION = "get_model"
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"recipe_data": ("RECIPE_DATA", {
"tooltip": "Recipe data containing model name strings to load.",
"forceInput": True,
}),
"model": (["model_a", "model_b", "model_c", "model_d"], {
"default": "model_a",
"tooltip": "Which model slot to load from recipe_data.",
}),
"weight_dtype": (WEIGHT_DTYPE_OPTIONS, {
"default": "default",
"tooltip": "Weight precision override for diffusion/UNet models. Ignored for checkpoints.",
}),
}
}
def get_model(self, recipe_data, model="model_a", weight_dtype="default"):
workflow_data = recipe_data
selected_model_slot = model
if selected_model_slot not in ("model_a", "model_b", "model_c", "model_d"):
selected_model_slot = "model_a"
# Initialize selected slot before normalization so v2 parsing can
# safely resolve per-slot loader/clip/vae fields.
self._model_key = selected_model_slot
self._weight_dtype = weight_dtype
passthrough_assets = _extract_preloaded_assets(workflow_data, selected_model_slot)
spec = self._normalize_spec(workflow_data)
loader_type = spec.get("loader_type", "").lower()
selected_name = spec.get(selected_model_slot, "")
selected_display_name = _short_display_name(selected_name)
if passthrough_assets is not None:
model_obj, clip_obj, vae_obj = passthrough_assets
clip_names = spec.get("clip") or []
vae_name = spec.get("vae", "")
ui_info = {
"model": selected_model_slot,
"model_name": selected_display_name or _short_display_name(spec.get("model_name", "")),
"loader_type": loader_type or "passthrough",
"model_kind": "passthrough",
"vae_name": vae_name,
"clip_names": clip_names,
"status": "ok",
"error_message": "",
"missing_name": "",
"uses_checkpoint_vae": False,
"uses_checkpoint_clip": False,
}
return {
"ui": {"workflow_model_loader_info": [ui_info]},
"result": (model_obj, clip_obj, vae_obj),
}
if loader_type == "checkpoint":
core_result = self._load_checkpoint_mode(spec)
elif loader_type in ("unet", "diffusion"):
core_result = self._load_unet_mode(spec)
else:
raise ValueError(
f"[RecipeModelLoader] Unsupported loader_type: {spec.get('loader_type')}"
)
result = core_result
clip_names = spec.get("clip") or []
vae_name = spec.get("vae", "")
selected_lower = selected_name.lower()
if loader_type == "checkpoint":
model_kind = "checkpoint"
elif selected_lower.endswith(".gguf"):
model_kind = "gguf"
else:
model_kind = "diffusion"
ui_info = {
"model": selected_model_slot,
"model_name": selected_display_name,
"loader_type": loader_type,
"model_kind": model_kind,
"vae_name": vae_name,
"clip_names": clip_names,
"status": "ok",
"error_message": "",
"missing_name": "",
"uses_checkpoint_vae": (loader_type == "checkpoint" and not vae_name),
"uses_checkpoint_clip": (loader_type == "checkpoint" and len(clip_names) == 0),
}
return {
"ui": {"workflow_model_loader_info": [ui_info]},
"result": result,
}
@staticmethod
def _is_placeholder(value):
"""True for display-only strings like '(Default)', '(none)', etc."""
return isinstance(value, str) and value.startswith("(")
def _normalize_spec(self, spec):
spec = dict(spec or {})
spec["model_a"] = (spec.get("model_a") or "").strip()
spec["model_b"] = (spec.get("model_b") or "").strip()
spec["model_c"] = (spec.get("model_c") or "").strip()
spec["model_d"] = (spec.get("model_d") or "").strip()
spec["loader_type"] = (spec.get("loader_type") or "").strip()
spec["clip_type"] = (spec.get("clip_type") or "").strip()
# v2 recipe_data stores model config in per-slot blocks.
if int(spec.get("version", 0) or 0) >= 2 and isinstance(spec.get("models"), dict):
models = spec.get("models", {})
for key in ("model_a", "model_b", "model_c", "model_d"):
block = models.get(key)
if isinstance(block, dict):
model_name = (block.get("model") or "").strip() if isinstance(block.get("model"), str) else ""
if model_name:
spec[key] = model_name
selected_key = getattr(self, "_model_key", "model_a")
if selected_key not in ("model_a", "model_b", "model_c", "model_d"):
selected_key = "model_a"
selected_block = models.get(selected_key) if isinstance(models.get(selected_key), dict) else None
if isinstance(selected_block, dict):
loader_type = (selected_block.get("loader_type") or "").strip() if isinstance(selected_block.get("loader_type"), str) else ""
clip_type = (selected_block.get("clip_type") or "").strip() if isinstance(selected_block.get("clip_type"), str) else ""
vae_name = (selected_block.get("vae") or "").strip() if isinstance(selected_block.get("vae"), str) else ""
clip_names = selected_block.get("clip")
if loader_type:
spec["loader_type"] = loader_type
if clip_type:
spec["clip_type"] = clip_type
if vae_name:
spec["vae"] = vae_name
if isinstance(clip_names, list):
spec["clip"] = clip_names
elif isinstance(clip_names, str) and clip_names.strip():
spec["clip"] = [clip_names.strip()]
# VAE / CLIP: placeholders like '(Default)' mean "use what
# the checkpoint already provides" — normalise to empty.
vae = (spec.get("vae") or "").strip()
spec["vae"] = "" if self._is_placeholder(vae) else vae
clip = spec.get("clip") or []
spec["clip"] = [c for c in clip if c and not self._is_placeholder(c)]
return spec
def _load_checkpoint_mode(self, spec):
ckpt_name = spec.get(self._model_key, "")
if not ckpt_name:
return (
ExecutionBlocker(f"Missing checkpoint in '{self._model_key}'"),
ExecutionBlocker("No CLIP available"),
ExecutionBlocker("No VAE available"),
)
model, clip, vae = _load_checkpoint_by_name(ckpt_name)
clip_override = self._maybe_load_clip_override(spec)
if clip_override is not None:
clip = clip_override
vae_override = self._maybe_load_vae_override(spec)
if vae_override is not None:
vae = vae_override
if clip is None:
clip = ExecutionBlocker(f"No CLIP available for checkpoint '{ckpt_name}'")
if vae is None:
vae = ExecutionBlocker(f"No VAE available for checkpoint '{ckpt_name}'")
return (model, clip, vae)
def _load_unet_mode(self, spec):
model_name = spec.get(self._model_key, "")
if not model_name:
return (
ExecutionBlocker(f"Missing model in '{self._model_key}'"),
ExecutionBlocker("No CLIP available"),
ExecutionBlocker("No VAE available"),
)
model = _load_diffusion_model_by_name(model_name, self._weight_dtype)
clip = self._maybe_load_clip_override(spec)
vae = self._maybe_load_vae_override(spec)
if clip is None:
clip = ExecutionBlocker(
f"No explicit CLIP provided for diffusion model '{model_name}'"
)
if vae is None:
vae = ExecutionBlocker(
f"No explicit VAE provided for diffusion model '{model_name}'"
)
return (model, clip, vae)
def _maybe_load_clip_override(self, spec):
clip_list = spec.get("clip") or []
if len(clip_list) == 0:
return None
return _load_clip_by_names(clip_list, spec.get("clip_type", ""))
def _maybe_load_vae_override(self, spec):
vae_name = spec.get("vae", "")
if not vae_name:
return None
return _load_vae_by_name(vae_name)
+184
View File
@@ -0,0 +1,184 @@
"""
Recipe Model Picker
Builder-style model selector that outputs structured model_data for Recipe Relay.
"""
import folder_paths
from ..py.workflow_families import (
MODEL_FAMILIES,
get_all_family_labels,
get_model_family,
get_compatible_families,
list_compatible_vaes,
list_compatible_clips,
)
DEFAULT_ASSET = "(Default)"
def _gather_models(folder_names):
gathered = []
seen = set()
for folder_name in folder_names:
try:
for model_name in folder_paths.get_filename_list(folder_name):
if model_name not in seen:
seen.add(model_name)
gathered.append(model_name)
except Exception:
continue
return gathered
def _list_models_for_family(family_key):
family_key = str(family_key or "").strip()
if not family_key:
return sorted(_gather_models(["checkpoints", "diffusion_models", "unet", "unet_gguf"]))
compat = get_compatible_families(family_key)
compat_specs = [MODEL_FAMILIES.get(fam, {}) for fam in compat]
preferred_folders = []
for spec in compat_specs:
for folder_name in (spec.get("model_folders", []) or []):
if folder_name and folder_name not in preferred_folders:
preferred_folders.append(folder_name)
if preferred_folders:
model_folders = preferred_folders
elif family_key == "sdxl":
model_folders = ["checkpoints"]
else:
model_folders = ["diffusion_models", "unet", "unet_gguf"]
all_models = _gather_models(model_folders)
models = [m for m in all_models if get_model_family(m) in compat]
if not models:
compat_has_checkpoint = any(spec.get("checkpoint", False) for spec in compat_specs if spec)
if compat_has_checkpoint and family_key == "sdxl":
models = _gather_models(["checkpoints"])
else:
folder_patterns = []
name_patterns = []
for fam in compat:
spec = MODEL_FAMILIES.get(fam, {})
folder_patterns.extend([
p.lower().replace("\\", "/").strip("/")
for p in spec.get("folders", []) if p
])
name_patterns.extend([p.lower() for p in spec.get("names", []) if p])
relaxed = []
for model_name in all_models:
model_lower = model_name.lower().replace("\\", "/")
folder_hit = any(fp and fp in model_lower for fp in folder_patterns)
name_hit = any(pat and pat in model_lower for pat in name_patterns)
if folder_hit or name_hit:
relaxed.append(model_name)
models = relaxed
if family_key == "wan_video_i2v" and models:
i2v_t2v = []
for model_name in models:
lower_name = model_name.lower().replace("\\", "/")
if ("i2v" in lower_name) or ("t2v" in lower_name):
i2v_t2v.append(model_name)
if i2v_t2v:
models = i2v_t2v
return sorted(models)
def _family_maps():
labels = dict(get_all_family_labels() or {})
labels.pop("ltxv", None)
keys = sorted(labels.keys(), key=lambda k: (k != "sdxl", labels.get(k, k).lower()))
label_to_key = {labels[k]: k for k in keys}
type_values = [labels[k] for k in keys]
return labels, label_to_key, type_values
def _family_key_from_type_value(type_value):
labels, label_to_key, _ = _family_maps()
value = str(type_value or "").strip()
if value in labels:
return value
if value in label_to_key:
return label_to_key[value]
return "sdxl"
class RecipeModelPicker:
"""Select family/model/vae/clip and output a single model_data payload."""
@classmethod
def _sync_inputs(cls):
labels, _label_to_key, type_values = _family_maps()
default_family = "sdxl" if "sdxl" in labels else (next(iter(labels.keys()), "sdxl"))
default_type = labels.get(default_family, "SDXL")
model_values = _list_models_for_family(default_family)
if not model_values:
model_values = [""]
vae_values = [DEFAULT_ASSET] + list_compatible_vaes(default_family)
clip_values = [DEFAULT_ASSET] + list_compatible_clips(default_family)
cls._TYPE_VALUES = tuple(type_values or ["SDXL"])
cls._MODEL_VALUES = tuple(model_values)
cls._VAE_VALUES = tuple(vae_values)
cls._CLIP_VALUES = tuple(clip_values)
cls._DEFAULT_TYPE = default_type
@classmethod
def INPUT_TYPES(cls):
cls._sync_inputs()
return {
"required": {
"type": (cls._TYPE_VALUES, {"default": cls._DEFAULT_TYPE, "tooltip": "Model family (Builder type)."}),
"model": (cls._MODEL_VALUES, {"tooltip": "Primary model for selected family."}),
"vae": (cls._VAE_VALUES, {"default": DEFAULT_ASSET, "tooltip": "Optional VAE override; (Default) keeps family defaults."}),
"clip": (cls._CLIP_VALUES, {"default": DEFAULT_ASSET, "tooltip": "Optional CLIP override; (Default) keeps family defaults."}),
}
}
RETURN_TYPES = ("ANY",)
RETURN_NAMES = ("model_data",)
FUNCTION = "pick"
CATEGORY = "Prompt Manager"
DESCRIPTION = "Builder-style Type/Model/VAE/CLIP selector that outputs model_data for Recipe Relay."
def pick(self, type, model, vae, clip):
family = _family_key_from_type_value(type)
family_spec = MODEL_FAMILIES.get(family, {})
selected_model = str(model or "").strip()
if selected_model:
detected = get_model_family(selected_model)
if detected and not family:
family = detected
family_spec = MODEL_FAMILIES.get(family, {})
loader_type = "checkpoint" if family_spec.get("checkpoint", False) else "unet"
clip_type = family_spec.get("clip_type", "")
selected_vae = str(vae or "").strip()
if selected_vae == DEFAULT_ASSET:
selected_vae = ""
selected_clip = str(clip or "").strip()
if selected_clip == DEFAULT_ASSET:
selected_clip = ""
model_data = {
"model": selected_model,
"family": family,
"loader_type": loader_type,
"clip_type": clip_type,
"vae": selected_vae,
"clip": [selected_clip] if selected_clip else [],
}
return (model_data,)
+825
View File
@@ -0,0 +1,825 @@
"""
ComfyUI Workflow Bridge - Pure passthrough node.
Unpacks recipe_data into individual typed outputs.
Any connected optional input overrides the corresponding field before output.
Models (MODEL/CLIP/VAE) are passed through only and cached on the selected model block.
Use RecipeModelLoader for loading from authored model names.
"""
import json
import os
import folder_paths
import nodes
import comfy.samplers
from ..py.lora_utils import resolve_lora_path, get_lora_relative_path, strip_lora_extension
from ..py.workflow_extraction_utils import resolve_model_name
from ..py.workflow_families import get_model_family, MODEL_FAMILIES
MODEL_EXTENSIONS = (".safetensors", ".ckpt", ".pt", ".pth", ".gguf")
def _strip_model_ext(name):
base = os.path.basename(str(name or "").replace("\\", "/"))
lower = base.lower()
for ext in MODEL_EXTENSIONS:
if lower.endswith(ext):
return base[:-len(ext)]
return os.path.splitext(base)[0]
def _resolve_rel_path(raw_name, folder_keys):
"""Resolve a model-like name to a relative Comfy path in the provided folder keys."""
if not raw_name:
return "", False
raw = str(raw_name).strip().replace("\\", "/")
if not raw:
return "", False
base = os.path.basename(raw).lower()
base_no_ext = _strip_model_ext(base).lower()
for key in folder_keys:
try:
file_list = folder_paths.get_filename_list(key)
except Exception:
continue
for rel in file_list:
rel_norm = rel.replace("\\", "/")
if rel_norm == raw:
return rel, True
rel_base = os.path.basename(rel_norm).lower()
if rel_base == base:
return rel, True
if _strip_model_ext(rel_base).lower() == base_no_ext:
return rel, True
return os.path.basename(raw), False
def _get_live_ksampler_combo_types():
"""Mirror the active KSampler enum sockets to avoid stale type mismatches."""
default_samplers = comfy.samplers.KSampler.SAMPLERS
default_schedulers = comfy.samplers.KSampler.SCHEDULERS
try:
from nodes import KSampler as CoreKSampler
required = CoreKSampler.INPUT_TYPES().get("required", {})
samplers = required.get("sampler_name", (default_samplers,))[0]
schedulers = required.get("scheduler", (default_schedulers,))[0]
return samplers, schedulers
except Exception:
return default_samplers, default_schedulers
def _get_live_loader_combo_types():
"""Mirror active loader combo socket types so Relay connects to core load nodes."""
def _from_node(node_names, key, fallback):
for node_name in node_names:
try:
cls = nodes.NODE_CLASS_MAPPINGS.get(node_name)
if cls is None:
continue
required = cls.INPUT_TYPES().get("required", {})
combo = required.get(key)
if isinstance(combo, tuple) and len(combo) >= 1:
return combo[0]
except Exception:
continue
return fallback
ckpt_enum = _from_node(
["CheckpointLoaderSimple", "CheckpointLoader"],
"ckpt_name",
folder_paths.get_filename_list("checkpoints"),
)
unet_enum = _from_node(
["UNETLoader", "UnetLoader", "DiffusionModelLoader"],
"unet_name",
folder_paths.get_filename_list("diffusion_models"),
)
vae_enum = _from_node(
["VAELoader"],
"vae_name",
folder_paths.get_filename_list("vae"),
)
clip_enum = _from_node(
["CLIPLoader"],
"clip_name",
folder_paths.get_filename_list("text_encoders"),
)
return ckpt_enum, unet_enum, vae_enum, clip_enum
_LIVE_SAMPLERS, _LIVE_SCHEDULERS = _get_live_ksampler_combo_types()
_LIVE_CKPTS, _LIVE_UNETS, _LIVE_VAES, _LIVE_CLIPS = _get_live_loader_combo_types()
_MODEL_KEYS = ("model_a", "model_b", "model_c", "model_d")
def _normalize_model_slot(value):
key = str(value or "model_a").strip().lower()
return key if key in _MODEL_KEYS else "model_a"
def _relay_default_sampler():
return {
"steps": 10,
"cfg": 5,
"sampler_name": "euler",
"scheduler": "simple",
"denoise": 1.0,
"seed": 0,
}
def _relay_default_resolution():
return {
"width": 512,
"height": 512,
"batch_size": 1,
"length": 1,
}
def _relay_default_model_block():
return {
"positive_prompt": "",
"negative_prompt": "",
"family": "sdxl",
"model": "",
"loras": [],
"clip_type": "",
"loader_type": "",
"vae": "",
"clip": [],
"sampler": _relay_default_sampler(),
"resolution": _relay_default_resolution(),
}
def _selected_model_block(wf, model_slot, create=False):
if not isinstance(wf.get("models"), dict):
if not create:
return None
wf["models"] = {}
models = wf["models"]
slot = _normalize_model_slot(model_slot)
block = models.get(slot)
if isinstance(block, dict):
return block
if not create:
return None
block = dict(_relay_default_model_block())
models[slot] = block
return block
DEFAULT_RECIPE_DATA = {
"_source": "RecipeRelay",
"version": 2,
"models": {},
}
class WorkflowRelay:
"""
Pure passthrough bridge node.
Unpacks recipe_data into individual typed outputs and forwards
any connected MODEL/CLIP/VAE inputs. No model loading.
"""
@classmethod
def _sync_combo_types(cls):
samplers, schedulers = _get_live_ksampler_combo_types()
ckpts, unets, vaes, clips = _get_live_loader_combo_types()
cls._SAMPLER_ENUM = samplers
cls._SCHEDULER_ENUM = schedulers
cls._UNET_ENUM = unets
cls._CKPT_ENUM = ckpts
cls._VAE_ENUM = vaes
cls._CLIP_ENUM = clips
cls.RETURN_TYPES = (
"RECIPE_DATA",
"MODEL", "CLIP", "CONDITIONING", "CONDITIONING", "VAE", "LATENT", "IMAGE", "MASK", "*", "*",
"INT", "INT", "FLOAT",
cls._SAMPLER_ENUM, cls._SCHEDULER_ENUM, "FLOAT",
"STRING", "STRING",
"LORA_STACK",
"INT", "INT", "INT", "INT",
"STRING", "STRING",
cls._CKPT_ENUM, cls._UNET_ENUM, cls._VAE_ENUM, cls._CLIP_ENUM,
)
@classmethod
def INPUT_TYPES(cls):
cls._sync_combo_types()
return {
"required": {},
"optional": {
"recipe_data": ("RECIPE_DATA", {"forceInput": True, "tooltip": "Optional recipe_data input. If omitted, bridge starts from an empty payload dict."}),
"model_slot": (_MODEL_KEYS, {"default": "model_a", "tooltip": "Select which model slot to read/update in recipe_data."}),
"model": ("MODEL", {"tooltip": "Pass-through Model"}),
"clip": ("CLIP", {"tooltip": "Pass-through CLIP"}),
"positive": ("CONDITIONING", {"tooltip": "Pass-through positive conditioning"}),
"negative": ("CONDITIONING", {"tooltip": "Pass-through negative conditioning"}),
"vae": ("VAE", {"tooltip": "Pass-through VAE"}),
"latent": ("LATENT", {"tooltip": "Pass-through latent"}),
"image": ("IMAGE", {"tooltip": "Pass-through image"}),
"mask": ("MASK", {"tooltip": "Pass-through mask"}),
"extra_1": ("*", {"tooltip": "Pass-through extra data (any type)"}),
"extra_2": ("*", {"tooltip": "Pass-through extra data (any type)"}),
"seed": ("INT", {"forceInput": True, "tooltip": "Override sampler seed"}),
"steps": ("INT", {"forceInput": True, "tooltip": "Override sampling steps"}),
"cfg": ("FLOAT", {"forceInput": True, "tooltip": "Override CFG scale"}),
"sampler_name": (cls._SAMPLER_ENUM, {"forceInput": True, "tooltip": "Override sampler name"}),
"scheduler": (cls._SCHEDULER_ENUM, {"forceInput": True, "tooltip": "Override scheduler"}),
"denoise": ("FLOAT", {"forceInput": True, "tooltip": "Override denoise"}),
"pos_prompt": ("STRING", {"forceInput": True, "tooltip": "Override positive prompt"}),
"neg_prompt": ("STRING", {"forceInput": True, "tooltip": "Override negative prompt"}),
"lora_stack": ("LORA_STACK", {"tooltip": "Override LoRA stack"}),
"width": ("INT", {"forceInput": True, "tooltip": "Override width"}),
"height": ("INT", {"forceInput": True, "tooltip": "Override height"}),
"batch_size": ("INT", {"forceInput": True, "tooltip": "Override batch size"}),
"length": ("INT", {"forceInput": True, "tooltip": "Override video length"}),
"model_name": ("STRING", {"forceInput": True, "tooltip": "Optional model name/path. Resolves and writes recipe model field(s)."}),
"family": ("STRING", {"forceInput": True, "tooltip": "Optional model family override. Writes selected slot family in recipe_data."}),
"model_data": ("*", {"forceInput": True, "tooltip": "Optional structured model payload from Recipe Model Picker."}),
},
}
RETURN_TYPES = (
"RECIPE_DATA",
"MODEL", "CLIP", "CONDITIONING", "CONDITIONING", "VAE", "LATENT", "IMAGE", "MASK", "*", "*",
"INT", "INT", "FLOAT",
_LIVE_SAMPLERS, _LIVE_SCHEDULERS, "FLOAT",
"STRING", "STRING",
"LORA_STACK",
"INT", "INT", "INT", "INT",
"STRING", "STRING",
_LIVE_CKPTS, _LIVE_UNETS, _LIVE_VAES, _LIVE_CLIPS,
)
RETURN_NAMES = (
"recipe_data",
"model", "clip", "positive", "negative", "vae", "latent", "image", "mask", "extra_1", "extra_2",
"seed", "steps", "cfg",
"sampler_name", "scheduler", "denoise",
"pos_prompt", "neg_prompt",
"lora_stack",
"width", "height", "batch_size", "length",
"model_name", "family",
"ckpt_name", "unet_name", "vae_name", "clip_name",
)
FUNCTION = "unpack"
CATEGORY = "Prompt Manager"
DESCRIPTION = (
"Pure passthrough bridge node. Unpacks recipe_data into individual "
"typed outputs. Slot runtime objects are cached on the selected model block."
)
# ------------------------------------------------------------------
def unpack(self, recipe_data=None, model_slot="model_a", **kwargs):
def _normalize_lora_stack_input(raw_stack):
rows = []
if raw_stack is None:
return rows
for entry in raw_stack:
if not (isinstance(entry, (list, tuple)) and len(entry) >= 1):
continue
raw_name = str(entry[0] or "").strip()
if not raw_name:
continue
try:
model_strength = float(entry[1]) if len(entry) >= 2 else 1.0
except Exception:
model_strength = 1.0
try:
clip_strength = float(entry[2]) if len(entry) >= 3 else model_strength
except Exception:
clip_strength = model_strength
rel_path, available = get_lora_relative_path(raw_name)
if not available or not rel_path:
# Some valid LoRA identifiers resolve via full-path lookup
# but not via relative-name lookup. Keep availability in
# sync with relay output path resolution behavior.
_resolved_full, resolved_available = resolve_lora_path(raw_name)
if resolved_available:
available = True
rel_path = raw_name
display_name = strip_lora_extension(os.path.basename(str(rel_path).replace("\\", "/")))
rows.append({
'name': display_name,
'path': rel_path,
'model_strength': model_strength,
'clip_strength': clip_strength,
'active': True,
'available': bool(available),
})
return rows
def _resolve_lora_output_path(lora_item):
if not isinstance(lora_item, dict):
return "", False
candidate = str(lora_item.get('path') or lora_item.get('name') or '').strip()
if not candidate:
return "", False
rel_path, available = get_lora_relative_path(candidate)
if available and rel_path:
return rel_path, True
# Some stored payloads contain absolute paths or names with extensions.
# Retry with basename and extension-stripped basename before declaring missing.
candidate_base = os.path.basename(candidate.replace("\\", "/")).strip()
if candidate_base:
rel_path, available = get_lora_relative_path(candidate_base)
if available and rel_path:
return rel_path, True
candidate_base_no_ext = strip_lora_extension(candidate_base)
if candidate_base_no_ext and candidate_base_no_ext != candidate_base:
rel_path, available = get_lora_relative_path(candidate_base_no_ext)
if available and rel_path:
return rel_path, True
_, resolved_available = resolve_lora_path(candidate)
if resolved_available:
rel_path, available = get_lora_relative_path(candidate)
if available and rel_path:
return rel_path, True
if candidate_base:
_, resolved_available = resolve_lora_path(candidate_base)
if resolved_available:
rel_path, available = get_lora_relative_path(candidate_base)
if available and rel_path:
return rel_path, True
candidate_base_no_ext = strip_lora_extension(candidate_base)
if candidate_base_no_ext and candidate_base_no_ext != candidate_base:
_, resolved_available = resolve_lora_path(candidate_base_no_ext)
if resolved_available:
rel_path, available = get_lora_relative_path(candidate_base_no_ext)
if available and rel_path:
return rel_path, True
return candidate_base or candidate, False
def _short_display_name(name):
raw = str(name or "").strip()
if not raw:
return ""
base = os.path.basename(raw.replace("\\", "/"))
return os.path.splitext(base)[0]
# Accept both dict and JSON string
if isinstance(recipe_data, str):
try:
incoming_wf = json.loads(recipe_data)
except (json.JSONDecodeError, TypeError):
incoming_wf = {}
elif isinstance(recipe_data, dict):
incoming_wf = dict(recipe_data)
else:
incoming_wf = {}
has_incoming_data = isinstance(incoming_wf, dict) and bool(incoming_wf)
has_slot_write_request = any([
kwargs.get('lora_stack') is not None,
any(kwargs.get(k) is not None for k in ('pos_prompt', 'neg_prompt')),
any(kwargs.get(k) is not None for k in ('steps', 'seed', 'cfg', 'denoise', 'sampler_name', 'scheduler')),
any(kwargs.get(k) is not None for k in ('width', 'height', 'batch_size', 'length')),
isinstance(kwargs.get('model_name'), str) and kwargs.get('model_name').strip() != '',
kwargs.get('family') is not None,
kwargs.get('model_data') is not None,
])
create_block_on_write = (not has_incoming_data) or has_slot_write_request
# Preserve incoming recipe_data exactly when present.
# Only fall back to the empty template when no input payload exists.
if has_incoming_data:
wf = dict(incoming_wf)
if isinstance(incoming_wf.get('sampler'), dict):
wf['sampler'] = dict(incoming_wf['sampler'])
if isinstance(incoming_wf.get('resolution'), dict):
wf['resolution'] = dict(incoming_wf['resolution'])
if isinstance(incoming_wf.get('models'), dict):
wf['models'] = {
k: dict(v) if isinstance(v, dict) else v
for k, v in incoming_wf.get('models', {}).items()
}
else:
wf = dict(DEFAULT_RECIPE_DATA)
wf['models'] = {}
# Relay now treats recipe payloads as v2-only canonical data.
wf['version'] = 2
if not isinstance(wf.get('models'), dict):
wf['models'] = {}
selected_slot = _normalize_model_slot(model_slot)
selected_block = _selected_model_block(wf, selected_slot, create=create_block_on_write)
slot_family = selected_block.get('family', '') if isinstance(selected_block, dict) else ''
slot_model_name = selected_block.get('model', '') if isinstance(selected_block, dict) else ''
slot_positive = selected_block.get('positive_prompt', '') if isinstance(selected_block, dict) else ''
slot_negative = selected_block.get('negative_prompt', '') if isinstance(selected_block, dict) else ''
slot_vae = selected_block.get('vae', '') if isinstance(selected_block, dict) else ''
slot_clip = selected_block.get('clip', []) if isinstance(selected_block, dict) else []
slot_loras = selected_block.get('loras', []) if isinstance(selected_block, dict) else []
slot_sampler = selected_block.get('sampler', {}) if isinstance(selected_block, dict) and isinstance(selected_block.get('sampler'), dict) else {}
slot_resolution = selected_block.get('resolution', {}) if isinstance(selected_block, dict) and isinstance(selected_block.get('resolution'), dict) else {}
sampler = dict(_relay_default_sampler())
if isinstance(wf.get('sampler'), dict):
sampler.update(wf.get('sampler', {}))
if isinstance(slot_sampler, dict):
sampler.update(slot_sampler)
resolution = dict(_relay_default_resolution())
if isinstance(wf.get('resolution'), dict):
resolution.update(wf.get('resolution', {}))
if isinstance(slot_resolution, dict):
resolution.update(slot_resolution)
# -- Apply top-level overrides -------------------------------
pos_text = kwargs.get('pos_prompt')
if pos_text is not None:
target_block = _selected_model_block(wf, selected_slot, create=create_block_on_write)
if isinstance(target_block, dict):
target_block['positive_prompt'] = pos_text
neg_text = kwargs.get('neg_prompt')
if neg_text is not None:
target_block = _selected_model_block(wf, selected_slot, create=create_block_on_write)
if isinstance(target_block, dict):
target_block['negative_prompt'] = neg_text
# -- LoRA stack overrides ------------------------------------
if kwargs.get('lora_stack') is not None:
normalized_stack = _normalize_lora_stack_input(kwargs['lora_stack'])
target_block = _selected_model_block(wf, selected_slot, create=create_block_on_write)
if isinstance(target_block, dict):
target_block['loras'] = normalized_stack
# -- Resolution overrides ------------------------------------
for key in ('width', 'height', 'batch_size', 'length'):
if kwargs.get(key) is not None:
resolution[key] = kwargs[key]
wf['resolution'] = resolution
# # -- Sampler overrides ---------------------------------------
# if kwargs.get('steps') is not None:
# sampler['steps_a'] = kwargs['steps']
# sampler['steps_b'] = kwargs['steps']
# if kwargs.get('seed') is not None:
# sampler['seed_a'] = kwargs['seed']
# sampler['seed_b'] = kwargs['seed']
for key in ('cfg', 'denoise', 'sampler_name', 'scheduler'):
if kwargs.get(key) is not None:
sampler[key] = kwargs[key]
wf['sampler'] = sampler
target_block = _selected_model_block(wf, selected_slot, create=create_block_on_write)
if isinstance(target_block, dict):
bs = target_block.get('sampler', {}) if isinstance(target_block.get('sampler'), dict) else {}
if kwargs.get('steps') is not None:
bs['steps'] = kwargs['steps']
if kwargs.get('seed') is not None:
bs['seed'] = kwargs['seed']
for key in ('cfg', 'denoise', 'sampler_name', 'scheduler'):
if kwargs.get(key) is not None:
bs[key] = kwargs[key]
target_block['sampler'] = bs
br = target_block.get('resolution', {}) if isinstance(target_block.get('resolution'), dict) else {}
for key in ('width', 'height', 'batch_size', 'length'):
if kwargs.get(key) is not None:
br[key] = kwargs[key]
if br:
target_block['resolution'] = br
# -- Model/CLIP/VAE name overrides ---------------------------
model_name_in = kwargs.get('model_name')
if isinstance(model_name_in, str) and model_name_in.strip():
resolved_name, _ = resolve_model_name(model_name_in)
chosen_name = resolved_name or os.path.basename(model_name_in.strip().replace("\\", "/"))
target_block = _selected_model_block(wf, selected_slot, create=create_block_on_write)
if isinstance(target_block, dict):
target_block['model'] = chosen_name
family = get_model_family(chosen_name)
if family:
family_spec = MODEL_FAMILIES.get(family, {})
target_block = _selected_model_block(wf, selected_slot, create=create_block_on_write)
if isinstance(target_block, dict):
target_block['family'] = family
target_block['clip_type'] = family_spec.get('clip_type', '')
target_block['loader_type'] = 'checkpoint' if family_spec.get('checkpoint', False) else 'unet'
# -- Pass-through MODEL / CLIP / VAE -------------------------
# Priority: explicit connected inputs > embedded objects in workflow_data.
model = kwargs.get('model')
if model is None:
model = selected_block.get('MODEL') if isinstance(selected_block, dict) else None
# if model is None:
# model = wf.get('MODEL')
# if model is None:
# model = wf.get('MODEL_A')
selected_loader_type = (
str((selected_block or {}).get('loader_type', '')).strip().lower()
if isinstance(selected_block, dict)
else ''
)
clip = kwargs.get('clip')
if clip is None:
clip = selected_block.get('CLIP') if isinstance(selected_block, dict) else None
if clip is None:
clip = wf.get('CLIP')
vae = kwargs.get('vae')
if vae is None:
vae = selected_block.get('VAE') if isinstance(selected_block, dict) else None
if vae is None:
vae = wf.get('VAE')
positive = kwargs.get('positive')
if positive is None:
positive = selected_block.get('POSITIVE') if isinstance(selected_block, dict) else None
if positive is None:
positive = wf.get('POSITIVE')
negative = kwargs.get('negative')
if negative is None:
negative = selected_block.get('NEGATIVE') if isinstance(selected_block, dict) else None
if negative is None:
negative = wf.get('NEGATIVE')
extra_1 = kwargs.get('extra_1')
if extra_1 is None:
extra_1 = selected_block.get('EXTRA_1') if isinstance(selected_block, dict) else None
if extra_1 is None:
extra_1 = wf.get('EXTRA_1')
extra_2 = kwargs.get('extra_2')
if extra_2 is None:
extra_2 = selected_block.get('EXTRA_2') if isinstance(selected_block, dict) else None
if extra_2 is None:
extra_2 = wf.get('EXTRA_2')
latent = kwargs.get('latent')
if latent is None:
latent = wf.get('LATENT')
image = kwargs.get('image')
if image is None:
image = wf.get('IMAGE')
mask = kwargs.get('mask')
if mask is None:
mask = wf.get('MASK')
if isinstance(target_block, dict):
if model is not None:
target_block['MODEL'] = model
if clip is not None:
target_block['CLIP'] = clip
if vae is not None:
target_block['VAE'] = vae
if positive is not None:
target_block['POSITIVE'] = positive
if negative is not None:
target_block['NEGATIVE'] = negative
if extra_1 is not None:
target_block['EXTRA_1'] = extra_1
if extra_2 is not None:
target_block['EXTRA_2'] = extra_2
if latent is not None:
wf['LATENT'] = latent
if image is not None:
wf['IMAGE'] = image
if mask is not None:
wf['MASK'] = mask
# -- Build lora stacks as tuples for LORA_STACK output -------
# Filter not-found LoRAs here so downstream nodes receiving
# LORA_STACK don't get unavailable entries. Keep wf['loras_*']
# unchanged to preserve authored workflow_data for chaining.
def _is_active_available(lora_item):
if not isinstance(lora_item, dict):
return False
resolved_path, available = _resolve_lora_output_path(lora_item)
if not resolved_path:
return False
if lora_item.get('active', True) is False:
return False
# Ignore persisted availability flags; they may be stale across sessions.
# Use current filesystem resolution as source of truth.
return available
legacy_slot_loras = []
lora_stack = [
(_resolve_lora_output_path(item)[0], item.get('model_strength', 1.0), item.get('clip_strength', 1.0))
for item in legacy_slot_loras
if _is_active_available(item)
]
final_selected = _selected_model_block(wf, selected_slot, create=create_block_on_write)
selected_loras = final_selected.get('loras', []) if isinstance(final_selected, dict) and isinstance(final_selected.get('loras'), list) else []
if selected_loras:
lora_stack = [
(_resolve_lora_output_path(item)[0], item.get('model_strength', 1.0), item.get('clip_strength', 1.0))
for item in selected_loras
if _is_active_available(item)
]
elif not lora_stack and isinstance(slot_loras, list):
lora_stack = [
(_resolve_lora_output_path(item)[0], item.get('model_strength', 1.0), item.get('clip_strength', 1.0))
for item in slot_loras
if _is_active_available(item)
]
final_sampler = dict(sampler)
if isinstance(final_selected, dict) and isinstance(final_selected.get('sampler'), dict):
final_sampler.update(final_selected.get('sampler', {}))
final_resolution = dict(resolution)
if isinstance(final_selected, dict) and isinstance(final_selected.get('resolution'), dict):
final_resolution.update(final_selected.get('resolution', {}))
final_model_name = ''
if isinstance(final_selected, dict):
final_model_name = _short_display_name(final_selected.get('model', ''))
if not final_model_name:
final_model_name = _short_display_name(slot_model_name)
final_pos = (final_selected.get('positive_prompt', '') if isinstance(final_selected, dict) else '') or slot_positive
final_neg = (final_selected.get('negative_prompt', '') if isinstance(final_selected, dict) else '') or slot_negative
raw_model_data = kwargs.get('model_data')
if isinstance(raw_model_data, str):
try:
model_data_in = json.loads(raw_model_data)
except Exception:
model_data_in = {}
elif isinstance(raw_model_data, dict):
model_data_in = dict(raw_model_data)
else:
model_data_in = {}
ckpt_name_in = str(model_data_in.get('ckpt_name', '') or '').strip()
unet_name_in = str(model_data_in.get('unet_name', '') or '').strip()
vae_name_in = str(model_data_in.get('vae_name', model_data_in.get('vae', '')) or '').strip()
clip_name_in = str(model_data_in.get('clip_name', '') or '').strip()
if not clip_name_in and isinstance(model_data_in.get('clip'), list) and model_data_in.get('clip'):
clip_name_in = str(model_data_in.get('clip')[0] or '').strip()
model_name_from_data = str(model_data_in.get('model', '') or '').strip()
loader_type_from_data = str(model_data_in.get('loader_type', '') or '').strip().lower()
family_from_data = str(model_data_in.get('family', '') or '').strip()
clip_type_from_data = str(model_data_in.get('clip_type', '') or '').strip()
selected_model_raw = (final_selected.get('model', '') if isinstance(final_selected, dict) else '') or slot_model_name or ''
selected_vae_raw = (final_selected.get('vae', '') if isinstance(final_selected, dict) else '') or slot_vae or ''
selected_clip_raw = ''
if isinstance(final_selected, dict) and isinstance(final_selected.get('clip'), list) and final_selected.get('clip'):
selected_clip_raw = str(final_selected.get('clip')[0] or '').strip()
elif isinstance(slot_clip, list) and slot_clip:
selected_clip_raw = str(slot_clip[0] or '').strip()
selected_model_name = str(selected_model_raw or '').strip()
selected_vae_name = str(selected_vae_raw or '').strip()
selected_clip_name = str(selected_clip_raw or '').strip()
# Structured model_data / combo-name overrides are authoritative.
if model_name_from_data:
selected_model_name = model_name_from_data
if loader_type_from_data in ('checkpoint', 'unet', 'diffusion'):
selected_loader_type = 'unet' if loader_type_from_data == 'diffusion' else loader_type_from_data
# If checkpoint/unet names are provided, update model name and loader type
# even when recipe_data did not previously declare a loader type.
if ckpt_name_in:
selected_model_name = ckpt_name_in
selected_loader_type = 'checkpoint'
elif unet_name_in:
selected_model_name = unet_name_in
selected_loader_type = 'unet'
if vae_name_in:
selected_vae_name = vae_name_in
if clip_name_in:
selected_clip_name = clip_name_in
target_block = _selected_model_block(wf, selected_slot, create=create_block_on_write)
if isinstance(target_block, dict):
if selected_model_name:
target_block['model'] = selected_model_name
if selected_loader_type:
target_block['loader_type'] = selected_loader_type
if family_from_data:
target_block['family'] = family_from_data
if clip_type_from_data:
target_block['clip_type'] = clip_type_from_data
if selected_vae_name:
target_block['vae'] = selected_vae_name
if selected_clip_name:
target_block['clip'] = [selected_clip_name]
if selected_model_name:
detected_family = get_model_family(selected_model_name)
if detected_family:
detected_block = _selected_model_block(wf, selected_slot, create=create_block_on_write)
if isinstance(detected_block, dict):
detected_block['family'] = detected_family
family_in = kwargs.get('family')
if family_in is not None:
family_override = str(family_in or '').strip()
family_block = _selected_model_block(wf, selected_slot, create=create_block_on_write)
if isinstance(family_block, dict):
family_block['family'] = family_override
# -- Extract all output values -------------------------------
model_name = _short_display_name(selected_model_name) or final_model_name
family_out = ''
current_block = _selected_model_block(wf, selected_slot, create=False)
if isinstance(current_block, dict):
family_out = str(current_block.get('family', '') or '').strip()
if not family_out:
family_out = str(slot_family or '').strip()
resolved_ckpt_name, ckpt_found = _resolve_rel_path(selected_model_name, ("checkpoints",))
resolved_unet_name, unet_found = _resolve_rel_path(selected_model_name, ("diffusion_models", "unet", "unet_gguf"))
# Infer loader type when metadata is missing but model path resolves.
if selected_loader_type not in ('checkpoint', 'unet', 'diffusion'):
if ckpt_found and not unet_found:
selected_loader_type = 'checkpoint'
elif unet_found and not ckpt_found:
selected_loader_type = 'unet'
elif ckpt_found and unet_found:
family_spec = MODEL_FAMILIES.get(family_out, {}) if family_out else {}
selected_loader_type = 'checkpoint' if family_spec.get('checkpoint', False) else 'unet'
# Always emit string outputs for combo-name sockets to avoid None flowing
# into downstream standard loader nodes.
if ckpt_name_in:
ckpt_out = ckpt_name_in
elif selected_loader_type == 'checkpoint':
ckpt_out = resolved_ckpt_name if ckpt_found else (selected_model_name or "")
elif ckpt_found and not unet_found:
ckpt_out = resolved_ckpt_name
else:
ckpt_out = ""
if unet_name_in:
unet_out = unet_name_in
elif selected_loader_type in ('unet', 'diffusion'):
unet_out = resolved_unet_name if unet_found else (selected_model_name or "")
elif unet_found and not ckpt_found:
unet_out = resolved_unet_name
else:
unet_out = ""
vae_name_out = selected_vae_name or ""
clip_name_out = selected_clip_name or ""
return (
wf,
model, clip, positive, negative, vae, latent, image, mask, extra_1, extra_2,
final_sampler.get('seed_a', final_sampler.get('seed', 0)),
final_sampler.get('steps_a', final_sampler.get('steps', 10)),
final_sampler.get('cfg', 5.0),
final_sampler.get('sampler_name', 'euler'),
final_sampler.get('scheduler', 'simple'),
final_sampler.get('denoise', 1.0),
final_pos,
final_neg,
lora_stack,
final_resolution.get('width', 512),
final_resolution.get('height', 512),
final_resolution.get('batch_size', 1),
final_resolution.get('length', 0) or 0,
model_name,
family_out,
ckpt_out,
unet_out,
vae_name_out,
clip_name_out,
)
File diff suppressed because it is too large Load Diff
-58
View File
@@ -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)
-2000
View File
File diff suppressed because it is too large Load Diff
View File
+422
View File
@@ -0,0 +1,422 @@
#!/usr/bin/env python3
"""
convert_to_api.py — Convert ComfyUI UI-format workflow JSON to API format + _map.json
Usage:
python tools/convert_to_api.py
# Reads from workflows/*.json, writes to workflows/api/*_api.json + *_map.json
API format: dict keyed by node ID (string), each value = {"class_type": ..., "inputs": {...}}
Map format: dict of semantic field -> [node_id_str, input_field_name]
"""
import json
import os
import sys
# ── Path setup ──────────────────────────────────────────────────────────────
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
REPO_ROOT = os.path.dirname(SCRIPT_DIR)
SRC_DIR = os.path.join(REPO_ROOT, "workflows")
DST_DIR = os.path.join(REPO_ROOT, "workflows", "api")
os.makedirs(DST_DIR, exist_ok=True)
# ── UI → API conversion ──────────────────────────────────────────────────────
def ui_to_api(ui_data):
"""
Convert a UI-format workflow dict to API-format.
UI format: { nodes: [...], links: [...], ... }
- nodes have id, type, inputs (with link IDs), outputs (with link IDs), widgets_values
API format: { "NODE_ID": { class_type, inputs: {field: value_or_[src_id, slot]} } }
Widget values are embedded directly; linked inputs reference the source node+slot.
"""
nodes = ui_data.get("nodes", [])
links = ui_data.get("links", [])
# Build link map: link_id -> (src_node_id, src_slot_index)
# Links: [link_id, src_node_id, src_slot, dst_node_id, dst_slot, type]
link_map = {}
for lk in links:
if len(lk) >= 4:
link_map[lk[0]] = (str(lk[1]), lk[2])
api = {}
for node in nodes:
node_id = str(node["id"])
class_type = node["type"]
inputs_def = node.get("inputs", []) # [{name, type, link, widget?}]
widgets_val = node.get("widgets_values", [])
# We need to figure out which inputs are widget-backed vs link-backed.
# ComfyUI heuristic:
# - If input has a "widget" key, it is widget-backed (value from widgets_values)
# - If input has a "link" key (non-null), it is link-backed
# - Some inputs can be either (widget overridable by link)
api_inputs = {}
widget_idx = 0 # index into widgets_values
for inp in inputs_def:
name = inp["name"]
link = inp.get("link")
has_widget = "widget" in inp
if link is not None:
# Link wins
src = link_map.get(link)
if src:
api_inputs[name] = [src[0], src[1]]
else:
# Dangling link — fall back to widget value if available
if has_widget and widget_idx < len(widgets_val):
api_inputs[name] = widgets_val[widget_idx]
widget_idx += 1
elif has_widget:
if widget_idx < len(widgets_val):
api_inputs[name] = widgets_val[widget_idx]
widget_idx += 1
# else: pure output-only input — skip
# Any remaining widgets_values beyond named widget inputs are for
# implicit widget-only nodes (e.g. seed control extra slot "control_after_generate")
# We inject them by matching known extra widget names per class_type
_inject_extra_widgets(class_type, api_inputs, widgets_val, widget_idx)
api[node_id] = {
"class_type": class_type,
"inputs": api_inputs,
}
return api
def _inject_extra_widgets(class_type, api_inputs, widgets_val, start_idx):
"""
Some nodes have implicit extra widget slots not reflected in the inputs list.
The most common: KSampler seed has a hidden 'control_after_generate' slot
inserted after noise_seed in widgets_values, but it is NOT in the inputs
definition — so our widget_idx counter goes off by 1 after consuming seed.
We fully re-map widgets_values for known node types that have hidden slots,
overwriting anything the loop may have set incorrectly.
"""
# KSampler: [seed, control_after_generate, steps, cfg, sampler_name, scheduler, denoise]
# inputs list has: seed, steps, cfg, sampler_name, scheduler, denoise (no control_after_generate)
if class_type == "KSampler" and len(widgets_val) >= 7:
api_inputs["seed"] = widgets_val[0]
# widgets_val[1] = control_after_generate -- skip
api_inputs["steps"] = widgets_val[2]
api_inputs["cfg"] = widgets_val[3]
api_inputs["sampler_name"] = widgets_val[4]
api_inputs["scheduler"] = widgets_val[5]
api_inputs["denoise"] = widgets_val[6]
# KSamplerAdvanced: [add_noise, noise_seed, control_after_generate, steps, cfg,
# sampler_name, scheduler, start_at_step, end_at_step, return_with_leftover_noise]
elif class_type == "KSamplerAdvanced" and len(widgets_val) >= 10:
api_inputs["add_noise"] = widgets_val[0]
api_inputs["noise_seed"] = widgets_val[1]
# widgets_val[2] = control_after_generate -- skip
api_inputs["steps"] = widgets_val[3]
api_inputs["cfg"] = widgets_val[4]
api_inputs["sampler_name"] = widgets_val[5]
api_inputs["scheduler"] = widgets_val[6]
api_inputs["start_at_step"] = widgets_val[7]
api_inputs["end_at_step"] = widgets_val[8]
api_inputs["return_with_leftover_noise"] = widgets_val[9]
# RandomNoise: [noise_seed, control_after_generate]
elif class_type == "RandomNoise" and len(widgets_val) >= 1:
api_inputs["noise_seed"] = widgets_val[0]
# widgets_val[1] = control_after_generate -- skip
# ── Map generation ───────────────────────────────────────────────────────────
def build_map(api, family_hint):
"""
Build a semantic field map for the given API workflow.
Returns a dict: { field_name: [node_id_str, input_key] | null }
The map is used by RecipeRenderer to patch values before execution.
"""
m = {}
for nid, node in api.items():
ct = node["class_type"]
inp = node["inputs"]
# ── Positive / Negative prompts ──────────────────────────────────
if ct == "CLIPTextEncode":
# Determine pos vs neg by looking at what this feeds into
# We'll do a two-pass approach after the loop
pass
# ── Checkpoint loader ─────────────────────────────────────────────
if ct in ("CheckpointLoaderSimple", "CheckpointLoader"):
m["checkpoint"] = [nid, "ckpt_name"]
# ── UNET loaders ─────────────────────────────────────────────────
if ct in ("UNETLoader", "UNETLoaderGGUF"):
if "model_a" not in m:
m["model_a"] = [nid, "unet_name"]
else:
m["model_b"] = [nid, "unet_name"]
# ── VAE ───────────────────────────────────────────────────────────
if ct == "VAELoader":
m["vae"] = [nid, "vae_name"]
# ── CLIP / text encoder ───────────────────────────────────────────
if ct in ("CLIPLoader", "DualCLIPLoader"):
if ct == "DualCLIPLoader":
m["clip_1"] = [nid, "clip_name1"]
m["clip_2"] = [nid, "clip_name2"]
else:
m["clip"] = [nid, "clip_name"]
# ── Latent size ───────────────────────────────────────────────────
if ct in ("EmptyLatentImage", "EmptySD3LatentImage", "EmptyHunyuanLatentVideo"):
m["latent_width"] = [nid, "width"]
m["latent_height"] = [nid, "height"]
if ct == "EmptyHunyuanLatentVideo":
m["latent_length"] = [nid, "length"]
# ── WanImageToVideo latent (i2v) — size comes from Resize node ───
if ct == "WanImageToVideo":
m["wan_i2v_latent"] = [nid, "start_image"] # image input
# width/height fed from resize node — mapped separately
# ── Resize node (used in i2v for size control) ────────────────────
if ct in ("ImageResizeKJv2", "ImageScale", "ImageResize"):
if "resize_width" not in m:
m["resize_width"] = [nid, "width"]
m["resize_height"] = [nid, "height"]
# ── KSampler (standard) ───────────────────────────────────────────
if ct == "KSampler":
m["ksampler_seed"] = [nid, "seed"]
m["ksampler_steps"] = [nid, "steps"]
m["ksampler_cfg"] = [nid, "cfg"]
m["ksampler_sampler"] = [nid, "sampler_name"]
m["ksampler_scheduler"] = [nid, "scheduler"]
m["ksampler_denoise"] = [nid, "denoise"]
# ── KSamplerAdvanced (WAN dual) ───────────────────────────────────
if ct == "KSamplerAdvanced":
if "ksampler_high_seed" not in m:
m["ksampler_high_seed"] = [nid, "noise_seed"]
m["ksampler_high_steps"] = [nid, "steps"]
m["ksampler_high_start"] = [nid, "start_at_step"]
m["ksampler_high_end"] = [nid, "end_at_step"]
m["ksampler_high_cfg"] = [nid, "cfg"]
m["ksampler_high_sampler"] = [nid, "sampler_name"]
m["ksampler_high_scheduler"] = [nid, "scheduler"]
else:
m["ksampler_low_seed"] = [nid, "noise_seed"]
m["ksampler_low_steps"] = [nid, "steps"]
m["ksampler_low_start"] = [nid, "start_at_step"]
m["ksampler_low_end"] = [nid, "end_at_step"]
m["ksampler_low_cfg"] = [nid, "cfg"]
m["ksampler_low_sampler"] = [nid, "sampler_name"]
m["ksampler_low_scheduler"] = [nid, "scheduler"]
# ── Flux / custom samplers ────────────────────────────────────────
if ct == "KSamplerSelect":
m["flux_sampler"] = [nid, "sampler_name"]
if ct in ("BasicScheduler",):
m["flux_scheduler"] = [nid, "scheduler"]
m["flux_steps"] = [nid, "steps"]
m["flux_denoise"] = [nid, "denoise"]
if ct == "Flux2Scheduler":
m["flux2_steps"] = [nid, "steps"]
m["flux2_width"] = [nid, "width"]
m["flux2_height"] = [nid, "height"]
if ct == "CFGGuider":
m["flux2_cfg"] = [nid, "cfg"]
if ct == "FluxGuidance":
m["flux_guidance"] = [nid, "guidance"]
if ct == "RandomNoise":
m["flux_seed"] = [nid, "noise_seed"]
# ── PromptApplyLora ───────────────────────────────────────────────
if ct == "PromptApplyLora":
if "lora_stack_a" not in m:
m["lora_stack_a"] = [nid, "lora_stack_text"]
else:
m["lora_stack_b"] = [nid, "lora_stack_text"]
# ── VAEDecode (output image) ───────────────────────────────────────
if ct == "VAEDecode":
m["vae_decode"] = [nid, None] # source of output IMAGE tensor
# ── SaveImage → mark for removal ─────────────────────────────────
if ct == "SaveImage":
m.setdefault("_save_nodes", []).append(nid)
# ── ModelSamplingSD3 (WAN shift) ──────────────────────────────────
if ct == "ModelSamplingSD3":
if "wan_shift_a" not in m:
m["wan_shift_a"] = [nid, "shift"]
else:
m["wan_shift_b"] = [nid, "shift"]
# ── Two-pass: resolve CLIPTextEncode pos/neg by tracing links ────────
_resolve_clip_text_encode(api, m)
return m
def _resolve_clip_text_encode(api, m):
"""
For CLIPTextEncode nodes, determine which is positive and which is negative
by checking what node/slot they feed into.
"""
# Build reverse link map: (dst_node_id, dst_slot) -> src_node_id
# We look at each node's inputs and find CLIPTextEncode sources
text_encode_nodes = [nid for nid, n in api.items() if n["class_type"] == "CLIPTextEncode"]
if not text_encode_nodes:
return
# For each CLIPTextEncode, check what uses its output
# In API format, inputs reference sources as [src_node_id, src_slot]
pos_node = None
neg_node = None
for nid, node in api.items():
for field, val in node["inputs"].items():
if isinstance(val, list) and len(val) == 2:
src_nid = str(val[0])
if src_nid in text_encode_nodes:
if field == "positive" and pos_node is None:
pos_node = src_nid
elif field == "negative" and neg_node is None:
neg_node = src_nid
# WanImageToVideo also has positive/negative
elif field == "positive":
pass
elif field == "negative":
pass
# Also handle FluxGuidance — positive goes into conditioning input
if pos_node is None:
for nid, node in api.items():
if node["class_type"] == "FluxGuidance":
for field, val in node["inputs"].items():
if field == "conditioning" and isinstance(val, list):
src = str(val[0])
if src in text_encode_nodes:
pos_node = src
break
# For ConditioningZeroOut — that's the negative for Flux
for nid, node in api.items():
if node["class_type"] == "ConditioningZeroOut":
neg_node = nid # The output of ConditioningZeroOut is the negative
if pos_node:
m["positive_prompt"] = [pos_node, "text"]
if neg_node and api.get(neg_node, {}).get("class_type") == "CLIPTextEncode":
m["negative_prompt"] = [neg_node, "text"]
elif neg_node and api.get(neg_node, {}).get("class_type") == "ConditioningZeroOut":
# For Flux, negative is zero — we patch the CLIPTextEncode feeding into it
for nid, node in api.items():
if node["class_type"] == "ConditioningZeroOut":
for field, val in node["inputs"].items():
if isinstance(val, list):
src = str(val[0])
if api.get(src, {}).get("class_type") == "CLIPTextEncode":
m["negative_prompt"] = [src, "text"]
break
# Fallback: if only one CLIPTextEncode, it's positive
if pos_node is None and len(text_encode_nodes) >= 1:
m["positive_prompt"] = [text_encode_nodes[0], "text"]
if neg_node is None and len(text_encode_nodes) >= 2:
m["negative_prompt"] = [text_encode_nodes[1], "text"]
# ── Strip SaveImage nodes from API ───────────────────────────────────────────
def strip_save_nodes(api, map_data):
"""Remove SaveImage nodes from the API dict (not needed for in-process execution)."""
save_ids = set(map_data.pop("_save_nodes", []))
for nid in save_ids:
api.pop(nid, None)
# Also remove any references to these nodes from other nodes' inputs
for node in api.values():
node["inputs"] = {
k: v for k, v in node["inputs"].items()
if not (isinstance(v, list) and len(v) == 2 and str(v[0]) in save_ids)
}
# ── Main ─────────────────────────────────────────────────────────────────────
FAMILY_HINTS = {
"sdxl": "sdxl",
"flux_1": "flux1",
"flux_2": "flux2",
"z_image": "zimage",
"wan_image": "wan_image",
"wan_video_t2v": "wan_video_t2v",
"wan_video_i2v": "wan_video_i2v",
"qwen_image": "qwen_image",
}
def convert_file(src_path, dst_api_path, dst_map_path, family_hint):
with open(src_path, "r", encoding="utf-8") as f:
ui_data = json.load(f)
api = ui_to_api(ui_data)
map_data = build_map(api, family_hint)
strip_save_nodes(api, map_data)
with open(dst_api_path, "w", encoding="utf-8") as f:
json.dump(api, f, indent=2)
with open(dst_map_path, "w", encoding="utf-8") as f:
json.dump(map_data, f, indent=2)
print(f" {os.path.basename(src_path)} -> {os.path.basename(dst_api_path)} (map: {os.path.basename(dst_map_path)})")
return api, map_data
def main():
print(f"Source: {SRC_DIR}")
print(f"Destination: {DST_DIR}")
print()
for fname in sorted(os.listdir(SRC_DIR)):
if not fname.endswith(".json"):
continue
stem = fname[:-5] # strip .json
if stem in FAMILY_HINTS:
hint = FAMILY_HINTS[stem]
else:
hint = stem
src_path = os.path.join(SRC_DIR, fname)
dst_api_path = os.path.join(DST_DIR, f"{stem}_api.json")
dst_map_path = os.path.join(DST_DIR, f"{stem}_map.json")
try:
api, map_data = convert_file(src_path, dst_api_path, dst_map_path, hint)
# Print key mappings for review
for k, v in sorted(map_data.items()):
print(f" {k}: {v}")
print()
except Exception as e:
print(f" ERROR converting {fname}: {e}")
import traceback
traceback.print_exc()
print("Done.")
if __name__ == "__main__":
main()
+171
View File
@@ -0,0 +1,171 @@
"""
Shared LoRA resolution utilities for ComfyUI-Prompt-Manager.
Provides fuzzy matching logic for finding LoRA files on disk, handling
renamed LoRAs, WAN-related tokens, and partial name matches.
Used by: PromptManagerAdvanced, PromptExtractor, RecipeBuilder, RecipeRenderer.
"""
import os
import re
import folder_paths
# Known LoRA file extensions
LORA_EXTENSIONS = ['.safetensors', '.ckpt', '.pt', '.bin', '.pth']
# Tokens to remove for fuzzy matching (case-insensitive)
# Order matters: remove longer tokens first to avoid partial matches
WAN_TOKENS = ['wan_2_2', 'wan22', 'wan2.2', '20epoc', 'a14b', '14b', 'i2v', 't2v']
def get_available_loras():
"""Get all available LoRAs from ComfyUI's folder system."""
return folder_paths.get_filename_list("loras")
def normalize_path_separators(path):
"""Normalize path separators based on OS - for basename extraction only."""
if os.name == 'nt': # Windows
return path.replace('/', '\\')
else: # Linux/Mac
return path.replace('\\', '/')
def strip_lora_extension(name):
"""Remove only known LoRA file extensions, not arbitrary dots in names."""
name_lower = name.lower()
for ext in LORA_EXTENSIONS:
if name_lower.endswith(ext):
return name[:-len(ext)]
return name
def _normalize_name_for_fuzzy(name):
"""
Remove WAN tokens from name, treating underscores and hyphens as separators.
Also removes content in parentheses (e.g., "MyLora (1)" becomes "MyLora").
Returns list of remaining non-empty parts in lowercase.
"""
name_lower = name.lower()
# Remove anything in parentheses (e.g., " (1)", "(copy)", etc.)
name_lower = re.sub(r'\s*\([^)]*\)', '', name_lower)
# Replace each token with a placeholder to preserve boundaries
for token in WAN_TOKENS:
# Use word boundary-aware replacement with _ or - as delimiter
pattern = rf'(?:^|[_-]){re.escape(token)}(?:[_-]|$)'
name_lower = re.sub(pattern, '_', name_lower)
# Split by underscore or hyphen and filter out empty strings
parts = [p for p in re.split(r'[_-]', name_lower) if p]
return parts
def fuzzy_match_lora(lora_name, lora_files):
"""
Attempt to find a matching LoRA using fuzzy matching.
Handles renamed LoRAs by removing common WAN-related tokens.
Example: "DR34LAY_HIGH_V2" can match "DR34LAY_I2V_14B_HIGH_V2"
Returns (matched_file, True) if available, (None, False) otherwise.
"""
# Normalize the search name
search_parts = _normalize_name_for_fuzzy(strip_lora_extension(lora_name))
search_set = set(search_parts)
# If search_set is empty after normalization, we can't do fuzzy matching
if not search_set:
return None, False
candidates = []
for lora_file in lora_files:
file_name_no_ext = strip_lora_extension(os.path.basename(lora_file))
file_parts = _normalize_name_for_fuzzy(file_name_no_ext)
file_set = set(file_parts)
# Check if all search parts are present in the file parts
if search_set.issubset(file_set):
# Calculate how well this matches (prefer closer matches)
extra_parts = len(file_set - search_set)
candidates.append((lora_file, file_name_no_ext, extra_parts))
if not candidates:
return None, False
# If only one match, return it
if len(candidates) == 1:
return candidates[0][0], True
# Multiple matches - prefer ones that match i2v/t2v from original if present
lora_name_lower = lora_name.lower()
has_i2v = 'i2v' in lora_name_lower
has_t2v = 't2v' in lora_name_lower
if has_i2v:
i2v_matches = [c for c in candidates if 'i2v' in c[1].lower()]
if i2v_matches:
candidates = i2v_matches
elif has_t2v:
t2v_matches = [c for c in candidates if 't2v' in c[1].lower()]
if t2v_matches:
candidates = t2v_matches
# Return the match with fewest extra parts (closest match)
candidates.sort(key=lambda x: x[2])
return candidates[0][0], True
def get_lora_relative_path(lora_name):
"""
Get the relative path for a LoRA that ComfyUI expects for loading.
Returns (relative_path, available) tuple.
Supports fuzzy matching for renamed LoRAs.
"""
lora_files = get_available_loras()
lora_name_lower = lora_name.lower()
# Try exact match first
for lora_file in lora_files:
file_name_no_ext = strip_lora_extension(os.path.basename(lora_file))
if file_name_no_ext.lower() == lora_name_lower:
return lora_file, True
# Try fuzzy match for renamed LoRAs
fuzzy_match, available = fuzzy_match_lora(lora_name, lora_files)
if available:
return fuzzy_match, True
# Not available
return lora_name, False
def resolve_lora_path(lora_name):
"""
Resolve a LoRA name to its full path using ComfyUI's folder system.
Uses exact matching first, then fuzzy matching with WAN token handling.
Returns (full_path_or_name, available) tuple.
"""
lora_files = get_available_loras()
# Try exact match first (with extension, as-is from workflow)
for lora_file in lora_files:
if lora_file == lora_name:
return folder_paths.get_full_path("loras", lora_file), True
# Try matching by name without extension
lora_name_lower = lora_name.lower()
for lora_file in lora_files:
file_name_no_ext = strip_lora_extension(os.path.basename(lora_file))
if file_name_no_ext.lower() == lora_name_lower:
return folder_paths.get_full_path("loras", lora_file), True
# Fuzzy match for renamed LoRAs
fuzzy_match, available = fuzzy_match_lora(lora_name, lora_files)
if available:
return folder_paths.get_full_path("loras", fuzzy_match), True
return None, False
+152 -56
View File
@@ -17,33 +17,32 @@ _preferences_cache = {
"custom_llama_path": "",
"custom_llama_model_path": "",
"close_llama_on_exit": True,
"custom_llama_port": 8080
"custom_llama_port": 8080,
"llm_backend": "llama.cpp", # "llama.cpp" or "ollama"
"ollama_url": "http://127.0.0.1:11434",
"ollama_keep_alive": "5m", # How long Ollama keeps model loaded after request
}
# Predefined models - use real filenames as keys
# Qwen3.5 models are unified vision+text — every model supports vision via its mmproj.
# "mmproj" is the LOCAL filename we store on disk.
# "mmproj_repo_filename" is the filename in the HuggingFace repo (may differ).
QWEN_MODELS = {
"Qwen3-4B-Q8_0.gguf": {
"repo": "Qwen/Qwen3-4B-GGUF"
"Qwen3.5-9B-UD-Q4_K_XL.gguf": {
"repo": "unsloth/Qwen3.5-9B-GGUF",
"mmproj": "mmproj-Qwen3.5-9B-F16.gguf",
"mmproj_repo_filename": "mmproj-F16.gguf"
},
"Qwen3-8B-Q8_0.gguf": {
"repo": "Qwen/Qwen3-8B-GGUF"
"Qwen3.5-9B-Q8_0.gguf": {
"repo": "unsloth/Qwen3.5-9B-GGUF",
"mmproj": "mmproj-Qwen3.5-9B-F16.gguf",
"mmproj_repo_filename": "mmproj-F16.gguf"
},
"Qwen3VL-4B-Instruct-Q8_0.gguf": {
"repo": "Qwen/Qwen3-VL-4B-Instruct-GGUF",
"mmproj": "mmproj-Qwen3VL-4B-Instruct-Q8_0.gguf"
"Qwen3.5-9B-UD-Q8_K_XL.gguf": {
"repo": "unsloth/Qwen3.5-9B-GGUF",
"mmproj": "mmproj-Qwen3.5-9B-F16.gguf",
"mmproj_repo_filename": "mmproj-F16.gguf"
},
"Qwen3VL-8B-Instruct-Q8_0.gguf": {
"repo": "Qwen/Qwen3-VL-8B-Instruct-GGUF",
"mmproj": "mmproj-Qwen3VL-8B-Instruct-Q8_0.gguf"
},
"Qwen3VL-4B-Thinking-Q8_0.gguf": {
"repo": "Qwen/Qwen3-VL-4B-Thinking-GGUF",
"mmproj": "mmproj-Qwen3VL-4B-Thinking-Q8_0.gguf"
},
"Qwen3VL-8B-Thinking-Q8_0.gguf": {
"repo": "Qwen/Qwen3-VL-8B-Thinking-GGUF",
"mmproj": "mmproj-Qwen3VL-8B-Thinking-Q8_0.gguf"
}
}
@server.PromptServer.instance.routes.get("/prompt-manager/load-preferences")
@@ -65,7 +64,10 @@ async def save_preference(request):
"custom_llama_path",
"custom_llama_model_path",
"close_llama_on_exit",
"custom_llama_port"]:
"custom_llama_port",
"llm_backend",
"ollama_url",
"ollama_keep_alive"]:
return server.web.json_response({"success": False, "error": "Invalid preference key"})
# Update in-memory cache
@@ -76,6 +78,18 @@ async def save_preference(request):
print(f"[Model Manager] Error saving preference: {e}")
return server.web.json_response({"success": False, "error": str(e)}, status=500)
@server.PromptServer.instance.routes.get("/prompt-manager/ollama-models")
async def list_ollama_models(request):
"""API endpoint to discover available Ollama models."""
try:
from .ollama_wrapper import discover_ollama_models
models, status = discover_ollama_models(_preferences_cache)
return server.web.json_response({"models": models, "status": status})
except Exception as e:
return server.web.json_response({"models": [], "status": f"Error: {e}"}, status=500)
def get_models_directory():
"""Get the path to the primary models directory (ComfyUI/models/gguf) for downloads"""
# Register both gguf and LLM folders
@@ -176,41 +190,117 @@ def get_model_path(model_name):
models_dir = get_models_directory()
return os.path.join(models_dir, model_name)
# Quantization-related filename parts — stripped when matching models to mmproj files
_QUANT_PARTS = frozenset({
"Q2", "Q3", "Q4", "Q5", "Q6", "Q8",
"K", "M", "S", "L", "XS", "XL", "XXS", "XXL",
"IQ1", "IQ2", "IQ3", "IQ4", "NL",
"BF16", "F16", "F32",
"0", "1", "UD",
})
def _get_model_keywords(name):
"""Extract normalised keyword set from a model filename for fuzzy matching.
Splits on hyphens, underscores, dots, and spaces, lowercases everything,
and strips quantisation tags + the literal 'mmproj' token.
Example: 'qwen3.5-9b-nsfw-captioning-v3.Q8_0.gguf'
→ {'qwen3.5', '9b', 'nsfw', 'captioning', 'v3'}
'qwen3.5-9b-nsfw-captioning-v3.mmproj-Q8_0.gguf'
→ {'qwen3.5', '9b', 'nsfw', 'captioning', 'v3'}
"""
base = os.path.splitext(os.path.basename(name))[0]
# First split on hyphens, underscores, spaces (not dots)
raw_parts = [p for p in re.split(r"[-_ ]", base) if p]
# Then split tokens on dots, UNLESS the token is a version string like 'qwen3.5'
parts = []
for token in raw_parts:
if re.match(r'^[a-zA-Z]+\d+\.\d+$', token):
# Version string (e.g. 'qwen3.5') — keep intact
parts.append(token)
elif '.' in token:
# Split other dotted tokens (e.g. 'v3.Q8' → 'v3', 'Q8')
parts.extend(p for p in token.split('.') if p)
else:
parts.append(token)
lc_quant = {q.lower() for q in _QUANT_PARTS}
return {p.lower() for p in parts if p.lower() not in lc_quant and p.lower() != "mmproj" and p.lower() != "gguf"}
def get_mmproj_for_model(model_name):
"""Get the mmproj filename for a given vision model"""
"""Get the mmproj filename for a given model from the predefined registry."""
if model_name in QWEN_MODELS and "mmproj" in QWEN_MODELS[model_name]:
return QWEN_MODELS[model_name]["mmproj"]
return None
def get_mmproj_path(model_name):
"""Get the path to the mmproj file for a vision model, if it exists
Searches for mmproj files that contain all parts of the model name
"""Get the path to the mmproj file for a model, if it exists.
1. Check the explicit QWEN_MODELS mapping first.
2. Fall back to heuristic matching by model identity (strips quant parts).
"""
# Get all parts of the model name (excluding .gguf)
model_parts = [part for part in re.split(r"[-.]", os.path.splitext(os.path.basename(model_name))[0]) if part]
# --- 1. Explicit mapping ---
mmproj_name = get_mmproj_for_model(model_name)
if mmproj_name:
all_dirs = get_all_model_directories()
for d in all_dirs:
p = os.path.join(d, mmproj_name)
if os.path.exists(p):
return p
# Mapped but file not found on disk
return None
# --- 2. Heuristic: keyword-based matching ---
# Split the model name into normalised keywords (no quant tags, no 'mmproj')
# and find the mmproj file that shares the most keywords (minimum 4).
model_keywords = _get_model_keywords(model_name)
if len(model_keywords) < 2:
return None
MIN_KEYWORD_MATCH = min(4, len(model_keywords)) # at least 4, or all if fewer
# Get all local mmproj files
all_dirs = get_all_model_directories()
mmproj_files = []
best_match = None
best_match_count = 0
for models_dir in all_dirs:
if os.path.exists(models_dir):
for f in os.listdir(models_dir):
if 'mmproj' in f.lower() and f.endswith('.gguf'):
mmproj_files.append(f)
if not os.path.exists(models_dir):
continue
for f in os.listdir(models_dir):
if 'mmproj' not in f.lower() or not f.endswith('.gguf'):
continue
mmproj_keywords = _get_model_keywords(f)
common = model_keywords & mmproj_keywords
if len(common) >= MIN_KEYWORD_MATCH and len(common) > best_match_count:
best_match = os.path.join(models_dir, f)
best_match_count = len(common)
# Find mmproj that contains all model parts
for mmproj_file in mmproj_files:
# Let's split the mmproj filename to check for matching bits, we remove extension and mmproj
mmproj_parts = [part for part in re.split(r"[-.]", os.path.splitext(os.path.basename(mmproj_file))[0].replace('mmproj', '')) if part]
if all(part in mmproj_parts for part in model_parts):
return get_model_path(mmproj_file)
return best_match
def has_vision_support(model_name):
"""Check whether a model has vision capabilities.
Returns True if an mmproj file is available (on disk or in the registry).
"""
# Check explicit registry first (even if not yet downloaded)
if get_mmproj_for_model(model_name):
return True
# Check if a matching mmproj file already exists on disk
return get_mmproj_path(model_name) is not None
def download_model(model_name):
"""Download a model from HuggingFace with automatic progress display
For VL models, also downloads the matching mmproj file if needed
"""Download a model from HuggingFace with automatic progress display.
Also downloads the matching mmproj file if one is defined.
The mmproj file in the repo may have a generic name (e.g. 'mmproj-F16.gguf').
We rename it on download to a model-specific name to avoid conflicts when
multiple model sizes are installed side-by-side.
Args:
model_name: Filename of the model (e.g., "Qwen3-4B-Q8_0.gguf")
model_name: Filename of the model (e.g., 'Qwen3.5-9B-Q8_0.gguf')
Returns:
Path to downloaded model or None on error
@@ -224,38 +314,44 @@ def download_model(model_name):
models_dir = get_models_directory()
# Build list of files to download
# Each entry: repo_filename (name in the HF repo), local_filename (name on disk), desc
files_to_download = [
{"filename": model_name, "desc": "Downloading model"}
{"repo_filename": model_name, "local_filename": model_name, "desc": "Downloading model"}
]
# Add mmproj file if this is a VL model
mmproj_name = get_mmproj_for_model(model_name)
if mmproj_name:
# Add mmproj file if this model has one
mmproj_local = get_mmproj_for_model(model_name)
if mmproj_local:
mmproj_repo = model_info.get("mmproj_repo_filename", mmproj_local)
files_to_download.append({
"filename": mmproj_name,
"repo_filename": mmproj_repo,
"local_filename": mmproj_local,
"desc": "Downloading mmproj"
})
# Download each file if it doesn't exist
for file_info in files_to_download:
filename = file_info["filename"]
local_path = os.path.join(models_dir, filename)
repo_filename = file_info["repo_filename"]
local_filename = file_info["local_filename"]
local_path = os.path.join(models_dir, local_filename)
if os.path.exists(local_path):
print(f"[Model Manager] File already exists: {filename}")
print(f"[Model Manager] File already exists: {local_filename}")
continue
# Download the file
try:
print(f"[Model Manager] Downloading {filename} from {repo_id}...")
print(f"[Model Manager] Downloading {repo_filename} from {repo_id}...")
api = HfApi()
repo_info = api.repo_info(repo_id=repo_id, files_metadata=True)
file_metadata = next((f for f in repo_info.siblings if f.rfilename == filename), None)
repo_info_obj = api.repo_info(repo_id=repo_id, files_metadata=True)
file_metadata = next((f for f in repo_info_obj.siblings if f.rfilename == repo_filename), None)
if not file_metadata or file_metadata.size is None:
print(f"[Model Manager] Could not find file size for {filename} in {repo_id}")
print(f"[Model Manager] Could not find file size for {repo_filename} in {repo_id}")
return None
total_size = file_metadata.size
download_url = f"https://huggingface.co/{repo_id}/resolve/main/{filename}"
download_url = f"https://huggingface.co/{repo_id}/resolve/main/{repo_filename}"
if local_filename != repo_filename:
print(f"[Model Manager] Will save as: {local_filename}")
pbar = tqdm(total=total_size, unit="B", unit_scale=True, desc=file_info["desc"])
with requests.get(download_url, stream=True) as r, open(local_path, "wb") as f:
r.raise_for_status()
@@ -264,9 +360,9 @@ def download_model(model_name):
f.write(chunk)
pbar.update(len(chunk))
pbar.close()
print(f"[Model Manager] Successfully downloaded {filename}")
print(f"[Model Manager] Successfully downloaded {local_filename}")
except Exception as e:
print(f"[Model Manager] Error downloading {filename}: {e}")
print(f"[Model Manager] Error downloading {repo_filename}: {e}")
return None
return os.path.join(models_dir, model_name)
+198
View File
@@ -0,0 +1,198 @@
"""
Ollama integration for ComfyUI Prompt Manager.
Provides model discovery, generation, and memory management
via Ollama's native API and OpenAI-compatible endpoint.
"""
import requests
import json
# ============================================================================
# Default endpoints
# ============================================================================
DEFAULT_OLLAMA_URL = "http://127.0.0.1:11434"
def _get_ollama_base(user_config):
"""Resolve Ollama base URL (without /v1 or /api) from config."""
url = str(user_config.get("ollama_url", DEFAULT_OLLAMA_URL)).strip().rstrip("/")
if not url:
url = DEFAULT_OLLAMA_URL
# Strip trailing /v1 or /api paths so we always have the root
for suffix in ("/v1", "/api", "/api/tags", "/api/chat"):
if url.endswith(suffix):
url = url[: -len(suffix)]
break
return url
# ============================================================================
# Model discovery
# ============================================================================
def discover_ollama_models(user_config):
"""Query Ollama for available models.
Returns:
(list_of_model_names, status_message)
"""
base = _get_ollama_base(user_config)
tags_url = f"{base}/api/tags"
timeout = 12
try:
response = requests.get(tags_url, timeout=timeout)
if response.status_code == 200:
payload = response.json()
names = []
if isinstance(payload, dict):
for item in payload.get("models", []):
if isinstance(item, dict):
name = item.get("model") or item.get("name")
if isinstance(name, str) and name.strip():
names.append(name.strip())
if names:
unique = sorted(set(names), key=lambda x: x.lower())
return unique, f"Found {len(unique)} Ollama model(s)."
return [], "Ollama responded but no models were found. Pull one first, e.g. `ollama pull llama3.1`."
return [], f"Ollama returned HTTP {response.status_code}."
except requests.exceptions.ConnectionError:
return [], f"Could not connect to Ollama at {base}. Start `ollama serve` and retry."
except requests.exceptions.Timeout:
return [], f"Timed out querying Ollama at {base}."
except Exception as e:
return [], f"Failed to query Ollama models: {e}"
def is_ollama_available(user_config):
"""Check if Ollama is reachable."""
base = _get_ollama_base(user_config)
try:
resp = requests.get(f"{base}/api/tags", timeout=5)
return resp.status_code == 200
except Exception:
return False
# ============================================================================
# Generation (OpenAI-compatible chat/completions via Ollama)
# ============================================================================
def generate_chat(user_config, model_name, messages, temperature=0.8,
top_k=40, top_p=0.95, min_p=0.05, repeat_penalty=1.0,
seed=None, stream=True, timeout=120,
use_model_defaults=True, enable_thinking=False):
"""Send a chat completion request to Ollama's OpenAI-compatible endpoint.
Args:
user_config: preferences dict with ollama_url, ollama_keep_alive, etc.
model_name: Ollama model tag (e.g. "llama3.1:latest")
messages: list of {role, content} dicts (OpenAI format)
stream: if True, returns a streaming response iterator
timeout: request timeout in seconds
Returns:
If stream=False: (response_text, thinking_text, usage_stats, error_msg)
If stream=True: (response_object, error_msg) — caller handles streaming
"""
base = _get_ollama_base(user_config)
url = f"{base}/v1/chat/completions"
payload = {
"model": model_name,
"messages": messages,
"stream": stream,
}
# Set keep_alive to control how long the model stays loaded after this request
keep_alive = user_config.get("ollama_keep_alive", "5m")
if keep_alive:
payload["keep_alive"] = keep_alive
if stream:
payload["stream_options"] = {"include_usage": True}
if seed is not None:
payload["seed"] = seed
if enable_thinking:
payload["chat_template_kwargs"] = {"enable_thinking": True}
if not use_model_defaults:
payload["temperature"] = temperature
payload["top_k"] = top_k
payload["top_p"] = top_p
payload["min_p"] = min_p
payload["repeat_penalty"] = repeat_penalty
try:
response = requests.post(url, json=payload, timeout=timeout, stream=stream)
if response.status_code != 200:
detail = _extract_error(response)
return (None, f"Ollama request failed ({response.status_code}): {detail}")
if stream:
return (response, None)
else:
result = response.json()
text = result["choices"][0]["message"]["content"]
usage = result.get("usage")
return (text.strip(), "", usage, None)
except requests.exceptions.ConnectionError:
return (None, "Could not connect to Ollama. Start 'ollama serve' and retry.")
except requests.exceptions.Timeout:
return (None, f"Ollama request timed out ({timeout}s). Try a shorter prompt or smaller model.")
except (KeyError, IndexError):
return (None, "Unexpected response format from Ollama.")
except Exception as e:
return (None, f"Ollama generation failed: {e}")
# ============================================================================
# Memory management — unload model from Ollama VRAM
# ============================================================================
def unload_model(user_config, model_name):
"""Tell Ollama to unload a model from memory (free VRAM).
Uses the /api/generate endpoint with keep_alive=0 to immediately
evict the model from GPU memory.
"""
base = _get_ollama_base(user_config)
url = f"{base}/api/generate"
try:
response = requests.post(url, json={
"model": model_name,
"keep_alive": 0,
}, timeout=15)
if response.status_code == 200:
return True, f"Model '{model_name}' unloaded from Ollama memory."
return False, f"Ollama returned HTTP {response.status_code} while unloading model."
except requests.exceptions.ConnectionError:
return False, "Could not connect to Ollama to unload model."
except Exception as e:
return False, f"Failed to unload model from Ollama: {e}"
# ============================================================================
# Helpers
# ============================================================================
def _extract_error(response):
"""Extract error message from an Ollama error response."""
try:
payload = response.json()
except ValueError:
text = (response.text or "").strip()
return text[:300] if text else f"HTTP {response.status_code}"
if isinstance(payload, dict):
err = payload.get("error")
if isinstance(err, str) and err.strip():
return err.strip()
msg = payload.get("message")
if isinstance(msg, str) and msg.strip():
return msg.strip()
return f"HTTP {response.status_code}"
+385
View File
@@ -0,0 +1,385 @@
"""
Utility functions for RECIPE_DATA dicts.
Runtime object keys (MODEL_A, MODEL_B, CLIP, VAE, POSITIVE, NEGATIVE, etc.)
store non-serializable ComfyUI objects and must be stripped before JSON
serialization.
"""
import json
import math
# Keys that hold runtime (non-JSON-serializable) objects/conditioning payloads.
# These should never be persisted in saved prompt/workflow metadata.
RUNTIME_OBJECT_KEYS = frozenset({
"MODEL",
"MODEL_A",
"MODEL_B",
"CLIP",
"VAE",
"LATENT",
"IMAGE",
"MASK",
"EXTRA_1",
"EXTRA_2",
"POSITIVE",
"NEGATIVE",
})
_MODEL_KEYS = ("model_a", "model_b", "model_c", "model_d")
_LEGACY_TOP_LEVEL_KEYS = {
"family",
"model_a",
"model_b",
"positive_prompt",
"negative_prompt",
"loras_a",
"loras_b",
"vae",
"clip",
"clip_type",
"loader_type",
"sampler",
"resolution",
}
def _as_clip_list(raw_clip):
if isinstance(raw_clip, list):
return list(raw_clip)
if isinstance(raw_clip, tuple):
return list(raw_clip)
if raw_clip:
return [raw_clip]
return []
def _has_meaningful_legacy_slot(recipe_data, slot_key, sampler):
if slot_key not in ("model_a", "model_b"):
return False
suffix = "a" if slot_key == "model_a" else "b"
model_name = str(recipe_data.get(slot_key, "") or "").strip()
loras_key = f"loras_{suffix}"
loras = recipe_data.get(loras_key, []) if isinstance(recipe_data.get(loras_key), list) else []
has_loras = len(loras) > 0
steps_key = f"steps_{suffix}"
seed_key = f"seed_{suffix}"
has_slot_sampler = isinstance(sampler.get(steps_key), (int, float)) or isinstance(sampler.get(seed_key), (int, float))
return bool(model_name or has_loras or has_slot_sampler)
def _legacy_to_v2_recipe_data(recipe_data, source):
sampler = recipe_data.get("sampler", {}) if isinstance(recipe_data.get("sampler"), dict) else {}
resolution = recipe_data.get("resolution", {}) if isinstance(recipe_data.get("resolution"), dict) else {}
def _build_model_block(slot_key):
is_b = slot_key == "model_b"
suffix = "b" if is_b else "a"
loras_key = f"loras_{suffix}"
steps_key = f"steps_{suffix}"
seed_key = f"seed_{suffix}"
steps = sampler.get(steps_key)
if steps is None:
steps = sampler.get("steps_a", sampler.get("steps", 20))
seed = sampler.get(seed_key)
if seed is None:
seed = sampler.get("seed_a", sampler.get("seed", 0))
return {
"positive_prompt": str(recipe_data.get("positive_prompt", "") or ""),
"negative_prompt": str(recipe_data.get("negative_prompt", "") or ""),
"family": str(recipe_data.get("family", "") or ""),
"model": str(recipe_data.get(slot_key, "") or ""),
"loras": list(recipe_data.get(loras_key, [])) if isinstance(recipe_data.get(loras_key), list) else [],
"clip_type": str(recipe_data.get("clip_type", "") or ""),
"loader_type": str(recipe_data.get("loader_type", "") or ""),
"vae": str(recipe_data.get("vae", "") or ""),
"clip": _as_clip_list(recipe_data.get("clip", [])),
"sampler": {
"steps": int(steps if steps is not None else 20),
"cfg": float(sampler.get("cfg", 5.0)),
"denoise": float(sampler.get("denoise", 1.0)),
"seed": int(seed if seed is not None else 0),
"sampler_name": str(sampler.get("sampler_name", "euler") or "euler"),
"scheduler": str(sampler.get("scheduler", "simple") or "simple"),
},
"resolution": {
"width": int(resolution.get("width", 768)),
"height": int(resolution.get("height", 1280)),
"batch_size": int(resolution.get("batch_size", 1)),
"length": resolution.get("length", None),
},
}
out = {
"_source": str(recipe_data.get("_source") or source),
"version": 2,
"models": {},
}
# Preserve non-legacy metadata/runtime keys at root.
for key, val in recipe_data.items():
if key in {"_source", "version", "models"}:
continue
if key in _LEGACY_TOP_LEVEL_KEYS:
continue
out[key] = val
if _has_meaningful_legacy_slot(recipe_data, "model_a", sampler):
out["models"]["model_a"] = _build_model_block("model_a")
if _has_meaningful_legacy_slot(recipe_data, "model_b", sampler):
out["models"]["model_b"] = _build_model_block("model_b")
return out
def get_v2_model_block(recipe_data, model_key):
"""Return a v2 model block dict for model_key, or None if unavailable."""
if not isinstance(recipe_data, dict):
return None
if int(recipe_data.get("version", 0) or 0) < 2:
return None
models = recipe_data.get("models", {}) if isinstance(recipe_data.get("models"), dict) else {}
block = models.get(model_key)
return block if isinstance(block, dict) else None
def ensure_v2_recipe_data(recipe_data, source="RecipeData"):
"""Normalize recipe_data to strict v2 shape.
v2 contract is authoritative. Legacy top-level recipe fields are converted
into v2 model blocks.
"""
if not isinstance(recipe_data, dict):
return {
"_source": source,
"version": 2,
"models": {},
}
is_v2 = int(recipe_data.get("version", 0) or 0) >= 2 and isinstance(recipe_data.get("models"), dict)
if not is_v2:
return _legacy_to_v2_recipe_data(recipe_data, source)
out = {
"_source": str(recipe_data.get("_source") or source),
"version": 2,
"models": {},
}
# Preserve non-legacy root keys as passthrough metadata/runtime payload.
for key, val in recipe_data.items():
if key in {"_source", "version", "models"}:
continue
if key in _LEGACY_TOP_LEVEL_KEYS:
continue
out[key] = val
if is_v2:
for mk in _MODEL_KEYS:
block = recipe_data.get("models", {}).get(mk)
if isinstance(block, dict):
out["models"][mk] = dict(block)
return out
def _coerce_prompt_loras(raw_loras):
"""Convert prompt-style LoRA entries into canonical workflow LoRA dicts."""
if not isinstance(raw_loras, list):
return []
out = []
for lora in raw_loras:
if not isinstance(lora, dict):
continue
name = str(lora.get("name", "") or "").strip()
if not name:
continue
model_strength = lora.get("model_strength", lora.get("strength", 1.0))
clip_strength = lora.get("clip_strength", lora.get("strength", model_strength))
out.append({
"name": name,
"path": lora.get("path", name),
"model_strength": model_strength,
"clip_strength": clip_strength,
"active": lora.get("active", True),
"available": lora.get("available", True),
})
return out
def _blank_v2_model_block():
"""Return a blank v2 model block matching RecipeBuilder defaults."""
return {
"positive_prompt": "",
"negative_prompt": "",
"family": "",
"model": "",
"loras": [],
"clip_type": "",
"loader_type": "",
"vae": "",
"clip": [],
"sampler": {
"steps": 20,
"cfg": 5.0,
"denoise": 1.0,
"seed": 0,
"sampler_name": "dpmpp_2m_sde",
"scheduler": "karras",
},
"resolution": {
"width": 768,
"height": 1280,
"batch_size": 1,
"length": None,
},
}
def _merge_model_block_with_template(existing_block):
"""Merge an existing model block onto the blank v2 template."""
merged = _blank_v2_model_block()
if not isinstance(existing_block, dict):
return merged
for key, value in existing_block.items():
if key == "sampler" and isinstance(value, dict):
sampler = dict(merged["sampler"])
sampler.update(value)
merged["sampler"] = sampler
continue
if key == "resolution" and isinstance(value, dict):
resolution = dict(merged["resolution"])
resolution.update(value)
merged["resolution"] = resolution
continue
merged[key] = value
return merged
def build_v2_recipe_data_from_prompt(
prompt_text="",
negative_prompt="",
loras_a=None,
loras_b=None,
source="RecipeData",
base_recipe_data=None,
):
"""Build/update v2 recipe_data from prompt text and LoRA stacks.
- Preserves existing non-legacy root metadata from base_recipe_data.
- Preserves existing model names when available.
- Writes prompt + negative_prompt + loras into model_a/model_b.
"""
out = ensure_v2_recipe_data(
dict(base_recipe_data) if isinstance(base_recipe_data, dict) else {},
source=source,
)
models = out.get("models", {})
if not isinstance(models, dict):
models = {}
out["models"] = models
model_a = _merge_model_block_with_template(models.get("model_a"))
model_b = _merge_model_block_with_template(models.get("model_b"))
prompt_text = str(prompt_text or "")
negative_prompt = str(negative_prompt or "")
model_a["positive_prompt"] = prompt_text
model_b["positive_prompt"] = prompt_text
model_a["negative_prompt"] = negative_prompt
model_b["negative_prompt"] = negative_prompt
model_a["loras"] = _coerce_prompt_loras(loras_a)
model_b["loras"] = _coerce_prompt_loras(loras_b)
models["model_a"] = model_a
models["model_b"] = model_b
out["_source"] = source
return ensure_v2_recipe_data(out, source=source)
def _strip_runtime_keys_deep(value):
"""Recursively strip runtime-only keys from dict/list containers."""
if isinstance(value, dict):
return {
k: _strip_runtime_keys_deep(v)
for k, v in value.items()
if k not in RUNTIME_OBJECT_KEYS
}
if isinstance(value, list):
return [_strip_runtime_keys_deep(v) for v in value]
if isinstance(value, tuple):
return [_strip_runtime_keys_deep(v) for v in value]
if isinstance(value, set):
return [_strip_runtime_keys_deep(v) for v in value]
return value
def strip_runtime_objects(wf):
"""Return a deep copy of wf with all runtime object keys removed.
Use before JSON serialization (saving prompts, send_sync to JS, etc.).
"""
if not isinstance(wf, dict):
return wf
return _strip_runtime_keys_deep(wf)
def _json_default(value):
"""Best-effort fallback for objects that JSON cannot encode directly."""
if isinstance(value, (set, tuple)):
return list(value)
if isinstance(value, bytes):
return value.decode("utf-8", errors="replace")
return str(value)
def to_json_safe_workflow_data(wf):
"""Return a deep JSON-safe copy of workflow data with runtime keys removed.
This is stricter than strip_runtime_objects(): it also sanitizes nested
containers and unknown object types so metadata embedding cannot fail
during Save Image serialization.
"""
if not isinstance(wf, dict):
return {}
stripped = strip_runtime_objects(wf)
# Normalize NaN/Inf because Python's json allows them by default but strict
# JSON consumers may reject them.
def _normalize_numbers(value):
if isinstance(value, float) and (math.isnan(value) or math.isinf(value)):
return None
if isinstance(value, dict):
return {k: _normalize_numbers(v) for k, v in value.items()}
if isinstance(value, list):
return [_normalize_numbers(v) for v in value]
if isinstance(value, tuple):
return [_normalize_numbers(v) for v in value]
if isinstance(value, set):
return [_normalize_numbers(v) for v in value]
return value
normalized = _normalize_numbers(stripped)
try:
return json.loads(json.dumps(normalized, default=_json_default, allow_nan=False))
except Exception:
# Last-resort safety: stringify opaque values while preserving structure.
return json.loads(json.dumps(str(normalized)))
File diff suppressed because it is too large Load Diff
+502
View File
@@ -0,0 +1,502 @@
"""
Model family definitions and compatibility helpers for ComfyUI Prompt Manager.
Shared by workflow_builder, workflow_renderer, and workflow_extraction_utils.
Each family dict specifies:
"label" — human-readable name shown in UI dropdowns
"folders" — lowercase path prefixes (matched against relative model path)
"names" — lowercase substrings matched against filename only
"vae" — VAE filename substrings compatible with this family
"vae_exact" — VAE exact basenames (full filename match, e.g. "ae.safetensors")
"clip" — CLIP/text-encoder filename substrings compatible with this family
"clip_exact" — CLIP exact basenames (full filename match)
"clip_exclude" — substrings that DISQUALIFY a CLIP match (applied after include patterns)
"clip_type" — CLIPType key passed to comfy.sd.load_clip (e.g. "flux", "wan")
"clip_slots" — number of distinct CLIP files needed (default 1; flux1/sdxl need 2)
"sampler" — internal sampling strategy key (see SAMPLER_STRATEGIES below)
Matching rules:
VAE: vae_exact checked first (full basename), then vae substring patterns.
CLIP: clip_exclude applied first — any match disqualifies the file.
Then clip_exact checked (full basename), then clip substring patterns.
Folder prefixes checked before name patterns. First match wins for family detection.
To add a new family: add a dict entry and handle its "sampler" key in workflow_builder.
"""
import os
import folder_paths
# ─── Family definitions ──────────────────────────────────────────────────────
MODEL_FAMILIES = {
# ── Ernie Image (Flux2 template/runtime) ─────────────────────────────────
"ernie": {
"label": "Ernie",
# Name-only detection to avoid accidental family hits from unrelated
# checkpoint folder names.
"folders": [],
"names": ["ernie-image-turbo", "ernie-image", "ernie"],
# Ernie should be treated as diffusion/UNet family, not checkpoints.
"model_folders": ["diffusion_models", "unet", "unet_gguf"],
"vae": ["flux2-vae", "flux2_vae"],
"clip_exact": ["ministral-3-3b.safetensors"],
"clip": ["ministral"],
"clip_exclude": ["prompt-enhancer", "enhancer", "mistral_3_small_flux2_fp8"],
"clip_type": "flux2",
"sampler": "flux2",
},
# ── Flux 2 / Klein ───────────────────────────────────────────────────────
"flux2": {
"label": "Flux 2",
"folders": ["klein/", "flux2/"],
"names": ["flux2", "flux-2", "flux_2", "klein", "flux.2"],
# Flux2/Klein uses its own VAE — NOT ae.safetensors
"vae": ["flux2-vae", "flux2_vae"],
# Klein uses Qwen text encoders (NOT T5/CLIP-L):
# 4B model → qwen_3_4b.safetensors
# 9B model → qwen_3_8b_fp8mixed.safetensors
# CLIPLoader type must be "flux2" so CLIPType.FLUX2 is used.
"clip": ["qwen_3_8b"],
"clip_exclude": ["qwen_2.5", "qwen_2_5", "qwen_3_4b", "t5xxl", "umt5", "clip_l", "clip_g", "gemma"],
"clip_type": "flux2",
"sampler": "flux2",
},
# ── Flux 1 (Dev + Schnell merged) ────────────────────────────────────────
"flux1": {
"label": "Flux 1",
"folders": ["flux/", "flux1/"],
"names": ["flux-dev", "flux_dev", "fluxdev", "flux1-dev", "flux1_dev",
"flux-schnell", "flux_schnell", "fluxschnell", "flux1-schnell",
"flux1_schnell", "flux1-", "flux1_", "flux.1"],
# ae.safetensors is the canonical Flux1 VAE — exact match required to
# avoid catching "mae.safetensors" or other short-named files.
"vae": [],
"vae_exact": ["ae.safetensors"],
# Flux1 uses T5-XXL + CLIP-L dual encoders.
# umt5_xxl also contains "t5xxl" as substring — exclude it explicitly.
"clip": ["t5xxl"],
"clip_exclude": ["umt5", "clip_l", "clip_g", "qwen", "gemma", "awq-int"],
"clip_type": "flux",
"clip_slots": 2,
"sampler": "flux",
},
# ── Z-Image (Base + Turbo merged) ────────────────────────────────────────
"zimage": {
"label": "Z-Image",
"folders": ["zib/", "zit/", "zimage/"],
"names": ["z_image", "z-image", "zimage", "blitz"],
# Z-Image shares ae.safetensors with Flux1 for its base VAE.
"vae": ["zimageturbo_vae"],
"vae_exact": ["ae.safetensors"],
# Z-Image uses Qwen 3 4B as its text encoder (not the larger 8B,
# not T5, not CLIP-L). The 4B file is typically named
# "qwen-4b-zimage.safetensors" or "qwen_3_4b.safetensors".
"clip": ["qwen-4b-zimage", "qwen_3_4b"],
"clip_exclude": ["qwen_3_8b", "qwen_2.5", "qwen_2_5", "t5xxl", "umt5",
"clip_l", "clip_g", "gemma"],
"clip_type": "lumina2",
"sampler": "zimage",
},
# ── WAN 2.x Video — Image-to-Video (dual KSampler + i2v latent) ──────────
"wan_video_i2v": {
"label": "WAN Video (i2v)",
"folders": ["wan2_2/i2v/", "wan2_1/i2v/"],
"names": ["wan2.2_i2v", "wan2.1_i2v", "wan_i2v", "i2v"],
"vae": ["wan_2.1_vae", "wan2.1_vae", "wan2.1-vae", "wan_2.1-vae"],
"clip": ["umt5_xxl", "umt5-xxl"],
"clip_exclude": ["t5xxl", "clip_l", "clip_g", "qwen", "gemma"],
"clip_type": "wan",
"sampler": "wan_video",
},
# ── WAN 2.x Video — Text-to-Video (dual KSampler) ────────────────────────
# DETECTION PRIORITY: must appear before wan_image — they share the same
# folders/names, so first-match wins. Auto-detected T2V models land here;
# user selects wan_image explicitly from the family dropdown.
"wan_video_t2v": {
"label": "WAN Video (t2v)",
"folders": ["wan2_2/", "wan2_1/", "wan/"],
"names": ["wan2.2", "wan2.1", "wan2_2", "wan2_1", "wanvideo", "wan_t2v",
"wan2.2_t2v", "wan2.1_t2v"],
"vae": ["wan_2.1_vae", "wan2.1_vae", "wan2.1-vae", "wan_2.1-vae"],
"clip": ["umt5_xxl", "umt5-xxl"],
"clip_exclude": ["t5xxl", "clip_l", "clip_g", "qwen", "gemma"],
"clip_type": "wan",
"sampler": "wan_video",
},
# ── WAN 2.x Image (single KSampler, text-to-image) ──────────────────────
# Same model files as WAN Video T2V — identical folders/names/vae/clip.
# Must appear AFTER wan_video_t2v so auto-detection resolves T2V models
# to wan_video_t2v. User picks this family explicitly for still images.
# Sampler stays wan_image (single KSampler, no dual Steps rows).
"wan_image": {
"label": "WAN Image",
"folders": ["wan2_2/", "wan2_1/", "wan/"],
"names": ["wan2.2", "wan2.1", "wan2_2", "wan2_1", "wanvideo", "wan_t2v",
"wan2.2_t2v", "wan2.1_t2v"],
"vae": ["wan_2.1_vae", "wan2.1_vae", "wan2.1-vae", "wan_2.1-vae"],
# WAN uses UMT5-XXL exclusively — NOT t5xxl, NOT clip_l/g.
"clip": ["umt5_xxl", "umt5-xxl"],
"clip_exclude": ["t5xxl", "clip_l", "clip_g", "qwen", "gemma"],
"clip_type": "wan",
"sampler": "wan_image",
},
# ── LTX-Video ────────────────────────────────────────────────────────────
"ltxv": {
"label": "LTX-Video",
"folders": ["ltx/"],
"names": ["ltxv", "ltx-video", "ltx-2", "ltx2"],
# LTX has its own VAE — NOT ae.safetensors, NOT SDXL/SD VAE.
# taeltx* are TAE-based approximation VAEs for LTX.
"vae": ["ltx23_video_vae", "ltxv_vae", "ltx_vae", "taeltx"],
# LTX-Video uses T5-XXL only (same encoder family as Flux1 but
# NOT the dual CLIP-L+T5 combo — single T5 only).
# umt5_xxl contains "t5xxl" → must exclude it.
"clip": ["t5xxl"],
"clip_exclude": ["umt5", "clip_l", "clip_g", "qwen", "gemma"],
"clip_type": "sd3",
"sampler": "flux",
},
# ── SDXL (+ Pony, Illustrious, Turbo merged) ────────────────────────────
"sdxl": {
"label": "SDXL",
"folders": ["illustrious/", "pony/", "sdxl/"],
"names": ["sdxl", "illustrious", "noob", "pony"],
# SDXL uses its own finely-tuned VAE (sdxl_vae / sdxl-vae) or the
# widely-used vae-ft-mse-840000 variant.
"vae": ["sdxl_vae", "sdxl-vae", "vae-ft-mse"],
# SDXL uses dual text encoders: CLIP-L + CLIP-G.
"clip": ["clip_l", "clip_g"],
"clip_exclude": ["t5xxl", "umt5", "qwen", "gemma"],
"sampler": "standard",
"checkpoint": True,
},
# ── Qwen Image ───────────────────────────────────────────────────────────
"qwen_image": {
"label": "Qwen Image",
"folders": ["qwen/"],
"names": ["qwen_image"],
"vae": ["qwen_image_vae"],
"clip": ["qwen_2.5_vl", "qwen_2_5_vl"],
"clip_exclude": ["qwen_3", "t5xxl", "umt5", "clip_l", "clip_g", "gemma"],
"clip_type": "qwen_image",
"sampler": "standard",
},
}
# Compatibility groups — checkpoint families that can share each other's models.
# VAE/CLIP are NOT grouped (they differ per family) — model weights only.
MODEL_COMPAT_GROUPS = [
{"ernie"},
{"sdxl"}, # SDXL-arch — all merged into one now
{"flux1"}, # Flux1 variants — all merged into one now
{"zimage"}, # Z-Image — all merged
{"flux2"}, # Flux2 — all merged
{"wan_image", "wan_video_t2v"}, # WAN Image shares T2V model files
]
# Sampling strategy keys (referenced by workflow_builder.py / workflow_renderer.py)
# Each key maps to a specific sampling code path.
SAMPLER_STRATEGIES = {
"standard": "standard", # KSampler — SDXL, Qwen
"flux": "flux", # SamplerCustomAdvanced + BasicGuider (Flux1)
"flux2": "flux2", # SamplerCustomAdvanced + CFGGuider (Klein/Flux2/Ernie)
"zimage": "zimage", # ModelSamplingAuraFlow + standard KSampler (Z-Image)
"wan_image": "wan_image", # Single KSampler — WAN Image
"wan_video": "wan_video", # Dual KSamplerAdvanced high/low (WAN Video i2v + t2v)
}
# Workflow template filenames (in workflows/api/) keyed by family.
# Maps each family key to its _api.json and _map.json stem.
FAMILY_WORKFLOW_STEMS = {
"ernie": "flux_2",
"sdxl": "sdxl",
"flux1": "flux_1",
"flux2": "flux_2",
"zimage": "z_image",
"wan_image": "wan_image",
"wan_video_i2v": "wan_video_i2v",
"wan_video_t2v": "wan_video_t2v",
"ltxv": None, # No template yet
"qwen_image": "qwen_image",
}
# ─── Family lookup ───────────────────────────────────────────────────────────
def get_model_family(model_path):
"""
Return the family key for a model, or None if unknown.
Accepts a relative path like 'Illustrious/Anime/illustrij_v20.safetensors'.
"""
if not model_path:
return None
path_lower = model_path.lower().replace("\\", "/")
name_lower = os.path.basename(path_lower)
for family, spec in MODEL_FAMILIES.items():
for prefix in spec.get("folders", []):
if path_lower.startswith(prefix.lower().replace("\\", "/")):
return family
for pat in spec.get("names", []):
if pat in name_lower:
return family
return None
def get_family_label(family):
"""Return the human-readable label for a family, or the key itself."""
if not family:
return "Unknown"
return MODEL_FAMILIES.get(family, {}).get("label", family)
def get_family_sampler_strategy(family):
"""Return the sampler strategy key for a family (default: 'standard')."""
if not family:
return "standard"
return MODEL_FAMILIES.get(family, {}).get("sampler", "standard")
def get_compatible_families(family):
"""Return the set of all checkpoint-families compatible with the given one."""
if not family:
return set()
result = {family}
for group in MODEL_COMPAT_GROUPS:
if family in group:
result |= group
return result
def get_all_family_labels():
"""Return a dict of {family_key: label} for all known families."""
hidden = {"ltxv"}
return {k: v.get("label", k) for k, v in MODEL_FAMILIES.items() if k not in hidden}
# ─── Model listing ───────────────────────────────────────────────────────────
def _model_keywords(model_name):
"""Extract meaningful keywords from a model filename for fuzzy matching.
Strips extension, path, and GGUF quantization tokens (Q8_0, Q4_K_M, etc.)."""
import re
base = os.path.splitext(os.path.basename(model_name))[0].lower()
# Remove GGUF quant suffixes: Q8_0, Q4_K_M, Q5_K_S, Q6_K, etc.
base = re.sub(r'[-_]?q\d[_\w]*$', '', base, flags=re.IGNORECASE)
# Also strip common precision suffixes: fp8, fp16, bf16, fp32
base = re.sub(r'[-_]?(?:fp8|fp16|bf16|fp32)(?:mixed)?$', '', base, flags=re.IGNORECASE)
# Split on _ and - to get keywords, filter empties
return set(tok for tok in re.split(r'[-_]', base) if tok)
def list_compatible_models(reference_model, family_override=None):
"""
Given a reference model name/path, return a list of compatible
models found on disk, sorted by keyword similarity to the reference.
The best keyword match is first, so callers can use [0] as a fallback.
Parameters
----------
reference_model : str — model path/name to derive family from
family_override : str | None — explicit family key (takes priority)
"""
family = family_override or get_model_family(reference_model)
compat = get_compatible_families(family)
all_models = []
for folder_name in ['checkpoints', 'diffusion_models', 'unet', 'unet_gguf']:
try:
all_models.extend(folder_paths.get_filename_list(folder_name))
except Exception:
continue
# Deduplicate preserving order
seen = set()
unique = []
for m in all_models:
if m not in seen:
seen.add(m)
unique.append(m)
if not compat:
return []
compatible = []
for m in unique:
m_family = get_model_family(m)
if m_family and m_family in compat:
compatible.append(m)
if not compatible:
return []
# Sort by keyword similarity to reference model (best match first)
ref_keywords = _model_keywords(reference_model)
if ref_keywords:
def _match_score(m):
m_keywords = _model_keywords(m)
shared = len(ref_keywords & m_keywords)
# Tie-break: prefer fewer extra keywords (closer match)
extra = len(m_keywords - ref_keywords)
return (-shared, extra, m.lower())
compatible.sort(key=_match_score)
else:
compatible.sort()
return compatible
def list_all_models():
"""Return all models from all known model folder types (deduplicated, sorted)."""
all_models = []
seen = set()
for folder_name in ['checkpoints', 'diffusion_models', 'unet', 'unet_gguf']:
try:
for m in folder_paths.get_filename_list(folder_name):
if m not in seen:
seen.add(m)
all_models.append(m)
except Exception:
continue
return sorted(all_models)
def list_compatible_vaes(family, return_recommended=False):
"""Return sorted list of VAE files compatible with the given family.
If return_recommended=True, returns (list, recommended_str_or_None).
Matching order:
1. vae_exact — full basename match (e.g. "ae.safetensors"), case-insensitive
2. vae — substring match against basename or full relative path
Checkpoint families may fall back to all VAEs when no matches are found.
Non-checkpoint families stay strict (empty list) to avoid cross-family leaks.
"""
def _ret(lst, rec):
return (sorted(lst), rec) if return_recommended else sorted(lst)
if not family:
try:
return _ret(folder_paths.get_filename_list("vae"), None)
except Exception:
return _ret([], None)
spec = MODEL_FAMILIES.get(family, {})
exact_names = [e.lower() for e in spec.get("vae_exact", [])]
patterns = [p.lower() for p in spec.get("vae", [])]
if not exact_names and not patterns:
try:
all_vaes = folder_paths.get_filename_list("vae")
return _ret(all_vaes if spec.get("checkpoint", False) else [], None)
except Exception:
return _ret([], None)
try:
all_vaes = folder_paths.get_filename_list("vae")
except Exception:
return _ret([], None)
matched = []
recommended = None
is_checkpoint = spec.get("checkpoint", False)
for v in all_vaes:
v_lower = v.lower().replace("\\", "/")
v_name = os.path.basename(v_lower)
# 1. Exact basename match (e.g. "ae.safetensors")
if v_name in exact_names:
matched.append(v)
if recommended is None and not is_checkpoint:
recommended = v
continue
# 2. Substring patterns
for pat in patterns:
if pat in v_name or pat in v_lower:
matched.append(v)
if recommended is None and not is_checkpoint:
recommended = v
break
if matched:
return _ret(matched, recommended)
return _ret(all_vaes if is_checkpoint else [], None)
def list_compatible_clips(family, return_recommended=False):
"""Return sorted list of CLIP/text-encoder files compatible with the given family.
If return_recommended=True, returns (list, recommended_str_or_None).
Matching order:
1. clip_exclude — if ANY exclude pattern is found in the basename/path, skip the file
2. clip_exact — full basename match, case-insensitive
3. clip — substring match against basename or full relative path
Checkpoint families may fall back to all CLIPs when no matches are found.
Non-checkpoint families stay strict (empty list) to avoid cross-family leaks.
"""
def _ret(lst, rec):
return (sorted(lst), rec) if return_recommended else sorted(lst)
if not family:
clips = _gather_all_clips()
return _ret(clips, None)
spec = MODEL_FAMILIES.get(family, {})
exclude_pats = [e.lower() for e in spec.get("clip_exclude", [])]
exact_names = [e.lower() for e in spec.get("clip_exact", [])]
patterns = [p.lower() for p in spec.get("clip", [])]
if not exact_names and not patterns:
clips = _gather_all_clips()
return _ret(clips if spec.get("checkpoint", False) else [], None)
all_clips = _gather_all_clips()
matched = []
recommended = None
is_checkpoint = spec.get("checkpoint", False)
for c in all_clips:
c_lower = c.lower().replace("\\", "/")
c_name = os.path.basename(c_lower)
# 1. Exclusion check — disqualify if any exclude pattern is present
if any(ex in c_name or ex in c_lower for ex in exclude_pats):
continue
# 2. Exact basename match
if c_name in exact_names:
matched.append(c)
if recommended is None and not is_checkpoint:
recommended = c
continue
# 3. Substring include patterns
for pat in patterns:
if pat in c_name or pat in c_lower:
matched.append(c)
if recommended is None and not is_checkpoint:
recommended = c
break
if matched:
return _ret(matched, recommended)
return _ret(all_clips if is_checkpoint else [], None)
def _gather_all_clips():
"""Gather CLIP files from text_encoders and clip folders."""
clips = []
seen = set()
for folder in ['text_encoders', 'clip']:
try:
for c in folder_paths.get_filename_list(folder):
if c not in seen:
seen.add(c)
clips.append(c)
except Exception:
pass
return clips
+8
View File
@@ -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']
+2 -2
View File
@@ -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.13.5"
version = "2.5.1"
license = {file = "LICENSE"}
# classifiers = [
# # For OS-independent nodes (works on all operating systems)
@@ -20,7 +20,7 @@ license = {file = "LICENSE"}
# "Environment :: GPU :: Apple Metal", # Apple Metal support
# ]
dependencies = ["requests>=2.31.0", "huggingface_hub>=0.20.0", "psutil>=5.9.0", "tqdm>=4.66.0", "Pillow>=10.0.0", "torch>=2.0.0", "numpy>=1.24.0", "colorama"]
dependencies = ["requests", "huggingface_hub", "psutil", "tqdm", "Pillow", "torch", "numpy", "colorama"]
[project.urls]
Repository = "https://github.com/FranckyB/ComfyUI-Prompt-Manager"
+1 -7
View File
@@ -1,8 +1,2 @@
requests>=2.31.0
huggingface_hub>=0.20.0
psutil>=5.9.0
tqdm>=4.66.0
Pillow>=10.0.0
torch>=2.0.0
numpy>=1.24.0
huggingface_hub
colorama
+660
View File
@@ -0,0 +1,660 @@
# ComfyUI Prompt Manager
## A comprehensive prompt and workflow toolkit for [ComfyUI](https://github.com/comfyanonymous/ComfyUI) — Save, Generate, Extract, Build, and Reuse workflows with full LoRA support.
A complete prompt and workflow management suite featuring:
## v2.0 Introduces: Workflow Extractor + Workflow Builder + Workflow Renderer + Workflow Manager
The goal of this v2.0 workflow layer is to strip workflows down to their core elements so they are easier to understand, edit, and reuse.
- Extract metadata from source images and videos (ComfyUI or A1111/Forge)
- Reduce complex graphs into a clean, editable workflow core
- Rebuild and run from that simplified core with Workflow Builder to Workflow Renderer
- Save and reuse clean workflow entries through Workflow Manager
- Combine with Prompt tools (Prompt Manager, and Prompt Generator) for easier prompt creation and generation.
Think of it as workflow de-spaghetti: keep the important parts, remove unnecessary complexity.
This release marks version 2.0.0. More polish and quality-of-life improvements are planned.
**Prompt Manager** — Save and organize prompts with categories, complete with matching LoRA stacks, trigger words, and thumbnail previews. Supports dual LoRA stacks for complex workflows like Wan videos. Toggle LoRAs on/off or adjust strengths directly from saved presets. Supports workflow_data input from Workflow Builder or Prompt Extractor to pull workflow prompts and LoRA stacks directly into PMA. Will also remap LoRAs if paths differ.
**Prompt Generator** — Generate and enhance prompts using local LLMs via [llama.cpp](https://github.com/ggerganov/llama.cpp) or [Ollama](https://ollama.com). Supports text enhancement, image analysis with vision models (Qwen3.5), and thinking mode for deeper reasoning. Analyze up to 5 images at once.
**Prompt Extractor** — Extract prompts, LoRA configurations, and checkpoint/model paths from existing images, videos, or JSON workflow files. Extracts the first frame from any video. Automatically parses embedded metadata and outputs active LoRAs as LoRA stacks, plus resolved model paths (High/Low for dual-model workflows like Wan). Supports ComfyUI, A1111/Forge, and WebP metadata formats. When used with Prompt Manager Advanced, LoRAs are automatically found if available, regardless of path. For those that are not, right-click offers the option to look for them on Civitai. Browse files from both your input and output folders.
**Prompt Model Loader** — Load checkpoints, diffusion, or GGUF models from a string path output by Prompt Extractor. Auto-detects whether the model is a checkpoint (outputs MODEL + CLIP + VAE) or a diffusion/UNET/GGUF model (outputs MODEL only). Displays model type badge and name directly on the node. Works around ComfyUI's combo type limitation, allowing extracted model paths to connect directly to a loader. Supports [ComfyUI-GGUF](https://github.com/city96/ComfyUI-GGUF) models when the extension is installed.
**Workflow Suite of Tools** — Build and re-render extracted workflows with dedicated nodes:
- **Workflow Extractor**: Reads workflow metadata and normalizes it into reusable workflow_data.
- **Workflow Builder**: Lets you edit and assemble a clean core workflow from extracted metadata.
- **Workflow Renderer**: Runs built-in workflow templates for near one-click generation after Builder setup.
- **Workflow Bridge**: Passes workflow context and routing data between nodes cleanly.
- **Workflow Model Loader**: Resolves and loads the right model/checkpoint from workflow data.
- **Workflow Manager**: Saves and reuses cleaned workflow entries for fast reruns.
Builder + Renderer + Workflow Manager provides a streamlined generation path: configure Builder once, connect Renderer and Save Image/Save Video, and save both the output and the resulting workflow.
Built-in workflow support includes Flux 1, Flux 2, SDXL, Wan, Qwen, Z-Image, Wan Image, and Wan Video (I2V and T2V).
**Workflow Builder + Workflow Manager Reuse Loop** — Build workflow_data from extracted image/video metadata or from Workflow Builder directly, then save and reuse those workflow entries through Workflow Manager.
___
<div align="center">
<figcaption>Prompt Manager Advanced, with Lora and trigger word support</figcaption>
<img src="docs/prompt_manager_advanced.png" alt="Prompt Manager">
</div>
<div align="center">
<figcaption>Prompt Extractor connected to Manager Advanced, so workflow can be saved with Loras</figcaption>
<img src="docs/prompt_extractor.png" alt="Prompt Manager">
</div>
<div align="center">
<figcaption>Advanced Prompt Generator</figcaption>
<img src="docs/prompt_generator_advanced.png" alt="Prompt Manager">
</div>
<div align="center">
<figcaption>Simple Prompt Generator</figcaption>
<img src="docs/prompt_manager.png" alt="Prompt Manager">
</div>
<div align="center">
<figcaption>Workflow Builder</figcaption>
<img src="docs/workflow_builder.jpg" alt="Prompt Manager">
</div>
### Key features:
### Prompt Manager:
- **Category Organization**: Create and manage multiple categories to organize your prompts
- **Save & Load Prompts**: Quickly save and recall your favorite prompts with custom names
- **NSFW Tagging**: Mark categories and individual prompts as NSFW with visual badge indicator on the node title bar
- **NSFW Filtering**: Hide/show NSFW content via a global preference — NSFW categories and prompts are filtered from dropdowns when hidden
- **LLM Input Toggle**: Connect text outputs from other nodes and toggle between using them or your internal prompts
- **LLM Input Toggle**: When in use, display of categories and prompt is disabled, allowing user to switch category and save.
- **Persistent Storage**: All prompts saved in your ComfyUI user folder
### Prompt Manager Advanced:
- **All Prompt Manager Features**: Everything from the basic Prompt Manager, plus LoRA and trigger-word integration
- **NSFW Tagging**: Mark categories and individual prompts as NSFW — red "NSFW" badge appears on the prompt selector and in the thumbnail browser
- **NSFW Filtering**: Session-persistent NSFW toggle button in the thumbnail browser to show/hide NSFW content; navigation arrows skip NSFW entries when hidden
- **List View Mode**: Switch between thumbnail grid and compact list view in the prompt browser, with session-persistent preference
- **Prompt Thumbnails**: Save thumbnail images with your prompts for visual identification in the dropdown
- **Dual LoRA Stack Support**: Two separate LoRA stack inputs/outputs for complex workflows (e.g., Wan video with different LoRAs for image and video)
- **Visual LoRA Tags**: See connected LoRAs as clickable tags with strength values
- **Toggle LoRAs On/Off**: Click any LoRA tag to enable/disable it without disconnecting
- **Editable Strengths**: Click the strength value on any tag to adjust it inline
- **Trigger Words Support**: Save and display trigger words alongside prompts and LoRAs; can use [ComfyUI-Lora-Manager](https://github.com/infantesimone/ComfyUI-Lora-Manager) trigger words.
- **Right-Click to Delete**: Right-click any LoRA or trigger word tag to remove it
- **Save LoRAs with Prompts**: When you save a prompt, the current LoRA configuration is saved with it
- **Override Mode**: Toggle "Override Lora" to ignore connected inputs and use only saved preset LoRAs
- **Merge Mode**: When override is off, connected LoRAs are merged with saved presets
- **Workflow Data Input**: Optional workflow_data input from Workflow Builder or Prompt Extractor, with use_workflow_data toggle support to use extracted prompt and LoRA stacks directly in PMA
- **LoRA Manager Integration**: If [ComfyUI-Lora-Manager](https://github.com/infantesimone/ComfyUI-Lora-Manager) is installed, hovering over LoRA tags shows preview images
- **Missing LoRA Detection**: LoRAs that aren't found on your system are highlighted in red
- **Thumbnail Generation**: Right-click any prompt to generate a thumbnail using a selectable checkpoint model. Model choice persists in ComfyUI preferences.
### Prompt Extractor:
- **Extract from Images/Videos**: Load images or videos and extract embedded prompts, LoRAs, and workflow metadata
- **Model/Checkpoint Extraction**: Extracts checkpoint and UNET model paths from workflows, with High/Low (A/B) assignment for dual-model setups like Wan video
- **A1111/Forge Support**: Parses A1111 parameters format to extract prompts, LoRAs, and model names from Forge/A1111 generated images
- **WebP Metadata Support**: Reads EXIF metadata from WebP images (RIFF format parser)
- **JSON Workflow Support**: Browse and load JSON workflow files directly to extract prompts and LoRA configurations
- **Input/Output Folder Switching**: Toggle between browsing your input or output folder directly from the node
- **Dual LoRA Stack Output**: Outputs two separate LoRA stacks for workflows using dual stacking (e.g., Wan video)
- **Active LoRA Filtering**: Only extracts LoRAs that are marked as active in the source workflow
- **Wide Node Compatibility**: Supports 11+ model loader types including CheckpointLoader, UNETLoader, UnetLoaderGGUF, DiffusionModelLoader, WanVideoModelLoader, CyberdyneModelHub, and more
- **Preview in Manager**: View extracted data and repathed LoRAs using Manager Advanced.
### Prompt Model Loader:
- **String-to-Model Loading**: Takes a model path string (from Prompt Extractor) and loads the model directly
- **Auto-Detection**: Automatically detects whether the path is a checkpoint (returns MODEL + CLIP + VAE) or diffusion/UNET/GGUF model (returns MODEL only)
- **GGUF Support**: Loads GGUF models when [ComfyUI-GGUF](https://github.com/city96/ComfyUI-GGUF) is installed, with automatic runtime detection
- **Visual Model Info**: Displays model type badge (Checkpoint/Diffusion/GGUF) and model name directly on the node
- **State Persistence**: Model info display and output slot visibility persist across tab switches and workflow reloads
- **Graceful Error Handling**: Displays a red "NOT FOUND" badge instead of crashing when a model path cannot be resolved
- **Model Path Resolution**: Works with both full paths and relative paths, searching checkpoints, diffusion_models, and unet folders
- **Weight Dtype Support**: Optional weight dtype selection for memory optimization
- **Family Filtering Tip**: Family filtering works best when model families are separated into clear folder structures (for example folders that include family cues like i2v/t2v/high/low).
### Prompt Generator
- **Three Generation Modes**: Enhance text prompts, analyze images, or analyze images with custom instructions
- **Dual Backend Support**: Use llama.cpp (local server, default) or Ollama as the LLM backend
- **Prompt Enhancement**: Transform basic prompts into detailed descriptions using local LLMs
- **Vision Analysis**: Analyze images with vision-capable models to generate detailed descriptions
- **Custom Image Analysis**: Provide your own instructions for image analysis
- **JSON Output**: Optional structured JSON output with scene breakdown
- **Thinking Support**: Support Thinking models to perform deeper generative reasoning.
- **Automatic Server Management**: Starts/stops llama.cpp server as needed, with automatic shut off at exit.
- **Smart Model Selection**: Auto-selects appropriate model based on mode, using mmproj-based vision detection.
### Prompt Generator Options
- **Model Selection**: Choose from local models or download Qwen3.5 models from HuggingFace
- **Auto-Download**: Automatically downloads both model and required mmproj files for vision models
- **LLM Parameters**: Fine-tune temperature, top_k, top_p, min_p, repeat_penalty and context size.
- **Custom Instructions**: Override default system prompt for different enhancement styles.
- **Extra Image Inputs**: Combine up to 5 images to generate your prompt.
- **Console Debugging**: Enable outputting the entire process to the console for debugging purposes.
### Preference Options
- Set choices for preferred models for both base mode and vision mode.
- Set a new default model location. Previous folders (gguf and llm) are still scanned, but new downloads are saved to the new default.
- Set a custom location for Llama.cpp. If Llama.cpp was not added to your system PATH, this option lets you specify its location.
- **LLM Backend**: Choose between llama.cpp (default) or Ollama as the generation backend.
- **Ollama Settings**: Configure Ollama URL and keep-alive duration for model memory management.
## Installation
1. Navigate to your ComfyUI custom nodes directory:
```
cd ComfyUI/custom_nodes/
```
2. Clone this repository:
```bash
git clone https://github.com/FranckyB/ComfyUI-Prompt-Manager.git
```
3. Install dependencies:
```bash
cd ComfyUI-Prompt-Manager
pip install -r requirements.txt
```
4. Install [llama.cpp](https://github.com/ggml-org/llama.cpp/tree/master)
Windows:
```bash
winget install llama.cpp
```
Linux:
```bash
brew install llama.cpp
```
5. If you have them, place your .gguf models in the models/gguf folder, or set your preferred folder path in preferences.
6. Restart ComfyUI
## Usage
### Prompt Manager
1. **Add the Node**: Add Node → Prompt Manager
2. **Select a Category**: Use the dropdown to choose from your categories
3. **Choose a Prompt**: Select a saved prompt from the name dropdown
4. **Connect prompt output**: Connect Prompt Manager output to your clip text encode node.
### Prompt Manager Advanced
1. **Add the Node**: Add Node → Prompt Manager → Prompt Manager Advanced
2. **Connect LoRA Stackers**: Connect LoRA stacker nodes (e.g., from LoRA Manager) to `lora_stack_a` and/or `lora_stack_b` inputs
3. **View LoRA Tags**: Connected LoRAs appear as clickable tags showing name and strength
4. **Toggle LoRAs**: Click a tag to enable/disable that LoRA (disabled tags turn gray)
5. **Adjust Strength**: Click the strength number on a tag to edit it inline
6. **Save with LoRAs**: Click "Save Prompt" to save both the prompt text and current LoRA configuration
7. **Workflow Input (Optional)**: Connect workflow_data from Workflow Builder or Prompt Extractor and enable use_workflow_data to use extracted prompt and LoRA stacks in PMA
8. **Override Mode**: Enable "Override Lora" checkbox to ignore connected inputs and use only the saved preset LoRAs
9. **Connect Outputs**: Use `lora_stack_a` and `lora_stack_b` outputs with the Apply LoRA Stack node
### Prompt Extractor
1. **Add the Node**: Add Node → Prompt Manager → Prompt Extractor
2. **Choose Source Folder**: Use the `source_folder` dropdown to browse files from either your **input** or **output** folder
3. **Load Media**: Select an image or video from the file browser, or drag-and-drop files onto the node
4. **JSON Workflows**: Supports extracting from JSON workflow files directly
5. **Extract Data**: The node automatically extracts prompts, LoRAs, and trigger words from embedded metadata
6. **View Results**: Extracted positive/negative prompts display in the text outputs, LoRA stacks output as LORA_STACK
7. **Use with Manager**: Connect the LoRA stack outputs to Prompt Manager Advanced to view and save the extracted configuration
### Prompt Generator
**Basic Usage** (assuming a model is present in models\gguf):
1. **Add the Node**: Add Node → Prompt Generator
2. **Select Mode**: Choose from:
- "Enhance User Prompt" - Improve text prompts with LLM
- "Analyze Image" - Generate detailed image descriptions
- "Analyze Image with Prompt" - Analyze images with custom instructions
3. **Connect inputs**: Connect image for vision modes, or just use text for enhancement mode
4. **Output as Json**: Use Format_as_Json to experiment with Json prompts.
5. **Push the LLM**: Use enable_thinking to enable the model to perform deeper generative reasoning before producing the final prompt.
6. **Save memory**: Toggle "stop_server_after" ON to free VRAM after generation
7. **Run Workflow**: Generated prompt displays and can be saved to Prompt Manager
**Advanced Usage**:
1. **Add the Options Node**: Add Node → Prompt Generator Options
2. **Connect Options**: Connect the options node to the Prompt Generator Options input
3. **Analyze multiple images**: Connect up to 4 additional images, for a total of 5.
4. **Select from available models**: Select from models found in your models\gguf folder. Qwen models will be available to download.
5. **Adjust settings**: Adjust LLM parameters (temperature, top_k, etc.)
6. **Customize LLM**: Customize the default LLM instructions to modify the responses llama returns.
7. **Enable Debugging**: Enable complete printout of process to console using show_everything_in_console
**Qwen models found in options**
- Qwen3.5-9B-UD-Q4_K_XL.gguf: Unsloth Dynamic 4-bit, good balance (~6GB VRAM)
- Qwen3.5-9B-Q8_0.gguf: Standard 8-bit, high quality (~9.5GB VRAM)
- Qwen3.5-9B-UD-Q8_K_XL.gguf: Unsloth Dynamic 8-bit, best quality (~13GB VRAM)
All Qwen3.5 models are unified vision+text — every model supports both text enhancement and image analysis via its mmproj file. Thinking mode is controlled at runtime via a toggle, no separate model variant needed.
**Model Management**:
- Place gguf files in models/gguf folder
- Downloaded models are also placed in this folder.
**Preferences**:
Preference settings can be found in ComfyUI Settings → Prompt Manager
- **Preferred Base Model**: Name of model used for "Enhance User Prompt" mode
- **Preferred Vision Model**: Name of model used for "Analyze Image" modes
- **Set Default Port** You can set the port used by Llama.cpp
- **Close Llama on Exit** By default Llama.cpp will be closed on exit.
- **Hide NSFW by Default**: When enabled, NSFW categories and prompts are hidden from all dropdowns, navigation, and the thumbnail browser
- **Default View Mode**: Choose between thumbnail grid or list view for the Advanced prompt browser
- **LLM Backend**: Choose between llama.cpp (default) or Ollama
- **Ollama URL**: Set the Ollama server address (default: http://127.0.0.1:11434)
- **Keep Alive Duration**: How long Ollama keeps the model loaded after a request (e.g. 5m, 30m, 0 for immediate unload)
## Requirements
- ComfyUI
- Python 3.8+
- requests
- huggingface_hub
- psutil
- tqdm
- Pillow
- colorama
- llama-server (from llama.cpp)
## Troubleshooting
**Problem**: Prompts don't appear in the dropdown
- **Solution**: Make sure the category has saved prompts. Try creating a new prompt first.
**Problem**: Changes aren't saved
- **Solution**: Click the "Save Prompt" button after making changes. Direct edits in the text field are temporary.
**Problem**: Can't see LLM output in the node
- **Solution**: Make sure the LLM output is connected to the "llm_input" and run the workflow.
**Problem**: "llama-server command not found"
- **Solution**: Install llama.cpp and make sure `llama-server` is available in command line. See [llama.cpp releases](https://github.com/ggerganov/llama.cpp/releases)
**Problem**: "No models found"
- **Solution**: Either place a .gguf file in the `models/` folder, or connect the Prompt Generator Options node and select a model size (1.7B, 4B, or 8B) to download from HuggingFace
**Problem**: Server won't start
- **Solution**: Check that port 8080 is not in use. Close any existing llama-server processes.
**Problem**: Model download fails
- **Solution**: Check your internet connection and HuggingFace availability. Large models may take time to download.
**Problem**: Generation is slow
- **Solution**: Use a smaller quantized model (Q4 instead of Q8), or toggle 'stop_server_after' to quit llama.cpp after generating a prompt.
**Problem**: Default model used is not what I want
- **Solution**: You can set your preferred model in the ComfyUI settings. Simply add its full name, with .gguf extension, for both the VL and base models. Enabling Thinking in the Generator might change what is used for VL models.
## Changelog
### version 2.0.0
- **Prompt Manager becomes Prompt + Workflow Manager**
- Workflow Manager now allows saving Workflow and is integrated with Prompt Manager save/reuse behavior
- Extractor, Builder, and Manager workflow loop now focuses on simplified, reusable workflow cores
- Workflow save/reuse behavior aligned with workflow_data-first persistence for consistent prompt and LoRA retention
- Documentation updated to reflect full prompt and workflow scope
- More polish improvements coming soon
### version 1.25.0
- **Workflow Tools Release Milestone**
- Workflow Builder / Workflow Renderer / Workflow Bridge / Workflow Model Loader now form a complete editable workflow pipeline
- Improved extractor-to-builder update flow for image/video metadata refresh
- Improved Builder dropdown stability and selection persistence on first open
- Improved tab-switch persistence for Builder UI state, including LoRA stacks and LoRA state
- Improved compatibility when extracting from workflows generated by Builder persistence data
- **Wan i2v Workflow Quality and UX Improvements**
- Better high/low model handling and dual-pass sampler defaults in workflow path
- Improved model-family filtering and unsupported-family handling in Builder/Renderer
- Improved workflow update diagnostics to simplify troubleshooting of resolution and model propagation
- **Prompt Manager Advanced Save + Thumbnail Improvements**
- Save flow now reuses the full Advanced browser UI (same search, category tools, NSFW/filter handling, and existing prompt selection behavior)
- Save action terminology updated to **Save Workflow** for workflow-oriented entries
- Save now enforces category selection before submission to avoid uncategorized/invalid saves
- Workflow Saver save action now uses failure-only notifications (no success toast spam)
- Thumbnail generation now tries Workflow Renderer first when workflow_data is present, with automatic fallback to the basic checkpoint/LoRA thumbnail path
- Renderer thumbnail path now forces thumbnail-safe resolution and single-frame batch settings before queueing (consistent size, batch=1)
### version 1.22.6
- **Prompt Extractor now extract Prompt Extractor**
- Prompt Extractor now embeds extracted data in the workflow, so it can extract itself.
### version 1.22.5
- **Thumbnail Generation in Prompt Manager Advanced**
- Right-click any prompt to generate a thumbnail using a basic KSampler workflow
- Checkpoint model selector with filterable list of all available checkpoints
- Includes saved LoRAs (both stacks, active only) for more accurate thumbnails
- LoRA paths resolved via existing fuzzy matching — renamed LoRAs are found automatically
- Random seed on each generation — re-generate to get a different result
- Selected checkpoint persists in ComfyUI preferences across sessions
- Change model anytime via right-click menu or ComfyUI Settings → Prompt Manager
- Spinner overlay during generation with 120s timeout
- **Improved Model High/Low Detection**
- Better detection of embedded high/low indicators in model names (e.g., `tastysinHighV81`, `tastysinLowV81`)
### version 1.22.1
- **Prompt Model Loader Improvements**
- Added GGUF model support via runtime detection of [ComfyUI-GGUF](https://github.com/city96/ComfyUI-GGUF) extension
- Visual model type badge (Checkpoint/Diffusion/GGUF/NOT FOUND) and model name displayed on the node
- CLIP and VAE output slots automatically hidden for non-checkpoint models
- State persistence: model info and output slot visibility survive tab switches and workflow reloads
- Graceful error handling: shows red "NOT FOUND" badge instead of crashing on missing models
- Searches `unet_gguf` folder paths registered by ComfyUI-GGUF
### version 1.22.0
- **New Node: Prompt Model Loader**
- Loads checkpoints or diffusion/UNET models from a string path (output by Prompt Extractor)
- Auto-detects model type: checkpoints return MODEL + CLIP + VAE, diffusion models return MODEL only
- Searches ComfyUI checkpoints, diffusion_models, and unet folders automatically
- Optional weight dtype selection for memory optimization
- **Model/Checkpoint Extraction in Prompt Extractor**
- Extracts checkpoint and UNET model paths from workflow metadata
- High/Low (A/B) model assignment for dual-model workflows (e.g., Wan video with different models per noise level)
- Resolves extracted model names to local file paths using ComfyUI's folder system
- Supports 11+ model loader types: CheckpointLoaderSimple, UNETLoader, UnetLoaderGGUF, DiffusionModelLoader, WanVideoModelLoader, CyberdyneModelHub (dual high/low), and more
- New `model_a` and `model_b` STRING outputs on the Prompt Extractor node
- **A1111/Forge Image Support**
- Parses `Model:` field from A1111/Forge parameters format (both JS and Python paths)
- Extracts model names from images generated by Automatic1111, Forge, and compatible UIs
- **WebP Metadata Support**
- Added RIFF/EXIF parser for reading ComfyUI metadata from WebP images
- Fixed EXIF tag reading to use correct tags (0x010e ImageDescription, 0x010f Make) for ComfyUI metadata
- **Video Metadata Improvements**
- Added `comment` tag parsing in ffprobe fallback for videos that store metadata as JSON wrapper
### version 1.21.2
- **Improved Thumbnail Extraction**
- prompt extractor: enhance video thumbnail extraction and error handling for unsupported formats
- **Improve llama-server**
- Increase server startup timeout from 30s to 120s for large models
- Detect early server crashes and show stderr output to user
- Fix _get_model_keywords docstring to reflect version preservation (qwen3.5)
### version 1.21.1
- **Bug Fix** - Fixed issues caused by restructure
### version 1.21.0
- **Removed miscellaneous tools** — Switch Any, Save Video H26x, Apply LoRA Stack, Better Image Loader, and Animated Latent Preview have been moved to a dedicated repository: [ComfyUI-FBnodes](https://github.com/FranckyB/ComfyUI-FBnodes)
- **Project restructure** — Organized node files into `nodes/` and utility modules into `py/` for cleaner codebase
### version 1.20.0
- **New Node: Better Image Loader**
- Streamlined image and video loader with the same file browser as Prompt Extractor
- Browse input or output folders, preview images and videos, scrub through video frames
- Drag-and-drop support, single IMAGE output — no metadata extraction or LoRA processing
- **Prompt Extractor: Input/Output Folder Switching**
- New `source_folder` toggle to browse files from either your input or output directory
- File browser, thumbnails, and previews all respect the selected source folder
- **Switch Any Bug Fix**
- Fixed SwitchAnyBool not triggering upstream node execution
- Fixed SwitchAny input names reverting to defaults after execution
### version 1.19.0
- **True Switch Any Node**
- Added a 10 input 'True' Switch any node, that takes any inputs, doesn't lock in the type.
- Allows rename of inputs using a simple string with all names split using , or ;
- True lazy support, any Non selected input is disconnected internally.
- **Metadata Json**
- Added metadata output, so workflow found can be visualized
- **Bug Fix**
- Fixed bug where page reload and switching workflow would needlessly refetch the prompt.
### version 1.18.0
- **Thumbnail Hover Preview**
- Intelligent delay system: 1000ms initial, then 50ms for fast browsing (resets after 2s inactivity)
- Preference toggle in ComfyUI Settings and browser UI (🔍 Preview / 🔍 Off)
- Auto-scroll to selected prompt when browser opens
- **Improved Thumbnail Quality**
- Increased resolution to 200x200 (up from 128x128) with aspect ratio preservation
- Optimized JSON storage format
### version 1.17.6
- **Swap LoRA Stack Outputs**
- Added `swap_lora_outputs` toggle to swap LoRA Stack A and B outputs
- Useful for quickly testing different LoRA configurations in dual-stack workflows
- **LoRA Input Handling Fixes**
- Fixed issue when no LoRA input was connected: toggling LoRAs off would cause the list to refresh and revert the toggle state
- Fixed inability to set LoRA strength to 0 (zero values were incorrectly replaced with 1.0)
- Fixed saving prompts to use current displayed state instead of re-querying connected inputs
- Added automatic cleanup of input-derived LoRAs when they're no longer present in the connected input
- Improving `use_lora_input` toggle behavior to properly remove input-derived LoRAs when switching OFF while preserving preset LoRA toggle states
### version 1.17.5
- **Browser Context Menu Enhancements**
- Added "Delete Prompt", "Rename and Move Prompt" option to prompt right-click menu in the thumbnail browser
- Added "Delete Category", "Rename Category" options to category right-click menu
- Added "+" button at the end of the category list to create new categories directly from the browser
- All browser operations preserve unsaved prompt state (text, loras, trigger words are not reset)
- **Streamlined More Dropdown**
- Removed Rename Category, New Category, Delete Category, and Delete Prompt from the "More" dropdown (now accessible via browser context menus)
### version 1.17.0
- **NSFW Tagging & Filtering**
- Mark entire categories or individual prompts as NSFW
- Visual red "NSFW" badge on the Prompt Manager node title bar and on the Advanced prompt selector
- NSFW badge appears on all prompts within an NSFW-tagged category in the thumbnail browser
- Category buttons show red border for NSFW categories in the thumbnail browser
- Global preference to hide/show NSFW content — filters dropdowns, navigation arrows, and browser
- Session-persistent NSFW toggle button in the Advanced thumbnail browser
- Toggle NSFW on categories and prompts via context menu or the save/new category dialogs
- **List View Mode**
- New compact list view alternative to the thumbnail grid in the Advanced prompt browser
- Toggle between grid and list view with a button in the browser controls bar
- View mode preference is session-persistent
- Default view mode configurable in ComfyUI settings
- **UI Improvements**
- Search input moved into the controls bar with a clear (×) button
- Separator line between category buttons and prompt content
### version 1.16.0
- **Ollama Support**
- Added Ollama as an alternative LLM backend alongside llama.cpp
- Auto-discovers available Ollama models when no model is explicitly configured
- Keep-alive duration setting controls how long Ollama keeps the model loaded in memory
- "Stop server after" toggle unloads the model from Ollama memory to free VRAM
- **Upgraded to Qwen3.5 Models**
- Replaced Qwen3/Qwen3VL models with unified Qwen3.5-9B (vision+text in one model)
- Three download options: UD-Q4_K_XL (~6GB), Q8_0 (~9.5GB), UD-Q8_K_XL (~13GB)
- Thinking mode is now a runtime toggle — no separate model variant needed
- **mmproj-Based Vision Detection**
- Vision model detection no longer relies on "VL" in the filename
- Models are identified as vision-capable based on the presence of an mmproj file
- Heuristic matching supports user-provided models outside the predefined registry
- Backward compatible with existing Qwen3VL models and their mmproj files
- **Bug Fixes**
- Fixed seed control_after_generate not working (increment/decrement/randomize)
- Improved Prompt Extractor detection logic
### version 1.15.9
- **Bug Fixes**
- Improved Prompt Extractor, enhanced detection logic
### version 1.15.7
- **Added Rename Category Option**
- **Bug Fixes**
### version 1.15.6
- **Video Metadata Reader - VHS Compatible**
- Added capability to read metadata from VideoHelperSuite generated videos.
### version 1.15.5
- **Added get video components+ node**
- Since our save video node can saves latents, this also returns the matching latent (if found) and filepath.
- **Video Preview in Prompt Extractor**
- Added the option to preview in fullscreen with dark overlay for both images and video on the Prompt Extractor node.
### version 1.15.0
- **Added Animated Latent Preview**
- Added Similar option to VideoHelperSuite, to display animated Latent preview. With the addition that it works in TAESD mode.
- Check for VideoHelperSuite node, so not to conflict with it. (Will do nothing if installed)
### version 1.14.5
- **Added Save Latent support to Save Video node**
- allows to save the full data of a generation to then experiment without the need to regenerate.
- added some very quick workflow examples.
-A simplified version of my Wan workflow
-A basic Z-Image base workflow with Prompt Generator.
- Small bug fixes
### version 1.14.0
- **Addition of a "Save Video H264/H265" node, that replicates ComfyUI's Video Node**
- Adds choice between H264/H265
- Choice of Chroma Subsampling between yuv420, yuv422, yuv444
- Can set Constant Rate Factor (compression level)
- Generates a quick proxy video if chosen format could not play in browser (H265 + yuv422 or H265 + yuv444)
- Unlike VideoHelperSuite, clip with Audio also include Metadata. Which can then be used with Prompt Extractor.
### version 1.13.5
- Added browse window with thumbnails in Extractor, with cache system for speedup.
- Bug fix for issue caused by new additions.
### version 1.12.7
- Quality of life improvements and added option to change the strength of any LoRA in Manager, so we can tweak extracted workflows live.
### version 1.12.6
- Tweak to caching behavior for prompt extractor and prompt manager advanced
### version 1.12.5
- Some dependencies to FFMpeg were still present, remove them and added a frame_position value, so we can specify what frame to get from video.
### version 1.12.0
- Prompt Extractor: Added Lora inputs, so it can be used as a passthrough, with a None Choice at top, to easily deactivate it.
- Prompt Extractor: Improved logic for determining positive prompts in workflow.
- Prompt Extractor: Improved logic for finding High and Low Lora Stacks
- Prompt Manager Advanced: Added Fuzzy Logic to find Loras that might have been renamed
- Prompt Manager Advanced: Fixed issue of Lora buttons getting cleared when changing tab.
### Version 1.11.5
- Slight adjustement to extractor node, gets metadata in a method more consistent with ComfyUI, removing need for ffmpeg for videos.
### Version 1.11.2
- Slight adjustement to extractor node to behave exactly like the Load image node, while also supporting Videos. (With extract first frame support)
### Version 1.11.0
- **New Node: Prompt Extractor** - Extract prompts and LoRA configurations from images, videos, and JSON workflows
- Loads embedded metadata from PNG, JPEG, WebP images and MP4 videos
- Browse and load JSON workflow files directly
- Dual LoRA stack output for workflows using two stacks (e.g., Wan video)
- Filters inactive LoRAs - only extracts LoRAs marked as active
- Supports extraction from CLIP Text Encode, samplers, and LoRA stackers
- Compatible with Power Lora Loader, WanMoeKSamplerAdvanced, and other common nodes
- **Prompt Thumbnails** - Save thumbnail images with prompts in Prompt Manager Advanced
- Visual identification of prompts in the dropdown selector
- Thumbnails stored alongside prompt data for easy management
- **Simplified "New Prompt" button**
- Now clears fields immediately without asking for a name
- Enter the name when saving instead of when creating
- Keeps you in the current category for faster workflow
- **Bug fixes and improvements**
- Fixed JSON workflow file path resolution
- Improved LoRA extraction for complex workflows
### Version 1.10.0
- **Unified UI for Prompt Manager and Prompt Manager Advanced**
- Three-button layout: Save Prompt, New Prompt, and More (dropdown menu)
- New Prompt button creates a temporary prompt that isn't saved until you click Save Prompt
- Save Prompt opens a modal with category selection (create new or select existing)
- More dropdown includes: Import JSON, Export JSON, Delete Prompt, Delete Category
- **Import/Export JSON functionality**
- Export all prompts to a JSON file
- Import prompts with Merge (add to existing) or Replace (overwrite all) options
- Proper cancel handling without false success messages
- **Multi-tab synchronization**
- Changing category or prompt reloads data from server
- Prevents conflicts when editing prompts in multiple browser tabs
- **Prompt Manager now preserves LoRA data**
- LoRA stacks, trigger words, and active states are preserved when saving from basic Prompt Manager
- Seamless compatibility between Prompt Manager and Prompt Manager Advanced
- **Trigger Words support in Prompt Manager Advanced**
- Save and restore trigger words alongside prompts and LoRAs
- Trigger words display as editable text when loading saved prompts
- **Improved unsaved changes detection**
- Warning when switching away from newly created (unsaved) prompts
- Cancel button properly reverts dropdown to previous selection
### Version 1.9.0
- **New Node: Prompt Manager Advanced** - Extended prompt manager with LoRA stack support
- Dual LoRA stack inputs/outputs for complex workflows (Wan video, etc.)
- Visual LoRA tags showing name and editable strength values
- Toggle LoRAs on/off by clicking tags
- Save LoRA configurations alongside prompts
- Override mode to ignore connected inputs and use saved presets
- Merge mode combines connected LoRAs with saved presets
- Missing LoRA detection with visual warnings
- Integration with LoRA Manager for hover previews
- **New Node: Apply LoRA Stack** - Simple node to apply LORA_STACK to model/clip
- Categories and prompts now display in alphabetical order
- Fixed dropdown refresh after saving prompts
### Version 1.8.3
- Added option to leave Llama server running when closing ComfyUI.
### Version 1.8.2
- Added custom model path preference and enhance model management
### Version 1.8.1
- Added option to set a custom Llama path in preferences, for those that have specific installs.
### Version 1.8.0
- Added support for Qwen3VL Thinking model variants, with download options thru the Generator Options node.
- Model manager now searches for relevant `mmproj` files using model-name components for more reliable vision-model linking.
- Detailed console output options (debug logging)
- `enable_thinking` toggle to enable/disable the model's reasoning/thinking mode.
- Options node now accepts multiple images for analysis.
- Better Llama shutdown behavior to force-close the server when Comfy exits.
- Uses model-reported sampling params by default when available; the Options node can override them per-parameter.
- Moved preference API endpoints and cache handling into `model_manager.py` for cleaner management and persistence.
### Version 1.7.0
- Added three-mode prompt generator: "Enhance User Prompt", "Analyze Image", "Analyze Image with Prompt"
- Enhanced vision model workflow with dedicated image analysis modes
- Added custom image analysis with user-provided instructions (e.g., "describe the lighting", "identify objects")
- Added model preferences system integrated with ComfyUI Settings
- Added automatic model preference management (separate settings for base and vision models)
- Improved model selection with preference fallback to smallest model
- Filtered mmproj files from model selection dropdowns
- Model preferences stored in ComfyUI settings for persistence across updates
### Version 1.6.0
- Added Qwen3VL vision model support for image analysis
- Added JSON output format option with structured scene breakdown
- Added adjustable context size parameter (512-32768 tokens)
- Added automatic mmproj file download for vision models
- Added image resizing to ~2MP to optimize token usage
- Added token usage logging for monitoring context consumption
- Improved model selection logic with automatic VL/non-VL detection
- Fixed multiple directory support for model search (gguf + LLM folders)
### Version 1.5.1
- LLM output remains available when use_llm is off, so it can be edited.
- Improved caching detection: any change to options will be detected and force a new output.
- Improved some UI quirks
### Version 1.5.0
- Added Prompt Generator node with automatic llama.cpp server management
- Added Prompt Generator Options node for model selection and parameters
- Automatic model detection and auto-download from HuggingFace for Qwen3 models.
- VRAM management with optional server shutdown
### Version 1.1.0
- Added LLM input toggle for switching between internal and external text
- Made text fields scrollable even when disabled
- Fixed reload bugs with toggle state
### Version 1.0.0
- Initial release
- Category and prompt management
- LLM output integration
+38
View File
@@ -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]}')
-193
View File
@@ -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()
+189
View File
@@ -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);
};
```
File diff suppressed because it is too large Load Diff
-143
View File
@@ -1,143 +0,0 @@
"""
Test fuzzy LoRA matching logic
"""
import os
import re
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.
"""
# 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
search_parts = normalize_name(os.path.splitext(lora_name)[0])
search_set = set(search_parts)
candidates = []
for lora_file in lora_files:
file_name_no_ext = os.path.splitext(os.path.basename(lora_file))[0]
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 test_fuzzy_matching():
"""Test various fuzzy matching scenarios"""
# Simulate available LoRA files
available_loras = [
"DR34LAY_I2V_14B_HIGH_V2.safetensors",
"DR34LAY_T2V_14B_HIGH_V2.safetensors",
"DR34LAY_I2V_A14B_LOW_V2.safetensors",
"SomeOther_I2V_LoRA.safetensors",
"ExactMatch.safetensors",
"MyLora_WAN_2_2_I2V_Style.safetensors",
"MyLora_Style.safetensors",
"CoolStyle_I2V (1).safetensors",
"CoolStyle_I2V.safetensors",
]
test_cases = [
("DR34LAY_HIGH_V2", "DR34LAY_I2V_14B_HIGH_V2.safetensors", "Renamed WAN LoRA (missing I2V, 14B)"),
("DR34LAY_HIGH_V2.safetensors", "DR34LAY_I2V_14B_HIGH_V2.safetensors", "Renamed WAN LoRA with extension"),
("DR34LAY_LOW_V2", "DR34LAY_I2V_A14B_LOW_V2.safetensors", "Renamed WAN LoRA (missing I2V, A14B)"),
("DR34LAY_I2V_HIGH_V2", "DR34LAY_I2V_14B_HIGH_V2.safetensors", "Has I2V - should prefer I2V match"),
("DR34LAY_T2V_HIGH_V2", "DR34LAY_T2V_14B_HIGH_V2.safetensors", "Has T2V - should prefer T2V match"),
("MyLora_Style", "MyLora_WAN_2_2_I2V_Style.safetensors", "Should match with WAN_2_2 removed"),
("CoolStyle_I2V", "CoolStyle_I2V (1).safetensors", "Should match ignoring (1) suffix"),
("ExactMatch", "ExactMatch.safetensors", "Exact match case"),
("NonExistent_LoRA", None, "Non-existent LoRA"),
]
print("=" * 80)
print("FUZZY LORA MATCHING TESTS")
print("=" * 80)
all_passed = True
for search_name, expected_match, description in test_cases:
result, found = fuzzy_match_lora(search_name, available_loras)
expected_found = expected_match is not None
passed = (found == expected_found and (not found or result == expected_match))
status = "[PASS]" if passed else "[FAIL]"
print(f"\n{status} {description}")
print(f" Search: '{search_name}'")
print(f" Expected: {expected_match}")
print(f" Got: {result}")
if not passed:
all_passed = False
print("\n" + "=" * 80)
if all_passed:
print("[SUCCESS] All tests passed!")
else:
print("[FAILURE] Some tests failed!")
print("=" * 80)
return all_passed
if __name__ == "__main__":
test_fuzzy_matching()
-100
View File
@@ -1,100 +0,0 @@
"""
Test LoRA extraction from workflow data
"""
import json
import sys
import os
from unittest.mock import Mock
# Add parent directory to path so we can import prompt_extractor
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
# Mock ComfyUI and heavy dependencies
sys.modules['folder_paths'] = Mock()
sys.modules['server'] = Mock()
sys.modules['torch'] = Mock()
sys.modules['PIL'] = Mock()
from prompt_extractor import parse_workflow_for_prompts
def test_wan_workflow_with_shared_lora_loader():
"""
Test case: WAN workflow where both high and low noise models
connect to the same Power Lora Loader, but should still extract
separate lora stacks based on which model they feed into.
"""
# Load the problematic workflow
workflow_path = r"d:\ComfyUI\user\default\workflows\Unsaved Workflow (4).json"
if not os.path.exists(workflow_path):
print(f"Workflow file not found: {workflow_path}")
return
with open(workflow_path, 'r', encoding='utf-8') as f:
workflow_data = json.load(f)
# Parse the workflow
result = parse_workflow_for_prompts(None, workflow_data)
print("\n" + "=" * 80)
print("TEST: WAN Workflow with Shared LoRA Loader")
print("=" * 80)
print(f"\nPositive prompt: {result['positive_prompt'][:100] if result['positive_prompt'] else 'EMPTY'}...")
print(f"Negative prompt: {result['negative_prompt'][:100] if result['negative_prompt'] else 'EMPTY'}")
print(f"\nLoRAs Stack A (High): {len(result['loras_a'])} LoRAs")
for lora in result['loras_a']:
active_status = " [ACTIVE]" if lora.get('active', True) else " [INACTIVE]"
print(f" - {lora['name']} (model: {lora['model_strength']}, clip: {lora['clip_strength']}){active_status}")
print(f"\nLoRAs Stack B (Low): {len(result['loras_b'])} LoRAs")
for lora in result['loras_b']:
active_status = " [ACTIVE]" if lora.get('active', True) else " [INACTIVE]"
print(f" - {lora['name']} (model: {lora['model_strength']}, clip: {lora['clip_strength']}){active_status}")
print("\n" + "=" * 80)
# Assertions - verify we get both active and inactive LoRAs from connected nodes
assert len(result['loras_a']) > 0, "Stack A should have LoRAs (high noise)"
assert len(result['loras_b']) > 0, "Stack B should have LoRAs (low noise)"
# Verify that we have BOTH active and inactive LoRAs (as the extractor returns all)
all_loras = result['loras_a'] + result['loras_b']
has_active = any(lora.get('active', True) for lora in all_loras)
has_inactive = any(not lora.get('active', True) for lora in all_loras)
print(f"\nVerification: Has active LoRAs: {has_active}, Has inactive LoRAs: {has_inactive}")
print(f"Total LoRAs extracted: {len(all_loras)}")
# Note: This workflow uses subgraphs, so prompts might be inside the subgraph
# assert result['positive_prompt'], "Should have positive prompt"
print("\n[PASS] All tests passed!")
def test_non_wan_workflow():
"""
Test case: Regular workflow without high/low naming conventions.
Should fall back to position-based assignment (1st chain -> A, 2nd -> B)
"""
workflow_path = r"d:\ComfyUI\user\default\workflows\Unsaved Workflow.json"
if not os.path.exists(workflow_path):
print(f"Workflow file not found: {workflow_path}")
return
with open(workflow_path, 'r', encoding='utf-8') as f:
workflow_data = json.load(f)
result = parse_workflow_for_prompts(None, workflow_data)
print("\n" + "=" * 80)
print("TEST: Non-WAN Workflow (backward compatibility)")
print("=" * 80)
print(f"\nLoRAs Stack A: {len(result['loras_a'])} LoRAs")
print(f"LoRAs Stack B: {len(result['loras_b'])} LoRAs")
print("\n" + "=" * 80)
print("\n[PASS] Backward compatibility maintained!")
if __name__ == "__main__":
test_wan_workflow_with_shared_lora_loader()
test_non_wan_workflow()
+570
View File
@@ -0,0 +1,570 @@
#!/usr/bin/env python3
"""
Contract tests for Recipe Builder execute behavior.
This test file is intentionally self-contained and stubs ComfyUI runtime modules
so it can run outside a full ComfyUI session:
python tests/test_recipe_builder_contract.py
Expected flow-of-data contract (maintainer note):
1. Builder can run with or without incoming recipe_data.
2. When recipe_data is connected, Builder pulls all model slots (A/B/C/D).
3. User-authored UI state lives in per-slot profiles and lock flags.
4. Connected multi inputs (prompts/loras) may update slot state,
but locked sections must be protected from those inputs.
5. LoRAs are additive: recipe_data LoRAs plus connected input LoRAs,
while preserving user state (active/order/strength) and missing flags.
6. If a multi input is disconnected, treat it as an empty list/payload so
stale input-derived state does not persist.
7. Final rule: after update/merge, execute must emit recipe_data authored from
the now-populated Builder state. Prompts/samplers/resolution/LoRAs should
reflect what the user has set (subject to locks and connected inputs).
"""
import importlib.util
import json
import os
import random
import sys
import types
import unittest
from copy import deepcopy
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
RECIPE_BUILDER_PATH = os.path.join(ROOT, "nodes", "recipe_builder.py")
def _install_stub_modules():
"""Install lightweight runtime stubs required to import recipe_builder.py."""
if "server" not in sys.modules:
server_mod = types.ModuleType("server")
class _Routes:
def get(self, *_args, **_kwargs):
return lambda fn: fn
def post(self, *_args, **_kwargs):
return lambda fn: fn
class _PromptServerInstance:
def __init__(self):
self.routes = _Routes()
def send_sync(self, *_args, **_kwargs):
return None
server_mod.PromptServer = types.SimpleNamespace(instance=_PromptServerInstance())
server_mod.web = types.SimpleNamespace(
json_response=lambda data, **_kwargs: data,
Response=lambda **kwargs: kwargs,
)
sys.modules["server"] = server_mod
if "folder_paths" not in sys.modules:
folder_paths_mod = types.ModuleType("folder_paths")
folder_paths_mod.models_dir = ROOT
folder_paths_mod.get_filename_list = lambda _kind=None: []
folder_paths_mod.get_full_path = lambda *_args, **_kwargs: ""
folder_paths_mod.get_folder_paths = lambda *_args, **_kwargs: []
sys.modules["folder_paths"] = folder_paths_mod
if "comfy" not in sys.modules:
comfy_mod = types.ModuleType("comfy")
comfy_mod.__path__ = []
comfy_samplers = types.ModuleType("comfy.samplers")
comfy_samplers.KSampler = types.SimpleNamespace(
SAMPLERS=["euler"],
SCHEDULERS=["simple"],
)
comfy_sd = types.ModuleType("comfy.sd")
comfy_utils = types.ModuleType("comfy.utils")
comfy_sample = types.ModuleType("comfy.sample")
comfy_model_mgmt = types.ModuleType("comfy.model_management")
comfy_mod.samplers = comfy_samplers
comfy_mod.sd = comfy_sd
comfy_mod.utils = comfy_utils
comfy_mod.sample = comfy_sample
comfy_mod.model_management = comfy_model_mgmt
sys.modules["comfy"] = comfy_mod
sys.modules["comfy.samplers"] = comfy_samplers
sys.modules["comfy.sd"] = comfy_sd
sys.modules["comfy.utils"] = comfy_utils
sys.modules["comfy.sample"] = comfy_sample
sys.modules["comfy.model_management"] = comfy_model_mgmt
if "torch" not in sys.modules:
torch_mod = types.ModuleType("torch")
torch_mod.cuda = types.SimpleNamespace(is_available=lambda: False)
sys.modules["torch"] = torch_mod
if "numpy" not in sys.modules:
numpy_mod = types.ModuleType("numpy")
sys.modules["numpy"] = numpy_mod
if "PIL" not in sys.modules:
pil_mod = types.ModuleType("PIL")
class _DummyImage:
@staticmethod
def open(*_args, **_kwargs):
return None
pil_mod.Image = _DummyImage
pil_mod.ImageOps = types.SimpleNamespace(exif_transpose=lambda img: img)
sys.modules["PIL"] = pil_mod
def _install_recipe_builder_dependency_stubs(pkg_root_name):
"""Install package-scoped stubs used by recipe_builder imports."""
pkg_mod = types.ModuleType(pkg_root_name)
pkg_mod.__path__ = [ROOT]
sys.modules[pkg_root_name] = pkg_mod
nodes_pkg_name = f"{pkg_root_name}.nodes"
nodes_pkg_mod = types.ModuleType(nodes_pkg_name)
nodes_pkg_mod.__path__ = [os.path.join(ROOT, "nodes")]
sys.modules[nodes_pkg_name] = nodes_pkg_mod
py_pkg_name = f"{pkg_root_name}.py"
py_pkg_mod = types.ModuleType(py_pkg_name)
py_pkg_mod.__path__ = [os.path.join(ROOT, "py")]
sys.modules[py_pkg_name] = py_pkg_mod
prompt_extractor_name = f"{pkg_root_name}.nodes.prompt_extractor"
prompt_extractor_mod = types.ModuleType(prompt_extractor_name)
prompt_extractor_mod.parse_workflow_for_prompts = lambda *_args, **_kwargs: {}
prompt_extractor_mod.extract_metadata_from_png = lambda *_args, **_kwargs: {}
prompt_extractor_mod.extract_metadata_from_jpeg = lambda *_args, **_kwargs: {}
prompt_extractor_mod.extract_metadata_from_json = lambda *_args, **_kwargs: {}
prompt_extractor_mod.extract_metadata_from_video = lambda *_args, **_kwargs: {}
prompt_extractor_mod.build_node_map = lambda *_args, **_kwargs: {}
prompt_extractor_mod.build_link_map = lambda *_args, **_kwargs: {}
prompt_extractor_mod.extract_video_frame_av_to_tensor = lambda *_args, **_kwargs: None
prompt_extractor_mod.get_cached_video_frame = lambda *_args, **_kwargs: None
prompt_extractor_mod.get_placeholder_image_tensor = lambda *_args, **_kwargs: None
sys.modules[prompt_extractor_name] = prompt_extractor_mod
wf_families_name = f"{pkg_root_name}.py.workflow_families"
wf_families_mod = types.ModuleType(wf_families_name)
wf_families_mod.MODEL_FAMILIES = {
"sdxl": {"label": "SDXL", "checkpoint": True},
"wan": {"label": "Wan", "checkpoint": True},
}
wf_families_mod.get_model_family = lambda *_args, **_kwargs: "sdxl"
wf_families_mod.get_family_label = lambda family: str(family or "")
wf_families_mod.get_family_sampler_strategy = lambda *_args, **_kwargs: "single"
wf_families_mod.get_compatible_families = lambda family: [family] if family else ["sdxl"]
wf_families_mod.get_all_family_labels = lambda: ["SDXL", "Wan"]
def _compat_models(*_args, **kwargs):
rows = ["ckpt_a", "ckpt_b", "ckpt_c", "ckpt_d", "standalone_ckpt_c"]
if kwargs.get("return_recommended"):
return rows, (rows[0] if rows else "")
return rows
def _compat_vaes(*_args, **kwargs):
rows = ["vae_default"]
if kwargs.get("return_recommended"):
return rows, (rows[0] if rows else "")
return rows
def _compat_clips(*_args, **kwargs):
rows = ["clip_a"]
if kwargs.get("return_recommended"):
return rows, list(rows)
return rows
wf_families_mod.list_compatible_models = _compat_models
wf_families_mod.list_compatible_vaes = _compat_vaes
wf_families_mod.list_compatible_clips = _compat_clips
sys.modules[wf_families_name] = wf_families_mod
wf_extract_name = f"{pkg_root_name}.py.workflow_extraction_utils"
wf_extract_mod = types.ModuleType(wf_extract_name)
wf_extract_mod.extract_sampler_params = lambda *_args, **_kwargs: {}
wf_extract_mod.extract_vae_info = lambda *_args, **_kwargs: {"name": "", "source": ""}
wf_extract_mod.extract_clip_info = lambda *_args, **_kwargs: {"names": [], "type": "", "source": ""}
wf_extract_mod.extract_resolution = lambda *_args, **_kwargs: {"width": 768, "height": 1280, "batch_size": 1, "length": None}
wf_extract_mod.resolve_model_name = lambda name, _family=None: (name or "", bool(name))
wf_extract_mod.resolve_vae_name = lambda name, _family=None: (name or "", bool(name))
wf_extract_mod.resolve_clip_names = lambda names, _family=None: (list(names or []), bool(names))
def _build_simplified(extracted, wf_overrides, sampler_params):
return {
"_source": "RecipeBuilder",
"positive_prompt": wf_overrides.get("positive_prompt", extracted.get("positive_prompt", "")),
"negative_prompt": wf_overrides.get("negative_prompt", extracted.get("negative_prompt", "")),
"model_a": wf_overrides.get("model_a", extracted.get("model_a", "")),
"model_b": wf_overrides.get("model_b", extracted.get("model_b", "")),
"family": extracted.get("model_family", ""),
"vae": wf_overrides.get("vae", extracted.get("vae", {}).get("name", "")),
"clip": wf_overrides.get("clip_names", extracted.get("clip", {}).get("names", [])),
"loras_a": list(extracted.get("loras_a", [])),
"loras_b": list(extracted.get("loras_b", [])),
"sampler": dict(sampler_params or {}),
"resolution": dict(extracted.get("resolution", {})),
"clip_type": extracted.get("clip", {}).get("type", ""),
"loader_type": extracted.get("loader_type", ""),
}
wf_extract_mod.build_simplified_workflow_data = _build_simplified
sys.modules[wf_extract_name] = wf_extract_mod
wf_data_name = f"{pkg_root_name}.py.workflow_data_utils"
wf_data_mod = types.ModuleType(wf_data_name)
wf_data_mod.ensure_v2_recipe_data = lambda data: data
wf_data_mod.strip_runtime_objects = lambda data: data
wf_data_mod.to_json_safe_workflow_data = lambda data: data
sys.modules[wf_data_name] = wf_data_mod
lora_utils_name = f"{pkg_root_name}.py.lora_utils"
lora_utils_mod = types.ModuleType(lora_utils_name)
def _resolve_lora_path(name):
if not name:
return "", False
return (f"/loras/{name}", name != "missing_lora")
lora_utils_mod.resolve_lora_path = _resolve_lora_path
lora_utils_mod.strip_lora_extension = lambda n: str(n or "").replace(".safetensors", "")
sys.modules[lora_utils_name] = lora_utils_mod
def _load_recipe_builder_module():
_install_stub_modules()
pkg_root_name = "cpm_testpkg"
_install_recipe_builder_dependency_stubs(pkg_root_name)
module_name = f"{pkg_root_name}.nodes.recipe_builder"
spec = importlib.util.spec_from_file_location(module_name, RECIPE_BUILDER_PATH)
if spec is None or spec.loader is None:
raise RuntimeError("Failed to create module spec for recipe_builder.py")
module = importlib.util.module_from_spec(spec)
sys.modules[module_name] = module
spec.loader.exec_module(module)
return module
def _make_model_block(name="", positive="", negative="", loras=None):
return {
"positive_prompt": positive,
"negative_prompt": negative,
"family": "sdxl",
"model": name,
"loras": list(loras or []),
"clip_type": "",
"loader_type": "",
"vae": "",
"clip": [],
"sampler": {
"steps": 20,
"cfg": 5.0,
"denoise": 1.0,
"seed": 0,
"sampler_name": "euler",
"scheduler": "simple",
},
"resolution": {"width": 768, "height": 1280, "batch_size": 1, "length": None},
}
def _make_base_recipe():
return {
"version": 2,
"models": {
"model_a": _make_model_block("ckpt_a", "pos_a", "neg_a", [{"name": "recipe_lora", "model_strength": 0.8, "clip_strength": 0.7, "active": True}]),
"model_b": _make_model_block("ckpt_b", "pos_b", "neg_b"),
"model_c": _make_model_block("ckpt_c", "pos_c", "neg_c"),
"model_d": _make_model_block("ckpt_d", "pos_d", "neg_d"),
},
}
def _default_slot_profile(model_name="", pos="", neg=""):
return {
"ov": {
"positive_prompt": pos,
"negative_prompt": neg,
"model_a": model_name,
"_family": "sdxl",
"clip_type": "",
"loader_type": "",
"vae": "",
"clip_names": [],
"loras_a": [],
"steps_a": 20,
"cfg": 5.0,
"denoise": 1.0,
"seed_a": 0,
"sampler_name": "euler",
"scheduler": "simple",
"_seed_auto": False,
"width": 768,
"height": 1280,
"batch_size": 1,
"length": None,
"_section_locks": {
"prompt": False,
"model": False,
"loras": False,
"sampler": False,
"resolution": False,
"seed": False,
"positive": False,
"negative": False,
},
},
"ls": {},
}
class RecipeBuilderContractTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.rb_module = _load_recipe_builder_module()
cls.builder = cls.rb_module.WorkflowBuilder()
def _exec(self, **kwargs):
defaults = {
"recipe_data": None,
"multi_pos_prompts": "",
"multi_neg_prompts": "",
"multi_lora_stack": {},
"override_data": "{}",
"lora_state": "{}",
"unique_id": "contract-test",
}
defaults.update(kwargs)
result = self.builder.execute(**defaults)
self.assertIn("result", result)
self.assertIn("ui", result)
return result
def test_recipe_data_pull_preserves_all_four_models(self):
recipe = _make_base_recipe()
slot_profiles = {
"model_a": _default_slot_profile(),
"model_b": _default_slot_profile(),
"model_c": _default_slot_profile(),
"model_d": _default_slot_profile(),
}
override_data = json.dumps({"_model_slot": "model_a", "_slot_profiles": slot_profiles})
out = self._exec(recipe_data=deepcopy(recipe), override_data=override_data)
output_wf = out["result"][0]
models = output_wf.get("models", {})
self.assertEqual(set(models.keys()), {"model_a", "model_b", "model_c", "model_d"})
self.assertEqual(models["model_a"]["model"], "ckpt_a")
self.assertEqual(models["model_b"]["model"], "ckpt_b")
self.assertEqual(models["model_c"]["model"], "ckpt_c")
self.assertEqual(models["model_d"]["model"], "ckpt_d")
# UI payload should also carry all slots so switching model view is consistent.
extracted = out["ui"]["workflow_info"][0]["extracted"]
slot_profiles = extracted.get("_slot_profiles", {})
self.assertEqual(set(slot_profiles.keys()), {"model_a", "model_b", "model_c", "model_d"})
def test_standalone_mode_creates_all_slots_and_applies_slot_profile(self):
slot_profiles = {
"model_a": _default_slot_profile(),
"model_b": _default_slot_profile(),
"model_c": _default_slot_profile(model_name="standalone_ckpt_c", pos="standalone_pos_c", neg="standalone_neg_c"),
"model_d": _default_slot_profile(),
}
override_data = json.dumps({"_model_slot": "model_c", "_slot_profiles": slot_profiles})
out = self._exec(recipe_data=None, override_data=override_data)
models = out["result"][0].get("models", {})
self.assertEqual(set(models.keys()), {"model_a", "model_b", "model_c", "model_d"})
self.assertEqual(models["model_c"]["model"], "standalone_ckpt_c")
self.assertEqual(models["model_c"]["positive_prompt"], "standalone_pos_c")
self.assertEqual(models["model_c"]["negative_prompt"], "standalone_neg_c")
def test_multi_prompt_overrides_recipe_when_unlocked(self):
recipe = _make_base_recipe()
slot_profiles = {
"model_a": _default_slot_profile(model_name="ckpt_a", pos="slot_pos", neg="slot_neg"),
"model_b": _default_slot_profile(),
"model_c": _default_slot_profile(),
"model_d": _default_slot_profile(),
}
override_data = json.dumps({"_model_slot": "model_a", "_slot_profiles": slot_profiles})
out = self._exec(
recipe_data=deepcopy(recipe),
override_data=override_data,
multi_pos_prompts={"model_a": "incoming_multi_pos"},
multi_neg_prompts={"model_a": "incoming_multi_neg"},
)
model_a = out["result"][0]["models"]["model_a"]
self.assertEqual(model_a["positive_prompt"], "incoming_multi_pos")
self.assertEqual(model_a["negative_prompt"], "incoming_multi_neg")
def test_locked_prompt_sections_ignore_connected_prompt_inputs(self):
recipe = _make_base_recipe()
profile_a = _default_slot_profile(model_name="ckpt_a", pos="locked_user_pos", neg="locked_user_neg")
profile_a["ov"]["_section_locks"]["positive"] = True
profile_a["ov"]["_section_locks"]["negative"] = True
slot_profiles = {
"model_a": profile_a,
"model_b": _default_slot_profile(),
"model_c": _default_slot_profile(),
"model_d": _default_slot_profile(),
}
override_data = json.dumps({"_model_slot": "model_a", "_slot_profiles": slot_profiles})
out = self._exec(
recipe_data=deepcopy(recipe),
override_data=override_data,
multi_pos_prompts={"model_a": "incoming_multi_pos"},
multi_neg_prompts={"model_a": "incoming_multi_neg"},
)
model_a = out["result"][0]["models"]["model_a"]
self.assertEqual(model_a["positive_prompt"], "locked_user_pos")
self.assertEqual(model_a["negative_prompt"], "locked_user_neg")
def test_loras_are_additive_and_preserve_state_and_missing_flag(self):
recipe = _make_base_recipe()
recipe["models"]["model_a"]["loras"] = [
{"name": "recipe_lora", "model_strength": 0.8, "clip_strength": 0.7, "active": True},
{"name": "missing_lora", "model_strength": 1.0, "clip_strength": 1.0, "active": True},
]
profile_a = _default_slot_profile(model_name="ckpt_a")
profile_a["ov"]["loras_a"] = [
{"name": "input_lora", "model_strength": 0.25, "clip_strength": 0.2, "active": False, "source_input": True},
{"name": "recipe_lora", "model_strength": 0.9, "clip_strength": 0.85, "active": True},
]
slot_profiles = {
"model_a": profile_a,
"model_b": _default_slot_profile(),
"model_c": _default_slot_profile(),
"model_d": _default_slot_profile(),
}
override_data = json.dumps({"_model_slot": "model_a", "_slot_profiles": slot_profiles})
out = self._exec(
recipe_data=deepcopy(recipe),
override_data=override_data,
multi_lora_stack={"model_a": [["input_lora", 0.75, 0.65]]},
)
model_a = out["result"][0]["models"]["model_a"]
loras = model_a["loras"]
by_name = {row.get("name"): row for row in loras}
self.assertIn("recipe_lora", by_name)
self.assertIn("input_lora", by_name)
self.assertIn("missing_lora", by_name)
self.assertFalse(by_name["input_lora"].get("active", True))
self.assertEqual(float(by_name["input_lora"].get("model_strength", 0)), 0.25)
self.assertEqual(float(by_name["input_lora"].get("clip_strength", 0)), 0.2)
lora_names = [row.get("name") for row in loras]
self.assertLess(lora_names.index("input_lora"), lora_names.index("recipe_lora"))
extracted = out["ui"]["workflow_info"][0]["extracted"]
lora_availability = extracted.get("lora_availability", {})
self.assertIn("missing_lora", lora_availability)
self.assertFalse(lora_availability["missing_lora"])
def test_disconnected_multi_loras_behaves_as_empty_list(self):
recipe = _make_base_recipe()
profile_a = _default_slot_profile(model_name="ckpt_a")
profile_a["ov"]["loras_a"] = [
{"name": "stale_input_lora", "model_strength": 0.6, "clip_strength": 0.6, "active": True, "source_input": True},
{"name": "recipe_lora", "model_strength": 0.8, "clip_strength": 0.7, "active": True},
]
slot_profiles = {
"model_a": profile_a,
"model_b": _default_slot_profile(),
"model_c": _default_slot_profile(),
"model_d": _default_slot_profile(),
}
override_data = json.dumps({"_model_slot": "model_a", "_slot_profiles": slot_profiles})
out = self._exec(recipe_data=deepcopy(recipe), override_data=override_data, multi_lora_stack={})
loras = out["result"][0]["models"]["model_a"].get("loras", [])
lora_names = [row.get("name") for row in loras]
self.assertNotIn("stale_input_lora", lora_names)
self.assertIn("recipe_lora", lora_names)
def test_randomized_prompt_lock_contract(self):
rng = random.Random(1337)
slots = ("model_a", "model_b", "model_c", "model_d")
def _tok(prefix):
return f"{prefix}_{rng.randint(1000, 9999)}"
for _ in range(40):
recipe = {"version": 2, "models": {}}
slot_profiles = {}
multi_pos = {}
multi_neg = {}
expected_pos = {}
expected_neg = {}
for slot in slots:
recipe_pos = _tok(f"rpos_{slot}")
recipe_neg = _tok(f"rneg_{slot}")
recipe_model = _tok(f"rmodel_{slot}")
recipe["models"][slot] = _make_model_block(recipe_model, recipe_pos, recipe_neg)
profile = _default_slot_profile(
model_name=recipe_model,
pos=_tok(f"upos_{slot}"),
neg=_tok(f"uneg_{slot}"),
)
lock_pos = bool(rng.getrandbits(1))
lock_neg = bool(rng.getrandbits(1))
profile["ov"]["_section_locks"]["positive"] = lock_pos
profile["ov"]["_section_locks"]["negative"] = lock_neg
slot_profiles[slot] = profile
if bool(rng.getrandbits(1)):
multi_pos[slot] = _tok(f"inpos_{slot}")
if bool(rng.getrandbits(1)):
multi_neg[slot] = _tok(f"inneg_{slot}")
expected_pos[slot] = (
profile["ov"]["positive_prompt"]
if lock_pos
else multi_pos.get(slot, recipe_pos)
)
expected_neg[slot] = (
profile["ov"]["negative_prompt"]
if lock_neg
else multi_neg.get(slot, recipe_neg)
)
override_data = json.dumps({"_model_slot": "model_a", "_slot_profiles": slot_profiles})
out = self._exec(
recipe_data=deepcopy(recipe),
override_data=override_data,
multi_pos_prompts=multi_pos,
multi_neg_prompts=multi_neg,
)
models = out["result"][0].get("models", {})
self.assertEqual(set(models.keys()), set(slots))
for slot in slots:
self.assertEqual(models[slot].get("positive_prompt"), expected_pos[slot])
self.assertEqual(models[slot].get("negative_prompt"), expected_neg[slot])
if __name__ == "__main__":
suite = unittest.defaultTestLoader.loadTestsFromTestCase(RecipeBuilderContractTests)
runner = unittest.TextTestRunner(verbosity=2)
result = runner.run(suite)
raise SystemExit(0 if result.wasSuccessful() else 1)
+210
View File
@@ -0,0 +1,210 @@
#!/usr/bin/env node
/*
JS contract tests for Recipe Builder UI lock/persistence logic.
Runs directly with Node and evaluates real functions from js/recipe_builder.js.
Usage:
node tests/test_recipe_builder_js_contract.js
*/
const fs = require("fs");
const path = require("path");
const vm = require("vm");
const assert = require("assert/strict");
const SOURCE_PATH = path.join(__dirname, "..", "js", "recipe_builder.js");
const SOURCE = fs.readFileSync(SOURCE_PATH, "utf8");
function extractFunction(name) {
const marker = `function ${name}(`;
const start = SOURCE.indexOf(marker);
if (start < 0) {
throw new Error(`Could not find function ${name} in ${SOURCE_PATH}`);
}
const bodyStart = SOURCE.indexOf("{", start);
if (bodyStart < 0) {
throw new Error(`Could not find function body start for ${name}`);
}
let depth = 0;
let end = -1;
for (let i = bodyStart; i < SOURCE.length; i += 1) {
const ch = SOURCE[i];
if (ch === "{") depth += 1;
if (ch === "}") {
depth -= 1;
if (depth === 0) {
end = i;
break;
}
}
}
if (end < 0) {
throw new Error(`Could not find function body end for ${name}`);
}
return SOURCE.slice(start, end + 1);
}
const context = {
console,
requestAnimationFrame: (cb) => {
if (typeof cb === "function") cb();
},
reflowNode: () => {},
C: { textMuted: "#aaa", text: "#ccc" },
cleanModelName: (v) => String(v ?? ""),
normalizeSelectableFamily: (v) => String(v || "sdxl"),
updateLoras: () => {},
checkLoraAvailability: () => {},
updateWanVisibility: () => {},
_normalizeModelSlotKey: (v) => {
const s = String(v || "model_a").toLowerCase();
return ["model_a", "model_b", "model_c", "model_d"].includes(s) ? s : "model_a";
},
_normalizeSlotProfiles: (x) => (x && typeof x === "object" ? x : {}),
document: {
createElement: () => ({
value: "",
textContent: "",
appendChild: () => {},
}),
},
};
vm.createContext(context);
vm.runInContext(extractFunction("mergeSlotProfileWithLocks"), context);
vm.runInContext(extractFunction("applyOverrides"), context);
vm.runInContext(extractFunction("syncHidden"), context);
function testMergeSlotProfileWithLocks() {
const current = {
ov: {
model_a: "locked_model",
positive_prompt: "locked_pos",
negative_prompt: "unlocked_neg",
steps_a: 77,
loras_a: [{ name: "kept_lora" }],
_section_locks: {
model: true,
sampler: true,
positive: true,
negative: false,
loras: true,
},
},
ls: { "a:kept_lora": { active: false, model_strength: 0.2, clip_strength: 0.2 } },
};
const incoming = {
ov: {
model_a: "incoming_model",
positive_prompt: "incoming_pos",
negative_prompt: "incoming_neg",
steps_a: 10,
loras_a: [{ name: "incoming_lora" }],
},
ls: { "a:incoming_lora": { active: true, model_strength: 1.0, clip_strength: 1.0 } },
};
const out = context.mergeSlotProfileWithLocks(current, incoming);
assert.equal(out.ov.model_a, "locked_model", "model lock should preserve current model");
assert.equal(out.ov.steps_a, 77, "sampler lock should preserve current sampler values");
assert.equal(out.ov.positive_prompt, "locked_pos", "positive lock should preserve current positive prompt");
assert.equal(out.ov.negative_prompt, "incoming_neg", "unlocked negative should adopt incoming value");
assert.equal(
JSON.stringify(out.ov.loras_a),
JSON.stringify([{ name: "kept_lora" }]),
"LoRA lock should preserve current LoRA list",
);
assert.equal(
JSON.stringify(out.ls),
JSON.stringify(current.ls),
"LoRA lock should preserve current LoRA state map",
);
}
function testApplyOverridesRestoresSectionLocks() {
const calls = [];
const node = {
_weExtracted: {},
_weUseSlotProfiles: false,
_weSetSectionLock: (key, locked, options) => {
calls.push({ key, locked, options });
},
};
const ov = {
_section_locks: {
resolution: true,
positive: true,
loras: false,
},
};
context.applyOverrides(node, JSON.stringify(ov), "{}");
const byKey = Object.fromEntries(calls.map((c) => [c.key, c]));
assert.equal(byKey.resolution.locked, true, "resolution lock should restore to true");
assert.equal(byKey.positive.locked, true, "positive lock should restore to true");
assert.equal(byKey.loras.locked, false, "loras lock should restore to false");
}
function testSyncHiddenPersistsLocksAndPrompts() {
const widgets = [
{ name: "override_data", value: "" },
{ name: "lora_state", value: "" },
];
const node = {
widgets,
properties: {},
_weOverrides: {},
_weSectionLocks: {
resolution: true,
positive: true,
loras: false,
},
_weCollapsedSections: {
resolution: false,
model: true,
sampler: false,
positive: true,
negative: false,
loras: true,
},
_weUseSlotProfiles: false,
_wePosBox: { value: "user_pos" },
_weNegBox: { value: "user_neg" },
_weExtracted: {
loras_a: [],
loras_b: [],
lora_availability: {},
},
};
context.syncHidden(node);
const overrideJson = widgets.find((w) => w.name === "override_data").value;
const ov = JSON.parse(overrideJson || "{}");
assert.equal(ov.positive_prompt, "user_pos", "syncHidden should persist positive prompt from UI");
assert.equal(ov.negative_prompt, "user_neg", "syncHidden should persist negative prompt from UI");
assert.equal(ov._section_locks.resolution, true, "syncHidden should persist resolution lock");
assert.equal(ov._section_locks.positive, true, "syncHidden should persist positive lock");
assert.equal(Object.prototype.hasOwnProperty.call(ov._section_locks, "loras"), false, "unlocked section should not be persisted in non-slot mode");
assert.equal(ov._section_collapsed.model, true, "syncHidden should persist global collapsed section state");
assert.equal(ov._section_collapsed.positive, true, "syncHidden should persist positive collapsed state");
}
function run() {
testMergeSlotProfileWithLocks();
testApplyOverridesRestoresSectionLocks();
testSyncHiddenPersistsLocksAndPrompts();
console.log("JS contract tests passed");
}
run();
+97
View File
@@ -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 ===")
-89
View File
@@ -1,89 +0,0 @@
"""
Test the specific workflow with disconnected LoRAs
"""
import json
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 parse_workflow_for_prompts
def test_unsaved_workflow_3():
"""
Test the specific workflow that has disconnected LoRAs
"""
workflow_path = r"D:\ComfyUI\user\default\workflows\Unsaved Workflow (3).json"
if not os.path.exists(workflow_path):
print(f"Workflow file not found: {workflow_path}")
return
with open(workflow_path, 'r', encoding='utf-8') as f:
workflow_data = json.load(f)
result = parse_workflow_for_prompts(None, workflow_data)
# Filter to ACTIVE only (like the real PromptExtractor node does at lines 1565/1581)
active_loras_a = [lora for lora in result['loras_a'] if lora.get('active', True)]
active_loras_b = [lora for lora in result['loras_b'] if lora.get('active', True)]
print("\n" + "=" * 80)
print("TEST: Unsaved Workflow (3) - Should NOT include disconnected LoRAs")
print("=" * 80)
print(f"\nLoRAs Stack A (ALL): {len(result['loras_a'])} LoRAs")
for lora in result['loras_a'][:10]: # Show first 10
active_status = " [ACTIVE]" if lora.get('active', True) else " [INACTIVE]"
print(f" - {lora['name']} (model: {lora['model_strength']}, clip: {lora['clip_strength']}){active_status}")
if len(result['loras_a']) > 10:
print(f" ... and {len(result['loras_a']) - 10} more")
print(f"\nLoRAs Stack A (ACTIVE ONLY): {len(active_loras_a)} LoRAs")
for lora in active_loras_a:
print(f" - {lora['name']} (model: {lora['model_strength']}, clip: {lora['clip_strength']})")
print(f"\nLoRAs Stack B (ALL): {len(result['loras_b'])} LoRAs")
for lora in result['loras_b'][:10]: # Show first 10
active_status = " [ACTIVE]" if lora.get('active', True) else " [INACTIVE]"
print(f" - {lora['name']} (model: {lora['model_strength']}, clip: {lora['clip_strength']}){active_status}")
if len(result['loras_b']) > 10:
print(f" ... and {len(result['loras_b']) - 10} more")
print(f"\nLoRAs Stack B (ACTIVE ONLY): {len(active_loras_b)} LoRAs")
for lora in active_loras_b:
print(f" - {lora['name']} (model: {lora['model_strength']}, clip: {lora['clip_strength']})")
print("\n" + "=" * 80)
# Check for the disconnected LoRAs in ACTIVE lists only
active_lora_names_a = [lora['name'] for lora in active_loras_a]
active_lora_names_b = [lora['name'] for lora in active_loras_b]
has_23high = any('23High noise-Cumshot' in name for name in active_lora_names_a + active_lora_names_b)
has_56low = any('56Low noise-Cumshot' in name for name in active_lora_names_a + active_lora_names_b)
print("\nDisconnected LoRA check (in ACTIVE lists):")
print(f" '23High noise-Cumshot Aesthetics' found: {has_23high} (should be False)")
print(f" '56Low noise-Cumshot Aesthetics' found: {has_56low} (should be False)")
print(f"\nTotal ACTIVE LoRAs extracted: {len(active_loras_a) + len(active_loras_b)} (expected: 8)")
if has_23high or has_56low:
print("\n[FAIL] Disconnected/inactive LoRAs are appearing in active lists!")
elif len(active_loras_a) == 4 and len(active_loras_b) == 4:
print("\n[PASS] Disconnected/inactive LoRAs correctly excluded!")
else:
print(f"\n[FAIL] Expected 4 active LoRAs per stack, got {len(active_loras_a)} and {len(active_loras_b)}")
print("=" * 80 + "\n")
if __name__ == "__main__":
test_unsaved_workflow_3()
+82
View File
@@ -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 ===")