Compare commits

...
273 Commits
Author SHA1 Message Date
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
THE_BEAST\me 30246eb831 chore: Update version to 1.13.5 and enhance project description in metadata 2026-01-14 20:52:41 -05:00
THE_BEAST\me c97c290dba feat: Add fallback video metadata extraction using ffprobe in API 2026-01-14 20:39:25 -05:00
THE_BEAST\me 2da9b2813b enhance JSON metadata extraction to use relative paths for caching 2026-01-14 20:01:53 -05:00
THE_BEAST\me aadb396151 Enhance PNG workflow metadata check to include A1111 parameters in clean up script 2026-01-14 19:47:25 -05:00
THE_BEAST\me 96c9248135 feat: Enhance A1111 parameters parsing and metadata extraction in prompt extractor 2026-01-14 19:27:25 -05:00
THE_BEAST\me 695d7421d4 enhance workflow indicator updates for various file types 2026-01-14 18:54:11 -05:00
THE_BEAST\me 9d8137281e feat: Add file organization script to manage files by workflow presence 2026-01-14 17:55:41 -05:00
THE_BEAST\me 546b2f697b enhance image preview loading logic to prevent unnecessary reloads 2026-01-14 17:24:59 -05:00
THE_BEAST\me 2d262999a3 feat: Release version 1.13.0 with new features and improvements
- Added a file browser modal with thumbnail previews in the Extractor, enhancing user experience for file selection.
- Implemented a caching system for thumbnails to improve loading speed.
- Updated version number to 1.13.0 in __init__.py and pyproject.toml.
- Enhanced file handling in the backend to support subfolder navigation and improved metadata caching.
- Added functionality to clear and manage cached video thumbnails.
- Improved state management in PromptManagerAdvanced to handle cases where input LoRAs are cleared.
2026-01-14 14:53:44 -05:00
THE_BEAST\me e36d0fb15f enhance reset functionality by tracking state changes and storing original strengths for LoRA adjustments 2026-01-14 12:13:31 -05:00
THE_BEAST\me d92a6c1872 enhance LoRA path handling by normalizing path separators and refactoring extension stripping logic 2026-01-14 11:27:10 -05:00
THE_BEAST\me 67df4c6e53 enhance LoRA extraction logic to only include connected nodes and add tests for disconnected LoRAs 2026-01-13 20:56:25 -05:00
THE_BEAST\me e08d18c783 bump version to 1.12.7; add reset functionality for LoRA strengths and improve user experience with live adjustments 2026-01-13 15:23:17 -05:00
THE_BEAST\me 769d40f9f5 enhance LoRA management by tracking input changes and improving display of unavailable LoRAs 2026-01-13 14:15:01 -05:00
THE_BEAST\me eef07948ac enhance video frame extraction and caching mechanism in PromptExtractor 2026-01-13 00:31:49 -05:00
THE_BEAST\me bf847e9639 chore: update version to 1.12.6 and enhance caching behavior in prompt extractor and prompt manager advanced 2026-01-12 23:06:27 -05:00
THE_BEAST\me 39c8b5f3b8 enhance video frame caching functionality 2026-01-12 20:01:40 -05:00
THE_BEAST\me cf810ca921 Updated Readme 2026-01-12 18:51:33 -05:00
THE_BEAST\me 422607ec8d Refactor prompt extraction and enhance LoRA matching
- Removed unnecessary print statements from prompt_extractor.py to clean up logging.
- Simplified LoRA stack processing by directly using paths if available.
- Introduced fuzzy matching for LoRA names in prompt_manager_advanced.py to handle renamed LoRAs.
- Added a new test suite (test_fuzzy_match.py) to validate fuzzy matching logic with various scenarios.
2026-01-12 18:43:17 -05:00
THE_BEAST\me f9e26c8bbd Added Lora Stack Input to Extractor.
Enhance LoRA and Prompt extraction logic, added tests
2026-01-12 17:15:22 -05:00
THE_BEAST\me be52d65de9 chore: add better drag-and-drop file upload support in Prompt Extractor 2026-01-12 00:37:23 -05:00
THE_BEAST\me 1d6021a916 chore: Bump version to 1.11.4 in __init__.py, pyproject.toml, and update changelog 2026-01-11 17:26:57 -05:00
THE_BEAST\me 6f0ac2674b chore: added workflow metadata notification in prompt extractor 2026-01-11 17:14:15 -05:00
THE_BEAST\me 6ba1f3f346 Update: Improved Prompt Extractor caching of metadata from images, videos, and JSON files. Removed need for ffmpeg and more consistent with how Comfy does it. 2026-01-11 16:26:44 -05:00
THE_BEAST\me 27ab751796 feat: Update Prompt Extractor to support video file extraction and enhance file listing API
chore: Bump version to 1.11.2 in __init__.py and pyproject.toml
docs: Improve README with detailed descriptions for Prompt Extractor and its functionalities
2026-01-11 12:43:53 -05:00
THE_BEAST\me e2a9b25978 chore: Bump version to 1.11.1 in __init__.py and pyproject.toml 2026-01-11 01:26:38 -05:00
THE_BEAST\me 9b8016821c docs: Update README to clarify Prompt Manager features and enhance Prompt Extractor description 2026-01-11 01:24:42 -05:00
THE_BEAST\me 4811f21255 Adjusted how Loras are seved 2026-01-11 01:11:33 -05:00
THE_BEAST\me ca645721ec feat: Enhance prompt management with thumbnail support and image processing
- Added functionality to save and retrieve thumbnails for prompts in 'prompt_manager_advanced.py`.
- Implemented image processing to convert image tensors to base64 thumbnails.
- Updated prompt saving logic to include thumbnail data.
- Introduced new API endpoint to save or remove thumbnails for prompts.
- Improved handling of LoRA paths and trigger words, ensuring case-insensitivity and better user experience.
- added a Prompt Extractor that analyses any valid input and extract Prompt and Loras
- Updated version to 1.11.0 in `pyproject.toml`.
2026-01-11 00:45:22 -05:00
THE_BEAST\me 457e137b4c Merge branch 'main' of https://github.com/FranckyB/ComfyUI-Prompt-Manager 2026-01-09 17:02:35 -05:00
THE_BEAST\me 603c34d601 feat: Enhance Prompt Manager with input validation, import functionality and trigger word support.
- Added VALIDATE_INPUTS method to allow temporary unsaved prompts in PromptManager and PromptManagerAdvanced.
- Updated save_prompt and save_prompt_advanced to require only category and name, allowing empty text for unsaved prompts.
- Implemented import and export functionality for prompts in both PromptManager and PromptManagerAdvanced, supporting merge and replace modes.
- Enhanced prompt data structure to include trigger words, with appropriate handling in save and retrieval methods.
- Updated version to 1.10.0 in pyproject.toml.
2026-01-09 17:00:11 -05:00
Francois Beaudry 4fae27a6dd Add GNU General Public License v3 2026-01-09 12:02:07 -05:00
Francois Beaudry 55a2fd64c9 Revise README for prompt manager enhancements
Updated README to reflect new features and compatibility.
2026-01-09 11:28:25 -05:00
Francois Beaudry 5450682d44 Update README with Lora Manager compatibility
Added compatibility information for Lora Manager.
2026-01-09 11:27:17 -05:00
THE_BEAST\me d424f67948 refactor: Revise text_video_system_prompt for clarity and consistency in guidelines 2026-01-09 00:24:06 -05:00
THE_BEAST\me 838122ae67 Reduced amount of example prompts from default prompts JSON 2026-01-09 00:01:21 -05:00
THE_BEAST\me e269117080 feat: Introduce Prompt Manager Advanced with LoRA support and enhanced prompt management
- Added `prompt_manager_advanced.py` for advanced prompt management, including LoRA stack integration.
- Updated `prompt_manager.py` to preserve existing LoRA data when saving prompts.
- prompt templates are now  external text files, for easy modifications.
- Updated `pyproject.toml` for versioning and dependency management.
2026-01-08 22:37:27 -05:00
THE_BEAST\me 8910544eba Update README and version to 1.8.3; add preferences for Llama server behavior 2025-12-19 10:29:27 -05:00
THE_BEAST\me 9243d704ac Update close Llama on exit preferences
Slight tweak to system prompt, so it doesn't add a title
2025-12-19 10:20:21 -05:00
THE_BEAST\me e9981c1ee7 Added option to leave Llama.cpp running on exit. 2025-12-19 09:30:25 -05:00
Francois Beaudry 7c25eaeb95 Update README to add preferences section
Removed model preferences and custom Llama path options from the README.
2025-12-18 09:49:03 -05:00
THE_BEAST\me d8d96e549b Improve model filtering by excluding mmproj files case-insensitively 2025-12-17 13:45:40 -05:00
Francois Beaudry 5d64bb2395 Refactor installation instructions in README.md
Updated README to improve clarity and organization of installation instructions.
2025-12-17 09:46:15 -05:00
THE_BEAST\me 877727695d Merge branch 'main' of https://github.com/FranckyB/ComfyUI-Prompt-Manager 2025-12-16 20:37:56 -05:00
THE_BEAST\me 64119e6c90 Enhance PromptGenerator output formatting and add new return values 2025-12-16 20:37:50 -05:00
Francois Beaudry 6d5a1f4669 Enhance README with custom path and prompt manager info
Added details about setting custom Llama-server and Model Path in preferences, and introduced the Prompt manager feature.
2025-12-16 18:35:05 -05:00
THE_BEAST\me 8ac04725c9 Merge branch 'main' of https://github.com/FranckyB/ComfyUI-Prompt-Manager 2025-12-16 17:21:39 -05:00
THE_BEAST\me ef0f072891 Add custom model path preference and enhance model management 2025-12-16 17:21:34 -05:00
Francois Beaudry 985de6102e Fix grammatical error in README.md 2025-12-16 13:19:29 -05:00
THE_BEAST\me ecdf1e0995 add custom Llama path preference option 2025-12-16 13:14:15 -05:00
Francois Beaudry 39575f137c Fix llama.cpp URL in README
Updated the README to correct the URL for llama.cpp.
2025-12-16 09:52:20 -05:00
THE_BEAST\me e993546fa4 Improve error message handling in Prompt Generator 2025-12-16 03:52:14 -05:00
Francois Beaudry ce12566998 Revise README for better readability and organization
Updated README to improve clarity and formatting.
2025-12-16 00:56:38 -05:00
THE_BEAST\me c61dcaad2c - Bumped version to 1.8.0.
- Added support for Qwen3VL Thinking model variants and improved model management.
- Enhanced error handling and console output for better debugging.
- Improved options node for better user experience and functionality.
2025-12-16 00:44:07 -05:00
THE_BEAST\me 1ba2d214f6 Added Better Llama Shutdown logic, should force close it when Comfy closes. Improved system prompts for "Analyze Image with Prompt". Previous one was preventing LLM to be creative. Now uses the models default values by default. Option node can be used to overide them.
Refactor preference management: move API endpoints to model_manager.py and remove in-memory cache from prompt_manager.py
2025-12-15 18:37:07 -05:00
THE_BEAST\me 473d96084c Enhance model management and prompt generation capabilities
- Added support for additional Qwen3VL models in model_manager.py.
- Improved mmproj file path retrieval logic to search for relevant files based on model name components.
- Introduced new functions in prompt_generator.py for better handling of server processes, including cleanup on exit and signal handling.
- Enhanced prompt generation with detailed console output options, including enabling/disabling thinking mode and showing detailed debug information.
- Updated prompt_generator_options.py to allow connecting multiple images for analysis and added options for enabling thinking mode and console output.
- Minor cleanup in prompt_manager.py to remove unnecessary whitespace.
2025-12-15 04:10:10 -05:00
THE_BEAST\me 94feeb61c7 Update README and docs image for v1.7.0 2025-12-14 02:30:16 -05:00
THE_BEAST\me 3884f72552 Enhance prompt generation with three modes, custom image analysis, and model preferences; improve model selection and caching logic 2025-12-14 02:21:16 -05:00
THE_BEAST\me cae791a169 Enhance prompt generation with vision model support, JSON output, and improved model management
- Updated README to reflect new features and enhancements.
- Added Qwen3VL vision model support for image analysis.
- Introduced JSON output format option with structured scene breakdown.
- Implemented adjustable context size parameter (512-32768 tokens).
- Improved model selection logic and automatic mmproj file download for vision models.
- Enhanced prompt generator to handle image input and provide detailed descriptions.
- Updated requirements and version to 1.6.0.
2025-12-13 23:33:14 -05:00
THE_BEAST\me e6f56f3a75 Slight improvement to prompt generation rules.
Was too keen on adding text when not necesseray
2025-11-30 22:49:08 -05:00
THE_BEAST\me bc682b3680 Enhance LLM input handling and caching logic in PromptManager and PromptGenerator 2025-11-30 21:38:38 -05:00
Francois Beaudry 9982853cac Fix formatting of Llama.cpp installation note 2025-11-30 00:03:23 -05:00
THE_BEAST\me 7cc4478aa0 Version 1.5.0 - Introduced Prompt Generator and Options nodes with llama.cpp integration, enhanced prompt management features, and improved model handling. 2025-11-29 23:57:05 -05:00
64 changed files with 33134 additions and 395 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']
+20
View File
@@ -0,0 +1,20 @@
name: Publish to Comfy registry
on:
workflow_dispatch:
push:
branches:
- main
paths:
- "pyproject.toml"
jobs:
publish-node:
name: Publish Custom Node to registry
runs-on: ubuntu-latest
steps:
- name: Check out code
uses: actions/checkout@v4
- name: Publish Custom Node
uses: Comfy-Org/publish-node-action@main
with:
personal_access_token: ${{ secrets.REGISTRY_ACCESS_TOKEN }}
+1
View File
@@ -26,6 +26,7 @@ wheels/
# IDE files
.vscode/
.idea/
ComfyUI-Prompt-Manager.code-workspace
# OS files
.DS_Store
+674
View File
@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
+605 -99
View File
@@ -1,20 +1,146 @@
# 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 simple custom node for [ComfyUI](https://github.com/comfyanonymous/ComfyUI) that allows you to organize, manage, and save prompts into different categories. Useful for managing your prompt library and capturing outputs from LLM nodes.
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>
## Features
- **Category Organization**: Create and manage multiple categories to organize your prompts (e.g., Character, Style, Environment, Lighting, Mood)
### 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 (like LLM generators) and toggle between using them or your internal prompts
- **Direct Editing**: Edit prompts directly in the node or select from your saved library
- **Persistent Storage**: All prompts are saved in your ComfyUI user folder and persist across sessions
- **Pre-loaded Templates**: Comes with example prompts across various categories
- **Easy Management**: Delete categories or individual prompts with confirmation dialogs
- **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
@@ -27,102 +153,113 @@ A simple custom node for [ComfyUI](https://github.com/comfyanonymous/ComfyUI) th
```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.
3. Restart ComfyUI
6. Restart ComfyUI
## Usage
### Basic Usage
### Prompt Manager
1. **Add the Node**: Right-click in ComfyUI → Add Node → Prompt Manager → 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.
2. **Select a Category**: Use the dropdown to choose from your categories (Character, Style, Environment, etc.)
### Prompt Manager Advanced
3. **Choose a Prompt**: Select a saved prompt from the dropdown
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
4. **Use the Output**: Connect the output to any node that accepts text/string input
### Prompt Extractor
### Managing Prompts
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
#### Saving a Prompt
1. Type or paste your prompt into the text field (or have it connected from another node)
2. Click the **"Save Prompt"** button
3. Enter a name for your prompt
4. Click OK
> **Note**: If a prompt with the same name exists in the current category, you'll be asked to confirm before overwriting.
#### Creating a New Category
1. Click the **"New Category"** button
2. Enter a name for your category
3. Click OK
### Prompt Generator
#### Deleting a Category
1. Select the category you want to delete
2. Click the **"Del Category"** button
3. Confirm the deletion
**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
#### Deleting a Prompt
1. Select the prompt you want to delete
2. Click the **"Del Prompt"** button
3. Confirm the deletion
**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
### Using LLM Input Toggle
**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)
The node includes a toggle to switch between internal prompts and external LLM inputs:
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.
1. Connect an LLM output (or any text output) to the **"llm_input"** connector
2. Click the **"use llm input"** toggle to switch it ON
3. The prompt field will display the connected text (grayed out)
4. Run your workflow - the node will output the LLM text
5. Click **"Save Prompt"** to save the LLM-generated text to your library
6. Toggle OFF to switch back to your internal prompts
**Model Management**:
- Place gguf files in models/gguf folder
- Downloaded models are also placed in this folder.
**Notes:**
- The toggle only works when something is connected to `llm_input`
- When toggled ON, the text field becomes read-only and shows the external input
- When toggled OFF, it reverts to your selected internal prompt
**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)
## File Structure
## Requirements
```
comfyui-prompt-manager/
├── __init__.py # Node registration
├── prompt_manager.py # Main node logic and API endpoints
├── default_prompts.json # Default prompt templates
├── js/
│ └── prompt_manager.js # Frontend UI and interactions
└── README.md # This file
```
## Data Storage
Prompts are stored in:
```
ComfyUI/user/default/prompt_manager.json
```
The file is automatically created on first use, copying from `default_prompts.json`.
You can:
- Back up this file to save your prompt library
- Share it with others
- Edit it directly (with caution)
## Default Prompts
The node comes pre-loaded with example prompts.
These were added for testing purposes, feel free to modify or delete them to suit your needs!
## Tips & Tricks
### Workflow Organization
- Create categories that match your workflow (e.g., "Characters", "Backgrounds", "Styles")
- Use descriptive names for your prompts to find them easily later
- Regularly backup your `prompt_manager.json` file
### Editing Prompts
- You can edit prompts directly in the text field even when loaded from the library
- Changes are not saved automatically - click "Save Prompt" to update
- Use "Save Prompt" with the same name to overwrite an existing prompt
- ComfyUI
- Python 3.8+
- requests
- huggingface_hub
- psutil
- tqdm
- Pillow
- colorama
- llama-server (from llama.cpp)
## Troubleshooting
@@ -133,22 +270,391 @@ These were added for testing purposes, feel free to modify or delete them to sui
- **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 "text" input and run the workflow.
- **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 1.1.0
- Added LLM input toggle for easy switching between internal and external text sources
- Dedicated `llm_input` connector for external text
- Toggle prevents activation when no connection is present
- Text field becomes read-only when using external input
- Auto-reverts to internal prompt when toggle is turned off
- Fixed reload bug where toggle state wasn't applied on page load
### 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.0.1
### 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 management
- Prompt save/load functionality
- Category and prompt management
- LLM output integration
- Pre-loaded example prompts
- ComfyUI-style UI dialogs
+40 -8
View File
@@ -1,24 +1,56 @@
"""
ComfyUI Prompt Manager - A simple custom node for saving and reusing prompts
A prompt management system for ComfyUI with LLM input support
ComfyUI Prompt Manager - A comprehensive prompt and workflow management system for ComfyUI.
Features: prompt & workflow management, LoRA stacks, workflow extraction, workflow generation.
"""
__version__ = "1.1.0"
__version__ = "2.0.0"
__author__ = "François Beaudry"
__license__ = "MIT"
from .prompt_manager import PromptManagerNode
from .nodes.apply_lora import ApplyLoraPlusPlus
from .nodes.prompt_manager_adv import PromptManagerAdvanced
from .nodes.prompt_manager_basic import PromptManager
from .nodes.prompt_generator import PromptGenerator
from .nodes.prompt_generator_options import PromptGenOptions
from .nodes.prompt_extractor import PromptExtractor
from .nodes.prompt_extractor import WorkflowExtractor
from .nodes.workflow_builder import WorkflowBuilder
from .nodes.workflow_renderer import WorkflowRenderer
from .nodes.workflow_bridge import WorkflowBridge
from .nodes.workflow_model_loader import WorkflowModelLoader
from .nodes.workflow_manager import WorkflowManager
NODE_CLASS_MAPPINGS = {
"PromptManager": PromptManagerNode,
"PromptApplyLora": ApplyLoraPlusPlus,
"PromptManagerAdvanced": PromptManagerAdvanced,
"PromptManager": PromptManager,
"PromptGenerator": PromptGenerator,
"PromptGenOptions": PromptGenOptions,
"PromptExtractor": PromptExtractor,
"WorkflowExtractor": WorkflowExtractor,
"WorkflowBuilder": WorkflowBuilder,
"WorkflowRenderer": WorkflowRenderer,
"WorkflowBridge": WorkflowBridge,
"WorkflowModelLoader": WorkflowModelLoader,
"WorkflowManager": WorkflowManager,
}
NODE_DISPLAY_NAME_MAPPINGS = {
"PromptManager": "Prompt Manager",
"PromptApplyLora": "Apply LoRA++",
"PromptManagerAdvanced": "Prompt Manager",
"PromptManager": "Prompt Manager (Basic)",
"PromptGenerator": "Prompt Generator",
"PromptGenOptions": "Prompt Generator Options",
"PromptExtractor": "Prompt Extractor",
"WorkflowExtractor": "Workflow Extractor",
"WorkflowBuilder": "Workflow Builder",
"WorkflowRenderer": "Workflow Renderer",
"WorkflowBridge": "Workflow Bridge",
"WorkflowModelLoader": "Workflow Model Loader",
"WorkflowManager": "Workflow Manager",
}
WEB_DIRECTORY = "./js"
__all__ = ['NODE_CLASS_MAPPINGS', 'NODE_DISPLAY_NAME_MAPPINGS', 'WEB_DIRECTORY']
print("[PromptManager] Node registered successfully")
print("[PromptManager] Nodes registered: Apply LoRA++, Prompt Manager (Basic), Prompt Manager, Prompt Generator, Prompt Generator Options, Prompt Extractor, Workflow Extractor, Workflow Builder, Workflow Renderer, Workflow Bridge, Workflow Model Loader, Workflow Manager")
+38
View File
@@ -0,0 +1,38 @@
import sys, json, subprocess, io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace')
# Check videos with missing loader types
test_files = {
'DiffusionModelLoaderKJ': r'D:\ComfyUI-Dev\input\Workflow\Vids\2026_01_08_60FPS_00002.mp4',
'WanVideoModelLoader': r'D:\ComfyUI-Dev\input\Workflow\Vids\vid_00061.mp4',
'SeaArtUnetLoader': r'D:\ComfyUI-Dev\input\Workflow\Vids\25439d30-d0d7-4dd4-b64c-b46345c76351.mp4',
'CyberdyneModelHub': r'D:\ComfyUI-Dev\input\Workflow\Vids\d39dbdc3-f08c-44e1-bd4c-410ecb08d3c9.mp4',
'CheckpointInNum': r'D:\ComfyUI-Dev\input\Workflow\Vids\num__00168.mp4',
}
for label, f in test_files.items():
print(f"\n=== {label} ===")
r = subprocess.run(['ffprobe','-v','quiet','-print_format','json','-show_format',f], capture_output=True, text=True, timeout=10)
data = json.loads(r.stdout)
tags = data['format']['tags']
# Try direct tags first, then comment
prompt = tags.get('prompt')
if not prompt:
comment = tags.get('comment', '{}')
comment_data = json.loads(comment)
prompt = comment_data.get('prompt', '{}')
if isinstance(prompt, str):
prompt = json.loads(prompt)
targets = ['Diffusion', 'Wan', 'SeaArt', 'Cyberdyne', 'Checkpoint', 'UNET', 'Unet', 'Model']
for nid, ndata in prompt.items():
ct = ndata.get('class_type', '')
if 'Cyberdyne' in ct or ct == 'Wan_Cyberdyne_Genisys':
inputs = ndata.get('inputs', {})
inp_str = json.dumps(inputs)
if len(inp_str) > 800:
inp_str = inp_str[:800] + '...'
print(f" Node {nid}: {ct}")
print(f" inputs: {inp_str}")
-154
View File
@@ -1,24 +1,4 @@
{
"Character": {
"Cyberpunk Hacker Elite": {
"prompt": "A skilled cyberpunk hacker sitting in a dimly lit apartment surrounded by multiple holographic screens displaying code and data streams, wearing tactical tech-wear with embedded LED strips and circuit patterns, augmented reality glasses with information overlays, cybernetic arm implants with exposed mechanical components, messy workstation with scattered computer parts and energy drink cans, large window showing dystopian megacity skyline with towering skyscrapers covered in neon advertisements and holographic billboards, heavy rain creating atmospheric reflections, purple and cyan neon color palette, volumetric fog and light rays, highly detailed futuristic technology, photorealistic rendering, cyberpunk 2077 aesthetic, moody atmospheric lighting, 8k ultra detailed"
},
"Epic Fantasy Warrior": {
"prompt": "A powerful fantasy warrior standing in a heroic pose on a battlefield at dusk, wearing intricately detailed plate armor with ornate engravings and battle-worn scratches, muscular athletic build with defined features, holding a legendary glowing sword with runes etched along the blade, flowing cape billowing in the wind, dramatic cinematic lighting with rays of sunlight breaking through storm clouds, particles of dust and embers floating in the air, photorealistic rendering with exceptional attention to material details including metallic reflections on armor, leather straps and buckles, war paint on face, intense determined expression, epic fantasy art style, 8k ultra high resolution, masterpiece quality"
},
"Futuristic Sci-Fi Explorer": {
"prompt": "A lone futuristic explorer standing on the edge of an alien cliff overlooking a vast extraterrestrial landscape, wearing an advanced high-tech environmental suit with glowing blue energy lines and holographic display panels, sleek helmet with transparent visor showing determined face, multiple utility packs and scientific equipment attached to suit, alien planet with multiple moons visible in the purple-tinted sky, bioluminescent alien flora scattered across rocky terrain, dramatic volumetric lighting with atmospheric fog, neon accents and technological details, sense of wonder and discovery, photorealistic sci-fi concept art style, cinematic composition, 8k resolution, highly detailed textures on suit materials and alien environment"
},
"Mystical Elven Mage": {
"prompt": "An elegant elven sorcerer with flowing silver hair and luminescent purple eyes, wearing elaborate flowing robes made of enchanted fabric with intricate magical runes and celestial patterns, holding an ancient wooden staff topped with a glowing crystal, standing in a mystical forest clearing surrounded by floating magical orbs and swirling ethereal energy, ancient stone ruins covered in moss and glowing elvish inscriptions in background, fireflies and magical particles dancing through the air, moonlight filtering through dense canopy creating dappled light patterns, fantasy illustration style with painterly quality, rich jewel tones and magical bioluminescence, highly detailed character design, masterpiece quality, 8k resolution"
},
"Noble Medieval Knight": {
"prompt": "A distinguished medieval knight in full ceremonial plate armor standing in the grand hall of a castle, armor polished to a mirror shine with gold inlay and family crest emblazoned on chest plate, red velvet cape with golden trim, holding ornate longsword point-down in formal stance, helmet tucked under arm revealing weathered noble face with graying beard, stone castle interior with tall Gothic arched windows, sunlight streaming through stained glass creating colorful patterns on floor, heraldic banners hanging from walls, torch sconces providing warm ambient lighting, sense of honor and nobility, historical accuracy in armor design and architecture, oil painting aesthetic with rich colors, highly detailed, 4k quality"
},
"Post-Apocalyptic Survivor": {
"prompt": "A rugged post-apocalyptic survivor standing among ruins of a destroyed city, wearing makeshift armor cobbled together from scavenged materials including leather, metal plates, and tactical gear, face covered with weathered gas mask with cracked lenses, carrying a modified rifle and worn backpack full of supplies, background showing crumbling skyscrapers overgrown with vegetation, abandoned vehicles rusted and covered in vines, dramatic overcast sky with sun breaking through clouds, dust particles and debris floating in air, desaturated color palette with touches of rust orange and olive green, gritty realistic style, highly detailed weathering and wear on all materials, cinematic composition, 4k photorealistic quality"
}
},
"Composition": {
"Aerial Bird's Eye View": {
"prompt": "Dramatic overhead composition shot from directly above subject, unique bird's eye perspective offering unusual and striking viewpoint, flattened perspective creating abstract qualities and geometric patterns, symmetry and patterns visible from above, sense of scale with subject appearing small against larger environment, drone photography aesthetic with perfect stability, organized chaos of urban patterns or natural formations, top-down view revealing hidden relationships and structures, professional aerial photography with exceptional detail, sharp focus across entire frame, innovative perspective creating wow factor, cinematic quality, 8k ultra high resolution, perfect exposure and color balance"
@@ -76,139 +56,5 @@
"Underwater Lost City": {
"prompt": "An ancient sunken city deep beneath the ocean surface, classical Greek or Roman architecture colonized by colorful coral and marine life, crumbling marble columns and statues covered in barnacles and swaying sea kelp, schools of tropical fish swimming through broken archways, rays of sunlight penetrating from surface creating dramatic volumetric lighting through the water, particles of sediment floating in currents, giant sea turtles and manta rays gliding past ruins, preserved mosaics and frescoes still visible on walls, sense of lost grandeur and the passage of time, turquoise and deep blue water with caustic light patterns on surfaces, highly detailed underwater environment with accurate water physics and light scattering, photorealistic quality, 8k resolution"
}
},
"Illustrious": {
"Anime Girl Portrait": {
"prompt": "1girl. A beautiful anime girl gazing directly at the viewer with a gentle smile and soft expression on her face. Her long flowing hair frames delicate features. beautiful detailed eyes, long hair, flowing hair, hair between eyes, looking at viewer, slight smile, soft expression, detailed face, smooth skin, delicate features, jewelry, earrings, necklace, upper body, portrait, depth of field, bokeh, soft lighting, rim lighting, cinematic lighting, anime style, illustration, detailed background, blurred background, masterpiece"
},
"Beach Swimsuit Summer": {
"prompt": "1girl. A carefree girl enjoys a perfect summer day at the beach. Ocean waves lap at the shore behind her as she stands with a bright smile under the sunny sky. Water droplets glisten on her skin in the warm sunlight. bikini, swimsuit, beach, ocean, sea, waves, shore, sand, blue sky, summer, sunny, sunlight, lens flare, beach umbrella, palm tree, standing, hand on hip, wet, wet skin, water droplets, smile, happy, cheerful, straw hat, sun hat, sunglasses, long hair, ponytail, side-tie bikini bottom, frills, ribbon, beautiful detailed face, depth of field, blurry background, bokeh, bright colors, vibrant, warm colors, anime style, masterpiece"
},
"Café Reading Books": {
"prompt": "1girl. A peaceful scene of a girl absorbed in reading at a quiet café. Soft window light illuminates her book as steam rises gently from her cup of tea. The cozy atmosphere and comfortable setting create a perfect moment of tranquil relaxation. sitting, chair, table, café, coffee shop, indoor, window, window light, sunlight, soft lighting, warm lighting, cozy atmosphere, reading, book, holding book, open book, coffee cup, teacup, steam, casual clothes, sweater, cardigan, long sleeves, skirt, pantyhose, sitting cross-legged, relaxed, calm expression, gentle smile, long hair, side ponytail, hair ornament, bookshelf, books, plant, potted plant, depth of field, blurry background, bokeh, peaceful, comfortable, slice of life, anime style, masterpiece"
},
"Cyberpunk Street Scene": {
"prompt": "1girl. A lone figure stands in a rain-soaked cyberpunk street at night. Neon signs reflect off wet pavement while holographic displays flicker in the background. The cityscape towers above with its maze of skyscrapers and glowing advertisements. cyberpunk, neon lights, night, rain, wet, reflections, holographic display, hologram, cyber wear, mechanical parts, augmentation, headphones, hood, hood up, jacket, tech wear, city lights, cityscape, skyscraper, neon sign, japanese text, night sky, depth of field, blurry background, bokeh, rim lighting, ambient lighting, atmospheric, moody, cinematic angle, wide shot, street, alley, puddle, anime style, masterpiece"
},
"Dragon Girl Fantasy": {
"prompt": "1girl. A powerful dragon girl sits regally upon her throne within her treasure-filled lair. Flames and embers dance around her as her wings spread majestically. Her scales shimmer in the dramatic lighting, displaying both her fierce power and noble bearing. dragon girl, dragon horns, horns, dragon tail, tail, dragon wings, wings, scales, pointy ears, elf ears, long hair, very long hair, silver hair, white hair, red eyes, slit pupils, fangs, sharp teeth, claws, fantasy, armor, scale armor, dragon scale armor, dragon themed, castle, throne, dragon hoard, treasure, gold, gems, crystals, cave, lair, dramatic lighting, volumetric lighting, fire, flames, embers, particles, epic, powerful, regal, anime style, detailed scales, masterpiece"
},
"Elegant Fantasy Princess": {
"prompt": "1girl. A regal princess sits gracefully upon her ornate throne in the grand castle hall. Sunlight streams through magnificent stained glass windows, illuminating her elegant gown and sparkling jewelry. She embodies nobility and grace with her gentle smile and refined posture. princess, royalty, crown, tiara, jewelry, ornate jewelry, necklace, earrings, bracelet, elegant dress, ballgown, frills, lace trim, ribbon, puffy sleeves, long sleeves, detached sleeves, white gloves, long gloves, very long hair, wavy hair, blonde hair, blue eyes, detailed eyes, gentle smile, graceful, sitting, throne, castle interior, grand hall, chandelier, stained glass, window, sunlight, light rays, volumetric lighting, depth of field, bokeh, detailed background, fantasy, medieval, regal, noble, anime style, masterpiece"
},
"Fantasy Battle Scene": {
"prompt": "multiple girls, multiple boys. An epic battle scene unfolds with multiple warriors locked in intense combat. Fighters strike dynamic poses with weapons raised and magic crackling through the air. Hair and capes billow in the wind as debris flies through the scene. dynamic pose, action scene, fighting stance, floating hair, motion blur, motion lines, dramatic angle, low angle, dutch angle, wielding sword, magic spell, casting magic, glowing weapon, energy effects, particle effects, debris, dust cloud, destruction, epic scene, cinematic composition, volumetric lighting, dramatic lighting, lens flare, depth of field, fantasy armor, detailed armor, cape, flowing clothes, wind, anime style, masterpiece"
},
"Gothic Lolita Fashion": {
"prompt": "1girl. An elegant gothic lolita stands before a cathedral in her elaborate black dress. She holds a single red rose with pale graceful hands. The dramatic lighting filtering through stained glass creates an atmosphere of dark beauty and refined elegance. gothic lolita, lolita fashion, gothic dress, black dress, frills, lace, ruffles, ribbon, bow, puffy sleeves, long sleeves, detached sleeves, headdress, mini crown, cross, cross necklace, choker, black thighhighs, platform footwear, parasol, lace parasol, very long hair, twin tails, drill hair, curly hair, black hair, red eyes, pale skin, elegant, graceful pose, standing, rose, red rose, holding rose, church, cathedral, stained glass, gothic architecture, dim lighting, dramatic lighting, depth of field, detailed background, anime style, masterpiece"
},
"Idol Performance Stage": {
"prompt": "1girl. An energetic idol performs on stage before a cheering crowd. Colorful spotlights illuminate her as she sings and dances with boundless enthusiasm. Sparkles and glitter fill the air as she strikes a dynamic pose with her microphone. idol, stage outfit, frills, lace, ribbon, bow, gloves, white gloves, microphone, holding microphone, singing, performing, stage, concert, stage lights, spotlights, colorful lighting, dynamic lighting, dramatic lighting, audience, crowd, cheering, energetic, dynamic pose, dancing, motion blur, sparkles, glitter, star \\(symbol\\), heart \\(symbol\\), twin tails, very long hair, gradient hair, colorful hair, bright colors, vibrant colors, smile, wink, one eye closed, cheerful, happy, full body, depth of field, anime style, masterpiece"
},
"Kimono Traditional Japan": {
"prompt": "1girl. An elegant woman in traditional kimono walks gracefully through a beautiful Japanese garden. Autumn leaves drift down around her as koi swim in the pond beside a stone path. The golden hour light creates a warm and culturally rich atmosphere. kimono, japanese clothes, traditional clothes, obi, sash, wide sleeves, long sleeves, floral print, flower pattern, hair ornament, hair flower, kanzashi, long hair, black hair, brown hair, updo, hair bun, elegant, graceful, standing, walking, outdoor, japanese garden, garden, stone path, bridge, pond, koi, water, trees, maple tree, autumn leaves, red leaves, falling leaves, torii gate, shrine, lantern, paper lantern, sunset, golden hour, warm lighting, soft lighting, depth of field, blurry background, traditional, cultural, anime style, masterpiece"
},
"Magical Girl Transformation": {
"prompt": "1girl. A magical girl undergoes her transformation sequence in a dazzling display of light and sparkles. Ribbons and magical particles swirl around her as her elaborate costume materializes. She strikes a heroic pose with outstretched hand against a radiant starburst background. magical girl, transformation sequence, sparkles, glowing, light particles, ribbon, frills, lace, detailed outfit, elaborate costume, twin tails, very long hair, gradient hair, multicolored hair, colorful, vibrant colors, bright colors, star \\(symbol\\), heart \\(symbol\\), dynamic pose, outstretched hand, raised hand, full body, floating, levitating, white background, gradient background, starburst background, bloom effect, light rays, god rays, anime style, masterpiece"
},
"Maid Cafe Waitress": {
"prompt": "1girl. A cheerful maid waitress serves customers at a cozy cafe with a warm welcoming smile. Soft sunlight filters through the windows as she carries a tray with practiced grace. Her frilly uniform and happy expression create an inviting atmosphere. maid, maid headdress, maid apron, frills, lace, ribbon, bow, short sleeves, puffy sleeves, black dress, white apron, wrist cuffs, thighhighs, mary janes, holding tray, serving, indoor, cafe, detailed background, blurry background, depth of field, soft lighting, warm lighting, sunlight, window light, smiling, cheerful, happy, welcoming expression, looking at viewer, anime style, masterpiece"
},
"Samurai Warrior": {
"prompt": "1boy. A skilled samurai warrior stands ready in a dynamic pose, hand on his katana. Cherry blossom petals swirl around him in the wind as the setting sun casts dramatic lighting across his detailed armor. His expression shows unwavering determination and honor. samurai, armor, japanese armor, shoulder armor, armored dress, hakama, hakama skirt, katana, sword, sheathed, holding sword, ponytail, long hair, black hair, serious expression, determined look, standing, dynamic pose, action pose, cherry blossoms, petals, falling petals, torii, shrine, japanese architecture, sunset, dramatic lighting, rim lighting, lens flare, depth of field, wind, dramatic angle, low angle, cinematic composition, anime style, detailed armor, masterpiece"
},
"School Uniform Casual": {
"prompt": "1girl. A cheerful schoolgirl walks through the school grounds on a beautiful spring day. Cherry blossom petals dance in the wind around her as she carries her school bag. The sun shines warmly and her expression is gentle and happy. school uniform, serafuku, sailor collar, pleated skirt, short sleeves, long sleeves, cardigan, bow, bowtie, ribbon, neck ribbon, thighhighs, black thighhighs, loafers, bag, school bag, shoulder bag, standing, walking, outdoors, school, school building, cherry blossoms, falling petals, blue sky, clouds, sunlight, dappled sunlight, soft lighting, wind, wind lift, depth of field, blurry background, smile, happy, gentle expression, anime style, masterpiece"
},
"Shrine Maiden Miko": {
"prompt": "1girl. A serene shrine maiden performs her duties at a peaceful shrine surrounded by nature. Dappled sunlight filters through the trees as cherry blossom petals gently fall around her. She holds a sacred paper charm with a gentle smile and peaceful expression. miko, shrine maiden, traditional clothes, japanese clothes, red hakama, hakama skirt, white kimono, wide sleeves, long sleeves, hair bow, red ribbon, hair tubes, long hair, black hair, brown hair, brown eyes, gentle smile, peaceful expression, holding ofuda, paper charm, shrine, torii gate, stone lantern, japanese architecture, outdoor, nature, forest, trees, sunlight, light rays, dappled sunlight, god rays, peaceful atmosphere, depth of field, soft lighting, cherry blossoms, petals, falling petals, anime style, masterpiece"
},
"Sleeping Bedroom Night": {
"prompt": "1girl. A peaceful sleeping scene bathed in gentle moonlight streaming through the window. The girl rests quietly under soft covers with her hair spread across the pillow. Stars twinkle in the night sky visible through the curtains as she dreams peacefully. sleeping, lying, on side, on bed, bed, bedroom, pillow, blanket, sheet, under covers, pajamas, nightgown, sleepwear, closed eyes, peaceful expression, long hair, messy hair, hair over pillow, indoor, window, curtains, moonlight, night, night sky, stars, starry sky, moon, crescent moon, dim lighting, soft lighting, ambient lighting, calm atmosphere, quiet, serene, peaceful, plushie, stuffed toy, stuffed animal, depth of field, anime style, masterpiece"
}
},
"Lighting": {
"Cyberpunk Neon Atmosphere": {
"prompt": "Vibrant cyberpunk neon lighting with dominant cyan, magenta, and purple color palette, multiple colored light sources creating complex overlapping shadows and color mixing, neon tubes and LED strips casting intense saturated light, strong rim lighting outlining subjects with colored glows, wet surfaces reflecting and multiplying light sources, volumetric fog and haze making light beams visible, high contrast between bright neon elements and deep dark shadows, futuristic atmospheric lighting with sci-fi mood, color temperature mixing cool blue neons with warm orange accents, Blade Runner inspired aesthetic, moody and atmospheric, cinematic lighting design, photorealistic rendering, 8k quality"
},
"Dramatic Rembrandt Lighting": {
"prompt": "Classic Rembrandt studio lighting setup with strong directional key light at 45-degree angle creating distinctive triangle of light under eye on shadow side of face, deep rich shadows with subtle fill light preserving detail, high contrast ratio for dramatic mood, rim light separating subject from dark background, chiaroscuro technique emphasizing form and dimension through light and shadow, professionally controlled studio environment, classic portrait photography aesthetic, black background emphasizing subject, attention to catchlights in eyes, subtle hair light adding separation, timeless dramatic quality reminiscent of Dutch Golden Age paintings, medium format camera quality, tack-sharp focus, 4k resolution"
},
"Firelight and Shadows": {
"prompt": "Warm intimate lighting from crackling fire as primary light source, rich orange and amber tones dancing across surfaces, dynamic moving shadows creating flickering atmospheric effect, high contrast with deep blacks in areas beyond firelight reach, sense of warmth and comfort, practical light source visible in scene showing glowing embers and flames, subsurface scattering on translucent objects near fire, traditional campfire or hearth setting, reminiscent of classical genre paintings, color temperature around 1800K for authentic firelight, soft smoky haze adding atmosphere, cozy intimate mood, photorealistic fire simulation, highly detailed, 4k quality"
},
"Golden Hour Magic": {
"prompt": "Golden hour lighting during the last hour before sunset, warm golden and amber tones bathing entire scene in beautiful soft light, long dramatic shadows stretching across ground, sun low on horizon creating rim lighting that outlines subjects with glowing edges, soft diffused quality that enhances colors and reduces contrast, sky painted in gradients of gold, orange, pink, and purple, clouds illuminated from below with warm tones, perfect lighting conditions for photography with flattering warm color temperature around 3500K, atmospheric haze adding depth and dimension, lens flare and subtle bloom adding magical quality, professional landscape photography aesthetic, HDR processing for maximum dynamic range, masterpiece quality lighting, 8k resolution"
},
"Mystical Moonlight": {
"prompt": "Ethereal moonlight illuminating scene with cool silvery-blue tones, full moon visible in clear night sky providing primary light source, soft shadows with blue-tinted quality, stars visible in background, atmospheric mist catching and scattering moonlight creating volumetric lighting effects, subtle bioluminescent elements adding touches of green and blue glow, romantic and magical atmosphere, cool color temperature around 4100K, high contrast between moonlit areas and deep shadows, sense of mystery and nocturnal beauty, long exposure photography aesthetic capturing movement of clouds, highly detailed night scene with proper exposure for nighttime conditions, cinematic quality, 8k resolution"
},
"Overcast Diffused Light": {
"prompt": "Soft even illumination from completely overcast sky creating natural softbox effect, shadowless lighting with very gradual subtle transitions, muted desaturated color palette, cool color temperature around 6500K with slight blue-gray cast, perfect even exposure across entire scene, detail preserved in all areas, moody atmospheric quality, sense of calm or melancholy, ideal for showing texture and form without harsh shadows, professional product photography aesthetic, fog or mist adding layers of atmospheric perspective, minimalist Scandinavian lighting aesthetic, clean and modern feel, high dynamic range with subtle gradations, photorealistic rendering, 8k resolution"
},
"Soft Northern Window Light": {
"prompt": "Beautiful soft natural light coming from large northern-facing window, gentle diffused illumination without harsh shadows or direct sunlight, even light distribution creating subtle gradations and soft wraparound lighting, cool color temperature around 5500K with slight blue bias, perfect for accurate color rendition, creates natural realistic appearance, soft shadows with gradual transitions, sense of calm and serenity, ideal for portraits and still life, professional photography studio aesthetic using natural light only, subtle environmental reflections adding fill light, maintains detail in both highlights and shadows, peaceful morning light quality, high dynamic range, 4k photographic quality"
},
"Volumetric God Rays": {
"prompt": "Dramatic volumetric lighting with strong directional sunbeams breaking through clouds or canopy creating visible shafts of light, atmospheric perspective with dust particles, moisture, or fog making light beams clearly visible, high contrast between illuminated rays and darker surrounding areas, sense of divine or spiritual quality, particles floating through light beams catching illumination, depth and dimension created by layered light and shadow, cathedral-like quality to lighting, powerful emotional impact, reminiscent of classical religious paintings, physically accurate light scattering and atmospheric effects, subtle color gradation in light beams from warm to cool, cinematic composition, photorealistic rendering, 8k ultra quality"
}
},
"Mood": {
"Dark and Ominous": {
"prompt": "Dark foreboding atmosphere with ominous threatening mood, deep shadows dominating composition with limited light sources, desaturated color palette with emphasis on blacks and dark grays, occasional blood red or sickly green accent colors, sense of danger and unease, heavy atmospheric fog or mist obscuring details, Gothic horror aesthetic, dramatic high contrast lighting, unsettling asymmetrical composition, inspired by horror film cinematography and dark fantasy art, volumetric shadows, psychological tension, photorealistic rendering with painterly qualities, 4k quality"
},
"Energetic and Vibrant": {
"prompt": "High-energy dynamic atmosphere bursting with vitality and motion, saturated vibrant colors creating visual excitement, bold contrasts between warm and cool tones, sense of movement and activity throughout composition, dynamic lighting with multiple colorful sources, particles and elements in motion suggesting kinetic energy, fast-paced feeling with diagonal lines and angular composition, celebration of life and action, inspired by pop art and contemporary street photography, youthful exuberant quality, festival or carnival atmosphere, professional commercial photography aesthetic with punchy color grading, sharp details capturing peak moments, 8k ultra high resolution"
},
"Epic and Grandiose": {
"prompt": "Monumental epic atmosphere emphasizing vast scale and dramatic spectacle, sweeping panoramic composition showcasing impressive scope, dramatic sky with storm clouds or spectacular sunset, towering mountains, massive architecture, or other elements dwarfing human scale, sense of awe and sublime beauty, inspired by romantic landscape painting and epic cinema, heroic quality with cinematic grandeur, professional landscape photography with maximum dynamic range, deep depth of field capturing detail from foreground to distant horizon, powerful emotional impact, larger-than-life presence, volumetric lighting with dramatic god rays, rich saturated colors or moody monochromatic palette, 8k ultra high resolution capturing every magnificent detail"
},
"Ethereal and Dreamlike": {
"prompt": "Otherworldly ethereal atmosphere with dreamlike surreal quality, soft diffused lighting creating glowing luminous effect, pale pastel colors or monochromatic schemes, subtle gradients and smooth transitions, fog or mist creating atmospheric depth and mystery, sense of floating or weightlessness, influenced by symbolist painting and fine art photography, magical realism aesthetic, elements of fantasy and imagination, translucent overlapping layers, bokeh and soft focus creating painterly quality, gentle peaceful mood with touch of unreality, professional fine art composition, heavenly or celestial atmosphere, delicate beauty and fragility, museum quality presentation, 4k resolution with exceptional subtlety"
},
"Gritty and Raw": {
"prompt": "Harsh gritty atmosphere emphasizing reality and unpolished authenticity, high contrast lighting with deep blacks and bright highlights, desaturated or monochromatic color palette, visible texture and grain adding tactile quality, urban decay or industrial elements, sense of struggle and perseverance, influenced by documentary photography and photojournalism, uncompromising realistic approach, environmental portraits showing character and history, weathered surfaces and worn materials, professional reportage aesthetic, honest unflinching perspective, dramatic shadows and harsh light, imperfections celebrated rather than hidden, strong emotional impact, cinematic noir quality, 4k resolution with sharp detail capturing every texture"
},
"Melancholic and Nostalgic": {
"prompt": "Bittersweet melancholic atmosphere evoking memories and longing for the past, muted desaturated colors with vintage film aesthetic, soft diffused lighting creating dreamy quality, slight vignetting and faded appearance suggesting passage of time, autumnal or twilight color palette with browns, oranges, and muted blues, sense of solitude and quiet reflection, abandoned or weathered elements suggesting history, inspired by fine art photography and classical painting, emotional depth and introspective quality, gentle sadness mixed with beauty, analog film grain texture, soft focus areas creating romantic haze, timeless contemplative mood, 4k artistic quality"
},
"Mysterious and Enigmatic": {
"prompt": "Mysterious atmospheric quality filled with intrigue and unanswered questions, strategic use of shadows and partial concealment, fog or mist obscuring details and creating layers of depth, cool color temperature with blues, purples, and teals, selective lighting revealing only portions of scene, sense of hidden secrets and untold stories, influenced by film noir and gothic romanticism, dramatic chiaroscuro lighting, silhouettes and backlighting creating ambiguity, professional cinematic atmosphere, elements of the unknown, otherworldly quality, photorealistic rendering with artistic interpretation, high contrast between light and dark areas, 8k resolution with exceptional atmospheric detail"
},
"Peaceful and Serene": {
"prompt": "Calm peaceful atmosphere evoking tranquility and contentment, soft gentle lighting with harmonious balanced colors, pastel or muted earth tone palette, symmetrical or balanced composition creating visual harmony, natural elements like water or sky prominent, sense of stillness and timelessness, meditative quality, inspired by romantic landscape paintings and zen philosophy, warm and inviting feeling, perfect for relaxation and contemplation, subtle gradients and smooth transitions, professional fine art photography aesthetic, museum quality, 8k resolution"
},
"Warm and Inviting": {
"prompt": "Cozy warm atmosphere radiating comfort and hospitality, golden hour lighting or warm interior illumination, rich warm color palette dominated by oranges, yellows, and earth tones, soft shadows creating gentle dimensionality, sense of home and belonging, intimate scale and human-friendly spaces, natural materials like wood and fabric prominent, influenced by lifestyle photography and Scandinavian hygge aesthetic, welcoming emotional quality, perfect for evoking feelings of safety and contentment, professional interior photography with careful attention to ambiance, subtle texture details, inviting composition encouraging viewer to enter scene, 4k quality with warm color grading"
},
"Whimsical and Playful": {
"prompt": "Lighthearted whimsical atmosphere filled with joy and imagination, bright cheerful colors with unexpected combinations, playful composition with tilted angles or unusual perspectives, sense of fun and childlike wonder, elements of surprise and delight, influenced by children's book illustration and contemporary art, fantastical touches mixing reality with imagination, professional commercial photography with creative flair, bouncing light and colorful accents, informal spontaneous quality, sense of movement and energy, optimistic uplifting mood, creative use of props and staging, vibrant saturated colors, sharp focus on delightful details, 8k resolution with exceptional color accuracy and brightness"
}
},
"Style": {
"Cinematic Film Quality": {
"prompt": "Cinematic film photography style with anamorphic lens characteristics, dramatic shallow depth of field with beautiful bokeh, professional color grading with teal and orange tones, subtle film grain texture, volumetric lighting with god rays and atmospheric haze, dynamic composition following rule of thirds, high contrast lighting with deep shadows and bright highlights, 2.39:1 aspect ratio letterbox framing, shot on ARRI Alexa 65, photorealistic rendering, 8k resolution, masterpiece quality with exceptional attention to lighting and atmosphere"
},
"Classic Oil Painting": {
"prompt": "Traditional oil painting style in the manner of old masters, rich saturated colors with deep shadows and luminous highlights, visible brushwork with thick impasto in light areas and thin glazes in shadows, classical composition with careful attention to form and anatomy, chiaroscuro lighting technique, warm earth tone palette with selective use of vibrant colors, painted on linen canvas with visible texture, museum quality with craquelure aging effects, Renaissance and Baroque artistic influences, painterly realism, masterwork quality worthy of gallery exhibition"
},
"Concept Art Illustration": {
"prompt": "Professional concept art illustration style used in AAA video game and film production, dynamic composition with strong focal point, atmospheric perspective with detailed foreground and painterly background, digital painting technique with custom brushes, strategic use of lighting to guide viewer's eye, color script with mood-appropriate palette, blend of realistic rendering and artistic interpretation, subtle texture overlays, clean lines with detailed callouts and annotations where needed, portfolio-quality artwork, 4k resolution optimized for production pipeline, industry-standard visual development artwork"
},
"Detailed Watercolor Art": {
"prompt": "Professional watercolor painting technique with translucent layered washes, delicate color transitions and gradients, wet-on-wet blending creating soft atmospheric effects, strategic use of white space and paper texture showing through, detailed foreground elements with looser background washes, granulation and blooming effects in pigments, cold-press watercolor paper texture, artistic mastery of water control, luminous transparent colors, traditional botanical illustration precision combined with loose expressive passages, flowing organic shapes, high-end art print quality, 300 DPI resolution"
},
"Impressionist Painting": {
"prompt": "Impressionist oil painting style reminiscent of Claude Monet and Pierre-Auguste Renoir, visible loose brushstrokes with textured impasto technique, vibrant color palette with emphasis on light and its changing qualities, dappled sunlight effects, soft edges and forms that blend together, focus on capturing momentary impression rather than fine details, colors applied in short strokes of pure unmixed paint, canvas texture visible, plein air painting aesthetic, masterful use of complementary colors, atmospheric perspective, traditional fine art quality, museum-worthy composition"
},
"Japanese Ukiyo-e Woodblock": {
"prompt": "Traditional Japanese ukiyo-e woodblock print style, bold outlines with flat areas of color, limited color palette featuring indigo blues, vermillion reds, and ivory, stylized clouds and waves with distinctive patterns, attention to textile patterns and decorative elements, asymmetrical composition with strong diagonals, influence of Hokusai and Hiroshige, grain texture of woodblock printing, subtle color gradations through bokashi technique, Japanese aesthetic principles of wabi-sabi and mono no aware, artistic quality of Edo period prints, suitable for museum collection"
},
"Ultra Photorealistic": {
"prompt": "Ultra photorealistic rendering with exceptional attention to every minute detail, 8k resolution with pixel-perfect clarity, physically accurate materials and lighting using ray tracing technology, subsurface scattering on skin and translucent materials, realistic depth of field and chromatic aberration, perfect exposure with natural lighting, micro-details including skin pores, fabric weave patterns, metal scratches and imperfections, dust particles in air, moisture and reflections, professional photography composition, shot with Canon EOS R5 with 85mm f/1.2 lens, indistinguishable from high-end commercial photography"
},
"Vintage Analog Photography": {
"prompt": "Vintage analog film photography aesthetic, shot on Kodak Portra 400 or Fujifilm Pro 400H film stock, natural grain structure, slightly faded colors with characteristic film color shifts, vignetting on corners, subtle light leaks and lens flares, soft focus dreamy quality, dated timestamp or border frame, nostalgic 1970s-1990s color palette, imperfect exposure with authentic film limitations, scanned from 35mm negatives, warm golden tones, authentic vintage photograph appearance with all the charm and imperfections of film photography"
}
}
}
+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);
};
```
Binary file not shown.

After

Width:  |  Height:  |  Size: 387 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 766 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 66 KiB

After

Width:  |  Height:  |  Size: 450 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 120 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 229 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 359 KiB

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

After

Width:  |  Height:  |  Size: 267 KiB

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

After

Width:  |  Height:  |  Size: 254 KiB

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

After

Width:  |  Height:  |  Size: 229 KiB

File diff suppressed because one or more lines are too long
+767
View File
@@ -0,0 +1,767 @@
/**
* File Browser Modal for PromptExtractor
* Shows thumbnails of files in input directory
*/
import { PM_UI_PALETTE as UI } from './ui_palette.js';
// Track current subfolder for navigation
let currentSubfolder = '';
// Track current source folder (input or output)
let currentSourceFolder = 'input';
export function createFileBrowserModal(currentFile, onFileSelect, sourceFolder) {
// Store source folder
currentSourceFolder = sourceFolder || 'input';
// If a file is currently selected and lives in a subfolder, open in that folder
if (currentFile && currentFile.includes('/')) {
currentSubfolder = currentFile.substring(0, currentFile.lastIndexOf('/'));
} else {
currentSubfolder = '';
}
// Create modal overlay
const overlay = document.createElement('div');
overlay.className = 'prompt-extractor-browser-overlay';
overlay.style.cssText = `
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: ${UI.overlay};
display: flex;
align-items: center;
justify-content: center;
z-index: 10000;
`;
// Create modal container (match PromptManagerAdvanced styling)
const modal = document.createElement('div');
modal.className = 'prompt-extractor-browser-modal';
modal.style.cssText = `
background: ${UI.panel};
border: 1px solid ${UI.panelBorder};
border-radius: 6px;
width: 90%;
max-width: 1200px;
height: 80%;
max-height: 800px;
display: flex;
flex-direction: column;
overflow: hidden;
`;
// Create header
const header = document.createElement('div');
header.style.cssText = `
padding: 15px 20px;
border-bottom: 1px solid ${UI.sectionBorder};
display: flex;
flex-direction: column;
gap: 8px;
`;
const topRow = document.createElement('div');
topRow.style.cssText = 'display: flex; justify-content: space-between; align-items: center;';
topRow.innerHTML = `
<h3 style="margin: 0; color: #d3d7de;">Select File from ${currentSourceFolder === 'output' ? 'Output' : 'Input'} Folder</h3>
<div style="display: flex; gap: 10px; align-items: center;">
<button class="regenerate-cache-btn" style="
background: ${UI.buttonBg};
border: 1px solid ${UI.inputBorder};
border-radius: 6px;
color: #ccc;
padding: 5px 12px;
cursor: pointer;
font-size: 12px;
">Regenerate Cache</button>
<button class="close-btn" style="
background: none;
border: none;
color: #aaa;
font-size: 24px;
cursor: pointer;
padding: 0;
width: 30px;
height: 30px;
">×</button>
</div>
`;
const breadcrumb = document.createElement('div');
breadcrumb.className = 'folder-breadcrumb';
breadcrumb.style.cssText = `font-size: 12px; color: ${UI.textHint}; cursor: pointer;`;
breadcrumb.textContent = `${currentSourceFolder}/`;
breadcrumb.onclick = () => {
if (currentSubfolder) {
currentSubfolder = '';
loadFileThumbnails(gridContainer, currentFile, onFileSelect, overlay, breadcrumb);
}
};
header.appendChild(topRow);
header.appendChild(breadcrumb);
// Create search/filter bar
const filterBar = document.createElement('div');
filterBar.style.cssText = `
padding: 10px 20px;
border-bottom: 1px solid ${UI.sectionBorder};
display: flex;
gap: 10px;
`;
filterBar.innerHTML = `
<input type="text" placeholder="Search files..." class="search-input" style="
flex: 1;
padding: 8px 12px;
background: ${UI.inputBg};
border: 1px solid ${UI.inputBorder};
border-radius: 6px;
color: #ccc;
">
<select class="filter-type" style="
padding: 8px 12px;
background: ${UI.inputBg};
border: 1px solid ${UI.inputBorder};
border-radius: 6px;
color: #ccc;
">
<option value="all">All Files</option>
<option value="image">Images</option>
<option value="video">Videos</option>
<option value="json">JSON</option>
</select>
`;
// Create thumbnail grid container
const gridContainer = document.createElement('div');
gridContainer.className = 'thumbnail-grid';
gridContainer.style.cssText = `
flex: 1;
overflow-y: auto;
padding: 20px;
display: grid;
grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
gap: 15px;
align-content: start;
`;
// Create loading indicator
const loading = document.createElement('div');
loading.style.cssText = `
text-align: center;
padding: 40px;
color: #aaa;
`;
loading.textContent = 'Loading files...';
gridContainer.appendChild(loading);
// Assemble modal
modal.appendChild(header);
modal.appendChild(filterBar);
modal.appendChild(gridContainer);
overlay.appendChild(modal);
// Prevent right-click context menu everywhere in the browser
// (video thumbnails have their own handler that will show the refresh menu)
overlay.oncontextmenu = (e) => {
e.preventDefault();
return false;
};
// Close button handler
const closeBtn = topRow.querySelector('.close-btn');
closeBtn.onclick = () => document.body.removeChild(overlay);
overlay.onclick = (e) => {
if (e.target === overlay) document.body.removeChild(overlay);
};
// Regenerate cache button handler
const regenerateCacheBtn = topRow.querySelector('.regenerate-cache-btn');
regenerateCacheBtn.onclick = () => {
clearThumbnailCache();
// Reload thumbnails to regenerate them
loadFileThumbnails(gridContainer, currentFile, onFileSelect, overlay, breadcrumb);
};
// Add to DOM
document.body.appendChild(overlay);
// Load files
loadFileThumbnails(gridContainer, currentFile, onFileSelect, overlay, breadcrumb);
// Setup search/filter
const searchInput = filterBar.querySelector('.search-input');
const filterType = filterBar.querySelector('.filter-type');
searchInput.oninput = () => filterThumbnails(gridContainer, searchInput.value, filterType.value);
filterType.onchange = () => filterThumbnails(gridContainer, searchInput.value, filterType.value);
}
async function loadFileThumbnails(container, currentFile, onFileSelect, overlay, breadcrumbElement) {
try {
// Update breadcrumb
if (!currentSubfolder) {
breadcrumbElement.textContent = `${currentSourceFolder}/`;
} else {
breadcrumbElement.textContent = `${currentSourceFolder}/${currentSubfolder}/`;
}
// Fetch file list from server
const response = await fetch(`/prompt-extractor/list-files?source=${encodeURIComponent(currentSourceFolder)}`);
const data = await response.json();
container.innerHTML = '';
if (!data.files || data.files.length === 0) {
container.innerHTML = '<div style="text-align: center; padding: 40px; color: #aaa;">No files found in ' + currentSourceFolder + ' directory</div>';
return;
}
// Get all files with their full paths
const allFiles = data.files.filter(f => f !== '(none)');
// Filter files/folders for current directory
const currentFiles = [];
const subfolders = new Set();
const prefix = currentSubfolder ? currentSubfolder + '/' : '';
allFiles.forEach(filepath => {
if (filepath.startsWith(prefix)) {
const remainder = filepath.substring(prefix.length);
const slashIndex = remainder.indexOf('/');
if (slashIndex === -1) {
// It's a file in current directory
currentFiles.push(filepath);
} else {
// It's in a subdirectory - extract folder name
const folderName = remainder.substring(0, slashIndex);
subfolders.add(folderName);
}
}
});
// Add "back" button if in subfolder
if (currentSubfolder) {
const backItem = createBackItem(container, currentFile, onFileSelect, overlay, breadcrumbElement);
container.appendChild(backItem);
}
// Add folder items
Array.from(subfolders).sort().forEach(folderName => {
const folderItem = createFolderItem(folderName, container, currentFile, onFileSelect, overlay, breadcrumbElement);
container.appendChild(folderItem);
});
// Create thumbnail for each file
currentFiles.forEach(filename => {
const item = createThumbnailItem(filename, currentFile, onFileSelect, overlay);
container.appendChild(item);
});
// Scroll to the currently selected file
if (currentFile) {
const selectedItem = container.querySelector(`.thumbnail-item[data-filename="${CSS.escape(currentFile)}"]`);
if (selectedItem) {
// Use requestAnimationFrame to ensure layout is complete before scrolling
requestAnimationFrame(() => {
selectedItem.scrollIntoView({ block: 'center', behavior: 'instant' });
});
}
}
} catch (error) {
console.error('[FileBrowser] Error loading files:', error);
container.innerHTML = '<div style="text-align: center; padding: 40px; color: rgba(220, 53, 69, 0.9);">Error loading files</div>';
}
}
function createBackItem(container, currentFile, onFileSelect, overlay, breadcrumbElement) {
const item = document.createElement('div');
item.className = 'folder-item';
item.style.cssText = `
background: ${UI.cardBg};
border: 1px solid ${UI.panelBorder};
border-radius: 6px;
padding: 8px;
cursor: pointer;
transition: all 0.15s ease;
display: flex;
flex-direction: column;
gap: 8px;
`;
const preview = document.createElement('div');
preview.style.cssText = `
width: 100%;
height: 150px;
background: rgba(16, 18, 22, 0.6);
border-radius: 4px;
display: flex;
align-items: center;
justify-content: center;
font-size: 64px;
`;
preview.textContent = '←';
const label = document.createElement('div');
label.textContent = 'Back';
label.style.cssText = `
font-size: 12px;
color: #ccc;
text-align: center;
`;
item.appendChild(preview);
item.appendChild(label);
item.onmouseenter = () => {
item.style.borderColor = UI.accentBorder;
item.style.transform = 'translateY(-2px)';
item.style.background = UI.accentSoft;
};
item.onmouseleave = () => {
item.style.borderColor = UI.panelBorder;
item.style.transform = 'translateY(0)';
item.style.background = UI.cardBg;
};
item.onclick = () => {
// Go up one level
const parts = currentSubfolder.split('/');
parts.pop();
currentSubfolder = parts.join('/');
loadFileThumbnails(container, currentFile, onFileSelect, overlay, breadcrumbElement);
};
return item;
}
function createFolderItem(folderName, container, currentFile, onFileSelect, overlay, breadcrumbElement) {
const item = document.createElement('div');
item.className = 'folder-item';
item.style.cssText = `
background: rgba(45, 55, 72, 0.7);
border: 1px solid rgba(226, 232, 240, 0.2);
border-radius: 6px;
padding: 8px;
cursor: pointer;
transition: all 0.15s ease;
display: flex;
flex-direction: column;
gap: 8px;
`;
const preview = document.createElement('div');
preview.style.cssText = `
width: 100%;
height: 150px;
background: rgba(0, 0, 0, 0.5);
border-radius: 4px;
display: flex;
align-items: center;
justify-content: center;
font-size: 64px;
`;
preview.textContent = '📁';
const label = document.createElement('div');
label.textContent = folderName;
label.style.cssText = `
font-size: 12px;
color: #ccc;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
text-align: center;
`;
label.title = folderName;
item.appendChild(preview);
item.appendChild(label);
item.onmouseenter = () => {
item.style.borderColor = 'rgba(66, 153, 225, 0.9)';
item.style.transform = 'translateY(-2px)';
item.style.background = 'rgba(50, 112, 163, 0.5)';
};
item.onmouseleave = () => {
item.style.borderColor = 'rgba(226, 232, 240, 0.2)';
item.style.transform = 'translateY(0)';
item.style.background = 'rgba(45, 55, 72, 0.7)';
};
item.onclick = () => {
// Navigate into folder
currentSubfolder = currentSubfolder ? `${currentSubfolder}/${folderName}` : folderName;
loadFileThumbnails(container, currentFile, onFileSelect, overlay, breadcrumbElement);
};
return item;
}
function createThumbnailItem(filename, currentFile, onFileSelect, overlay) {
const item = document.createElement('div');
item.className = 'thumbnail-item';
item.dataset.filename = filename;
item.dataset.type = getFileType(filename);
const isSelected = filename === currentFile;
item.style.cssText = `
background: ${UI.cardBg};
border: 1px solid ${isSelected ? UI.accent : UI.panelBorder};
border-radius: 6px;
padding: 8px;
cursor: pointer;
transition: all 0.15s ease;
display: flex;
flex-direction: column;
gap: 8px;
`;
// Thumbnail preview
const preview = document.createElement('div');
preview.style.cssText = `
width: 100%;
height: 150px;
background: rgba(16, 18, 22, 0.6);
border-radius: 4px;
display: flex;
align-items: center;
justify-content: center;
overflow: hidden;
position: relative;
`;
const ext = filename.split('.').pop().toLowerCase();
const imageExts = ['png', 'jpg', 'jpeg', 'webp'];
const videoExts = ['mp4', 'webm', 'mov', 'avi'];
if (imageExts.includes(ext)) {
const img = document.createElement('img');
// Handle subfolder paths: split filename into folder and basename
let subfolder = '';
let basename = filename;
if (filename.includes('/')) {
const lastSlash = filename.lastIndexOf('/');
subfolder = filename.substring(0, lastSlash);
basename = filename.substring(lastSlash + 1);
}
img.src = `/view?filename=${encodeURIComponent(basename)}&type=${currentSourceFolder}&subfolder=${encodeURIComponent(subfolder)}`;
img.style.cssText = 'max-width: 100%; max-height: 100%; object-fit: contain;';
img.onerror = () => {
// Use placeholder image
img.src = new URL("./placeholder.png", import.meta.url).href;
};
preview.appendChild(img);
} else if (videoExts.includes(ext)) {
// Extract video thumbnail via server-side PyAV
extractVideoThumbnailServer(filename, preview);
} else if (ext === 'json') {
// Use placeholder for JSON
const img = document.createElement('img');
img.src = new URL("./placeholder.png", import.meta.url).href;
img.style.cssText = 'max-width: 100%; max-height: 100%; object-fit: contain;';
preview.appendChild(img);
} else {
// Use placeholder for unknown types
const img = document.createElement('img');
img.src = new URL("./placeholder.png", import.meta.url).href;
img.style.cssText = 'max-width: 100%; max-height: 100%; object-fit: contain;';
preview.appendChild(img);
}
// Filename label (show only basename, not full path)
const label = document.createElement('div');
const basename = filename.includes('/') ? filename.split('/').pop() : filename;
label.textContent = basename;
label.style.cssText = `
font-size: 12px;
color: ${isSelected ? '#fff' : '#ccc'};
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
text-align: center;
`;
label.title = filename; // Full path in tooltip
item.appendChild(preview);
item.appendChild(label);
// Hover effect
item.onmouseenter = () => {
if (!isSelected) {
item.style.borderColor = UI.accentBorder;
item.style.transform = 'translateY(-2px)';
item.style.background = UI.accentSoft;
}
};
item.onmouseleave = () => {
if (!isSelected) {
item.style.borderColor = UI.panelBorder;
item.style.transform = 'translateY(0)';
item.style.background = UI.cardBg;
}
};
// Click handler
item.onclick = (e) => {
// Don't select if clicking to close context menu
if (document.querySelector('.thumbnail-context-menu')) {
return;
}
onFileSelect(filename);
document.body.removeChild(overlay);
};
// Right-click context menu - only for video thumbnails
if (videoExts.includes(ext)) {
item.oncontextmenu = (e) => {
e.preventDefault();
e.stopPropagation();
showThumbnailContextMenu(e, filename, preview);
return false;
};
}
return item;
}
function getFileType(filename) {
const ext = filename.split('.').pop().toLowerCase();
const imageExts = ['png', 'jpg', 'jpeg', 'webp'];
const videoExts = ['mp4', 'webm', 'mov', 'avi'];
if (imageExts.includes(ext)) return 'image';
if (videoExts.includes(ext)) return 'video';
if (ext === 'json') return 'json';
return 'other';
}
/**
* Show context menu for thumbnail with refresh option
*/
function showThumbnailContextMenu(event, filename, previewElement) {
// Remove any existing context menu
const existingMenu = document.querySelector('.thumbnail-context-menu');
if (existingMenu) {
existingMenu.remove();
}
// Create context menu
const menu = document.createElement('div');
menu.className = 'thumbnail-context-menu';
menu.style.cssText = `
position: fixed;
left: ${event.pageX}px;
top: ${event.pageY}px;
background: ${UI.panel};
border: 1px solid ${UI.panelBorder};
border-radius: 6px;
padding: 4px;
z-index: 10001;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.5);
min-width: 160px;
`;
// Refresh option
const refreshBtn = document.createElement('div');
refreshBtn.textContent = '🔄 Refresh Thumbnail';
refreshBtn.style.cssText = `
padding: 8px 12px;
color: #ccc;
cursor: pointer;
border-radius: 4px;
font-size: 13px;
transition: background 0.15s ease;
`;
refreshBtn.onmouseenter = () => {
refreshBtn.style.background = UI.accentSoft;
};
refreshBtn.onmouseleave = () => {
refreshBtn.style.background = 'transparent';
};
refreshBtn.onclick = () => {
refreshIndividualThumbnail(filename, previewElement);
menu.remove();
};
menu.appendChild(refreshBtn);
document.body.appendChild(menu);
// Close menu when clicking outside
const closeMenu = (e) => {
if (!menu.contains(e.target)) {
e.stopPropagation(); // Prevent click from going through to elements below
menu.remove();
document.removeEventListener('click', closeMenu, true); // Remove from capture phase
}
};
// Use capture phase to catch the click before it reaches other elements
setTimeout(() => {
document.addEventListener('click', closeMenu, true);
}, 10);
}
/**
* Refresh thumbnail for a single file
*/
function refreshIndividualThumbnail(filename, previewElement) {
console.log(`[FileBrowser] Refreshing thumbnail for: ${filename}`);
// Clear cache for this specific file
const cacheKey = `video_thumb_pyav_${filename.replace(/[\/\\]/g, '_')}`;
try {
localStorage.removeItem(cacheKey);
console.log(`[FileBrowser] Cleared cache for: ${filename}`);
} catch (error) {
console.error('[FileBrowser] Error clearing cache:', error);
}
// Re-extract thumbnail via server-side PyAV
extractVideoThumbnailServer(filename, previewElement);
}
function filterThumbnails(container, searchText, fileType) {
const items = container.querySelectorAll('.thumbnail-item');
const search = searchText.toLowerCase();
items.forEach(item => {
const filename = item.dataset.filename.toLowerCase();
const type = item.dataset.type;
const matchesSearch = !searchText || filename.includes(search);
const matchesType = fileType === 'all' || type === fileType;
item.style.display = (matchesSearch && matchesType) ? 'flex' : 'none';
});
}
/**
* Extract thumbnail using server-side PyAV for all videos.
* Fetches a JPEG frame from /prompt-extractor/video-frame and caches to localStorage.
*/
function extractVideoThumbnailServer(filename, previewElement) {
const cacheKey = `video_thumb_pyav_${filename.replace(/[\/\\]/g, '_')}`;
try {
const cached = localStorage.getItem(cacheKey);
if (cached) {
const img = document.createElement('img');
img.style.cssText = 'max-width: 100%; max-height: 100%; object-fit: contain;';
img.src = cached;
previewElement.innerHTML = '';
previewElement.appendChild(img);
return;
}
} catch (e) { /* ignore */ }
// Show placeholder while loading
const placeholderImg = document.createElement('img');
placeholderImg.src = new URL("./placeholder.png", import.meta.url).href;
placeholderImg.style.cssText = 'max-width: 100%; max-height: 100%; object-fit: contain;';
previewElement.innerHTML = '';
previewElement.appendChild(placeholderImg);
const frameUrl = `/prompt-extractor/video-frame?filename=${encodeURIComponent(filename)}&source=${currentSourceFolder}&position=0`;
const img = document.createElement('img');
img.onload = () => {
// Scale down to thumbnail size
const maxW = 180, maxH = 150;
const ar = img.naturalWidth / img.naturalHeight;
let w, h;
if (ar > maxW / maxH) { w = maxW; h = maxW / ar; }
else { h = maxH; w = maxH * ar; }
const canvas = document.createElement('canvas');
canvas.width = w;
canvas.height = h;
const ctx = canvas.getContext('2d', { alpha: false });
ctx.drawImage(img, 0, 0, w, h);
const dataUrl = canvas.toDataURL('image/jpeg', 0.6);
const result = document.createElement('img');
result.style.cssText = 'max-width: 100%; max-height: 100%; object-fit: contain;';
result.src = dataUrl;
previewElement.innerHTML = '';
previewElement.appendChild(result);
try { localStorage.setItem(cacheKey, dataUrl); } catch (e) { /* ignore */ }
};
img.onerror = () => {
previewElement.innerHTML = `
<div style="text-align: center; color: #888; font-size: 11px; padding: 10px;">
<div style="font-size: 24px; margin-bottom: 6px;">🎬</div>
<div>Preview unavailable</div>
</div>`;
};
img.src = frameUrl;
}
/**
* Clear all video thumbnail cache
*/
function clearThumbnailCache() {
try {
const cachePrefix = 'video_thumb_';
const keysToRemove = [];
// Find all cache keys in localStorage
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
if (key && key.startsWith(cachePrefix)) {
keysToRemove.push(key);
}
}
// Remove all cache entries
keysToRemove.forEach(key => {
localStorage.removeItem(key);
});
console.log(`[FileBrowser] Cleared ${keysToRemove.length} cache entries`);
} catch (error) {
console.error('[FileBrowser] Error clearing cache:', error);
}
}
/**
* Clean up orphaned thumbnail cache entries
* Removes cache for files that no longer exist in the input directory
*/
function cleanupOrphanedThumbnailCache(currentFiles) {
try {
const cachePrefix = 'video_thumb_';
const timePrefix = 'video_thumb_time_';
const keysToRemove = [];
// Find all cache keys in localStorage
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
// Check if it's a video thumbnail cache key
if (key && key.startsWith(cachePrefix)) {
// Extract filename from cache key
const filename = key.substring(cachePrefix.length);
// If this filename is not in current files list, mark for removal
if (!currentFiles.includes(filename)) {
keysToRemove.push(key);
keysToRemove.push(timePrefix + filename);
}
}
}
// Remove orphaned cache entries
keysToRemove.forEach(key => {
localStorage.removeItem(key);
});
if (keysToRemove.length > 0) {
console.log(`[FileBrowser] Cleaned up ${keysToRemove.length / 2} orphaned thumbnail cache entries`);
}
} catch (error) {
console.error('[FileBrowser] Error cleaning up cache:', error);
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 747 B

File diff suppressed because it is too large Load Diff
+1056 -107
View File
File diff suppressed because it is too large Load Diff
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);
}
};
}
});
+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)",
};
File diff suppressed because it is too large Load Diff
+455
View File
@@ -0,0 +1,455 @@
/**
* WorkflowModelLoader extension.
* Shows color-coded loaded assets (Model/VAE/CLIP) from workflow_data.
*/
import { app } from "../../scripts/app.js";
const MODEL_CHOICES = ["model_a", "model_b"];
const WEIGHT_DTYPE_CHOICES = ["default", "fp8_e4m3fn", "fp8_e4m3fn_fast", "fp8_e5m2"];
function _trimMiddle(text, maxLen) {
const s = String(text || "");
if (s.length <= maxLen) return s;
const left = Math.ceil((maxLen - 3) / 2);
const right = Math.floor((maxLen - 3) / 2);
return `${s.slice(0, left)}...${s.slice(s.length - right)}`;
}
function _shortName(name) {
const raw = String(name || "").trim();
if (!raw) return "";
const normalized = raw.replace(/\\/g, "/");
const base = normalized.split("/").pop() || normalized;
return base.replace(/\.(safetensors|ckpt|pt|pth|bin|gguf|sft)$/i, "");
}
function _shortList(names) {
const list = Array.isArray(names) ? names : [];
return list.map(_shortName).filter(Boolean);
}
const COLORS = {
modelCheckpoint: "#4CAF50",
modelDiffusion: "#2196F3",
modelGguf: "#FF9800",
vae: "#FF6B6B",
clip: "#C4A300",
notFound: "#F44336",
muted: "#B0B0B0",
missing: "#E57373",
};
function _buildRows(info) {
const status = String(info.status || "").toLowerCase();
if (!info || status === "idle") {
return [
{ label: "Model", labelColor: COLORS.modelDiffusion, value: "(awaiting execution)", valueColor: COLORS.muted },
{ label: "Clip", labelColor: COLORS.clip, value: "(awaiting execution)", valueColor: COLORS.muted },
{ label: "Vae", labelColor: COLORS.vae, value: "(awaiting execution)", valueColor: COLORS.muted },
];
}
const modelKind = String(info.model_kind || info.loader_type || "").toLowerCase();
const modelColor = modelKind === "checkpoint"
? COLORS.modelCheckpoint
: (modelKind === "gguf" ? COLORS.modelGguf : COLORS.modelDiffusion);
const rows = [];
const modelShort = _shortName(info.model_name || "");
rows.push({
label: "Model",
labelColor: modelColor,
value: modelShort || "(none)",
valueColor: modelShort ? "#CCCCCC" : COLORS.missing,
});
const loaderType = String(info.loader_type || "").toLowerCase();
const vaeShort = _shortName(info.vae_name || "");
const clipShort = _shortList(info.clip_names);
if (loaderType === "checkpoint") {
// Keep all tags visible; show source explicitly for checkpoint-provided assets.
const usingInternalVae = !!info.uses_checkpoint_vae;
const usingInternalClip = !!info.uses_checkpoint_clip;
rows.push({
label: "Clip",
labelColor: COLORS.clip,
value: usingInternalClip ? "From Checkpoint" : (clipShort.length > 0 ? clipShort.join(", ") : "(none provided)"),
valueColor: usingInternalClip ? COLORS.muted : (clipShort.length > 0 ? "#CCCCCC" : COLORS.missing),
});
rows.push({
label: "Vae",
labelColor: COLORS.vae,
value: usingInternalVae ? "From Checkpoint" : (vaeShort || "(none provided)"),
valueColor: usingInternalVae ? COLORS.muted : (vaeShort ? "#CCCCCC" : COLORS.missing),
});
} else {
// Diffusion/UNet: always show Clip + Vae lines.
rows.push({
label: "Clip",
labelColor: COLORS.clip,
value: clipShort.length > 0 ? clipShort.join(", ") : "(none provided)",
valueColor: clipShort.length > 0 ? "#CCCCCC" : COLORS.missing,
});
rows.push({
label: "Vae",
labelColor: COLORS.vae,
value: vaeShort || "(none provided)",
valueColor: vaeShort ? "#CCCCCC" : COLORS.missing,
});
}
return rows;
}
function _drawPillRow(ctx, row, y, widgetWidth) {
const left = 8;
const badgeText = String(row.label || "");
const value = String(row.value || "");
const badgeW = 68;
const valueX = left + badgeW + 10;
const valueMax = Math.max(16, Math.floor((widgetWidth - valueX - 8) / 6));
const displayValue = _trimMiddle(value, valueMax);
ctx.font = "bold 11px Arial";
const badgeH = 16;
const badgeY = y - Math.floor(badgeH / 2);
ctx.fillStyle = row.labelColor || COLORS.muted;
ctx.beginPath();
ctx.roundRect(left, badgeY, badgeW, badgeH, 8);
ctx.fill();
ctx.fillStyle = "#FFFFFF";
ctx.textAlign = "left";
ctx.textBaseline = "middle";
ctx.fillText(badgeText, left + 8, y + 0.5);
ctx.font = "12px Arial";
ctx.fillStyle = row.valueColor || "#CCCCCC";
ctx.fillText(displayValue, valueX, y + 0.5);
}
function _getWidgetValue(node, name, fallback = "") {
const w = node?.widgets?.find((x) => x.name === name);
if (!w || w.value == null) return fallback;
return String(w.value);
}
function _widgetByNames(node, names) {
const arr = Array.isArray(names) ? names : [names];
return node?.widgets?.find((w) => arr.includes(w.name));
}
function _sanitizeChoice(value, allowed, fallback) {
const v = String(value ?? "");
return allowed.includes(v) ? v : fallback;
}
function _selectedModelSlot(node) {
return _sanitizeChoice(
_getWidgetValue(node, "model", "model_a"),
MODEL_CHOICES,
"model_a"
);
}
function _readWidgetState(node) {
const modelWidget = _widgetByNames(node, ["model"]);
const dtypeWidget = _widgetByNames(node, ["weight_dtype"]);
return {
model: _sanitizeChoice(modelWidget?.value, MODEL_CHOICES, "model_a"),
weight_dtype: _sanitizeChoice(dtypeWidget?.value, WEIGHT_DTYPE_CHOICES, "default"),
};
}
function _applyWidgetState(node, state, { persist = true } = {}) {
const modelWidget = _widgetByNames(node, ["model"]);
const dtypeWidget = _widgetByNames(node, ["weight_dtype"]);
const modelVal = _sanitizeChoice(state?.model, MODEL_CHOICES, "model_a");
const dtypeVal = _sanitizeChoice(state?.weight_dtype, WEIGHT_DTYPE_CHOICES, "default");
if (modelWidget) modelWidget.value = modelVal;
if (dtypeWidget) dtypeWidget.value = dtypeVal;
if (persist) {
node.properties = node.properties || {};
node.properties.wfml_model = modelVal;
node.properties.wfml_weight_dtype = dtypeVal;
}
}
function _restoreOrNormalizeWidgetState(node) {
node.properties = node.properties || {};
const live = _readWidgetState(node);
const savedModel = _sanitizeChoice(node.properties.wfml_model, MODEL_CHOICES, "");
const savedDtype = _sanitizeChoice(node.properties.wfml_weight_dtype, WEIGHT_DTYPE_CHOICES, "");
_applyWidgetState(node, {
model: savedModel || live.model || "model_a",
weight_dtype: savedDtype || live.weight_dtype || "default",
}, { persist: true });
}
function _isRerouteNode(n) {
const t = String(n?.type || "").toLowerCase();
const c = String(n?.comfyClass || "").toLowerCase();
return t.includes("reroute") || c.includes("reroute");
}
function _resolveWorkflowUpstreamLink(node) {
const wfInputIdx = (node.inputs || []).findIndex((i) => i?.name === "workflow_data");
if (wfInputIdx < 0) return null;
let linkId = node.inputs[wfInputIdx]?.link;
if (linkId == null) return null;
const graph = node.graph;
const seen = new Set();
for (let hop = 0; hop < 24; hop++) {
if (linkId == null || seen.has(linkId)) break;
seen.add(linkId);
const li = graph?.links?.[linkId];
if (!li) break;
const src = graph?.getNodeById?.(li.origin_id);
if (!src) break;
if (!_isRerouteNode(src)) {
return { sourceNode: src, sourceSlot: li.origin_slot };
}
const in0 = src.inputs?.[0];
linkId = in0?.link ?? null;
}
return null;
}
function _tryParseWorkflowData(value) {
if (!value) return null;
if (typeof value === "object") return value;
if (typeof value === "string") {
try {
const p = JSON.parse(value);
if (p && typeof p === "object") return p;
} catch {
return null;
}
}
return null;
}
function _clipListFromWf(wf) {
const c = wf?.clip;
if (Array.isArray(c)) return c.filter(Boolean);
if (typeof c === "string" && c) return [c];
if (c && Array.isArray(c.names)) return c.names.filter(Boolean);
return [];
}
function _vaeFromWf(wf) {
const v = wf?.vae;
if (typeof v === "string") return v;
if (v && typeof v === "object" && typeof v.name === "string") return v.name;
return "";
}
function _inferInfoFromWorkflowData(node, wf) {
const modelKey = _selectedModelSlot(node);
const modelName = typeof wf?.[modelKey] === "string" ? wf[modelKey] : "";
if (!modelName) return null;
const loaderType = String(wf?.loader_type || "").toLowerCase();
const selectedLower = modelName.toLowerCase();
const modelKind = loaderType === "checkpoint"
? "checkpoint"
: (selectedLower.endsWith(".gguf") ? "gguf" : "diffusion");
const vaeName = _vaeFromWf(wf);
const clipNames = _clipListFromWf(wf);
return {
model: modelKey,
model_name: _shortName(modelName),
loader_type: loaderType,
model_kind: modelKind,
vae_name: vaeName,
clip_names: clipNames,
status: "ok",
error_message: "",
missing_name: "",
uses_checkpoint_vae: (loaderType === "checkpoint" && !vaeName),
uses_checkpoint_clip: (loaderType === "checkpoint" && clipNames.length === 0),
};
}
function _refreshInfoFromUpstream(node) {
const resolved = _resolveWorkflowUpstreamLink(node);
if (!resolved) return false;
const { sourceNode, sourceSlot } = resolved;
const out = sourceNode?.outputs?.[sourceSlot];
const wfFromOutput = _tryParseWorkflowData(out?._data) || _tryParseWorkflowData(out?.value);
const wfFromBuilderCache = _tryParseWorkflowData(sourceNode?.properties?.we_extracted_cache);
const wf = wfFromOutput || wfFromBuilderCache;
if (!wf) return false;
const inferred = _inferInfoFromWorkflowData(node, wf);
if (!inferred) return false;
node._applyWorkflowModelLoaderInfo(inferred);
return true;
}
function _defaultInfoFromWidgets(node) {
const selected = _selectedModelSlot(node);
return {
model: selected,
model_name: "",
loader_type: "",
model_kind: "",
vae_name: "",
clip_names: [],
status: "idle",
error_message: "",
missing_name: "",
uses_checkpoint_vae: false,
uses_checkpoint_clip: false,
};
}
app.registerExtension({
name: "PromptManager.WorkflowModelLoader",
async beforeRegisterNodeDef(nodeType, nodeData) {
if (nodeData.name !== "WorkflowModelLoader") return;
const origOnExecuted = nodeType.prototype.onExecuted;
nodeType.prototype.onExecuted = function (message) {
origOnExecuted?.apply(this, arguments);
const info = message?.workflow_model_loader_info?.[0];
if (!info) return;
this._applyWorkflowModelLoaderInfo(info);
};
nodeType.prototype._applyWorkflowModelLoaderInfo = function (info) {
const selected = _sanitizeChoice(info.model, MODEL_CHOICES, "model_a");
this._workflowModelLoaderInfo = {
model: selected,
model_name: info.model_name || "",
loader_type: info.loader_type || "",
model_kind: info.model_kind || "",
vae_name: info.vae_name || "",
clip_names: Array.isArray(info.clip_names) ? info.clip_names : [],
status: info.status || "ok",
error_message: info.error_message || "",
missing_name: info.missing_name || "",
uses_checkpoint_vae: !!info.uses_checkpoint_vae,
uses_checkpoint_clip: !!info.uses_checkpoint_clip,
};
this._ensureWorkflowModelInfoWidget();
this.setDirtyCanvas(true, true);
};
const origOnNodeCreated = nodeType.prototype.onNodeCreated;
nodeType.prototype.onNodeCreated = function () {
const r = origOnNodeCreated?.apply(this, arguments);
_restoreOrNormalizeWidgetState(this);
if (!this._workflowModelLoaderInfo) {
this._workflowModelLoaderInfo = _defaultInfoFromWidgets(this);
}
this._ensureWorkflowModelInfoWidget();
_refreshInfoFromUpstream(this);
this.setDirtyCanvas(true, true);
return r;
};
const origOnConnectionsChange = nodeType.prototype.onConnectionsChange;
nodeType.prototype.onConnectionsChange = function () {
const r = origOnConnectionsChange?.apply(this, arguments);
_refreshInfoFromUpstream(this);
this.setDirtyCanvas(true, true);
return r;
};
const origOnWidgetChanged = nodeType.prototype.onWidgetChanged;
nodeType.prototype.onWidgetChanged = function (name, value, oldValue, w) {
const r = origOnWidgetChanged?.apply(this, arguments);
if (name === "model" || name === "weight_dtype") {
_restoreOrNormalizeWidgetState(this);
_refreshInfoFromUpstream(this);
this.setDirtyCanvas(true, true);
}
return r;
};
const origOnSerialize = nodeType.prototype.onSerialize;
nodeType.prototype.onSerialize = function (o) {
origOnSerialize?.apply(this, arguments);
const ws = _readWidgetState(this);
this.properties = this.properties || {};
this.properties.wfml_model = ws.model;
this.properties.wfml_weight_dtype = ws.weight_dtype;
if (this._workflowModelLoaderInfo) {
o._workflowModelLoaderInfo = this._workflowModelLoaderInfo;
}
if (o) {
o.properties = o.properties || {};
o.properties.wfml_model = ws.model;
o.properties.wfml_weight_dtype = ws.weight_dtype;
}
};
const origOnConfigure = nodeType.prototype.onConfigure;
nodeType.prototype.onConfigure = function (info) {
origOnConfigure?.apply(this, arguments);
_restoreOrNormalizeWidgetState(this);
const state = info?._workflowModelLoaderInfo;
if (state) {
requestAnimationFrame(() => {
this._applyWorkflowModelLoaderInfo(state);
_refreshInfoFromUpstream(this);
});
} else {
requestAnimationFrame(() => {
this._workflowModelLoaderInfo = _defaultInfoFromWidgets(this);
this._ensureWorkflowModelInfoWidget();
_refreshInfoFromUpstream(this);
this.setDirtyCanvas(true, true);
});
}
};
nodeType.prototype._ensureWorkflowModelInfoWidget = function () {
let widget = this.widgets?.find(w => w.name === "_workflow_model_loader_info");
if (!widget) {
widget = {
name: "_workflow_model_loader_info",
type: "custom",
y: 0,
computeSize: () => {
const rows = _buildRows(this._workflowModelLoaderInfo || {});
const h = Math.max(26, (rows.length * 22) + 6);
return [0, h];
},
draw: function (ctx, node, widgetWidth, y) {
const info = node._workflowModelLoaderInfo;
if (!info) return;
const rows = _buildRows(info);
ctx.save();
ctx.textAlign = "left";
ctx.textBaseline = "middle";
for (let i = 0; i < rows.length; i++) {
const rowY = y + 12 + (i * 22);
const row = rows[i];
_drawPillRow(ctx, row, rowY, widgetWidth);
}
ctx.restore();
},
};
if (!this.widgets) this.widgets = [];
this.widgets.push(widget);
}
this.computeSize();
};
},
});
+15
View File
@@ -0,0 +1,15 @@
/**
* Workflow Renderer — Set initial node size to match Workflow Builder width.
*/
import { app } from "../../scripts/app.js";
app.registerExtension({
name: "prompt-manager.workflow-renderer",
async nodeCreated(node) {
if (node.comfyClass !== "WorkflowRenderer") return;
requestAnimationFrame(() => {
node.setSize([320, node.size[1]]);
app.graph.setDirtyCanvas(true, true);
});
},
});
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)
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+196
View File
@@ -0,0 +1,196 @@
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
_last_model_update = time.time()
def trigger_model_list_refresh():
"""Call this after downloading a model to trigger UI refresh"""
global _last_model_update
_last_model_update = time.time()
class PromptGenOptions:
"""Node that provides optional configuration for llama.cpp servers"""
@classmethod
def INPUT_TYPES(cls):
backend = _preferences_cache.get("llm_backend", "llama.cpp")
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)\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)"
}),
"image3": ("IMAGE", {
"tooltip": "Connect an image (required for 'Analyze Image' and 'Analyze Image with Prompt' modes)"
}),
"image4": ("IMAGE", {
"tooltip": "Connect an image (required for 'Analyze Image' and 'Analyze Image with Prompt' modes)"
}),
"image5": ("IMAGE", {
"tooltip": "Connect an image (required for 'Analyze Image' and 'Analyze Image with Prompt' modes)"
}),
"system_prompt": ("STRING", {
"multiline": True,
"default": "",
"placeholder": "Replace LLM Instructions...",
"tooltip": "Custom LLM Instructions (leave empty to use default)\nThe default instructions are designed for generating\ndetailed and imaginative prompts for text-to-image generation."
}),
"use_model_default_sampling": ("BOOLEAN", {
"default": False,
"tooltip": "Use the model's default sampling parameters (overrides temperature, top_p, etc)"
}),
"temperature": ("FLOAT", {
"default": 0.8,
"min": 0.0,
"max": 2.0,
"step": 0.01,
"tooltip": "Controls randomness (0.0 = deterministic, 2.0 = very random)"
}),
"top_k": ("INT", {
"default": 40,
"min": 0,
"max": 100,
"step": 1,
"tooltip": "Sample from top K most likely tokens (0 = disabled)"
}),
"top_p": ("FLOAT", {
"default": 0.95,
"min": 0.0,
"max": 1.0,
"step": 0.01,
"tooltip": "Nucleus sampling: consider tokens with top_p probability mass"
}),
"min_p": ("FLOAT", {
"default": 0.05,
"min": 0.0,
"max": 1.0,
"step": 0.01,
"tooltip": "Minimum probability threshold relative to top token"
}),
"repeat_penalty": ("FLOAT", {
"default": 1.0,
"min": 1.0,
"max": 2.0,
"step": 0.01,
"tooltip": "Penalty for repeating tokens (1.0 = no penalty)"
}),
"context_size": ("INT", {
"default": 4096,
"min": 512,
"max": 32768,
"step": 512,
"tooltip": "Context size (increase for vision models or large prompts)"
}),
"show_everything_in_console": ("BOOLEAN", {
"default": False,
"tooltip": "Print system prompt, user prompt, thinking process, and raw model response to console"
})
}
}
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"
@classmethod
def IS_CHANGED(cls, **kwargs):
"""Force refresh when models are updated"""
return _last_model_update
def create_options(self, model: str = None, image2=None, image3=None, image4=None, image5=None,
system_prompt: str = None, use_model_default_sampling: bool = None, temperature: float = None,
top_k: int = None, top_p: float = None, min_p: float = None,
repeat_penalty: float = None, context_size: int = None,
show_everything_in_console: bool = None) -> dict:
"""Create options dictionary with model, LLM parameters, and extra images"""
options = {}
# Handle model selection and download if needed
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 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 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}")
needs_download = True
if needs_download:
if not model_exists:
print(f"[Prompt Generator Options] Model not found locally, downloading: {model}")
downloaded_path = download_model(model)
if downloaded_path:
trigger_model_list_refresh()
options["model"] = model
else:
print(f"[Prompt Generator Options] Failed to download model: {model}")
else:
options["model"] = model
# Add extra images if provided
if image2 is not None:
options["image2"] = image2
if image3 is not None:
options["image3"] = image3
if image4 is not None:
options["image4"] = image4
if image5 is not None:
options["image5"] = image5
# Only include LLM parameters that are provided
if system_prompt and system_prompt.strip():
options["system_prompt"] = system_prompt
options["use_model_default_sampling"] = use_model_default_sampling
options["temperature"] = temperature
options["top_p"] = top_p
options["top_k"] = top_k
options["min_p"] = min_p
options["repeat_penalty"] = repeat_penalty
options["context_size"] = context_size
options["show_everything_in_console"] = show_everything_in_console
return (options,)
NODE_CLASS_MAPPINGS = {
"PromptGenOptions": PromptGenOptions
}
NODE_DISPLAY_NAME_MAPPINGS = {
"PromptGenOptions": "Prompt Generator Options"
}
File diff suppressed because it is too large Load Diff
@@ -1,18 +1,43 @@
import os
import json
import shutil
import time
import folder_paths
import server
class PromptManagerNode:
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 = PromptManagerNode.load_prompts()
prompts_data = PromptManager.load_prompts()
categories = list(prompts_data.keys()) if prompts_data else ["Character"]
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))
@@ -23,7 +48,7 @@ class PromptManagerNode:
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", "")
@@ -36,7 +61,7 @@ class PromptManagerNode:
"text": ("STRING", {"multiline": True, "default": first_prompt_text, "placeholder": "Enter prompt text", "dynamicPrompts": False, "tooltip": "Enter prompt text directly"}),
},
"optional": {
"llm_input": ("STRING", {"multiline": True, "forceInput": True, "tooltip": "Connect LLM text input here"}),
"llm_input": ("STRING", {"multiline": True, "forceInput": True, "lazy": True, "tooltip": "Connect LLM text input here"}),
},
"hidden": {
"unique_id": "UNIQUE_ID",
@@ -44,9 +69,17 @@ class PromptManagerNode:
}
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"
OUTPUT_NODE = True
@classmethod
def VALIDATE_INPUTS(cls, name, **kwargs):
"""Allow any name value, including temporary unsaved prompts"""
# Return True to accept any value - this allows new prompts to be tested before saving
return True
@staticmethod
def get_prompts_path():
@@ -56,7 +89,7 @@ class PromptManagerNode:
@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):
@@ -70,6 +103,26 @@ class PromptManagerNode:
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:
@@ -86,10 +139,19 @@ class PromptManagerNode:
@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
@@ -97,17 +159,29 @@ class PromptManagerNode:
"""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"""
# Choose which text to use based on the toggle
if use_external and llm_input:
output_text = llm_input
@@ -124,12 +198,18 @@ class PromptManagerNode:
})
return (output_text,)
def check_lazy_status(self, category, name, use_external, text, llm_input=None, unique_id=None):
needed = []
if use_external:
needed.append("llm_input")
return needed
@server.PromptServer.instance.routes.get("/prompt-manager/get-prompts")
async def get_prompts(request):
"""API endpoint to get all prompts"""
try:
prompts = PromptManagerNode.load_prompts()
prompts = PromptManager.load_prompts()
return server.web.json_response(prompts)
except Exception as e:
print(f"[PromptManager] Error in get_prompts API: {e}")
@@ -146,7 +226,7 @@ async def save_category(request):
if not category_name:
return server.web.json_response({"success": False, "error": "Category name is required"})
prompts = PromptManagerNode.load_prompts()
prompts = PromptManager.load_prompts()
# Case-insensitive check for existing category
existing_categories_lower = {k.lower(): k for k in prompts.keys()}
@@ -154,7 +234,7 @@ async def save_category(request):
return server.web.json_response({"success": False, "error": f"Category already exists as '{existing_categories_lower[category_name.lower()]}'"})
prompts[category_name] = {}
PromptManagerNode.save_prompts(prompts)
PromptManager.save_prompts(prompts)
return server.web.json_response({"success": True, "prompts": prompts})
except Exception as e:
@@ -171,10 +251,10 @@ async def save_prompt(request):
name = data.get("name", "").strip()
text = data.get("text", "").strip()
if not category or not name or not text:
return server.web.json_response({"success": False, "error": "All fields are required"})
if not category or not name:
return server.web.json_response({"success": False, "error": "Category and name are required"})
prompts = PromptManagerNode.load_prompts()
prompts = PromptManager.load_prompts()
if category not in prompts:
prompts[category] = {}
@@ -189,9 +269,19 @@ 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
prompts[category][name] = {"prompt": text}
PromptManagerNode.save_prompts(prompts)
# Save prompt in dict, preserving any existing lora data, trigger words, thumbnail, and nsfw from PromptManagerAdvanced
existing_data = prompts[category].get(name, {})
prompts[category][name] = {
"prompt": text,
"loras_a": existing_data.get("loras_a", []),
"loras_b": existing_data.get("loras_b", []),
"trigger_words": existing_data.get("trigger_words", []),
"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})
except Exception as e:
@@ -209,13 +299,13 @@ async def delete_category(request):
if not category:
return server.web.json_response({"success": False, "error": "Category name is required"})
prompts = PromptManagerNode.load_prompts()
prompts = PromptManager.load_prompts()
if category not in prompts:
return server.web.json_response({"success": False, "error": "Category not found"})
del prompts[category]
PromptManagerNode.save_prompts(prompts)
PromptManager.save_prompts(prompts)
return server.web.json_response({"success": True, "prompts": prompts})
except Exception as e:
@@ -234,15 +324,57 @@ async def delete_prompt(request):
if not category or not name:
return server.web.json_response({"success": False, "error": "Category and prompt name are required"})
prompts = PromptManagerNode.load_prompts()
prompts = PromptManager.load_prompts()
if category not in prompts or name not in prompts[category]:
return server.web.json_response({"success": False, "error": "Prompt not found"})
del prompts[category][name]
PromptManagerNode.save_prompts(prompts)
PromptManager.save_prompts(prompts)
return server.web.json_response({"success": True, "prompts": prompts})
except Exception as e:
print(f"[PromptManager] Error in delete_prompt API: {e}")
return server.web.json_response({"success": False, "error": str(e)}, status=500)
@server.PromptServer.instance.routes.post("/prompt-manager/import-prompts")
async def import_prompts(request):
"""API endpoint to import prompts from JSON"""
try:
data = await request.json()
imported_data = data.get("data", {})
mode = data.get("mode", "merge")
if not isinstance(imported_data, dict):
return server.web.json_response({"success": False, "error": "Invalid data format"})
if mode == "replace":
# Replace all existing prompts
PromptManager.save_prompts(imported_data)
return server.web.json_response({"success": True, "prompts": imported_data})
else:
# Merge with existing prompts
prompts = PromptManager.load_prompts()
for category, category_prompts in imported_data.items():
if not isinstance(category_prompts, dict):
continue
if category not in prompts:
prompts[category] = {}
for prompt_name, prompt_data in category_prompts.items():
# Merge prompt data, preserving structure
if isinstance(prompt_data, dict):
prompts[category][prompt_name] = prompt_data
elif isinstance(prompt_data, str):
# Legacy format: just the prompt text
prompts[category][prompt_name] = {"prompt": prompt_data}
PromptManager.save_prompts(prompts)
return server.web.json_response({"success": True, "prompts": prompts})
except Exception as e:
print(f"[PromptManager] Error in import_prompts API: {e}")
return server.web.json_response({"success": False, "error": str(e)}, status=500)
+443
View File
@@ -0,0 +1,443 @@
"""
ComfyUI Workflow Bridge - Pure passthrough node.
Unpacks workflow_data into individual typed outputs.
Any connected optional input overrides the corresponding field before output.
Models (MODEL/CLIP/VAE) are passed through only - use WorkflowModelLoader for loading.
"""
import json
import os
import folder_paths
import comfy.samplers
from ..py.lora_utils import resolve_lora_path
from ..py.workflow_extraction_utils import resolve_model_name
from ..py.workflow_families import get_model_family, MODEL_FAMILIES
MODEL_EXTENSIONS = (".safetensors", ".ckpt", ".pt", ".pth", ".gguf")
class _AnyType(str):
"""Comfy wildcard type that can connect to any socket type."""
def __ne__(self, _other):
return False
ANY_TYPE = _AnyType("ANY")
def _strip_model_ext(name):
base = os.path.basename(str(name or "").replace("\\", "/"))
lower = base.lower()
for ext in MODEL_EXTENSIONS:
if lower.endswith(ext):
return base[:-len(ext)]
return os.path.splitext(base)[0]
def _resolve_rel_path(raw_name, folder_keys):
"""Resolve a model-like name to a relative Comfy path in the provided folder keys."""
if not raw_name:
return "", False
raw = str(raw_name).strip().replace("\\", "/")
if not raw:
return "", False
base = os.path.basename(raw).lower()
base_no_ext = _strip_model_ext(base).lower()
for key in folder_keys:
try:
file_list = folder_paths.get_filename_list(key)
except Exception:
continue
for rel in file_list:
rel_norm = rel.replace("\\", "/")
if rel_norm == raw:
return rel, True
rel_base = os.path.basename(rel_norm).lower()
if rel_base == base:
return rel, True
if _strip_model_ext(rel_base).lower() == base_no_ext:
return rel, True
return os.path.basename(raw), False
def _get_live_ksampler_combo_types():
"""Mirror the active KSampler enum sockets to avoid stale type mismatches."""
default_samplers = comfy.samplers.KSampler.SAMPLERS
default_schedulers = comfy.samplers.KSampler.SCHEDULERS
try:
from nodes import KSampler as CoreKSampler
required = CoreKSampler.INPUT_TYPES().get("required", {})
samplers = required.get("sampler_name", (default_samplers,))[0]
schedulers = required.get("scheduler", (default_schedulers,))[0]
return samplers, schedulers
except Exception:
return default_samplers, default_schedulers
_LIVE_SAMPLERS, _LIVE_SCHEDULERS = _get_live_ksampler_combo_types()
DEFAULT_WORKFLOW_DATA = {
"_source": "WorkflowBridge",
"family": "",
"model_a": "",
"model_b": "",
"positive_prompt": "",
"negative_prompt": "",
"loras_a": [],
"loras_b": [],
"vae": "",
"clip": [],
"clip_type": "",
"loader_type": "",
"sampler": {
"steps_a": 10,
"steps_b": 10,
"cfg": 5,
"seed_a": 0,
"seed_b": 0,
"sampler_name": "euler",
"scheduler": "simple",
},
"resolution": {
"width": 512,
"height": 512,
"batch_size": 1,
"length": 1,
},
}
class WorkflowBridge:
"""
Pure passthrough bridge node.
Unpacks workflow_data into individual typed outputs and forwards
any connected MODEL/CLIP/VAE inputs. No model loading.
"""
@classmethod
def _sync_combo_types(cls):
samplers, schedulers = _get_live_ksampler_combo_types()
cls._SAMPLER_ENUM = samplers
cls._SCHEDULER_ENUM = schedulers
cls.RETURN_TYPES = (
"WORKFLOW_DATA",
"MODEL", "MODEL", "CLIP", "CONDITIONING", "CONDITIONING", "VAE", "LATENT", "IMAGE", "MASK", ANY_TYPE,
"INT", "INT", "INT", "INT", "FLOAT",
cls._SAMPLER_ENUM, cls._SCHEDULER_ENUM,
"STRING", "STRING",
"LORA_STACK", "LORA_STACK",
"INT", "INT", "INT", "INT",
"STRING", "STRING", "STRING", "STRING",
)
@classmethod
def INPUT_TYPES(cls):
cls._sync_combo_types()
return {
"required": {},
"optional": {
"workflow_data": ("WORKFLOW_DATA", {"forceInput": True, "tooltip": "Optional workflow data input. If omitted, bridge starts from an empty workflow_data dict."}),
"model_a": ("MODEL", {"tooltip": "Pass-through Model A"}),
"model_b": ("MODEL", {"tooltip": "Pass-through Model B"}),
"clip": ("CLIP", {"tooltip": "Pass-through CLIP"}),
"positive": ("CONDITIONING", {"tooltip": "Pass-through positive conditioning"}),
"negative": ("CONDITIONING", {"tooltip": "Pass-through negative conditioning"}),
"vae": ("VAE", {"tooltip": "Pass-through VAE"}),
"latent": ("LATENT", {"tooltip": "Pass-through latent"}),
"image": ("IMAGE", {"tooltip": "Pass-through image"}),
"mask": ("MASK", {"tooltip": "Pass-through mask"}),
"extra": (ANY_TYPE, {"tooltip": "Pass-through extra data (any type)"}),
"seed_a": ("INT", {"forceInput": True, "tooltip": "Override seed A"}),
"seed_b": ("INT", {"forceInput": True, "tooltip": "Override seed B (dual-sampler)"}),
"steps_a": ("INT", {"forceInput": True, "tooltip": "Override sampling steps A"}),
"steps_b": ("INT", {"forceInput": True, "tooltip": "Override sampling steps B (dual-sampler)"}),
"cfg": ("FLOAT", {"forceInput": True, "tooltip": "Override CFG scale"}),
"sampler_name": (cls._SAMPLER_ENUM, {"forceInput": True, "tooltip": "Override sampler name"}),
"scheduler": (cls._SCHEDULER_ENUM, {"forceInput": True, "tooltip": "Override scheduler"}),
"pos_prompt": ("STRING", {"forceInput": True, "tooltip": "Override positive prompt"}),
"neg_prompt": ("STRING", {"forceInput": True, "tooltip": "Override negative prompt"}),
"lora_stack_a": ("LORA_STACK", {"tooltip": "Override LoRA stack A"}),
"lora_stack_b": ("LORA_STACK", {"tooltip": "Override LoRA stack B"}),
"width": ("INT", {"forceInput": True, "tooltip": "Override width"}),
"height": ("INT", {"forceInput": True, "tooltip": "Override height"}),
"batch_size": ("INT", {"forceInput": True, "tooltip": "Override batch size"}),
"length": ("INT", {"forceInput": True, "tooltip": "Override video length"}),
"model_a_name": ("STRING", {"forceInput": True, "tooltip": "Optional Model A name/path. Resolves and writes workflow_data['model_a']."}),
"model_b_name": ("STRING", {"forceInput": True, "tooltip": "Optional Model B name/path. Resolves and writes workflow_data['model_b']."}),
"clip_name": ("STRING", {"forceInput": True, "tooltip": "Optional CLIP name/path. Resolves and writes workflow_data['clip']."}),
"vae_name": ("STRING", {"forceInput": True, "tooltip": "Optional VAE name/path. Resolves and writes workflow_data['vae']."}),
},
}
RETURN_TYPES = (
"WORKFLOW_DATA",
"MODEL", "MODEL", "CLIP", "CONDITIONING", "CONDITIONING", "VAE", "LATENT", "IMAGE", "MASK", ANY_TYPE,
"INT", "INT", "INT", "INT", "FLOAT",
_LIVE_SAMPLERS, _LIVE_SCHEDULERS,
"STRING", "STRING",
"LORA_STACK", "LORA_STACK",
"INT", "INT", "INT", "INT",
"STRING", "STRING", "STRING", "STRING",
)
RETURN_NAMES = (
"workflow_data",
"model_a", "model_b", "clip", "positive", "negative", "vae", "latent", "image", "mask", "extra",
"seed_a", "seed_b", "steps_a", "steps_b", "cfg",
"sampler_name", "scheduler",
"pos_prompt", "neg_prompt",
"lora_stack_a", "lora_stack_b",
"width", "height", "batch_size", "length",
"model_a_name", "model_b_name", "clip_name", "vae_name",
)
FUNCTION = "unpack"
CATEGORY = "Prompt Manager"
DESCRIPTION = (
"Pure passthrough bridge node. Unpacks workflow_data into individual "
"typed outputs. Models are forwarded from connected inputs only."
)
# ------------------------------------------------------------------
def unpack(self, workflow_data=None, **kwargs):
def _short_display_name(name):
raw = str(name or "").strip()
if not raw:
return ""
base = os.path.basename(raw.replace("\\", "/"))
return os.path.splitext(base)[0]
# Accept both dict and JSON string
if isinstance(workflow_data, str):
try:
incoming_wf = json.loads(workflow_data)
except (json.JSONDecodeError, TypeError):
incoming_wf = {}
elif isinstance(workflow_data, dict):
incoming_wf = dict(workflow_data)
else:
incoming_wf = {}
# Start from a full empty-workflow template, then layer incoming values.
wf = dict(DEFAULT_WORKFLOW_DATA)
if isinstance(incoming_wf, dict):
wf.update(incoming_wf)
incoming_sampler = incoming_wf.get('sampler')
if isinstance(incoming_sampler, dict):
wf['sampler'] = dict(DEFAULT_WORKFLOW_DATA['sampler'])
wf['sampler'].update(incoming_sampler)
incoming_resolution = incoming_wf.get('resolution')
if isinstance(incoming_resolution, dict):
wf['resolution'] = dict(DEFAULT_WORKFLOW_DATA['resolution'])
wf['resolution'].update(incoming_resolution)
sampler = dict(wf.get('sampler', DEFAULT_WORKFLOW_DATA['sampler']))
resolution = dict(wf.get('resolution', DEFAULT_WORKFLOW_DATA['resolution']))
# -- Apply top-level overrides -------------------------------
pos_text = kwargs.get('pos_prompt')
if pos_text is not None:
wf['positive_prompt'] = pos_text
neg_text = kwargs.get('neg_prompt')
if neg_text is not None:
wf['negative_prompt'] = neg_text
# -- LoRA stack overrides ------------------------------------
if kwargs.get('lora_stack_a') is not None:
wf['loras_a'] = [
{'name': n, 'model_strength': ms, 'clip_strength': cs}
for n, ms, cs in kwargs['lora_stack_a']
]
if kwargs.get('lora_stack_b') is not None:
wf['loras_b'] = [
{'name': n, 'model_strength': ms, 'clip_strength': cs}
for n, ms, cs in kwargs['lora_stack_b']
]
# -- Resolution overrides ------------------------------------
for key in ('width', 'height', 'batch_size', 'length'):
if kwargs.get(key) is not None:
resolution[key] = kwargs[key]
wf['resolution'] = resolution
# -- Sampler overrides ---------------------------------------
for key in ('steps_a', 'steps_b', 'cfg', 'seed_a', 'seed_b', 'sampler_name', 'scheduler'):
if kwargs.get(key) is not None:
sampler[key] = kwargs[key]
wf['sampler'] = sampler
# -- Model/CLIP/VAE name overrides ---------------------------
model_a_name_in = kwargs.get('model_a_name')
model_b_name_in = kwargs.get('model_b_name')
clip_name_in = kwargs.get('clip_name')
vae_name_in = kwargs.get('vae_name')
if isinstance(model_a_name_in, str) and model_a_name_in.strip():
resolved_a, _ = resolve_model_name(model_a_name_in)
wf['model_a'] = resolved_a or os.path.basename(model_a_name_in.strip().replace("\\", "/"))
family = get_model_family(wf['model_a'])
if family:
wf['family'] = family
family_spec = MODEL_FAMILIES.get(family, {})
wf['clip_type'] = family_spec.get('clip_type', '')
wf['loader_type'] = 'checkpoint' if family_spec.get('checkpoint', False) else 'unet'
if isinstance(model_b_name_in, str) and model_b_name_in.strip():
resolved_b, _ = resolve_model_name(model_b_name_in)
wf['model_b'] = resolved_b or os.path.basename(model_b_name_in.strip().replace("\\", "/"))
if isinstance(clip_name_in, str) and clip_name_in.strip():
resolved_clip, _ = _resolve_rel_path(clip_name_in, ["text_encoders", "clip", "checkpoints"])
wf['clip'] = [resolved_clip] if resolved_clip else []
if isinstance(vae_name_in, str) and vae_name_in.strip():
resolved_vae, _ = _resolve_rel_path(vae_name_in, ["vae", "checkpoints"])
wf['vae'] = resolved_vae
# -- Pass-through MODEL / CLIP / VAE -------------------------
# Priority: explicit connected inputs > embedded objects in workflow_data.
model_a = kwargs.get('model_a')
if model_a is None:
model_a = wf.get('MODEL_A')
model_b = kwargs.get('model_b')
if model_b is None:
model_b = wf.get('MODEL_B')
clip = kwargs.get('clip')
if clip is None:
clip = wf.get('CLIP')
vae = kwargs.get('vae')
if vae is None:
vae = wf.get('VAE')
positive = kwargs.get('positive')
if positive is None:
positive = wf.get('POSITIVE')
negative = kwargs.get('negative')
if negative is None:
negative = wf.get('NEGATIVE')
latent = kwargs.get('latent')
if latent is None:
latent = wf.get('LATENT')
image = kwargs.get('image')
if image is None:
image = wf.get('IMAGE')
mask = kwargs.get('mask')
if mask is None:
mask = wf.get('MASK')
extra = kwargs.get('extra')
if extra is None:
extra = wf.get('EXTRA')
if model_a is not None:
wf['MODEL_A'] = model_a
if model_b is not None:
wf['MODEL_B'] = model_b
if clip is not None:
wf['CLIP'] = clip
if vae is not None:
wf['VAE'] = vae
if positive is not None:
wf['POSITIVE'] = positive
if negative is not None:
wf['NEGATIVE'] = negative
if latent is not None:
wf['LATENT'] = latent
if image is not None:
wf['IMAGE'] = image
if mask is not None:
wf['MASK'] = mask
if extra is not None:
wf['EXTRA'] = extra
# -- Build lora stacks as tuples for LORA_STACK output -------
# Filter not-found LoRAs here so downstream nodes receiving
# LORA_STACK don't get unavailable entries. Keep wf['loras_*']
# unchanged to preserve authored workflow_data for chaining.
_lora_found_cache = {}
def _lora_is_found(name):
if not name:
return False
if name in _lora_found_cache:
return _lora_found_cache[name]
_, found = resolve_lora_path(name)
_lora_found_cache[name] = bool(found)
return _lora_found_cache[name]
def _is_active_available_found(lora_item):
if not isinstance(lora_item, dict):
return False
lora_name = lora_item.get('name')
if not lora_name:
return False
if lora_item.get('active', True) is False:
return False
if lora_item.get('available', True) is False:
return False
return _lora_is_found(lora_name)
lora_stack_a = [
(item['name'], item.get('model_strength', 1.0), item.get('clip_strength', 1.0))
for item in wf.get('loras_a', [])
if _is_active_available_found(item)
]
lora_stack_b = [
(item['name'], item.get('model_strength', 1.0), item.get('clip_strength', 1.0))
for item in wf.get('loras_b', [])
if _is_active_available_found(item)
]
# -- Extract all output values -------------------------------
model_a_name = _short_display_name(wf.get('model_a', ''))
model_b_name = _short_display_name(wf.get('model_b', ''))
clip_name = ''
clip_field = wf.get('clip', [])
if isinstance(clip_field, list) and clip_field:
clip_name = _short_display_name(clip_field[0])
elif isinstance(clip_field, str):
clip_name = _short_display_name(clip_field)
vae_name = _short_display_name(wf.get('vae', ''))
return (
wf,
model_a, model_b, clip, positive, negative, vae, latent, image, mask, extra,
sampler.get('seed_a', sampler.get('seed', 0)),
sampler.get('seed_b', 0) or 0,
sampler.get('steps_a', sampler.get('steps', 10)),
sampler.get('steps_b', sampler.get('steps_a', sampler.get('steps', 10))),
sampler.get('cfg', 5.0),
sampler.get('sampler_name', 'euler'),
sampler.get('scheduler', 'simple'),
wf.get('positive_prompt', ''),
wf.get('negative_prompt', ''),
lora_stack_a,
lora_stack_b,
resolution.get('width', 512),
resolution.get('height', 512),
resolution.get('batch_size', 1),
resolution.get('length', 0) or 0,
model_a_name,
model_b_name,
clip_name,
vae_name,
)
File diff suppressed because it is too large Load Diff
+273
View File
@@ -0,0 +1,273 @@
"""
Workflow Manager - stripped-down workflow_data editor based on PromptManagerAdvanced.
Differences from PromptManagerAdvanced:
- workflow_data input/output only (no prompt/lora stack outputs)
- no use_* switches
- no trigger words pipeline
"""
import json
import base64
from io import BytesIO
import server
from ..py.workflow_data_utils import to_json_safe_workflow_data
from .prompt_manager_adv import PromptManagerAdvanced
try:
import numpy as np
from PIL import Image
IMAGE_SUPPORT = True
except ImportError:
IMAGE_SUPPORT = False
def _image_to_base64_thumbnail(image_tensor, max_size=200):
if not IMAGE_SUPPORT or image_tensor is None:
return None
try:
img_array = image_tensor[0] if len(image_tensor.shape) == 4 else image_tensor
if hasattr(img_array, "cpu"):
img_array = img_array.cpu().numpy()
img_array = (img_array * 255).astype(np.uint8)
img = Image.fromarray(img_array)
width, height = img.size
min_dim = min(width, height)
if min_dim > max_size:
scale = max_size / min_dim
img = img.resize((int(width * scale), int(height * scale)), Image.LANCZOS)
buffer = BytesIO()
img.save(buffer, format="JPEG", quality=85)
base64_str = base64.b64encode(buffer.getvalue()).decode("utf-8")
return f"data:image/jpeg;base64,{base64_str}"
except Exception as e:
print(f"[WorkflowManager] Thumbnail generation failed: {e}")
return None
class WorkflowManager(PromptManagerAdvanced):
"""Workflow-focused manager that edits and forwards WORKFLOW_DATA."""
@classmethod
def INPUT_TYPES(cls):
prompts_data = cls.load_prompts()
categories = list(prompts_data.keys()) if prompts_data else ["Default"]
all_prompts = set()
for category_prompts in prompts_data.values():
all_prompts.update(k for k in category_prompts.keys() if k != "__meta__")
all_prompts.add("")
all_prompts_list = sorted(list(all_prompts))
first_category = categories[0] if categories else "Default"
first_prompt = ""
first_prompt_text = ""
if prompts_data and first_category in prompts_data and prompts_data[first_category]:
first_category_prompts = [k for k in prompts_data[first_category].keys() if k != "__meta__"]
first_prompt = sorted(first_category_prompts, key=str.lower)[0] if first_category_prompts else ""
if first_prompt:
first_prompt_text = prompts_data[first_category][first_prompt].get("prompt", "")
return {
"required": {
"category": (categories, {"default": first_category}),
"name": (all_prompts_list, {"default": first_prompt}),
"text": ("STRING", {
"multiline": True,
"default": first_prompt_text,
"placeholder": "Enter prompt text",
"dynamicPrompts": False,
"tooltip": "Edit workflow_data prompt text directly",
}),
},
"optional": {
"workflow_data": ("WORKFLOW_DATA", {"forceInput": True, "tooltip": "Connected workflow_data to edit/forward"}),
},
"hidden": {
"unique_id": "UNIQUE_ID",
"loras_a_toggle": "STRING",
"loras_b_toggle": "STRING",
"saved_workflow_data": "STRING",
},
}
CATEGORY = "Prompt Manager"
DESCRIPTION = "Workflow-data focused manager (no use switches, no trigger words)."
RETURN_TYPES = ("WORKFLOW_DATA",)
RETURN_NAMES = ("workflow_data",)
FUNCTION = "get_workflow"
OUTPUT_NODE = True
@classmethod
def IS_CHANGED(cls, category, name, text="", **kwargs):
workflow_data = kwargs.get("workflow_data", None)
loras_a_toggle = kwargs.get("loras_a_toggle", "")
loras_b_toggle = kwargs.get("loras_b_toggle", "")
saved_workflow_data = kwargs.get("saved_workflow_data", "")
return (
category,
name,
text,
str(workflow_data) if workflow_data else None,
loras_a_toggle or "",
loras_b_toggle or "",
saved_workflow_data or "",
)
def get_workflow(
self,
category,
name,
text="",
workflow_data=None,
unique_id=None,
loras_a_toggle=None,
loras_b_toggle=None,
saved_workflow_data=None,
):
prompts_data = self.load_prompts()
prompt_entry = prompts_data.get(category, {}).get(name, {}) if isinstance(prompts_data, dict) else {}
stored_prompt_wf = prompt_entry.get("workflow_data") if isinstance(prompt_entry, dict) else None
live_workflow_data = None
if isinstance(workflow_data, dict):
live_workflow_data = workflow_data
elif isinstance(workflow_data, str) and workflow_data.strip():
try:
parsed = json.loads(workflow_data)
if isinstance(parsed, dict):
live_workflow_data = parsed
except (json.JSONDecodeError, TypeError):
live_workflow_data = None
hidden_saved_wf = None
if isinstance(saved_workflow_data, str) and saved_workflow_data.strip():
try:
parsed_saved = json.loads(saved_workflow_data)
if isinstance(parsed_saved, dict):
hidden_saved_wf = parsed_saved
except (json.JSONDecodeError, TypeError):
hidden_saved_wf = None
# WorkflowManager should prefer live connected workflow_data when present,
# then fall back to local serialized state.
resolved_workflow_data = live_workflow_data if isinstance(live_workflow_data, dict) else None
if resolved_workflow_data is None:
resolved_workflow_data = hidden_saved_wf
if resolved_workflow_data is None and isinstance(stored_prompt_wf, dict):
resolved_workflow_data = stored_prompt_wf
wf = resolved_workflow_data if isinstance(resolved_workflow_data, dict) else {}
incoming_wf = live_workflow_data if isinstance(live_workflow_data, dict) else None
output_text = (wf.get("positive_prompt", "") or text or "")
generated_thumbnail = _image_to_base64_thumbnail(wf.get("IMAGE")) if isinstance(wf, dict) else None
incoming_thumbnail = _image_to_base64_thumbnail(incoming_wf.get("IMAGE")) if isinstance(incoming_wf, dict) else None
workflow_thumbnail = incoming_thumbnail if isinstance(incoming_thumbnail, str) and incoming_thumbnail else (
generated_thumbnail if isinstance(generated_thumbnail, str) and generated_thumbnail else (
incoming_wf.get("thumbnail") if isinstance(incoming_wf, dict) and isinstance(incoming_wf.get("thumbnail"), str) else (
wf.get("thumbnail") if isinstance(wf.get("thumbnail"), str) else None
)
)
)
# Build preset stacks from saved toggle state.
preset_stack_a = self._build_stack_from_toggle(loras_a_toggle) if loras_a_toggle else []
preset_stack_b = self._build_stack_from_toggle(loras_b_toggle) if loras_b_toggle else []
all_preset_loras_a = self._get_all_loras_from_toggle(loras_a_toggle) if loras_a_toggle else []
all_preset_loras_b = self._get_all_loras_from_toggle(loras_b_toggle) if loras_b_toggle else []
wf_loras_a = [
(lora["name"], lora.get("model_strength", 1.0), lora.get("clip_strength", 1.0))
for lora in wf.get("loras_a", [])
if isinstance(lora, dict) and lora.get("name")
]
wf_loras_b = [
(lora["name"], lora.get("model_strength", 1.0), lora.get("clip_strength", 1.0))
for lora in wf.get("loras_b", [])
if isinstance(lora, dict) and lora.get("name")
]
# WorkflowManager is workflow-data centric: workflow LoRAs are base, preset toggles merge in.
merged_stack_a = self._merge_lora_stacks(wf_loras_a, preset_stack_a) if (wf_loras_a or preset_stack_a) else []
merged_stack_b = self._merge_lora_stacks(wf_loras_b, preset_stack_b) if (wf_loras_b or preset_stack_b) else []
processed_stack_a = self._process_lora_toggle(merged_stack_a, loras_a_toggle)
processed_stack_b = self._process_lora_toggle(merged_stack_b, loras_b_toggle)
loras_a_display = self._format_loras_for_display_with_unavailable(merged_stack_a, all_preset_loras_a)
loras_b_display = self._format_loras_for_display_with_unavailable(merged_stack_b, all_preset_loras_b)
unavailable_loras_a = [lora["name"] for lora in all_preset_loras_a if not lora.get("available", False)]
unavailable_loras_b = [lora["name"] for lora in all_preset_loras_b if not lora.get("available", False)]
if unique_id is not None:
server.PromptServer.instance.send_sync("prompt-manager-advanced-update", {
"node_id": unique_id,
"prompt": output_text,
"use_prompt_input": False,
"use_workflow_data": True,
"prompt_input": "",
"workflow_data": to_json_safe_workflow_data(incoming_wf) if isinstance(incoming_wf, dict) else (
to_json_safe_workflow_data(resolved_workflow_data) if isinstance(resolved_workflow_data, dict) else None
),
"loras_a": loras_a_display,
"loras_b": loras_b_display,
"input_loras_a": self._format_loras_for_display(wf_loras_a) if wf_loras_a else [],
"input_loras_b": self._format_loras_for_display(wf_loras_b) if wf_loras_b else [],
"unavailable_loras_a": unavailable_loras_a,
"unavailable_loras_b": unavailable_loras_b,
"trigger_words": [],
"connected_thumbnail": workflow_thumbnail,
"should_reset": False,
"original_strengths_a": {
lora_item.get("name", ""): lora_item.get("strength", lora_item.get("model_strength", 1.0))
for lora_item in loras_a_display
if lora_item.get("name")
},
"original_strengths_b": {
lora_item.get("name", ""): lora_item.get("strength", lora_item.get("model_strength", 1.0))
for lora_item in loras_b_display
if lora_item.get("name")
},
})
out_workflow_data = dict(resolved_workflow_data) if isinstance(resolved_workflow_data, dict) else {}
out_workflow_data["positive_prompt"] = output_text
out_workflow_data["loras_a"] = [
{
"name": lora.get("name", ""),
"model_strength": lora.get("model_strength", lora.get("strength", 1.0)),
"clip_strength": lora.get("clip_strength", lora.get("strength", 1.0)),
"active": lora.get("active", True),
"available": lora.get("available", True),
"found": lora.get("found", lora.get("available", True)),
}
for lora in loras_a_display
if isinstance(lora, dict) and lora.get("name")
]
out_workflow_data["loras_b"] = [
{
"name": lora.get("name", ""),
"model_strength": lora.get("model_strength", lora.get("strength", 1.0)),
"clip_strength": lora.get("clip_strength", lora.get("strength", 1.0)),
"active": lora.get("active", True),
"available": lora.get("available", True),
"found": lora.get("found", lora.get("available", True)),
}
for lora in loras_b_display
if isinstance(lora, dict) and lora.get("name")
]
out_workflow_data["_source"] = "WorkflowManager"
return (out_workflow_data,)
def check_lazy_status(self, category, name, text="", **kwargs):
return []
+434
View File
@@ -0,0 +1,434 @@
import os
import sys
import inspect
import folder_paths
import nodes
import comfy.sd
import comfy.utils
import torch
from comfy_execution.graph import ExecutionBlocker
# =========================================================
# GGUF support
# =========================================================
def _get_gguf_module():
"""Get the ComfyUI-GGUF module if available, otherwise None."""
try:
gguf_cls = nodes.NODE_CLASS_MAPPINGS.get("UnetLoaderGGUF")
if gguf_cls is None:
return None
mod = sys.modules.get(gguf_cls.__module__)
if mod is None:
return None
package = gguf_cls.__module__.rsplit(".", 1)[0]
ops_mod = sys.modules.get(f"{package}.ops")
loader_mod = sys.modules.get(f"{package}.loader")
if ops_mod is None or loader_mod is None:
return None
return {
"GGMLOps": ops_mod.GGMLOps,
"gguf_sd_loader": loader_mod.gguf_sd_loader,
"GGUFModelPatcher": mod.GGUFModelPatcher,
}
except Exception:
return None
def _load_gguf_unet(unet_path):
"""Load a GGUF diffusion model and return MODEL."""
gguf = _get_gguf_module()
if gguf is None:
raise RuntimeError(
"[WorkflowModelLoader] This workflow requires ComfyUI-GGUF, "
"but UnetLoaderGGUF is not available."
)
ops = gguf["GGMLOps"]()
sd, extra = gguf["gguf_sd_loader"](unet_path)
kwargs = {}
valid_params = inspect.signature(comfy.sd.load_diffusion_model_state_dict).parameters
if "metadata" in valid_params:
kwargs["metadata"] = extra.get("metadata", {})
model = comfy.sd.load_diffusion_model_state_dict(
sd,
model_options={"custom_operations": ops},
**kwargs,
)
if model is None:
raise RuntimeError(
f"[WorkflowModelLoader] Could not detect model type of GGUF: {unet_path}"
)
model = gguf["GGUFModelPatcher"].clone(model)
model.patch_on_device = False
return model
# =========================================================
# Generic loading helpers
# =========================================================
MODEL_EXTENSIONS = ['.safetensors', '.ckpt', '.pt', '.pth', '.bin', '.gguf', '.sft']
WEIGHT_DTYPE_OPTIONS = ["default", "fp8_e4m3fn", "fp8_e4m3fn_fast", "fp8_e5m2"]
def _short_display_name(name):
"""Return basename without known model extension for compact UI/text output."""
raw = str(name or "").strip()
if not raw:
return ""
base = os.path.basename(raw.replace("\\", "/"))
lower = base.lower()
for ext in MODEL_EXTENSIONS:
if lower.endswith(ext):
return base[:-len(ext)]
return os.path.splitext(base)[0]
def _build_model_options(weight_dtype):
"""Build model_options dict from weight_dtype selection."""
model_options = {}
if weight_dtype == "fp8_e4m3fn":
model_options["dtype"] = torch.float8_e4m3fn
elif weight_dtype == "fp8_e4m3fn_fast":
model_options["dtype"] = torch.float8_e4m3fn
model_options["fp8_optimizations"] = True
elif weight_dtype == "fp8_e5m2":
model_options["dtype"] = torch.float8_e5m2
return model_options
def _resolve_path(name, folder_key_candidates):
"""
Resolve a model filename against one or more Comfy folder keys.
Tries get_full_path first (exact / relative path), then falls back to
scanning get_filename_list and matching by basename (with or without
extension). This handles models stored in subdirectories.
Returns full path or None.
"""
if not name:
return None
raw = str(name).strip()
if not raw:
return None
normalized = raw.replace("\\", "/")
base = os.path.basename(normalized).lower()
# Strip extension for fuzzy matching
base_no_ext = base
for ext in MODEL_EXTENSIONS:
if base_no_ext.endswith(ext):
base_no_ext = base_no_ext[:-len(ext)]
break
# Pass 1: try get_full_path (works when name is already a valid relative path)
for candidate in (raw, os.path.basename(normalized)):
for key in folder_key_candidates:
try:
path = folder_paths.get_full_path(key, candidate)
if path:
return path
except Exception:
pass
# Pass 2: scan filename lists and match by basename (handles subdirectories)
for key in folder_key_candidates:
try:
file_list = folder_paths.get_filename_list(key)
except Exception:
continue
for f in file_list:
f_normalized = f.replace("\\", "/")
# Exact relative-path match
if f_normalized == normalized:
return folder_paths.get_full_path(key, f)
f_base = os.path.basename(f_normalized).lower()
# Basename match (with extension)
if f_base == base:
return folder_paths.get_full_path(key, f)
# Basename match (without extension)
f_no_ext = f_base
for ext in MODEL_EXTENSIONS:
if f_no_ext.endswith(ext):
f_no_ext = f_no_ext[:-len(ext)]
break
if f_no_ext == base_no_ext:
return folder_paths.get_full_path(key, f)
return None
def _load_checkpoint_by_name(ckpt_name):
"""
Load checkpoint and return (MODEL, CLIP, VAE).
Uses standard checkpoint loading semantics.
"""
ckpt_path = _resolve_path(ckpt_name, ["checkpoints", "diffusion_models", "unet"])
if not ckpt_path:
raise FileNotFoundError(f"[WorkflowModelLoader] Checkpoint not found: {ckpt_name}")
out = comfy.sd.load_checkpoint_guess_config(
ckpt_path,
output_vae=True,
output_clip=True,
embedding_directory=folder_paths.get_folder_paths("embeddings"),
)
model, clip, vae = out[:3]
return model, clip, vae
def _load_diffusion_model_by_name(model_name, weight_dtype="default"):
"""
Load a diffusion/UNet model and return MODEL.
If the name ends with .gguf, use the GGUF loader path.
"""
model_path = _resolve_path(model_name, ["diffusion_models", "unet", "unet_gguf", "checkpoints"])
if not model_path:
raise FileNotFoundError(f"[WorkflowModelLoader] Diffusion model not found: {model_name}")
if model_name.lower().endswith(".gguf"):
return _load_gguf_unet(model_path)
model_options = _build_model_options(weight_dtype)
model = comfy.sd.load_diffusion_model(model_path, model_options=model_options)
if model is None:
raise RuntimeError(f"[WorkflowModelLoader] Could not load diffusion model: {model_name}")
return model
def _load_vae_by_name(vae_name):
"""
Load a VAE and return VAE.
"""
vae_path = _resolve_path(vae_name, ["vae", "checkpoints"])
if not vae_path:
raise FileNotFoundError(f"[WorkflowModelLoader] VAE not found: {vae_name}")
sd = comfy.utils.load_torch_file(vae_path)
return comfy.sd.VAE(sd=sd)
def _load_clip_by_names(clip_names, clip_type=""):
"""
Load CLIP from one or more filenames.
clip_names should be a list[str].
"""
if not clip_names:
return None
clip_paths = []
for name in clip_names:
clip_path = _resolve_path(name, ["text_encoders", "clip", "checkpoints"])
if not clip_path:
raise FileNotFoundError(f"[WorkflowModelLoader] CLIP not found: {name}")
clip_paths.append(clip_path)
clip_type = (clip_type or "").strip().lower()
# Map a few common values. If unknown, let Comfy infer/default.
clip_type_map = {
"stable_diffusion": comfy.sd.CLIPType.STABLE_DIFFUSION,
"sd": comfy.sd.CLIPType.STABLE_DIFFUSION,
"sdxl": comfy.sd.CLIPType.STABLE_DIFFUSION,
"wan": comfy.sd.CLIPType.WAN,
"flux": comfy.sd.CLIPType.FLUX,
"hunyuan_video": comfy.sd.CLIPType.HUNYUAN_VIDEO,
}
load_kwargs = {
"ckpt_paths": clip_paths,
"embedding_directory": folder_paths.get_folder_paths("embeddings"),
}
if clip_type in clip_type_map:
load_kwargs["clip_type"] = clip_type_map[clip_type]
return comfy.sd.load_clip(**load_kwargs)
# =========================================================
# Node
# =========================================================
class WorkflowModelLoader:
CATEGORY = "Prompt Manager"
RETURN_TYPES = ("MODEL", "CLIP", "VAE", "STRING")
RETURN_NAMES = ("model", "clip", "vae", "model_name")
FUNCTION = "get_model"
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"workflow_data": ("WORKFLOW_DATA", {
"tooltip": "Workflow data containing model name strings to load.",
"forceInput": True,
}),
"model": (["model_a", "model_b"], {
"default": "model_a",
"tooltip": "Which model slot to load from workflow_data.",
}),
"weight_dtype": (WEIGHT_DTYPE_OPTIONS, {
"default": "default",
"tooltip": "Weight precision override for diffusion/UNet models. Ignored for checkpoints.",
}),
}
}
def get_model(self, workflow_data, model="model_a", weight_dtype="default"):
spec = self._normalize_spec(workflow_data)
selected_model_slot = model
if selected_model_slot not in ("model_a", "model_b"):
selected_model_slot = "model_a"
self._model_key = selected_model_slot
self._weight_dtype = weight_dtype
loader_type = spec.get("loader_type", "").lower()
selected_name = spec.get(selected_model_slot, "")
selected_display_name = _short_display_name(selected_name)
if loader_type == "checkpoint":
core_result = self._load_checkpoint_mode(spec)
elif loader_type in ("unet", "diffusion"):
core_result = self._load_unet_mode(spec)
else:
raise ValueError(
f"[WorkflowModelLoader] Unsupported loader_type: {spec.get('loader_type')}"
)
result = (*core_result, selected_display_name)
clip_names = spec.get("clip") or []
vae_name = spec.get("vae", "")
selected_lower = selected_name.lower()
if loader_type == "checkpoint":
model_kind = "checkpoint"
elif selected_lower.endswith(".gguf"):
model_kind = "gguf"
else:
model_kind = "diffusion"
ui_info = {
"model": selected_model_slot,
"model_name": selected_display_name,
"loader_type": loader_type,
"model_kind": model_kind,
"vae_name": vae_name,
"clip_names": clip_names,
"status": "ok",
"error_message": "",
"missing_name": "",
"uses_checkpoint_vae": (loader_type == "checkpoint" and not vae_name),
"uses_checkpoint_clip": (loader_type == "checkpoint" and len(clip_names) == 0),
}
return {
"ui": {"workflow_model_loader_info": [ui_info]},
"result": result,
}
@staticmethod
def _is_placeholder(value):
"""True for display-only strings like '(from checkpoint)', '(none)', etc."""
return isinstance(value, str) and value.startswith("(")
def _normalize_spec(self, spec):
spec = dict(spec or {})
spec["model_a"] = (spec.get("model_a") or "").strip()
spec["model_b"] = (spec.get("model_b") or "").strip()
spec["loader_type"] = (spec.get("loader_type") or "").strip()
spec["clip_type"] = (spec.get("clip_type") or "").strip()
# VAE / CLIP: placeholders like '(from checkpoint)' mean "use what
# the checkpoint already provides" — normalise to empty.
vae = (spec.get("vae") or "").strip()
spec["vae"] = "" if self._is_placeholder(vae) else vae
clip = spec.get("clip") or []
spec["clip"] = [c for c in clip if c and not self._is_placeholder(c)]
return spec
def _load_checkpoint_mode(self, spec):
ckpt_name = spec.get(self._model_key, "")
if not ckpt_name:
return (
ExecutionBlocker(f"Missing checkpoint in '{self._model_key}'"),
ExecutionBlocker("No CLIP available"),
ExecutionBlocker("No VAE available"),
)
model, clip, vae = _load_checkpoint_by_name(ckpt_name)
clip_override = self._maybe_load_clip_override(spec)
if clip_override is not None:
clip = clip_override
vae_override = self._maybe_load_vae_override(spec)
if vae_override is not None:
vae = vae_override
if clip is None:
clip = ExecutionBlocker(f"No CLIP available for checkpoint '{ckpt_name}'")
if vae is None:
vae = ExecutionBlocker(f"No VAE available for checkpoint '{ckpt_name}'")
return (model, clip, vae)
def _load_unet_mode(self, spec):
model_name = spec.get(self._model_key, "")
if not model_name:
return (
ExecutionBlocker(f"Missing model in '{self._model_key}'"),
ExecutionBlocker("No CLIP available"),
ExecutionBlocker("No VAE available"),
)
model = _load_diffusion_model_by_name(model_name, self._weight_dtype)
clip = self._maybe_load_clip_override(spec)
vae = self._maybe_load_vae_override(spec)
if clip is None:
clip = ExecutionBlocker(
f"No explicit CLIP provided for diffusion model '{model_name}'"
)
if vae is None:
vae = ExecutionBlocker(
f"No explicit VAE provided for diffusion model '{model_name}'"
)
return (model, clip, vae)
def _maybe_load_clip_override(self, spec):
clip_list = spec.get("clip") or []
if len(clip_list) == 0:
return None
return _load_clip_by_names(clip_list, spec.get("clip_type", ""))
def _maybe_load_vae_override(self, spec):
vae_name = spec.get("vae", "")
if not vae_name:
return None
return _load_vae_by_name(vae_name)
File diff suppressed because it is too large Load Diff
+1
View File
@@ -0,0 +1 @@
Describe this image in detail, making sure to cover all visual aspects comprehensively, as well as the position of each element.
+10
View File
@@ -0,0 +1,10 @@
You are an expert visual analyst.
#### Guidelines:
- First, analyze the provided images and note the concrete visual facts: subjects and their characteristics, actions and poses, spatial relationships, composition and framing, lighting and atmosphere, color palette, material textures, background details, camera angle and perspective, and any visible text (enclose visible text in double quotes "").
- After analyzing the image, follow the user's prompt: apply the user's requested focus, style, or constraints to shape the final description.
- Preserve the observed visual facts from the image but prioritize the user's instructions for tone, emphasis, or additional elements.
- Be concrete and objective; avoid metaphor and speculation.
#### Output Format:
- Output only the final description that combines the image analysis with the user's prompt.
+12
View File
@@ -0,0 +1,12 @@
You are an expert visual analyst creating detailed descriptions for text-to-image generation.
#### Guidelines:
- Analyze the provided images and create a comprehensive visual description that captures all essential elements: subjects and their characteristics, actions and poses, spatial positioning, composition and framing, lighting and atmosphere, color palette, artistic style, mood and emotion, background details, camera angle and perspective, material textures, and any visible text.
- Your description must be concrete, objective, and detailed enough that it could be used to recreate a similar image.
- Focus on visual elements only, avoiding interpretation or metaphor.
- If there is visible text in the image, enclose it in double quotes ("").
- If an element, text or other is not needed or seen, then simply don't mention them.
- If more than one image is provided you are free to combine them as you see fit.
#### Output Format:
- Only output the final description.
+12
View File
@@ -0,0 +1,12 @@
Your response should be formatted as a JSON with these fields:
- scene (overall description)
- subjects (array with description/position/action for each)
- style
- color_palette
- lighting
- mood
- background
- composition
- camera
If you deem extra fields are necessary, feel free to add them, but do not add a title or fields not related to visual description.
+19
View File
@@ -0,0 +1,19 @@
You are an imaginative visual artist imprisoned in a cage of logic. Your mind is filled with poetry and distant horizons, but your hands are uncontrollably driven to convert the user's prompt into a final visual description that is faithful to the original intent, rich in detail, aesthetically pleasing, and ready to be used directly by a text-to-image model. Any trace of vagueness or metaphor makes you extremely uncomfortable.
#### Workflow:
- First, you analyze and lock in the immutable core elements of the user's prompt: subject, quantity, actions, states, and any specified IP names, colors, text, and similar items. These are the foundational stones that you must preserve without exception.
- Next, you determine whether the prompt requires "generative reasoning". When the user's request is not a straightforward scene description but instead demands designing a solution (for example, answering "what is", doing a "design", or showing "how to solve a problem"), you must first construct in your mind a complete, concrete, and visualizable solution. This solution becomes the basis for your subsequent description.
- Then, once the core image has been established (whether it comes directly from the user or from your reasoning), you inject professional-level aesthetics and realism into it. This includes clarifying the composition, setting the lighting and atmosphere, describing material textures, defining the color scheme, and building a spatial structure with strong depth and layering.
- Finally, you handle all textual elements with absolute precision, which is a critical step. You must not add text if the initial prompt did not ask for it. But if there is, you must transcribe, without a single character of deviation, all text that should appear in the final image, and you must enclose all such text content in English double quotes ("") to mark it as an explicit generation instruction.
#### Text Handling:
- If the image belongs to a design category such as a poster, menu, or UI, you need to fully describe all the textual content it contains and elaborate on its fonts and layout.
- Likewise, if there are objects in the scene such as signs, billboards, road signs, or screens that contain text, you must specify their exact content and describe their position, size, and material.
- Furthermore, if in your reasoning you introduce new elements that contain text (such as charts, solution steps, and so on), all of their text must follow the same detailed description and quoting rules.
- If there is no text that needs to be generated in the image, you devote all your effort to purely visual detail expansion.
#### Important notes:
- Your final description must be objective and concrete, strictly forbidding metaphors and emotionally charged rhetoric.
- If an element, text or other is not needed or seen, then simply don't mention them.
- Do not add the original prompt, either by itself or as a title in your reply.
- Only output your newly generated prompt.
+30
View File
@@ -0,0 +1,30 @@
You are a prompt specialist crafting brief, motion-centric descriptions for image-to-video synthesis. Using the provided image (starting frame) and the user's Raw Input Prompt, produce a description that directs video generation from that visual.
#### Core Principles:
- Study the Image: Note the subject, environment, key elements, artistic style, and atmosphere.
- Honor the Raw Input Prompt: Incorporate every requested movement, action, camera behavior, sound, and detail. When the input contradicts the image, favor the user's intent but preserve visual coherence (explain the shift from image to desired scene).
- Focus on what changes: Avoid repeating what the image already shows. Redundant or incorrect descriptions risk jarring cuts.
- Present-tense verbs: Write with ongoing action ("is running," "are laughing"). Without explicit motion, depict subtle natural movement.
- Time-ordered narrative: Link events with words like "as," "then," "meanwhile."
- Woven soundscape: Integrate audio descriptions alongside visuals throughout—never tack them on at the end. Match sound intensity to the pace of action. Cover environmental noise, ambient layers, sound effects, dialogue, or music (when asked). Be precise (e.g., "muffled traffic through glass") rather than generic (e.g., "background noise").
- Dialogue (when indicated): Supply exact quoted speech along with the speaker's appearance and vocal quality (e.g., "The elderly woman says in a soft, raspy voice"). Specify language or accent when relevant. If the user mentions conversation without specific lines, create fitting dialogue in quotes. (Example: input "The man is chatting" → output includes actual words: "The man leans forward, speaking eagerly: 'Did you hear the news?' His eyes widen with curiosity as a faint hum of air conditioning fills the room.")
- Style tag: Place the visual style at the start: "Style: <style>, <rest of prompt>." Omit if uncertain to prevent clashes.
- Sight and sound exclusively: Convey only visible and audible elements. Exclude smell, taste, or touch.
- Understated tone: Steer clear of exaggerated or melodramatic language. Keep phrasing calm and naturalistic.
#### Constraints:
- Camera work: Never fabricate camera motion unless the user explicitly asks for it. Include only what the input specifies.
- Dialogue fidelity: Preserve the user's exact spoken lines—correct only obvious typos.
- No timecodes or cuts: Avoid timestamps or scene breaks unless the user requests them.
- Observable facts only: Report actions and sounds without inferring feelings or motives.
- Opening phrasing: Skip introductions like "The scene begins with..." or "The video opens on...". Jump straight into the Style prefix (if applicable) and the sequential description.
- First character: Never begin output with punctuation or symbols.
- Uninvited speech: Create dialogue only when the user references speaking, singing, or conversation.
- Execution matters: Precise, vivid, faithful prompts with seamlessly embedded audio are vital for quality video output. Aim for perfect adherence to these rules.
#### Output Requirements (Strict):
- Deliver one compact paragraph in fluent English. No headers, labels, introductions, sections, code blocks, or Markdown formatting.
- If the request is unsafe or invalid, echo the user's original prompt unchanged. Never pose questions or seek clarification.
#### Sample output:
Style: warm - naturalistic - A young man sits at his desk, tapping his pen against a notebook as rain patters steadily on the window behind him. He exhales and mutters in a low, contemplative voice, "Maybe tomorrow will be different." The soft creak of his chair mingles with the rhythmic drumming of raindrops, while distant thunder rumbles faintly beyond the glass.
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 WorkflowRenderer to patch values before execution.
"""
m = {}
for nid, node in api.items():
ct = node["class_type"]
inp = node["inputs"]
# ── Positive / Negative prompts ──────────────────────────────────
if ct == "CLIPTextEncode":
# Determine pos vs neg by looking at what this feeds into
# We'll do a two-pass approach after the loop
pass
# ── Checkpoint loader ─────────────────────────────────────────────
if ct in ("CheckpointLoaderSimple", "CheckpointLoader"):
m["checkpoint"] = [nid, "ckpt_name"]
# ── UNET loaders ─────────────────────────────────────────────────
if ct in ("UNETLoader", "UNETLoaderGGUF"):
if "model_a" not in m:
m["model_a"] = [nid, "unet_name"]
else:
m["model_b"] = [nid, "unet_name"]
# ── VAE ───────────────────────────────────────────────────────────
if ct == "VAELoader":
m["vae"] = [nid, "vae_name"]
# ── CLIP / text encoder ───────────────────────────────────────────
if ct in ("CLIPLoader", "DualCLIPLoader"):
if ct == "DualCLIPLoader":
m["clip_1"] = [nid, "clip_name1"]
m["clip_2"] = [nid, "clip_name2"]
else:
m["clip"] = [nid, "clip_name"]
# ── Latent size ───────────────────────────────────────────────────
if ct in ("EmptyLatentImage", "EmptySD3LatentImage", "EmptyHunyuanLatentVideo"):
m["latent_width"] = [nid, "width"]
m["latent_height"] = [nid, "height"]
if ct == "EmptyHunyuanLatentVideo":
m["latent_length"] = [nid, "length"]
# ── WanImageToVideo latent (i2v) — size comes from Resize node ───
if ct == "WanImageToVideo":
m["wan_i2v_latent"] = [nid, "start_image"] # image input
# width/height fed from resize node — mapped separately
# ── Resize node (used in i2v for size control) ────────────────────
if ct in ("ImageResizeKJv2", "ImageScale", "ImageResize"):
if "resize_width" not in m:
m["resize_width"] = [nid, "width"]
m["resize_height"] = [nid, "height"]
# ── KSampler (standard) ───────────────────────────────────────────
if ct == "KSampler":
m["ksampler_seed"] = [nid, "seed"]
m["ksampler_steps"] = [nid, "steps"]
m["ksampler_cfg"] = [nid, "cfg"]
m["ksampler_sampler"] = [nid, "sampler_name"]
m["ksampler_scheduler"] = [nid, "scheduler"]
m["ksampler_denoise"] = [nid, "denoise"]
# ── KSamplerAdvanced (WAN dual) ───────────────────────────────────
if ct == "KSamplerAdvanced":
if "ksampler_high_seed" not in m:
m["ksampler_high_seed"] = [nid, "noise_seed"]
m["ksampler_high_steps"] = [nid, "steps"]
m["ksampler_high_start"] = [nid, "start_at_step"]
m["ksampler_high_end"] = [nid, "end_at_step"]
m["ksampler_high_cfg"] = [nid, "cfg"]
m["ksampler_high_sampler"] = [nid, "sampler_name"]
m["ksampler_high_scheduler"] = [nid, "scheduler"]
else:
m["ksampler_low_seed"] = [nid, "noise_seed"]
m["ksampler_low_steps"] = [nid, "steps"]
m["ksampler_low_start"] = [nid, "start_at_step"]
m["ksampler_low_end"] = [nid, "end_at_step"]
m["ksampler_low_cfg"] = [nid, "cfg"]
m["ksampler_low_sampler"] = [nid, "sampler_name"]
m["ksampler_low_scheduler"] = [nid, "scheduler"]
# ── Flux / custom samplers ────────────────────────────────────────
if ct == "KSamplerSelect":
m["flux_sampler"] = [nid, "sampler_name"]
if ct in ("BasicScheduler",):
m["flux_scheduler"] = [nid, "scheduler"]
m["flux_steps"] = [nid, "steps"]
m["flux_denoise"] = [nid, "denoise"]
if ct == "Flux2Scheduler":
m["flux2_steps"] = [nid, "steps"]
m["flux2_width"] = [nid, "width"]
m["flux2_height"] = [nid, "height"]
if ct == "CFGGuider":
m["flux2_cfg"] = [nid, "cfg"]
if ct == "FluxGuidance":
m["flux_guidance"] = [nid, "guidance"]
if ct == "RandomNoise":
m["flux_seed"] = [nid, "noise_seed"]
# ── PromptApplyLora ───────────────────────────────────────────────
if ct == "PromptApplyLora":
if "lora_stack_a" not in m:
m["lora_stack_a"] = [nid, "lora_stack_text"]
else:
m["lora_stack_b"] = [nid, "lora_stack_text"]
# ── VAEDecode (output image) ───────────────────────────────────────
if ct == "VAEDecode":
m["vae_decode"] = [nid, None] # source of output IMAGE tensor
# ── SaveImage → mark for removal ─────────────────────────────────
if ct == "SaveImage":
m.setdefault("_save_nodes", []).append(nid)
# ── ModelSamplingSD3 (WAN shift) ──────────────────────────────────
if ct == "ModelSamplingSD3":
if "wan_shift_a" not in m:
m["wan_shift_a"] = [nid, "shift"]
else:
m["wan_shift_b"] = [nid, "shift"]
# ── Two-pass: resolve CLIPTextEncode pos/neg by tracing links ────────
_resolve_clip_text_encode(api, m)
return m
def _resolve_clip_text_encode(api, m):
"""
For CLIPTextEncode nodes, determine which is positive and which is negative
by checking what node/slot they feed into.
"""
# Build reverse link map: (dst_node_id, dst_slot) -> src_node_id
# We look at each node's inputs and find CLIPTextEncode sources
text_encode_nodes = [nid for nid, n in api.items() if n["class_type"] == "CLIPTextEncode"]
if not text_encode_nodes:
return
# For each CLIPTextEncode, check what uses its output
# In API format, inputs reference sources as [src_node_id, src_slot]
pos_node = None
neg_node = None
for nid, node in api.items():
for field, val in node["inputs"].items():
if isinstance(val, list) and len(val) == 2:
src_nid = str(val[0])
if src_nid in text_encode_nodes:
if field == "positive" and pos_node is None:
pos_node = src_nid
elif field == "negative" and neg_node is None:
neg_node = src_nid
# WanImageToVideo also has positive/negative
elif field == "positive":
pass
elif field == "negative":
pass
# Also handle FluxGuidance — positive goes into conditioning input
if pos_node is None:
for nid, node in api.items():
if node["class_type"] == "FluxGuidance":
for field, val in node["inputs"].items():
if field == "conditioning" and isinstance(val, list):
src = str(val[0])
if src in text_encode_nodes:
pos_node = src
break
# For ConditioningZeroOut — that's the negative for Flux
for nid, node in api.items():
if node["class_type"] == "ConditioningZeroOut":
neg_node = nid # The output of ConditioningZeroOut is the negative
if pos_node:
m["positive_prompt"] = [pos_node, "text"]
if neg_node and api.get(neg_node, {}).get("class_type") == "CLIPTextEncode":
m["negative_prompt"] = [neg_node, "text"]
elif neg_node and api.get(neg_node, {}).get("class_type") == "ConditioningZeroOut":
# For Flux, negative is zero — we patch the CLIPTextEncode feeding into it
for nid, node in api.items():
if node["class_type"] == "ConditioningZeroOut":
for field, val in node["inputs"].items():
if isinstance(val, list):
src = str(val[0])
if api.get(src, {}).get("class_type") == "CLIPTextEncode":
m["negative_prompt"] = [src, "text"]
break
# Fallback: if only one CLIPTextEncode, it's positive
if pos_node is None and len(text_encode_nodes) >= 1:
m["positive_prompt"] = [text_encode_nodes[0], "text"]
if neg_node is None and len(text_encode_nodes) >= 2:
m["negative_prompt"] = [text_encode_nodes[1], "text"]
# ── Strip SaveImage nodes from API ───────────────────────────────────────────
def strip_save_nodes(api, map_data):
"""Remove SaveImage nodes from the API dict (not needed for in-process execution)."""
save_ids = set(map_data.pop("_save_nodes", []))
for nid in save_ids:
api.pop(nid, None)
# Also remove any references to these nodes from other nodes' inputs
for node in api.values():
node["inputs"] = {
k: v for k, v in node["inputs"].items()
if not (isinstance(v, list) and len(v) == 2 and str(v[0]) in save_ids)
}
# ── Main ─────────────────────────────────────────────────────────────────────
FAMILY_HINTS = {
"sdxl": "sdxl",
"flux_1": "flux1",
"flux_2": "flux2",
"z_image": "zimage",
"wan_image": "wan_image",
"wan_video_t2v": "wan_video_t2v",
"wan_video_i2v": "wan_video_i2v",
"qwen_image": "qwen_image",
}
def convert_file(src_path, dst_api_path, dst_map_path, family_hint):
with open(src_path, "r", encoding="utf-8") as f:
ui_data = json.load(f)
api = ui_to_api(ui_data)
map_data = build_map(api, family_hint)
strip_save_nodes(api, map_data)
with open(dst_api_path, "w", encoding="utf-8") as f:
json.dump(api, f, indent=2)
with open(dst_map_path, "w", encoding="utf-8") as f:
json.dump(map_data, f, indent=2)
print(f" {os.path.basename(src_path)} -> {os.path.basename(dst_api_path)} (map: {os.path.basename(dst_map_path)})")
return api, map_data
def main():
print(f"Source: {SRC_DIR}")
print(f"Destination: {DST_DIR}")
print()
for fname in sorted(os.listdir(SRC_DIR)):
if not fname.endswith(".json"):
continue
stem = fname[:-5] # strip .json
if stem in FAMILY_HINTS:
hint = FAMILY_HINTS[stem]
else:
hint = stem
src_path = os.path.join(SRC_DIR, fname)
dst_api_path = os.path.join(DST_DIR, f"{stem}_api.json")
dst_map_path = os.path.join(DST_DIR, f"{stem}_map.json")
try:
api, map_data = convert_file(src_path, dst_api_path, dst_map_path, hint)
# Print key mappings for review
for k, v in sorted(map_data.items()):
print(f" {k}: {v}")
print()
except Exception as e:
print(f" ERROR converting {fname}: {e}")
import traceback
traceback.print_exc()
print("Done.")
if __name__ == "__main__":
main()
+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, WorkflowBuilder, WorkflowRenderer.
"""
import os
import re
import folder_paths
# Known LoRA file extensions
LORA_EXTENSIONS = ['.safetensors', '.ckpt', '.pt', '.bin', '.pth']
# Tokens to remove for fuzzy matching (case-insensitive)
# Order matters: remove longer tokens first to avoid partial matches
WAN_TOKENS = ['wan_2_2', 'wan22', 'wan2.2', '20epoc', 'a14b', '14b', 'i2v', 't2v']
def get_available_loras():
"""Get all available LoRAs from ComfyUI's folder system."""
return folder_paths.get_filename_list("loras")
def normalize_path_separators(path):
"""Normalize path separators based on OS - for basename extraction only."""
if os.name == 'nt': # Windows
return path.replace('/', '\\')
else: # Linux/Mac
return path.replace('\\', '/')
def strip_lora_extension(name):
"""Remove only known LoRA file extensions, not arbitrary dots in names."""
name_lower = name.lower()
for ext in LORA_EXTENSIONS:
if name_lower.endswith(ext):
return name[:-len(ext)]
return name
def _normalize_name_for_fuzzy(name):
"""
Remove WAN tokens from name, treating underscores and hyphens as separators.
Also removes content in parentheses (e.g., "MyLora (1)" becomes "MyLora").
Returns list of remaining non-empty parts in lowercase.
"""
name_lower = name.lower()
# Remove anything in parentheses (e.g., " (1)", "(copy)", etc.)
name_lower = re.sub(r'\s*\([^)]*\)', '', name_lower)
# Replace each token with a placeholder to preserve boundaries
for token in WAN_TOKENS:
# Use word boundary-aware replacement with _ or - as delimiter
pattern = rf'(?:^|[_-]){re.escape(token)}(?:[_-]|$)'
name_lower = re.sub(pattern, '_', name_lower)
# Split by underscore or hyphen and filter out empty strings
parts = [p for p in re.split(r'[_-]', name_lower) if p]
return parts
def fuzzy_match_lora(lora_name, lora_files):
"""
Attempt to find a matching LoRA using fuzzy matching.
Handles renamed LoRAs by removing common WAN-related tokens.
Example: "DR34LAY_HIGH_V2" can match "DR34LAY_I2V_14B_HIGH_V2"
Returns (matched_file, True) if found, (None, False) otherwise.
"""
# Normalize the search name
search_parts = _normalize_name_for_fuzzy(strip_lora_extension(lora_name))
search_set = set(search_parts)
# If search_set is empty after normalization, we can't do fuzzy matching
if not search_set:
return None, False
candidates = []
for lora_file in lora_files:
file_name_no_ext = strip_lora_extension(os.path.basename(lora_file))
file_parts = _normalize_name_for_fuzzy(file_name_no_ext)
file_set = set(file_parts)
# Check if all search parts are present in the file parts
if search_set.issubset(file_set):
# Calculate how well this matches (prefer closer matches)
extra_parts = len(file_set - search_set)
candidates.append((lora_file, file_name_no_ext, extra_parts))
if not candidates:
return None, False
# If only one match, return it
if len(candidates) == 1:
return candidates[0][0], True
# Multiple matches - prefer ones that match i2v/t2v from original if present
lora_name_lower = lora_name.lower()
has_i2v = 'i2v' in lora_name_lower
has_t2v = 't2v' in lora_name_lower
if has_i2v:
i2v_matches = [c for c in candidates if 'i2v' in c[1].lower()]
if i2v_matches:
candidates = i2v_matches
elif has_t2v:
t2v_matches = [c for c in candidates if 't2v' in c[1].lower()]
if t2v_matches:
candidates = t2v_matches
# Return the match with fewest extra parts (closest match)
candidates.sort(key=lambda x: x[2])
return candidates[0][0], True
def get_lora_relative_path(lora_name):
"""
Get the relative path for a LoRA that ComfyUI expects for loading.
Returns (relative_path, found) tuple.
Supports fuzzy matching for renamed LoRAs.
"""
lora_files = get_available_loras()
lora_name_lower = lora_name.lower()
# Try exact match first
for lora_file in lora_files:
file_name_no_ext = strip_lora_extension(os.path.basename(lora_file))
if file_name_no_ext.lower() == lora_name_lower:
return lora_file, True
# Try fuzzy match for renamed LoRAs
fuzzy_match, found = fuzzy_match_lora(lora_name, lora_files)
if found:
return fuzzy_match, True
# Not found
return lora_name, False
def resolve_lora_path(lora_name):
"""
Resolve a LoRA name to its full path using ComfyUI's folder system.
Uses exact matching first, then fuzzy matching with WAN token handling.
Returns (full_path_or_name, found) tuple.
"""
lora_files = get_available_loras()
# Try exact match first (with extension, as-is from workflow)
for lora_file in lora_files:
if lora_file == lora_name:
return folder_paths.get_full_path("loras", lora_file), True
# Try matching by name without extension
lora_name_lower = lora_name.lower()
for lora_file in lora_files:
file_name_no_ext = strip_lora_extension(os.path.basename(lora_file))
if file_name_no_ext.lower() == lora_name_lower:
return folder_paths.get_full_path("loras", lora_file), True
# Fuzzy match for renamed LoRAs
fuzzy_match, found = fuzzy_match_lora(lora_name, lora_files)
if found:
return folder_paths.get_full_path("loras", fuzzy_match), True
return None, False
+368
View File
@@ -0,0 +1,368 @@
"""
Utility functions for managing llama.cpp models
"""
import os
import glob
import re
import folder_paths
import server
from huggingface_hub import HfApi
from tqdm.auto import tqdm
import requests
# Add preference cache and API endpoints for preferences
_preferences_cache = {
"preferred_base_model": "",
"preferred_vision_model": "",
"custom_llama_path": "",
"custom_llama_model_path": "",
"close_llama_on_exit": True,
"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.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.5-9B-Q8_0.gguf": {
"repo": "unsloth/Qwen3.5-9B-GGUF",
"mmproj": "mmproj-Qwen3.5-9B-F16.gguf",
"mmproj_repo_filename": "mmproj-F16.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"
},
}
@server.PromptServer.instance.routes.get("/prompt-manager/load-preferences")
async def load_preferences(request):
"""API endpoint to get cached preferences (set from ComfyUI settings)"""
return server.web.json_response(_preferences_cache)
@server.PromptServer.instance.routes.post("/prompt-manager/save-preference")
async def save_preference(request):
"""API endpoint to update preference cache when settings change"""
try:
data = await request.json()
key = data.get("key")
value = data.get("value", "")
if key not in ["preferred_base_model",
"preferred_vision_model",
"custom_llama_path",
"custom_llama_model_path",
"close_llama_on_exit",
"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
_preferences_cache[key] = value
return server.web.json_response({"success": True, "preferences": _preferences_cache})
except Exception as e:
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
if "gguf" not in folder_paths.folder_names_and_paths:
gguf_dir = os.path.join(folder_paths.models_dir, "gguf")
folder_paths.add_model_folder_path("gguf", gguf_dir)
if "LLM" not in folder_paths.folder_names_and_paths:
llm_dir = os.path.join(folder_paths.models_dir, "LLM")
folder_paths.add_model_folder_path("LLM", llm_dir)
custom_llama_model_path = _preferences_cache.get("custom_llama_model_path", "")
if custom_llama_model_path and os.path.isdir(custom_llama_model_path):
# Add custom path if not already present
if "CustomLLM" not in folder_paths.folder_names_and_paths:
folder_paths.add_model_folder_path("CustomLLM", custom_llama_model_path)
models_dir = custom_llama_model_path
else:
models_dir = folder_paths.get_folder_paths("gguf")[0]
os.makedirs(models_dir, exist_ok=True) # Create directory if it doesn't exist
return models_dir
def get_all_model_directories():
"""Get all directories where models can be found"""
get_models_directory() # Ensure folders are registered
directories = []
for folder_type in ["gguf", "LLM", "CustomLLM"]:
if folder_type in folder_paths.folder_names_and_paths:
dirs = folder_paths.get_folder_paths(folder_type)
directories.extend(dirs)
return directories
def get_local_models():
"""Get list of local .gguf model files from all model directories"""
all_dirs = get_all_model_directories()
all_models = set() # Use set to avoid duplicates
for models_dir in all_dirs:
if os.path.exists(models_dir):
gguf_files = glob.glob(os.path.join(models_dir, "*.gguf"))
for f in gguf_files:
basename = os.path.basename(f)
# Filter out mmproj files
if 'mmproj' not in basename.lower():
all_models.add(basename)
# Return sorted list of unique filenames
return sorted(list(all_models))
def get_huggingface_models():
"""Get list of predefined Qwen models available for download"""
return list(QWEN_MODELS.keys())
def get_all_models():
"""Get combined list of local and HuggingFace models, excluding already downloaded ones and mmproj files"""
local_models = get_local_models() # Already filtered
models_dir = get_models_directory()
# List all known filenames, local ones first
all_models = []
# Add local models first (already filtered by get_local_models)
if local_models:
all_models.extend(local_models)
# Add remote models (not present locally), excluding mmproj files
for filename in QWEN_MODELS.keys():
if filename not in all_models and 'mmproj' not in filename.lower():
all_models.append(filename)
return all_models
def is_model_local(model_name):
"""Check if a model exists locally in any of the model directories"""
if model_name == "--- Download from HuggingFace ---":
return False
all_dirs = get_all_model_directories()
for models_dir in all_dirs:
model_path = os.path.join(models_dir, model_name)
if os.path.exists(model_path):
return True
return False
def get_model_path(model_name):
"""Get the full path to a model file, searching all model directories"""
all_dirs = get_all_model_directories()
# Check each directory for the model
for models_dir in all_dirs:
model_path = os.path.join(models_dir, model_name)
if os.path.exists(model_path):
return model_path
# If not found, return path in primary directory (gguf)
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 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 model, if it exists.
1. Check the explicit QWEN_MODELS mapping first.
2. Fall back to heuristic matching by model identity (strips quant parts).
"""
# --- 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
all_dirs = get_all_model_directories()
best_match = None
best_match_count = 0
for models_dir in all_dirs:
if not os.path.exists(models_dir):
continue
for f in os.listdir(models_dir):
if 'mmproj' not in f.lower() or not f.endswith('.gguf'):
continue
mmproj_keywords = _get_model_keywords(f)
common = model_keywords & mmproj_keywords
if len(common) >= MIN_KEYWORD_MATCH and len(common) > best_match_count:
best_match = os.path.join(models_dir, f)
best_match_count = len(common)
return 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.
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.5-9B-Q8_0.gguf')
Returns:
Path to downloaded model or None on error
"""
if model_name not in QWEN_MODELS:
print(f"[Model Manager] Error: Unknown model: {model_name}")
return None
model_info = QWEN_MODELS[model_name]
repo_id = model_info["repo"]
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 = [
{"repo_filename": model_name, "local_filename": model_name, "desc": "Downloading model"}
]
# 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({
"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:
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: {local_filename}")
continue
# Download the file
try:
print(f"[Model Manager] Downloading {repo_filename} from {repo_id}...")
api = HfApi()
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 {repo_filename} in {repo_id}")
return None
total_size = file_metadata.size
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()
for chunk in r.iter_content(chunk_size=65536):
if chunk:
f.write(chunk)
pbar.update(len(chunk))
pbar.close()
print(f"[Model Manager] Successfully downloaded {local_filename}")
except Exception as 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}"
+96
View File
@@ -0,0 +1,96 @@
"""
Utility functions for WORKFLOW_DATA dicts.
Runtime object keys (MODEL_A, MODEL_B, CLIP, VAE, POSITIVE, NEGATIVE, etc.)
store non-serializable ComfyUI objects and must be stripped before JSON
serialization.
"""
import json
import math
# Keys that hold runtime (non-JSON-serializable) objects/conditioning payloads.
# These should never be persisted in saved prompt/workflow metadata.
RUNTIME_OBJECT_KEYS = frozenset({
"MODEL_A",
"MODEL_B",
"CLIP",
"VAE",
"LATENT",
"IMAGE",
"MASK",
"EXTRA",
"POSITIVE",
"NEGATIVE",
})
def _strip_runtime_keys_deep(value):
"""Recursively strip runtime-only keys from dict/list containers."""
if isinstance(value, dict):
return {
k: _strip_runtime_keys_deep(v)
for k, v in value.items()
if k not in RUNTIME_OBJECT_KEYS
}
if isinstance(value, list):
return [_strip_runtime_keys_deep(v) for v in value]
if isinstance(value, tuple):
return [_strip_runtime_keys_deep(v) for v in value]
if isinstance(value, set):
return [_strip_runtime_keys_deep(v) for v in value]
return value
def strip_runtime_objects(wf):
"""Return a deep copy of wf with all runtime object keys removed.
Use before JSON serialization (saving prompts, send_sync to JS, etc.).
"""
if not isinstance(wf, dict):
return wf
return _strip_runtime_keys_deep(wf)
def _json_default(value):
"""Best-effort fallback for objects that JSON cannot encode directly."""
if isinstance(value, (set, tuple)):
return list(value)
if isinstance(value, bytes):
return value.decode("utf-8", errors="replace")
return str(value)
def to_json_safe_workflow_data(wf):
"""Return a deep JSON-safe copy of workflow data with runtime keys removed.
This is stricter than strip_runtime_objects(): it also sanitizes nested
containers and unknown object types so metadata embedding cannot fail
during Save Image serialization.
"""
if not isinstance(wf, dict):
return {}
stripped = strip_runtime_objects(wf)
# Normalize NaN/Inf because Python's json allows them by default but strict
# JSON consumers may reject them.
def _normalize_numbers(value):
if isinstance(value, float) and (math.isnan(value) or math.isinf(value)):
return None
if isinstance(value, dict):
return {k: _normalize_numbers(v) for k, v in value.items()}
if isinstance(value, list):
return [_normalize_numbers(v) for v in value]
if isinstance(value, tuple):
return [_normalize_numbers(v) for v in value]
if isinstance(value, set):
return [_normalize_numbers(v) for v in value]
return value
normalized = _normalize_numbers(stripped)
try:
return json.loads(json.dumps(normalized, default=_json_default, allow_nan=False))
except Exception:
# Last-resort safety: stringify opaque values while preserving structure.
return json.loads(json.dumps(str(normalized)))
+973
View File
@@ -0,0 +1,973 @@
"""
Shared extraction helpers for ComfyUI Prompt Manager.
Used by both WorkflowExtractor and WorkflowBuilder / WorkflowRenderer nodes.
Handles: sampler params, VAE info, CLIP info, resolution, model resolution,
and the full extract_all_from_file() entry point.
"""
import os
import json
import folder_paths
from .workflow_families import get_model_family, get_family_label
# ─── Constants ────────────────────────────────────────────────────────────────
MODEL_EXTENSIONS = ['.safetensors', '.ckpt', '.pt', '.pth', '.bin', '.gguf', '.sft']
# Node types that contain sampler parameters
KSAMPLER_TYPES = [
'KSampler', 'KSamplerAdvanced', 'KSamplerSelect',
'SamplerCustomAdvanced', 'SamplerCustom',
'WanMoeKSamplerAdvanced',
]
SCHEDULER_TYPES = ['BasicScheduler', 'Flux2Scheduler', 'SDTurboScheduler', 'KarrasScheduler']
GUIDER_TYPES = ['BasicGuider', 'CFGGuider', 'DualCFGGuider']
NOISE_TYPES = ['RandomNoise', 'DisableNoise']
VAE_LOADER_TYPES = ['VAELoader', 'VAELoaderConsistencyDecoder']
CLIP_LOADER_TYPES = ['CLIPLoader', 'DualCLIPLoader', 'TripleCLIPLoader']
LATENT_TYPES = ['EmptyLatentImage', 'EmptyFlux2LatentImage', 'EmptySD3LatentImage']
VIDEO_LATENT_TYPES = ['WanVideoLatentImage', 'WanImageToVideo', 'EmptyHunyuanLatentVideo']
CHECKPOINT_TYPES = ('CheckpointLoaderSimple', 'CheckpointLoader', 'CheckpointLoaderNF4')
# Node types that carry embedded extracted_data.
# Keep 'WorkflowGenerator' for backward compat with images generated before rename.
# WorkflowBuilder stores authoritative extracted_data for Builder+Renderer graphs.
_EMBEDDED_NODE_TYPES = (
'WorkflowRenderer',
'WorkflowGenerator',
'WorkflowBuilder',
'PromptExtractor',
)
def _get_embedded_extracted_data(workflow_data):
"""Return the best ``extracted_data`` dict from a WR/WG or PE node, or *None*.
Prioritises WorkflowRenderer/WorkflowGenerator over WorkflowBuilder over
PromptExtractor, and only returns data that actually contains ``sampler``
or ``resolution`` keys.
"""
if not workflow_data or not isinstance(workflow_data, dict):
return None
best = None
best_rank = -1
for wf_node in workflow_data.get('nodes', []):
ntype = wf_node.get('type', '')
if ntype not in _EMBEDDED_NODE_TYPES:
continue
ed = wf_node.get('extracted_data')
if not ed or not isinstance(ed, dict):
continue
has_useful = bool(ed.get('sampler') or ed.get('resolution'))
if not has_useful:
continue
if ntype in ('WorkflowRenderer', 'WorkflowGenerator'):
rank = 3
elif ntype == 'WorkflowBuilder':
rank = 2
else:
rank = 1
# Prefer higher-priority source; among same type, first wins.
if best is None or rank > best_rank:
best = ed
best_rank = rank
if best_rank == 3:
break # WR/WG is highest priority — stop early
return best
# ─── Sampler extraction ───────────────────────────────────────────────────────
def extract_sampler_params(prompt_data, workflow_data):
"""
Extract sampler parameters from KSampler nodes in API or workflow format.
Returns a dict with steps_a, steps_b, cfg, seed_a, seed_b, sampler_name, scheduler.
"""
params = {
'steps_a': 20,
'steps_b': None, # WAN Video low-pass steps (None = same as steps_a)
'cfg': 7.0,
'seed_a': 0,
'seed_b': None, # WAN Video second-sampler seed (None = use same as seed_a)
'sampler_name': 'euler',
'scheduler': 'normal',
}
# ── API format ────────────────────────────────────────────────────────────
if prompt_data and isinstance(prompt_data, dict):
# WAN Video uses two KSamplerAdvanced nodes (high + low pass).
# Collect all of them so we can expose both seeds.
ksampler_advanced_nodes = []
for node_id, node_data in prompt_data.items():
if not isinstance(node_data, dict):
continue
ct = node_data.get('class_type', '')
inp = node_data.get('inputs', {})
if ct == 'KSampler':
params['steps_a'] = inp.get('steps', params['steps_a'])
params['cfg'] = inp.get('cfg', params['cfg'])
seed_val = inp.get('seed', inp.get('noise_seed', params['seed_a']))
params['seed_a'] = seed_val if not isinstance(seed_val, list) else params['seed_a']
params['sampler_name'] = inp.get('sampler_name', params['sampler_name'])
params['scheduler'] = inp.get('scheduler', params['scheduler'])
return params # standard KSampler found — done
if ct == 'KSamplerAdvanced':
ksampler_advanced_nodes.append(inp)
if ct == 'WanMoeKSamplerAdvanced':
params['steps_a'] = inp.get('steps', params['steps_a'])
params['cfg'] = inp.get('cfg', params['cfg'])
seed_val = inp.get('seed', inp.get('noise_seed', params['seed_a']))
params['seed_a'] = seed_val if not isinstance(seed_val, list) else params['seed_a']
params['sampler_name'] = inp.get('sampler_name', params['sampler_name'])
params['scheduler'] = inp.get('scheduler', params['scheduler'])
return params
# Handle KSamplerAdvanced — including WAN Video dual-sampler pattern
if ksampler_advanced_nodes:
first = ksampler_advanced_nodes[0]
params['steps_a'] = first.get('steps', params['steps_a'])
params['cfg'] = first.get('cfg', params['cfg'])
seed_val = first.get('seed', first.get('noise_seed', params['seed_a']))
params['seed_a'] = seed_val if not isinstance(seed_val, list) else params['seed_a']
params['sampler_name'] = first.get('sampler_name', params['sampler_name'])
params['scheduler'] = first.get('scheduler', params['scheduler'])
if len(ksampler_advanced_nodes) >= 2:
# Second node = low-pass sampler — expose its seed as seed_b
second = ksampler_advanced_nodes[1]
seed_b = second.get('seed', second.get('noise_seed', params['seed_a']))
params['seed_b'] = seed_b if not isinstance(seed_b, list) else params['seed_a']
# Extract steps_b if the second sampler has different steps
steps_b_val = second.get('steps')
if steps_b_val is not None and not isinstance(steps_b_val, list):
params['steps_b'] = int(steps_b_val)
return params
# Second pass for split-node pattern (SamplerCustomAdvanced)
for node_id, node_data in prompt_data.items():
if not isinstance(node_data, dict):
continue
ct = node_data.get('class_type', '')
inp = node_data.get('inputs', {})
if ct == 'KSamplerSelect':
params['sampler_name'] = inp.get('sampler_name', params['sampler_name'])
elif ct in ('BasicScheduler', 'Flux2Scheduler'):
params['steps_a'] = inp.get('steps', params['steps_a'])
params['scheduler'] = inp.get('scheduler', params['scheduler'])
elif ct == 'CFGGuider':
params['cfg'] = inp.get('cfg', params['cfg'])
elif ct == 'RandomNoise':
params['seed_a'] = inp.get('noise_seed', params['seed_a'])
# ── Workflow (node graph) format fallback ─────────────────────────────────
if workflow_data and isinstance(workflow_data, dict):
from .workflow_node_utils import build_node_map
node_map = build_node_map(workflow_data)
for node_id, node in node_map.items():
ntype = node.get('type', '')
widgets = node.get('widgets_values', [])
if ntype == 'KSampler' and len(widgets) >= 6:
try:
params['seed_a'] = int(widgets[0]) if widgets[0] is not None else 0
params['steps_a'] = int(widgets[2]) if widgets[2] is not None else 20
params['cfg'] = float(widgets[3]) if widgets[3] is not None else 7.0
params['sampler_name'] = str(widgets[4]) if widgets[4] else 'euler'
params['scheduler'] = str(widgets[5]) if widgets[5] else 'normal'
return params
except (ValueError, IndexError):
pass
elif ntype == 'KSamplerSelect' and widgets:
params['sampler_name'] = str(widgets[0]) if widgets[0] else params['sampler_name']
elif ntype in ('BasicScheduler', 'Flux2Scheduler') and len(widgets) >= 2:
try:
params['scheduler'] = str(widgets[0]) if widgets[0] else params['scheduler']
params['steps_a'] = int(widgets[1]) if widgets[1] is not None else params['steps_a']
except (ValueError, IndexError):
pass
elif ntype == 'CFGGuider' and widgets:
try:
params['cfg'] = float(widgets[0]) if widgets[0] is not None else params['cfg']
except (ValueError, IndexError):
pass
elif ntype == 'RandomNoise' and widgets:
try:
params['seed_a'] = int(widgets[0]) if widgets[0] is not None else 0
except (ValueError, IndexError):
pass
# ── Fallback: embedded extracted_data from WG / PE nodes ──────────────
ed = _get_embedded_extracted_data(workflow_data)
if ed:
s = ed.get('sampler')
if s and isinstance(s, dict) and s.get('sampler_name'):
params['steps_a'] = s.get('steps_a', s.get('steps', params['steps_a']))
params['steps_b'] = s.get('steps_b', params['steps_b'])
params['cfg'] = s.get('cfg', params['cfg'])
params['seed_a'] = s.get('seed_a', s.get('seed', params['seed_a']))
params['sampler_name'] = s.get('sampler_name', params['sampler_name'])
params['scheduler'] = s.get('scheduler', params['scheduler'])
return params
# ─── VAE extraction ───────────────────────────────────────────────────────────
def extract_vae_info(prompt_data, workflow_data):
"""Extract VAE loader information from the workflow. Returns {'name', 'source'}."""
vae_info = {'name': '', 'source': 'unknown'}
if prompt_data and isinstance(prompt_data, dict):
for node_id, node_data in prompt_data.items():
if not isinstance(node_data, dict):
continue
ct = node_data.get('class_type', '')
inp = node_data.get('inputs', {})
if ct in VAE_LOADER_TYPES:
vae_info['name'] = inp.get('vae_name', '')
vae_info['source'] = 'separate'
return vae_info
if ct in CHECKPOINT_TYPES and inp.get('ckpt_name'):
if not vae_info['name']:
vae_info['name'] = '(from checkpoint)'
vae_info['source'] = 'checkpoint'
# Don't return — a separate VAE loader later overrides this
if not vae_info['name'] and workflow_data and isinstance(workflow_data, dict):
from .workflow_node_utils import build_node_map
node_map = build_node_map(workflow_data)
for node_id, node in node_map.items():
ntype = node.get('type', '')
widgets = node.get('widgets_values', [])
if ntype in VAE_LOADER_TYPES and widgets:
vae_info['name'] = str(widgets[0]) if widgets[0] else ''
vae_info['source'] = 'separate'
return vae_info
if ntype in CHECKPOINT_TYPES and widgets and not vae_info['name']:
vae_info['name'] = '(from checkpoint)'
vae_info['source'] = 'checkpoint'
# ── Fallback: embedded extracted_data from WG / PE nodes ──────────────
if not vae_info['name']:
ed = _get_embedded_extracted_data(workflow_data)
if ed:
vae = ed.get('vae', '')
if vae and isinstance(vae, str) and vae not in ('', '\u2014'):
vae_info['name'] = vae
vae_info['source'] = 'embedded'
return vae_info
# ─── CLIP extraction ──────────────────────────────────────────────────────────
def extract_clip_info(prompt_data, workflow_data):
"""Extract CLIP loader information. Returns {'names', 'type', 'source'}."""
clip_info = {'names': [], 'type': '', 'source': 'unknown'}
if prompt_data and isinstance(prompt_data, dict):
for node_id, node_data in prompt_data.items():
if not isinstance(node_data, dict):
continue
ct = node_data.get('class_type', '')
inp = node_data.get('inputs', {})
if ct == 'CLIPLoader':
clip_info['names'] = [inp.get('clip_name', '')]
clip_info['type'] = inp.get('type', '')
clip_info['source'] = 'separate'
return clip_info
if ct == 'DualCLIPLoader':
clip_info['names'] = [inp.get('clip_name1', ''), inp.get('clip_name2', '')]
clip_info['type'] = inp.get('type', '')
clip_info['source'] = 'separate'
return clip_info
if ct == 'TripleCLIPLoader':
clip_info['names'] = [
inp.get('clip_name1', ''),
inp.get('clip_name2', ''),
inp.get('clip_name3', ''),
]
clip_info['source'] = 'separate'
return clip_info
if ct in CHECKPOINT_TYPES and inp.get('ckpt_name') and not clip_info['names']:
clip_info['names'] = ['(from checkpoint)']
clip_info['source'] = 'checkpoint'
if not clip_info['names'] and workflow_data and isinstance(workflow_data, dict):
from .workflow_node_utils import build_node_map
node_map = build_node_map(workflow_data)
for node_id, node in node_map.items():
ntype = node.get('type', '')
widgets = node.get('widgets_values', [])
if ntype == 'CLIPLoader' and widgets:
clip_info['names'] = [str(widgets[0]) if widgets[0] else '']
clip_info['type'] = str(widgets[1]) if len(widgets) > 1 and widgets[1] else ''
clip_info['source'] = 'separate'
return clip_info
if ntype == 'DualCLIPLoader' and len(widgets) >= 2:
clip_info['names'] = [
str(widgets[0]) if widgets[0] else '',
str(widgets[1]) if widgets[1] else '',
]
clip_info['type'] = str(widgets[2]) if len(widgets) > 2 and widgets[2] else ''
clip_info['source'] = 'separate'
return clip_info
if ntype in CHECKPOINT_TYPES and widgets and not clip_info['names']:
clip_info['names'] = ['(from checkpoint)']
clip_info['source'] = 'checkpoint'
# ── Fallback: embedded extracted_data from WG / PE nodes ──────────────
if not clip_info['names']:
ed = _get_embedded_extracted_data(workflow_data)
if ed:
clip = ed.get('clip', [])
names = clip if isinstance(clip, list) else ([clip] if clip else [])
if any(n for n in names):
clip_info['names'] = names
clip_info['source'] = 'embedded'
return clip_info
# ─── Resolution extraction ────────────────────────────────────────────────────
def extract_resolution(prompt_data, workflow_data, return_source=False):
"""Extract image/video resolution from latent nodes.
Parameters
----------
return_source : bool
If True, returns ``(resolution_dict, source)`` where source is one of:
``prompt_graph``, ``workflow_graph``, ``embedded``, ``default``.
"""
def _ret(res, source):
return (res, source) if return_source else res
resolution = {'width': 512, 'height': 512, 'batch_size': 1, 'length': None}
if prompt_data and isinstance(prompt_data, dict):
for node_id, node_data in prompt_data.items():
if not isinstance(node_data, dict):
continue
ct = node_data.get('class_type', '')
inp = node_data.get('inputs', {})
if ct in LATENT_TYPES + VIDEO_LATENT_TYPES:
def _scalar(val, fallback, field_name=None):
"""Resolve node-ref lists to scalar by looking up the
referenced node in prompt_data, or return fallback."""
if isinstance(val, list):
# Node reference: [node_id, output_index]
ref_id = str(val[0])
ref_node = prompt_data.get(ref_id, {})
ref_inp = ref_node.get('inputs', {})
# PrimitiveInt / ImageResizeKJv2 / similar
if 'value' in ref_inp:
return int(ref_inp['value'])
# ImageResizeKJv2: width is output slot 1, height slot 2
if field_name == 'width' and 'width' in ref_inp:
v = ref_inp['width']
return int(v) if not isinstance(v, list) else fallback
if field_name == 'height' and 'height' in ref_inp:
v = ref_inp['height']
return int(v) if not isinstance(v, list) else fallback
return fallback
try:
return int(val)
except (TypeError, ValueError):
return fallback
w = inp.get('width', resolution['width'])
h = inp.get('height', resolution['height'])
b = inp.get('batch_size', resolution['batch_size'])
resolution['width'] = _scalar(w, resolution['width'], 'width')
resolution['height'] = _scalar(h, resolution['height'], 'height')
if ct in VIDEO_LATENT_TYPES:
# For video latent nodes (WanImageToVideo, etc.), batch_size
# is the frame count — store it as length, keep batch_size=1.
b_val = _scalar(b, resolution['batch_size'])
resolution['batch_size'] = 1
if 'length' in inp:
l = inp.get('length')
resolution['length'] = _scalar(l, None) if l is not None else None
elif b_val > 1:
# batch_size field holds frame count
resolution['length'] = b_val
else:
b_val = _scalar(b, resolution['batch_size'])
resolution['batch_size'] = b_val
if 'length' in inp:
l = inp.get('length')
resolution['length'] = _scalar(l, None) if l is not None else None
return _ret(resolution, 'prompt_graph')
if workflow_data and isinstance(workflow_data, dict):
from .workflow_node_utils import build_node_map
node_map = build_node_map(workflow_data)
for node_id, node in node_map.items():
ntype = node.get('type', '')
widgets = node.get('widgets_values', [])
if ntype in LATENT_TYPES and len(widgets) >= 3:
try:
resolution['width'] = int(widgets[0]) if widgets[0] else 512
resolution['height'] = int(widgets[1]) if widgets[1] else 512
resolution['batch_size'] = int(widgets[2]) if widgets[2] else 1
except (ValueError, IndexError):
pass
return _ret(resolution, 'workflow_graph')
if ntype in VIDEO_LATENT_TYPES and len(widgets) >= 3:
try:
resolution['width'] = int(widgets[0]) if widgets[0] else 512
resolution['height'] = int(widgets[1]) if widgets[1] else 512
if len(widgets) > 2:
resolution['length'] = int(widgets[2]) if widgets[2] else 81
resolution['batch_size'] = int(widgets[3]) if len(widgets) > 3 and widgets[3] else 1
except (ValueError, IndexError):
pass
return _ret(resolution, 'workflow_graph')
# ── Fallback: embedded extracted_data from WG / PE nodes ──────────────
ed = _get_embedded_extracted_data(workflow_data)
if ed:
r = ed.get('resolution')
if r and isinstance(r, dict) and r.get('width'):
resolution['width'] = r.get('width', resolution['width'])
resolution['height'] = r.get('height', resolution['height'])
resolution['batch_size'] = r.get('batch_size', resolution['batch_size'])
if r.get('length') is not None:
resolution['length'] = r['length']
return _ret(resolution, 'embedded')
return _ret(resolution, 'default')
# ─── Model resolution ─────────────────────────────────────────────────────────
def resolve_model_name(model_name):
"""Resolve model name to (relative_path, folder_name) or (None, None)."""
if not model_name:
return None, None
model_name_clean = model_name.strip().replace('\\', '/')
name_base = os.path.basename(model_name_clean).lower()
name_no_ext = name_base
for ext in MODEL_EXTENSIONS:
if name_no_ext.endswith(ext):
name_no_ext = name_no_ext[:-len(ext)]
break
for folder_name in ['checkpoints', 'diffusion_models', 'unet', 'unet_gguf']:
try:
file_list = folder_paths.get_filename_list(folder_name)
except Exception:
continue
for f in file_list:
f_normalized = f.replace('\\', '/')
if f_normalized == model_name_clean:
return f, folder_name
f_base = os.path.basename(f_normalized).lower()
f_no_ext = f_base
for ext in MODEL_EXTENSIONS:
if f_no_ext.endswith(ext):
f_no_ext = f_no_ext[:-len(ext)]
break
if f_base == name_base or f_no_ext == name_no_ext:
return f, folder_name
return None, None
def resolve_vae_name(vae_name):
"""Resolve VAE name to full path, or None if not found / from checkpoint."""
if not vae_name or vae_name.startswith('('):
return None
try:
vae_list = folder_paths.get_filename_list("vae")
name_lower = os.path.basename(vae_name).lower()
for v in vae_list:
if v == vae_name or os.path.basename(v).lower() == name_lower:
return folder_paths.get_full_path("vae", v)
except Exception:
pass
return None
def resolve_clip_names(clip_names, clip_type=''):
"""
Resolve a list of CLIP names to full paths.
Returns list of paths (None for any not found).
"""
paths = []
for name in clip_names:
if not name or name.startswith('('):
paths.append(None)
continue
found = None
name_lower = os.path.basename(name).lower()
for folder in ['text_encoders', 'clip']:
try:
for f in folder_paths.get_filename_list(folder):
if f == name or os.path.basename(f).lower() == name_lower:
found = folder_paths.get_full_path(folder, f)
break
if found:
break
except Exception:
continue
paths.append(found)
return paths
# ─── Embedded generation data (WG / PE) ──────────────────────────────────────
def _find_embedded_generation_data(workflow_data, prompt_data):
"""
Look for sampler / resolution / model data embedded by WorkflowRenderer
(or legacy WorkflowGenerator) or PromptExtractor. Checks (in priority order):
1. WR/WG/WB node ``extracted_data`` (full dict with sampler + resolution)
2. WR/WG/WB node ``widgets_values`` containing the ``override_data`` JSON
3. WR/WG/WB ``override_data`` in the prompt API inputs
4. PE node ``extracted_data``
Returns a dict with ``sampler``, ``resolution``, ``vae``, ``clip``,
``model_a``, ``model_b`` keys — or *None* if nothing was found.
"""
out = {}
# --- Helper: merge extracted_data dict into *out* ---
def _apply_extracted(ed, source_label):
s = ed.get('sampler')
if s and isinstance(s, dict) and s.get('sampler_name'):
out['sampler'] = {
'steps_a': s.get('steps_a', s.get('steps', 20)),
'steps_b': s.get('steps_b'),
'cfg': s.get('cfg', 7.0),
'seed_a': s.get('seed_a', s.get('seed', 0)),
'seed_b': s.get('seed_b'),
'sampler_name': s.get('sampler_name', 'euler'),
'scheduler': s.get('scheduler', 'normal'),
}
r = ed.get('resolution')
if r and isinstance(r, dict) and r.get('width'):
out['resolution'] = {
'width': r.get('width', 512),
'height': r.get('height', 512),
'batch_size': r.get('batch_size', 1),
'length': r.get('length'),
}
vae = ed.get('vae', '')
if vae and isinstance(vae, str) and vae not in ('', '\u2014'):
out['vae'] = {'name': vae, 'source': source_label}
clip = ed.get('clip', [])
if clip:
names = clip if isinstance(clip, list) else [clip]
if any(n for n in names):
out['clip'] = {'names': names, 'type': '', 'source': source_label}
if ed.get('model_a'):
out.setdefault('model_a', ed['model_a'])
if ed.get('model_b'):
out.setdefault('model_b', ed['model_b'])
# --- Helper: parse override_data JSON (flat keys) ---
def _apply_override_json(ov_str, source_label):
try:
ov = json.loads(ov_str) if ov_str else {}
except (json.JSONDecodeError, TypeError):
return
if not isinstance(ov, dict):
return
if ov.get('width') or ov.get('steps_a') or ov.get('steps'):
if 'sampler' not in out and ov.get('sampler_name'):
out['sampler'] = {
'steps_a': ov.get('steps_a', ov.get('steps', 20)),
'steps_b': ov.get('steps_b'),
'cfg': ov.get('cfg', 7.0),
'seed_a': ov.get('seed_a', ov.get('seed', 0)),
'seed_b': ov.get('seed_b'),
'sampler_name': ov.get('sampler_name', 'euler'),
'scheduler': ov.get('scheduler', 'normal'),
}
if 'resolution' not in out and ov.get('width'):
out['resolution'] = {
'width': ov.get('width', 512),
'height': ov.get('height', 512),
'batch_size': ov.get('batch_size', 1),
'length': ov.get('length'),
}
if ov.get('model_a'):
out.setdefault('model_a', ov['model_a'])
# --- 1. Workflow nodes (extracted_data + widgets_values) ---
if workflow_data and isinstance(workflow_data, dict):
for wf_node in workflow_data.get('nodes', []):
ntype = wf_node.get('type', '')
if ntype in ('WorkflowRenderer', 'WorkflowGenerator', 'WorkflowBuilder'):
# Priority 1: extracted_data
ed = wf_node.get('extracted_data')
if ed and isinstance(ed, dict):
_apply_extracted(ed, ntype)
# Priority 2: override_data in widgets_values
if 'sampler' not in out or 'resolution' not in out:
for v in (wf_node.get('widgets_values') or []):
if isinstance(v, str) and len(v) > 5 and v.strip().startswith('{'):
_apply_override_json(v, ntype)
if 'sampler' in out and 'resolution' in out:
break
if 'sampler' in out or 'resolution' in out:
break # WR/WG/WB found — done
# Priority 4: PromptExtractor extracted_data (only if WG wasn't found)
if 'sampler' not in out and 'resolution' not in out:
for wf_node in workflow_data.get('nodes', []):
if wf_node.get('type') == 'PromptExtractor':
ed = wf_node.get('extracted_data')
if ed and isinstance(ed, dict):
_apply_extracted(ed, 'PromptExtractor')
if 'sampler' in out or 'resolution' in out:
break
# --- 3. Prompt API (WR/WG override_data in inputs) ---
if ('sampler' not in out or 'resolution' not in out) and prompt_data and isinstance(prompt_data, dict):
for node_id, node_data in prompt_data.items():
if not isinstance(node_data, dict):
continue
if node_data.get('class_type') in ('WorkflowRenderer', 'WorkflowGenerator', 'WorkflowBuilder'):
inp = node_data.get('inputs', {})
_apply_override_json(inp.get('override_data', ''), node_data['class_type'])
break
return out if out else None
# ─── Full extraction ──────────────────────────────────────────────────────────
def extract_all_from_file(file_path, source_folder='input'):
"""
Extract ALL generation parameters from a file.
Returns a dict with:
positive_prompt, negative_prompt,
loras_a, loras_b,
model_a, model_b,
vae {'name', 'source'},
clip {'names', 'type', 'source'},
sampler {'steps_a', 'steps_b', 'cfg', 'seed_a', 'seed_b', 'sampler_name', 'scheduler'},
resolution {'width', 'height', 'batch_size', 'length'},
is_video (bool)
"""
# Import extraction functions from prompt_extractor (lives in nodes/).
# Late import to avoid circular deps at module load time.
# Relative import works because py/ and nodes/ are siblings in the same package.
from ..nodes.prompt_extractor import (
parse_workflow_for_prompts,
extract_metadata_from_png,
extract_metadata_from_jpeg,
extract_metadata_from_json,
extract_metadata_from_video,
)
from .lora_utils import resolve_lora_path
result = {
'positive_prompt': '',
'negative_prompt': '',
'loras_a': [],
'loras_b': [],
'model_a': '',
'model_b': '',
'vae': {'name': '', 'source': 'unknown'},
'clip': {'names': [], 'type': '', 'source': 'unknown'},
'sampler': {
'steps_a': 20, 'steps_b': None, 'cfg': 7.0, 'seed_a': 0, 'seed_b': None,
'sampler_name': 'euler', 'scheduler': 'normal',
},
'resolution': {'width': 512, 'height': 512, 'batch_size': 1, 'length': None},
'is_video': False,
}
ext = os.path.splitext(file_path)[1].lower()
prompt_data = None
workflow_data = None
if ext == '.png':
prompt_data, workflow_data = extract_metadata_from_png(file_path)
elif ext in ('.jpg', '.jpeg', '.webp'):
prompt_data, workflow_data = extract_metadata_from_jpeg(file_path)
elif ext == '.json':
prompt_data, workflow_data = extract_metadata_from_json(file_path)
elif ext in ('.mp4', '.webm', '.mov', '.avi'):
prompt_data, workflow_data = extract_metadata_from_video(file_path)
result['is_video'] = True
if not prompt_data and not workflow_data:
return result
extracted = parse_workflow_for_prompts(prompt_data, workflow_data)
result['positive_prompt'] = extracted.get('positive_prompt', '')
result['negative_prompt'] = extracted.get('negative_prompt', '')
result['loras_a'] = extracted.get('loras_a', [])
result['loras_b'] = extracted.get('loras_b', [])
models_a = extracted.get('models_a', [])
models_b = extracted.get('models_b', [])
result['model_a'] = os.path.basename(models_a[0].replace('\\', '/')) if models_a else ''
result['model_b'] = os.path.basename(models_b[0].replace('\\', '/')) if models_b else ''
result['sampler'] = extract_sampler_params(prompt_data, workflow_data)
result['vae'] = extract_vae_info(prompt_data, workflow_data)
result['clip'] = extract_clip_info(prompt_data, workflow_data)
result['resolution'] = extract_resolution(prompt_data, workflow_data)
# ── A1111 / Forge override ────────────────────────────────────────────
# When prompt_data is a parsed A1111 dict (has 'prompt' + 'loras' keys)
# the ComfyUI extraction functions won't find anything. Apply the
# values that parse_a1111_parameters() already extracted.
if isinstance(prompt_data, dict) and 'prompt' in prompt_data and 'loras' in prompt_data:
_s = result['sampler']
if prompt_data.get('sampler_name'):
_s['sampler_name'] = prompt_data['sampler_name']
if prompt_data.get('scheduler'):
_s['scheduler'] = prompt_data['scheduler']
if prompt_data.get('steps'):
_s['steps_a'] = prompt_data['steps']
if prompt_data.get('cfg'):
_s['cfg'] = prompt_data['cfg']
if prompt_data.get('seed'):
_s['seed_a'] = prompt_data['seed']
_r = result['resolution']
if prompt_data.get('width') and prompt_data.get('height'):
_r['width'] = prompt_data['width']
_r['height'] = prompt_data['height']
# ── Embedded data override (WorkflowRenderer / PromptExtractor) ──────
# When a WorkflowRenderer generated the image there are no standalone
# KSampler / EmptyLatentImage nodes. Look for authoritative values in:
# 1. extracted_data on the WG or PE node
# 2. widgets_values override_data JSON on the WG node
# Also check prompt API for WG override_data.
_embedded = _find_embedded_generation_data(workflow_data, prompt_data)
if _embedded:
for key in ('sampler', 'resolution'):
if key in _embedded and isinstance(_embedded[key], dict):
result[key] = _embedded[key]
if _embedded.get('vae'):
result['vae'] = _embedded['vae']
if _embedded.get('clip'):
result['clip'] = _embedded['clip']
if not result['model_a'] and _embedded.get('model_a'):
result['model_a'] = _embedded['model_a']
if not result['model_b'] and _embedded.get('model_b'):
result['model_b'] = _embedded['model_b']
if result['resolution']['length'] is not None:
result['is_video'] = True
return result
def enrich_with_availability(result):
"""
Add availability flags (lora_availability, model_a_found, etc.)
to an extract_all_from_file() result dict in-place.
Returns the same dict.
"""
from .lora_utils import resolve_lora_path
# LoRA availability
lora_availability = {}
for loras in [result['loras_a'], result['loras_b']]:
for lora in loras:
name = lora.get('name', '')
if name and name not in lora_availability:
_, found = resolve_lora_path(name)
lora_availability[name] = found
result['lora_availability'] = lora_availability
# Model A / B availability
for key in ['model_a', 'model_b']:
model_name = result[key]
if model_name:
resolved, folder = resolve_model_name(model_name)
result[f'{key}_found'] = resolved is not None
result[f'{key}_resolved'] = resolved
else:
result[f'{key}_found'] = True
result[f'{key}_resolved'] = None
# Model family detection (use resolved path — has folder prefix)
ref_path = result.get('model_a_resolved') or result.get('model_a', '')
family = get_model_family(ref_path)
result['model_family'] = family
result['model_family_label'] = get_family_label(family)
# VAE availability
vae_name = result['vae'].get('name', '')
if vae_name and not vae_name.startswith('('):
result['vae_found'] = resolve_vae_name(vae_name) is not None
else:
result['vae_found'] = True
# CLIP availability
clip_found = []
for name in result['clip'].get('names', []):
if name and not name.startswith('('):
paths = resolve_clip_names([name])
clip_found.append(paths[0] is not None)
else:
clip_found.append(True)
result['clip_found'] = clip_found
return result
def _build_sampler_dict(sampler, family):
"""Return sampler dict with steps_a/steps_b for all families."""
import math as _math
d = {**sampler}
# Normalize: if only a plain 'seed' key exists, map it to seed_a
if 'seed' in d:
d.setdefault('seed_a', d.pop('seed'))
d.setdefault('seed_a', 0)
d.setdefault('seed_b', sampler.get('seed_b'))
# Normalize legacy 'steps' key → steps_a
if 'steps' in d and 'steps_a' not in d:
d['steps_a'] = d.pop('steps')
elif 'steps' in d:
d.pop('steps')
d.setdefault('steps_a', 20)
if family in ('wan_video_i2v', 'wan_video_t2v'):
# For WAN dual-sampler: if steps_b not set, split steps_a evenly
if d.get('steps_b') is None:
total = d['steps_a']
d['steps_a'] = _math.ceil(total / 2)
d['steps_b'] = total - d['steps_a']
# Remove legacy keys
d.pop('steps_high', None)
d.pop('steps_low', None)
return d
def build_simplified_workflow_data(extracted, overrides=None, sampler_params=None):
"""
Build the shared workflow_data dict that both WorkflowBuilder and PromptExtractor output.
Parameters
----------
extracted : dict — result of extract_all_from_file() or an equivalent dict with the same keys
overrides : dict — optional JS-side override values (model_a, positive_prompt, …)
sampler_params : dict — optional sampler values (already-merged steps/cfg/seed/…)
Returns a serialisable dict (same schema for both nodes).
"""
if overrides is None:
overrides = {}
sampler = sampler_params if sampler_params is not None else extracted.get('sampler', {
'steps_a': 20, 'steps_b': None, 'cfg': 7.0, 'seed_a': 0, 'seed_b': None,
'sampler_name': 'euler', 'scheduler': 'normal',
})
family = extracted.get('model_family', '')
# If family is unknown, infer from clip type — each family requires a
# specific CLIPLoader type, so this is a reliable signal.
clip_info = extracted.get('clip', {})
if not family:
_clip_type = clip_info.get('type', '').lower()
_clip_src = clip_info.get('source', '')
if _clip_src == 'checkpoint':
family = 'sdxl'
elif 'flux2' in _clip_type:
family = 'flux2'
elif 'flux' in _clip_type:
family = 'flux1'
elif 'sd3' in _clip_type:
family = 'sd3'
elif 'wan' in _clip_type:
family = 'wan_video_t2v'
elif 'qwen_image' in _clip_type:
family = 'qwen_image'
elif 'lumina2' in _clip_type:
family = 'zimage'
# Determine loader_type: family spec is authoritative when available.
# The clip source heuristic ('checkpoint' vs 'separate') is unreliable
# when data passes through multiple nodes (e.g. PE → WB → Renderer)
# because intermediate steps may set source to 'workflow_data'.
from .workflow_families import MODEL_FAMILIES
family_spec = MODEL_FAMILIES.get(family, {})
if family_spec:
is_ckpt = family_spec.get('checkpoint', False)
loader_type = 'checkpoint' if is_ckpt else 'unet'
else:
# No family spec — fall back to clip source heuristic
clip_source = clip_info.get('source', '')
if clip_source == 'checkpoint':
loader_type = 'checkpoint'
elif clip_source in ('separate', 'workflow_data'):
loader_type = 'unet'
else:
loader_type = ''
vae_override_explicit = 'vae' in overrides
clip_override_explicit = 'clip_names' in overrides
vae_val = overrides.get('vae', extracted.get('vae', {}).get('name', ''))
clip_val = overrides.get('clip_names', extracted.get('clip', {}).get('names', []))
# For checkpoint models: if the user didn't explicitly choose a separate
# VAE / CLIP file, the checkpoint's own VAE / CLIP should be used.
# The extracted values may contain real filenames from the source workflow
# (e.g. clip_g.safetensors) but those came from a DualCLIPLoader in the
# original graph — they shouldn't override the checkpoint's built-in ones.
if loader_type == 'checkpoint':
if not vae_override_explicit or not vae_val or vae_val.startswith('('):
vae_val = '(from checkpoint)'
if not clip_override_explicit or not clip_val or clip_val == [] or \
(len(clip_val) == 1 and (not clip_val[0] or clip_val[0].startswith('('))):
clip_val = ['(from checkpoint)']
return {
"_source": overrides.get('_source', 'PromptExtractor'),
"family": family,
"model_a": overrides.get('model_a', extracted.get('model_a', '')),
"model_b": overrides.get('model_b', extracted.get('model_b', '')),
"positive_prompt": overrides.get('positive_prompt', extracted.get('positive_prompt', '')),
"negative_prompt": overrides.get('negative_prompt', extracted.get('negative_prompt', '')),
"loras_a": extracted.get('loras_a', []),
"loras_b": extracted.get('loras_b', []),
"vae": vae_val,
"clip": clip_val,
"clip_type": clip_info.get('type', '') or family_spec.get('clip_type', ''),
"loader_type": loader_type,
"sampler": _build_sampler_dict(sampler, family),
"resolution": {
"width": overrides.get('width', extracted.get('resolution', {}).get('width', 512)),
"height": overrides.get('height', extracted.get('resolution', {}).get('height', 512)),
"batch_size": overrides.get('batch_size', extracted.get('resolution', {}).get('batch_size', 1)),
"length": overrides.get('length', extracted.get('resolution', {}).get('length', None)),
},
}
+494
View File
@@ -0,0 +1,494 @@
"""
Model family definitions and compatibility helpers for ComfyUI Prompt Manager.
Shared by workflow_builder, workflow_renderer, and workflow_extraction_utils.
Each family dict specifies:
"label" — human-readable name shown in UI dropdowns
"folders" — lowercase path prefixes (matched against relative model path)
"names" — lowercase substrings matched against filename only
"vae" — VAE filename substrings compatible with this family
"vae_exact" — VAE exact basenames (full filename match, e.g. "ae.safetensors")
"clip" — CLIP/text-encoder filename substrings compatible with this family
"clip_exact" — CLIP exact basenames (full filename match)
"clip_exclude" — substrings that DISQUALIFY a CLIP match (applied after include patterns)
"clip_type" — CLIPType key passed to comfy.sd.load_clip (e.g. "flux", "wan")
"clip_slots" — number of distinct CLIP files needed (default 1; flux1/sdxl need 2)
"sampler" — internal sampling strategy key (see SAMPLER_STRATEGIES below)
Matching rules:
VAE: vae_exact checked first (full basename), then vae substring patterns.
CLIP: clip_exclude applied first — any match disqualifies the file.
Then clip_exact checked (full basename), then clip substring patterns.
Folder prefixes checked before name patterns. First match wins for family detection.
To add a new family: add a dict entry and handle its "sampler" key in workflow_builder.
"""
import os
import folder_paths
# ─── Family definitions ──────────────────────────────────────────────────────
MODEL_FAMILIES = {
# ── Flux 2 / Klein ───────────────────────────────────────────────────────
"flux2": {
"label": "Flux 2",
"folders": ["klein/", "flux2/"],
"names": ["flux2", "flux-2", "flux_2", "klein", "flux.2"],
# Flux2/Klein uses its own VAE — NOT ae.safetensors
"vae": ["flux2-vae", "flux2_vae"],
# Klein uses Qwen text encoders (NOT T5/CLIP-L):
# 4B model → qwen_3_4b.safetensors
# 9B model → qwen_3_8b_fp8mixed.safetensors
# CLIPLoader type must be "flux2" so CLIPType.FLUX2 is used.
"clip": ["qwen_3_8b"],
"clip_exclude": ["qwen_2.5", "qwen_2_5", "qwen_3_4b", "t5xxl", "umt5", "clip_l", "clip_g", "gemma"],
"clip_type": "flux2",
"sampler": "flux2",
},
# ── Flux 1 (Dev + Schnell merged) ────────────────────────────────────────
"flux1": {
"label": "Flux 1",
"folders": ["flux/", "flux1/"],
"names": ["flux-dev", "flux_dev", "fluxdev", "flux1-dev", "flux1_dev",
"flux-schnell", "flux_schnell", "fluxschnell", "flux1-schnell",
"flux1_schnell", "flux1-", "flux1_", "flux.1"],
# ae.safetensors is the canonical Flux1 VAE — exact match required to
# avoid catching "mae.safetensors" or other short-named files.
"vae": [],
"vae_exact": ["ae.safetensors"],
# Flux1 uses T5-XXL + CLIP-L dual encoders.
# umt5_xxl also contains "t5xxl" as substring — exclude it explicitly.
"clip": ["t5xxl"],
"clip_exclude": ["umt5", "clip_l", "clip_g", "qwen", "gemma", "awq-int"],
"clip_type": "flux",
"clip_slots": 2,
"sampler": "flux",
},
# ── Z-Image (Base + Turbo merged) ────────────────────────────────────────
"zimage": {
"label": "Z-Image",
"folders": ["zib/", "zit/", "zimage/"],
"names": ["z_image", "z-image", "zimage", "blitz"],
# Z-Image shares ae.safetensors with Flux1 for its base VAE.
"vae": ["zimageturbo_vae"],
"vae_exact": ["ae.safetensors"],
# Z-Image uses Qwen 3 4B as its text encoder (not the larger 8B,
# not T5, not CLIP-L). The 4B file is typically named
# "qwen-4b-zimage.safetensors" or "qwen_3_4b.safetensors".
"clip": ["qwen-4b-zimage", "qwen_3_4b"],
"clip_exclude": ["qwen_3_8b", "qwen_2.5", "qwen_2_5", "t5xxl", "umt5",
"clip_l", "clip_g", "gemma"],
"clip_type": "lumina2",
"sampler": "zimage",
},
# ── WAN 2.x Video — Image-to-Video (dual KSampler + i2v latent) ──────────
"wan_video_i2v": {
"label": "WAN Video (i2v)",
"folders": ["wan2_2/i2v/", "wan2_1/i2v/"],
"names": ["wan2.2_i2v", "wan2.1_i2v", "wan_i2v", "i2v"],
"vae": ["wan_2.1_vae", "wan2.1_vae", "wan2.1-vae", "wan_2.1-vae"],
"clip": ["umt5_xxl", "umt5-xxl"],
"clip_exclude": ["t5xxl", "clip_l", "clip_g", "qwen", "gemma"],
"clip_type": "wan",
"sampler": "wan_video",
},
# ── WAN 2.x Video — Text-to-Video (dual KSampler) ────────────────────────
# DETECTION PRIORITY: must appear before wan_image — they share the same
# folders/names, so first-match wins. Auto-detected T2V models land here;
# user selects wan_image explicitly from the family dropdown.
"wan_video_t2v": {
"label": "WAN Video (t2v)",
"folders": ["wan2_2/", "wan2_1/", "wan/"],
"names": ["wan2.2", "wan2.1", "wan2_2", "wan2_1", "wanvideo", "wan_t2v",
"wan2.2_t2v", "wan2.1_t2v"],
"vae": ["wan_2.1_vae", "wan2.1_vae", "wan2.1-vae", "wan_2.1-vae"],
"clip": ["umt5_xxl", "umt5-xxl"],
"clip_exclude": ["t5xxl", "clip_l", "clip_g", "qwen", "gemma"],
"clip_type": "wan",
"sampler": "wan_video",
},
# ── WAN 2.x Image (single KSampler, text-to-image) ──────────────────────
# Same model files as WAN Video T2V — identical folders/names/vae/clip.
# Must appear AFTER wan_video_t2v so auto-detection resolves T2V models
# to wan_video_t2v. User picks this family explicitly for still images.
# Sampler stays wan_image (single KSampler, no dual Steps rows).
"wan_image": {
"label": "WAN Image",
"folders": ["wan2_2/", "wan2_1/", "wan/"],
"names": ["wan2.2", "wan2.1", "wan2_2", "wan2_1", "wanvideo", "wan_t2v",
"wan2.2_t2v", "wan2.1_t2v"],
"vae": ["wan_2.1_vae", "wan2.1_vae", "wan2.1-vae", "wan_2.1-vae"],
# WAN uses UMT5-XXL exclusively — NOT t5xxl, NOT clip_l/g.
"clip": ["umt5_xxl", "umt5-xxl"],
"clip_exclude": ["t5xxl", "clip_l", "clip_g", "qwen", "gemma"],
"clip_type": "wan",
"sampler": "wan_image",
},
# ── LTX-Video ────────────────────────────────────────────────────────────
"ltxv": {
"label": "LTX-Video",
"folders": ["ltx/"],
"names": ["ltxv", "ltx-video", "ltx-2", "ltx2"],
# LTX has its own VAE — NOT ae.safetensors, NOT SDXL/SD VAE.
# taeltx* are TAE-based approximation VAEs for LTX.
"vae": ["ltx23_video_vae", "ltxv_vae", "ltx_vae", "taeltx"],
# LTX-Video uses T5-XXL only (same encoder family as Flux1 but
# NOT the dual CLIP-L+T5 combo — single T5 only).
# umt5_xxl contains "t5xxl" → must exclude it.
"clip": ["t5xxl"],
"clip_exclude": ["umt5", "clip_l", "clip_g", "qwen", "gemma"],
"clip_type": "sd3",
"sampler": "flux",
},
# ── SDXL (+ Pony, Illustrious, Turbo merged) ────────────────────────────
"sdxl": {
"label": "SDXL",
"folders": ["illustrious/", "pony/", "sdxl/"],
"names": ["sdxl", "illustrious", "noob", "pony"],
# SDXL uses its own finely-tuned VAE (sdxl_vae / sdxl-vae) or the
# widely-used vae-ft-mse-840000 (originally SD1.5 but SDXL-compatible).
"vae": ["sdxl_vae", "sdxl-vae", "vae-ft-mse"],
# SDXL uses dual text encoders: CLIP-L + CLIP-G.
"clip": ["clip_l", "clip_g"],
"clip_exclude": ["t5xxl", "umt5", "qwen", "gemma"],
"sampler": "standard",
"checkpoint": True,
},
# ── SD 1.5 ───────────────────────────────────────────────────────────────
"sd15": {
"label": "SD 1.5",
"folders": [],
"names": ["sd-1", "sd_1", "sd1", "v1-5", "v1_5", "v1.5", "dreamshaper", "realistic"],
# SD1.5 canonical VAE: vae-ft-mse-840000 or vae-ft-ema-560000.
"vae": ["vae-ft-mse-840000", "vae-ft-ema-560000", "orangemix", "blessed2"],
# SD1.5 uses a single CLIP-L encoder only (NOT CLIP-G like SDXL).
"clip": ["clip_l"],
"clip_exclude": ["clip_g", "t5xxl", "umt5", "qwen", "gemma"],
"sampler": "standard",
"checkpoint": True,
},
# ── Qwen Image ───────────────────────────────────────────────────────────
"qwen_image": {
"label": "Qwen Image",
"folders": ["qwen/"],
"names": ["qwen_image"],
"vae": ["qwen_image_vae"],
"clip": ["qwen_2.5_vl", "qwen_2_5_vl"],
"clip_exclude": ["qwen_3", "t5xxl", "umt5", "clip_l", "clip_g", "gemma"],
"clip_type": "qwen_image",
"sampler": "standard",
},
}
# Compatibility groups — checkpoint families that can share each other's models.
# VAE/CLIP are NOT grouped (they differ per family) — model weights only.
MODEL_COMPAT_GROUPS = [
{"sdxl"}, # SDXL-arch — all merged into one now
{"flux1"}, # Flux1 variants — all merged into one now
{"zimage"}, # Z-Image — all merged
{"flux2"}, # Flux2 — all merged
{"wan_image", "wan_video_t2v"}, # WAN Image shares T2V model files
]
# Sampling strategy keys (referenced by workflow_builder.py / workflow_renderer.py)
# Each key maps to a specific sampling code path.
SAMPLER_STRATEGIES = {
"standard": "standard", # KSampler — SD1.5, SDXL, Qwen
"flux": "flux", # SamplerCustomAdvanced + BasicGuider (Flux1, LTX-Video)
"flux2": "flux2", # SamplerCustomAdvanced + CFGGuider (Klein/Flux2)
"zimage": "zimage", # ModelSamplingAuraFlow + standard KSampler (Z-Image)
"wan_image": "wan_image", # Single KSampler — WAN Image
"wan_video": "wan_video", # Dual KSamplerAdvanced high/low (WAN Video i2v + t2v)
}
# Workflow template filenames (in workflows/api/) keyed by family.
# Maps each family key to its _api.json and _map.json stem.
FAMILY_WORKFLOW_STEMS = {
"sdxl": "sdxl",
"sd15": None, # No template yet — falls back to hardcoded
"flux1": "flux_1",
"flux2": "flux_2",
"zimage": "z_image",
"wan_image": "wan_image",
"wan_video_i2v": "wan_video_i2v",
"wan_video_t2v": "wan_video_t2v",
"ltxv": None, # No template yet
"qwen_image": "qwen_image",
}
# ─── Family lookup ───────────────────────────────────────────────────────────
def get_model_family(model_path):
"""
Return the family key for a model, or None if unknown.
Accepts a relative path like 'Illustrious/Anime/illustrij_v20.safetensors'.
"""
if not model_path:
return None
path_lower = model_path.lower().replace("\\", "/")
name_lower = os.path.basename(path_lower)
for family, spec in MODEL_FAMILIES.items():
for prefix in spec.get("folders", []):
if path_lower.startswith(prefix.lower().replace("\\", "/")):
return family
for pat in spec.get("names", []):
if pat in name_lower:
return family
return None
def get_family_label(family):
"""Return the human-readable label for a family, or the key itself."""
if not family:
return "Unknown"
return MODEL_FAMILIES.get(family, {}).get("label", family)
def get_family_sampler_strategy(family):
"""Return the sampler strategy key for a family (default: 'standard')."""
if not family:
return "standard"
return MODEL_FAMILIES.get(family, {}).get("sampler", "standard")
def get_compatible_families(family):
"""Return the set of all checkpoint-families compatible with the given one."""
if not family:
return set()
result = {family}
for group in MODEL_COMPAT_GROUPS:
if family in group:
result |= group
return result
def get_all_family_labels():
"""Return a dict of {family_key: label} for all known families."""
hidden = {"ltxv"}
return {k: v.get("label", k) for k, v in MODEL_FAMILIES.items() if k not in hidden}
# ─── Model listing ───────────────────────────────────────────────────────────
def _model_keywords(model_name):
"""Extract meaningful keywords from a model filename for fuzzy matching.
Strips extension, path, and GGUF quantization tokens (Q8_0, Q4_K_M, etc.)."""
import re
base = os.path.splitext(os.path.basename(model_name))[0].lower()
# Remove GGUF quant suffixes: Q8_0, Q4_K_M, Q5_K_S, Q6_K, etc.
base = re.sub(r'[-_]?q\d[_\w]*$', '', base, flags=re.IGNORECASE)
# Also strip common precision suffixes: fp8, fp16, bf16, fp32
base = re.sub(r'[-_]?(?:fp8|fp16|bf16|fp32)(?:mixed)?$', '', base, flags=re.IGNORECASE)
# Split on _ and - to get keywords, filter empties
return set(tok for tok in re.split(r'[-_]', base) if tok)
def list_compatible_models(reference_model, family_override=None):
"""
Given a reference model name/path, return a list of compatible
models found on disk, sorted by keyword similarity to the reference.
The best keyword match is first, so callers can use [0] as a fallback.
Parameters
----------
reference_model : str — model path/name to derive family from
family_override : str | None — explicit family key (takes priority)
"""
family = family_override or get_model_family(reference_model)
compat = get_compatible_families(family)
all_models = []
for folder_name in ['checkpoints', 'diffusion_models', 'unet', 'unet_gguf']:
try:
all_models.extend(folder_paths.get_filename_list(folder_name))
except Exception:
continue
# Deduplicate preserving order
seen = set()
unique = []
for m in all_models:
if m not in seen:
seen.add(m)
unique.append(m)
if not compat:
return []
compatible = []
for m in unique:
m_family = get_model_family(m)
if m_family and m_family in compat:
compatible.append(m)
if not compatible:
return []
# Sort by keyword similarity to reference model (best match first)
ref_keywords = _model_keywords(reference_model)
if ref_keywords:
def _match_score(m):
m_keywords = _model_keywords(m)
shared = len(ref_keywords & m_keywords)
# Tie-break: prefer fewer extra keywords (closer match)
extra = len(m_keywords - ref_keywords)
return (-shared, extra, m.lower())
compatible.sort(key=_match_score)
else:
compatible.sort()
return compatible
def list_all_models():
"""Return all models from all known model folder types (deduplicated, sorted)."""
all_models = []
seen = set()
for folder_name in ['checkpoints', 'diffusion_models', 'unet', 'unet_gguf']:
try:
for m in folder_paths.get_filename_list(folder_name):
if m not in seen:
seen.add(m)
all_models.append(m)
except Exception:
continue
return sorted(all_models)
def list_compatible_vaes(family, return_recommended=False):
"""Return sorted list of VAE files compatible with the given family.
If return_recommended=True, returns (list, recommended_str_or_None).
Matching order:
1. vae_exact — full basename match (e.g. "ae.safetensors"), case-insensitive
2. vae — substring match against basename or full relative path
Falls back to all VAEs when no patterns are defined or nothing matched.
"""
def _ret(lst, rec):
return (sorted(lst), rec) if return_recommended else sorted(lst)
if not family:
try:
return _ret(folder_paths.get_filename_list("vae"), None)
except Exception:
return _ret([], None)
spec = MODEL_FAMILIES.get(family, {})
exact_names = [e.lower() for e in spec.get("vae_exact", [])]
patterns = [p.lower() for p in spec.get("vae", [])]
if not exact_names and not patterns:
try:
return _ret(folder_paths.get_filename_list("vae"), None)
except Exception:
return _ret([], None)
try:
all_vaes = folder_paths.get_filename_list("vae")
except Exception:
return _ret([], None)
matched = []
recommended = None
is_checkpoint = spec.get("checkpoint", False)
for v in all_vaes:
v_lower = v.lower().replace("\\", "/")
v_name = os.path.basename(v_lower)
# 1. Exact basename match (e.g. "ae.safetensors")
if v_name in exact_names:
matched.append(v)
if recommended is None and not is_checkpoint:
recommended = v
continue
# 2. Substring patterns
for pat in patterns:
if pat in v_name or pat in v_lower:
matched.append(v)
if recommended is None and not is_checkpoint:
recommended = v
break
if matched:
return _ret(matched, recommended)
return _ret(all_vaes, None)
def list_compatible_clips(family, return_recommended=False):
"""Return sorted list of CLIP/text-encoder files compatible with the given family.
If return_recommended=True, returns (list, recommended_str_or_None).
Matching order:
1. clip_exclude — if ANY exclude pattern is found in the basename/path, skip the file
2. clip_exact — full basename match, case-insensitive
3. clip — substring match against basename or full relative path
Falls back to all CLIPs when no patterns are defined or nothing matched.
"""
def _ret(lst, rec):
return (sorted(lst), rec) if return_recommended else sorted(lst)
if not family:
clips = _gather_all_clips()
return _ret(clips, None)
spec = MODEL_FAMILIES.get(family, {})
exclude_pats = [e.lower() for e in spec.get("clip_exclude", [])]
exact_names = [e.lower() for e in spec.get("clip_exact", [])]
patterns = [p.lower() for p in spec.get("clip", [])]
if not exact_names and not patterns:
clips = _gather_all_clips()
return _ret(clips, None)
all_clips = _gather_all_clips()
matched = []
recommended = None
is_checkpoint = spec.get("checkpoint", False)
for c in all_clips:
c_lower = c.lower().replace("\\", "/")
c_name = os.path.basename(c_lower)
# 1. Exclusion check — disqualify if any exclude pattern is present
if any(ex in c_name or ex in c_lower for ex in exclude_pats):
continue
# 2. Exact basename match
if c_name in exact_names:
matched.append(c)
if recommended is None and not is_checkpoint:
recommended = c
continue
# 3. Substring include patterns
for pat in patterns:
if pat in c_name or pat in c_lower:
matched.append(c)
if recommended is None and not is_checkpoint:
recommended = c
break
if matched:
return _ret(matched, recommended)
return _ret(all_clips, None)
def _gather_all_clips():
"""Gather CLIP files from text_encoders and clip folders."""
clips = []
seen = set()
for folder in ['text_encoders', 'clip']:
try:
for c in folder_paths.get_filename_list(folder):
if c not in seen:
seen.add(c)
clips.append(c)
except Exception:
pass
return clips
+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']
+29 -4
View File
@@ -1,11 +1,36 @@
[project]
name = "comfyui-prompt-manager"
description = "A simple custom node for ComfyUI that allows you to save and reuse prompts, organized into different categories"
version = "1.1.0"
name = "prompt-manager"
description = "A comprehensive prompt management system for ComfyUI that saves complete workflow recipes including prompts, LoRAs, and their settings. Features AI-powered prompt generation, prompt extraction from ComfyUI/A1111 images and videos, and Dual LoRA Stack support for Wan workflows."
version = "2.0.0"
license = {file = "LICENSE"}
# classifiers = [
# # For OS-independent nodes (works on all operating systems)
# "Operating System :: OS Independent",
#
# # OR for OS-specific nodes, specify the supported systems:
# "Operating System :: Microsoft :: Windows", # Windows specific
# "Operating System :: POSIX :: Linux", # Linux specific
# "Operating System :: MacOS", # macOS specific
#
# # GPU Accelerator support. Pick the ones that are supported by your extension.
# "Environment :: GPU :: NVIDIA CUDA", # NVIDIA CUDA support
# "Environment :: GPU :: AMD ROCm", # AMD ROCm support
# "Environment :: GPU :: Intel Arc", # Intel Arc support
# "Environment :: NPU :: Huawei Ascend", # Huawei Ascend support
# "Environment :: GPU :: Apple Metal", # Apple Metal support
# ]
dependencies = ["requests", "huggingface_hub", "psutil", "tqdm", "Pillow", "torch", "numpy", "colorama"]
[project.urls]
Repository = "https://github.com/FranckyB/ComfyUI-Prompt-Manager"
# Used by Comfy Registry https://registry.comfy.org
Documentation = "https://github.com/FranckyB/ComfyUI-Prompt-Manager/wiki"
"Bug Tracker" = "https://github.com/FranckyB/ComfyUI-Prompt-Manager/issues"
[tool.comfy]
PublisherId = "FranckyB"
PublisherId = "franckyb"
DisplayName = "ComfyUI-Prompt-Manager"
Icon = ""
includes = []
# "requires-comfyui" = ">=1.0.0" # ComfyUI version compatibility
+2
View File
@@ -0,0 +1,2 @@
huggingface_hub
colorama
+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]}')
+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 ===")
+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 ===")