Compare commits

..
199 Commits
Author SHA1 Message Date
FranckyB 68ab668373 Adding Extract workflow tool 2026-11-02 06:50:27 -05:00
FranckyB 43319e7330 Merge branch 'llama_test' 2026-11-01 11:06:25 -05:00
FranckyB 1db0e6a4f5 feat: enhance GPU detection and symlink handling in prompt generator 2026-11-01 10:58:33 -05:00
Francois Beaudry 54f99f67b7 Merge pull request #50 from FranckyB/llama_test
Fix for newer version of llama
2026-10-30 11:59:59 -04:00
FranckyB 7a894ccb90 fix for latest version of llama 2026-10-28 13:59:31 -04:00
FranckyB 3a182253eb Removed, now redundant Prompt Browser Node, sidebar adds same features 2026-10-28 02:01:09 -04:00
FranckyB b6b243c130 feat: update version to 3.0.0 in __init__.py and pyproject.toml 2026-10-28 01:30:34 -04:00
FranckyB fe5f1080df Add Krea layout workflow from image with prompt generation and image loading 2026-10-28 00:49:48 -04:00
FranckyB e258bd0c47 feat: Update Prompt Manager to use MANAGER_DATA instead of RECIPE_DATA
- Refactored PromptManagerAdvanced to introduce _PROMPT_MANAGER_RECIPE_KEY for better data handling.
- Changed input and output types in RecipeBuilder, WorkflowBuilder, and related classes to use MANAGER_DATA.
- Updated recipe_model_loader, recipe_relay, and recipe_renderer to accept and return MANAGER_DATA.
- Added new JavaScript file for Prompt Library Hub, enabling better management and interaction with saved prompts.
- Enhanced UI components for browsing, importing, and exporting prompts in the library hub.
2026-10-26 21:46:42 -04:00
FranckyB 8c0341771d feat: introduce Prompt Composer Manager for editing and saving compose_data with thumbnail support 2026-10-26 21:46:28 -04:00
FranckyB 433f0ef95c feat: rename Compose Manager to Composition Manager and enhance layout handling in prompt components 2026-10-26 04:02:47 -04:00
FranckyB d9b496df33 feat: add Prompt Layout Builder for MOSS-Image layouts
- Implemented a new node to create and manage MOSS-Image layouts.
- Added functionality to import and export layouts in various formats (JSON, percent, 0-1000).
- Introduced methods for cleaning and validating box data, converting between bounding boxes and layout formats.
- Integrated image background fitting and preview rendering capabilities.
- Enhanced user interface elements for layout management and visualization.
2026-10-26 03:22:36 -04:00
FranckyB 45125d570d feat: implement Node 2.0 Compatibility 2026-10-24 21:11:26 -04:00
FranckyB 3759813b39 feat: add customizable thumbnail generation steps and improve sampler defaults handling 2026-10-19 23:50:38 -04:00
FranckyB edf48eb0bf feat: enhance NSFW handling in prompt browser and save functionality 2026-10-18 18:18:35 -04:00
FranckyB c1b454eaa3 feat: Implement system prompt selector in prompt_generator.js
- Added a new system prompt selector widget to the prompt generator.
- Integrated fetching and displaying of system prompts from the API.
- Implemented navigation through prompts with arrow buttons and a thumbnail browser.
- Enhanced user experience with improved styling and event handling.

refactor: Enhance error handling and logging in prompt_generator.py

- Introduced custom error classes for better error management.
- Added logging capabilities to capture startup errors and provide actionable feedback.
- Improved model selection logic to handle missing models and provide fallbacks.

test: Add comprehensive tests for prompt generator functionality

- Created tests for the new system prompt selector in prompt_generator_selector.test.mjs.
- Implemented unit tests for model selection and error handling in test_prompt_generator_models.py.
- Ensured coverage for various scenarios including fallback mechanisms and user interactions.
2026-10-18 10:33:06 -04:00
FranckyB e735e7317a feat: update prompt editor button behavior for renaming and saving prompts 2026-10-16 22:39:02 -04:00
FranckyB 7a30c6ad89 feat: improve prompt sorting and enhance prompt entry validation in editor 2026-10-14 00:06:54 -04:00
FranckyB 9446358c56 feat: enhance prompt editor with draft metadata handling and update save button behavior 2026-10-09 02:08:46 -04:00
FranckyB 8e99c8e3c3 feat: enhance prompt management with draft metadata handling and save summary updates in the editor 2026-10-07 23:09:55 -04:00
FranckyB 603fbaaeee feat: enhance prompt management with preferred model settings and draft handling in the editor 2026-10-07 22:18:24 -04:00
FranckyB 76f19a75bc feat: add refmod core loading and expand refmod rows functionality in prompt composer 2026-10-01 00:53:20 -04:00
FranckyB f9a9731924 feat: add functionality to clear muted nodes in prompt composer and enhance context menu options 2026-09-29 22:43:11 -04:00
FranckyB 726571abfd feat: improve subject handling in prompt composer with reset functionality and tooltip updates i.e. UI Polish 2026-09-29 10:13:31 -04:00
FranckyB 51dbfcfac0 feat: enhance subject handling in prompt composer and improve text section key generation 2026-09-29 00:33:37 -04:00
FranckyB cc039ee32e feat: enhance LoRA fetching with cache control and update subject handling in composer 2026-09-28 23:40:21 -04:00
FranckyB 72eeb7e303 Similar to Prompt Composer, added the option to export only specific categories from Prompt Manager 2026-09-28 14:25:08 -04:00
FranckyB 369186bda0 UI Polish:
feat: enhance dialog functionality with optional overlay support
2026-09-28 08:17:01 -04:00
FranckyB 77d7ac30e0 feat: add tooltip functionality for prompt text in composer UI 2026-09-27 19:43:13 -04:00
FranckyB 435e7b1d4c Add advanced prompt composer workflow JSON file with image saving and management features 2026-09-27 18:36:21 -04:00
FranckyB dd07bb5aea feat: enhance prompt composer and manager with improved LoRA handling and source tracking 2026-09-27 17:06:28 -04:00
FranckyB d181b50097 fix: adjust prompt merging logic to prioritize existing prompts over incoming ones 2026-09-27 15:00:25 -04:00
FranckyB 14f2f2ffac fix: adjust dimensions and styles in Prompt Composer for improved UI consistency 2026-09-27 14:27:28 -04:00
FranckyB 78a8b16c1a feat: add input prompt and LoRA modes to Prompt Composer and advanced manager. Allowing Compose Data going thru PMA to add loras and be saved for re-use 2026-09-27 13:59:39 -04:00
FranckyB 9815e38c54 feat: enhance workflow manager with new category filtering options and UI improvements (UI Polish) 2026-09-27 11:32:22 -04:00
FranckyB d44ada12bf feat: added a small file management tool to move files without workflows
update: fixed that tab switching would loose composer manager's data
2026-09-27 10:27:18 -04:00
Francois Beaudry d7e6b32480 Merge pull request #48 from Martlet-Tech/fix/lora-stack-wrapper-height
Fix LoRA stack cards collapsing or stretching to viewport height
2026-09-27 09:58:33 -04:00
FranckyB 0c08e843e1 fix: Rename thumbnail_image to image for consistency in PromptComposerManager 2026-09-27 09:42:02 -04:00
FranckyB a47676eea8 Added new Prompt Composer Manager to save Composer Setups 2026-09-27 09:32:50 -04:00
Martlet-Tech 096335993d Fix LoRA stack cards collapsing or stretching to viewport height
The LoRA stack display widgets force-collapse their positioned wrapper
while hidden (Stack C/D) and previously stripped the manager-written
inline height on every draw while visible (Stack A/B).

The wrapper is position:fixed with height:100% (size-full), so a missing
inline height resolves against the viewport and the card stretches to
full screen height. The DOM widget manager only re-applies its style
when widgetState.pos/size change (i.e. while the view is being panned),
so while the canvas is idle the removed height left the card collapsed
or stretched to the viewport.

Pin the wrapper height to the manager's own slot height
(computedHeight - 2*margin) on every draw of visible stacks, and only
undo the forced collapse when a stack transitions from hidden to
visible (tracked per widget instead of unconditionally).
2026-09-27 16:01:57 +08:00
FranckyB 45d9979eec feat: Add PromptComposerManager for enhanced recipe_data management and thumbnail support 2026-09-27 02:56:14 -04:00
FranckyB df030d5db2 feat: Implement effective parts resolution and prompt library signature generation in Prompt Composer 2026-09-27 02:39:23 -04:00
FranckyB bc0f700c81 feat: Enhance Prompt Manager with Composer Manager integration
- Updated `prompt_manager_advanced.js` to support ComposerManager alongside existing managers.
- Modified node definitions to include ComposerManager and its specific functionalities.
- Enhanced workflow management to handle thumbnail images for ComposerManager.
- Introduced new `composer_manager.py` to manage recipe_data for Prompt Composer with thumbnail support.
- Updated `prompt_composer.py` to handle recipe_data payloads and synchronization modes.
- Improved `prompt_manager_adv.py` to accommodate recipe_data inputs and ensure compatibility with ComposerManager.
2026-09-27 02:33:36 -04:00
FranckyB 738ea302d9 Add subject kind normalization and handling in prompt composer store
- Introduced `_default_subject_kind` and `_legacy_subject_kind_for_name` functions to determine the kind of subject based on type.
- Added `_normalize_subject_kind` function to normalize subject kind values.
- Updated `_normalize_type_data` and `_serialize_type_data` to include subject kind in the type data structure.
- Enhanced `_flatten_canonical_library` to handle subject kind when flattening library data.
- Modified `_ensure_type` to set subject kind based on provided subject type and name.
- Updated type validation in `_looks_like_single_type_payload` to include subject kind.
- Adjusted `compose_save_type_settings` to properly handle subject kind during type settings saving.
2026-09-27 00:45:04 -04:00
FranckyB 56c19498c9 Refactor code structure for improved readability and maintainability 2026-09-26 23:40:13 -04:00
FranckyB 4b3c40a150 feat: improve dialog layout handling and responsiveness in thumbnail browser 2026-09-26 23:28:34 -04:00
FranckyB d3460b5f10 feat: enhance subject handling in image rendering and improve label management 2026-09-26 23:03:33 -04:00
FranckyB 87f6bc523c refactor: remove unused prompt type constants and simplify subject type handling 2026-09-26 22:35:45 -04:00
FranckyB a27f9c41ef feat: enhance category resolution and selection handling in prompt composer 2026-09-26 21:51:50 -04:00
FranckyB f0102c96bf feat: add dialog for creating new prompt groups with category selection 2026-09-26 20:08:22 -04:00
FranckyB e70b66dbb0 Refactor Prompt Composer Store for v2 migration and enhance thumbnail quality
- Updated the PromptComposerStore to convert legacy v1 composer libraries to canonical v2 on first load.
- Removed legacy type order presets and adjusted prompt loading methods to utilize canonical v2 data.
- Introduced new methods for saving type files and resolving requested type files.
- Enhanced the normalization process for category and prompt data during migration.
- Improved error handling and logging for loading type files.
- Updated the image_to_base64_thumbnail function to increase JPEG quality from 75 to 85.
2026-09-26 19:50:14 -04:00
FranckyB 64ebd5e192 Refactor code structure for improved readability and maintainability 2026-09-26 17:14:41 -04:00
FranckyB fd9eb00b20 feat: implement ordered category retrieval for composer and enhance drag scrolling 2026-09-26 13:41:14 -04:00
FranckyB 401c003471 Refactor code structure for improved readability and maintainability 2026-09-26 13:27:02 -04:00
FranckyB 2464d45e24 Move over to a V2 data type, that will be much more flexible 2026-09-26 10:41:05 -04:00
FranckyB ce3be7999f Cleanup Thumbnail Generation code
Reduce quality and generation size slightly.
To reduce the json size and speed up generation
2026-09-26 01:11:13 -04:00
FranckyB 4f772ebbba feat: add home button functionality to prompt and composer browsers 2026-09-25 22:11:38 -04:00
FranckyB 31689ecd6f feat: implement double-click selection for prompts in thumbnail browser 2026-09-25 09:51:58 -04:00
FranckyB a3c96f6d84 feat: update subject role terminology and improve image subject prefix handling 2026-09-25 09:45:40 -04:00
FranckyB 98139769c2 feat: add bulk snippet generation prompt and enhance prompt saving logic
- Introduced a new prompt for generating bulk snippets focused on a single subject category, with specific guidelines for format and content.
- Enhanced the prompt saving functionality to handle cases where prompts may be renamed or moved between categories, ensuring no conflicts arise with existing prompts.
- Implemented case-insensitive checks for existing prompts to prevent duplication and maintain consistency across categories.
2026-09-25 09:16:50 -04:00
FranckyB 2b983e2bea feat: Enhance prompt management with export and import functionalities
- Added `_safe_abspath` function to safely resolve file paths.
- Introduced `_count_prompt_totals` to count categories and prompts in the data.
- Implemented `_normalize_export_path` to ensure export paths are valid and have a .json extension.
- Created new endpoint `/prompt-manager/compose/replace-prompts` for replacing prompts with imported data.
- Added `/prompt-manager/compose/export-prompts-file` endpoint to export prompts to a specified file.
- Implemented `/prompt-manager/compose/load-prompts-file` endpoint to load prompts from a JSON file.
- Enhanced error handling and response messages for better user feedback.
2026-09-24 22:46:16 -04:00
FranckyB f68f8f1201 feat: add anima family support with default sampler settings and rendering functionality 2026-09-24 02:55:19 -04:00
FranckyB 7ef3b1d2bf Add prompt composer workflow for generating images with customizable parameters 2026-09-24 00:41:37 -04:00
FranckyB 31391c579f feat: enhance prompt part selection with default category handling and improved structure 2026-09-23 23:08:01 -04:00
FranckyB d5d5bcf7a0 feat: optimize composer UI height calculation for improved responsiveness 2026-09-23 22:17:26 -04:00
FranckyB 7ba9c464fb feat: enhance prompt renaming functionality with case-insensitive checks and improved error handling 2026-09-23 21:51:09 -04:00
FranckyB a01c6c3e0f feat: add prompt store adapters with utility functions and constants
- Introduced new file `prompt_store_adapters.js` to manage prompt-related endpoints and sources.
- Added constants for various prompt endpoints and sources.
- Implemented utility functions to handle prompt entry visibility, category retrieval, and request body construction for saving prompts based on source and endpoint.
2026-09-23 02:44:31 -04:00
FranckyB 284ae4e0b1 feat: enhance text and JSON section handling in Prompt Composer 2026-09-21 23:52:50 -04:00
FranckyB d819748089 feat: update icon assets for improved visual consistency 2026-09-21 22:23:45 -04:00
FranckyB 16ea1d1551 Refactor code structure for improved readability and maintainability 2026-09-21 22:09:55 -04:00
FranckyB a2ea2df2c5 feat: enhance prompt browser and composer functionality
- Added new prompt types: "Characteristic" and "Expression" to the prompt type choices.
- Introduced dynamic width adjustment for the prompt browser edit panel based on user input.
- Enhanced the clearPrompt function to optionally skip confirmation for discarding changes.
- Implemented functions to manage selected part indices in the prompt composer, allowing for better selection handling.
- Added merging and splitting functionality for prompt parts in the composer, improving user experience.
- Updated the prompt selection process to build parts from browser selections more efficiently.
- Modified the forwardWheelToCanvas function to capture events, ensuring better interaction with the canvas.
- Extended the prompt composer store to save additional metadata for prompts, including a new prompt type field.
2026-09-21 11:35:44 -04:00
FranckyB 95a847a9fd feat: Add mute functionality for prompt parts in Prompt Composer 2026-09-21 08:51:15 -04:00
FranckyB 25732b9086 feat: Enhance subject handling in Prompt Composer with new subject types and improved logic for non-subject prompts 2026-09-21 02:27:15 -04:00
FranckyB cfc078a960 feat: Implement subject number handling and enhance subject assignment logic in Prompt Composer 2026-09-21 01:13:05 -04:00
FranckyB ca447b6b62 feat: Add generation mode toggle for Prompt Composer and enhance Lora handling
- Introduced a new generation mode toggle in the Prompt Composer UI to switch between Image and Video LoRAs.
- Updated the prompt composition logic to handle separate Lora settings for image and video modes.
- Enhanced the Lora resolution functions to support relative path matching and improved error handling.
- Modified the prompt saving logic to accommodate new Lora fields for image and video strengths.
- Added functions to merge and manage Lora stacks more effectively.
- Implemented fetching of thumbnail results from history for improved user experience.
2026-09-21 00:47:41 -04:00
FranckyB 98d733faca feat(prompt_composer): add output format and compose position options
- Introduced output format selection (text or JSON) and compose position (before or after) in the prompt composer UI.
- Updated the prompt composer logic to handle new properties and ensure proper serialization of prompts.
- Enhanced the UI with toggle switches for output format and compose position.
- Modified the backend to support new properties in the prompt composition process.
- Improved handling of LoRA and RefMod assets in the prompt composition.
2026-09-20 23:44:00 -04:00
FranckyB 17122db4e3 feat: Add GPU support detection for llama-server and adjust command arguments accordingly 2026-09-17 20:54:07 -04:00
FranckyB 93ad34ecae fix: Improve trigger word processing to retain prompt-saved words while pruning connected-origin words 2026-09-15 08:17:46 -04:00
FranckyB af07ab7f69 fix: Enhance trigger word processing to ensure only connected words are retained and properly marked 2026-09-15 00:59:48 -04:00
FranckyB 0cf69cad19 feat: Add preference to hide downloadable built-in models in Prompt Manager 2026-09-13 23:33:25 -04:00
FranckyB 539926f486 refactor: Remove deprecated image action prompt handling and centralize system prompt management 2026-08-23 22:08:55 -04:00
FranckyB e6ab89c4ec Updated default_system_prompts and Updated examples to clarify speaker identification in MiniMax Prompts. 2026-08-23 19:28:35 -04:00
FranckyB f17cad3a5c Fixed Typos 2026-08-23 17:46:52 -04:00
FranckyB 9db6605473 fix: Revise description in README for clarity and conciseness 2026-08-23 17:42:52 -04:00
Francois Beaudry 9bd5afa256 Revise feature descriptions in README.md
Updated the README to enhance clarity on features and functionalities.
2026-08-23 17:35:01 -04:00
FranckyB b3ccc25cd7 Bump version to 2.7.2 and add system prompt storage format converter
- Updated version number in pyproject.toml to 2.7.2.
- Introduced a new module `system_prompt_converter.py` for converting legacy system prompt formats to a new category-based structure.
- The converter supports in-place JSON file conversion with optional backup creation.
- Ensured that all system prompt categories are present in the converted data.
2026-08-23 17:05:32 -04:00
Francois Beaudry 842dddbfbf Enhance README with additional resource links
Added links to installation guide, node reference, and latest update in README.
2026-08-23 11:03:52 -04:00
FranckyB 68f47d788d feat: Update README and feature reference for improved clarity and navigation; enhance prompt browser functionality and UI styling 2026-08-23 11:00:22 -04:00
FranckyB b449821dfc - Removed legacy migration logic from prompt_manager.js and moved it to a new prompt_generator.js file for better organization.
- Updated the PromptGenerator class to handle prompt input updates and communicate with the frontend.
- Enhanced the UI behavior of the PromptGenOptions and PromptGenerator nodes to ensure proper widget visibility and state management.
2026-08-23 00:36:09 -04:00
FranckyB 36a2c484f7 feat: Update LoRA blacklist to include new keywords for minimax and distilled LoRAs 2026-08-20 22:52:40 -04:00
FranckyB 8a73f906b6 chore: Bump version to 2.7.1 and update README with latest features 2026-08-18 12:54:53 -04:00
FranckyB e5421431c0 feat: Update prompt handling to echo input prompt in UI on execution 2026-08-17 02:04:43 -04:00
FranckyB 645f58da8e feat: Enhance prompt input handling and model management in Prompt Generator 2026-08-17 01:25:16 -04:00
FranckyB 80389a6621 Add comprehensive video prompt writing guides for MiniMax generation
- Introduced VIDEO_PROMPT_WRITING_GUIDE_REF2VA.md for full-reference video prompt structure, detailing core behaviors, output sections, and example formats.
- Created VIDEO_PROMPT_WRITING_GUIDE_T2VA.md for task-oriented video prompt writing, emphasizing user text expansion and output structure without reference labels.
2026-08-16 19:32:54 -04:00
FranckyB bf0a871563 fix: Guard against temporal dead zone for getThumbnailRenderState in thumbnail rendering 2026-08-16 13:04:24 -04:00
FranckyB 8ea8f2866d feat: Add video input support for prompt extraction and update UI behavior 2026-08-15 11:46:15 -04:00
FranckyB 29f4073247 feat: Update prompt text widget behavior to be read-only when using external inputs 2026-08-14 22:51:14 -04:00
FranckyB 11f1f6b798 feat: Update version to 2.7.0 and enhance README with Prompt Browser details 2026-08-12 09:09:07 -04:00
FranckyB 1f09925d4f Add default system prompts for image and video generation models 2026-08-12 08:54:19 -04:00
FranckyB d14422deb4 feat: Enhance prompt management and system prompt categories
- Updated `saveComposerPrompt` function to accept an optional `promptCategory` parameter for better categorization.
- Modified `buildComposerButtonBar` to handle the new payload structure for saving prompts.
- Introduced new constants for system prompt categories and legacy mode mappings in `prompt_generator.py`.
- Implemented functions to read and merge basic system prompts, ensuring essential prompts are always available.
- Added API endpoint to update the category of existing prompts without altering their text.
- Refactored prompt loading logic to accommodate new structure and ensure backward compatibility.
- Created `basic_system_prompts.json` to store default prompts for various media types (Image, Video, Audio).
2026-08-09 00:26:11 -04:00
FranckyB 39426d6a2e Add .gitattributes, normalize line endings to LF 2026-08-08 08:09:05 -04:00
FranckyB a4a5df9e53 feat: Add bulk prompt builder and tools section in prompt editor 2026-08-04 23:45:39 -04:00
FranckyB 2299db05ae fix: Ensure self-contained prompts by removing dangling prompt references in metadata 2026-08-04 23:06:09 -04:00
FranckyB aa8c355461 feat: Enhance prompt editing with unsaved changes confirmation and UI improvements 2026-08-04 22:16:55 -04:00
FranckyB 0133804a7b feat: Implement centralized backup manager for prompt data files with rotating backups 2026-08-04 02:33:49 -04:00
Francois Beaudry a486506317 Merge pull request #44 from sophosympatheia/feat/gpu-device-selection
feat: Add GPU device selection for llama.cpp server (multi-GPU support)
2026-08-04 02:04:04 -04:00
Francois Beaudry 8a84224dea Merge pull request #45 from sophosympatheia/fix/recursive-model-subfolder-discovery
Fix/recursive model subfolder discovery
2026-08-04 02:01:39 -04:00
Francois Beaudry 746cbdb9e1 Merge pull request #43 from sophosympatheia/fix/llama-port-preference
Fix llama-server port always using hardcoded default instead of saved…
2026-08-04 01:59:43 -04:00
sophosympatheia 4459c270c2 Fix mmproj discovery to recurse into subfolders and match same-folder files
get_mmproj_path()'s heuristic search used os.listdir(models_dir), so mmproj
files placed in a model's own subfolder were never found. It also required
>= 4 shared non-quant keywords between model and mmproj filenames, which
fails for generically-named files like 'mmproj-BF16.gguf' that carry no
identifying keywords at all.

Add a same-folder fallback: if the model's directory contains exactly one
mmproj file, use it without requiring any naming convention. Keep the
keyword heuristic as a fallback for mmproj files that live elsewhere, and
make that search recurse into subfolders too.
2026-08-03 21:21:43 -07:00
sophosympatheia fd707a2a05 Fix local model discovery to recurse into subfolders
get_local_models() used a non-recursive glob.glob(models_dir/*.gguf), so
.gguf files placed in subfolders of a configured models directory (e.g.
~/models/Gemma-4-31B-it/gemma-4-31B-it-qat-UD-Q4_K_XL.gguf) were never
listed as available models.

Walk the directory tree with os.walk instead and return each match as a
path relative to its models_dir. This matches the relative-path
convention ComfyUI's own folder_paths.recursive_search uses, so
is_model_local() and get_model_path() (which already join models_dir
with the returned name) work unchanged for subfolder entries.
2026-08-03 21:15:08 -07:00
sophosympatheia 39ea2125d2 Fix GPU pinning for vision models: use CUDA_VISIBLE_DEVICES instead of --device
llama.cpp's mmproj/clip multimodal loader has a known upstream bug
(ggml-org/llama.cpp#15804) where it ignores --main-gpu/--device entirely and
always loads the projector file onto GPU 0, even with 'split-mode none'.
This meant vision mode still OOM'd the wrong GPU regardless of gpu_device.

Restrict GPU visibility via the CUDA_VISIBLE_DEVICES environment variable on
the llama-server subprocess instead. Since this operates at the CUDA driver
level before the process starts, no other GPU is visible to any code path
in llama.cpp -- including the buggy mmproj loader -- so it can't fall back
to the wrong device.
2026-08-03 11:51:49 -07:00
sophosympatheia 8720a8afc8 Fix GPU pinning: use --device instead of --main-gpu
--main-gpu only designates which GPU handles KV cache/intermediate results
while the default split-mode (layer) still spreads model layers across every
visible GPU. This meant setting gpu_device to '1' still loaded weights onto
GPU 0 as well, causing OOM crashes when the diffusion model later needed
that VRAM.

--device restricts offloading to the specified device only, fully pinning
the model to one GPU as intended.
2026-08-03 11:45:24 -07:00
sophosympatheia 4082485800 Fix llama-server port always using hardcoded default instead of saved setting
SERVER_PORT was a class attribute computed once at module import time, before
the frontend has a chance to push the user's saved custom_llama_port setting
to the backend via /prompt-manager/save-preference. As a result the server
always launched on port 8080 regardless of what was configured in settings.

Replace the frozen class attribute with get_server_port(), a static method
that reads the preferences cache fresh on every call.
2026-08-03 10:24:47 -07:00
sophosympatheia 5411a0bf88 feat: Add GPU device selection for llama.cpp server (multi-GPU support)
Add optional gpu_device input to Prompt Generator Options node, allowing users
to specify which GPU loads the LLM weights via llama.cpp's --main-gpu flag.

Use case: with two GPUs, load your diffusion model on cuda:0 and the LLM
on cuda:1 by setting gpu_device to "1".

Changes:
- py/model_manager.py: Add llama_gpu_device preference (global default)
- nodes/prompt_generator_options.py: Add gpu_device optional input string field
- nodes/prompt_generator.py: Pass --main-gpu flag when gpu_device is specified,
  track device in restart condition so server reloads when GPU selection changes
2026-08-03 10:24:47 -07:00
FranckyB 50467d1cc1 feat: Ensure synchronous DOM widget creation for prompt composer during setup and workflow restore 2026-08-03 04:27:41 -04:00
FranckyB d9d49bc368 Seperated System Prompts as standalone prompt_generator.json, since we now have prompt browser to view and edit it. 2026-08-03 03:12:09 -04:00
FranckyB 69da89d7e3 feat: Adjust alignment and overflow behavior in thumbnail browser for improved layout 2026-08-03 01:34:17 -04:00
FranckyB a2c258b654 feat: Refactor category selector into a static controls bar with horizontal scrolling for improved usability 2026-08-03 01:30:14 -04:00
FranckyB d9ae13e4a9 feat: Add category type filter dropdown and enhance prompt type choices 2026-08-03 00:37:22 -04:00
FranckyB 15bca6eaee feat: Implement horizontal scroll for category selector and enhance visibility of selected category 2026-08-03 00:26:55 -04:00
FranckyB c1c6472b94 feat: Update thumbnail browser layout and improve edit panel responsiveness 2026-08-03 00:13:19 -04:00
FranckyB c39c3fd568 feat: Initialize thumbnail area with placeholder and update empty state display in composer preview 2026-08-02 23:17:24 -04:00
FranckyB c07c785192 feat: Adjust minimum grid width calculation and update padding in prompt browser edit panel 2026-08-02 23:05:54 -04:00
FranckyB c6ed164196 feat: Enhance thumbnail browser view mode toggling and auto-save prompt type settings 2026-08-02 22:47:56 -04:00
FranckyB ae98dc306f feat: Move delete category option to the end of the menu for better usability 2026-08-02 22:21:35 -04:00
FranckyB 84a8c5f688 feat: Simplify edit panel behavior in multi-select mode for thumbnail browser 2026-08-02 22:05:55 -04:00
FranckyB bcfe782bfb feat: Implement multi-select functionality in thumbnail browser with initial state option 2026-08-02 21:49:58 -04:00
FranckyB 17f1245eaa feat: Adjust edit panel width and layout for compact mode in prompt browser 2026-08-02 20:57:33 -04:00
FranckyB f7a87346a1 feat: Enhance compact browser mode detection based on viewport size 2026-08-02 20:42:08 -04:00
FranckyB 0f4402f9e0 feat: Adjust thumbnail browser layout and footer hints for improved usability 2026-08-02 20:32:58 -04:00
FranckyB 1b3001cbad feat: Update default value for thumbnail hover preview to false 2026-08-02 20:05:09 -04:00
FranckyB deb4bbb983 feat: Add placeholder thumbnail functionality in composer preview 2026-08-02 15:20:06 -04:00
FranckyB cfd06a0ce1 feat: Enhance restorePromptBrowserSource to conditionally persist source values 2026-08-02 15:15:13 -04:00
FranckyB 39dceb9596 feat: Refactor composer root layout to use flexbox for improved responsiveness and height management 2026-08-02 15:11:24 -04:00
FranckyB 6c27225d92 feat: Add drag-and-drop resizing functionality to composer preview 2026-08-02 14:07:41 -04:00
FranckyB 8e58f3fe06 feat: Implement prompt source management with normalization and persistence 2026-08-02 13:55:11 -04:00
FranckyB 23c5721318 feat: Enhance prompt selection handling and clear functionality in prompt browser 2026-08-02 13:40:36 -04:00
FranckyB 34a6c1a8f3 Add Prompt Mixer Selector and Store for managing prompt fragments
- Implemented PromptMixerSelector to select and format prompt fragments with adjustable strength.
- Created PromptMixerStore for isolated JSON storage of prompt fragments, including loading, saving, and managing categories and prompts.
- Added API endpoints for retrieving, saving, renaming, and deleting prompts and categories.
- Introduced functionality for handling NSFW flags and thumbnail management for prompts.
2026-08-02 13:03:39 -04:00
FranckyB 46e499efb8 fix: Simplify multi-select logic and enhance category settings confirmation in prompt browser 2026-08-02 03:59:23 -04:00
FranckyB add4d1f22c feat: Enhance thumbnail browser interaction and improve UI padding 2026-08-02 03:46:12 -04:00
FranckyB 52b72c9277 Refactor prompt management system
- Removed the ExpressionSelector class and its associated methods from expression_selector.py, consolidating expression handling into a new test file.
- Updated prompt_composer.py to introduce new prompt type handling, including a new function to resolve prompt types.
- Modified prompt_composer_manager.py to accommodate changes in hidden category entry keys.
- Adjusted prompt_composer_store.py to replace legacy prompt prefix handling with prompt type management.
- Added a new JavaScript file (prompt_browser_edit.js) for editing prompt categories, including UI elements for prompt type and base prompt settings.
- Introduced a new test file (expression_selector.py) to ensure the functionality of the expression selection process.
2026-08-02 01:44:13 -04:00
FranckyB 4e8e47f8f4 Refactor Prompt Mixer to Prompt Composer
- Renamed `PromptMixerStore` to `PromptComposerStore` in `prompt_composer_store.py` for consistency.
- Updated method names and comments to reflect the new naming convention.
- Added new JavaScript files: `prompt_composer_common.js` and `prompt_composer_manager.js` to handle prompt composer functionality.
- Implemented functions for loading, saving, deleting, and managing prompts in the composer.
- Enhanced UI components for prompt selection and management, including buttons for saving, creating, and deleting prompts.
- Integrated thumbnail preview functionality for prompts.
- Added JSON import/export capabilities for prompt data.
2026-08-01 21:56:34 -04:00
FranckyB 2af07072fd Updated base composer prompt 2026-08-01 16:19:37 -04:00
FranckyB 229d7291ee feat: Implement Prompt Composer for building prompts from multiple parts
- Added a new PromptComposer node to compose prompt fragments from multiple selectable parts.
- Each part can store category, selected prompt names (multi-select), and strength.
- Introduced functions to normalize strength, format fragments, and resolve prompt prefixes.
- Enhanced prompt mixing functionality by allowing dynamic prompt selection based on user-defined parts.
- Added API endpoints for saving base prompts and prompt prefixes for categories.
- Updated UI components to support the new prompt composer features, including thumbnail zoom and context menus.
- Refactored existing code to improve handling of hidden category entries and prompt selection logic.
2026-08-01 16:00:04 -04:00
FranckyB 99c05514da Refactor Prompt Mixer to Prompt Composer
- Updated `prompt_mixer_manager.js` to handle both PromptMixerManager and PromptComposerManager.
- Changed export filename from `prompt_mixer_data.json` to `prompt_composer_data.json`.
- Modified `prompt_mixer_selector.js` to include a preview box in the mixer preview.
- Removed `prompt_mixer_manager.py` as it is no longer needed.
- Renamed `prompt_mixer_store.py` to `prompt_composer_store.py` and updated its functionality to support the new Prompt Composer structure.
- Added new `default_composer_prompts.json` for default prompts.
- Created `prompt_composer_manager.py` to manage Prompt Composer fragments.
- Updated server routes to handle Prompt Composer requests.
2026-08-01 12:51:49 -04:00
FranckyB e9a28545b1 fix: Adjust thumbnail browser layout and column widths for improved display 2026-08-01 11:58:15 -04:00
FranckyB e4c39ce0f6 Refactor code structure for improved readability and maintainability 2026-08-01 11:37:05 -04:00
FranckyB 16405ceb17 Add Prompt Mixer functionality with isolated storage and selection capabilities
- Implemented PromptMixerManager for saving, loading, and editing prompt fragments.
- Created PromptMixerSelector for selecting prompt fragments with support for strength and random selection.
- Developed PromptMixerStore for managing isolated JSON storage of prompt fragments, including backup and restore functionality.
- Added API endpoints for managing prompt categories and fragments, including save, delete, rename, and toggle NSFW status.
2026-08-01 02:16:12 -04:00
FranckyB b59f1c1bbe fix: Improve VRAM flush logging and handling for CLIP/text encoder 2026-07-31 01:15:38 -04:00
FranckyB ac358436fe feat: - Added support for direct Clip (text encoders in Prompt Generator)
- Update README and documentation for improved clarity on prompt generation options and workflows; bump version to 2.6.0
2026-07-31 00:53:50 -04:00
FranckyB b560c4a17a Fixed bad prompt 2026-07-28 02:26:41 -04:00
FranckyB bc76189941 Added KREA2 workflow JSON
Added Strength Slider to Expression Selector
2026-07-28 00:00:48 -04:00
FranckyB 52e9626059 feat: Add stack count configuration to MultiLoraStackerLM for flexible LoRA stack management 2026-07-26 20:48:14 -04:00
FranckyB 0f50056ab1 fix: Ensure proper handling of hidden LoRA stacks to prevent UI interaction issues 2026-07-26 20:17:44 -04:00
FranckyB 17f577ec8d feat: Enhance expression node handling with graph validation and improved hover detection 2026-07-26 19:27:45 -04:00
FranckyB 819b82af35 feat: Implement arrow navigation for expression selection and improve hover handling 2026-07-26 18:55:46 -04:00
FranckyB deb22acfaa fix: Update default value for static seed in expression thumbnail generation 2026-07-26 15:04:43 -04:00
FranckyB c4faf12236 fix: Remove unused parameters from showThumbnailBrowser function 2026-07-26 13:25:05 -04:00
FranckyB 3cd52a032b fix: Update MIN_NODE_WIDTH to improve layout consistency 2026-07-26 03:38:30 -04:00
FranckyB 0b72ad0c65 chore: Bump version to 2.5.5 in __init__.py and pyproject.toml 2026-07-26 00:02:35 -04:00
FranckyB b60d9b006e Improved Expresion names 2026-07-25 23:50:32 -04:00
FranckyB fef2545c8e Implement code changes to enhance functionality and improve performance 2026-07-25 19:04:10 -04:00
FranckyB 4416ffee23 Fixed Expression name 2026-07-25 17:48:07 -04:00
FranckyB dac1a9a705 feat: Add drag-and-drop functionality for setting prompt thumbnails 2026-07-25 17:36:27 -04:00
FranckyB e1a3e70442 Tweak to expression and node size as well as added thumbnails to default prompts 2026-07-25 17:12:30 -04:00
FranckyB 6a6ed5afd5 feat: Add functionality to merge default expressions into user prompts
- Implemented `hasExpressionCategory` to check for existing Expressions category in prompts.
- Created `ensureExpressionsCategory` to fetch and merge default expressions if the category is missing.
- Updated `loadPrompts` calls to ensure default expressions are merged before retrieving expression names.
- Added a new endpoint `/prompt-manager/merge-default-expressions` to handle merging of default expressions from `expressions.json`.
- Enhanced error handling and logging for merging process.
2026-07-25 15:24:20 -04:00
FranckyB db528293aa Implement code changes to enhance functionality and improve performance 2026-07-25 14:55:23 -04:00
FranckyB 799feac2e9 feat: update compact prompt browser layout for improved usability 2026-07-25 11:32:51 -04:00
FranckyB 0567a5e1fe feat: add compact prompt browser option for enhanced UI flexibility 2026-07-25 11:14:32 -04:00
FranckyB e00f57a5d0 feat: add Expression Selector extension for managing expressions in prompts
- Implemented a new JavaScript module for the Expression Selector UI, allowing users to select and preview expressions stored in the Prompt Manager.
- Created a corresponding Python node to handle expression selection and substitution in prompts, including gender adaptations for pronouns.
- Integrated the expression selection functionality into the existing prompt management system, ensuring compatibility with current workflows.
- Added UI components for expression selection and preview, enhancing user experience and interaction.
2026-07-25 10:10:58 -04:00
FranckyB 2aea1845e6 feat: Refine active trigger word retrieval logic in PromptManagerAdvanced 2026-07-24 13:22:37 -04:00
FranckyB 6697b32e37 feat: Implement prompt input mask shim for PromptManager and PromptManagerAdvanced 2026-07-21 23:49:29 -04:00
FranckyB dda225708b feat: Improve workflow extraction validation and documentation in extract_video_workflow.py 2026-07-19 04:22:55 -04:00
FranckyB adee96644a feat: Enhance prompt management with trigger word parsing and resolution for llama-server path on linux 2026-07-18 23:52:02 -04:00
FranckyB d64b13a54b feat: Add support for mode-specific JSON system prompts and enhance prompt instructions for audio, image, and video 2026-07-17 08:39:05 -04:00
FranckyB 67f12480ae feat: Enhance Prompt Manager with Multi-Slot LoRA Support
- Added support for multiple LoRA slots (C and D) in PromptManagerAdvanced and PromptManager.
- Implemented functions to normalize and combine multi-LORA inputs.
- Updated metadata handling to persist resolved prompts for both workflow and API.
- Enhanced recipe data building to include additional LoRA configurations.
- Refactored existing methods to accommodate new LoRA structures and ensure backward compatibility.
2026-07-17 08:38:41 -04:00
FranckyB 65504b8263 feat: Rename PromptGeneratorKillRelay to PromptGeneratorKillSwitch and remove unused mappings 2026-07-14 00:27:42 -04:00
FranckyB b7862153e5 feat: Implement system prompt override functionality in PromptGenerator instead, for simpler workflows. 2026-07-11 11:36:17 -04:00
FranckyB 922ff007f4 feat: Revise README for clarity and detail on prompt management and recipe tools 2026-07-11 00:21:56 -04:00
FranckyB 5ce3408cfc feat: Enhance media path handling and preview functionality
- Introduced new utility functions in `path_browser.js` for media path classification and URL generation.
- Updated `prompt_extractor.js` to utilize new path handling functions for building preview URLs and resolving media sources.
- Improved image and video preview modals to use the new URL structure.
- Added support for browsing files from custom paths, including enhanced metadata extraction for media files.
- Refactored file listing and directory browsing in `prompt_extractor.py` to support new media types and improved error handling.
- Updated version to 2.5.3 in `pyproject.toml`.
2026-07-07 08:35:16 -04:00
FranckyB b7679d0e5a fix: Update MultiLoraStackerLM and MultiLoraStacker to improve module loading and fast preview functionality 2026-07-04 16:25:48 -04:00
FranckyB ea88616f81 feat: Add LoraStackCombine class to merge multiple LORA_STACK inputs into a single output 2026-07-04 08:56:52 -04:00
FranckyB 7b0e59a502 feat: Add MultiLoraSplitter class to split MULTI_LORA_STACK payload into A/B/C/D outputs 2026-07-03 13:39:49 -04:00
FranckyB 40bfc8e3b7 fix: Adjust margin-top in ensureStyles function for MultiLoraStackerLM to improve layout 2026-07-03 11:14:24 -04:00
FranckyB 782aa7c63b feat: Add PromptGeneratorKillRelay node to manage server shutdown and model unloading, fixed issue with multi lora stack and added that it can be used as a standard Lora Stacker, with sections... 2026-07-03 09:30:50 -04:00
FranckyB 7295cf2e50 feat: Add system prompts for cinematic enhancement and realism, with options for prompt overrides in Prompt Generator Option node. Improved Memory Management for Generator. 2026-06-07 10:38:18 -04:00
FranckyB bb68fd890f feat: Add clear_vram_on_run option to PromptGenerator for improved VRAM management 2026-06-01 04:19:30 -04:00
FranckyB 070b9c2dfe refactor: Remove recipe_data output from PromptExtractor and enhance legacy metadata parsing functions 2026-05-31 02:08:05 -04:00
FranckyB 3cd6c3cf9b fix: Remove Recipe Output from Prompt Extractor, now prompt only 2026-05-28 00:30:46 -04:00
FranckyB d77b89c388 feat: Enhance thumbnail rendering with improved loading UI and LoRA fetching logic 2026-05-24 20:37:46 -04:00
FranckyB e9bfdceee2 feat: Add support for LoRA selection in thumbnail rendering and enhance recipe data normalization 2026-05-24 19:41:15 -04:00
FranckyB b6156bc59a refactor: Update model selection priority logic in PromptGenerator for improved clarity and functionality 2026-05-20 00:56:28 -04:00
FranckyB c765112c38 feat: Implement legacy prompt generation options migration and enhance context size retrieval for GPU compatibility 2026-05-18 20:24:46 -04:00
THE_BEAST\me 9f185c5806 Merge branch 'main' of https://github.com/FranckyB/ComfyUI-Prompt-Manager 2026-05-17 04:41:00 -04:00
THE_BEAST\me c8fb3dada0 feat: Enhance prompt generation options with system prompt mode and update audio prompt description 2026-05-17 04:39:13 -04:00
THE_BEAST\me 98c7d94290 refactor: Consolidate model preference handling by renaming and unifying preferred model settings 2026-05-17 03:48:22 -04:00
Francois Beaudry 7bb27c5c40 Merge pull request #39 from FranckyB/dev
Add video workflow extraction script and update version to 2.5.2
2026-05-14 21:21:58 -04:00
THE_BEAST\me 22facf075b feat: Bump version to 2.5.2 and update changelog with new features 2026-05-14 21:18:35 -04:00
THE_BEAST\me ac7bb560a5 feat: Add video workflow extraction script and batch file for JSON output 2026-05-14 10:02:22 -04:00
122 changed files with 41956 additions and 11462 deletions
+50
View File
@@ -0,0 +1,50 @@
# Normalize all text files to LF in the repository.
# Working-tree endings are controlled by each machine's core.autocrlf setting;
# the repo always stores LF so Windows/Linux checkouts stop showing phantom diffs.
* text=auto
# Source files: always LF (in repo and on disk)
*.py text eol=lf
*.js text eol=lf
*.json text eol=lf
*.md text eol=lf
*.toml text eol=lf
*.txt text eol=lf
*.yml text eol=lf
*.yaml text eol=lf
*.cfg text eol=lf
*.ini text eol=lf
*.css text eol=lf
*.html text eol=lf
*.sh text eol=lf
# Windows-only scripts keep CRLF
*.bat text eol=crlf
*.cmd text eol=crlf
*.ps1 text eol=crlf
# Binary files: never convert
*.png binary
*.jpg binary
*.jpeg binary
*.gif binary
*.webp binary
*.ico binary
*.mp4 binary
*.webm binary
*.mkv binary
*.mov binary
*.avi binary
*.mp3 binary
*.wav binary
*.flac binary
*.safetensors binary
*.ckpt binary
*.pt binary
*.pth binary
*.bin binary
*.onnx binary
*.af binary
*.pyc binary
*.pdf binary
*.zip binary
+1
View File
@@ -20,6 +20,7 @@ wheels/
*.egg-info/
.installed.cfg
*.egg
test/
# VS Code history extension
.history/
+128 -96
View File
@@ -1,28 +1,33 @@
# ComfyUI Prompt Manager
## A comprehensive prompt and recipe toolkit for [ComfyUI](https://github.com/comfyanonymous/ComfyUI)
ComfyUI Prompt Manager is an all-in-one prompt and recipe toolkit for ComfyUI, built for creating recipes from scratch or by extracting core workflow elements from Images and Videos with embedded workflows. It includes local LLM-powered prompt generation (llama.cpp or Ollama) with automatic download of Qwen3.5 models, LoRA stack tooling, and end-to-end Recipe nodes to build, edit, render, save, and reuse repeatable generation pipelines. It can extract core metadata from media generated in ComfyUI, A1111, and Forge, supporting Wan Workflows with dual model/stack support.
ComfyUI Prompt Manager is a prompt toolkit for ComfyUI. It helps you manage, save, and reuse prompts along with their LoRAs and trigger words. It can generate prompts using a local LLM through llama.cpp or Ollama, or generate them directly with ComfyUI’s own CLIP/text encoders. It also extracts metadata from images, videos, and JSON files, so you can turn them into reusable prompts — and the **Prompts** sidebar and save/load tools keep everything organized.
> **Naming Update (v2.1):**
> We have shifted from using the term "Workflow" to "Recipe" for this toolset.
> This is an unfortunate but needed naming change to better represent the purpose of this tool.
[See Installation Guide](#installation)
> **New in v2.5.0:**
> Recipe Builder can now setup Multi Model all in one Node. Gone is the need to stack multiple Builder nodes when setting multi model workflows.
> You can build and route `model_a` through `model_d` in one node, keep per-slot prompts/LoRAs/sampler data, and extract Builder-authored recipes from media with v2 metadata preserved as the authoritative source.
> Added a New Multi Lora Stack node, that is based on Lora-Manager and works with it. Simply select the column you want to add to and then added loras with be added to it.
> This new Multi Model may break combatibility wirh previous workflows, but this is now MUCH closer to the initial visioin! One node to build the entire Recipe.
[See Node Reference](docs/feature-reference.md)
[See Prompt Composer](#prompt-composer)
## What This Provides
- **Prompt tools**: Prompt Manager, Prompt Extractor
- **Local LLM support**: Prompt Generator using llama.cpp or Ollama. Supports text enhancement and image analysis with vision models (Qwen3.5)
- **Recipe tools**: Recipe Extractor, Recipe Builder, Recipe Builder (WAN), Recipe Hub, Recipe Relay, Recipe Renderer, Recipe Model Loader, Recipe Manager
- **LoRA workflow support**: Display and modify added Loras. When reusing Saved presets, values can still be changed.
- **Model support**: Recipe Renderer supports: Flux 1/2, Ernie, SDXL, Wan, Qwen, Z-Image, Wan Image, Wan Video (I2V/T2V)
- **Lora Preview**: When [Lora-Manager](https://github.com/willmiao/ComfyUI-Lora-Manager) is installed, LoRAs can be previewed on hover.
- **Prompt Browser**: Includes a Browser to easily find and select your prompts or Recipes.
- **Advance Image Loader**: Extractors can serve as advanced Image loaders, loading from Input or Ouput.
- **Prompt Manager**:
- For saving and loading Prompts.
- These saved prompts can include LoRA stacks, trigger words, as well as thumbnails.
- **Prompt Generator**:
- To run a local LLM (llama.cpp or Ollama), or directly use ComfyUI's CLIP/text encoders.
- Also supports image analysis when using Vision Capable models.
- **Prompt Composer**:
- For building prompts from reusable prompt fragments such as attire, expression, action, style, ambience, and more.
- Supports the v2 Prompt Composer library format with thumbnails, prompt groups, subject-aware group behavior, LoRAs, RefMods, random multi-prompt selection, and video/image composition modes.
- **Prompt Extractor**:
- Read metadata from images/videos/JSON and output the prompt and LoRAs they use.
- **Lora Preview integration**:
- When [Lora-Manager](https://github.com/willmiao/ComfyUI-Lora-Manager) is installed, LoRAs can be previewed on hover.
- **Advanced media loading**:
- Extractor nodes can also act as advanced image loaders, but I'd recommend [FBNodes](https://github.com/FranckyB/ComfyUI-FBnodes) for better solutions.
- **And more**:
- See the [Reference guide](docs/feature-reference.md) for a complete list.
---
<div align="center">
@@ -41,97 +46,115 @@ ComfyUI Prompt Manager is an all-in-one prompt and recipe toolkit for ComfyUI, b
</div>
<div align="center">
<figcaption>Recipe extraction and modifcation (Adding a Style Lora)</figcaption>
<figcaption>Recipe extraction and modification (Adding a Style LoRA)</figcaption>
<img src="docs/images/workflow_builder.png" alt="Recipe Builder">
</div>
<div align="center">
<figcaption>Easily find saved Prompts & Recipe using the Built-in File Browser</figcaption>
<figcaption>Easily find saved Prompts & Recipes using the Built-in File Browser</figcaption>
<img src="docs/images/prompt_selector.png" alt="Recipe Builder">
</div>
<div align="center">
<figcaption>Use Extractor Nodes as an Image Loader, allowing browsing from Input and Output folder.</figcaption>
<img src="docs/images/adv_file_loading.png" alt="Recipe Builder">
</div>
## v2.0 Introduces The Recipe Toolset
Version 2.x introduces a Recipe toolset that can be used on its own, or in combination with the Prompt toolset.
- Use the Recipe toolset when you want repeatable generation pipelines from extracted or hand-edited recipe data.
- Recipe Data includes prompts (pos & neg), LoRA stack, mode used, KSampler settings, resolution, seed, and more.
- This data can be created using Recipe Builder or extracted from existing media with Recipe Extractor.
- Recipe Renderer provides an easy way to render this recipe.
- Recipe data can also be used traditionally with the Recipe Relay node, which can access all of it.
- Use the Prompt toolset when you want fast prompt library management and local LLM-assisted prompt creation.
- Prompt Generator allows creation of new prompts using the LLM model of your choice.
- Prompt Manager can save these to be reusable later.
- Prompt Extractor is similar to Recipe Extractor, but can individually output prompts or LoRAs.
- Use both together when you want to create Recipes, but use different prompts.
In short: Prompt tools help you author and manage Prompts + LoRA intent, while Recipe tools help you build, execute and reuse full generation configurations.
## Toolset Overview
### Prompt Toolset
- Prompt Manager: dual LoRA stacks, trigger words, thumbnail workflows, and advanced save flows.
- Prompt Extractor: reads metadata from images/videos/JSON and outputs prompt + LoRA + recipe context.
- Prompt Generator + Options: local LLM prompt creation and enhancement using llama.cpp or Ollama.
- Prompt Manager (Basic): category-based prompt save/load. A no-frills basic version (The OG).
- Prompt Manager: Supports Prompts, LoRA stacks, trigger words and thumbnail for workflows.
- Prompt Manager (Basic): Simple no-frills basic version (The OG).
- Prompt Generator: prompt creation and enhancement using llama.cpp, Ollama, or a connected ComfyUI CLIP/text encoder.
- Prompt Extractor: Reads metadata from images/videos/JSON and outputs prompt + LoRA + recipe context.
- Prompt Composer: Build prompts from reusable fragments, with random prompt groups, subject-aware composition, LoRA/RefMod support, and image/video generation modes.
- Prompt Layout Builder: Draw boxes over a scene prompt (or load them from an LLM) and output a layout prompt for MOSS-Image, Ideogram 4 or Krea 2.
- Prompt Library Hub (sidebar **Prompts** button, can be hidden in Settings): browse, edit, import and export System Prompts, Prompt Snippets, and Saved Compose / Prompts / Layouts / Recipes from one panel, with per-category export.
### Recipe Toolset
- Recipe Extractor: normalizes extracted metadata into reusable recipe_data.
- Recipe Builder: edit and validate recipe_data in a cleaner authoring surface.
- Recipe Renderer: execute recipe_data through built-in generation templates.
- Recipe Hub: merge/append model blocks into one `recipe_data` and expose each model block as its own output.
### Recipe Toolset (Experimental)
These tools were an experiment, with some of the tech now used in other parts of the add-on.
- Recipe Extractor: normalizes extracted metadata into reusable `manager_data`.
- Recipe Builder: edit and validate recipe data in a cleaner authoring surface.
- Recipe Renderer: execute recipe data through built-in generation templates.
- Recipe Hub: merge/append model blocks into one `manager_data` and expose each model block as its own output.
- Recipe Relay: edit one model block (`model_data`) with seed and LoRA stack overrides.
- Recipe Model Loader: resolve and load models from recipe_data.
- Recipe Manager: save and reuse recipe entries.
## Common Pipelines
### Prompt-first Pipeline
1. Write or generate prompts and connect LoRA stacks into Prompt Manager.
2. Generate with your normal ComfyUI graph.
3. Save reusable prompt entries when satisfied.
### Recipe-first Pipeline
1. Create preset in Recipe Builder
- By extracting recipe_data from media or JSON, using Recipe Extractor
- Or by directly modifying Recipe Builder to the values you want.
2. Render in Recipe Renderer.
3. Save reusable recipe entries with Recipe Manager.
- To include Thumbnail, add after the Renderer node.
### Hybrid Pipeline
1. Extract or build recipe_data.
2. Add Prompt Generator or Save prompts into Builder.
3. Add LoRAs, either using LoRA stackers or saved LoRA stacks in Prompt Manager.
4. Render through Recipe Renderer.
5. Save final reusable entries in Recipe Manager.
## Preferences And Settings
- Addon settings are available in ComfyUI Preferences (Settings) under Prompt Manager.
- This is where you set model/backend defaults, NSFW visibility defaults, view preferences, and related addon behavior.
- Prompt Generator backend choices (llama.cpp or Ollama) and related options are configured there.
- Recipe Model Loader: resolve and load models from recipe data.
- Save and reuse recipes with the **Library Manager** (it replaces the former Recipe Manager).
## Workflow Examples
Workflow examples are provided to help understand the basics.
## Preferences And Settings
- Addon settings are available in ComfyUI Preferences (Settings) under Prompt Manager.
- This is where you set model/backend defaults, NSFW visibility defaults, view preferences, and more.
- If you want the Prompt Generator dropdowns to show only your local models, enable `Hide downloadable built-in models` in these settings.
- Prompt Generator backend choices (llama.cpp, Ollama) and related options are configured there.
- The Prompt Generator's system prompts are fully user-customizable. They're stored in `user/default/prompt_generator_data.json` and can be created and edited with the **Prompt Library Hub** (sidebar) — your custom prompts then show up directly in the Prompt Generator node.
## Documentation
- Detailed node and feature reference: [docs/feature-reference.md](docs/feature-reference.md)
- Full changelog history: [docs/changelog.md](docs/changelog.md)
- Detailed node reference: [docs/feature-reference.md](docs/feature-reference.md)
## Prompt Composer
Prompt Composer is a visual prompt builder for assembling full prompts from reusable fragments such as characters, expressions, attire, action, lighting, ambience, style, environment, and camera.
The Prompt Composer library now uses a more flexible v2 format built around prompt groups. This makes it much easier to add new groups, organize categories inside them, keep subject behavior per group, and manage larger prompt libraries without relying on the older flat composer JSON layout.
- Compose output before or after the selected prompt source, or use it on its own.
- Return output as plain text or JSON.
- Works in both image and video modes. The Video mode being formatted for Minimax.
- Prompt fragments can include LoRAs, RefMods, and thumbnails can be generated easily.
- Categories and prompt groups support prompt types, prefixes, and subject behavior for cleaner browsing and formatting.
- Multi-select can become one random pool or multiple separate prompt parts.
- Parts support subject-aware grouping, muting, reordering, merge/split actions, and per-part strength.
- Prompt Browser integration supports direct editing, easy creation of new prompt groups, thumbnail generation, export, open, merge flows for older composer data, and reopen behavior that preserves browser state.
- Includes an extensive collection of style prompts, including styles based on Reddit user Dear-Spend-2865 prompts.
Node-side Prompt Composer controls include:
- Click a fragment to edit or replace it.
- Middle click to mute or unmute a fragment.
- Ctrl-click to select multiple parts, then right-click to merge compatible selections.
- Right-click a merged part to split it back into separate prompts.
- Drag and drop parts to reorder them.
- Adjust fragment strength directly on the card.
### Saving And Reloading Composer Workflows
The **Library Manager** node (formerly Compose Manager, and replacing Recipe Manager) saves and reloads the `manager_data` of **Prompt Manager**, the **Recipe** nodes, **Prompt Composer** and **Prompt Layout Builder**; they all share the `MANAGER_DATA` type. The Prompt Browser marks their entries **P**, **C** and **L** (recipes show under Type: Recipe). Connect Library Manager's `manager_data` to Prompt Composer's `manager_data` input to restore a saved Composer setup.
To restore a saved Composer setup in **Prompt Composer**, use the **second row of toggles** on the node:
- **Sync** rebuilds the Prompt Composer graph from the incoming `compose_data`
- **Prompt** uses the prompt stored in the incoming `compose_data`
- **LoRA** uses the LoRAs stored in the incoming `compose_data`
This allows `compose_data` to take priority over directly connected prompt and LoRA inputs when those toggles are enabled.
<div align="center">
<figcaption>Use Prompt Composer to build prompts from reusable fragments, including random multi-prompt groups.</figcaption>
<img src="docs/images/prompt_composer.jpg" alt="Prompt Composer Example">
</div>
<div align="center">
<figcaption>Edit prompts in the browser, attach LoRAs or RefMods, and generate thumbnails for any prompt.</figcaption>
<img src="docs/images/prompt_browser_ui.png" alt="Prompt Browser Editor">
</div>
## Prompt Layout Builder
Prompt Layout Builder places the parts of an image in boxes: draw them over a scene prompt, or let the Prompt Generator write the layout for you, then output it in the format your model reads.
- Each box is an Object, Character, Text (with the exact words to render) or Panel, with its own description and colors. Box descriptions can come from Prompt Composer snippets.
- **Output** formats:
- **MOSS**: MOSS-Image layout JSON.
- **Ideogram**: Ideogram 4 JSON caption, with background, style, lighting and medium fields.
- **Krea 2**: Krea 2 grounding lines, with style, medium and background, panels, and character tags and IDs to keep a character consistent across panels. Requires the **krea2-turbo-bbox** model or LoRA, found here: [jimmycarter/krea2-turbo-bbox](https://huggingface.co/jimmycarter/krea2-turbo-bbox). Its PROMPTING.md covers the prompt format and sampler settings.
- **Use import_json** loads a layout from the Prompt Generator (system prompts **MOSS Layout**, **Ideogram Layout** and **Krea 2 Layout** in the **Bbox** category, each with Create and From Image versions), from Create Bounding Boxes, or from a layout saved with Library Manager. Turn it off to keep editing the imported boxes.
- **Bbox Converter** converts layouts to and from ComfyUI's bounding-box types.
See [docs/feature-reference.md](docs/feature-reference.md#prompt-layout-builder) for details.
## Installation
@@ -153,22 +176,31 @@ Workflow examples are provided to help understand the basics.
```bash
winget install llama.cpp
```
This installs the `ggml.llamacpp` package, which ships the official **Vulkan** Windows build (for example `llama-b11946-bin-win-vulkan-x64.zip`), so GPU offload works on NVIDIA / AMD / Intel GPUs with a working Vulkan driver, and falls back to CPU when there is no Vulkan-capable driver.
If you want CUDA instead (needed for the node's GPU device selector, and generally the fastest on NVIDIA), download `Windows x64 (CUDA 12/13)` from the [llama.cpp releases](https://github.com/ggml-org/llama.cpp/releases) page, keep its CUDA DLLs next to `llama-server.exe`, and point **Settings → Prompt Manager → 2. Llama Preferences → Custom Llama Path** at that folder.
- Linux:
```bash
brew install llama.cpp
```
Homebrew builds ggml with **Vulkan** and OpenBLAS on Linux (and Metal on Apple Silicon), so GPU offload works there as well. Otherwise build llama.cpp yourself with `-DGGML_CUDA=ON` (or `-DGGML_VULKAN=ON`) and set **Custom Llama Path** to the build folder.
5. Place custom `.gguf` models in models/gguf.
- Or use preferences to set a custom path.
6. Restart ComfyUI.
## Requirements
**Checking that your llama.cpp can use the GPU** — run this in a terminal, using the same path the Prompt Generator resolves (it is printed as `llama-server:` in the console):
- ComfyUI
- Python 3.8+
- requests
```bash
llama-server --list-devices
```
If it prints `Available devices:` followed by `CUDA0: ...` or `Vulkan0: ...`, GPU offload works. If it prints `(none)`, that build (or its driver) cannot use your GPU — Prompt Generator will then run the model on CPU and say so at startup.
**Using the CLIP/text encoder backend**: No additional setup is needed. Connect any ComfyUI `CLIP` output to the Prompt Generator node's `clip` input. When `clip` is connected, the node bypasses llama.cpp/Ollama and generates prompts directly through the text encoder.
**Data Location**
All data generated by the nodes is saved under user/default folder. The data is saved in JSON format and the thumbnail data is also included, saved as base64 data URL. The node creates a backup folder that keeps 5 daily copies in the hope of preventing any mishap. As the node supports exporting the JSON, be safe and make backups from time to time.
## Requirements
- huggingface_hub
- psutil
- tqdm
- Pillow
- colorama
- llama-server (from llama.cpp)
- llama-server, Ollama or Comfy's text encoders (Much Slower)
+33 -10
View File
@@ -2,64 +2,87 @@
ComfyUI Prompt Manager - A comprehensive prompt and workflow management system for ComfyUI.
Features: prompt & workflow management, LoRA stacks, workflow extraction, workflow generation.
"""
__version__ = "2.5.1"
__version__ = "3.0.0"
__author__ = "François Beaudry"
__license__ = "MIT"
from .nodes.apply_lora import ApplyLoraPlusPlus
from .py.backup_manager import check_backup
from .py.prompt_composer_store import PromptComposerStore
from .nodes.prompt_manager_adv import PromptManagerAdvanced
from .nodes.prompt_manager_basic import PromptManager
from .nodes.prompt_generator import PromptGenerator
from .nodes.prompt_composer import PromptComposer
from .nodes.library_manager import LibraryManager
from .nodes.prompt_generator import PromptGenerator, PromptGeneratorDataStore
from .nodes.prompt_generator_options import PromptGenOptions
from .nodes.prompt_generator_kill_switch import PromptGeneratorKillSwitch
from .nodes.prompt_extractor import PromptExtractor
from .nodes.prompt_layout_builder import PromptLayoutBuilder, BboxConverter
from .nodes.prompt_extractor import WorkflowExtractor as RecipeExtractor
from .nodes.recipe_builder import RecipeBuilder
from .nodes.recipe_renderer import WorkflowRenderer as RecipeRenderer
from .nodes.recipe_relay import WorkflowRelay as RecipeRelay
from .nodes.recipe_model_loader import WorkflowModelLoader as RecipeModelLoader
from .nodes.recipe_model_picker import RecipeModelPicker
from .nodes.recipe_manager import WorkflowManager as RecipeManager
from .nodes.multi_prompt import RecipeBuilderMultiPrompts
from .nodes.multi_lora_stacker import MultiLoraStackerLM, MultiLoraCombine
from .nodes.multi_lora_stacker import MultiLoraStackerLM, MultiLoraCombine, MultiLoraSplitter, LoraStackCombine
NODE_CLASS_MAPPINGS = {
"PromptApplyLora": ApplyLoraPlusPlus,
"PromptManagerAdvanced": PromptManagerAdvanced,
"PromptManager": PromptManager,
"PromptComposer": PromptComposer,
"LibraryManager": LibraryManager,
"PromptGenerator": PromptGenerator,
"PromptGenOptions": PromptGenOptions,
"PromptGeneratorKillSwitch": PromptGeneratorKillSwitch,
"PromptExtractor": PromptExtractor,
"PromptLayoutBuilder": PromptLayoutBuilder,
"BboxConverter": BboxConverter,
"RecipeExtractor": RecipeExtractor,
"RecipeBuilder": RecipeBuilder,
"RecipeRenderer": RecipeRenderer,
"RecipeRelay": RecipeRelay,
"RecipeModelLoader": RecipeModelLoader,
"RecipeModelPicker": RecipeModelPicker,
"RecipeManager": RecipeManager,
"RecipeBuilderMultiPrompts": RecipeBuilderMultiPrompts,
"MultiLoraStackerLM": MultiLoraStackerLM,
"MultiLoraCombine": MultiLoraCombine,
"MultiLoraSplitter": MultiLoraSplitter,
"LoraStackCombine": LoraStackCombine,
}
NODE_DISPLAY_NAME_MAPPINGS = {
"PromptApplyLora": "Apply LoRA++",
"PromptManagerAdvanced": "Prompt Manager",
"PromptManager": "Prompt Manager (Basic)",
"PromptComposer": "Prompt Composer",
"LibraryManager": "Library Manager",
"PromptGenerator": "Prompt Generator",
"PromptGenOptions": "Prompt Generator Options",
"PromptGeneratorKillSwitch": "Prompt Generator Kill Switch",
"PromptExtractor": "Prompt Extractor",
"PromptLayoutBuilder": "Prompt Layout Builder",
"BboxConverter": "Bbox Converter",
"RecipeExtractor": "Recipe Extractor",
"RecipeBuilder": "Recipe Builder",
"RecipeRenderer": "Recipe Renderer",
"RecipeRelay": "Recipe Relay",
"RecipeModelLoader": "Recipe Model Loader",
"RecipeModelPicker": "Recipe Model Picker",
"RecipeManager": "Recipe Manager",
"RecipeBuilderMultiPrompts": "Multi Prompts",
"MultiLoraStackerLM": "Multi LoRA Stack",
"MultiLoraCombine": "Multi LoRA Combine",
"MultiLoraSplitter": "Multi LoRA Splitter",
"LoraStackCombine": "LoRA Stack Combine",
}
WEB_DIRECTORY = "./js"
__all__ = ['NODE_CLASS_MAPPINGS', 'NODE_DISPLAY_NAME_MAPPINGS', 'WEB_DIRECTORY']
print("[PromptManager] Nodes registered: Apply LoRA++, Prompt Manager, Prompt Generator, Prompt Extractor, Recipe Extractor, Recipe Builder, Recipe Renderer, Recipe Relay, Recipe Manager")
# Ensure rotating backups exist for all prompt data files on ComfyUI startup.
try:
check_backup(PromptManager.get_prompts_path())
check_backup(PromptComposerStore.get_data_path())
check_backup(PromptGeneratorDataStore.get_data_path())
except Exception as e:
print(f"[PromptManager] Backup initialization skipped: {e}")
print("[PromptManager] Nodes registered: Prompt Manager, Prompt Composer, Prompt Generator, Prompt Generator Kill Switch, Prompt Extractor, Recipe Extractor, Recipe Builder, Recipe Renderer, Recipe Relay, Library Manager")
-60
View File
@@ -1,60 +0,0 @@
{
"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"
},
"Dynamic Action Scene": {
"prompt": "Extreme dynamic composition capturing peak moment of action, subject frozen mid-motion with sense of kinetic energy and movement, dramatic diagonal lines and angles creating visual tension, motion blur on background elements while keeping subject sharp, debris and particles flying through air, forced perspective emphasizing speed and impact, rule of thirds with subject positioned at power point, leading lines directing eye to focal point, sense of chaos controlled through thoughtful composition, high shutter speed photography aesthetic, dramatic depth of field separating subject from background, cinematic framing worthy of movie poster, professional action photography, 8k ultra sharp detail"
},
"Epic Landscape Vista": {
"prompt": "Sweeping panoramic landscape composition showcasing vast scale and grandeur of nature, foreground with detailed elements leading eye into scene, middle ground with points of interest, distant background with atmospheric perspective fading to horizon, dramatic sky occupying upper third of composition, sense of depth created through layering and scale relationships, golden ratio spiral guiding viewer's journey through image, professional landscape photography aesthetic, perfect balance of earth and sky, sense of awe and sublime beauty, Ansel Adams inspired tonal range, 21:9 ultra-wide aspect ratio, maximum dynamic range, 8k ultra high resolution"
},
"Frame Within Frame": {
"prompt": "Creative composition using natural or architectural elements to create frame within the photograph's frame, doorways, windows, arches, or overhanging branches framing main subject, layered composition adding depth and visual interest, vignetting effect drawing attention to central subject, sense of discovery as if viewer is peeking into scene, strategic use of foreground elements to add context and depth, professional composition technique adding sophistication, balance between frame elements and main subject, enhanced three-dimensional quality, painterly aesthetic with careful attention to spatial relationships, selective focus with frame slightly softened, artistic photography style, 4k quality with rich detail"
},
"Leading Lines Perspective": {
"prompt": "Strong compositional technique using leading lines to draw viewer's eye deep into scene, converging lines creating powerful sense of depth and three-dimensional space, linear perspective with prominent vanishing point, roads, pathways, rivers, or architectural elements creating directional flow toward focal point, exaggerated perspective emphasizing distance and scale, wide-angle lens characteristics with slight distortion at edges, journey-like quality inviting exploration, strategic placement of subject at convergence point, professional architectural photography aesthetic, sharp detail from foreground to background, enhanced depth of field, dramatic sense of scale and distance, cinematic composition, 8k ultra detailed"
},
"Low Angle Power Shot": {
"prompt": "Dramatic low angle composition shot from ground level looking upward, subject towering above camera creating sense of power, dominance, and monumentality, exaggerated perspective with converging vertical lines, hero shot aesthetic emphasizing strength and importance, sky or ceiling as background creating clean backdrop, forced perspective making subject appear larger than life, cinematic quality reminiscent of superhero movie posters, dynamic tension from unusual viewpoint, professional photography technique for impactful imagery, wide-angle lens characteristics, dramatic clouds or architectural details in background, epic scale and presence, 8k ultra sharp detail"
},
"Minimalist Zen Composition": {
"prompt": "Clean minimalist composition with abundant negative space, single focal point following principle of ma (negative space) from Japanese aesthetics, careful balance and harmony, limited color palette with subtle variations, geometric simplicity, breathing room around subject, sense of calm and contemplation, influenced by Scandinavian design principles and Japanese wabi-sabi, thoughtful placement following golden ratio, asymmetrical balance, every element serving purpose, no clutter or unnecessary details, modern contemporary art aesthetic, museum-quality presentation, pristine clarity, 4k resolution"
},
"Rule of Thirds Mastery": {
"prompt": "Expert application of rule of thirds compositional technique, subject positioned at intersection points of imaginary grid dividing frame into nine equal parts, horizon line carefully placed along upper or lower third line, key elements strategically positioned along grid lines, negative space balanced across frame, dynamic tension created by off-center placement, professional photography composition creating visual interest, golden ratio principles subtly integrated, perfect balance between subject and environment, sense of movement and energy from asymmetrical placement, cinematic quality worthy of film frame, natural eye flow through image, masterful composition, 8k resolution with exceptional clarity"
},
"Spiral Composition": {
"prompt": "Elegant spiral composition with elements arranged in curved flowing pattern leading eye in circular journey through image, fibonacci spiral or golden spiral guiding placement of key elements, sense of movement and natural flow, dynamic yet harmonious arrangement, organic curved lines contrasting with or complementing subject, shell-like or galaxy-like compositional structure, baroque painting influence with sweeping curves, professional fine art composition creating visual rhythm, balanced yet energetic, eye travels continuously through frame, painterly quality with masterful arrangement, depth created through overlapping curved elements, sophisticated artistic composition, museum quality, 4k resolution"
},
"Symmetrical Balance Portrait": {
"prompt": "Perfectly symmetrical composition with subject centered in frame, bilateral symmetry creating sense of stability and formality, architectural elements framing subject on both sides, mirrored elements balanced left and right, frontal perspective with direct eye contact, classical portrait composition reminiscent of renaissance paintings, vertical orientation emphasizing height and dignity, careful attention to equal weight distribution across frame, geometric precision in placement, formal aesthetic with authoritative presence, balanced color distribution, professional studio portrait photography, sharp focus throughout, medium format camera quality, 4k resolution with exceptional detail"
}
},
"Environment": {
"Alien Planet Landscape": {
"prompt": "A vast alien planetary landscape featuring bizarre otherworldly geology with towering crystalline formations jutting from the ground, purple and teal-colored soil and rock formations created by exotic mineral compositions, strange alien vegetation with bioluminescent properties growing in unusual fractal patterns, multiple moons of different sizes visible in the sky along with a nearby gas giant planet, alien atmosphere creating unusual light diffraction effects and colorful aurora-like phenomena, exotic weather patterns with unusual cloud formations, distant alien ruins suggesting ancient civilization, sense of wonder and cosmic scale, scientifically plausible exobiology, volumetric atmosphere with unique lighting, photorealistic rendering of fantastical elements, inspired by speculative xenobiology, cinematic composition, 8k ultra high resolution"
},
"Desert Oasis Settlement": {
"prompt": "A thriving desert oasis settlement surrounded by endless golden sand dunes, cluster of traditional mud-brick buildings with flat roofs and decorative arches clustered around a pristine blue pool of water fed by underground springs, palm trees providing shade and greenery, colorful market stalls with fabric awnings selling spices and goods, people in flowing desert robes and head wraps, camels resting near water, mountains visible in distant heat haze, dramatic sunset lighting casting long shadows and painting sky in oranges and purples, sense of refuge and life in harsh environment, Middle Eastern and North African architectural influences, warm earth tone color palette, atmospheric perspective with heat shimmer, highly detailed textures on adobe buildings and desert landscape, photorealistic rendering, 8k resolution"
},
"Enchanted Ancient Forest": {
"prompt": "A mystical ancient forest with towering thousand-year-old trees whose massive trunks are covered in luminescent moss and glowing mushrooms, thick canopy overhead filtering ethereal beams of golden sunlight that illuminate swirling magical particles and floating motes of light, forest floor carpeted with colorful wildflowers and bioluminescent plants that pulse with soft light, weathered stone ruins of an ancient civilization partially reclaimed by nature with intricate carvings still visible, gentle mist rolling through the undergrowth creating atmospheric depth, crystal-clear stream winding through the scene with small waterfalls, fireflies dancing in the air, sense of timeless magic and natural wonder, fantasy illustration style with rich saturated colors, highly detailed vegetation and atmospheric lighting effects, 8k resolution"
},
"Gothic Cathedral Grand Hall": {
"prompt": "Interior of a magnificent Gothic cathedral with soaring vaulted ceilings reaching into darkness, massive stone pillars with intricate carved details and gargoyles, enormous stained glass windows depicting biblical scenes in rich jewel tones casting colorful light patterns across the stone floor, rows of wooden pews leading to ornate altar, burning candles and hanging chandeliers providing warm ambient lighting, morning sunlight streaming through rose window creating dramatic god rays through dust motes in air, sense of awe-inspiring scale and sacred atmosphere, weathered stone showing centuries of history, architectural details including flying buttresses visible through windows, rich tapestries hanging from walls, incense smoke adding atmospheric haze, historical accuracy in medieval architecture, painterly lighting, highly detailed stonework and decorative elements, 4k quality"
},
"Neon-Lit Cyberpunk Metropolis": {
"prompt": "A sprawling cyberpunk megacity at night viewed from an elevated position, endless skyscrapers stretching to the horizon covered in massive holographic advertisements displaying animated corporate logos and products, streets far below bustling with hovering vehicles leaving light trails, neon signs in multiple Asian languages creating a vibrant glow, heavy rain creating reflections on every surface and adding atmospheric moisture, steam venting from industrial grates, layered city architecture showing wealth disparity from gleaming corporate towers to cramped lower-level slums, drone traffic weaving between buildings, atmospheric fog and smog creating volumetric lighting effects, dominant color palette of cyan, magenta, and purple neons contrasted with warm orange street lights, Blade Runner and Ghost in the Shell aesthetic, highly detailed urban environment, photorealistic rendering, 8k resolution"
},
"Orbital Space Station Interior": {
"prompt": "Interior of a massive rotating space station with curved corridors and large observation windows showing breathtaking views of Earth and stars, high-tech modular architecture with clean white and gray surfaces, holographic control panels and floating displays, artificial gravity section with hydroponics gardens growing food, astronauts in modern space suits working on equipment, sense of scale with multiple levels visible, soft blue accent lighting along corridors, scientific equipment and research stations, glimpse of space through massive reinforced windows showing auroras on Earth below, futuristic yet functional design, hard science fiction realism, attention to zero-g engineering details, photorealistic rendering with accurate lighting and materials, inspired by NASA concepts and modern space station design, 8k ultra detailed"
},
"Steampunk Victorian London": {
"prompt": "A Victorian-era London reimagined with steampunk technology, cobblestone streets with brass street lamps emitting warm gas light, elaborate clockwork mechanisms and steam-powered machinery integrated into Gothic architecture, gentlemen in top hats and ladies in corsets walking past shops with copper and brass storefronts, massive airships floating above buildings with visible propellers and steam vents, intricate gear-work visible in building facades, smog and steam creating atmospheric haze, newspaper boys selling penny dreadfuls, horse-drawn carriages sharing streets with steam-powered vehicles, warm amber and bronze color palette, attention to Victorian-era details combined with fantastical brass technology, oil painting aesthetic with rich textures, highly detailed architectural elements, 4k quality"
},
"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"
}
}
}
+110
View File
@@ -1,5 +1,115 @@
# Changelog
## version 3.0.1
- **Prompt Generator: GPU detection fix for Windows (and recent llama.cpp builds)**
- `--n-gpu-layers 0` is no longer forced just because GPU support could not be detected. On Windows the old check always failed (`ldd` does not exist there, `--version` no longer names the backend, and `-h` lists `--n-gpu-layers` on every build), which pushed CUDA users into CPU inference and printed a misleading "CPU-only build" error.
- Detection now asks llama.cpp itself with `--list-devices`, and falls back to the GPU backend libraries next to the binary (`ggml-cuda.dll` etc.) or `ldd` on Linux.
- Console output now distinguishes "no GPU device in this build" (warning, CPU is correct) from "unknown" (offload is requested and llama.cpp decides).
- README: corrected install notes (winget `ggml.llamacpp` ships the official **Vulkan** build, Homebrew builds ggml with Vulkan/OpenBLAS on Linux and Metal on Apple Silicon) and added a `llama-server --list-devices` check.
## version 3.0.0
- **Breaking: one `MANAGER_DATA` type**
- Prompt Manager, Prompt Composer, Prompt Layout Builder and the Recipe nodes now share `manager_data` (replaces `RECIPE_DATA` and `COMPOSE_DATA`). Older workflows need these links reconnected.
- Recipe Renderer outputs `output_image`, `output_latent`, `manager_data`; Recipe Extractor outputs `image`, `manager_data`.
- **New Library Manager** (replaces Composition Manager and Recipe Manager)
- Saves and reloads the `manager_data` of Prompt Manager, the Recipe nodes, Prompt Composer and Prompt Layout Builder, with thumbnails.
- Filters for All / Prompt / Recipe / Compose / Layout.
- **New Prompt Library Hub** (sidebar **Prompts** button, can be hidden in Settings)
- Replaces the Prompt Browser node, which has been removed.
- Browse & Edit, Import and Export for Saved Prompts (Prompt Manager / Prompt Composer / Prompt Layout / Prompt Recipe), Saved Snippets and Saved System Prompts.
- Per-category export; Snippets and System Prompts can also be replaced from a file, and System Prompts can restore the built-in defaults.
- **New Prompt Layout Builder**
- Draw Object, Character, Text and Panel boxes over a scene prompt, or load them from an LLM.
- Outputs MOSS-Image layout JSON, Ideogram 4 JSON captions or Krea 2 grounding lines (needs [krea2-turbo-bbox](https://huggingface.co/jimmycarter/krea2-turbo-bbox)).
- `import_json` reads all three formats, Create Bounding Boxes elements, and layouts saved with Library Manager.
- Box descriptions can come from Prompt Composer snippets.
- **New Bbox Converter**: converts a layout JSON to bounding boxes and elements, or bounding boxes back to a layout JSON.
- **Prompt Generator**
- The system prompt dropdown is replaced by a selector: arrows cycle through prompts, the name opens the Prompt Browser.
- New **Bbox** category with **MOSS Layout**, **Ideogram Layout** and **Krea 2 Layout** system prompts (Create and From Image).
- Fixed: the selected system prompt was reset to Enhance Prompt when reopening a workflow or switching tabs if the prompt was added or moved after the page loaded. Prompts moved to another category are now found by name.
- **Prompt Manager and editor**
- Export only selected categories.
- Preferred model settings, draft handling and clearer save/rename buttons in the prompt editor.
- Improved NSFW handling in the browser.
- **Prompt Composer**
- Prompt text tooltips, clear muted parts, RefMod rows.
- Picker renamed to "Select Prompt Snippet".
- Customizable thumbnail generation steps.
- Nodes 2.0 compatibility.
- Larger text across the node UIs.
- New Krea layout example workflow.
## version 2.8.0
- **Prompt Composer v2**
- New library format built around prompt groups, with a dialog to create groups and pick their category.
- Output as text or JSON, before or after the selected prompt, or on its own.
- Image and video generation modes.
- Subject numbers and subject types, mute for prompt parts.
- Export and import of composer libraries; new Generate Bulk Snippets system prompt.
- **Prompt Composer Manager** to save and reload Composer setups with thumbnails.
- Input prompt and LoRA modes on Prompt Composer and Prompt Manager, so compose data passing through Prompt Manager can add LoRAs and be saved for reuse.
- **Prompt Browser**: double-click to select, Home button, more responsive dialogs.
- Anima family support for thumbnail rendering.
- Preference to hide the downloadable built-in models in Prompt Generator.
- llama-server GPU support detection.
- Trigger word fixes: only connected words are pruned, words saved with the prompt are kept.
- Fixed LoRA stack cards collapsing or stretching to viewport height (thanks Martlet-Tech).
- Prompt Composer example workflows.
## version 2.7.2
- LoRA blacklist keywords for MiniMax and distilled LoRAs.
- Prompt Generator code moved to its own `prompt_generator.js`.
- Converter for the older system prompt storage format.
- README and feature reference updates.
## version 2.7.1
- Prompt text widgets become read-only while an external prompt input is connected; the received prompt is shown after execution.
- Prompt Extractor accepts a video input.
- Video prompt writing guides for MiniMax.
- Prompt Generator input prompt handling and model management improvements.
## version 2.7.0
- **New Prompt Composer** (started as Prompt Mixer): build prompts from multiple reusable parts.
- **System prompts are now user data**
- Stored in `prompt_generator_data.json` and editable in the Prompt Browser, grouped by category.
- New default system prompts for image and video models.
- **Prompt Browser**: multi-select, category type filter, scrolling category bar, view modes, unsaved-changes confirmation, bulk prompt builder.
- **llama.cpp** (thanks sophosympatheia)
- GPU device selection for multi-GPU systems.
- Fixed the server port ignoring the saved setting.
- Models and mmproj files are found in subfolders.
- Rotating backups for prompt data files.
- VRAM flush fixes when using a CLIP/text encoder.
## version 2.6.0
- Prompt Generator can use a connected CLIP/text encoder directly.
- Expression Selector: arrow navigation and strength slider.
- Multi LoRA Stacker: configurable stack count.
- Krea2 example workflow.
## version 2.5.4
- **Prompt Manager Advanced browser overhaul**
- Larger non-compact prompt browser with bigger 3:4 thumbnails.
- New browser view modes: Grid, Icon (small grid), and List.
- View mode is persisted in the browser and no longer controlled by a preference default.
- Compact browser size can still be restored via Preferences.
- **Krea2 thumbnail generation support**
- Recipe Renderer now supports the Krea2 family for thumbnail renders.
- **New Expression Selector node**
- Appends a saved Expression-category prompt to an input prompt.
- Supports gender-aware pronoun substitution.
- Add new expressions directly through Prompt Manager Advanced.
- Select `(none)` to pass the input prompt through unchanged.
## version 2.5.3
- **Improved Prompt Extractor to better match FBNodes image loader+**
- Can now browse any folder and can view in detail, normal and large Thumbnails.
## version 2.5.2
- **Improved LLM prompts in Prompt Generator**
- New System prompts for Video and Audio Generation
## version 2.5.0
- **Recipe Builder is now Multi-model Only**
- Expanded Builder authoring around `recipe_data` with slot-aware model blocks (`model_a`/`model_b`/`model_c`/`model_d`).
+145 -64
View File
@@ -1,87 +1,168 @@
# Feature Reference
This page contains the detailed feature overview that was moved out of the main README for faster scanning.
## Prompt Toolset
**This documentation is ongoing and will continue to improve**
### Prompt Manager
- All Prompt Manager features, plus LoRA and trigger-word integration
- Dual LoRA stack support for complex pipelines (for example Wan video)
- LoRA tags with inline strength editing
- Toggle active state per LoRA without rewiring
- Save LoRAs with prompt entries
- Override/merge behavior for connected vs saved LoRAs
- Optional recipe_data input integration
- Missing LoRA highlighting and LoRA Manager preview support
- Thumbnail generation from saved prompt entries
Allows for Saving and Loading prompts quickly using the Prompt Browser UI.
- Clicking the Blue Prompt Name button, under the text area, will open the Prompt Browser.
- Pressing the < > on each side of the button will quickly switch to the next prompt.
- **In Prompt Browser mode:**
- Click the + to create new Categories.
- Generate Thumbnails for Prompts or Categories (Right Click)
- If not set, a Pop Up will ask you to select the model to use for generation.
- Enable Edit mode to enable writing Prompts directly in the Browser.
- Be sure to save the prompt before generating its thumbnail
- Right click provides other options such as:
- Tagging as NSFW (filtering by default can be enabled in prefs)
- Moving or Renaming
- Pasting an image in as a Prompt
- Generating a thumbnail for a Prompt
- It is also possible to simply drag an image over a prompt to replace its Thumbnail.
- **On the node's Main UI:**
- Use Prompt input toggle to display incoming prompt (from Prompt Generator for example).
- Toggling off allows editing that new prompt.
- Use LoRA input allows choosing which LoRAs are used:
- Prompt LoRAs Only: This turns off any LoRAs connected to our node.
- Combine LoRAs: This uses both the prompt and incoming LoRAs, but will remove duplicates.
- Input LoRAs Only: For those times when you want just the Prompt but use your own new recipe.
- **Do note: If a prompt is saved again, this can change the LoRAs assigned to the Prompt**
- LoRA Support:
- Supports the Add-On LoRA Manager to display LoRA Thumbnails on Hover.
- LoRA input supports either Traditional LoRA Stackers or the new included Multi LoRA Stack.
- Using normal LoRA Stackers, two stacks of LoRAs can be used and will be displayed in our UI.
- Connecting Multi LoRA Stack instead allows up to four stacks to be displayed.
- Multi LoRA Stack uses the LoRA Manager add-on at its core and is needed for it to work.
- When LoRAs are used, the UI will display them as tags, allowing strength editing or toggling On or Off.
- A list of Trigger words can be connected and will be displayed as Tags that can be toggled On or Off.
- LoRAs are saved with prompt entries; this includes their state (On or Off) as well as their Strength.
- Missing LoRAs will be displayed as Red.
- The Save Button opens up the Prompt Browser, allowing saving under any category.
- The New Prompt Button is practical when you want to clear everything, including LoRAs, and start fresh.
- The More button allows access to Exporting your Saved Prompt, but also merging another JSON. Be careful.
### Prompt Manager (Basic)
- Category-based prompt organization
- Save/load prompts quickly
- NSFW tagging and filtering
- LLM input toggle
- Persistent storage in your ComfyUI user folder
A simpler no frills version that supports only Prompts. (This is the OG node)
- Select category and prompt using a purely comfy UI.
- If saving over an existing prompt, LoRAs and Thumbnails will be preserved.
- If NSFW filtering is enabled, NSFW Prompts will be hidden.
- LLM input toggle works similar to full node.
### Prompt Extractor
- Extract prompt/model/LoRA metadata from image, video, and JSON workflow files
- Supports ComfyUI, A1111/Forge, and WebP metadata formats
- First-frame extraction from videos
- Dual LoRA stack extraction for compatible workflows
- Input/output folder browsing
- Can also be used as an advanced media loader with metadata awareness
### Prompt Generator
- Local LLM generation with llama.cpp or Ollama
- Text enhancement and image analysis modes
- Optional JSON output mode
- Thinking mode support
- Multi-image support (up to 5 total with options node)
- Prompt Generator Options node for model and parameter control
Generates prompts using a local LLM. Supports either Llama.cpp or Ollama, but can also be used directly with Comfy's Text encoders.
Allows downloading of 3 different sizes of Unsloth's Qwen 3.5, but users are free to add more models in models/gguf. If found, the add-on will list them. (Refresh when adding new ones)
## Recipe Toolset
- Comes with a bundle of pre-made System Prompts.
- Use the arrows beside the system prompt name to cycle through saved prompts across categories, or click the name to open Prompt Browser on System Prompts. When loading workflows, legacy names such as `Enhance Prompt (Image)` are matched to current entries. Missing prompts fall back to `Image / Enhance Prompt` (or the first available entry if that default was removed), without changing other widget values.
- Create your own system prompts with the **Prompt Library Hub** (sidebar) or by clicking the system prompt name
- I highly recommend using the **rgthree add-on** and enable *"Auto Nest Subdirectories in Menus"*. This will display categories as submenus.
- Options to output in JSON format and enable Thinking mode.
- The stop_server_after toggle:
- Kills Llama.cpp after generating the prompt
- Tries to force Ollama to unload the current model
- The clear_vram_on_run toggle:
- Unloads Comfy's model from memory before generating the prompt
- Clears Vram again once the prompt is generated.
- It is recommended to leave on, unless you are using small models
- Both Stop_server and clear_vram are ignored when using Text encoders, as we instead let Comfy manage the VRAM.
- Expected llama.cpp startup failures log one actionable summary without a console traceback. Enable **Show everything in Console** in Prompt Generator Options and retry to see the traceback, full launch command, and server stderr. The workflow still fails normally, and unexpected errors retain their tracebacks.
- Lastly, the **Model Selection**:
- (Use Default): Uses the default model set in preferences, or the first found, if not set.
- Missing saved model selections fall back to the default selection with a console warning. If no suitable model is available, generation still reports an error.
- 3 Different Quant size of Qwen 3.5 can be automatically downloaded.
- Any models you add in models/gguf, or any custom folder if set in preferences.
- If you no longer want to see the built-in download entries, enable the `Hide downloadable built-in models` preference under Prompt Manager settings.
- For Multi-image support, connect the Generator Option node.
- Use the Prompt Generator Options node for controlling model parameters.
The Recipe Toolset is designed to build, manage, and rerun reusable generation pipelines. You can author recipes from scratch in Builder, combine recipe logic with Prompt Manager/Prompt Manager Advanced to reuse saved prompts, or import existing metadata via Extractor when you want to bootstrap from prior outputs.
### Prompt Generator Options
This node provides extra control to **Prompt Generator** and is NOT mandatory.
- Modify the selected system prompt, by either appending extra instructions or replacing it entirely.
- Provides extra images input for a Total of 5.
- Change the System settings for the model
- Change the GPU used by the LLM
### Prompt Library Hub
The **Prompts** button in ComfyUI's left sidebar opens the Prompt Library Hub (hide it with Settings > Prompt Manager > 4. Advanced Preferences > Show Prompts Sidebar Button): one place to browse, edit, import and export every Prompt Manager library. It has three sections:
- **Saved Prompts**: pick the type with the Prompt Manager / Prompt Composer / Prompt Layout / Prompt Recipe buttons (saved through Prompt Manager or Library Manager).
- **Saved Snippets**: the snippets used by Prompt Composer.
- **Saved System Prompts**: the system prompts used by Prompt Generator.
Every section has the same three buttons:
- **Browse & Edit**: opens the Prompt Browser on that library with the Edit tab on.
- **Import**: merge a file; when entries already exist you choose to keep or overwrite them. Snippets and System Prompts can also be replaced from a file, and System Prompts can restore the built-in defaults (adds back missing built-in prompts without touching yours). Saved Prompt types share one file, so they only merge.
- **Export**: pick the categories to export as one JSON file (Snippets export selected prompt groups as a ZIP).
The Prompt Generator's system prompts are stored in *prompt_generator_data.json*, so you can author your own. Built-in prompts added by updates can be brought into your saved system prompts with **Restore defaults**.
### Prompt Extractor
Extract prompt, model, and LoRA info out of images, videos, and JSON workflow files.
- Supports ComfyUI, A1111/Forge, and WebP metadata formats.
- Grabs the frame of your choice from videos using a time slider.
- Dual LoRA stack extraction for compatible workflows.
- Can browse from either the input or output folders directly.
- Can also be used as an advanced media loader with metadata awareness
### Prompt Layout Builder
Draw a layout of boxes over a scene prompt, or load one from an LLM, and output it as a layout prompt for MOSS-Image, Ideogram 4 or Krea 2.
- The canvas follows the aspect ratio and megapixels, or a connected image's ratio with **Use Reference Ratio**. A connected image is also shown behind the boxes.
- Draw, move and resize boxes on the canvas, or type exact x/y/width/height values. Each box is an **Object**, **Character**, **Text** (with the exact words to render) or **Panel** (shown in Krea 2 mode), with a description and an optional color palette.
- The thumbnail button beside a description picks a Prompt Composer snippet for the box.
- Full screen editor, grid overlay, canvas text size, undo/redo (Ctrl/Cmd+Z), duplicate (Ctrl/Cmd+D) and delete (Del).
- A hint lists what is missing, such as a box without a description.
- **Output** formats:
- **MOSS**: MOSS-Image layout JSON (the same format as the core MOSS-Image Layout Prompt), with meta tags, canvas type and palettes.
- **Ideogram**: Ideogram 4 JSON caption (the same format as Build JSON Prompt (Ideogram)), with background, photo or art style, aesthetics, lighting, medium and a style palette.
- **Krea 2**: Krea 2 grounding lines: a one-sentence summary, `@style; medium`, `~background`, then one line per box (panels first). Character boxes get a Person / Anime character / Furry tag and an optional ID; reuse the ID to keep the same character across panels. Requires the **krea2-turbo-bbox** model or LoRA, found here: [jimmycarter/krea2-turbo-bbox](https://huggingface.co/jimmycarter/krea2-turbo-bbox). See its PROMPTING.md for the prompt format and sampler settings.
- **Use import_json** reads the layout from `import_json` and locks the editor. It accepts layout JSON (percent, 0-1000 or MOSS-native boxes), Ideogram 4 captions, Krea 2 grounding lines, Create Bounding Boxes elements, or a saved layout's `manager_data` from Library Manager. Turn it off to keep editing the imported boxes.
- Prompt Generator system prompts for layouts (**Bbox** category): **MOSS Layout**, **Ideogram Layout** and **Krea 2 Layout**, each with **Create** and **From Image** versions. If they are missing, use **Restore defaults** for System Prompts in the Prompt Library Hub.
- Outputs: prompt, preview (the boxes drawn over the canvas), width, height and `manager_data` (save it with Library Manager).
- **Bbox Converter** converts layouts to and from ComfyUI's bounding-box types, so the builder can be chained with other box nodes. Connect a `layout_json` (any format the builder imports) or `bboxes` (bounding boxes, Create Bounding Boxes elements or their JSON); with both connected, a toggle picks the source. It outputs `layout_json` (passed through, or a percent layout when converting bboxes, without a prompt), pixel `bboxes` and `elements`.
## Recipe Toolset (Experimental)
The Recipe Toolset are a set of experimental nodes to lets you build, manage, and rerun reusable pipelines. You can write recipes from scratch in Builder, combine them with Prompt Manager / Prompt Manager Advanced to reuse saved prompts, or import existing metadata through Extractor when you want to bootstrap from something you already made. Then saved them as complete Recipes.
As Stated these were an experiment into improving Manager, but as been put aside a bit. The technology behind it is what allowed for Thumbnail Generation in Prompt Browser. The Recipe Relay node is great when creating slick workflows with a single link between subgraph, as it can stack 4 workflows of data in a single connection.
### Recipe Builder
- Central editing surface to build or modify recipes
- Primary authoring path for creating recipes from scratch
- Provides a recipe-focused workspace to inspect, adjust, and refine recipe fields without manually wiring every parameter node-by-node
- Can be used standalone or connected with other recipe/prompt nodes
- Works well with Prompt Manager so saved prompts can be reused as part of recipe-driven pipelines
- Ideal for iterative tuning: extract once, then keep adjusting recipe values and rerendering until the pipeline is where you want it
- Helps standardize presets so repeated jobs start from consistent known-good settings
The main place to create or tweak recipes.
- Build or modify recipes from scratch in one central spot.
- Inspect and adjust recipe fields without wiring every parameter by hand.
- Use it standalone, or connect it with other recipe/prompt nodes.
- Works well with Prompt Manager so saved prompts can be slotted into recipe-driven pipelines.
- Great for iterative tuning: extract once, keep tweaking values and rerendering until the pipeline feels right.
- Helps standardize presets so repeated jobs start from the same known-good setup.
### Recipe Extractor
- Reads and normalizes workflow metadata into reusable recipe data
- Converts raw generation metadata into a structured recipe format that is easier to edit and pass between nodes
- Helps preserve key settings (for example model family, sampler context, and recipe-specific parameters) when moving from ad-hoc runs to reusable setups
- Useful when you want to recreate a look/style from existing outputs and then iterate from a stable baseline
Reads and normalizes workflow metadata into reusable recipe data.
- Converts raw generation metadata into a cleaner recipe format that's easier to edit and pass between nodes.
- Keeps important settings intact when moving from one-off runs to reusable setups.
- Useful when you want to recreate a look/style from an existing output and iterate from there.
### Recipe Renderer
- Executes recipe-driven generation for fast reruns after setup
- Interprets recipe data and applies it to generation execution so you can reproduce prior results or batch variants with minimal manual changes
- Reduces setup overhead for repeated jobs by moving configuration logic into reusable recipe data
- Especially useful when you want to test multiple prompt/input variations while keeping the same core generation recipe intact
Runs recipe-driven generation so you can rerun pipelines quickly.
- Interprets recipe data during execution to reproduce prior results or batch variants with minimal manual work.
- Cuts down setup time for repeated jobs by moving configuration into reusable recipe data.
- Especially handy when testing different prompts or inputs while keeping the same core recipe.
### Recipe Relay
- Relays recipe data and compatible passthrough context across nodes
- Acts as a clean handoff point for recipe payloads so larger graphs stay modular and easier to reason about
- Preserves compatible context as data moves through the pipeline, reducing brittle copy/paste style wiring patterns
- Helpful when splitting complex graphs into logical stages (extract/build/render/manage) without losing recipe continuity
A clean handoff point for recipe data between nodes.
- Passes recipe data and compatible context across the graph.
- Keeps larger graphs modular and easier to follow.
- Preserves context through the pipeline, so you don't lose recipe continuity when splitting graphs into stages.
### Recipe Model Loader
- Loads model/checkpoint assets based on recipe data
- Resolves and applies model selections encoded in recipes so execution follows the intended model path automatically
- Supports model slot selection and loader-specific behavior
- Makes recipe playback more reliable across sessions by tying loader behavior to saved recipe intent instead of manual recollection
- Useful for multi-model pipelines where model choice is part of the recipe contract, not an afterthought
Loads models/checkpoints based on recipe data.
- Resolves model selections encoded in recipes so execution follows the intended model path automatically.
- Supports model slot selection and loader-specific behavior.
- Makes recipe playback more reliable across sessions by tying loader behavior to the saved recipe, not memory.
- Useful for multi-model pipelines where model choice is part of the recipe itself.
### Recipe Manager
- Save, browse, and reuse recipe entries
- Provides persistent recipe storage so successful setups can be cataloged and recalled quickly
- Works with Builder to quickly review and update saved recipe data
- Encourages a library-style workflow: capture working recipes, name/tag them, and reapply them across projects
- Great for maintaining repeatable production presets while still allowing safe versioned edits over time
### Saving Recipes (Library Manager)
Recipe nodes pass their data as `manager_data`, the same type used by Prompt Manager, Prompt Composer and Prompt Layout Builder. Save, browse, and reuse recipes with the **Library Manager** (it replaces the former Recipe Manager).
- Persistent recipe storage so successful setups can be cataloged and recalled quickly.
- Works with Builder for quick review and updates.
- Encourages a library-style workflow: capture working recipes, name/tag them, and reapply them across projects.
- Good for keeping repeatable production presets while still allowing safe edits over time.
## Model Family Support
Binary file not shown.

After

Width:  |  Height:  |  Size: 758 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 830 KiB

Before

Width:  |  Height:  |  Size: 93 KiB

After

Width:  |  Height:  |  Size: 93 KiB

Before

Width:  |  Height:  |  Size: 50 KiB

After

Width:  |  Height:  |  Size: 50 KiB

Before

Width:  |  Height:  |  Size: 95 KiB

After

Width:  |  Height:  |  Size: 95 KiB

Before

Width:  |  Height:  |  Size: 72 KiB

After

Width:  |  Height:  |  Size: 72 KiB

Before

Width:  |  Height:  |  Size: 102 KiB

After

Width:  |  Height:  |  Size: 102 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 53 KiB

After

Width:  |  Height:  |  Size: 87 KiB

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

After

Width:  |  Height:  |  Size: 142 KiB

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

After

Width:  |  Height:  |  Size: 433 KiB

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

After

Width:  |  Height:  |  Size: 538 KiB

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

After

Width:  |  Height:  |  Size: 668 KiB

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

After

Width:  |  Height:  |  Size: 5.5 KiB

+1638 -118
View File
File diff suppressed because it is too large Load Diff
+309 -15
View File
@@ -5,15 +5,19 @@ import { PM_UI_PALETTE } from "./ui_palette.js";
const NODE_CLASS = "MultiLoraStackerLM";
const LM_PROVIDER_CLASS = "Lora Stacker (LoraManager)";
const STYLE_ID = "pm-multi-lm-style";
const MIN_NODE_WIDTH = 1080;
const MIN_NODE_WIDTH = 320;
const MIN_NODE_HEIGHT = 320;
const DEFAULT_NODE_WIDTH = 1080;
const DEFAULT_NODE_WIDTH = 600;
const DEFAULT_NODE_HEIGHT = 430;
const MIN_STACK_COUNT = 1;
const MAX_STACK_COUNT = 4;
const DEFAULT_STACK_COUNT = 2;
// Height constants mirroring LM's loras_widget_utils.js
const LM_LORA_ENTRY_H = 40;
const LM_HEADER_H = 32;
const LM_CONTAINER_PAD = 12;
const LM_EMPTY_H = 100;
const FAST_PREVIEW_DELAY_MS = 20;
// Per-column chrome: title(22) + search textarea(50) + col padding(16)
const COL_CHROME_H = 88;
@@ -55,9 +59,10 @@ function ensureStyles() {
height: 100%;
box-sizing: border-box;
padding: 6px 6px 6px 6px;
overflow: hidden;
overflow: visible;
display: flex;
flex-direction: column;
position: relative;
}
.pm-multi-lm-root,
.pm-multi-lm-root * {
@@ -72,11 +77,74 @@ function ensureStyles() {
}
.pm-multi-lm-grid {
display: grid;
grid-template-columns: repeat(4, minmax(200px, 1fr));
grid-template-columns: repeat(2, minmax(200px, 1fr));
gap: 8px;
flex: 1;
min-height: 0;
align-items: stretch;
margin-top: -16px;
}
.pm-multi-lm-topbar {
display: inline-flex;
align-items: center;
justify-content: flex-start;
position: absolute;
left: 8px;
top: -48px;
z-index: 2;
margin-top: 0;
margin-bottom: 0;
flex-shrink: 0;
}
.pm-multi-lm-stack-control {
display: inline-flex;
align-items: center;
gap: 8px;
border: 1px solid ${panelBorder};
border-radius: 8px;
background: ${panel};
padding: 5px 8px;
}
.pm-multi-lm-stack-label {
font-size: 14px;
font-weight: 700;
letter-spacing: 0.02em;
color: ${textHeading};
user-select: none;
}
.pm-multi-lm-stepper {
display: inline-flex;
align-items: center;
gap: 4px;
}
.pm-multi-lm-step-btn {
width: 24px;
height: 24px;
border: 1px solid ${inputBorder};
border-radius: 5px;
background: ${inputBg};
color: ${textPrimary};
font-size: 14px;
line-height: 1;
padding: 0;
cursor: pointer;
}
.pm-multi-lm-step-btn:hover {
border-color: ${textHeading};
}
.pm-multi-lm-step-btn:disabled {
opacity: 0.45;
cursor: default;
}
.pm-multi-lm-step-value {
min-width: 16px;
text-align: center;
font-size: 14px;
font-weight: 700;
line-height: 1.1;
color: hsl(0 0% 100%);
font-variant-numeric: tabular-nums;
user-select: none;
}
.pm-multi-lm-col {
border: 1px solid ${panelBorder};
@@ -99,7 +167,7 @@ function ensureStyles() {
}
.pm-multi-lm-title {
font-weight: 700;
font-size: 12px;
font-size: 14px;
letter-spacing: 0.02em;
color: ${textHeading};
margin-bottom: 6px;
@@ -116,7 +184,7 @@ function ensureStyles() {
background: ${inputBg};
color: ${textPrimary};
margin-bottom: 6px;
font-size: 12px;
font-size: 14px;
flex-shrink: 0;
}
.pm-multi-lm-search::placeholder {
@@ -158,11 +226,13 @@ async function loadLmBridge() {
import("/extensions/ComfyUI-Lora-Manager/loras_widget.js"),
import("/extensions/ComfyUI-Lora-Manager/utils.js"),
import("/extensions/ComfyUI-Lora-Manager/lora_syntax_utils.js"),
]).then(([autocompleteMod, lorasWidgetMod, utilsMod, syntaxMod]) => ({
import("/extensions/ComfyUI-Lora-Manager/preview_tooltip.js"),
]).then(([autocompleteMod, lorasWidgetMod, utilsMod, syntaxMod, previewTooltipMod]) => ({
AutoComplete: autocompleteMod.AutoComplete,
addLorasWidget: lorasWidgetMod.addLorasWidget,
mergeLoras: utilsMod.mergeLoras,
applyLoraValuesToText: syntaxMod.applyLoraValuesToText,
PreviewTooltip: previewTooltipMod.PreviewTooltip,
})).catch((err) => {
console.warn("[PromptManager] Failed to load Lora-Manager bridge modules", err);
lmBridgePromise = null;
@@ -239,6 +309,73 @@ function getSlotByKey(node, slotKey) {
return node.__pmMultiLmSlots.find((s) => s && s.key === slotKey) ?? null;
}
function clampStackCount(value) {
const n = Number(value);
if (!Number.isFinite(n)) return DEFAULT_STACK_COUNT;
return Math.max(MIN_STACK_COUNT, Math.min(MAX_STACK_COUNT, Math.round(n)));
}
function getStackCount(node) {
const raw = node?.properties?.pmLoraStackCount;
return clampStackCount(raw ?? DEFAULT_STACK_COUNT);
}
function getVisibleSlotKeys(node) {
const count = getStackCount(node);
return SLOT_DEFS.slice(0, count).map((s) => s.key);
}
function syncStackCountWidget(node, count) {
const widget = getWidgetByName(node, "stack_count");
if (widget) widget.value = count;
}
function ensureActiveSlotVisible(node) {
if (!node || !node.properties) return;
const visible = getVisibleSlotKeys(node);
if (visible.length === 0) return;
if (!visible.includes(node.properties.pmActiveSlot)) {
node.properties.pmActiveSlot = visible[0];
}
}
function updateStackControlUi(node) {
const refs = node?.__pmStackControl;
if (!refs) return;
const count = getStackCount(node);
refs.value.textContent = String(count);
refs.dec.disabled = count <= MIN_STACK_COUNT;
refs.inc.disabled = count >= MAX_STACK_COUNT;
}
function applyVisibleStackCount(node) {
const slots = node?.__pmMultiLmSlots;
const grid = node?.__pmMultiLmGrid;
if (!Array.isArray(slots) || !grid) return;
const visible = new Set(getVisibleSlotKeys(node));
const visibleCount = visible.size || DEFAULT_STACK_COUNT;
grid.style.gridTemplateColumns = `repeat(${visibleCount}, minmax(200px, 1fr))`;
for (const slot of slots) {
if (!slot?.col) continue;
slot.col.style.display = visible.has(slot.key) ? "flex" : "none";
}
}
function setStackCount(node, value) {
if (!node) return;
if (!node.properties) node.properties = {};
node.properties.pmLoraStackCount = clampStackCount(value);
ensureActiveSlotVisible(node);
applyVisibleStackCount(node);
updateStackControlUi(node);
syncStackCountWidget(node, node.properties.pmLoraStackCount);
updateActiveColumnHighlight(node);
notifyHeightChange(node);
applyNodeSizeConstraints(node, false, true);
}
// ---------------------------------------------------------------------------
// Apply incoming lora code to a slot
// ---------------------------------------------------------------------------
@@ -331,9 +468,14 @@ function setActiveSlot(node, slotKey) {
function updateActiveColumnHighlight(node) {
if (!Array.isArray(node.__pmMultiLmSlots)) return;
ensureActiveSlotVisible(node);
const activeSlot = node.properties?.pmActiveSlot ?? "model_a";
const visible = new Set(getVisibleSlotKeys(node));
for (const slot of node.__pmMultiLmSlots) {
if (slot?.col) slot.col.classList.toggle("active-slot", slot.key === activeSlot);
if (slot?.col) {
const isActive = slot.key === activeSlot && visible.has(slot.key);
slot.col.classList.toggle("active-slot", isActive);
}
}
}
@@ -369,7 +511,75 @@ function createEmbeddedLorasWidget(node, lm, widgetName, initialValue, onChange)
out.widget.value = initialValue;
}
return { host, widget: out?.widget ?? null };
const fastPreviewCleanup = attachFastPreviewHandlers(host, lm);
return { host, widget: out?.widget ?? null, fastPreviewCleanup };
}
function attachFastPreviewHandlers(host, lm) {
if (!host || typeof lm?.PreviewTooltip !== "function") {
return () => {};
}
const tooltip = new lm.PreviewTooltip({ modelType: "loras" });
const processed = new WeakSet();
const bindNameEl = (nameEl) => {
if (!nameEl || processed.has(nameEl)) return;
processed.add(nameEl);
// Replace LM's delayed listeners on this element with a faster local one.
const replacement = nameEl.cloneNode(true);
const triggerEl = nameEl.closest(".lm-lora-entry") || nameEl.parentElement || replacement;
let previewTimer = null;
const clearPreviewTimer = () => {
if (previewTimer) {
clearTimeout(previewTimer);
previewTimer = null;
}
};
triggerEl.addEventListener("mouseenter", () => {
clearPreviewTimer();
previewTimer = setTimeout(async () => {
previewTimer = null;
const name = String(replacement.textContent || "").trim();
if (!name) return;
const rect = triggerEl.getBoundingClientRect();
try {
await tooltip.show(name, rect.right, rect.top);
} catch (_e) {
}
}, FAST_PREVIEW_DELAY_MS);
});
triggerEl.addEventListener("mouseleave", () => {
clearPreviewTimer();
tooltip.hide();
});
nameEl.replaceWith(replacement);
processed.add(replacement);
};
const bindAll = () => {
const nameEls = host.querySelectorAll(".lm-lora-name");
for (const nameEl of nameEls) bindNameEl(nameEl);
};
bindAll();
const observer = new MutationObserver(() => {
bindAll();
});
observer.observe(host, { childList: true, subtree: true });
return () => {
observer.disconnect();
tooltip.hide();
tooltip.cleanup();
};
}
// ---------------------------------------------------------------------------
@@ -380,8 +590,10 @@ function createEmbeddedLorasWidget(node, lm, widgetName, initialValue, onChange)
function computeContentHeight(node) {
let maxListH = LM_EMPTY_H;
const visible = new Set(getVisibleSlotKeys(node));
if (Array.isArray(node.__pmMultiLmSlots)) {
for (const slot of node.__pmMultiLmSlots) {
if (!visible.has(slot.key)) continue;
const count = Array.isArray(slot.lorasWidget?.value) ? slot.lorasWidget.value.length : 0;
const h = count === 0
? LM_EMPTY_H
@@ -389,7 +601,7 @@ function computeContentHeight(node) {
if (h > maxListH) maxListH = h;
}
}
return COL_CHROME_H + maxListH + 20;
return COL_CHROME_H + maxListH + 56;
}
function notifyHeightChange(node) {
@@ -402,15 +614,19 @@ function notifyHeightChange(node) {
setTimeout(() => { node?.setDirtyCanvas?.(true, true); }, 10);
}
function applyNodeSizeConstraints(node, useDefaultSize = false) {
function applyNodeSizeConstraints(node, useDefaultSize = false, forceWidth = false) {
if (!node || node.__pmApplyingSizeConstraint) return;
const currentW = Number(node?.size?.[0]) || 0;
const currentH = Number(node?.size?.[1]) || 0;
const targetW = useDefaultSize
? Math.max(DEFAULT_NODE_WIDTH, MIN_NODE_WIDTH, currentW)
: Math.max(MIN_NODE_WIDTH, currentW);
const minW = MIN_NODE_WIDTH * getStackCount(node);
const targetW = forceWidth
? minW
: (useDefaultSize
? Math.max(DEFAULT_NODE_WIDTH, minW, currentW)
: Math.max(minW, currentW));
const targetH = useDefaultSize
? Math.max(DEFAULT_NODE_HEIGHT, MIN_NODE_HEIGHT, currentH)
@@ -493,7 +709,14 @@ function buildSlotColumn(node, lm, slotDef) {
col.appendChild(embedded.host);
embedded.host.addEventListener("pointerdown", () => setActiveSlot(node, slotDef.key));
return { key: slotDef.key, stateWidget, searchInput, lorasWidget: embedded.widget, col };
return {
key: slotDef.key,
stateWidget,
searchInput,
lorasWidget: embedded.widget,
fastPreviewCleanup: embedded.fastPreviewCleanup,
col,
};
}
// ---------------------------------------------------------------------------
@@ -534,6 +757,45 @@ async function setupNodeUi(node) {
const root = document.createElement("div");
root.className = "pm-multi-lm-root";
// Top-left custom stack count control (1..4)
const topbar = document.createElement("div");
topbar.className = "pm-multi-lm-topbar";
const stackControl = document.createElement("div");
stackControl.className = "pm-multi-lm-stack-control";
const stackLabel = document.createElement("div");
stackLabel.className = "pm-multi-lm-stack-label";
stackLabel.textContent = "Lora Stack";
const stepper = document.createElement("div");
stepper.className = "pm-multi-lm-stepper";
const decBtn = document.createElement("button");
decBtn.className = "pm-multi-lm-step-btn";
decBtn.type = "button";
decBtn.textContent = "<";
const valueEl = document.createElement("div");
valueEl.className = "pm-multi-lm-step-value";
valueEl.textContent = String(getStackCount(node));
const incBtn = document.createElement("button");
incBtn.className = "pm-multi-lm-step-btn";
incBtn.type = "button";
incBtn.textContent = ">";
decBtn.addEventListener("click", () => setStackCount(node, getStackCount(node) - 1));
incBtn.addEventListener("click", () => setStackCount(node, getStackCount(node) + 1));
stepper.appendChild(decBtn);
stepper.appendChild(valueEl);
stepper.appendChild(incBtn);
stackControl.appendChild(stackLabel);
stackControl.appendChild(stepper);
topbar.appendChild(stackControl);
root.appendChild(topbar);
// 4-column LoRA grid
const grid = document.createElement("div");
grid.className = "pm-multi-lm-grid";
@@ -554,10 +816,15 @@ async function setupNodeUi(node) {
node.__pmMultiLmBridge = lm;
node.__pmMultiLmSlots = slots;
node.__pmMultiLmGrid = grid;
node.__pmStackControl = { dec: decBtn, inc: incBtn, value: valueEl };
node.__pmMultiLmRoot = root;
node.__pmMultiLmReady = true;
node.__pmMultiLmRefresh = () => {
refreshFromStoredValues(node);
applyVisibleStackCount(node);
updateStackControlUi(node);
syncStackCountWidget(node, getStackCount(node));
updateActiveColumnHighlight(node);
};
@@ -565,6 +832,8 @@ async function setupNodeUi(node) {
// Restore any lora data that onConfigure may have written before async completed
refreshFromStoredValues(node);
hideStateWidgets(node);
applyVisibleStackCount(node);
updateStackControlUi(node);
updateActiveColumnHighlight(node);
notifyHeightChange(node);
applyNodeSizeConstraints(node);
@@ -598,6 +867,13 @@ app.registerExtension({
if (!this.properties) this.properties = {};
if (!this.properties.pmActiveSlot) this.properties.pmActiveSlot = "model_a";
if (!Number.isFinite(Number(this.properties.pmLoraStackCount))) {
this.properties.pmLoraStackCount = DEFAULT_STACK_COUNT;
} else {
this.properties.pmLoraStackCount = clampStackCount(this.properties.pmLoraStackCount);
}
ensureActiveSlotVisible(this);
syncStackCountWidget(this, this.properties.pmLoraStackCount);
applyNodeSizeConstraints(this, true);
@@ -614,6 +890,14 @@ app.registerExtension({
this.comfyClass = LM_PROVIDER_CLASS;
hideStateWidgets(this);
if (!Number.isFinite(Number(this.properties?.pmLoraStackCount))) {
if (!this.properties) this.properties = {};
this.properties.pmLoraStackCount = DEFAULT_STACK_COUNT;
} else {
this.properties.pmLoraStackCount = clampStackCount(this.properties.pmLoraStackCount);
}
ensureActiveSlotVisible(this);
syncStackCountWidget(this, this.properties.pmLoraStackCount);
if (typeof this.__pmMultiLmRefresh === "function") {
this.__pmMultiLmRefresh();
@@ -645,9 +929,19 @@ app.registerExtension({
// ── onRemoved ──────────────────────────────────────────────────────
const onRemoved = nodeType.prototype.onRemoved;
nodeType.prototype.onRemoved = function () {
if (Array.isArray(this.__pmMultiLmSlots)) {
for (const slot of this.__pmMultiLmSlots) {
try {
slot?.fastPreviewCleanup?.();
} catch (_e) {
}
}
}
this.__pmMultiLmSlots = null;
this.__pmMultiLmRoot = null;
this.__pmMultiLmBridge = null;
this.__pmMultiLmGrid = null;
this.__pmStackControl = null;
this.__pmMultiLmReady = false;
this.__pmMultiLmRefresh = null;
return onRemoved ? onRemoved.apply(this, arguments) : undefined;
+108
View File
@@ -0,0 +1,108 @@
/**
* Shared media path browser helpers for FBnodes Load+ nodes.
*
* Provides the backend-list/file URL helpers, root resolution, and the
* input/output/absolute selection classifier used by the thumbnail browser
* (file_browser.js) so the loader nodes can browse anywhere while keeping
* old workflows working.
*/
import { app } from "../../scripts/app.js";
import { api } from "../../scripts/api.js";
export const SETTING_CUSTOM_PATH = "PromptManager.PromptExtractorCustomPath";
export function getCustomPresetPath() {
const pref = app.ui?.settings?.getSettingValue(SETTING_CUSTOM_PATH) || "";
return typeof pref === "string" ? pref.trim() : "";
}
/** URL that streams a media file from any path (for previews of out-of-tree files). */
export function mediaFileUrl(absPath) {
return api.apiURL(`/prompt-extractor/path-browser/file?path=${encodeURIComponent(absPath)}`);
}
function normalizeSlashes(p) {
return String(p || "").replace(/\\/g, "/");
}
/** True when `child` is inside `parent` (both absolute), case-insensitive on Windows. */
function isUnder(child, parent) {
if (!child || !parent) return false;
let c = normalizeSlashes(child).replace(/\/+$/, "");
let p = normalizeSlashes(parent).replace(/\/+$/, "");
if (navigator.platform.startsWith("Win")) {
c = c.toLowerCase();
p = p.toLowerCase();
}
return c === p || c.startsWith(p + "/");
}
/**
* Given a selected absolute path and the input/output roots, work out how to
* store it so old workflows keep working:
* - inside input -> { sourceFolder:"input", value:<relative> }
* - inside output -> { sourceFolder:"output", value:<relative> }
* - elsewhere -> { sourceFolder:null, value:<absolute> }
*/
export function classifySelection(absPath, roots) {
const inputRoot = roots?.input || "";
const outputRoot = roots?.output || "";
const norm = normalizeSlashes(absPath);
if (inputRoot && isUnder(absPath, inputRoot)) {
const rel = norm.slice(normalizeSlashes(inputRoot).replace(/\/+$/, "").length + 1);
return { sourceFolder: "input", value: rel, absPath };
}
if (outputRoot && isUnder(absPath, outputRoot)) {
const rel = norm.slice(normalizeSlashes(outputRoot).replace(/\/+$/, "").length + 1);
return { sourceFolder: "output", value: rel, absPath };
}
return { sourceFolder: null, value: absPath, absPath };
}
async function fetchBrowser(path, kind) {
const params = [];
if (path) params.push(`path=${encodeURIComponent(path)}`);
if (kind) params.push(`kind=${encodeURIComponent(kind)}`);
const query = params.length ? `?${params.join("&")}` : "";
const resp = await api.fetchApi(`/prompt-extractor/path-browser/list${query}`);
if (!resp.ok) {
let msg = `Request failed (${resp.status})`;
try {
const err = await resp.json();
if (err?.error) msg = err.error;
} catch {
// ignore
}
throw new Error(msg);
}
return await resp.json();
}
/** Resolve the input/output preset roots once (backend "roots" mode). */
export async function getMediaRoots() {
try {
const data = await fetchBrowser("", "");
const roots = Array.isArray(data?.roots) ? data.roots : [];
return { input: roots[0] || "", output: roots[1] || "" };
} catch {
return { input: "", output: "" };
}
}
// Register the shared Custom-path preference once.
app.registerExtension({
name: "PromptManager.PromptExtractorPathBrowser",
settings: [
{
id: SETTING_CUSTOM_PATH,
category: ["Prompt Manager", "Prompt Extractor", "Custom Browser Path"],
name: "Prompt Extractor Custom Browser Path",
tooltip: "Optional folder shown as the 'Custom' preset in the Load+ file browsers.",
type: "text",
defaultValue: "",
},
],
});
BIN
View File
Binary file not shown.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 747 B

After

Width:  |  Height:  |  Size: 29 KiB

+7061
View File
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+249
View File
@@ -0,0 +1,249 @@
import { api } from "../../scripts/api.js";
import { COMPOSER_ENDPOINT_PREFIX, getCategoryPromptEntries } from "./prompt_store_adapters.js";
const COMPOSER_CATEGORY_KEY_SEPARATOR = "::";
function newComposerLibrary() {
return { __meta__: { schema_version: 2, storage: "type_files" }, _types_: {} };
}
function isCanonicalComposerLibrary(library) {
return !!(
library
&& typeof library === "object"
&& !Array.isArray(library)
&& library._types_
&& typeof library._types_ === "object"
&& !Array.isArray(library._types_)
);
}
function normalizeComposerLibrary(library) {
if (!isCanonicalComposerLibrary(library)) {
throw new Error("Prompt Composer requires canonical v2 library data with _types_");
}
return library;
}
function getComposerTypeOrder(typeData) {
const numeric = Number(typeData?.order);
return Number.isInteger(numeric) ? numeric : Number.POSITIVE_INFINITY;
}
function getOrderedComposerTypes(types) {
const entries = Object.entries(types || {});
const hasExplicitOrder = entries.some(([, typeData]) => Number.isInteger(Number(typeData?.order)));
if (!hasExplicitOrder) {
return entries.sort((a, b) => String(a[0] || "").localeCompare(String(b[0] || ""), undefined, { sensitivity: "base" }));
}
return entries.sort((a, b) => {
const orderDiff = getComposerTypeOrder(a[1]) - getComposerTypeOrder(b[1]);
if (orderDiff !== 0) return orderDiff;
return String(a[0] || "").localeCompare(String(b[0] || ""), undefined, { sensitivity: "base" });
});
}
function buildComposerCategoryKey(typeFile, categoryName) {
const normalizedTypeFile = String(typeFile || "").trim();
const normalizedCategory = String(categoryName || "").trim();
if (!normalizedTypeFile) return normalizedCategory;
return `${normalizedTypeFile}${COMPOSER_CATEGORY_KEY_SEPARATOR}${normalizedCategory}`;
}
function normalizeComposerSubjectKind(value, fallback = "other") {
const normalized = String(value || "").trim().toLowerCase();
if (["character", "animal", "environment", "other"].includes(normalized)) {
return normalized;
}
if (normalized === "person") return "character";
return fallback;
}
function defaultComposerSubjectKind(subjectType) {
return String(subjectType || "").trim().toLowerCase() === "new_subject" ? "character" : "other";
}
function parseComposerCategoryKey(category) {
const raw = String(category || "").trim();
const separatorIndex = raw.indexOf(COMPOSER_CATEGORY_KEY_SEPARATOR);
if (separatorIndex <= 0) {
return { typeFile: "", categoryName: raw };
}
return {
typeFile: raw.slice(0, separatorIndex).trim(),
categoryName: raw.slice(separatorIndex + COMPOSER_CATEGORY_KEY_SEPARATOR.length).trim(),
};
}
export function resolveComposerCategoryKey(data, category) {
const raw = String(category || "").trim();
if (!raw) return "";
if (data?.[raw] && typeof data[raw] === "object") {
return raw;
}
const parsed = parseComposerCategoryKey(raw);
const normalizedCategoryName = String(parsed.categoryName || raw).trim().toLowerCase();
const normalizedTypeFile = String(parsed.typeFile || "").trim().toLowerCase();
let fallback = "";
for (const [categoryKey, categoryData] of Object.entries(data || {})) {
if (categoryKey === "__meta__" || !categoryData || typeof categoryData !== "object") continue;
const candidateCategoryName = String(categoryData._category_name_ || categoryKey).trim().toLowerCase();
if (candidateCategoryName !== normalizedCategoryName) continue;
const candidateTypeFile = String(categoryData._type_file_ || "").trim().toLowerCase();
if (normalizedTypeFile && candidateTypeFile === normalizedTypeFile) {
return categoryKey;
}
if (!fallback) {
fallback = categoryKey;
}
}
if (fallback) return fallback;
if (parsed.typeFile && parsed.categoryName) {
return buildComposerCategoryKey(parsed.typeFile, parsed.categoryName);
}
return raw;
}
function flattenComposerType(typeFile, typeData, flatData) {
if (!typeData || typeof typeData !== "object") return;
const typeKey = String(typeFile || "").replace(/\.json$/i, "").trim().toLowerCase();
const typeName = String(typeData.name || "").trim() || typeKey || "Misc";
const typePrefix = String(typeData.prefix || "");
const typeBasePrompt = String(typeData.base_prompt || "");
const typeSubjectType = String(typeData.subject_type || "subject").trim().toLowerCase() || "subject";
const typeSubjectKind = normalizeComposerSubjectKind(typeData.subject_kind, defaultComposerSubjectKind(typeSubjectType));
const typeNsfw = typeData.nsfw === true;
const categories = typeData.categories;
if (!categories || typeof categories !== "object" || Array.isArray(categories)) return;
for (const [categoryName, categoryData] of Object.entries(categories)) {
if (!categoryName || !categoryData || typeof categoryData !== "object") continue;
const promptEntries = categoryData._prompts_ && typeof categoryData._prompts_ === "object"
? categoryData._prompts_
: {};
const effectivePrefix = String(categoryData.prefix || typePrefix || "");
const effectiveBasePrompt = String(categoryData.base_prompt || typeBasePrompt || "");
const effectiveNsfw = categoryData.nsfw === true || typeNsfw;
const flatCategory = {
_prompts_: promptEntries,
_category_name_: String(categoryName || "").trim(),
_prompt_type_: typeKey,
_type_file_: String(typeFile || ""),
_type_name_: typeName,
_subject_type_: typeSubjectType,
_subject_kind_: typeSubjectKind,
};
if (effectivePrefix.trim()) flatCategory._prompt_prefix_ = effectivePrefix;
if (effectiveBasePrompt.trim()) flatCategory._base_prompt_ = effectiveBasePrompt;
if (String(categoryData.prefix || "").trim()) flatCategory._category_prefix_ = String(categoryData.prefix || "");
if (String(categoryData.base_prompt || "").trim()) flatCategory._category_base_prompt_ = String(categoryData.base_prompt || "");
if (typePrefix.trim()) flatCategory._type_prefix_ = typePrefix;
if (typeBasePrompt.trim()) flatCategory._type_base_prompt_ = typeBasePrompt;
if (typeNsfw) flatCategory._type_nsfw_ = true;
if (effectiveNsfw) flatCategory.__meta__ = { nsfw: true };
flatData[buildComposerCategoryKey(typeFile, categoryName)] = flatCategory;
}
}
export function flattenComposerLibrary(library) {
const normalized = normalizeComposerLibrary(library);
const flatData = { __meta__: normalized.__meta__ || { schema_version: 2, storage: "type_files" } };
for (const [typeFile, typeData] of getOrderedComposerTypes(normalized._types_ || {})) {
flattenComposerType(typeFile, typeData, flatData);
}
return flatData;
}
export async function loadComposerPrompts(node) {
try {
const resp = await fetch(`${COMPOSER_ENDPOINT_PREFIX}/get-prompts`, {
cache: "no-store",
});
const library = await resp.json();
node.composerPromptLibrary = normalizeComposerLibrary(library);
node.composerPrompts = flattenComposerLibrary(node.composerPromptLibrary);
// Make the shared browser see composer data instead of prompt_manager_data.json.
node.prompts = node.composerPrompts;
} catch (err) {
console.error("[PromptComposer] Error loading composer prompts:", err);
node.composerPromptLibrary = newComposerLibrary();
node.composerPrompts = {};
node.prompts = {};
}
return node.composerPrompts;
}
function getComposerData(node) {
// The shared browser mutates node.prompts; for composer nodes that is always composer data.
return node.prompts || node.composerPrompts || {};
}
export function getComposerCategories(node) {
const data = getComposerData(node);
return Object.keys(data).filter((c) => c !== "__meta__").sort((a, b) => a.localeCompare(b, undefined, { sensitivity: "base" }));
}
export function getComposerNames(node, category) {
const data = getComposerData(node);
const catData = data[resolveComposerCategoryKey(data, category)];
if (!catData || typeof catData !== "object") return [];
return Object.keys(getCategoryPromptEntries(catData, "composer")).sort((a, b) => a.localeCompare(b, undefined, { sensitivity: "base" }));
}
export function getComposerEntry(node, category, name) {
const data = getComposerData(node);
const catData = data[resolveComposerCategoryKey(data, category)];
if (!catData || typeof catData !== "object") return null;
return getCategoryPromptEntries(catData, "composer")[name] || null;
}
export async function saveComposerCategorySettings(category, settings) {
try {
const resp = await fetch(`${COMPOSER_ENDPOINT_PREFIX}/save-category-settings`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
category,
type_file: settings.typeFile || "",
base_prompt: settings.basePrompt || "",
prompt_type: settings.promptType || "",
prefix: settings.promptPrefix || "",
}),
});
return await resp.json();
} catch (err) {
console.error("[PromptComposer] Error saving category settings:", err);
return { success: false, error: String(err) };
}
}
export async function saveComposerTypeSettings(settings) {
try {
const resp = await fetch(`${COMPOSER_ENDPOINT_PREFIX}/save-type-settings`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
type_file: settings.typeFile || "",
prompt_type: settings.promptType || "",
type_name: settings.typeName || "",
subject_type: settings.subjectType || "subject",
subject_kind: normalizeComposerSubjectKind(
settings.subjectKind,
defaultComposerSubjectKind(settings.subjectType || "subject")
),
prefix: settings.promptPrefix || "",
base_prompt: settings.basePrompt || "",
}),
});
return await resp.json();
} catch (err) {
console.error("[PromptComposer] Error saving type settings:", err);
return { success: false, error: String(err) };
}
}
export { COMPOSER_ENDPOINT_PREFIX };
+423 -147
View File
@@ -6,6 +6,7 @@
import { app } from "../../scripts/app.js";
import { api } from "../../scripts/api.js";
import { createFileBrowserModal } from "./file_browser.js";
import { mediaFileUrl, getMediaRoots, classifySelection } from "./path_browser.js";
// Placeholder image path - loaded from static PNG file
const PLACEHOLDER_IMAGE_PATH = new URL("./placeholder.png", import.meta.url).href;
@@ -13,6 +14,55 @@ const PLACEHOLDER_IMAGE_PATH = new URL("./placeholder.png", import.meta.url).hre
// Track videos that the browser cannot decode (H265/yuv444) - skip browser attempts on scrub
const _nonBrowserDecodableVideos = new Set();
function isAbsolutePath(value) {
if (!value) return false;
return /^([a-zA-Z]:[\\/]|\\\\|\/)/.test(value);
}
function hideWidget(widget) {
if (!widget) return;
widget.hidden = true;
widget.computeSize = () => [0, -4];
if (widget.inputEl) widget.inputEl.style.display = "none";
}
function buildPreviewUrl(filename, viewType) {
if (isAbsolutePath(filename)) {
return mediaFileUrl(filename);
}
let actualFilename = filename;
let subfolder = "";
if (filename.includes('/')) {
const lastSlash = filename.lastIndexOf('/');
subfolder = filename.substring(0, lastSlash);
actualFilename = filename.substring(lastSlash + 1);
}
let url = `/view?filename=${encodeURIComponent(actualFilename)}&type=${viewType || 'input'}`;
if (subfolder) {
url += `&subfolder=${encodeURIComponent(subfolder)}`;
}
return url;
}
function resolveMediaSource(filename, sourceFolder) {
return isAbsolutePath(filename) ? "absolute" : (sourceFolder || "input");
}
function basenameForDisplay(value) {
const s = String(value || "");
const normalized = s.replace(/\\/g, "/");
const i = normalized.lastIndexOf("/");
return i >= 0 ? normalized.substring(i + 1) : normalized;
}
function stripAnnotation(filename) {
if (!filename) return filename;
const match = filename.match(/^(.+)\s+\[(input|output|temp)\]$/);
return match ? match[1] : filename;
}
/**
* Extract metadata from PNG file
* Reads tEXt/iTXt chunks for prompt and workflow (ComfyUI native approach)
@@ -329,7 +379,7 @@ function _createExtractorSummaryLoraTag(lora) {
background:${isAvailable ? "rgba(61,134,210,0.9)" : "rgba(220,53,69,0.9)"};
color:#fff;
flex-shrink:0;
font-size:12px;
font-size:14px;
`;
const nameSpan = document.createElement("span");
@@ -339,7 +389,7 @@ function _createExtractorSummaryLoraTag(lora) {
const strengthBadge = document.createElement("span");
strengthBadge.textContent = Number.isFinite(strength) ? strength.toFixed(2) : "1.00";
strengthBadge.style.cssText = "font-size:10px; font-weight:600; padding:1px 6px; border-radius:999px; background:rgba(255,255,255,0.15);";
strengthBadge.style.cssText = "font-size:12px; font-weight:600; padding:1px 6px; border-radius:999px; background:rgba(255,255,255,0.15);";
tag.appendChild(strengthBadge);
return tag;
@@ -359,7 +409,7 @@ function _showExtractorWorkflowSummaryDialog(summary) {
dialog.appendChild(title);
const meta = document.createElement("div");
meta.style.cssText = "margin-bottom:12px; color:#9eb2c6; font-size:12px; padding-bottom:10px; border-bottom:1px solid rgba(115,144,170,0.35);";
meta.style.cssText = "margin-bottom:12px; color:#9eb2c6; font-size:14px; padding-bottom:10px; border-bottom:1px solid rgba(115,144,170,0.35);";
meta.innerHTML = `<b style=\"color:#c5d8ea;\">Models found:</b> ${summary.modelCount}`;
dialog.appendChild(meta);
@@ -371,14 +421,14 @@ function _showExtractorWorkflowSummaryDialog(summary) {
if (!summary.modelDetails.length) {
const none = document.createElement("div");
none.textContent = "No models found.";
none.style.cssText = "color:#9aa8b7; font-size:12px;";
none.style.cssText = "color:#9aa8b7; font-size:14px;";
modelsList.appendChild(none);
} else {
for (const item of summary.modelDetails) {
const row = document.createElement("div");
const familyText = item.family ? ` (${item.family})` : "";
row.textContent = `${item.slotLabel}: ${item.modelDisplay || "(none)"}${familyText}`;
row.style.cssText = "color:#d9e6f3; font-size:13px; background:rgba(37,48,60,0.55); border:1px solid rgba(96,124,150,0.35); border-radius:6px; padding:6px 8px;";
row.style.cssText = "color:#d9e6f3; font-size:15px; background:rgba(37,48,60,0.55); border:1px solid rgba(96,124,150,0.35); border-radius:6px; padding:6px 8px;";
modelsList.appendChild(row);
}
}
@@ -394,7 +444,7 @@ function _showExtractorWorkflowSummaryDialog(summary) {
if (!summary.modelDetails.some((m) => Array.isArray(m.loras) && m.loras.length > 0)) {
const none = document.createElement("div");
none.textContent = "No LoRAs found.";
none.style.cssText = "color:#9aa8b7; font-size:12px; margin-bottom:8px;";
none.style.cssText = "color:#9aa8b7; font-size:14px; margin-bottom:8px;";
loraSection.appendChild(none);
} else {
for (const item of summary.modelDetails) {
@@ -404,7 +454,7 @@ function _showExtractorWorkflowSummaryDialog(summary) {
const stackTitle = document.createElement("div");
stackTitle.textContent = `Stack ${item.slotLabel}:`;
stackTitle.style.cssText = "color:#c5d8ea; font-size:12px; margin:0 0 6px 0;";
stackTitle.style.cssText = "color:#c5d8ea; font-size:14px; margin:0 0 6px 0;";
stackCard.appendChild(stackTitle);
const stackTags = document.createElement("div");
@@ -447,7 +497,7 @@ async function showExtractorWorkflowDiscoverySummary(node) {
if (!workflowData) {
const imageWidget = node?.widgets?.find((w) => w.name === "image");
const filename = String(imageWidget?.value || "").trim();
const sourceFolder = node?._sourceFolder || "input";
const sourceFolder = resolveMediaSource(filename, node?._sourceFolder || "input");
if (filename && filename !== "(none)") {
try {
const previewResp = await fetch(`/prompt-extractor/extract-preview?filename=${encodeURIComponent(filename)}&source=${encodeURIComponent(sourceFolder)}`);
@@ -835,20 +885,7 @@ async function cacheVideoFrame(filename, frameData, framePosition) {
* Create and show image preview modal
*/
function showImagePreviewModal(filename, viewType) {
// Build image URL
let actualFilename = filename;
let subfolder = "";
if (filename.includes('/')) {
const lastSlash = filename.lastIndexOf('/');
subfolder = filename.substring(0, lastSlash);
actualFilename = filename.substring(lastSlash + 1);
}
let imageUrl = `/view?filename=${encodeURIComponent(actualFilename)}&type=${viewType || 'input'}`;
if (subfolder) {
imageUrl += `&subfolder=${encodeURIComponent(subfolder)}`;
}
const imageUrl = buildPreviewUrl(filename, viewType);
// Create modal overlay
const overlay = document.createElement('div');
@@ -884,7 +921,7 @@ function showImagePreviewModal(filename, viewType) {
title.textContent = filename;
title.style.cssText = `
color: #fff;
font-size: 14px;
font-size: 16px;
font-family: sans-serif;
overflow: hidden;
text-overflow: ellipsis;
@@ -893,7 +930,7 @@ function showImagePreviewModal(filename, viewType) {
`;
const closeBtn = document.createElement('button');
closeBtn.textContent = '?';
closeBtn.textContent = 'X';
closeBtn.style.cssText = `
background: rgba(255, 255, 255, 0.1);
border: none;
@@ -941,7 +978,7 @@ function showImagePreviewModal(filename, viewType) {
<div style="color: #ff6666; font-family: sans-serif; text-align: center;">
<div style="font-size: 48px; margin-bottom: 10px;">??</div>
<div>Failed to load image</div>
<div style="font-size: 12px; margin-top: 5px; opacity: 0.7;">${filename}</div>
<div style="font-size: 14px; margin-top: 5px; opacity: 0.7;">${filename}</div>
</div>
`;
};
@@ -955,7 +992,7 @@ function showImagePreviewModal(filename, viewType) {
position: absolute;
bottom: 20px;
color: rgba(255, 255, 255, 0.5);
font-size: 12px;
font-size: 14px;
font-family: sans-serif;
`;
@@ -987,20 +1024,7 @@ function showImagePreviewModal(filename, viewType) {
* Create and show video preview modal
*/
function showVideoPreviewModal(filename, viewType) {
// Build video URL
let actualFilename = filename;
let subfolder = "";
if (filename.includes('/')) {
const lastSlash = filename.lastIndexOf('/');
subfolder = filename.substring(0, lastSlash);
actualFilename = filename.substring(lastSlash + 1);
}
let videoUrl = `/view?filename=${encodeURIComponent(actualFilename)}&type=${viewType || 'input'}`;
if (subfolder) {
videoUrl += `&subfolder=${encodeURIComponent(subfolder)}`;
}
const videoUrl = buildPreviewUrl(filename, viewType);
// Create modal overlay
const overlay = document.createElement('div');
@@ -1036,7 +1060,7 @@ function showVideoPreviewModal(filename, viewType) {
title.textContent = filename;
title.style.cssText = `
color: #fff;
font-size: 14px;
font-size: 16px;
font-family: sans-serif;
overflow: hidden;
text-overflow: ellipsis;
@@ -1045,7 +1069,7 @@ function showVideoPreviewModal(filename, viewType) {
`;
const closeBtn = document.createElement('button');
closeBtn.textContent = '?';
closeBtn.textContent = 'X';
closeBtn.style.cssText = `
background: rgba(255, 255, 255, 0.1);
border: none;
@@ -1093,7 +1117,8 @@ function showVideoPreviewModal(filename, viewType) {
// Error handling - browser can't decode (H265/yuv444)
video.onerror = () => {
// Fall back to server-extracted frame with overlay
const frameUrl = `/prompt-extractor/video-frame?filename=${encodeURIComponent(filename)}&source=${viewType || 'input'}&position=0`;
const frameSource = resolveMediaSource(filename, viewType || 'input');
const frameUrl = `/prompt-extractor/video-frame?filename=${encodeURIComponent(filename)}&source=${frameSource}&position=0`;
const fallbackImg = document.createElement('img');
fallbackImg.style.cssText = `
max-width: 100%; max-height: 80vh; border-radius: 8px;
@@ -1107,7 +1132,7 @@ function showVideoPreviewModal(filename, viewType) {
msgOverlay.style.cssText = `
position: absolute; bottom: 20px; left: 50%; transform: translateX(-50%);
background: rgba(0, 0, 0, 0.75); color: #ccc; padding: 8px 16px;
border-radius: 6px; font-family: sans-serif; font-size: 13px;
border-radius: 6px; font-family: sans-serif; font-size: 15px;
pointer-events: none; white-space: nowrap;
`;
msgOverlay.textContent = 'H265/yuv444 \u2014 browser playback not supported';
@@ -1118,7 +1143,7 @@ function showVideoPreviewModal(filename, viewType) {
<div style="color: #aaa; font-family: sans-serif; text-align: center;">
<div style="font-size: 48px; margin-bottom: 10px;">\uD83C\uDFAC</div>
<div>This video format cannot be played in the browser</div>
<div style="font-size: 12px; margin-top: 5px; opacity: 0.7;">H265 or yuv444 encoded</div>
<div style="font-size: 14px; margin-top: 5px; opacity: 0.7;">H265 or yuv444 encoded</div>
</div>
`;
};
@@ -1134,7 +1159,7 @@ function showVideoPreviewModal(filename, viewType) {
position: absolute;
bottom: 20px;
color: rgba(255, 255, 255, 0.5);
font-size: 12px;
font-size: 14px;
font-family: sans-serif;
`;
@@ -1234,27 +1259,63 @@ app.registerExtension({
node._loadedFramePosition = null;
// Track source folder for URL type
node._sourceFolder = 'input';
node._imagePickerMap = { "(none)": "(none)" };
// Find the frame_position widget (slider) early so we can reference it
const framePositionWidget = this.widgets?.find(w => w.name === "frame_position");
let imagePickerWidget = null;
let updateImagePickerOptions = () => {};
let refreshImageOptionsForSource = async () => {};
let refreshImageOptionsForBrowsePath = async () => false;
// Find the source_folder widget
const sourceFolderWidget = this.widgets?.find(w => w.name === "source_folder");
if (sourceFolderWidget) {
node._sourceFolder = sourceFolderWidget.value || 'input';
hideWidget(sourceFolderWidget);
const origSourceFolderCb = sourceFolderWidget.callback;
sourceFolderWidget.callback = async function(value) {
if (origSourceFolderCb) origSourceFolderCb.apply(this, arguments);
node._sourceFolder = value || 'input';
// Refresh file list for the new source folder
// Refresh file list for the new source folder.
// Keep current selection (including absolute paths) if still valid.
try {
const listResponse = await api.fetchApi(`/prompt-extractor/list-files?source=${encodeURIComponent(value)}`);
if (listResponse.ok) {
const result = await listResponse.json();
if (imageWidget) {
imageWidget.options.values = ["(none)", ...(result.files || [])];
// Reset selection since files are from a different folder
imageWidget.value = "(none)";
if (imageWidget.callback) imageWidget.callback("(none)");
const files = Array.isArray(result.files) ? result.files : [];
imageWidget.options.values = ["(none)", ...files];
if (imagePickerWidget) {
const labels = ["(none)"];
const map = { "(none)": "(none)" };
const usedLabels = new Set(["(none)"]);
for (const fullValue of files) {
const base = basenameForDisplay(fullValue) || fullValue;
let label = base;
let idx = 2;
while (usedLabels.has(label)) {
label = `${base} (${idx++})`;
}
usedLabels.add(label);
labels.push(label);
map[label] = fullValue;
}
node._imagePickerMap = map;
imagePickerWidget.options.values = labels;
}
const currentValue = imageWidget.value;
const keepValue = isAbsolutePath(currentValue) || files.includes(currentValue);
if (keepValue && currentValue && currentValue !== "(none)") {
if (!imageWidget.options.values.includes(currentValue)) {
imageWidget.options.values = [...imageWidget.options.values, currentValue];
}
imageWidget.value = currentValue;
} else {
imageWidget.value = "(none)";
if (imageWidget.callback) imageWidget.callback("(none)");
}
}
}
} catch (err) {
@@ -1267,9 +1328,111 @@ app.registerExtension({
// Find the image widget (combo dropdown)
const imageWidget = this.widgets?.find(w => w.name === "image");
if (imageWidget) {
updateImagePickerOptions = (values, preferredValue = null) => {
if (!imagePickerWidget) return;
const labels = ["(none)"];
const map = { "(none)": "(none)" };
const usedLabels = new Set(["(none)"]);
for (const fullValue of values || []) {
const base = basenameForDisplay(fullValue) || fullValue;
let label = base;
let idx = 2;
while (usedLabels.has(label)) {
label = `${base} (${idx++})`;
}
usedLabels.add(label);
labels.push(label);
map[label] = fullValue;
}
node._imagePickerMap = map;
imagePickerWidget.options.values = labels;
const desired = stripAnnotation(preferredValue != null ? preferredValue : imageWidget?.value);
if (desired && desired !== "(none)") {
const label = Object.keys(map).find((k) => map[k] === desired);
imagePickerWidget.value = label || "(none)";
} else {
imagePickerWidget.value = "(none)";
}
};
refreshImageOptionsForSource = async (source, options = {}) => {
const { resetSelection = false, preferredValue = null } = options;
try {
const listResponse = await api.fetchApi(`/prompt-extractor/list-files?source=${encodeURIComponent(source || 'input')}`);
if (!listResponse.ok) return;
const result = await listResponse.json();
const files = Array.isArray(result?.files) ? result.files : [];
imageWidget.options.values = ["(none)", ...files];
updateImagePickerOptions(files, preferredValue);
if (resetSelection) {
if (imageWidget.value !== "(none)") {
imageWidget.value = "(none)";
if (imageWidget.callback) imageWidget.callback("(none)");
}
return;
}
const desiredRaw = preferredValue != null ? preferredValue : imageWidget.value;
const desired = stripAnnotation(desiredRaw);
if (desired && desired !== "(none)") {
if (!imageWidget.options.values.includes(desired)) {
imageWidget.options.values = ["(none)", desired, ...files.filter((f) => f !== desired)];
}
imageWidget.value = desired;
}
} catch (err) {
console.warn('[PromptExtractor] Could not fetch file list:', err);
}
};
refreshImageOptionsForBrowsePath = async (browsePath, preferredValue = null) => {
if (!browsePath) return false;
try {
const roots = await getMediaRoots();
const resp = await api.fetchApi(
`/prompt-extractor/path-browser/list?path=${encodeURIComponent(browsePath)}&kind=media`
);
if (!resp.ok) return false;
const data = await resp.json();
const files = Array.isArray(data?.files) ? data.files : [];
const mapped = [];
const seen = new Set();
for (const f of files) {
const absPath = typeof f === "string" ? f : f?.path;
if (!absPath) continue;
const cls = classifySelection(absPath, roots);
const value = cls?.value || String(absPath);
if (!seen.has(value)) {
seen.add(value);
mapped.push(value);
}
}
const desiredRaw = preferredValue != null ? preferredValue : imageWidget.value;
const desired = stripAnnotation(desiredRaw);
imageWidget.options.values = ["(none)", ...mapped];
updateImagePickerOptions(mapped, desired);
if (desired && desired !== "(none)") imageWidget.value = desired;
return true;
} catch (err) {
console.warn('[PromptExtractor] Could not refresh options for browse path:', err);
return false;
}
};
// Track the last known value to detect changes
let lastImageValue = imageWidget.value;
let extractionInProgress = false;
hideWidget(imageWidget);
// Store original callback
const originalCallback = imageWidget.callback;
@@ -1295,6 +1458,43 @@ app.registerExtension({
// Load and display the image/video (handles all display logic)
loadAndDisplayImage(node, value);
};
const setImageFilename = (value) => {
if (!imageWidget) return;
if (!imageWidget.options) imageWidget.options = {};
const values = imageWidget.options.values;
if (Array.isArray(values)) {
if (value && !values.includes(value)) {
imageWidget.options.values = [...values, value];
}
} else if (values && typeof values === "object") {
const existingValues = Object.values(values);
if (value && !existingValues.includes(value)) {
const base = basenameForDisplay(value) || value;
let label = base;
let n = 2;
while (Object.prototype.hasOwnProperty.call(values, label)) {
label = `${base} (${n++})`;
}
imageWidget.options.values = { ...values, [label]: value };
}
} else {
imageWidget.options.values = ["(none)"];
if (value && value !== "(none)") {
imageWidget.options.values.push(value);
}
}
imageWidget.value = value;
if (imageWidget.callback) imageWidget.callback(value);
const map = node._imagePickerMap || { "(none)": "(none)" };
const currentLabel = Object.keys(map).find((k) => map[k] === value);
if (imagePickerWidget) {
imagePickerWidget.value = currentLabel || "(none)";
}
node.setDirtyCanvas(true);
};
// Watch for value changes to update metadata indicator
const originalOnDrawForeground = node.onDrawForeground;
@@ -1315,33 +1515,99 @@ app.registerExtension({
// Add custom "Browse Files" button AFTER the image widget
const imageWidgetIndex = this.widgets.indexOf(imageWidget);
imagePickerWidget = this.addWidget(
"combo",
"file",
"(none)",
(label) => {
const selected = node._imagePickerMap?.[label] || "(none)";
setImageFilename(selected);
},
{ values: ["(none)"] }
);
imagePickerWidget.serialize = false;
const pickerIndex = this.widgets.indexOf(imagePickerWidget);
if (pickerIndex >= 0) {
this.widgets.splice(pickerIndex, 1);
this.widgets.splice(imageWidgetIndex + 1, 0, imagePickerWidget);
}
const browseButton = {
type: "button",
name: "\uD83D\uDCC1 Browse Files",
name: "Browse Files",
value: null,
callback: () => {
callback: async () => {
const roots = await getMediaRoots();
const currentFile = imageWidget.value === "(none)" ? null : imageWidget.value;
const sourceFolder = node._sourceFolder || 'input';
let initialPath = node.properties?._browsePath || "";
if (!initialPath) {
const sf = node.widgets?.find(w => w.name === "source_folder")?.value || "input";
initialPath = sf === "output" ? roots.output : roots.input;
}
const sf = node.widgets?.find(w => w.name === "source_folder")?.value || "input";
const currentSelection = stripAnnotation(imageWidget.value);
let selectedAbsPath = "";
if (currentSelection && currentSelection !== "(none)") {
if (isAbsolutePath(currentSelection)) {
selectedAbsPath = currentSelection;
} else {
const root = sf === "output" ? roots.output : roots.input;
if (root) {
const rootNorm = String(root).replace(/[\\/]+$/, "");
const relNorm = String(currentSelection).replace(/^[\\/]+/, "");
selectedAbsPath = `${rootNorm}/${relNorm}`;
}
}
}
if (!selectedAbsPath && node.properties?._browseSelectedAbsPath) {
selectedAbsPath = node.properties._browseSelectedAbsPath;
}
// Open file browser modal
createFileBrowserModal(currentFile, (selectedFile) => {
// Update the dropdown value
imageWidget.value = selectedFile;
// Trigger the callback to load/display the file
if (imageWidget.callback) {
imageWidget.callback(selectedFile);
await createFileBrowserModal(currentSelection, (selected, meta) => {
if (!node.properties) node.properties = {};
if (meta && meta.absPath) {
node.properties._browsePath = meta.dir || "";
node.properties._browseSelectedAbsPath = meta.absPath;
const cls = classifySelection(meta.absPath, meta.roots);
const sfW = node.widgets?.find(w => w.name === "source_folder");
if (cls.sourceFolder && sfW) {
sfW.value = cls.sourceFolder;
node._sourceFolder = cls.sourceFolder;
}
setImageFilename(cls.value);
refreshImageOptionsForBrowsePath(meta.dir, cls.value);
} else {
node.properties._browseSelectedAbsPath = "";
setImageFilename(selected);
if (node.properties?._browsePath) {
refreshImageOptionsForBrowsePath(node.properties._browsePath, selected);
}
}
// Mark node as needing update
node.setDirtyCanvas(true);
}, sourceFolder);
}, sf, {
enableNavigation: true,
navKind: "all",
allowedTypes: ["image", "video", "json"],
initialPath,
selectedAbsPath,
viewMode: node.properties?._fileBrowserViewMode || "medium",
onViewModeChange: (mode) => {
if (!node.properties) node.properties = {};
node.properties._fileBrowserViewMode = mode;
},
});
},
serialize: false // Don't save button state
};
// Insert button right after the image widget
this.widgets.splice(imageWidgetIndex + 1, 0, browseButton);
this.widgets.splice(imageWidgetIndex + 2, 0, browseButton);
Object.defineProperty(browseButton, "node", { value: node });
// Track if current file is a video for UI behavior
@@ -1423,7 +1689,7 @@ app.registerExtension({
const isWorkflowExtractor = this.type === "RecipeExtractor";
const VALID_INPUTS = isWorkflowExtractor
? new Set([])
: new Set(["lora_stack_a", "lora_stack_b"]);
: new Set(["lora_stack_a", "lora_stack_b", "video"]);
if (this.inputs) {
for (let i = this.inputs.length - 1; i >= 0; i--) {
if (!VALID_INPUTS.has(this.inputs[i].name)) {
@@ -1433,28 +1699,39 @@ app.registerExtension({
}
const VALID_OUTPUTS = isWorkflowExtractor
? [
{ name: "recipe_data", type: "RECIPE_DATA" },
{ name: "image", type: "IMAGE" },
{ name: "manager_data", type: "MANAGER_DATA" },
]
: [
{ name: "positive_prompt", type: "STRING" },
{ name: "negative_prompt", type: "STRING" },
{ name: "lora_stack_a", type: "LORA_STACK" },
{ name: "lora_stack_b", type: "LORA_STACK" },
{ name: "recipe_data", type: "RECIPE_DATA" },
{ name: "image", type: "IMAGE" },
];
if (this.outputs) {
const namesMatch = this.outputs.length === VALID_OUTPUTS.length &&
VALID_OUTPUTS.every((v, i) => this.outputs[i]?.name === v.name && this.outputs[i]?.type === v.type);
if (!namesMatch) {
// Preserve existing links before resetting
const savedLinks = this.outputs.map(o => o.links ? [...o.links] : null);
// Preserve existing links by output name (recipe_data was renamed manager_data)
const legacyNames = { recipe_data: "manager_data" };
const savedByIndex = this.outputs.map(o => o.links ? [...o.links] : null);
const savedLinks = new Map(this.outputs.map((o, i) => [legacyNames[o.name] || o.name, savedByIndex[i]]));
this.outputs.length = 0;
for (let i = 0; i < VALID_OUTPUTS.length; i++) {
this.addOutput(VALID_OUTPUTS[i].name, VALID_OUTPUTS[i].type);
// Restore links for slots that existed at the same index
if (savedLinks[i]) this.outputs[i].links = savedLinks[i];
const links = savedLinks.has(VALID_OUTPUTS[i].name) || isWorkflowExtractor
? savedLinks.get(VALID_OUTPUTS[i].name)
: savedByIndex[i];
if (!links) continue;
this.outputs[i].links = links;
for (const linkId of links) {
const link = this.graph?.links?.[linkId];
if (link) {
link.origin_slot = i;
link.type = VALID_OUTPUTS[i].type;
}
}
}
}
}
@@ -1465,21 +1742,13 @@ app.registerExtension({
node._sourceFolder = sfWidget.value || 'input';
}
// Refresh file list if source folder is not the default (input)
// INPUT_TYPES only lists input files, so output files need to be fetched
if (node._sourceFolder === 'output' && imageWidget) {
api.fetchApi(`/prompt-extractor/list-files?source=output`).then(resp => {
if (resp.ok) return resp.json();
}).then(data => {
if (data && data.files) {
const savedValue = imageWidget.value;
imageWidget.options.values = ["(none)", ...data.files];
// Restore saved value if it exists in the new list
if (savedValue && data.files.includes(savedValue)) {
imageWidget.value = savedValue;
}
}
}).catch(() => {});
// Refresh source list and keep current value, including absolute paths.
if (imageWidget) {
if (node.properties?._browsePath) {
refreshImageOptionsForBrowsePath(node.properties._browsePath, imageWidget?.value);
} else {
refreshImageOptionsForSource(node._sourceFolder, { preferredValue: imageWidget?.value });
}
}
// Restore frame_position if it exists in the workflow data
@@ -1766,10 +2035,70 @@ app.registerExtension({
return true; // Consume the event
}
}
return onMouseDown ? onMouseDown.apply(this, arguments) : undefined;
};
// ── Ghost the file-picker UI when a VIDEO input is connected ──
// When the optional "video" input is linked, extraction reads the
// connected video directly, so the image/source/browse widgets are
// irrelevant. We hide them (LiteGraph "ghosting") while connected.
const videoInputIndex = () => (node.inputs || []).findIndex(i => i?.name === "video");
const isVideoConnected = () => {
const idx = videoInputIndex();
return idx >= 0 && node.inputs[idx]?.link != null;
};
const updateVideoConnectedUI = () => {
const connected = isVideoConnected();
const targets = [imageWidget, imagePickerWidget, sourceFolderWidget];
// Also hide the browse button (added after imagePickerWidget).
const browseBtn = node.widgets?.find(w => w?.type === "button" && w?.name && String(w.name).toLowerCase().includes("browse"));
if (browseBtn) targets.push(browseBtn);
for (const w of targets) {
if (!w) continue;
if (connected) {
if (!w._peHiddenForVideo) {
w._peHiddenForVideo = true;
w._pePrevHidden = w.hidden;
w._pePrevComputeSize = w.computeSize;
}
w.hidden = true;
w.computeSize = () => [0, -4];
if (w.inputEl) w.inputEl.style.display = "none";
} else if (w._peHiddenForVideo) {
w._peHiddenForVideo = false;
// Restore: source_folder stays hidden (it was always hidden),
// others return to their prior state.
w.hidden = w === sourceFolderWidget ? true : (w._pePrevHidden ?? false);
if (w._pePrevComputeSize) { w.computeSize = w._pePrevComputeSize; delete w._pePrevComputeSize; }
if (w.inputEl && !w.hidden) w.inputEl.style.display = "";
}
}
node.setDirtyCanvas(true, true);
node.setSize(node.computeSize());
};
const origOnConnectionsChange = node.onConnectionsChange;
node.onConnectionsChange = function (type, index, connected) {
const r = origOnConnectionsChange?.apply(this, arguments);
updateVideoConnectedUI();
return r;
};
const origOnConnectInput = node.onConnectInput;
node.onConnectInput = function (idx, type) {
const r = origOnConnectInput?.apply(this, arguments);
updateVideoConnectedUI();
return r;
};
const origOnConfigureVideo = node.onConfigure;
node.onConfigure = function (info) {
const r = origOnConfigureVideo?.apply(this, arguments);
updateVideoConnectedUI();
return r;
};
// Initial state.
setTimeout(updateVideoConnectedUI, 100);
return result;
};
}
@@ -1789,22 +2118,7 @@ async function extractAndUpdateMetadata(node, filename) {
try {
const ext = filename.split('.').pop().toLowerCase();
const viewType = node._sourceFolder || 'input';
// Split path into filename and subfolder for proper URL handling
let actualFilename = filename;
let subfolder = "";
if (filename.includes('/')) {
const lastSlash = filename.lastIndexOf('/');
subfolder = filename.substring(0, lastSlash);
actualFilename = filename.substring(lastSlash + 1);
}
// Build URL with subfolder parameter if present
let fileUrl = `/view?filename=${encodeURIComponent(actualFilename)}&type=${viewType}`;
if (subfolder) {
fileUrl += `&subfolder=${encodeURIComponent(subfolder)}`;
}
const fileUrl = buildPreviewUrl(filename, viewType);
// Fetch the file to extract metadata
const response = await fetch(fileUrl);
@@ -1834,7 +2148,7 @@ async function extractAndUpdateMetadata(node, filename) {
// If JavaScript parser failed, ask Python to try with ffprobe
if (metadata === null) {
console.log(`[PromptExtractor] JavaScript parser returned null, trying Python ffprobe for: ${filename}`);
metadata = await extractVideoMetadataWithPython(filename, viewType);
metadata = await extractVideoMetadataWithPython(filename, resolveMediaSource(filename, viewType));
if (metadata) {
console.log(`[PromptExtractor] Successfully got metadata from Python for: ${filename}`);
@@ -1868,7 +2182,7 @@ async function extractAndUpdateMetadata(node, filename) {
// pull it without executing PromptExtractor (live-menu pattern).
if (node.hasWorkflow) {
try {
const sourceFolder = node._sourceFolder || 'input';
const sourceFolder = resolveMediaSource(filename, node._sourceFolder || 'input');
const previewResp = await fetch(
`/prompt-extractor/extract-preview?filename=${encodeURIComponent(filename)}&source=${encodeURIComponent(sourceFolder)}`
);
@@ -1934,20 +2248,7 @@ async function loadAndDisplayImage(node, filename) {
async function loadImageFile(node, filename) {
try {
const viewType = node._sourceFolder || 'input';
// Fetch the image file to extract metadata
// Handle subfolder paths
let actualFilename = filename;
let subfolder = "";
if (filename.includes('/')) {
const lastSlash = filename.lastIndexOf('/');
subfolder = filename.substring(0, lastSlash);
actualFilename = filename.substring(lastSlash + 1);
}
let fileUrl = `/view?filename=${encodeURIComponent(actualFilename)}&type=${viewType}`;
if (subfolder) {
fileUrl += `&subfolder=${encodeURIComponent(subfolder)}`;
}
const fileUrl = buildPreviewUrl(filename, viewType);
const imageBlob = await fetch(fileUrl).then(res => res.blob());
@@ -2009,19 +2310,7 @@ async function loadImageFile(node, filename) {
async function loadJSONFile(node, filename) {
try {
const viewType = node._sourceFolder || 'input';
// Fetch the JSON file
let actualFilename = filename;
let subfolder = "";
if (filename.includes('/')) {
const lastSlash = filename.lastIndexOf('/');
subfolder = filename.substring(0, lastSlash);
actualFilename = filename.substring(lastSlash + 1);
}
let fileUrl = `/view?filename=${encodeURIComponent(actualFilename)}&type=${viewType}`;
if (subfolder) {
fileUrl += `&subfolder=${encodeURIComponent(subfolder)}`;
}
const fileUrl = buildPreviewUrl(filename, viewType);
const jsonBlob = await fetch(fileUrl).then(res => res.blob());
@@ -2052,7 +2341,8 @@ async function loadJSONFile(node, filename) {
* Load a video frame from the server-side PyAV endpoint (for H265/yuv444 videos).
*/
function loadVideoFrameFromServer(node, filename, framePosition, viewType) {
const frameUrl = `/prompt-extractor/video-frame?filename=${encodeURIComponent(filename)}&source=${viewType}&position=${framePosition}`;
const frameSource = resolveMediaSource(filename, viewType);
const frameUrl = `/prompt-extractor/video-frame?filename=${encodeURIComponent(filename)}&source=${frameSource}&position=${framePosition}`;
const img = new Image();
img.onload = () => {
node.imgs = [img];
@@ -2094,21 +2384,7 @@ async function loadVideoFrame(node, filename) {
const framePosition = framePositionWidget ? framePositionWidget.value : 0.0;
const viewType = node._sourceFolder || 'input';
// Split path into filename and subfolder for ComfyUI's /view endpoint
let actualFilename = filename;
let subfolder = "";
if (filename.includes('/')) {
const lastSlash = filename.lastIndexOf('/');
subfolder = filename.substring(0, lastSlash);
actualFilename = filename.substring(lastSlash + 1);
}
// Build URL with subfolder parameter if present
let videoUrl = `/view?filename=${encodeURIComponent(actualFilename)}&type=${viewType}`;
if (subfolder) {
videoUrl += `&subfolder=${encodeURIComponent(subfolder)}`;
}
const videoUrl = buildPreviewUrl(filename, viewType);
// If this video is already known to be non-browser-decodable, go straight to server
if (_nonBrowserDecodableVideos.has(filename)) {
+414
View File
@@ -0,0 +1,414 @@
import { app } from "../../scripts/app.js";
import { api } from "../../scripts/api.js";
import { showThumbnailBrowser } from "./prompt_browser.js";
import { SYSTEM_PROMPTS_ENDPOINT_PREFIX, getCategoryPromptEntries } from "./prompt_store_adapters.js";
import { setPromptTextLocked } from "./prompt_text_lock.js";
function setupSystemPromptSelector(node) {
const widget = node.widgets?.find(w => w.name === "system_prompt");
if (!widget || widget.type === "system_prompt_selector") return;
const selectPrompt = async (value) => {
widget.value = value;
await widget.callback?.call(widget, value, app.canvas, node);
updateDisplay();
node.setDirtyCanvas(true, true);
};
const loadSystemPrompts = async () => {
const response = await api.fetchApi(`${SYSTEM_PROMPTS_ENDPOINT_PREFIX}/get-prompts`, { cache: "no-store" });
if (!response.ok) throw new Error(`Could not load system prompts (${response.status})`);
const prompts = await response.json();
node.prompts = prompts;
// The combo list comes from page load; keep it current with prompts added or moved since.
const choices = getChoices(prompts);
if (choices.length && widget.options && typeof widget.options.values !== "function") widget.options.values = choices;
return prompts;
};
const getChoices = (prompts) => Object.entries(prompts)
.filter(([category, entries]) => !category.startsWith("_") && entries && typeof entries === "object")
.flatMap(([category, entries]) => Object.entries(getCategoryPromptEntries(entries, "generator"))
.filter(([name, entry]) => {
const text = entry && typeof entry === "object" ? entry.prompt : entry;
return !name.startsWith("_") && String(text ?? "").trim();
})
.map(([name]) => `${category} / ${name}`))
.sort((left, right) => left.toLowerCase().localeCompare(right.toLowerCase()));
let busy = false;
const activate = async (direction) => {
if (busy) return;
busy = true;
try {
if (direction) {
const choices = getChoices(await loadSystemPrompts());
if (!choices.length) return;
const index = choices.indexOf(widget.value);
const nextIndex = index < 0
? (direction > 0 ? 0 : choices.length - 1)
: (index + direction + choices.length) % choices.length;
await selectPrompt(choices[nextIndex]);
} else {
const value = String(widget.value ?? "");
const separator = value.indexOf(" / ");
const category = separator < 0 ? "" : value.slice(0, separator);
const name = separator < 0 ? value : value.slice(separator + 3);
const selection = await showThumbnailBrowser(node, category, name, {
title: "Select System Prompt",
endpointPrefix: SYSTEM_PROMPTS_ENDPOINT_PREFIX,
loadPromptsFn: loadSystemPrompts,
preferenceScope: "system",
promptOnly: true,
allowMultiSelect: false,
});
if (selection?.prompt) {
await selectPrompt(`${selection.category} / ${selection.prompt}`);
}
}
} catch (error) {
console.error("[PromptGenerator] System prompt selection failed:", error);
app.extensionManager.toast.add({
severity: "error",
summary: "System prompts unavailable",
detail: String(error.message || error),
});
} finally {
busy = false;
}
};
const container = document.createElement("div");
// Mirrors Prompt Manager's selector; the dark backing is what keeps the translucent name button dark.
container.style.cssText = `
display: flex;
align-items: center;
gap: 0;
background: #1a1a1a;
border-radius: 6px;
width: 100%;
min-width: 0;
height: 26px;
box-sizing: border-box;
`;
for (const eventName of ["pointerdown", "mousedown", "dblclick"]) {
container.addEventListener(eventName, event => event.stopPropagation());
}
const makeButton = (label, title, direction) => {
const button = document.createElement("button");
button.type = "button";
button.textContent = label;
button.title = title;
button.setAttribute("aria-label", title);
button.style.cssText = `
background: #2a2a2a;
border: none;
color: #888;
padding: 0 10px;
height: 100%;
cursor: pointer;
font-size: 12px;
transition: all 0.15s ease;
`;
button.addEventListener("mouseover", () => {
button.style.background = direction ? "#3a3a3a" : "rgba(56, 130, 246, 0.32)";
if (direction) button.style.color = "#fff";
});
button.addEventListener("mouseout", () => {
button.style.background = direction ? "#2a2a2a" : "rgba(56, 130, 246, 0.22)";
if (direction) button.style.color = "#888";
});
button.addEventListener("click", event => {
event.stopPropagation();
void activate(direction);
});
container.appendChild(button);
return button;
};
makeButton("\u25c0", "Previous system prompt", -1);
const nameButton = makeButton("", "Browse System Prompts", 0);
nameButton.style.cssText = `
flex: 1;
min-width: 0;
text-align: center;
color: #dbeafe;
font-family: inherit;
font-size: 15px;
padding: 0 10px;
cursor: pointer;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
background: rgba(56, 130, 246, 0.22);
border: 1px solid rgba(56, 130, 246, 0.85);
border-radius: 4px;
height: 100%;
transition: background 0.15s ease;
box-sizing: border-box;
`;
makeButton("\u25b6", "Next system prompt", 1);
const updateDisplay = () => {
nameButton.textContent = String(widget.value ?? "").replace(" / ", " : ");
nameButton.title = `Browse System Prompts: ${widget.value ?? ""}`;
};
const index = node.widgets.indexOf(widget);
const selector = node.addDOMWidget("system_prompt", "system_prompt_selector", container, {
getMinHeight: () => 26,
getMaxHeight: () => 26,
getValue: () => widget.value,
setValue: value => {
widget.value = value;
updateDisplay();
},
});
selector.computeSize = width => [width, 28];
// Nodes 2.0 stretches DOM widgets that expose computeLayoutSize; keep this row fixed-height.
selector.computeLayoutSize = undefined;
selector.serializeValue = () => widget.value;
node.widgets.splice(node.widgets.indexOf(selector), 1);
node.widgets.splice(index, 1, selector);
const matchChoice = (value, choices, allowFallback) => {
const normalized = String(value ?? "").trim().toLowerCase();
const entries = choices.map(choice => {
const separator = choice.indexOf(" / ");
return { value: choice, category: choice.slice(0, separator), name: choice.slice(separator + 3) };
});
const exact = entries.find(entry => entry.value.toLowerCase() === normalized);
const legacy = entries.find(entry => `${entry.name} (${entry.category})`.toLowerCase() === normalized);
// A prompt moved to another category keeps its name.
const previousName = normalized.includes(" / ") ? normalized.slice(normalized.indexOf(" / ") + 3) : normalized;
const names = entries.filter(entry => entry.name.toLowerCase() === previousName);
const match = exact || legacy || (names.length === 1 ? names[0] : null);
if (match || !allowFallback) return match;
return entries.find(entry => entry.value.toLowerCase() === "image / enhance prompt") || entries[0] || null;
};
const applyMatch = (match) => {
if (!match || widget.value === match.value) return;
const previous = widget.value;
selector.value = match.value;
console.log(`[PromptGenerator] Migrated system prompt '${previous}' to '${match.value}'.`);
node.setDirtyCanvas(true, true);
};
// The combo's choices date from page load, so canonical values are checked against the live list.
const reconcileSelection = async () => {
let choices;
try {
choices = getChoices(await loadSystemPrompts());
} catch (error) {
console.warn("[PromptGenerator] Could not refresh system prompts; keeping the saved selection.", error);
return;
}
if (choices.length) applyMatch(matchChoice(widget.value, choices, true));
};
const onConfigure = node.onConfigure;
node.onConfigure = function() {
const result = onConfigure?.apply(this, arguments);
// Legacy labels such as "Enhance Prompt (Image)" migrate at once so an immediate queue never sends them.
if (!String(widget.value ?? "").includes(" / ")) {
const choices = typeof widget.options?.values === "function" ? widget.options.values() : widget.options?.values;
if (Array.isArray(choices) && choices.length) applyMatch(matchChoice(widget.value, choices, false));
}
void reconcileSelection();
return result;
};
updateDisplay();
}
function migrateLegacyPromptGenOptionsWidgets(node) {
if (!node?.widgets || node.widgets.length === 0) {
return false;
}
const byName = (name) => node.widgets.find(w => w.name === name);
const modeWidget = byName("system_prompt_mode");
const systemPromptWidget = byName("system_prompt");
const useDefaultWidget = byName("use_model_default_sampling");
const temperatureWidget = byName("temperature");
const topKWidget = byName("top_k");
const topPWidget = byName("top_p");
const minPWidget = byName("min_p");
const repeatPenaltyWidget = byName("repeat_penalty");
const contextSizeWidget = byName("context_size");
const showConsoleWidget = byName("show_everything_in_console");
if (!modeWidget || !systemPromptWidget || !useDefaultWidget || !temperatureWidget ||
!topKWidget || !topPWidget || !minPWidget || !repeatPenaltyWidget ||
!contextSizeWidget || !showConsoleWidget) {
return false;
}
const modeIsValid = modeWidget.value === "replace" || modeWidget.value === "append";
const looksLegacyShape = typeof systemPromptWidget.value === "boolean" && typeof useDefaultWidget.value === "number";
if (modeIsValid && !looksLegacyShape) {
return false;
}
const oldSystemPrompt = modeWidget.value;
const oldUseDefaultSampling = systemPromptWidget.value;
const oldTemperature = useDefaultWidget.value;
const oldTopK = temperatureWidget.value;
const oldTopP = topPWidget.value;
const oldMinP = topPWidget.value;
const oldRepeatPenalty = repeatPenaltyWidget.value;
const oldContextSize = contextSizeWidget.value;
const oldShowInConsole = showConsoleWidget.value;
modeWidget.value = "replace";
systemPromptWidget.value = typeof oldSystemPrompt === "string" ? oldSystemPrompt : "";
useDefaultWidget.value = Boolean(oldUseDefaultSampling);
temperatureWidget.value = Number(oldTemperature);
topKWidget.value = Number.isFinite(Number(oldTopK)) ? Math.round(Number(oldTopK)) : oldTopK;
topPWidget.value = Number(oldTopP);
minPWidget.value = Number(oldMinP);
repeatPenaltyWidget.value = Number(oldRepeatPenalty);
contextSizeWidget.value = Number.isFinite(Number(oldContextSize)) ? Math.round(Number(oldContextSize)) : oldContextSize;
showConsoleWidget.value = Boolean(oldShowInConsole);
node.serialize_widgets = true;
app.graph.setDirtyCanvas(true, true);
console.log("[PromptManager] Migrated legacy PromptGenOptions widget order for workflow compatibility.");
return true;
}
app.registerExtension({
name: "comfyui-prompt-manager.generator",
async beforeRegisterNodeDef(nodeType, nodeData, app) {
// Make the Options node taller/wider by default so the system_prompt area is roomier
if (nodeData.name === "PromptGenOptions") {
const onNodeCreated = nodeType.prototype.onNodeCreated;
nodeType.prototype.onNodeCreated = function () {
const result = onNodeCreated?.apply(this, arguments);
migrateLegacyPromptGenOptionsWidgets(this);
// Model selection now lives on the Prompt Generator base node. The
// Options node's model widget is kept (hidden) purely so old workflows
// still load and pass their value through as a fallback.
const modelWidget = this.widgets?.find(w => w.name === "model");
if (modelWidget) {
modelWidget.hidden = true;
modelWidget.computeSize = () => [0, -4];
if (modelWidget.inputEl) modelWidget.inputEl.style.display = "none";
}
// Set a default size (width x height)
try {
this.setSize([400, 420]);
} catch (e) {
// ignore if method unavailable
}
return result;
};
const onConfigureOpt = nodeType.prototype.onConfigure;
nodeType.prototype.onConfigure = function(info) {
const result = onConfigureOpt?.apply(this, arguments);
migrateLegacyPromptGenOptionsWidgets(this);
// Re-hide the legacy model widget on restore (tab switch / reload).
const modelWidget = this.widgets?.find(w => w.name === "model");
if (modelWidget) {
modelWidget.hidden = true;
modelWidget.computeSize = () => [0, -4];
if (modelWidget.inputEl) modelWidget.inputEl.style.display = "none";
}
return result;
};
// Enforce sensible minimums when the user resizes the options node
const onResizeOpt = nodeType.prototype.onResize;
nodeType.prototype.onResize = function(size) {
size[0] = Math.max(300, size[0]);
return onResizeOpt ? onResizeOpt.apply(this, arguments) : size;
};
}
// Enforce minimum size for PromptGenerator node (no default size)
if (nodeData.name === "PromptGenerator") {
const onNodeCreated = nodeType.prototype.onNodeCreated;
nodeType.prototype.onNodeCreated = function () {
const result = onNodeCreated?.apply(this, arguments);
setupSystemPromptSelector(this);
// Set a default size (width x height) - taller to fit the UI comfortably
try {
this.setSize([400, 600]);
} catch (e) {
// ignore if method unavailable
}
// Darken + make the prompt widget read-only while a `prompt_input`
// link is connected (mirrors PromptManager's use_prompt_input UI).
const node = this;
const promptWidget = node.widgets?.find(w => w.name === "prompt");
const promptInputSlot = () => node.inputs?.find(i => i && i.name === "prompt_input");
const isPromptInputConnected = () => {
const inp = promptInputSlot();
return !!(inp && inp.link != null);
};
const applyPromptInputState = () => {
setPromptTextLocked(promptWidget, isPromptInputConnected());
};
// Python echoes back the value it actually received on prompt_input
// (only when that input was connected) in the "executed" event.
// Display it here; when the key is absent, never touch the widget.
const prevOnConnectionsChange = node.onConnectionsChange;
node.onConnectionsChange = function () {
const r = prevOnConnectionsChange?.apply(this, arguments);
applyPromptInputState();
return r;
};
const prevOnConfigure = node.onConfigure;
node.onConfigure = function () {
const r = prevOnConfigure?.apply(this, arguments);
applyPromptInputState();
return r;
};
const prevOnExecuted = node.onExecuted;
node.onExecuted = function (output) {
const r = prevOnExecuted?.apply(this, arguments);
applyPromptInputState();
const echoed = output && output.ui ? output.ui.prompt : null;
if (Array.isArray(echoed) && typeof echoed[0] === "string" && echoed[0].length > 0) {
promptWidget.value = echoed[0];
if (promptWidget.inputEl) {
promptWidget.inputEl.value = echoed[0];
}
node.setDirtyCanvas(true, true);
}
return r;
};
// Listen for incoming prompt_input text updates from the backend.
// This fires at the very start of execution, before the LLM call.
api.addEventListener("prompt-generator-update-text", (event) => {
if (String(event.detail.node_id) === String(node.id)) {
const incoming = event.detail.prompt || "";
if (event.detail.has_prompt_input) {
if (promptWidget) {
promptWidget.value = incoming;
if (promptWidget.inputEl) {
promptWidget.inputEl.value = incoming;
}
setPromptTextLocked(promptWidget, true);
}
} else {
setPromptTextLocked(promptWidget, false);
}
node.serialize_widgets = true;
app.graph.setDirtyCanvas(true, true);
}
});
// Initial state.
applyPromptInputState();
return result;
};
const onResizeModel = nodeType.prototype.onResize;
nodeType.prototype.onResize = function(size) {
size[0] = Math.max(300, size[0]);
return onResizeModel ? onResizeModel.apply(this, arguments) : size;
};
}
}
});
console.log("[PromptManager] PromptGenerator extension loaded");
File diff suppressed because it is too large Load Diff
+637
View File
@@ -0,0 +1,637 @@
import { app } from "../../scripts/app.js";
import { api } from "../../scripts/api.js";
import { PM_UI_PALETTE as UI } from "./ui_palette.js";
import { showInfo, showConfirm } from "./prompt_manager_advanced.js";
import { showThumbnailBrowser, getPromptNamesForCategory } from "./prompt_browser.js";
import {
exportComposerJsonLibrary,
mergeComposerJsonLibrary,
openComposerJsonLibrary,
showComposerImportModeDialog,
triggerBrowserDownload,
} from "./prompt_composer.js";
import { loadComposerPrompts } from "./prompt_composer_common.js";
import {
COMPOSER_ENDPOINT_PREFIX,
PROMPT_ADVANCED_ENDPOINT_PREFIX,
PROMPT_ENDPOINT_PREFIX,
SYSTEM_PROMPTS_ENDPOINT_PREFIX,
getCategoryPromptEntries,
isHiddenPromptEntryKey,
} from "./prompt_store_adapters.js";
const HUB_TITLE = "Prompt Library Hub";
const STYLE_ID = "pm-library-hub-style";
const KIND_STORAGE_KEY = "pm-library-hub-kind";
// Saved prompt kinds share prompt_manager_data.json and are told apart by the browser's Type filter.
const PROMPT_KINDS = [
{ id: "prompt", label: "Prompt Manager", badge: "P", color: "56, 130, 246", hint: "Saved from Prompt Manager or Library Manager." },
{ id: "compose", label: "Prompt Composer", badge: "C", color: "47, 146, 72", hint: "Prompt Composer setups saved with Library Manager." },
{ id: "layout", label: "Prompt Layout", badge: "L", color: "124, 92, 220", hint: "Prompt Layout Builder layouts saved with Library Manager." },
{ id: "recipe", label: "Prompt Recipe", badge: "R", color: "235, 140, 35", hint: "Recipes saved with Library Manager." },
];
const SECTIONS = [
{ id: "prompts", title: "Saved Prompts", store: "manager", kinds: PROMPT_KINDS, unit: "entr" },
{ id: "snippets", title: "Saved Snippets", browseTitle: "Saved Composer Snippets", store: "composer", hint: "Prompt snippets used by Prompt Composer.", unit: "snippet" },
{ id: "system", title: "Saved System Prompts", store: "generator", hint: "System prompts used by Prompt Generator.", unit: "prompt" },
];
const plural = (count, unit) => `${count} ${unit === "entr" ? (count === 1 ? "entry" : "entries") : `${unit}${count === 1 ? "" : "s"}`}`;
function libraryFor(section, kind) {
if (!kind) return { id: section.id, title: section.browseTitle || section.title, store: section.store, unit: section.unit };
return { id: `${section.id}_${kind.id}`, title: `${section.title} - ${kind.label}`, store: section.store, filter: kind.id, unit: section.unit };
}
const STORE_ENDPOINTS = {
generator: SYSTEM_PROMPTS_ENDPOINT_PREFIX,
composer: COMPOSER_ENDPOINT_PREFIX,
manager: PROMPT_ADVANCED_ENDPOINT_PREFIX,
};
// Stand-in "node" objects: the shared browser and Composer helpers keep their loaded data on these.
const hosts = {
generator: { prompts: {} },
composer: { prompts: {} },
manager: { prompts: {} },
};
async function fetchStore(host, endpointPrefix) {
const response = await api.fetchApi(`${endpointPrefix}/get-prompts`, { cache: "no-store" });
if (!response.ok) throw new Error(`Could not load ${endpointPrefix} (${response.status})`);
host.prompts = await response.json();
return host.prompts;
}
const loadSystemPrompts = (host) => fetchStore(host, SYSTEM_PROMPTS_ENDPOINT_PREFIX);
const loadManagerPrompts = (host) => fetchStore(host, PROMPT_ADVANCED_ENDPOINT_PREFIX);
function categoryNames(data) {
return Object.keys(data || {})
.filter((category) => category !== "__meta__" && data[category] && typeof data[category] === "object")
.sort((a, b) => a.localeCompare(b, undefined, { sensitivity: "base" }));
}
function entryNames(library, category) {
const data = hosts[library.store].prompts;
if (library.store === "manager") {
return getPromptNamesForCategory(hosts.manager, category, { contentFilter: library.filter, endpointPrefix: PROMPT_ADVANCED_ENDPOINT_PREFIX });
}
return Object.keys(getCategoryPromptEntries(data?.[category], library.store));
}
function summarize(library) {
const data = hosts[library.store].prompts;
let entries = 0;
let categories = 0;
for (const category of categoryNames(data)) {
const count = entryNames(library, category).length;
entries += count;
if (count) categories += 1;
}
const groups = library.store === "composer" ? Object.keys(hosts.composer.composerPromptLibrary?._types_ || {}).length : 0;
return { entries, categories, groups };
}
function timestamp() {
return new Date().toISOString().slice(0, 19).replace(/[:T]/g, "-");
}
function pickJsonFile() {
return new Promise((resolve) => {
const input = document.createElement("input");
input.type = "file";
input.accept = ".json,application/json";
input.onchange = () => resolve(input.files?.[0] || null);
input.oncancel = () => resolve(null);
input.click();
});
}
async function readLibraryFile() {
const file = await pickJsonFile();
if (!file) return null;
let data;
try {
data = JSON.parse(await file.text());
} catch {
throw new Error(`"${file.name}" is not valid JSON.`);
}
if (!data || typeof data !== "object" || Array.isArray(data)) {
throw new Error(`"${file.name}" is not a prompt library (expected categories of entries).`);
}
return { file, data };
}
function makeButton(label, { primary = false, title = "" } = {}) {
const button = document.createElement("button");
button.type = "button";
button.textContent = label;
button.title = title;
button.className = primary ? "pm-hub-btn pm-hub-btn-primary" : "pm-hub-btn";
return button;
}
// Category picker modelled on Prompt Composer's "Save JSONs" dialog.
function showCategoryExportDialog(library, categories) {
return new Promise((resolve) => {
const selected = new Set(categories.map((item) => item.name));
const overlay = document.createElement("div");
overlay.className = "pm-hub-overlay";
const dialog = document.createElement("div");
dialog.className = "pm-hub-dialog";
const header = document.createElement("div");
header.className = "pm-hub-dialog-header";
const heading = document.createElement("div");
heading.className = "pm-hub-dialog-title";
heading.textContent = `Export ${library.title}`;
const hint = document.createElement("div");
hint.className = "pm-hub-muted";
hint.textContent = "Select the categories to export as one JSON file.";
header.append(heading, hint);
const body = document.createElement("div");
body.className = "pm-hub-dialog-grid";
const cards = new Map();
for (const item of categories) {
const card = document.createElement("button");
card.type = "button";
card.className = "pm-hub-pick";
const name = document.createElement("div");
name.className = "pm-hub-pick-name";
name.textContent = item.name;
const count = document.createElement("div");
count.className = "pm-hub-muted";
count.textContent = `${item.count} entr${item.count === 1 ? "y" : "ies"}`;
card.append(name, count);
card.onclick = () => {
if (selected.has(item.name)) selected.delete(item.name);
else selected.add(item.name);
sync();
};
cards.set(item.name, card);
body.appendChild(card);
}
const footer = document.createElement("div");
footer.className = "pm-hub-dialog-footer";
const info = document.createElement("div");
info.className = "pm-hub-muted";
info.style.marginRight = "auto";
const clearButton = makeButton("Clear");
const allButton = makeButton("Select All");
const cancelButton = makeButton("Cancel");
const saveButton = makeButton("Export JSON", { primary: true });
footer.append(info, clearButton, allButton, cancelButton, saveButton);
function sync() {
cards.forEach((card, name) => card.classList.toggle("active", selected.has(name)));
const total = categories.filter((item) => selected.has(item.name)).reduce((sum, item) => sum + item.count, 0);
info.textContent = `${selected.size} categor${selected.size === 1 ? "y" : "ies"} · ${total} entr${total === 1 ? "y" : "ies"}`;
saveButton.disabled = selected.size === 0;
}
const finish = (value) => {
overlay.remove();
resolve(value);
};
clearButton.onclick = () => { selected.clear(); sync(); };
allButton.onclick = () => { categories.forEach((item) => selected.add(item.name)); sync(); };
cancelButton.onclick = () => finish(null);
saveButton.onclick = () => finish(categories.map((item) => item.name).filter((name) => selected.has(name)));
overlay.onclick = (event) => { if (event.target === overlay) finish(null); };
dialog.append(header, body, footer);
overlay.appendChild(dialog);
document.body.appendChild(overlay);
sync();
});
}
async function exportLibrary(library) {
if (library.store === "composer") {
await loadComposerPrompts(hosts.composer);
await exportComposerJsonLibrary(hosts.composer);
return;
}
const data = hosts[library.store].prompts;
const categories = categoryNames(data)
.map((name) => ({ name, count: entryNames(library, name).length }))
.filter((item) => item.count > 0);
if (!categories.length) {
await showInfo("Nothing to Export", `${library.title} has no entries yet.`);
return;
}
const picked = await showCategoryExportDialog(library, categories);
if (!picked?.length) return;
const out = {};
for (const category of picked) {
const source = data[category];
const names = new Set(entryNames(library, category));
out[category] = Object.fromEntries(Object.entries(source).filter(([key]) => names.has(key) || isHiddenPromptEntryKey(key)));
}
const blob = new Blob([JSON.stringify(out, null, 2)], { type: "application/json" });
triggerBrowserDownload(blob, `${library.id}_${timestamp()}.json`);
}
function showChoiceDialog(title, choices) {
return new Promise((resolve) => {
const overlay = document.createElement("div");
overlay.className = "pm-hub-overlay";
const dialog = document.createElement("div");
dialog.className = "pm-hub-dialog pm-hub-dialog-small";
const header = document.createElement("div");
header.className = "pm-hub-dialog-header";
const heading = document.createElement("div");
heading.className = "pm-hub-dialog-title";
heading.textContent = title;
header.appendChild(heading);
const body = document.createElement("div");
body.className = "pm-hub-dialog-list";
const finish = (value) => {
overlay.remove();
resolve(value);
};
for (const choice of choices) {
const option = document.createElement("button");
option.type = "button";
option.className = "pm-hub-pick";
const name = document.createElement("div");
name.className = "pm-hub-pick-name";
name.textContent = choice.label;
const description = document.createElement("div");
description.className = "pm-hub-muted";
description.textContent = choice.description;
option.append(name, description);
option.onclick = () => finish(choice.value);
body.appendChild(option);
}
const footer = document.createElement("div");
footer.className = "pm-hub-dialog-footer";
const cancelButton = makeButton("Cancel");
cancelButton.style.marginLeft = "auto";
cancelButton.onclick = () => finish(null);
footer.appendChild(cancelButton);
overlay.onclick = (event) => { if (event.target === overlay) finish(null); };
dialog.append(header, body, footer);
overlay.appendChild(dialog);
document.body.appendChild(overlay);
});
}
async function importLibrary(library) {
if (library.store === "manager") {
await importJsonFile(library, false);
return;
}
const choices = [
{ value: "merge", label: "Merge a file", description: "Add the file's entries; you choose what happens to entries that already exist." },
{ value: "replace", label: "Replace with a file", description: `Replace all ${library.title} with the file's contents.` },
];
if (library.store === "generator") {
choices.push({ value: "defaults", label: "Restore built-in defaults", description: "Add back missing built-in system prompts without touching yours." });
}
const action = await showChoiceDialog(`Import ${library.title}`, choices);
if (!action) return;
if (action === "defaults") {
await restoreDefaultSystemPrompts();
} else if (library.store === "composer") {
await loadComposerPrompts(hosts.composer);
await (action === "replace" ? openComposerJsonLibrary : mergeComposerJsonLibrary)(hosts.composer);
} else {
await importJsonFile(library, action === "replace");
}
}
async function importJsonFile(library, replace) {
const picked = await readLibraryFile();
if (!picked) return;
if (replace) {
const confirmed = await showConfirm(
`Replace ${library.title}`,
`Replace ALL ${library.title} with "${picked.file.name}"? This cannot be undone.`,
"Replace",
UI.accent,
);
if (!confirmed) return;
}
let mode = replace ? "replace" : "skip_existing";
if (!replace) {
const current = hosts[library.store].prompts;
let duplicates = 0;
for (const category of categoryNames(picked.data)) {
const existing = getCategoryPromptEntries(current?.[category], library.store);
for (const name of Object.keys(getCategoryPromptEntries(picked.data[category], library.store))) {
if (Object.prototype.hasOwnProperty.call(existing, name)) duplicates += 1;
}
}
if (duplicates) {
mode = await showComposerImportModeDialog({ duplicatePromptCount: duplicates });
if (mode === "cancel") return;
}
}
// Prompt Manager's file is shared by all saved kinds; entries keep their kind through their data blocks.
const endpointPrefix = library.store === "manager" ? PROMPT_ENDPOINT_PREFIX : STORE_ENDPOINTS[library.store];
const response = await api.fetchApi(`${endpointPrefix}/import-prompts`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ data: picked.data, mode }),
});
const result = await response.json();
if (!response.ok || !result?.success) throw new Error(result?.error || "Import failed.");
if (replace) {
await showInfo("Replace Complete", `${library.title} replaced with "${picked.file.name}".`);
return;
}
const imported = Number(result.imported_prompts || 0);
const skipped = Number(result.skipped_prompts || 0);
const created = Number(result.created_categories || 0);
const parts = [`Imported ${imported} entr${imported === 1 ? "y" : "ies"}`];
if (created) parts.push(`created ${created} categor${created === 1 ? "y" : "ies"}`);
if (skipped) parts.push(`kept ${skipped} existing entr${skipped === 1 ? "y" : "ies"}`);
await showInfo("Import Complete", `${parts.join(", ")}.`);
}
async function restoreDefaultSystemPrompts() {
const confirmed = await showConfirm(
"Restore Default System Prompts",
"This adds any missing built-in system prompts without overwriting your custom ones. Continue?",
"Restore",
UI.accent,
);
if (!confirmed) return;
const response = await api.fetchApi(`${SYSTEM_PROMPTS_ENDPOINT_PREFIX}/reimport-default-prompts`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({}),
});
const result = await response.json();
if (!response.ok || !result?.success) throw new Error(result?.error || "Failed to restore default system prompts.");
await showInfo("Restore Complete", "Added back any missing built-in system prompts.");
}
async function browseLibrary(library) {
const title = library.title;
if (library.store === "generator") {
await showThumbnailBrowser(hosts.generator, "", "", {
title,
endpointPrefix: SYSTEM_PROMPTS_ENDPOINT_PREFIX,
loadPromptsFn: loadSystemPrompts,
promptOnly: true,
allowMultiSelect: false,
editMode: true,
});
} else if (library.store === "composer") {
await showThumbnailBrowser(hosts.composer, "", "", {
title,
endpointPrefix: COMPOSER_ENDPOINT_PREFIX,
loadPromptsFn: loadComposerPrompts,
preferenceScope: "composer",
promptOnly: true,
allowMultiSelect: false,
editMode: true,
});
} else {
await showThumbnailBrowser(hosts.manager, "", "", {
title,
loadPromptsFn: loadManagerPrompts,
contentFilter: library.filter,
hideContentFilterControl: true,
filterEmptyCategories: true,
allowMultiSelect: false,
editMode: true,
});
}
}
function ensureStyle() {
if (document.getElementById(STYLE_ID)) return;
const style = document.createElement("style");
style.id = STYLE_ID;
style.textContent = `
.pm-hub { display: flex; flex-direction: column; gap: 12px; height: 100%; overflow: auto; padding: 12px;
box-sizing: border-box; color: ${UI.textPrimary}; font: 14px/1.4 sans-serif; }
.pm-hub-header { display: flex; align-items: center; gap: 8px; }
.pm-hub-title { font-size: 16px; font-weight: 700; color: ${UI.textHeading}; margin-right: auto; }
.pm-hub-muted { color: ${UI.textMuted}; font-size: 13px; }
.pm-hub-section { border: 1px solid ${UI.panelBorder}; border-radius: 8px; background: ${UI.panel}; padding: 12px;
display: flex; flex-direction: column; gap: 10px; }
.pm-hub-section-head { display: flex; align-items: baseline; gap: 8px; }
.pm-hub-name { font-size: 15px; font-weight: 700; color: ${UI.textHeading}; }
.pm-hub-count { margin-left: auto; color: ${UI.textHint}; font-size: 13px; white-space: nowrap; }
.pm-hub-kinds { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 6px; }
.pm-hub-kind { display: flex; align-items: center; gap: 8px; padding: 6px 8px; border-radius: 6px; cursor: pointer;
border: 1px solid ${UI.inputBorder}; background: ${UI.inputBg}; color: ${UI.textPrimary}; font: inherit; font-size: 13px; text-align: left; }
.pm-hub-kind:hover { border-color: rgba(var(--pm-hub-rgb), 0.8); }
.pm-hub-kind.active { border-color: rgba(var(--pm-hub-rgb), 0.95); background: rgba(var(--pm-hub-rgb), 0.18); }
.pm-hub-kind-count { margin-left: auto; color: ${UI.textHint}; }
.pm-hub-badge { flex: 0 0 20px; height: 20px; border-radius: 5px; display: flex; align-items: center; justify-content: center;
font-weight: 700; font-size: 12px; color: #fff; background: rgba(var(--pm-hub-rgb), 0.9); }
.pm-hub-actions { display: grid; grid-template-columns: repeat(3, 1fr); gap: 6px; }
.pm-hub-btn { padding: 6px 10px; border-radius: 6px; border: 1px solid ${UI.inputBorder}; background: ${UI.buttonBg};
color: ${UI.textPrimary}; font: inherit; font-size: 13px; cursor: pointer; white-space: nowrap; }
.pm-hub-btn:hover:not(:disabled) { border-color: ${UI.accentBorder}; }
.pm-hub-btn:disabled { opacity: 0.5; cursor: not-allowed; }
.pm-hub-btn-primary { border-color: ${UI.accentBorder}; background: hsl(208 73% 57% / 0.2); color: #dbeafe; }
.pm-hub-overlay { position: fixed; inset: 0; background: rgba(0, 0, 0, 0.72); z-index: 9999; display: flex;
align-items: center; justify-content: center; }
.pm-hub-dialog { width: min(860px, calc(100vw - 48px)); max-height: min(760px, calc(100vh - 48px)); background: ${UI.panel};
border: 1px solid ${UI.panelBorder}; border-radius: 10px; box-shadow: 0 10px 32px rgba(0, 0, 0, 0.45);
color: ${UI.textPrimary}; display: flex; flex-direction: column; overflow: hidden; font: 14px/1.4 sans-serif; }
.pm-hub-dialog-small { width: min(480px, calc(100vw - 48px)); }
.pm-hub-dialog-header { padding: 16px 18px 10px; border-bottom: 1px solid ${UI.sectionBorder}; }
.pm-hub-dialog-title { font-size: 16px; font-weight: 700; margin-bottom: 6px; }
.pm-hub-dialog-grid { padding: 16px 18px; overflow: auto; display: grid; grid-template-columns: repeat(auto-fill, minmax(180px, 1fr)); gap: 12px; }
.pm-hub-dialog-list { padding: 16px 18px; overflow: auto; display: flex; flex-direction: column; gap: 10px; }
.pm-hub-dialog-footer { padding: 12px 18px 18px; border-top: 1px solid ${UI.sectionBorder}; display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
.pm-hub-pick { text-align: left; min-height: 64px; border: 1px solid ${UI.inputBorder}; border-radius: 10px; background: ${UI.cardBg};
color: ${UI.textPrimary}; padding: 12px; cursor: pointer; display: flex; flex-direction: column; gap: 6px; font: inherit; }
.pm-hub-pick:hover { border-color: ${UI.accentBorder}; }
.pm-hub-pick.active { background: hsl(208 73% 57% / 0.16); border-color: ${UI.accentBorder}; }
.pm-hub-pick-name { font-size: 15px; font-weight: 700; word-break: break-word; }
`;
document.head.appendChild(style);
}
function renderHub(container) {
ensureStyle();
container.replaceChildren();
const root = document.createElement("div");
root.className = "pm-hub";
container.appendChild(root);
const header = document.createElement("div");
header.className = "pm-hub-header";
const title = document.createElement("div");
title.className = "pm-hub-title";
title.textContent = HUB_TITLE;
const refreshButton = makeButton("Refresh", { title: "Reload all libraries" });
header.append(title, refreshButton);
const status = document.createElement("div");
status.className = "pm-hub-muted";
root.append(header);
let selectedKind = PROMPT_KINDS.find((kind) => kind.id === localStorage.getItem(KIND_STORAGE_KEY)) || PROMPT_KINDS[0];
let busy = false;
const updaters = [];
const update = () => updaters.forEach((fn) => fn());
const refresh = async () => {
status.textContent = "Loading libraries…";
const results = await Promise.allSettled([
loadManagerPrompts(hosts.manager),
loadComposerPrompts(hosts.composer),
loadSystemPrompts(hosts.generator),
]);
const failed = results.filter((result) => result.status === "rejected");
failed.forEach((result) => console.error("[PromptLibraryHub]", result.reason));
status.textContent = failed.length ? "Some libraries could not be loaded; see the console." : "";
update();
};
const run = async (task) => {
if (busy) return;
busy = true;
try {
await task();
} catch (error) {
console.error("[PromptLibraryHub]", error);
await showInfo(HUB_TITLE, error?.message || String(error));
} finally {
busy = false;
await refresh();
}
};
for (const section of SECTIONS) {
const card = document.createElement("div");
card.className = "pm-hub-section";
const head = document.createElement("div");
head.className = "pm-hub-section-head";
const name = document.createElement("div");
name.className = "pm-hub-name";
name.textContent = section.title;
const count = document.createElement("div");
count.className = "pm-hub-count";
head.append(name, count);
const hint = document.createElement("div");
hint.className = "pm-hub-muted";
card.append(head);
const current = () => libraryFor(section, section.kinds ? selectedKind : null);
if (section.kinds) {
const kinds = document.createElement("div");
kinds.className = "pm-hub-kinds";
for (const kind of section.kinds) {
const chip = document.createElement("button");
chip.type = "button";
chip.className = "pm-hub-kind";
chip.style.setProperty("--pm-hub-rgb", kind.color);
const badge = document.createElement("span");
badge.className = "pm-hub-badge";
badge.textContent = kind.badge;
const label = document.createElement("span");
label.textContent = kind.label;
const kindCount = document.createElement("span");
kindCount.className = "pm-hub-kind-count";
chip.append(badge, label, kindCount);
chip.onclick = () => {
selectedKind = kind;
localStorage.setItem(KIND_STORAGE_KEY, kind.id);
update();
};
updaters.push(() => {
chip.classList.toggle("active", kind === selectedKind);
kindCount.textContent = String(summarize(libraryFor(section, kind)).entries);
});
kinds.appendChild(chip);
}
card.appendChild(kinds);
}
card.appendChild(hint);
const actions = document.createElement("div");
actions.className = "pm-hub-actions";
const browse = makeButton("Browse & Edit", { primary: true });
browse.onclick = () => run(() => browseLibrary(current()));
const importButton = makeButton("Import");
importButton.onclick = () => run(() => importLibrary(current()));
const exportButton = makeButton("Export");
exportButton.onclick = () => run(() => exportLibrary(current()));
actions.append(browse, importButton, exportButton);
card.appendChild(actions);
updaters.push(() => {
const library = current();
const { entries, categories, groups } = summarize(library);
const parts = [plural(entries, library.unit), `${categories} categor${categories === 1 ? "y" : "ies"}`];
if (groups) parts.push(`${groups} group${groups === 1 ? "" : "s"}`);
count.textContent = parts.join(" · ");
hint.textContent = section.kinds ? selectedKind.hint : section.hint;
browse.title = `Open ${library.title} in the Prompt Browser with editing on`;
importButton.title = section.store === "manager"
? "Merge a JSON file into Saved Prompts (entries keep their own type)"
: `Merge or replace ${library.title} from a file`;
exportButton.title = section.store === "composer" ? "Export selected prompt groups as a ZIP" : "Export selected categories as JSON";
});
root.appendChild(card);
}
root.appendChild(status);
refreshButton.onclick = () => run(async () => {});
update();
refresh();
}
const SHOW_SIDEBAR_SETTING = "PromptManager.LibraryHub.ShowSidebar";
const SIDEBAR_TAB_ID = "prompt-library-hub";
let sidebarTabRegistered = false;
function syncSidebarTab(show) {
const manager = app.extensionManager;
if (show && !sidebarTabRegistered && manager?.registerSidebarTab) {
manager.registerSidebarTab({
id: SIDEBAR_TAB_ID,
icon: "pi pi-book",
title: HUB_TITLE,
tooltip: HUB_TITLE,
label: "Prompts",
type: "custom",
render: (container) => renderHub(container),
});
sidebarTabRegistered = true;
} else if (!show && sidebarTabRegistered && manager?.unregisterSidebarTab) {
manager.unregisterSidebarTab(SIDEBAR_TAB_ID);
sidebarTabRegistered = false;
}
}
app.registerExtension({
name: "PromptManager.LibraryHub",
settings: [
{
id: SHOW_SIDEBAR_SETTING,
category: ["Prompt Manager", "4. Advanced Preferences", "Show Prompts Sidebar Button"],
name: "Show the Prompts button (Prompt Library Hub) in the sidebar",
tooltip: "Adds a Prompts button to ComfyUI's left sidebar that opens the Prompt Library Hub.",
type: "boolean",
defaultValue: true,
onChange: (value) => syncSidebarTab(value !== false),
},
],
setup() {
const value = app.extensionManager?.setting?.get?.(SHOW_SIDEBAR_SETTING)
?? app.ui?.settings?.getSettingValue?.(SHOW_SIDEBAR_SETTING);
syncSidebarTab(value !== false);
},
});
+193 -130
View File
@@ -1,41 +1,136 @@
import { app } from "../../scripts/app.js";
import { ComfyWidgets } from "../../scripts/widgets.js";
import { api } from "../../scripts/api.js";
import { setPromptTextLocked } from "./prompt_text_lock.js";
let promptInputMaskPatched = false;
const AUTO_SELECT_MODEL_OPTION = "Default (auto-select)";
const preferredModelSettingOptions = [AUTO_SELECT_MODEL_OPTION];
const preferredModelBaseTooltip = "Select the preferred model for all modes (text and vision). Leave blank to auto-select.";
function normalizePreferredModelSettingValue(value) {
return value === AUTO_SELECT_MODEL_OPTION || value == null ? "" : String(value);
}
function updatePreferredModelSettingDefinition(definition, models, tooltip) {
preferredModelSettingOptions.splice(0, preferredModelSettingOptions.length, AUTO_SELECT_MODEL_OPTION, ...models);
definition.options = preferredModelSettingOptions;
definition.tooltip = tooltip || preferredModelBaseTooltip;
const registeredDefinition = app?.ui?.settings?.settingsLookup?.[definition.id];
if (registeredDefinition) {
registeredDefinition.options = preferredModelSettingOptions;
registeredDefinition.tooltip = definition.tooltip;
}
const currentValue = app?.ui?.settings?.getSettingValue?.(definition.id);
if (currentValue === "") {
app.ui.settings.setSettingValue(definition.id, AUTO_SELECT_MODEL_OPTION);
}
}
async function refreshPreferredModelOptions(definition) {
try {
const response = await api.fetchApi("/prompt-manager/available-models");
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const data = await response.json();
const models = Array.isArray(data?.models)
? data.models.filter(model => typeof model === "string" && model.trim())
: [];
const tooltipParts = [preferredModelBaseTooltip];
const status = typeof data?.status === "string" ? data.status.trim() : "";
if (status && !status.toLowerCase().startsWith("error:")) {
tooltipParts.push(status);
}
updatePreferredModelSettingDefinition(definition, models, tooltipParts.join("\n"));
} catch (error) {
console.error("[PromptManager] Error loading preferred model options:", error);
updatePreferredModelSettingDefinition(definition, [], preferredModelBaseTooltip);
}
}
function isTruthyInputFlag(value) {
return value === true || value === 1 || value === "1" || value === "true";
}
function attachPromptInputMaskShim() {
if (promptInputMaskPatched) return;
if (!app || typeof app.graphToPrompt !== "function") return;
promptInputMaskPatched = true;
const originalGraphToPrompt = app.graphToPrompt.bind(app);
app.graphToPrompt = async function (...args) {
const result = await originalGraphToPrompt(...args);
const promptData = result && typeof result === "object"
? (result.output && typeof result.output === "object"
? result.output
: (result.prompt && typeof result.prompt === "object" ? result.prompt : null))
: null;
if (!promptData) return result;
for (const nodeId of Object.keys(promptData)) {
const nodePayload = promptData[nodeId];
if (!nodePayload || typeof nodePayload !== "object") continue;
const classType = String(nodePayload.class_type || nodePayload.type || "");
if (classType !== "PromptManager") continue;
const inputs = nodePayload.inputs;
if (!inputs || typeof inputs !== "object") continue;
const useExternal = isTruthyInputFlag(inputs.use_external);
if (!useExternal && Object.prototype.hasOwnProperty.call(inputs, "llm_input")) {
delete inputs.llm_input;
}
}
return result;
};
}
const preferredModelSetting = {
id: "PromptManager.PreferredModel",
category: ["Prompt Manager", "1. Model Preferences", "Preferred Model"],
name: "Preferred Model",
tooltip: preferredModelBaseTooltip,
type: "combo",
options: preferredModelSettingOptions,
defaultValue: AUTO_SELECT_MODEL_OPTION,
onChange(value) {
fetch("/prompt-manager/save-preference", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ key: "preferred_model", value: normalizePreferredModelSettingValue(value) })
}).catch(error => {
console.error("[PromptManager] Error saving preferred model preference:", error);
});
}
};
app.registerExtension({
name: "PromptManager",
settings: [
preferredModelSetting,
{
id: "PromptManager.PreferredBaseModel",
category: ["Prompt Manager", "1. Model Preferences", "Base Model (text enhancement)"],
name: "Preferred Base Model",
tooltip: "Filename of default model for 'Enhance User Prompt' mode (leave empty to auto-select model)",
type: "text",
defaultValue: "",
id: "PromptManager.HideDownloadableModels",
category: ["Prompt Manager", "1. Model Preferences", "Hide Downloadable Models"],
name: "Hide downloadable built-in models",
tooltip: "When enabled, Prompt Generator dropdowns only show locally available models instead of also listing the built-in HuggingFace download options.",
type: "boolean",
defaultValue: false,
onChange(value) {
fetch("/prompt-manager/save-preference", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ key: "preferred_base_model", value: value })
}).catch(error => {
console.error("[PromptManager] Error saving base model preference:", error);
});
}
},
{
id: "PromptManager.PreferredVisionModel",
category: ["Prompt Manager", "1. Model Preferences", "Vision Model (image analysis)"],
name: "Preferred Vision Model",
tooltip: "Filename of default model for 'Analyze Image' modes (leave empty to auto-select model)",
type: "text",
defaultValue: "",
onChange(value) {
fetch("/prompt-manager/save-preference", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ key: "preferred_vision_model", value: value })
}).catch(error => {
console.error("[PromptManager] Error saving vision model preference:", error);
body: JSON.stringify({ key: "hide_downloadable_models", value: value })
}).then(() => refreshPreferredModelOptions(preferredModelSetting)).catch(error => {
console.error("[PromptManager] Error saving hide-downloadable-models preference:", error);
});
}
},
@@ -68,7 +163,7 @@ app.registerExtension({
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ key: "custom_llama_model_path", value: value })
}).catch(error => {
}).then(() => refreshPreferredModelOptions(preferredModelSetting)).catch(error => {
console.error("[PromptManager] Error saving Model path preference:", error);
});
}
@@ -123,22 +218,22 @@ app.registerExtension({
type: "boolean",
defaultValue: true
},
{
id: "PromptManager.DefaultViewMode",
category: ["Prompt Manager", "4. Advanced Preferences", "Prompt Browser View Mode"],
name: "Default prompt browser view mode",
tooltip: "Choose the default display mode for the prompt browser: thumbnails grid or compact list view.",
type: "combo",
options: ["thumbnails", "list"],
defaultValue: "thumbnails"
},
{
id: "PromptManager.EnableThumbnailPreview",
category: ["Prompt Manager", "4. Advanced Preferences", "Enable Thumbnail Hover Preview"],
name: "Enable thumbnail hover preview",
tooltip: "When enabled, hovering over thumbnails in the prompt browser shows a larger preview after a short delay.",
type: "boolean",
defaultValue: true
defaultValue: false
},
{
id: "PromptManager.CompactPromptBrowser",
category: ["Prompt Manager", "4. Advanced Preferences", "Compact Prompt Browser"],
name: "Use compact prompt browser",
tooltip: "When enabled, the prompt browser dialog uses the smaller legacy size. When disabled (default), it is enlarged to show more thumbnails.",
type: "boolean",
defaultValue: false
},
{
id: "PromptManager.ThumbnailCheckpoint",
@@ -148,6 +243,31 @@ app.registerExtension({
type: "text",
defaultValue: ""
},
{
id: "PromptManager.ThumbnailRenderSteps",
category: ["Prompt Manager", "4. Advanced Preferences", "Thumbnail Generation Steps"],
name: "Thumbnail generation steps (per family overrides)",
tooltip: "JSON map of model family -> step count used for thumbnail generation, e.g. {\"sdxl\": 12}. Set from the gear icon in the prompt browser (Steps row). Leave empty to use the hardcoded per-family defaults, or use the Reset button in the picker to revert a family.",
type: "text",
defaultValue: ""
},
{
id: "PromptManager.ThumbnailComposerSeed",
category: ["Prompt Manager", "4. Advanced Preferences", "Composer Thumbnail Seed"],
name: "Static seed for Prompt Composer thumbnail generation",
tooltip: "Seed used by Thumbnail Generator for Prompt Composer Manager categories. Set to 0 to use random seeds instead.",
type: "number",
defaultValue: 42,
onChange(value) {
fetch("/prompt-manager/save-preference", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ key: "thumbnail_composer_seed", value: value })
}).catch(error => {
console.error("[PromptManager] Error saving composer thumbnail seed preference:", error);
});
}
},
{
id: "PromptManager.LLMBackend",
category: ["Prompt Manager", "5. Ollama Settings", "LLM Backend"],
@@ -161,7 +281,7 @@ app.registerExtension({
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ key: "llm_backend", value: value })
}).catch(error => {
}).then(() => refreshPreferredModelOptions(preferredModelSetting)).catch(error => {
console.error("[PromptManager] Error saving LLM backend preference:", error);
});
}
@@ -205,8 +325,8 @@ app.registerExtension({
// Load settings from ComfyUI and sync to Python cache
try {
// Sync current values to Python cache first
const baseModel = app.ui.settings.getSettingValue("PromptManager.PreferredBaseModel");
const visionModel = app.ui.settings.getSettingValue("PromptManager.PreferredVisionModel");
const preferredModel = normalizePreferredModelSettingValue(app.ui.settings.getSettingValue("PromptManager.PreferredModel"));
const hideDownloadableModels = app.ui.settings.getSettingValue("PromptManager.HideDownloadableModels");
const llamaPath = app.ui.settings.getSettingValue("PromptManager.LlamaPath");
const modelPath = app.ui.settings.getSettingValue("PromptManager.ModelPath");
const port = app.ui.settings.getSettingValue("PromptManager.Port");
@@ -215,16 +335,16 @@ app.registerExtension({
const ollamaUrl = app.ui.settings.getSettingValue("PromptManager.OllamaUrl");
const ollamaKeepAlive = app.ui.settings.getSettingValue("PromptManager.OllamaKeepAlive");
console.log("[PromptManager] Syncing preferences:", { baseModel, visionModel, llamaPath, modelPath, port, CloseLlama, llmBackend, ollamaUrl, ollamaKeepAlive });
console.log("[PromptManager] Syncing preferences:", { preferredModel, hideDownloadableModels, llamaPath, modelPath, port, CloseLlama, llmBackend, ollamaUrl, ollamaKeepAlive });
await fetch("/prompt-manager/save-preference", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ key: "preferred_base_model", value: baseModel })
body: JSON.stringify({ key: "preferred_model", value: preferredModel })
});
await fetch("/prompt-manager/save-preference", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ key: "preferred_vision_model", value: visionModel })
body: JSON.stringify({ key: "hide_downloadable_models", value: hideDownloadableModels === true })
});
await fetch("/prompt-manager/save-preference", {
method: "POST",
@@ -261,12 +381,15 @@ app.registerExtension({
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ key: "ollama_keep_alive", value: ollamaKeepAlive })
});
await refreshPreferredModelOptions(preferredModelSetting);
} catch (error) {
console.error("[PromptManager] Error syncing preferences:", error);
await refreshPreferredModelOptions(preferredModelSetting);
}
},
async beforeRegisterNodeDef(nodeType, nodeData, app) {
if (nodeData.name === "PromptManager") {
attachPromptInputMaskShim();
const onNodeCreated = nodeType.prototype.onNodeCreated;
nodeType.prototype.onNodeCreated = function () {
@@ -294,15 +417,9 @@ app.registerExtension({
useExternalWidget.label = "use llm input";
}
// Make text widget scrollable even when disabled
// Make text widget scrollable even when read-only
if (promptTextWidget && promptTextWidget.inputEl) {
promptTextWidget.inputEl.style.pointerEvents = "auto";
promptTextWidget.inputEl.addEventListener("mousedown", function(e) {
if (this.disabled) {
// Allow scrolling but prevent editing
e.stopPropagation();
}
});
}
// Listen for text updates from backend (when connected inputs change or toggle changes)
@@ -313,16 +430,11 @@ app.registerExtension({
const llmInput = event.detail.llm_input || "";
if (useExternal && llmInput) {
// When using external, display the LLM input text (grayed out)
// When using external, display the LLM input text (read-only, ghosted)
promptTextWidget.value = llmInput;
promptTextWidget.disabled = true;
// Keep scrolling enabled
if (promptTextWidget.inputEl) {
promptTextWidget.inputEl.style.pointerEvents = "auto";
}
setPromptTextLocked(promptTextWidget, true);
} else {
// When using internal, enable the widget
promptTextWidget.disabled = false;
setPromptTextLocked(promptTextWidget, false);
}
this.serialize_widgets = true;
@@ -442,46 +554,6 @@ app.registerExtension({
};
}
// Make the Options node taller/wider by default so the system_prompt area is roomier
if (nodeData.name === "PromptGenOptions") {
const onNodeCreated = nodeType.prototype.onNodeCreated;
nodeType.prototype.onNodeCreated = function () {
const result = onNodeCreated?.apply(this, arguments);
// Set a default size (width x height)
try {
this.setSize([400, 420]);
} catch (e) {
// ignore if method unavailable
}
return result;
};
// Enforce sensible minimums when the user resizes the options node
const onResizeOpt = nodeType.prototype.onResize;
nodeType.prototype.onResize = function(size) {
size[0] = Math.max(300, size[0]);
return onResizeOpt ? onResizeOpt.apply(this, arguments) : size;
};
}
// Enforce minimum size for ModelGenerator node (no default size)
if (nodeData.name === "PromptGenerator") {
const onNodeCreated = nodeType.prototype.onNodeCreated;
nodeType.prototype.onNodeCreated = function () {
const result = onNodeCreated?.apply(this, arguments);
// Set a default size (width x height)
try {
this.setSize([400, 300]);
} catch (e) {
// ignore if method unavailable
}
return result;
};
const onResizeModel = nodeType.prototype.onResize;
nodeType.prototype.onResize = function(size) {
size[0] = Math.max(300, size[0]);
return onResizeModel ? onResizeModel.apply(this, arguments) : size;
};
}
}
});
@@ -755,7 +827,13 @@ function addButtonBar(node) {
{
label: "Import JSON",
action: async () => {
await importPromptsJSON(node);
await importPromptsJSON(node, "merge");
}
},
{
label: "Replace JSON",
action: async () => {
await importPromptsJSON(node, "replace");
}
}
]);
@@ -772,6 +850,8 @@ function addButtonBar(node) {
htmlWidget.computeSize = function(width) {
return [width, 36];
};
// Nodes 2.0 stretches DOM widgets that expose computeLayoutSize; keep this row fixed-height.
htmlWidget.computeLayoutSize = undefined;
node.buttonBarAttached = true;
}
@@ -927,13 +1007,8 @@ function setupUseExternalToggleHandler(node) {
const isLlmConnected = llmInputConnection && llmInputConnection.link != null;
if (value && isLlmConnected) {
// Using LLM and it's connected - disable text widget immediately
textWidget.disabled = true;
// Keep scrolling enabled but prevent editing
if (textWidget.inputEl) {
textWidget.inputEl.style.pointerEvents = "auto";
textWidget.inputEl.readOnly = true;
}
// Using LLM and it's connected - make text widget read-only (ghosted)
setPromptTextLocked(textWidget, true);
// Try to show LLM value if available
const graph = app.graph;
@@ -956,10 +1031,7 @@ function setupUseExternalToggleHandler(node) {
}
} else {
// Using internal text - enable widget but keep current text (which may be LLM output)
textWidget.disabled = false;
if (textWidget.inputEl) {
textWidget.inputEl.readOnly = false;
}
setPromptTextLocked(textWidget, false);
}
};
@@ -1003,7 +1075,7 @@ function createButton(text, callback) {
button.style.color = "#fff";
button.style.border = "1px solid #444";
button.style.borderRadius = "6px";
button.style.fontSize = "11px";
button.style.fontSize = "13px";
button.style.fontWeight = "normal";
button.style.whiteSpace = "nowrap";
button.style.overflow = "hidden";
@@ -1034,7 +1106,7 @@ function createDropdownButton(text, items) {
button.style.color = "#fff";
button.style.border = "1px solid #444";
button.style.borderRadius = "6px";
button.style.fontSize = "11px";
button.style.fontSize = "13px";
button.style.fontWeight = "normal";
button.style.whiteSpace = "nowrap";
button.style.height = "28px";
@@ -1067,7 +1139,7 @@ function createDropdownButton(text, items) {
menuItem.style.cssText = `
padding: 8px 12px;
cursor: pointer;
font-size: 11px;
font-size: 13px;
color: #fff;
white-space: nowrap;
`;
@@ -1147,12 +1219,12 @@ function showPromptWithCategory(title, message, defaultName, categories, default
dialog.innerHTML = `
<div style="margin-bottom: 15px; font-size: 16px; font-weight: bold; color: #fff;">${title}</div>
<div style="margin-bottom: 6px; color: #aaa; font-size: 12px;">Category:</div>
<select style="width: 100%; padding: 8px; margin-bottom: 12px; background: #333; border: 1px solid #555; color: #fff; border-radius: 4px; font-size: 14px;">
<div style="margin-bottom: 6px; color: #aaa; font-size: 14px;">Category:</div>
<select style="width: 100%; padding: 8px; margin-bottom: 12px; background: #333; border: 1px solid #555; color: #fff; border-radius: 4px; font-size: 16px;">
${categoryOptions}
</select>
<div style="margin-bottom: 6px; color: #aaa; font-size: 12px;">${message}</div>
<input type="text" value="${defaultName}" style="width: 100%; padding: 8px; margin-bottom: 15px; background: #333; border: 1px solid #555; color: #fff; border-radius: 4px; font-size: 14px; box-sizing: border-box;" />
<div style="margin-bottom: 6px; color: #aaa; font-size: 14px;">${message}</div>
<input type="text" value="${defaultName}" style="width: 100%; padding: 8px; margin-bottom: 15px; background: #333; border: 1px solid #555; color: #fff; border-radius: 4px; font-size: 16px; box-sizing: border-box;" />
<div style="display: flex; gap: 10px; justify-content: flex-end;">
<button class="cancel-btn" style="padding: 8px 16px; background: #555; color: #fff; border: none; border-radius: 4px; cursor: pointer;">Cancel</button>
<button class="ok-btn" style="padding: 8px 16px; background: #0a0; color: #fff; border: none; border-radius: 4px; cursor: pointer;">OK</button>
@@ -1264,7 +1336,7 @@ async function exportPromptsJSON(node) {
}
}
async function importPromptsJSON(node) {
async function importPromptsJSON(node, importMode = "merge") {
return new Promise((resolve) => {
const input = document.createElement("input");
input.type = "file";
@@ -1288,15 +1360,6 @@ async function importPromptsJSON(node) {
return;
}
// Ask user how to handle import
const importMode = await showImportOptions();
if (importMode === null) {
// User cancelled
resolve(false);
return;
}
// Send to backend
const response = await fetch("/prompt-manager/import-prompts", {
method: "POST",
@@ -1329,10 +1392,10 @@ async function importPromptsJSON(node) {
node.serialize_widgets = true;
app.graph.setDirtyCanvas(true, true);
await showInfo("Import Complete", `Successfully imported prompts!`);
await showInfo(importMode === "replace" ? "Replace Complete" : "Import Complete", importMode === "replace" ? "Successfully replaced prompts!" : "Successfully imported prompts!");
resolve(true);
} else {
await showInfo("Error", result.error || "Failed to import prompts");
await showInfo("Error", result.error || (importMode === "replace" ? "Failed to replace prompts" : "Failed to import prompts"));
resolve(false);
}
} catch (error) {
@@ -1453,7 +1516,7 @@ function showTextPrompt(title, message, defaultValue = "") {
dialog.innerHTML = `
<div style="margin-bottom: 15px; font-size: 16px; font-weight: bold; color: #fff;">${title}</div>
<div style="margin-bottom: 10px; color: #ccc;">${message}</div>
<input type="text" value="${defaultValue}" style="width: 100%; padding: 8px; margin-bottom: 15px; background: #333; border: 1px solid #555; color: #fff; border-radius: 4px; font-size: 14px;" />
<input type="text" value="${defaultValue}" style="width: 100%; padding: 8px; margin-bottom: 15px; background: #333; border: 1px solid #555; color: #fff; border-radius: 4px; font-size: 16px;" />
<div style="display: flex; gap: 10px; justify-content: flex-end;">
<button class="cancel-btn" style="padding: 8px 16px; background: #555; color: #fff; border: none; border-radius: 4px; cursor: pointer;">Cancel</button>
<button class="ok-btn" style="padding: 8px 16px; background: #0a0; color: #fff; border: none; border-radius: 4px; cursor: pointer;">OK</button>
+2973 -2944
View File
File diff suppressed because it is too large Load Diff
+119
View File
@@ -0,0 +1,119 @@
export const PROMPT_ENDPOINT_PREFIX = "/prompt-manager";
export const PROMPT_ADVANCED_ENDPOINT_PREFIX = "/prompt-manager-advanced";
export const SYSTEM_PROMPTS_ENDPOINT_PREFIX = "/prompt-generator";
export const COMPOSER_ENDPOINT_PREFIX = "/prompt-manager/compose";
export const SOURCE_COMPOSE = "Compose Data";
export const SOURCE_PROMPT = "Prompt Data";
export const SOURCE_SYSTEM_PROMPTS = "System Prompts";
export function isHiddenPromptEntryKey(name) {
const normalized = String(name || "").trim().toLowerCase();
return normalized === "__meta__"
|| normalized === "_base_prompt_"
|| normalized === "_prompt_prefix_"
|| normalized === "_category_base_prompt_"
|| normalized === "_category_prefix_"
|| normalized === "_prompt_type_"
|| normalized === "_prompts_"
|| normalized === "_category_name_"
|| normalized === "_type_file_"
|| normalized === "_type_name_"
|| normalized === "_subject_type_"
|| normalized === "_subject_kind_"
|| normalized === "_type_prefix_"
|| normalized === "_type_base_prompt_"
|| normalized === "_type_nsfw_";
}
export function getPromptStoreKindFromSource(source) {
if (source === SOURCE_COMPOSE) return "composer";
if (source === SOURCE_PROMPT) return "manager";
return "generator";
}
export function getPromptStoreKindFromEndpoint(endpointPrefix) {
if (endpointPrefix === COMPOSER_ENDPOINT_PREFIX) return "composer";
if (endpointPrefix === SYSTEM_PROMPTS_ENDPOINT_PREFIX) return "generator";
return "manager";
}
export function getEndpointPrefixForSource(source) {
if (source === SOURCE_PROMPT) return PROMPT_ENDPOINT_PREFIX;
if (source === SOURCE_SYSTEM_PROMPTS) return SYSTEM_PROMPTS_ENDPOINT_PREFIX;
return COMPOSER_ENDPOINT_PREFIX;
}
export function getCategoryPromptEntries(categoryData, storeKind = "manager") {
if (!categoryData || typeof categoryData !== "object" || Array.isArray(categoryData)) return {};
if (storeKind === "composer") {
const nested = categoryData._prompts_;
if (nested && typeof nested === "object" && !Array.isArray(nested)) {
return nested;
}
}
return Object.fromEntries(
Object.entries(categoryData).filter(([name]) => !isHiddenPromptEntryKey(name))
);
}
export function getCategoryPromptEntriesForSource(categoryData, source) {
return getCategoryPromptEntries(categoryData, getPromptStoreKindFromSource(source));
}
export function getCategoryPromptEntriesForEndpoint(categoryData, endpointPrefix) {
return getCategoryPromptEntries(categoryData, getPromptStoreKindFromEndpoint(endpointPrefix));
}
export function getCategoryPromptEntryForEndpoint(categoryData, promptName, endpointPrefix) {
return getCategoryPromptEntriesForEndpoint(categoryData, endpointPrefix)?.[promptName] || null;
}
export function buildSavePromptRequestBody(storeKind, payload) {
const body = {
category: payload?.category,
name: payload?.name,
text: payload?.text,
};
if (Object.prototype.hasOwnProperty.call(payload || {}, "old_name")) body.old_name = payload.old_name;
if (Object.prototype.hasOwnProperty.call(payload || {}, "old_category")) body.old_category = payload.old_category;
if (storeKind === "generator") {
if (Object.prototype.hasOwnProperty.call(payload || {}, "thumbnail")) body.thumbnail = payload.thumbnail;
if (Object.prototype.hasOwnProperty.call(payload || {}, "prompt_category")) body.prompt_category = payload.prompt_category;
return body;
}
if (storeKind === "composer") {
if (Object.prototype.hasOwnProperty.call(payload || {}, "thumbnail")) body.thumbnail = payload.thumbnail;
if (Object.prototype.hasOwnProperty.call(payload || {}, "prompt_category")) body.prompt_category = payload.prompt_category;
if (Object.prototype.hasOwnProperty.call(payload || {}, "lora")) body.lora = payload.lora;
if (Object.prototype.hasOwnProperty.call(payload || {}, "lora_strength")) body.lora_strength = payload.lora_strength;
if (Object.prototype.hasOwnProperty.call(payload || {}, "lora_image")) body.lora_image = payload.lora_image;
if (Object.prototype.hasOwnProperty.call(payload || {}, "lora_image_strength")) body.lora_image_strength = payload.lora_image_strength;
if (Object.prototype.hasOwnProperty.call(payload || {}, "lora_video")) body.lora_video = payload.lora_video;
if (Object.prototype.hasOwnProperty.call(payload || {}, "lora_video_strength")) body.lora_video_strength = payload.lora_video_strength;
if (Object.prototype.hasOwnProperty.call(payload || {}, "refmod")) body.refmod = payload.refmod;
if (Object.prototype.hasOwnProperty.call(payload || {}, "refmod_weight")) body.refmod_weight = payload.refmod_weight;
return body;
}
if (Object.prototype.hasOwnProperty.call(payload || {}, "thumbnail")) body.thumbnail = payload.thumbnail;
if (Object.prototype.hasOwnProperty.call(payload || {}, "workflow_data")) body.workflow_data = payload.workflow_data;
if (Object.prototype.hasOwnProperty.call(payload || {}, "negative_prompt")) body.negative_prompt = payload.negative_prompt;
if (Object.prototype.hasOwnProperty.call(payload || {}, "loras_a")) body.loras_a = payload.loras_a;
if (Object.prototype.hasOwnProperty.call(payload || {}, "loras_b")) body.loras_b = payload.loras_b;
if (Object.prototype.hasOwnProperty.call(payload || {}, "loras_c")) body.loras_c = payload.loras_c;
if (Object.prototype.hasOwnProperty.call(payload || {}, "loras_d")) body.loras_d = payload.loras_d;
if (Object.prototype.hasOwnProperty.call(payload || {}, "trigger_words")) body.trigger_words = payload.trigger_words;
return body;
}
export function buildSavePromptRequestBodyForSource(source, payload) {
return buildSavePromptRequestBody(getPromptStoreKindFromSource(source), payload);
}
export function buildSavePromptRequestBodyForEndpoint(endpointPrefix, payload) {
return buildSavePromptRequestBody(getPromptStoreKindFromEndpoint(endpointPrefix), payload);
}
+24
View File
@@ -0,0 +1,24 @@
let lockStyleInstalled = false;
function installLockStyle() {
if (lockStyleInstalled) return;
lockStyleInstalled = true;
const style = document.createElement("style");
style.textContent = '.lg-node-widgets textarea[data-pm-locked="true"] { opacity: 0.5; }';
document.head.appendChild(style);
}
// Read-only + ghosted prompt textarea: classic edits inputEl; Nodes 2.0 renders its own textarea from widget options.
export function setPromptTextLocked(widget, locked) {
if (!widget) return;
locked = !!locked;
if (widget.inputEl) {
widget.inputEl.readOnly = locked;
if (locked) widget.inputEl.style.pointerEvents = "auto";
widget.inputEl.style.opacity = locked ? "0.5" : "";
}
if (!!widget.options?.read_only === locked) return;
installLockStyle();
// Reassigning options (not mutating) is what makes the Vue widget store react.
widget.options = { ...widget.options, read_only: locked, "data-pm-locked": locked ? "true" : undefined };
}
+33 -43
View File
@@ -68,7 +68,7 @@ function forwardWheelToCanvas(element) {
const style = document.createElement("style");
style.id = "we-select-style";
style.textContent = `
.we-select option, .we-select optgroup { font-size: 14px; }
.we-select option, .we-select optgroup { font-size: 16px; }
.we-select optgroup { font-weight: bold; color: #e06060; }
`;
document.head.appendChild(style);
@@ -121,7 +121,7 @@ function makeBtn(label, onclick, extraStyle) {
const b = makeEl("button", {
padding: "5px 10px", border: `1px solid ${C.border}`, borderRadius: "6px",
background: C.bgInput, color: "#ccc", cursor: "pointer",
fontSize: "12px", fontWeight: "600", width: "100%",
fontSize: "14px", fontWeight: "600", width: "100%",
...extraStyle,
}, label);
const baseBg = extraStyle?.background || C.bgInput;
@@ -207,7 +207,7 @@ function makeSection(title, node = null, key = null, opts = {}) {
const header = makeEl("div", {
display: "flex", alignItems: "center", justifyContent: "space-between",
padding: "4px 8px",
fontSize: "11px", fontWeight: "600", color: "#aaa",
fontSize: "13px", fontWeight: "600", color: "#aaa",
userSelect: "none",
borderBottom: "1px solid rgba(255,255,255,0.1)",
cursor: "pointer",
@@ -295,16 +295,16 @@ function makeSection(title, node = null, key = null, opts = {}) {
const LABEL_W = "35%";
const INPUT_W = "55%";
const ROW_STYLE = {
display: "flex", alignItems: "center", padding: "2px 0", fontSize: "12px", gap: "2px",
display: "flex", alignItems: "center", padding: "2px 0", fontSize: "14px", gap: "2px",
};
const INPUT_STYLE = {
background: C.bgInput, color: C.text, border: `1px solid ${C.border}`,
borderRadius: "6px", padding: "3px 6px", fontSize: "12px",
borderRadius: "6px", padding: "3px 6px", fontSize: "14px",
width: INPUT_W, boxSizing: "border-box", textAlign: "right",
};
const RESET_STYLE = {
background: "none", border: "none", color: C.textMuted, cursor: "pointer",
fontSize: "12px", padding: "0 2px", lineHeight: "1", flexShrink: "0",
fontSize: "14px", padding: "0 2px", lineHeight: "1", flexShrink: "0",
visibility: "hidden", width: "14px", textAlign: "center",
};
@@ -374,7 +374,7 @@ function _canonicalInputName(name) {
const n = String(name || "").trim().toLowerCase();
if (n === "positive_prompt") return "pos_prompt";
if (n === "negative_prompt") return "neg_prompt";
if (n === "workflow_data") return "recipe_data";
if (n === "workflow_data" || n === "recipe_data") return "manager_data";
return n;
}
@@ -957,7 +957,7 @@ function makeLoraTag(lora, avail, onToggle, onStrength, onMoveUp, onMoveDown, on
const tag = makeEl("div", {
display: "inline-flex", alignItems: "center", gap: "6px",
padding: "4px 10px", borderRadius: "6px", fontSize: "12px",
padding: "4px 10px", borderRadius: "6px", fontSize: "14px",
cursor: "pointer", userSelect: "none", flexShrink: "0",
transition: "background-color 0.15s ease, color 0.15s ease, border-color 0.15s ease",
backgroundColor: bgColor, color: textColor,
@@ -966,7 +966,7 @@ function makeLoraTag(lora, avail, onToggle, onStrength, onMoveUp, onMoveDown, on
});
if (!avail) {
const warn = makeEl("span", { fontSize: "11px", marginRight: "-2px" }, "\u26A0\uFE0F");
const warn = makeEl("span", { fontSize: "13px", marginRight: "-2px" }, "\u26A0\uFE0F");
tag.appendChild(warn);
}
@@ -983,7 +983,7 @@ function makeLoraTag(lora, avail, onToggle, onStrength, onMoveUp, onMoveDown, on
sinp.className = "strength-input";
sinp.value = str.toFixed(2);
Object.assign(sinp.style, {
fontSize: "10px", fontWeight: "600", padding: "1px 4px",
fontSize: "12px", fontWeight: "600", padding: "1px 4px",
borderRadius: "999px", backgroundColor: "rgba(255,255,255,0.15)",
color: "rgba(255,255,255,0.9)", width: "38px", textAlign: "center",
border: "1px solid transparent", outline: "none", cursor: "text",
@@ -1049,14 +1049,14 @@ function makeLoraTag(lora, avail, onToggle, onStrength, onMoveUp, onMoveDown, on
});
menu.className = "wb-lora-context-menu";
const title = makeEl("div", {
padding: "8px 12px", fontSize: "12px", color: "#aaa", fontWeight: "bold",
padding: "8px 12px", fontSize: "14px", color: "#aaa", fontWeight: "bold",
borderBottom: "1px solid #444", marginBottom: "4px", whiteSpace: "nowrap",
}, name);
menu.appendChild(title);
const addMenuItem = (label, color, onClick) => {
const item = makeEl("div", {
padding: "8px 12px", cursor: "pointer", fontSize: "12px",
padding: "8px 12px", cursor: "pointer", fontSize: "14px",
color, whiteSpace: "nowrap",
}, label);
item.addEventListener("mouseenter", () => { item.style.backgroundColor = "#3a3a3a"; });
@@ -1120,7 +1120,7 @@ function createLoraStackContainer(title, onResetStrength, onToggleAll) {
});
const titleLabel = document.createElement("span");
titleLabel.textContent = title;
Object.assign(titleLabel.style, { fontSize: "12px", fontWeight: "bold", color: "#aaa" });
Object.assign(titleLabel.style, { fontSize: "14px", fontWeight: "bold", color: "#aaa" });
titleBar.appendChild(titleLabel);
const btnContainer = document.createElement("div");
Object.assign(btnContainer.style, { display: "flex", gap: "4px" });
@@ -1128,7 +1128,7 @@ function createLoraStackContainer(title, onResetStrength, onToggleAll) {
const b = document.createElement("button");
b.textContent = text;
Object.assign(b.style, {
fontSize: "10px", padding: "2px 8px",
fontSize: "12px", padding: "2px 8px",
backgroundColor: P.buttonBg || C.bgCard,
color: C.text,
border: `1px solid ${C.border}`,
@@ -1214,12 +1214,12 @@ const FAMILY_DEFAULTS = {
flux1: { steps_a: 20, cfg: 1.0, sampler: "euler", scheduler: "simple" },
flux2: { steps_a: 4, cfg: 1.0, sampler: "euler", scheduler: "simple" },
zimage: { steps_a: 9, cfg: 1.0, sampler: "euler", scheduler: "simple" },
// ltxv: { steps_a: 8, cfg: 1.0, sampler: "euler", scheduler: "simple" },
wan_image: { steps_a: 10, cfg: 1.0, sampler: "lcm", scheduler: "simple" },
wan_video_t2v: { steps_a: 3, cfg: 1.0, sampler: "lcm", scheduler: "simple",
steps_b: 3 },
wan_video_i2v: { steps_a: 3, cfg: 1.0, sampler: "lcm", scheduler: "simple",
steps_b: 3 },
anima: { steps_a: 10, cfg: 1.0, sampler: "er_sde", scheduler: "simple" },
qwen_image: { steps_a: 10, cfg: 1.0, sampler: "euler", scheduler: "simple" },
};
@@ -1850,8 +1850,6 @@ function _getLoraOriginalStrength(node, stateKey, lora) {
}
// --- LoRA display ---
requestAnimationFrame(() => reflowNode(node));
function updateLoras(node) {
const containerA = node._weLoraAContainer;
const containerB = node._weLoraBContainer;
@@ -1907,7 +1905,7 @@ function updateLoras(node) {
const noLorasMsg = () => makeEl("div", {
color: "rgba(200, 200, 200, 0.5)", fontStyle: "italic",
fontSize: "11px", padding: "8px", width: "100%", textAlign: "center",
fontSize: "13px", padding: "8px", width: "100%", textAlign: "center",
}, "No LoRAs");
if (!lorasA.length) containerA.appendChild(noLorasMsg());
@@ -1999,14 +1997,14 @@ function _showError(node, errorMsg) {
border: "1px solid rgba(220, 53, 69, 0.6)",
borderRadius: "6px",
color: "#f88",
fontSize: "12px",
fontSize: "14px",
lineHeight: "1.4",
marginBottom: "4px",
wordBreak: "break-word",
});
banner.className = "we-error-banner";
const icon = makeEl("span", { marginRight: "6px", fontSize: "13px" }, "\u26A0\uFE0F");
const icon = makeEl("span", { marginRight: "6px", fontSize: "15px" }, "\u26A0\uFE0F");
const text = makeEl("span", {}, errorMsg);
banner.append(icon, text);
@@ -2029,7 +2027,7 @@ function _showInfo(node, infoMsg) {
border: "1px solid rgba(66, 153, 225, 0.65)",
borderRadius: "6px",
color: "#b9dcff",
fontSize: "12px",
fontSize: "14px",
lineHeight: "1.4",
marginBottom: "4px",
whiteSpace: "pre-wrap",
@@ -2040,8 +2038,9 @@ function _showInfo(node, infoMsg) {
const text = makeEl("span", {}, infoMsg);
banner.append(text);
root.insertBefore(banner, root.firstChild);
}
requestAnimationFrame(() => reflowNode(node));
}
// --- Sync hidden widgets ---
function syncHidden(node) {
@@ -2833,7 +2832,7 @@ app.registerExtension({
const _normalizeRecipePortsNow = () => {
const VALID_INPUTS = new Set([
"recipe_data",
"manager_data",
"pos_prompts",
"neg_prompts",
"multi_lora_stack",
@@ -2843,6 +2842,7 @@ app.registerExtension({
if (!inp || !inp.name) continue;
inp.name = _normalizeInputNameForVariant(inp.name);
if (inp.name === "pos_prompts" || inp.name === "neg_prompts") inp.type = "STRING";
if (inp.name === "manager_data") inp.type = "MANAGER_DATA";
}
const keepIndexByName = new Map();
for (let i = 0; i < node.inputs.length; i++) {
@@ -2870,14 +2870,14 @@ app.registerExtension({
}
const hasInput = (name) => node.inputs.some((inp) => _normalizeInputNameForVariant(inp?.name || "") === name);
if (!hasInput("recipe_data")) node.addInput("recipe_data", "RECIPE_DATA");
if (!hasInput("manager_data")) node.addInput("manager_data", "MANAGER_DATA");
if (!hasInput("pos_prompts")) node.addInput("pos_prompts", "STRING");
if (!hasInput("neg_prompts")) node.addInput("neg_prompts", "STRING");
if (!hasInput("multi_lora_stack")) node.addInput("multi_lora_stack", "MULTI_LORA_STACK");
}
const VALID_OUTPUTS = [
{ name: "recipe_data", type: "RECIPE_DATA" },
{ name: "manager_data", type: "MANAGER_DATA" },
];
if (node.outputs) {
const namesMatch = node.outputs.length === VALID_OUTPUTS.length &&
@@ -3177,7 +3177,7 @@ app.registerExtension({
let fallback = null;
for (const inp of ins) {
if (!inp) continue;
if (_canonicalInputName(inp.name) !== "recipe_data") continue;
if (_canonicalInputName(inp.name) !== "manager_data") continue;
if (fallback == null) fallback = inp;
if (inp.link != null) return inp;
}
@@ -3978,7 +3978,7 @@ app.registerExtension({
width: "100%", boxSizing: "border-box",
background: C.bgInput, color: C.text,
border: `1px solid ${C.border}`, borderRadius: "4px",
fontSize: "12px", padding: "6px", resize: "none",
fontSize: "14px", padding: "6px", resize: "none",
fontFamily: "inherit", lineHeight: "1.4",
minHeight: "128px", height: "128px", maxHeight: "none", overflow: "auto",
});
@@ -4003,7 +4003,7 @@ app.registerExtension({
width: "100%", boxSizing: "border-box",
background: C.bgInput, color: C.text,
border: `1px solid ${C.border}`, borderRadius: "4px",
fontSize: "12px", padding: "6px", resize: "none",
fontSize: "14px", padding: "6px", resize: "none",
fontFamily: "inherit", lineHeight: "1.4",
minHeight: "128px", height: "128px", maxHeight: "none", overflow: "auto",
});
@@ -4149,17 +4149,10 @@ app.registerExtension({
};
// -- Only hide data widgets, keep toggle switches visible --
// IMPORTANT: override_data and lora_state must keep their original
// STRING type so ComfyUI's graphToPrompt includes them in execution.
// "converted-widget" type causes ComfyUI to skip the widget value.
const KEEP_VISIBLE = new Set([]);
const KEEP_TYPE = new Set(["override_data", "lora_state"]);
for (const w of (node.widgets || [])) {
if (w === domW || KEEP_VISIBLE.has(w.name)) continue;
w.computeSize = () => [0, -4];
if (!KEEP_TYPE.has(w.name)) {
w.type = "converted-widget";
}
w.hidden = true;
w.draw = function () {};
if (w.element) w.element.style.display = "none";
@@ -4638,7 +4631,7 @@ app.registerExtension({
}
const VALID_INPUTS = new Set([
"recipe_data",
"manager_data",
"pos_prompts",
"neg_prompts",
"multi_lora_stack",
@@ -4652,6 +4645,7 @@ app.registerExtension({
if (!inp || !inp.name) continue;
inp.name = _normalizeInputNameForVariant(inp.name);
if (inp.name === "pos_prompts" || inp.name === "neg_prompts") inp.type = "STRING";
if (inp.name === "manager_data") inp.type = "MANAGER_DATA";
}
// Deduplicate legacy duplicate inputs by name. Prefer keeping
@@ -4694,8 +4688,8 @@ app.registerExtension({
// Ensure newly introduced inputs exist on restored nodes.
// Older saved workflows can miss optional inputs added later.
const hasInput = (name) => node.inputs.some((inp) => _normalizeInputNameForVariant(inp?.name || "") === name);
if (!hasInput("recipe_data")) {
node.addInput("recipe_data", "RECIPE_DATA");
if (!hasInput("manager_data")) {
node.addInput("manager_data", "MANAGER_DATA");
}
if (!hasInput("pos_prompts")) {
node.addInput("pos_prompts", "STRING");
@@ -4708,7 +4702,7 @@ app.registerExtension({
}
}
const VALID_OUTPUTS = [
{ name: "recipe_data", type: "RECIPE_DATA" },
{ name: "manager_data", type: "MANAGER_DATA" },
];
if (node.outputs) {
const namesMatch = node.outputs.length === VALID_OUTPUTS.length &&
@@ -4726,13 +4720,9 @@ app.registerExtension({
// Re-hide data widgets (same logic as onNodeCreated)
const domW = node.widgets?.find(w => w.name === "we_ui");
const KEEP_VISIBLE = new Set([]);
const KEEP_TYPE = new Set(["override_data", "lora_state"]);
for (const w of (node.widgets || [])) {
if (w === domW || KEEP_VISIBLE.has(w.name)) continue;
w.computeSize = () => [0, -4];
if (!KEEP_TYPE.has(w.name)) {
w.type = "converted-widget";
}
w.hidden = true;
w.draw = function () {};
if (w.element) w.element.style.display = "none";
+1 -1
View File
@@ -200,7 +200,7 @@ function _isRerouteNode(n) {
}
function _resolveWorkflowUpstreamLink(node) {
const wfInputIdx = (node.inputs || []).findIndex((i) => i?.name === "recipe_data");
const wfInputIdx = (node.inputs || []).findIndex((i) => i?.name === "manager_data");
if (wfInputIdx < 0) return null;
let linkId = node.inputs[wfInputIdx]?.link;
if (linkId == null) return null;
+2 -2
View File
@@ -37,7 +37,7 @@ export const PM_UI_PALETTE = {
// 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)",
accentSoft: "hsl(208 73% 57% / 0.55)",
// Accent border used on selected elements
accentBorder: "hsl(208 73% 57% / 0.65)",
accentBorder: "hsl(208 73% 57% / 0.95)",
};
-116
View File
@@ -1,116 +0,0 @@
"""
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)
@@ -1,57 +1,24 @@
"""
Workflow Manager - stripped-down workflow_data editor based on PromptManagerAdvanced.
Library Manager - save and reload manager_data from Prompt Manager, Recipe nodes, Prompt Composer and Prompt Layout Builder.
Differences from PromptManagerAdvanced:
- workflow_data input/output only (no prompt/lora stack outputs)
- no use_* switches
- no trigger words pipeline
Compared to the base Prompt Manager node:
- accepts an IMAGE input to provide/save a thumbnail alongside the data
- tags saved/forwarded workflow metadata as LibraryManager
"""
import json
import base64
from io import BytesIO
import server
from ..py.thumbnail_utils import image_to_base64_thumbnail
from ..py.workflow_data_utils import ensure_v2_recipe_data, get_v2_model_block, to_json_safe_workflow_data, build_v2_recipe_data_from_prompt
from .prompt_manager_adv import PromptManagerAdvanced
try:
import numpy as np
from PIL import Image
IMAGE_SUPPORT = True
except ImportError:
IMAGE_SUPPORT = False
class LibraryManager(PromptManagerAdvanced):
"""Workflow-focused manager for manager_data payloads with explicit thumbnail input."""
def _image_to_base64_thumbnail(image_tensor, max_size=200):
if not IMAGE_SUPPORT or image_tensor is None:
return None
try:
img_array = image_tensor[0] if len(image_tensor.shape) == 4 else image_tensor
if hasattr(img_array, "cpu"):
img_array = img_array.cpu().numpy()
img_array = (img_array * 255).astype(np.uint8)
img = Image.fromarray(img_array)
width, height = img.size
min_dim = min(width, height)
if min_dim > max_size:
scale = max_size / min_dim
img = img.resize((int(width * scale), int(height * scale)), Image.LANCZOS)
buffer = BytesIO()
img.save(buffer, format="JPEG", quality=85)
base64_str = base64.b64encode(buffer.getvalue()).decode("utf-8")
return f"data:image/jpeg;base64,{base64_str}"
except Exception as e:
print(f"[RecipeManager] Thumbnail generation failed: {e}")
return None
class WorkflowManager(PromptManagerAdvanced):
"""Workflow-focused manager that edits and forwards RECIPE_DATA."""
SOURCE_NAME = "LibraryManager"
@classmethod
def INPUT_TYPES(cls):
@@ -67,24 +34,21 @@ class WorkflowManager(PromptManagerAdvanced):
first_category = categories[0] if categories else "Default"
# Keep new node instances empty until the user explicitly selects a prompt.
first_prompt = ""
first_prompt_text = ""
return {
"required": {
"category": (categories, {"default": first_category}),
"name": (all_prompts_list, {"default": first_prompt}),
"name": (all_prompts_list, {"default": ""}),
"text": ("STRING", {
"multiline": True,
"default": first_prompt_text,
"default": "",
"placeholder": "Enter prompt text",
"dynamicPrompts": False,
"tooltip": "Edit prompt text directly",
}),
},
"optional": {
"recipe_data": ("RECIPE_DATA", {"forceInput": True, "tooltip": "Connected recipe_data to edit/forward"}),
"manager_data": ("MANAGER_DATA", {"forceInput": True, "tooltip": "manager_data from Prompt Manager, Recipe nodes, Prompt Composer or Prompt Layout Builder to save/forward"}),
"image": ("IMAGE", {"tooltip": "Optional image input used as the saved thumbnail when present."}),
},
"hidden": {
"unique_id": "UNIQUE_ID",
@@ -95,23 +59,33 @@ class WorkflowManager(PromptManagerAdvanced):
}
CATEGORY = "Prompt Manager"
DESCRIPTION = "Workflow-data focused manager (no use switches, no trigger words)."
RETURN_TYPES = ("RECIPE_DATA",)
RETURN_NAMES = ("recipe_data",)
DESCRIPTION = "Library Manager: save and reload manager_data from Prompt Manager, Recipe nodes, Prompt Composer and Prompt Layout Builder, with optional thumbnail image input."
RETURN_TYPES = ("MANAGER_DATA",)
RETURN_NAMES = ("manager_data",)
FUNCTION = "get_workflow"
OUTPUT_NODE = True
@classmethod
def IS_CHANGED(cls, category, name, text="", **kwargs):
recipe_data = kwargs.get("recipe_data", None)
data = kwargs.get("manager_data", None)
if data is None:
data = kwargs.get("data", None)
image = kwargs.get("image", 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", "")
thumbnail_sig = None
try:
if image is not None:
thumbnail_sig = tuple(getattr(image, "shape", []) or [])
except Exception:
thumbnail_sig = "image"
return (
category,
name,
text,
str(recipe_data) if recipe_data else None,
str(data) if data else None,
thumbnail_sig,
loras_a_toggle or "",
loras_b_toggle or "",
saved_workflow_data or "",
@@ -122,13 +96,21 @@ class WorkflowManager(PromptManagerAdvanced):
category,
name,
text="",
recipe_data=None,
manager_data=None,
image=None,
unique_id=None,
loras_a_toggle=None,
loras_b_toggle=None,
saved_workflow_data=None,
**kwargs,
):
prompts_data = self.load_prompts()
source_name = self.SOURCE_NAME
recipe_data = manager_data
if recipe_data is None:
recipe_data = kwargs.get("data")
if recipe_data is None:
recipe_data = kwargs.get("recipe_data")
def _as_workflow_dict(raw):
if isinstance(raw, dict):
@@ -142,8 +124,6 @@ class WorkflowManager(PromptManagerAdvanced):
return None
prompt_entry = prompts_data.get(category, {}).get(name, {}) if isinstance(prompts_data, dict) else {}
# On reload, category/name can be temporarily out of sync in the UI.
# If direct lookup misses, find the selected name in any category.
if not isinstance(prompt_entry, dict) or not prompt_entry:
if isinstance(prompts_data, dict) and isinstance(name, str) and name:
for cat_prompts in prompts_data.values():
@@ -152,21 +132,15 @@ class WorkflowManager(PromptManagerAdvanced):
break
stored_prompt_wf = _as_workflow_dict(prompt_entry.get("workflow_data")) if isinstance(prompt_entry, dict) else None
live_workflow_data = _as_workflow_dict(recipe_data)
hidden_saved_wf = _as_workflow_dict(saved_workflow_data)
# WorkflowManager should prefer live connected workflow_data when present,
# then fall back to local serialized state.
resolved_workflow_data = ensure_v2_recipe_data(live_workflow_data, source="RecipeManager") if isinstance(live_workflow_data, dict) else None
resolved_workflow_data = ensure_v2_recipe_data(live_workflow_data, source=source_name) if isinstance(live_workflow_data, dict) else None
if resolved_workflow_data is None:
resolved_workflow_data = ensure_v2_recipe_data(hidden_saved_wf, source="RecipeManager") if isinstance(hidden_saved_wf, dict) else None
resolved_workflow_data = ensure_v2_recipe_data(hidden_saved_wf, source=source_name) if isinstance(hidden_saved_wf, dict) else None
if resolved_workflow_data is None and isinstance(stored_prompt_wf, dict):
resolved_workflow_data = ensure_v2_recipe_data(stored_prompt_wf, source="RecipeManager")
resolved_workflow_data = ensure_v2_recipe_data(stored_prompt_wf, source=source_name)
# Prompt-only fallback: allow RecipeManager to open saved PMA prompts
# (prompt + lora stacks) by synthesizing minimal v2 recipe_data.
if resolved_workflow_data is None and isinstance(prompt_entry, dict):
prompt_text = str(prompt_entry.get("prompt", "") or text or "")
negative_text = str(prompt_entry.get("negative_prompt", "") or "")
@@ -186,31 +160,36 @@ class WorkflowManager(PromptManagerAdvanced):
negative_prompt=negative_text,
loras_a=prompt_loras_a,
loras_b=prompt_loras_b,
source="RecipeManager",
source=source_name,
)
wf = resolved_workflow_data if isinstance(resolved_workflow_data, dict) else {}
wf_model_a = get_v2_model_block(wf, "model_a") or {}
wf_model_b = get_v2_model_block(wf, "model_b") or {}
wf_has_model_b = isinstance(get_v2_model_block(wf, "model_b"), dict)
composer_payload = wf.get("prompt_composer") if isinstance(wf.get("prompt_composer"), dict) else {}
composer_input_data = composer_payload.get("input_data") if isinstance(composer_payload.get("input_data"), dict) else {}
incoming_wf = live_workflow_data if isinstance(live_workflow_data, dict) else None
incoming_has_model_b = None
if isinstance(incoming_wf, dict):
incoming_v2 = ensure_v2_recipe_data(incoming_wf, source="RecipeManager")
incoming_v2 = ensure_v2_recipe_data(incoming_wf, source=source_name)
incoming_models = incoming_v2.get("models", {}) if isinstance(incoming_v2.get("models"), dict) else {}
incoming_has_model_b = isinstance(incoming_models.get("model_b"), dict)
output_text = (wf_model_a.get("positive_prompt", "") or text or "")
generated_thumbnail = _image_to_base64_thumbnail(wf.get("IMAGE")) if isinstance(wf, dict) else None
incoming_thumbnail = _image_to_base64_thumbnail(incoming_wf.get("IMAGE")) if isinstance(incoming_wf, dict) else None
workflow_thumbnail = incoming_thumbnail if isinstance(incoming_thumbnail, str) and incoming_thumbnail else (
generated_thumbnail if isinstance(generated_thumbnail, str) and generated_thumbnail else (
incoming_wf.get("thumbnail") if isinstance(incoming_wf, dict) and isinstance(incoming_wf.get("thumbnail"), str) else (
wf.get("thumbnail") if isinstance(wf.get("thumbnail"), str) else None
generated_thumbnail = image_to_base64_thumbnail(wf.get("IMAGE"), log_prefix=source_name) if isinstance(wf, dict) else None
incoming_thumbnail = image_to_base64_thumbnail(incoming_wf.get("IMAGE"), log_prefix=source_name) if isinstance(incoming_wf, dict) else None
explicit_thumbnail = image_to_base64_thumbnail(image, log_prefix=source_name) if image is not None else None
workflow_thumbnail = explicit_thumbnail if isinstance(explicit_thumbnail, str) and explicit_thumbnail else (
incoming_thumbnail if isinstance(incoming_thumbnail, str) and incoming_thumbnail else (
generated_thumbnail if isinstance(generated_thumbnail, str) and generated_thumbnail else (
incoming_wf.get("thumbnail") if isinstance(incoming_wf, dict) and isinstance(incoming_wf.get("thumbnail"), str) else (
wf.get("thumbnail") if isinstance(wf.get("thumbnail"), str) else None
)
)
)
)
# Build preset stacks from saved toggle state.
preset_stack_a = self._build_stack_from_toggle(loras_a_toggle) if loras_a_toggle else []
preset_stack_b = self._build_stack_from_toggle(loras_b_toggle) if (wf_has_model_b and loras_b_toggle) else []
@@ -230,19 +209,19 @@ class WorkflowManager(PromptManagerAdvanced):
if isinstance(lora, dict) and lora.get("name")
]
# WorkflowManager is workflow-data centric: preserve connected workflow order
# and use toggles only to modify active/strength state for those entries.
# Fallback to preset stack only when no workflow LoRAs are present.
if wf_loras_a:
merged_stack_a = list(wf_loras_a)
else:
merged_stack_a = list(preset_stack_a) if preset_stack_a else []
composer_input_loras_a = [
(
lora.get("path") or lora.get("name"),
lora.get("model_strength", 1.0),
lora.get("clip_strength", 1.0),
)
for lora in composer_input_data.get("lora_stack", [])
if isinstance(lora, dict) and (lora.get("path") or lora.get("name"))
]
merged_stack_a = list(wf_loras_a) if wf_loras_a else (list(preset_stack_a) if preset_stack_a else [])
if wf_has_model_b:
if wf_loras_b:
merged_stack_b = list(wf_loras_b)
else:
merged_stack_b = list(preset_stack_b) if preset_stack_b else []
merged_stack_b = list(wf_loras_b) if wf_loras_b else (list(preset_stack_b) if preset_stack_b else [])
else:
merged_stack_b = []
@@ -262,12 +241,12 @@ class WorkflowManager(PromptManagerAdvanced):
"use_prompt_input": False,
"use_workflow_data": True,
"prompt_input": "",
"workflow_data": to_json_safe_workflow_data(ensure_v2_recipe_data(recipe_data, source="RecipeManager")) if isinstance(recipe_data, dict) else (
"workflow_data": to_json_safe_workflow_data(ensure_v2_recipe_data(recipe_data, source=source_name)) if isinstance(recipe_data, dict) else (
to_json_safe_workflow_data(resolved_workflow_data) if isinstance(resolved_workflow_data, dict) else None
),
"loras_a": loras_a_display,
"loras_b": loras_b_display,
"input_loras_a": self._format_loras_for_display(wf_loras_a) if wf_loras_a else [],
"input_loras_a": self._format_loras_for_display(composer_input_loras_a) if composer_input_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,
@@ -288,7 +267,7 @@ class WorkflowManager(PromptManagerAdvanced):
out_workflow_data = ensure_v2_recipe_data(
dict(resolved_workflow_data) if isinstance(resolved_workflow_data, dict) else {},
source="RecipeManager",
source=source_name,
)
models_out = out_workflow_data.get("models", {})
@@ -332,11 +311,9 @@ class WorkflowManager(PromptManagerAdvanced):
model_b_pos = str(model_b_out.get("positive_prompt", "") or "").strip()
model_b_neg = str(model_b_out.get("negative_prompt", "") or "").strip()
model_b_has_runtime = any(
model_b_out.get(k) is not None
for k in ("MODEL", "CLIP", "VAE", "POSITIVE", "NEGATIVE")
model_b_out.get(key) is not None
for key in ("MODEL", "CLIP", "VAE", "POSITIVE", "NEGATIVE")
)
# model_b is considered meaningful when it has authored content
# that is not just a mirrored default of model_a.
keep_model_b = bool(model_b_loras) or bool(model_b_pos) or bool(model_b_neg) or model_b_has_runtime
if model_b_name and model_b_name != model_a_name:
keep_model_b = True
@@ -345,7 +322,6 @@ class WorkflowManager(PromptManagerAdvanced):
not model_b_loras and not model_b_pos and not model_b_neg and not model_b_has_runtime):
keep_model_b = False
# Canonical rule: if incoming recipe_data had no model_b, scrub model_b from output.
if incoming_has_model_b is False:
keep_model_b = False
@@ -354,9 +330,12 @@ class WorkflowManager(PromptManagerAdvanced):
models_out["model_b"] = model_b_out
else:
models_out.pop("model_b", None)
out_workflow_data["_source"] = "RecipeManager"
if workflow_thumbnail:
out_workflow_data["thumbnail"] = workflow_thumbnail
out_workflow_data["_source"] = source_name
return (out_workflow_data,)
def check_lazy_status(self, category, name, text="", **kwargs):
return []
return []
+169 -27
View File
@@ -1,6 +1,7 @@
"""Multi-slot LoRA stacker outputting four independent LORA_STACK outputs (A/B/C/D)."""
import json
import importlib
import os
import sys
@@ -13,13 +14,38 @@ except Exception:
def _try_get_lm_get_lora_info():
"""Return LM's get_lora_info function if it is already loaded in sys.modules."""
for mod in sys.modules.values():
"""Return LM's get_lora_info function when available."""
# First, try already-loaded modules.
for mod_name, mod in list(sys.modules.items()):
if mod is None:
continue
mod_dict = getattr(mod, "__dict__", None)
if not isinstance(mod_dict, dict):
continue
# Use module __dict__ lookup to avoid invoking module-level __getattr__.
fn = mod_dict.get("get_lora_info")
if callable(fn):
file_path = str(mod_dict.get("__file__") or "").lower()
has_absolute_variant = callable(mod_dict.get("get_lora_info_absolute"))
if "comfyui-lora-manager" in file_path or has_absolute_variant:
return fn
# If not loaded yet, try common module paths directly.
candidate_modules = (
"custom_nodes.ComfyUI_Lora_Manager.py.utils.utils",
"ComfyUI_Lora_Manager.py.utils.utils",
"py.utils.utils",
)
for module_name in candidate_modules:
try:
mod = importlib.import_module(module_name)
except Exception:
continue
fn = getattr(mod, "get_lora_info", None)
if callable(fn):
module_name = getattr(fn, "__module__", "") or ""
if "lora_manager" in module_name.lower():
return fn
return fn
return None
@@ -30,26 +56,29 @@ def _build_lora_stack(loras_json):
Each entry: {"name": str, "strength": float, "clipStrength": float, "active": bool}
Returns a list of (lora_path, model_strength, clip_strength) tuples.
"""
empty_result = ([], [])
if isinstance(loras_json, str):
raw = loras_json.strip()
if not raw or raw == "[]":
return []
return empty_result
try:
loras = json.loads(raw)
except Exception:
return []
return empty_result
elif isinstance(loras_json, dict) and "__value__" in loras_json:
loras = loras_json["__value__"]
elif isinstance(loras_json, list):
loras = loras_json
else:
return []
return empty_result
if not isinstance(loras, list):
return []
return empty_result
get_lora_info = _try_get_lm_get_lora_info()
stack = []
trigger_words = []
def _normalize_to_relative_lora(raw_value, fallback_name):
candidate = str(raw_value or "").strip()
@@ -96,8 +125,20 @@ def _build_lora_stack(loras_json):
if get_lora_info is not None:
try:
result = get_lora_info(name)
if isinstance(result, tuple) and result[0]:
lora_path = _normalize_to_relative_lora(result[0], name)
if isinstance(result, tuple):
if len(result) >= 1 and result[0]:
lora_path = _normalize_to_relative_lora(result[0], name)
if len(result) >= 2:
raw_triggers = result[1]
if isinstance(raw_triggers, str):
token = raw_triggers.strip()
if token:
trigger_words.append(token)
elif isinstance(raw_triggers, (list, tuple, set)):
for trigger in raw_triggers:
token = str(trigger or "").strip()
if token:
trigger_words.append(token)
except Exception:
pass
@@ -107,11 +148,11 @@ def _build_lora_stack(loras_json):
stack.append((lora_path, strength, clip_strength))
return stack
return stack, trigger_words
class MultiLoraStackerLM:
"""Multi-slot LoRA stacker with four independent stacks (A / B / C / D)."""
"""Multi-slot LoRA stacker with per-slot and combined stack outputs."""
NAME = "Multi Lora Stacker (LoraManager)"
CATEGORY = "Prompt Manager"
@@ -126,14 +167,23 @@ class MultiLoraStackerLM:
"loras_state_c": ("STRING", {"default": "[]", "multiline": True}),
"loras_state_d": ("STRING", {"default": "[]", "multiline": True}),
},
"optional": {
"stack_count": ("INT", {
"default": 2,
"min": 1,
"max": 4,
"tooltip": "Number of LoRA stacks to expose and combine.",
}),
},
}
RETURN_TYPES = ("MULTI_LORA_STACK",)
RETURN_NAMES = ("multi_lora_stack",)
RETURN_TYPES = ("MULTI_LORA_STACK", "LORA_STACK", "STRING")
RETURN_NAMES = ("multi_lora_stack", "lora_stack", "trigger_words")
FUNCTION = "stack_multi"
DESCRIPTION = (
"Multi-slot LoRA stacker with a visual 4-panel UI (A / B / C / D). "
"Outputs one MULTI_LORA_STACK payload containing all four stacks."
"Outputs one MULTI_LORA_STACK payload plus one combined LORA_STACK "
"containing A+B+C+D in order."
)
def stack_multi(
@@ -142,19 +192,32 @@ class MultiLoraStackerLM:
loras_state_b="[]",
loras_state_c="[]",
loras_state_d="[]",
stack_count=2,
**kwargs,
):
stack_a = _build_lora_stack(loras_state_a)
stack_b = _build_lora_stack(loras_state_b)
stack_c = _build_lora_stack(loras_state_c)
stack_d = _build_lora_stack(loras_state_d)
multi_lora_stack = {
"a": stack_a,
"b": stack_b,
"c": stack_c,
"d": stack_d,
}
return (multi_lora_stack,)
stack_a, triggers_a = _build_lora_stack(loras_state_a)
stack_b, triggers_b = _build_lora_stack(loras_state_b)
stack_c, triggers_c = _build_lora_stack(loras_state_c)
stack_d, triggers_d = _build_lora_stack(loras_state_d)
count = max(1, min(4, int(stack_count or 2)))
slot_stacks = [stack_a, stack_b, stack_c, stack_d]
slot_triggers = [triggers_a, triggers_b, triggers_c, triggers_d]
slot_keys = ["a", "b", "c", "d"]
multi_lora_stack = {}
combined_lora_stack = []
trigger_words = []
for i in range(4):
if i < count:
multi_lora_stack[slot_keys[i]] = slot_stacks[i]
combined_lora_stack.extend(slot_stacks[i])
trigger_words.extend(slot_triggers[i])
else:
multi_lora_stack[slot_keys[i]] = []
trigger_words_text = ",, ".join(trigger_words) if trigger_words else ""
return (multi_lora_stack, combined_lora_stack, trigger_words_text)
def _coerce_lora_stack(raw_stack):
@@ -273,3 +336,82 @@ class MultiLoraCombine:
"d": out_d,
}
return (merged,)
class MultiLoraSplitter:
"""Split one MULTI_LORA_STACK payload into A/B/C/D LORA_STACK outputs."""
NAME = "Multi LoRA Splitter"
CATEGORY = "Prompt Manager"
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"multi_lora_stack": ("MULTI_LORA_STACK", {
"tooltip": "Input MULTI_LORA_STACK payload to split into A/B/C/D stacks.",
}),
},
}
RETURN_TYPES = ("LORA_STACK", "LORA_STACK", "LORA_STACK", "LORA_STACK")
RETURN_NAMES = ("lora_stack_a", "lora_stack_b", "lora_stack_c", "lora_stack_d")
FUNCTION = "split_multi"
DESCRIPTION = "Split a MULTI_LORA_STACK payload into LORA_STACK outputs A/B/C/D."
def split_multi(self, multi_lora_stack, **kwargs):
if not isinstance(multi_lora_stack, dict):
return ([], [], [], [])
out_a = _coerce_lora_stack(multi_lora_stack.get("a"))
out_b = _coerce_lora_stack(multi_lora_stack.get("b"))
out_c = _coerce_lora_stack(multi_lora_stack.get("c"))
out_d = _coerce_lora_stack(multi_lora_stack.get("d"))
return (out_a, out_b, out_c, out_d)
class LoraStackCombine:
"""Combine up to four LORA_STACK inputs into one merged LORA_STACK output."""
NAME = "LoRA Stack Combine"
CATEGORY = "Prompt Manager"
@classmethod
def INPUT_TYPES(cls):
return {
"required": {},
"optional": {
"lora_stack_a": ("LORA_STACK", {
"tooltip": "Optional LORA_STACK to append first.",
}),
"lora_stack_b": ("LORA_STACK", {
"tooltip": "Optional LORA_STACK to append second.",
}),
"lora_stack_c": ("LORA_STACK", {
"tooltip": "Optional LORA_STACK to append third.",
}),
"lora_stack_d": ("LORA_STACK", {
"tooltip": "Optional LORA_STACK to append fourth.",
}),
},
}
RETURN_TYPES = ("LORA_STACK",)
RETURN_NAMES = ("lora_stack",)
FUNCTION = "combine_lora_stacks"
DESCRIPTION = "Combine up to four LORA_STACK inputs into one LORA_STACK output."
def combine_lora_stacks(
self,
lora_stack_a=None,
lora_stack_b=None,
lora_stack_c=None,
lora_stack_d=None,
**kwargs,
):
merged = []
merged.extend(_coerce_lora_stack(lora_stack_a))
merged.extend(_coerce_lora_stack(lora_stack_b))
merged.extend(_coerce_lora_stack(lora_stack_c))
merged.extend(_coerce_lora_stack(lora_stack_d))
return (merged,)
+240
View File
@@ -0,0 +1,240 @@
"""Prompt Browser node with source-aware prompt selection and random multi-pick."""
import json
import random
import time
import server
from ..py.prompt_composer_store import (
PromptComposerStore,
_find_category_case_insensitive,
_find_prompt_case_insensitive,
_get_category_prompts_map,
)
from .prompt_manager_basic import _get_workflow_node
from .prompt_manager_basic import PromptManager
from .prompt_generator import PromptGeneratorDataStore
def _is_hidden_category_entry_key(name):
normalized = str(name or "").strip().lower()
return normalized in {"__meta__", "_base_prompt_", "_prompt_type_", "_prompts_"}
def _iter_prompt_items(entries):
if not isinstance(entries, dict):
return []
prompt_entries = _get_category_prompts_map(entries)
if isinstance(prompt_entries, dict) and "_prompts_" in entries:
return list(prompt_entries.items())
return [
(name, entry)
for name, entry in entries.items()
if not _is_hidden_category_entry_key(name)
]
class PromptBrowser:
"""Browse prompts, select one or many, and emit a resolved prompt."""
SOURCE_COMPOSE = "Compose Data"
SOURCE_PROMPT = "Prompt Data"
SOURCE_SYSTEM_PROMPTS = "System Prompts"
@staticmethod
def _load_prompts_for_source(source):
if str(source or "") == PromptBrowser.SOURCE_PROMPT:
return PromptManager.load_prompts()
if str(source or "") == PromptBrowser.SOURCE_SYSTEM_PROMPTS:
return PromptGeneratorDataStore.load()
return PromptComposerStore.load_prompts()
@staticmethod
def _pick_from_selected(selected_json, seed):
try:
names = json.loads(selected_json or "[]")
except Exception:
names = []
if not isinstance(names, list) or not names:
return ""
normalized = [str(name).strip() for name in names if str(name).strip()]
if not normalized:
return ""
try:
seed_value = int(seed)
except Exception:
seed_value = 0
if seed_value == 0:
return random.choice(normalized)
rng = random.Random(seed_value)
return rng.choice(normalized)
@staticmethod
def _has_multiple_selection(selected_json):
try:
names = json.loads(selected_json or "[]")
except Exception:
names = []
return isinstance(names, list) and len(names) > 1
@classmethod
def INPUT_TYPES(s):
compose_data = PromptComposerStore.load_prompts()
prompt_data = PromptManager.load_prompts()
system_data = PromptGeneratorDataStore.load()
categories_set = set()
for source_data in (compose_data, prompt_data, system_data):
for category_name in source_data.keys():
if category_name == "__meta__":
continue
categories_set.add(category_name)
categories = sorted(categories_set, key=str.lower)
if not categories:
categories = [""]
all_prompts = []
first_prompt_text = ""
first_prompt = ""
for source_data in (compose_data, prompt_data, system_data):
for cat in categories:
entries = source_data.get(cat, {})
if not isinstance(entries, dict):
continue
for name, entry in _iter_prompt_items(entries):
all_prompts.append(name)
if not first_prompt:
first_prompt = name
if isinstance(entry, dict):
first_prompt_text = entry.get("prompt", "") or ""
all_prompts = sorted(all_prompts, key=str.lower)
if not all_prompts:
all_prompts = [""]
return {
"required": {
"source": ([s.SOURCE_COMPOSE, s.SOURCE_PROMPT, s.SOURCE_SYSTEM_PROMPTS], {"default": s.SOURCE_SYSTEM_PROMPTS}),
"category": (categories, {"default": categories[0]}),
"name": (all_prompts, {"default": first_prompt}),
"selected_prompts": ("STRING", {
"default": "[]",
"multiline": False,
"dynamicPrompts": False,
"tooltip": "Internal: JSON list of selected prompts",
}),
"use_prompt_input": ("BOOLEAN", {
"default": False,
"tooltip": "Toggle to use connected prompt input instead of internal text",
}),
"text": ("STRING", {
"multiline": True,
"default": first_prompt_text,
"placeholder": "Enter prompt fragment text",
"dynamicPrompts": False,
"tooltip": "Enter prompt fragment text directly",
}),
},
"optional": {
"prompt": ("STRING", {
"multiline": True,
"forceInput": True,
"tooltip": "Connect a prompt input to pass through",
}),
},
"hidden": {
"seed": ("INT", {
"default": 0,
"min": 0,
"max": 0xFFFFFFFFFFFFFFFF,
}),
"unique_id": "UNIQUE_ID",
"extra_pnginfo": "EXTRA_PNGINFO",
"api_prompt": "PROMPT",
}
}
CATEGORY = "Prompt Manager"
DESCRIPTION = "Browse prompts from Prompt Data, Compose Data, or System Prompts with single or multi-random selection."
RETURN_TYPES = ("STRING",)
RETURN_NAMES = ("prompt",)
FUNCTION = "get_prompt"
OUTPUT_NODE = True
@classmethod
def VALIDATE_INPUTS(cls, name, **kwargs):
return True
@classmethod
def IS_CHANGED(cls, source, category, name, selected_prompts="[]", use_prompt_input=False, text="", seed=0, prompt="", **kwargs):
if cls._has_multiple_selection(selected_prompts):
return (source, category, name, selected_prompts, use_prompt_input, text, time.time_ns(), prompt)
return (source, category, name, selected_prompts, use_prompt_input, text, seed, prompt)
@staticmethod
def _patch_runtime_prompt_metadata(unique_id, output_text, extra_pnginfo=None, api_prompt=None):
"""Persist resolved prompt into workflow/api metadata for downstream save nodes."""
node_id = str(unique_id) if unique_id is not None else ""
if not node_id:
return
workflow_node = _get_workflow_node(extra_pnginfo, node_id)
if isinstance(workflow_node, dict):
widgets = workflow_node.get("widgets_values")
if isinstance(widgets, list):
# Current layout: [source, category, name, selected_prompts, use_prompt_input, text]
if len(widgets) > 4:
widgets[4] = False
if len(widgets) > 5:
widgets[5] = output_text
elif len(widgets) > 4:
widgets[4] = output_text
if isinstance(api_prompt, dict):
prompt_node = api_prompt.get(node_id)
if isinstance(prompt_node, dict):
inputs = prompt_node.get("inputs")
if isinstance(inputs, dict):
inputs["use_prompt_input"] = False
inputs["text"] = output_text
def get_prompt(self, source, category, name, selected_prompts="[]", use_prompt_input=False, text="", prompt=None,
seed=0, unique_id=None, extra_pnginfo=None, api_prompt=None):
prompts_data = self._load_prompts_for_source(source)
canonical_category = _find_category_case_insensitive(prompts_data, category) or category
category_data = prompts_data.get(canonical_category, {})
chosen_name = name
if self._has_multiple_selection(selected_prompts):
picked = self._pick_from_selected(selected_prompts, seed)
if picked:
chosen_name = picked
entry, canonical_name = _find_prompt_case_insensitive(category_data, chosen_name)
resolved_text = ""
if isinstance(entry, dict):
resolved_text = str(entry.get("prompt", "") or "")
if use_prompt_input and isinstance(prompt, str):
output_text = prompt
elif resolved_text.strip():
output_text = resolved_text
else:
output_text = text
if unique_id is not None:
server.PromptServer.instance.send_sync("prompt-manager-update-text", {
"node_id": unique_id,
"prompt": output_text,
"use_prompt_input": use_prompt_input,
"selected_name": canonical_name or chosen_name,
"source": source,
})
self._patch_runtime_prompt_metadata(unique_id, output_text, extra_pnginfo, api_prompt)
return (output_text,)
File diff suppressed because it is too large Load Diff
+351 -68
View File
@@ -31,13 +31,160 @@ _video_frames_cache = {}
# "Update Workflow" button to pull data without re-executing PromptExtractor.
_last_extracted_info = {}
IMAGE_EXTS = {'.png', '.jpg', '.jpeg', '.webp', '.gif', '.bmp'}
VIDEO_EXTS = {'.mp4', '.webm', '.mov', '.avi', '.mkv', '.m4v', '.wmv'}
AUDIO_EXTS = {'.wav', '.flac', '.mp3', '.m4a', '.ogg', '.aac', '.opus'}
JSON_EXTS = {'.json'}
ALL_MEDIA_EXTS = IMAGE_EXTS | VIDEO_EXTS | AUDIO_EXTS
_MEDIA_META_CACHE = {}
def _safe_abspath(path):
return os.path.abspath(os.path.expanduser(path or ""))
def _is_within(base_dir, candidate_path):
real_base = os.path.realpath(base_dir)
real_path = os.path.realpath(candidate_path)
return real_path == real_base or real_path.startswith(real_base + os.sep)
def _resolve_source_base_dir(source):
if source == 'output':
return folder_paths.get_output_directory()
if source == 'temp':
return folder_paths.get_temp_directory()
return folder_paths.get_input_directory()
def _resolve_media_path(filename, source='input', allow_temp_fallback=False):
"""Resolve a relative-or-absolute media path and return absolute path or None."""
file_value = (filename or '').strip()
if not file_value:
return None
# Absolute selections from browse-anywhere mode.
if os.path.isabs(file_value):
abs_path = _safe_abspath(file_value)
return abs_path if os.path.exists(abs_path) else None
base_dir = _resolve_source_base_dir(source)
candidate = os.path.join(base_dir, file_value.replace('/', os.sep))
if os.path.exists(candidate) and _is_within(base_dir, candidate):
return os.path.realpath(candidate)
if allow_temp_fallback:
temp_dir = folder_paths.get_temp_directory()
candidate = os.path.join(temp_dir, file_value.replace('/', os.sep))
if os.path.exists(candidate) and _is_within(temp_dir, candidate):
return os.path.realpath(candidate)
return None
def _list_drives():
if os.name != 'nt':
return ['/']
drives = []
for letter in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ':
drive = f"{letter}:\\"
if os.path.exists(drive):
drives.append(drive)
return drives
def _default_browser_roots():
roots = []
for getter in (folder_paths.get_input_directory, folder_paths.get_output_directory):
try:
p = _safe_abspath(getter())
if os.path.isdir(p) and p not in roots:
roots.append(p)
except Exception:
pass
if not roots:
roots = _list_drives()
return roots
def _exts_for_kind(kind):
kind = (kind or 'media').lower()
if kind == 'image':
return IMAGE_EXTS
if kind == 'video':
return VIDEO_EXTS
if kind == 'audio':
return AUDIO_EXTS
if kind == 'json':
return JSON_EXTS
if kind == 'audiovideo':
return AUDIO_EXTS | VIDEO_EXTS
if kind == 'all':
return ALL_MEDIA_EXTS
return IMAGE_EXTS | VIDEO_EXTS
def _probe_media_meta(file_path, ext):
if ext not in VIDEO_EXTS and ext not in AUDIO_EXTS:
return {"duration": None, "width": None, "height": None}
try:
st = os.stat(file_path)
cache_key = (file_path, int(st.st_mtime), int(st.st_size))
except OSError:
return {"duration": None, "width": None, "height": None}
cached = _MEDIA_META_CACHE.get(cache_key)
if cached is not None:
return cached
meta = {"duration": None, "width": None, "height": None}
try:
import av
container = av.open(file_path)
try:
if container.duration:
meta["duration"] = float(container.duration) / 1_000_000.0
if ext in VIDEO_EXTS:
stream = next((s for s in container.streams if s.type == "video"), None)
if stream is not None:
if stream.width:
meta["width"] = int(stream.width)
if stream.height:
meta["height"] = int(stream.height)
if stream.duration is not None and stream.time_base is not None:
meta["duration"] = float(stream.duration * stream.time_base)
elif stream.frames and stream.average_rate:
fps = float(stream.average_rate)
if fps > 0:
meta["duration"] = float(stream.frames) / fps
else:
stream = next((s for s in container.streams if s.type == "audio"), None)
if stream is not None and stream.duration is not None and stream.time_base is not None:
meta["duration"] = float(stream.duration * stream.time_base)
finally:
container.close()
except Exception:
pass
if meta["duration"] is not None and meta["duration"] < 0:
meta["duration"] = None
_MEDIA_META_CACHE[cache_key] = meta
return meta
# LoRA Blacklist - LoRAs containing these keywords will be excluded from extraction
# Add keywords that identify non-style LoRAs (e.g., distillation, optimization LoRAs)
LORA_BLACKLIST = [
'lightx2v', # Distillation LoRAs
['4steps', 'seko'], # Fast sampling LoRAs - requires BOTH keywords
['4steps', 'lightning']] # Fast sampling LoRAs - requires BOTH keywords
['minimax', 'turbo'], # Minimax Turbo LoRAs - requires BOTH keywords
['ltx', 'distilled'], # LTX Distilled LoRAs - requires BOTH keywords
['4step', 'seko'], # Fast sampling LoRAs - requires BOTH keywords
['4step', 'lightning']] # Fast sampling LoRAs - requires BOTH keywords
def is_lora_blacklisted(lora_name):
"""Check if a LoRA name contains any blacklisted keywords (case-insensitive)"""
@@ -304,14 +451,9 @@ async def extract_video_metadata_api(request):
if not filename:
return server.web.json_response({"success": False, "error": "Missing filename"}, status=400)
# Build full path based on source folder
if source == 'output':
base_dir = folder_paths.get_output_directory()
else:
base_dir = folder_paths.get_input_directory()
file_path = os.path.join(base_dir, filename.replace('/', os.sep))
file_path = _resolve_media_path(filename, source=source, allow_temp_fallback=False)
if not os.path.exists(file_path):
if not file_path or not os.path.exists(file_path):
print(f"[PromptExtractor] File not found: {file_path}")
return server.web.json_response({"success": False, "error": "File not found"}, status=404)
@@ -383,33 +525,172 @@ async def extract_video_metadata_api(request):
# API endpoint to list files in input or output directory
@server.PromptServer.instance.routes.get("/prompt-extractor/path-browser/list")
async def prompt_extractor_path_browser_list(request):
"""Read-only directory browser for media files."""
try:
path = request.query.get('path', '').strip()
kind = request.query.get('kind', 'media')
allowed = _exts_for_kind(kind)
roots = _default_browser_roots()
if not path:
return server.web.json_response({"ok": True, "mode": "roots", "roots": roots})
current = _safe_abspath(path)
if not os.path.isdir(current):
return server.web.json_response({"ok": False, "error": "Folder not found"}, status=404)
try:
entries = list(os.scandir(current))
except PermissionError:
return server.web.json_response({"ok": False, "error": "Access denied"}, status=403)
dirs = []
files = []
for entry in entries:
name = entry.name
if name.startswith('.'):
continue
try:
if entry.is_dir(follow_symlinks=False):
dirs.append({"name": name, "path": _safe_abspath(entry.path)})
elif entry.is_file(follow_symlinks=False):
ext = os.path.splitext(name)[1].lower()
if ext in allowed:
size = None
modified = None
duration = None
width = None
height = None
try:
st = entry.stat(follow_symlinks=False)
size = int(st.st_size)
modified = float(st.st_mtime)
except OSError:
pass
media_meta = _probe_media_meta(entry.path, ext)
duration = media_meta.get('duration')
width = media_meta.get('width')
height = media_meta.get('height')
files.append({
"name": name,
"path": _safe_abspath(entry.path),
"size": size,
"modified": modified,
"duration": duration,
"width": width,
"height": height,
})
except OSError:
continue
dirs.sort(key=lambda d: d['name'].lower())
files.sort(key=lambda f: f['name'].lower())
parent = os.path.dirname(current.rstrip('\\/'))
parent_path = parent if parent and parent != current else None
return server.web.json_response({
"ok": True,
"mode": "browse",
"current_path": current,
"parent_path": parent_path,
"roots": roots,
"dirs": dirs,
"files": files,
})
except Exception as e:
return server.web.json_response({"ok": False, "error": str(e)}, status=500)
@server.PromptServer.instance.routes.get("/prompt-extractor/path-browser/file")
async def prompt_extractor_path_browser_file(request):
"""Serve a media file by absolute path (extension-guarded)."""
try:
path = request.query.get('path', '').strip()
if not path:
return server.web.json_response({"ok": False, "error": "Missing path"}, status=400)
real_path = os.path.realpath(_safe_abspath(path))
if not os.path.isfile(real_path):
return server.web.json_response({"ok": False, "error": "File not found"}, status=404)
ext = os.path.splitext(real_path)[1].lower()
if ext not in ALL_MEDIA_EXTS:
return server.web.json_response({"ok": False, "error": "Unsupported file type"}, status=403)
return server.web.FileResponse(real_path, headers={"Cache-Control": "no-cache"})
except Exception as e:
return server.web.json_response({"ok": False, "error": str(e)}, status=500)
@server.PromptServer.instance.routes.get("/prompt-extractor/list-files")
async def list_input_files(request):
"""API endpoint to get list of supported files in input or output directory, including subfolders"""
try:
source = request.rel_url.query.get('source', 'input')
kind = request.rel_url.query.get('kind', 'media')
include_meta = request.rel_url.query.get('include_meta', '0') in ('1', 'true', 'yes')
if source == 'output':
base_dir = folder_paths.get_output_directory()
else:
base_dir = folder_paths.get_input_directory()
files = []
supported_extensions = ['.png', '.jpg', '.jpeg', '.webp', '.json', '.mp4', '.webm', '.mov', '.avi']
allowed_extensions = _exts_for_kind(kind)
# Legacy behavior: media listings also include json files used by PromptExtractor.
if kind in ('media', 'all'):
allowed_extensions = set(allowed_extensions) | {'.json'}
if os.path.exists(base_dir):
# Walk through directory recursively
for root, dirs, filenames in os.walk(base_dir):
for filename in filenames:
ext = os.path.splitext(filename)[1].lower()
if ext in supported_extensions:
if ext in allowed_extensions:
# Get relative path from base directory
full_path = os.path.join(root, filename)
rel_path = os.path.relpath(full_path, base_dir)
# Convert Windows backslashes to forward slashes
rel_path = rel_path.replace('\\', '/')
files.append(rel_path)
if include_meta:
size = None
modified = None
duration = None
width = None
height = None
try:
st = os.stat(full_path)
size = int(st.st_size)
modified = float(st.st_mtime)
except OSError:
pass
files.sort()
media_meta = _probe_media_meta(full_path, ext)
duration = media_meta.get('duration')
width = media_meta.get('width')
height = media_meta.get('height')
files.append({
"name": os.path.basename(rel_path),
"path": rel_path,
"size": size,
"modified": modified,
"duration": duration,
"width": width,
"height": height,
})
else:
files.append(rel_path)
if include_meta:
files.sort(key=lambda f: str(f.get('path', '')).lower())
else:
files.sort()
return server.web.json_response({"files": files})
except Exception as e:
print(f"[PromptExtractor] Error listing files: {e}")
@@ -454,14 +735,8 @@ async def extract_preview(request):
if not filename or filename == '(none)':
return server.web.json_response({"extracted": None})
# Resolve path with directory-traversal protection
base_dir = folder_paths.get_output_directory() if source == 'output' else folder_paths.get_input_directory()
file_path = os.path.join(base_dir, filename.replace('/', os.sep))
real_base = os.path.realpath(base_dir)
real_path = os.path.realpath(file_path)
if not (real_path == real_base or real_path.startswith(real_base + os.sep)):
return server.web.json_response({"extracted": None, "error": "Invalid path"}, status=403)
if not os.path.exists(file_path):
file_path = _resolve_media_path(filename, source=source, allow_temp_fallback=False)
if not file_path or not os.path.exists(file_path):
return server.web.json_response({"extracted": None, "error": "File not found"})
ext = os.path.splitext(file_path)[1].lower()
@@ -1388,23 +1663,10 @@ async def extract_video_frame_api(request):
if not filename:
return server.web.json_response({"error": "Missing filename"}, status=400)
# Build full path
if source == 'output':
base_dir = folder_paths.get_output_directory()
else:
base_dir = folder_paths.get_input_directory()
file_path = os.path.join(base_dir, filename.replace('/', os.sep))
if not os.path.exists(file_path):
file_path = _resolve_media_path(filename, source=source, allow_temp_fallback=False)
if not file_path or not os.path.exists(file_path):
return server.web.json_response({"error": "File not found"}, status=404)
# Validate path stays within base directory
real_base = os.path.realpath(base_dir)
real_path = os.path.realpath(file_path)
if not real_path.startswith(real_base):
return server.web.json_response({"error": "Invalid path"}, status=403)
img = extract_video_frame_av(file_path, position)
if img is None:
return server.web.json_response({"error": "Failed to extract frame"}, status=500)
@@ -3580,7 +3842,7 @@ class PromptExtractor:
"""
def __init__(self):
pass
self._workflow_data = None
@classmethod
def INPUT_TYPES(cls):
@@ -3625,6 +3887,7 @@ class PromptExtractor:
"optional": {
"lora_stack_a": ("LORA_STACK",),
"lora_stack_b": ("LORA_STACK",),
"video": ("VIDEO", {"tooltip": "Optional video input. When connected, extract from this video directly and the file picker is ignored."}),
},
"hidden": {
"unique_id": "UNIQUE_ID",
@@ -3644,8 +3907,8 @@ class PromptExtractor:
def VALIDATE_INPUTS(cls, **kwargs):
return True
def extract(self, image="", source_folder="input", frame_position=0.0, use_lora_input_only=False, lora_stack_a=None, lora_stack_b=None, unique_id=None, extra_pnginfo=None, prompt=None):
"""Extract prompts and LoRAs from the specified file."""
def extract(self, image="", source_folder="input", frame_position=0.0, use_lora_input_only=False, lora_stack_a=None, lora_stack_b=None, video=None, unique_id=None, extra_pnginfo=None, prompt=None):
"""Extract prompts and LoRAs from the specified file (or connected video)."""
# Handle None for frame_position (workflow compatibility)
if frame_position is None:
@@ -3673,35 +3936,53 @@ class PromptExtractor:
if image == "(none)":
image = ""
# Normalize file path
# A connected VIDEO input overrides the file picker: resolve its path
# directly and ignore the image/source_folder widgets.
resolved_path = None
file_path = "" # Initialize file_path to avoid UnboundLocalError
if image and image.strip():
file_path = image.strip()
if video is not None:
video_path = None
try:
src = video.get_stream_source()
if isinstance(src, str) and src:
video_path = src
except Exception as e:
print(f"[PromptExtractor] Could not get connected video path: {e}")
if video_path and os.path.exists(video_path):
resolved_path = video_path
file_path = video_path
print(f"[PromptExtractor] Using connected video input: {os.path.basename(video_path)}")
# Skip the file-picker path entirely
image = ""
# Handle relative paths (check selected source directory first, then temp as fallback)
if not os.path.isabs(file_path):
# Check selected source directory first
if source_folder == "output":
base_dir = folder_paths.get_output_directory()
else:
base_dir = folder_paths.get_input_directory()
potential_path = os.path.join(base_dir, file_path)
if os.path.exists(potential_path):
resolved_path = potential_path
else:
# Check temp directory as fallback (for backwards compatibility)
temp_dir = folder_paths.get_temp_directory()
potential_path = os.path.join(temp_dir, file_path)
# Normalize file path
if not resolved_path:
if image and image.strip():
file_path = image.strip()
# Handle relative paths (check selected source directory first, then temp as fallback)
if not os.path.isabs(file_path):
# Check selected source directory first
if source_folder == "output":
base_dir = folder_paths.get_output_directory()
else:
base_dir = folder_paths.get_input_directory()
potential_path = os.path.join(base_dir, file_path)
if os.path.exists(potential_path):
resolved_path = potential_path
else:
print(f"[PromptExtractor] File not found in {source_folder} or temp directories: {file_path}")
else:
if os.path.exists(file_path):
resolved_path = file_path
# Check temp directory as fallback (for backwards compatibility)
temp_dir = folder_paths.get_temp_directory()
potential_path = os.path.join(temp_dir, file_path)
if os.path.exists(potential_path):
resolved_path = potential_path
else:
print(f"[PromptExtractor] File not found in {source_folder} or temp directories: {file_path}")
else:
print(f"[PromptExtractor] Absolute path does not exist: {file_path}")
if os.path.exists(file_path):
resolved_path = file_path
else:
print(f"[PromptExtractor] Absolute path does not exist: {file_path}")
if resolved_path:
print(f"[PromptExtractor] Processing file: {resolved_path}")
@@ -4322,11 +4603,12 @@ class PromptExtractor:
wf_node['extracted_data'] = extracted_data
break
self._workflow_data = workflow_data
return {
# Do not publish extractor preview images to Comfy history/tasks.
# This prevents extractor frames from becoming the queue thumbnail.
"ui": {},
"result": (positive_prompt, negative_prompt, final_lora_stack_a, final_lora_stack_b, workflow_data, image_tensor)
"result": (positive_prompt, negative_prompt, final_lora_stack_a, final_lora_stack_b, image_tensor)
}
def save_preview_images(self, images):
@@ -4427,8 +4709,8 @@ class WorkflowExtractor:
CATEGORY = "Prompt Manager"
DESCRIPTION = "Extract workflow data from images, videos, and workflow files. Simplified version for RecipeBuilder."
RETURN_TYPES = ("RECIPE_DATA", "IMAGE")
RETURN_NAMES = ("recipe_data", "image")
RETURN_TYPES = ("IMAGE", "MANAGER_DATA")
RETURN_NAMES = ("image", "manager_data")
FUNCTION = "extract_workflow"
OUTPUT_NODE = False
@@ -4444,15 +4726,16 @@ class WorkflowExtractor:
use_lora_input_only=True, lora_stack_a=None, lora_stack_b=None,
unique_id=unique_id, extra_pnginfo=extra_pnginfo, prompt=prompt,
)
# Parent returns {"ui": ..., "result": (pos, neg, loras_a, loras_b, workflow_data, image)}
# Parent returns {"ui": ..., "result": (pos, neg, loras_a, loras_b, image)}
# workflow_data is stored on self._pe._workflow_data
full = result["result"]
workflow_data = full[4]
image_tensor = full[5]
workflow_data = self._pe._workflow_data
image_tensor = full[4]
return {
# Keep RecipeExtractor silent in UI previews for the same reason
# as PromptExtractor: avoid replacing final generation thumbnails.
"ui": {},
"result": (workflow_data, image_tensor),
"result": (image_tensor, workflow_data),
}
@classmethod
+1625 -260
View File
File diff suppressed because it is too large Load Diff
+30
View File
@@ -0,0 +1,30 @@
from .prompt_generator import PromptGenerator, _preferences_cache, ollama_unload_model
class PromptGeneratorKillSwitch:
"""Pass-through node that also stops the local llm server."""
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"value": ("*", {"forceInput": True, "tooltip": "Any input value to pass through unchanged."}),
}
}
RETURN_TYPES = ("*",)
RETURN_NAMES = ("value",)
FUNCTION = "pass_and_kill"
CATEGORY = "Prompt Manager"
DESCRIPTION = "Pass-through any value, stop Prompt Generator's llama.cpp server, and unload all Ollama models from memory."
@classmethod
def VALIDATE_INPUTS(cls, **kwargs):
return True
def pass_and_kill(self, value):
PromptGenerator.stop_server()
ok, msg = ollama_unload_model(_preferences_cache)
if msg:
print(f"Prompt Generator Kill Switch: {msg}")
return (value,)
+111 -16
View File
@@ -10,12 +10,47 @@ def trigger_model_list_refresh():
global _last_model_update
_last_model_update = time.time()
def get_default_context_size():
"""Return a context size scaled to the active GPU's total VRAM.
Tiers:
>= 24 GB → 8192
>= 16 GB → 4096
< 16 GB → 2048
No GPU / unknown → 4096 (safe CPU default)
Note:
This uses GPU capacity (total VRAM), not current free/available VRAM.
"""
try:
import importlib
torch = importlib.import_module("torch")
if torch.cuda.is_available():
try:
device_index = torch.cuda.current_device()
except Exception:
device_index = 0
total_vram_gb = torch.cuda.get_device_properties(device_index).total_memory / (1024 ** 3)
if total_vram_gb >= 24:
return 8192
elif total_vram_gb >= 16:
return 4096
else:
return 2048
except Exception:
pass
return 4096 # CPU or VRAM detection failed
class PromptGenOptions:
"""Node that provides optional configuration for llama.cpp servers"""
@classmethod
def INPUT_TYPES(cls):
backend = _preferences_cache.get("llm_backend", "llama.cpp")
preferred_model = str(_preferences_cache.get("preferred_model", "") or "").strip()
hide_downloadable_models = _preferences_cache.get("hide_downloadable_models", False) is True
if backend == "ollama":
# Discover models from Ollama
@@ -27,13 +62,27 @@ class PromptGenOptions:
else:
available_models = get_all_models()
if not available_models:
available_models = ["No models found - check HuggingFace"]
if hide_downloadable_models:
available_models = ["No local models found - add a .gguf or disable 'Hide downloadable built-in models'"]
else:
available_models = ["No models found - check HuggingFace"]
default_model = available_models[0] if available_models else ""
if preferred_model and preferred_model in available_models:
default_model = preferred_model
if backend == "ollama":
model_tooltip = "Select the Ollama model to use."
elif hide_downloadable_models:
model_tooltip = "Select a locally available model. Built-in HuggingFace download entries are hidden by the Prompt Manager preference."
else:
model_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"
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"
"default": default_model,
"tooltip": model_tooltip
}),
"image2": ("IMAGE", {
"tooltip": "Connect an image (required for 'Analyze Image' and 'Analyze Image with Prompt' modes)"
@@ -47,6 +96,10 @@ class PromptGenOptions:
"image5": ("IMAGE", {
"tooltip": "Connect an image (required for 'Analyze Image' and 'Analyze Image with Prompt' modes)"
}),
"system_prompt_mode": (["replace", "append"], {
"default": "append",
"tooltip": "replace: the text below fully replaces the default LLM instructions\nappend: the text below is added after the default LLM instructions"
}),
"system_prompt": ("STRING", {
"multiline": True,
"default": "",
@@ -54,7 +107,7 @@ class PromptGenOptions:
"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,
"default": True,
"tooltip": "Use the model's default sampling parameters (overrides temperature, top_p, etc)"
}),
"temperature": ("FLOAT", {
@@ -93,7 +146,7 @@ class PromptGenOptions:
"tooltip": "Penalty for repeating tokens (1.0 = no penalty)"
}),
"context_size": ("INT", {
"default": 4096,
"default": get_default_context_size(),
"min": 512,
"max": 32768,
"step": 512,
@@ -102,6 +155,17 @@ class PromptGenOptions:
"show_everything_in_console": ("BOOLEAN", {
"default": False,
"tooltip": "Print system prompt, user prompt, thinking process, and raw model response to console"
}),
"max_length": ("INT", {
"default": 512,
"min": 1,
"max": 32768,
"step": 1,
"tooltip": "Maximum number of tokens to generate when the Prompt Generator is connected to a CLIP/text encoder."
}),
"gpu_device": ("STRING", {
"default": "",
"tooltip": "GPU device index for llama.cpp (e.g. '0', '1').\nLeave empty to use the system default GPU.\nUseful with multi-GPU setups to control which GPU loads LLM weights."
})
}
}
@@ -118,12 +182,42 @@ class PromptGenOptions:
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,
system_prompt: str = None, system_prompt_mode: str = "replace",
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:
show_everything_in_console: bool = None, max_length: int = None,
gpu_device: str = None) -> dict:
"""Create options dictionary with model, LLM parameters, and extra images"""
# Backward compatibility for workflows saved before `system_prompt_mode` existed.
# Old widget arrays can shift values by one slot when loaded by newer node definitions.
mode_valid = system_prompt_mode in ("replace", "append")
legacy_shape = isinstance(system_prompt, bool) and (
not mode_valid or isinstance(use_model_default_sampling, (int, float))
)
if legacy_shape:
old_system_prompt = system_prompt_mode
old_use_default_sampling = system_prompt
old_temperature = use_model_default_sampling
old_top_k = temperature
old_top_p = top_k
old_min_p = top_p
old_repeat_penalty = min_p
old_context_size = repeat_penalty
old_show_console = context_size
system_prompt_mode = "replace"
system_prompt = old_system_prompt if isinstance(old_system_prompt, str) else ""
use_model_default_sampling = bool(old_use_default_sampling) if old_use_default_sampling is not None else None
temperature = old_temperature
top_k = old_top_k
top_p = old_top_p
min_p = old_min_p
repeat_penalty = old_repeat_penalty
context_size = old_context_size
show_everything_in_console = bool(old_show_console) if old_show_console is not None else None
options = {}
# Handle model selection and download if needed
@@ -174,6 +268,7 @@ class PromptGenOptions:
# Only include LLM parameters that are provided
if system_prompt and system_prompt.strip():
options["system_prompt"] = system_prompt
options["system_prompt_mode"] = system_prompt_mode
options["use_model_default_sampling"] = use_model_default_sampling
options["temperature"] = temperature
@@ -183,14 +278,14 @@ class PromptGenOptions:
options["repeat_penalty"] = repeat_penalty
options["context_size"] = context_size
options["show_everything_in_console"] = show_everything_in_console
options["max_length"] = max_length
# GPU device: use node input if provided, otherwise fall back to global preference
gpu_device_value = None
if gpu_device is not None and str(gpu_device).strip():
gpu_device_value = str(gpu_device).strip()
elif _preferences_cache.get("llama_gpu_device", ""):
gpu_device_value = _preferences_cache["llama_gpu_device"]
options["gpu_device"] = gpu_device_value
return (options,)
NODE_CLASS_MAPPINGS = {
"PromptGenOptions": PromptGenOptions
}
NODE_DISPLAY_NAME_MAPPINGS = {
"PromptGenOptions": "Prompt Generator Options"
}
+551
View File
@@ -0,0 +1,551 @@
"""
Prompt Layout Builder - draw a MOSS-Image layout (scene prompt + boxed regions) or load one from an LLM.
The editor stores boxes as canvas fractions {x, y, w, h, type, text, desc, palette} in the layout_data widget.
The prompt output follows output_format: the native MOSS-Image layout JSON (bbox in pixels from the canvas centre,
yxyx, the same format as MOSS-Image Layout Prompt), an Ideogram 4 JSON caption (0-1000 yxyx elements, as Build JSON
Prompt (Ideogram)) or the Krea 2 grounding lines of jimmycarter/krea2-turbo-bbox (x-first 0-1000 boxes).
import_json accepts the MOSS
format, percent or 0-1000 yxyx layouts written by
an LLM, Ideogram 4 captions, Krea 2 grounding lines, and the elements list from Create Bounding Boxes. The two converter nodes translate layouts to and from the
core BOUNDING_BOX / elements types so the builder can be chained with other box nodes.
"""
import json
import math
import re
import numpy as np
from PIL import Image
import comfy.utils
import nodes
from comfy_extras.nodes_bounding_boxes import (
boxes_from_input,
build_elements,
fractions_to_pixels,
pixels_to_fractions,
render_preview,
)
from comfy_extras.nodes_resolution import ASPECT_RATIOS
from ..py.workflow_data_utils import build_v2_recipe_data_from_prompt
REF_RATIO = "Use Reference Ratio"
# manager_data key holding the editor state, next to Prompt Composer's "prompt_composer".
LAYOUT_RECIPE_KEY = "prompt_layout"
SIZE_MULTIPLE = 16
CANVASES = ("single", "multi_panel", "collage")
BOX_TYPES = ("object", "character", "text", "panel")
BOX_PALETTE_MAX = 8
SUMMARY_PALETTE_MAX = 16
HEX_COLOR = re.compile(r"#[0-9a-fA-F]{6}")
RELATIVE_SPACES = {"percent": 100.0, "relative_1000": 1000.0}
OUTPUT_FORMATS = ("MOSS", "Ideogram", "Krea 2")
# Krea 2 character tags: person, anime character, furry / anthro character.
KREA_CHARACTER_TAGS = ("pe", "ac", "fc")
KREA_CHARACTER_ID = re.compile(r"[a-z0-9_]+")
def _resolution(aspect_ratio, megapixels, ref_size):
if aspect_ratio != REF_RATIO:
w_ratio, h_ratio = ASPECT_RATIOS[aspect_ratio]
else:
w_ratio, h_ratio = ref_size or (1, 1)
scale = math.sqrt(megapixels * 1024 * 1024 / (w_ratio * h_ratio))
return tuple(max(SIZE_MULTIPLE, round(r * scale / SIZE_MULTIPLE) * SIZE_MULTIPLE) for r in (w_ratio, h_ratio))
def _strs(value):
if isinstance(value, str):
value = re.split(r"[,\n]", value)
return [str(v).strip() for v in (value if isinstance(value, list) else []) if str(v).strip()]
def _palette(value, limit):
return [c.upper() for c in _strs(value) if HEX_COLOR.fullmatch(c)][:limit]
def _clean_box(raw):
x, y, w, h = (float(raw.get(k) or 0.0) for k in ("x", "y", "w", "h"))
x1, x2 = sorted((x, x + w))
y1, y2 = sorted((y, y + h))
x1, y1, x2, y2 = (min(1.0, max(0.0, v)) for v in (x1, y1, x2, y2))
box_type = raw.get("type") if raw.get("type") in BOX_TYPES else "object"
box = {
"x": x1, "y": y1, "w": x2 - x1, "h": y2 - y1,
"type": box_type,
"text": str(raw.get("text") or "") if box_type == "text" else "",
"desc": str(raw.get("desc") or ""),
"palette": _palette(raw.get("palette"), BOX_PALETTE_MAX),
}
ref = raw.get("prompt_ref")
if isinstance(ref, dict) and ref.get("name"):
box["prompt_ref"] = {"category": str(ref.get("category") or ""), "name": str(ref["name"])}
if box_type == "character":
if raw.get("krea_tag") in KREA_CHARACTER_TAGS:
box["krea_tag"] = raw["krea_tag"]
char_id = str(raw.get("char_id") or "").strip().lower()
if KREA_CHARACTER_ID.fullmatch(char_id):
box["char_id"] = char_id
return box
def _find_layout(text):
# LLM output may wrap the JSON in prose or a code fence: take the first layout-shaped value.
decoder = json.JSONDecoder()
for match in re.finditer(r"[{\[]", text):
try:
value, _ = decoder.raw_decode(text, match.start())
except json.JSONDecodeError:
continue
if isinstance(value, dict) and isinstance(value.get("items"), list):
return value
if isinstance(value, list) and value and all(isinstance(v, dict) and "bbox" in v and "type" in v for v in value):
return {"items": value, "bbox_coord_space": "relative_1000"}
raise ValueError('Prompt Layout Builder: import_json has no layout (an object with "items", or a list of elements).')
KREA_ELEMENT = re.compile(r"(p|o|t|pe|ac|fc)(?::([a-z0-9_]+))?\[\s*(-?[\d.]+)\s*,\s*(-?[\d.]+)\s*,\s*(-?[\d.]+)\s*,\s*(-?[\d.]+)\s*\]\s*(.*)")
KREA_TEXT = re.compile(r'"((?:[^"\\]|\\.)*)"\s*(.*)')
KREA_BOX_TYPES = {"p": "panel", "o": "object", "t": "text", "pe": "character", "ac": "character", "fc": "character"}
def _parse_krea(text):
# Krea 2 grounding lines (krea2-turbo-bbox); None when the text has no element, @ or ~ line.
fence = re.search(r"```[^\n]*\n(.*?)```", text, re.S)
lines = [line.strip() for line in (fence.group(1) if fence else text).splitlines() if line.strip()]
summary, fields, boxes, grounded = "", {}, [], False
for line in lines:
element = KREA_ELEMENT.fullmatch(line)
if element:
tag, char_id, rest = element.group(1), element.group(2), element.group(7)
x0, y0, x1, y1 = (float(element.group(i)) / 1000 for i in range(3, 7))
box = {"x": x0, "y": y0, "w": x1 - x0, "h": y1 - y0, "type": KREA_BOX_TYPES[tag], "desc": rest}
if tag == "t":
quoted = KREA_TEXT.match(rest)
if quoted:
box["text"] = re.sub(r"\\(.)", lambda m: "\n" if m.group(1) == "n" else m.group(1), quoted.group(1))
box["desc"] = quoted.group(2)
if box["type"] == "character":
box.update(krea_tag=tag, char_id=char_id)
boxes.append(_clean_box(box))
grounded = True
elif line.startswith("@"):
head, sep, tail = line[1:].rpartition(";")
fields["style"], fields["medium"] = (head.strip(), tail.strip()) if sep else (tail.strip(), "")
grounded = True
elif line.startswith("~"):
fields["background"] = line[1:].strip()
grounded = True
elif not summary and not grounded:
summary = line
return {"prompt": summary, "krea": fields, "boxes": boxes} if grounded else None
def _parse_ideogram(text):
# Ideogram 4 JSON caption (Build JSON Prompt (Ideogram)); None when the text has none.
decoder = json.JSONDecoder()
for match in re.finditer(r"\{", text):
try:
caption, _ = decoder.raw_decode(text, match.start())
except json.JSONDecodeError:
continue
if isinstance(caption, dict) and isinstance(caption.get("compositional_deconstruction"), dict):
break
else:
return None
scene = caption["compositional_deconstruction"]
style = caption.get("style_description") if isinstance(caption.get("style_description"), dict) else {}
text_of = lambda value: str(value or "").strip()
fields = {"background": text_of(scene.get("background"))}
if style:
kind = "art_style" if "art_style" in style else "photo" if "photo" in style else (
"photo" if text_of(style.get("medium")).lower() == "photograph" else "art_style")
fields.update(style=kind, style_detail=text_of(style.get(kind)), aesthetics=text_of(style.get("aesthetics")),
lighting=text_of(style.get("lighting")), medium=text_of(style.get("medium")))
elements = [e for e in scene.get("elements") or [] if isinstance(e, dict)]
return {
"prompt": text_of(caption.get("high_level_description")),
"ideogram": fields,
"palette": _palette(style.get("color_palette"), SUMMARY_PALETTE_MAX),
"boxes": _import_boxes({"items": elements, "bbox_coord_space": "relative_1000"}, 1, 1),
}
def _parse_text_layout(text, width, height, label):
parsed = _parse_krea(text) or _parse_ideogram(text)
if parsed:
return parsed
try:
layout = _find_layout(text)
except ValueError:
received = " ".join(text.split())
raise ValueError(f"{label} has no layout. Expected layout JSON (an object with \"items\" or a list of elements), "
"an Ideogram 4 caption or Krea 2 grounding lines; check the Prompt Generator system prompt. "
f"Received: {received[:200]!r}{'...' if len(received) > 200 else ''}") from None
return {"layout": layout, "boxes": _import_boxes(layout, width, height)}
def _boxes_from_bboxes(bboxes, width, height):
boxes = []
for raw in boxes_from_input(bboxes, width, height):
metadata = raw.get("metadata") or {}
box_type = "text" if metadata.get("type") == "text" else "character" if metadata.get("is_character") else "object"
boxes.append(_clean_box({
**pixels_to_fractions(raw, width, height),
"type": box_type,
"text": metadata.get("text"),
"desc": metadata.get("desc"),
"palette": metadata.get("palette"),
}))
return boxes
def _import_boxes(layout, width, height):
space = str(layout.get("bbox_coord_space") or "abs_centralized")
if space != "abs_centralized" and space not in RELATIVE_SPACES:
raise ValueError(f"Prompt Layout Builder: unsupported bbox_coord_space {space!r} "
"(expected percent, relative_1000 or abs_centralized).")
if str(layout.get("bbox_format") or "yxyx") != "yxyx":
raise ValueError('Prompt Layout Builder: bbox_format must be "yxyx" (top, left, bottom, right).')
boxes = []
for index, item in enumerate(layout["items"], 1):
if not isinstance(item, dict):
continue
try:
top, left, bottom, right = (float(v) for v in item.get("bbox"))
except (TypeError, ValueError):
raise ValueError(f"Prompt Layout Builder: item {index} needs a bbox [top, left, bottom, right].")
if space == "abs_centralized":
top, bottom = ((v + height // 2) / height for v in (top, bottom))
left, right = ((v + width // 2) / width for v in (left, right))
else:
top, left, bottom, right = (v / RELATIVE_SPACES[space] for v in (top, left, bottom, right))
boxes.append(_clean_box({
"x": left, "y": top, "w": right - left, "h": bottom - top,
"type": item.get("label", item.get("type")),
"text": item.get("text"),
"desc": item.get("caption", item.get("desc")),
"palette": item.get("palette", item.get("color_palette")),
}))
return boxes
def _moss_bbox(box, width, height):
# Same rounding as MOSS-Image Layout Prompt: pixel edges enclosing the box, origin at the canvas centre.
hx, hy = width // 2, height // 2
return [math.floor(round(box["y"] * height, 9)) - hy, math.floor(round(box["x"] * width, 9)) - hx,
math.ceil(round((box["y"] + box["h"]) * height, 9)) - hy, math.ceil(round((box["x"] + box["w"]) * width, 9)) - hx]
def _layout_prompt(prompt, meta, canvas, palette, boxes, width, height):
items = []
for box in boxes:
item = {"label": "object" if box["type"] == "panel" else box["type"], "caption": box["desc"]}
if box["type"] == "text":
item["text"] = box["text"]
if box["palette"]:
item["palette"] = box["palette"]
item["bbox"] = _moss_bbox(box, width, height)
items.append(item)
if not items:
return prompt
summary = {}
if meta:
summary["meta"] = meta
if canvas in CANVASES:
summary["canvas"] = canvas
summary["caption"] = prompt.strip()
if palette:
summary["palette"] = palette
layout = {"summary": summary, "items": items, "bbox_coord_space": "abs_centralized", "bbox_format": "yxyx"}
return json.dumps(layout, ensure_ascii=False, separators=(",", ":"))
def _ideogram_prompt(prompt, palette, boxes, fields):
# Same caption as Ideogram 4 Prompt Builder KJ: compact JSON, and every style key in order once a style is set.
fields = fields if isinstance(fields, dict) else {}
text = lambda key: str(fields.get(key) or "")
caption = {}
if prompt.strip():
caption["high_level_description"] = prompt.strip()
style = fields.get("style")
if style in ("photo", "art_style"):
style_description = {"aesthetics": text("aesthetics"), "lighting": text("lighting")}
if style == "photo":
style_description.update(photo=text("style_detail"), medium=text("medium"))
else:
style_description.update(medium=text("medium"), art_style=text("style_detail"))
if palette:
style_description["color_palette"] = palette
caption["style_description"] = style_description
caption["compositional_deconstruction"] = {"background": text("background"), "elements": build_elements(boxes)}
return json.dumps(caption, ensure_ascii=False, separators=(",", ":"))
def _format_prompt(output_format, prompt, meta, canvas, palette, boxes, width, height, ideogram=None, krea=None):
if output_format == "Ideogram":
return _ideogram_prompt(prompt, palette, boxes, ideogram)
if output_format == "Krea 2":
return _krea_prompt(prompt, boxes, krea)
if not boxes:
return prompt
return _layout_prompt(prompt, meta, canvas, palette, boxes, width, height)
def _one_line(text):
return " ".join(str(text or "").split())
def _krea_prompt(prompt, boxes, fields):
# Grounding DSL from jimmycarter/krea2-turbo-bbox PROMPTING.md: summary, @style; medium, ~background, one line per box.
fields = fields if isinstance(fields, dict) else {}
lines = []
if _one_line(prompt):
lines.append(_one_line(prompt))
style_line = "; ".join(part for part in (_one_line(fields.get("style")), _one_line(fields.get("medium"))) if part)
if style_line:
lines.append("@" + style_line)
if _one_line(fields.get("background")):
lines.append("~" + _one_line(fields.get("background")))
# Panels first, as in the training data; the rest keep the editor order.
for box in sorted(boxes, key=lambda b: b["type"] != "panel"):
bbox = ",".join(str(round(v * 1000)) for v in (box["x"], box["y"], box["x"] + box["w"], box["y"] + box["h"]))
if box["type"] == "character":
head = box.get("krea_tag", "pe") + (f":{box['char_id']}" if box.get("char_id") else "")
else:
head = {"panel": "p", "text": "t"}.get(box["type"], "o")
line = f"{head}[{bbox}]"
if box["type"] == "text":
escaped = box["text"].replace("\\", "\\\\").replace('"', '\\"').replace("\n", "\\n")
line += f'"{escaped}"'
if _one_line(box["desc"]):
line += " " + _one_line(box["desc"])
lines.append(line)
return "\n".join(lines)
def _fit_background(image, width, height):
samples = image[:1, :, :, :3].movedim(-1, 1)
return comfy.utils.common_upscale(samples, width, height, "lanczos", "center").movedim(1, -1)
def _manager_data(layout_prompt, state, width, height):
data = build_v2_recipe_data_from_prompt(prompt_text=layout_prompt, source="PromptLayoutBuilder")
data["models"]["model_a"]["resolution"].update(width=width, height=height)
data[LAYOUT_RECIPE_KEY] = {
**state,
"width": width,
"height": height,
"composer_prompts": [
{"box": index, **box["prompt_ref"]} for index, box in enumerate(state["boxes"], 1) if box.get("prompt_ref")
],
}
return data
def _pixel_frame(boxes, width, height):
# Pixel boxes carrying the metadata Create Bounding Boxes and Vantage read back.
frame = []
for box in boxes:
metadata = {"type": "text" if box["type"] == "text" else "obj", "text": box["text"], "desc": box["desc"],
"palette": box["palette"]}
if box["type"] == "character":
metadata["is_character"] = True
frame.append({**fractions_to_pixels(box, width, height), "metadata": metadata})
return [frame] if frame else []
def _percent_item(box):
item = {"label": box["type"], "caption": box["desc"]}
if box["type"] == "text":
item["text"] = box["text"]
if box["palette"]:
item["palette"] = box["palette"]
item["bbox"] = [round(v * 100, 1) for v in (box["y"], box["x"], box["y"] + box["h"], box["x"] + box["w"])]
return item
_SIZE_INPUT = {"default": 1024, "min": 16, "max": 16384, "step": 8,
"tooltip": "Canvas size the pixel boxes refer to, e.g. the layout builder's width/height outputs."}
class BboxConverter:
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"width": ("INT", _SIZE_INPUT),
"height": ("INT", _SIZE_INPUT),
"use_bboxes": ("BOOLEAN", {
"default": False,
"label_on": "bboxes",
"label_off": "layout_json",
"tooltip": "Input to convert when both are connected (shown only then).",
}),
},
"optional": {
"layout_json": ("STRING", {
"forceInput": True,
"tooltip": "Layout JSON (MOSS-native, percent or 0-1000 boxes), an Ideogram 4 caption or Krea 2 "
"grounding lines. Passed through to the layout_json output.",
}),
"bboxes": ("BOUNDING_BOX,ARRAY,STRING", {
"forceInput": True,
"tooltip": "Bounding boxes, Create Bounding Boxes elements, or their JSON.",
}),
},
}
RETURN_TYPES = ("STRING", "BOUNDING_BOX", "ARRAY")
RETURN_NAMES = ("layout_json", "bboxes", "elements")
FUNCTION = "convert"
CATEGORY = "Prompt Manager"
DESCRIPTION = ("Convert between a layout JSON and bounding boxes. Outputs the layout JSON (percent boxes when "
"converting bboxes), pixel bounding boxes and Create Bounding Boxes elements.")
def convert(self, width, height, use_bboxes=False, layout_json=None, bboxes=None):
if bboxes is not None and (use_bboxes or layout_json is None):
boxes = _boxes_from_bboxes(bboxes, width, height)
layout_json = json.dumps({"items": [_percent_item(box) for box in boxes], "bbox_coord_space": "percent",
"bbox_format": "yxyx"}, ensure_ascii=False, indent=2)
elif layout_json is not None:
boxes = _parse_text_layout(layout_json, width, height, "Bbox Converter: layout_json")["boxes"]
else:
raise ValueError("Bbox Converter: connect layout_json or bboxes.")
return (layout_json, _pixel_frame(boxes, width, height), build_elements(boxes))
class PromptLayoutBuilder:
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"aspect_ratio": ([REF_RATIO, *(ratio.value for ratio in ASPECT_RATIOS)], {
"default": "1:1 (Square)",
"tooltip": "Canvas aspect ratio. 'Use Reference Ratio' follows a layout restored from manager_data, "
"otherwise the connected image.",
}),
"megapixels": ("FLOAT", {
"default": 1.0, "min": 0.1, "max": 16.0, "step": 0.1,
"tooltip": "Target canvas size; width and height are rounded to multiples of 16.",
}),
"prompt": ("STRING", {
"multiline": True,
"default": "",
"placeholder": "Scene description (summary caption)",
"dynamicPrompts": False,
"tooltip": "Description of the whole image and its style.",
}),
"meta": ("STRING", {
"default": "",
"tooltip": "Comma-separated style tags for summary.meta, e.g. \"poster, graphic design\" (blank = omitted).",
}),
"canvas": (["none", *CANVASES], {
"default": "none",
"tooltip": "summary.canvas: single image, multi_panel or collage (none = omitted).",
}),
"use_import_json": ("BOOLEAN", {
"default": False,
"tooltip": "Read the layout from import_json and lock the editor. Turn off to edit the imported boxes.",
}),
"layout_data": ("STRING", {"default": "{}", "tooltip": "Editor boxes (managed by the node UI)."}),
"output_format": (list(OUTPUT_FORMATS), {
"default": "MOSS",
"tooltip": "Prompt format: MOSS-Image layout JSON, Ideogram 4 JSON caption or Krea 2 grounding lines.",
}),
},
"optional": {
"image": ("IMAGE", {"tooltip": "Background for the editor; also sets the ratio with 'Use Reference Ratio'."}),
"import_json": ("STRING,MANAGER_DATA", {
"forceInput": True,
"lazy": True,
"tooltip": "Layout JSON (e.g. from Prompt Generator: percent, 0-1000 or MOSS-native boxes), an "
"Ideogram 4 caption, Krea 2 grounding lines, or a saved "
"layout's manager_data from Library Manager. Only evaluated when use_import_json is on.",
}),
},
}
RETURN_TYPES = ("STRING", "IMAGE", "INT", "INT", "MANAGER_DATA")
RETURN_NAMES = ("prompt", "preview", "width", "height", "manager_data")
FUNCTION = "build"
CATEGORY = "Prompt Manager"
OUTPUT_NODE = True
DESCRIPTION = ("Draw layout boxes over a scene prompt, or load them from an LLM layout. "
"Outputs a MOSS-Image, Ideogram 4 or Krea 2 prompt.")
def check_lazy_status(self, use_import_json, **kwargs):
return ["import_json"] if use_import_json else []
def build(self, aspect_ratio, megapixels, prompt, meta, canvas, use_import_json, layout_data,
image=None, import_json=None, output_format="MOSS"):
saved = None
if use_import_json and isinstance(import_json, dict):
saved = import_json.get(LAYOUT_RECIPE_KEY)
if not isinstance(saved, dict):
raise ValueError("Prompt Layout Builder: this manager_data has no layout (it comes from Prompt Manager or Prompt Composer).")
text_import = use_import_json and isinstance(import_json, str) and import_json.strip()
if saved and saved.get("width") and saved.get("height"):
ref_size = (int(saved["width"]), int(saved["height"]))
elif image is not None:
ref_size = (int(image.shape[2]), int(image.shape[1]))
else:
ref_size = None
width, height = _resolution(aspect_ratio, megapixels, ref_size)
state = saved if saved else json.loads(layout_data or "{}")
boxes = [_clean_box(box) for box in state.get("boxes", []) if isinstance(box, dict)]
palette = _palette(state.get("palette"), SUMMARY_PALETTE_MAX)
ideogram = state.get("ideogram") if isinstance(state.get("ideogram"), dict) else {}
krea = state.get("krea") if isinstance(state.get("krea"), dict) else {}
meta_tags = _strs(meta)
ui = {}
if saved:
prompt = str(saved.get("prompt") or "")
meta_tags = _strs(saved.get("meta"))
canvas = saved.get("canvas") if saved.get("canvas") in CANVASES else "none"
elif text_import:
parsed = _parse_text_layout(import_json, width, height, "Prompt Layout Builder: import_json")
prompt, boxes = parsed.get("prompt", prompt), parsed["boxes"]
krea = parsed.get("krea", krea)
ideogram = parsed.get("ideogram", ideogram)
palette = parsed.get("palette", palette)
summary = (parsed.get("layout") or {}).get("summary")
if isinstance(summary, dict):
prompt = str(summary.get("caption") or "")
meta_tags = _strs(summary.get("meta"))
canvas = summary.get("canvas") if summary.get("canvas") in CANVASES else "none"
palette = _palette(summary.get("palette"), SUMMARY_PALETTE_MAX)
if saved or text_import:
ui["pm_layout_import"] = [{
"boxes": boxes, "palette": palette, "prompt": prompt, "meta": ", ".join(meta_tags), "canvas": canvas,
**({"ideogram": ideogram} if ideogram and (saved or text_import) else {}),
**({"krea": krea} if krea and (saved or text_import) else {}),
}]
ui["pm_layout_ref_size"] = list(ref_size) if ref_size else []
if image is None:
preview_bg = None
ui["pm_layout_background"] = []
else:
background = _fit_background(image, width, height)
preview_bg = Image.fromarray((background[0].cpu().numpy() * 255).clip(0, 255).astype(np.uint8))
ui["pm_layout_background"] = nodes.PreviewImage().save_images(background, "pm.layout.background")["ui"]["images"]
layout_prompt = _format_prompt(output_format, prompt, meta_tags, canvas, palette, boxes, width, height, ideogram, krea)
editor_state = {
"boxes": boxes, "palette": palette, "prompt": prompt, "meta": meta_tags, "canvas": canvas,
"aspect_ratio": aspect_ratio, "megapixels": megapixels, "ideogram": ideogram, "krea": krea,
}
return {
"ui": ui,
"result": (
layout_prompt,
render_preview(boxes, width, height, preview_bg),
width,
height,
_manager_data(layout_prompt, editor_state, width, height),
),
}
File diff suppressed because it is too large Load Diff
+272 -78
View File
@@ -4,32 +4,82 @@ import shutil
import time
import folder_paths
import server
from ..py.backup_manager import atomic_save, load_with_fallback, check_backup
def _safe_abspath(path):
return os.path.abspath(os.path.expanduser(path or ""))
def _normalize_export_path(raw_path):
candidate = _safe_abspath(raw_path)
if not candidate:
return ""
if not candidate.lower().endswith(".json"):
candidate = f"{candidate}.json"
return candidate
def _get_workflow_node(extra_pnginfo, node_id: str):
"""Find workflow node by id, including nested subgraphs (id chains like a:b:c)."""
if not isinstance(extra_pnginfo, dict):
return None
workflow = extra_pnginfo.get("workflow")
if not isinstance(workflow, dict):
return None
nodes_list = workflow.get("nodes", []) if isinstance(workflow.get("nodes"), list) else []
subgraphs = []
definitions = workflow.get("definitions")
if isinstance(definitions, dict):
maybe_subgraphs = definitions.get("subgraphs")
if isinstance(maybe_subgraphs, list):
subgraphs = maybe_subgraphs
found = None
for part in str(node_id).split(":"):
found = next((n for n in nodes_list if isinstance(n, dict) and str(n.get("id")) == part), None)
if not isinstance(found, dict):
return None
subgraph = next((sg for sg in subgraphs if isinstance(sg, dict) and str(sg.get("id")) == str(found.get("type"))), None)
if isinstance(subgraph, dict) and isinstance(subgraph.get("nodes"), list):
nodes_list = subgraph.get("nodes", [])
return found
def _patch_runtime_prompt_metadata(unique_id, output_text, extra_pnginfo=None, api_prompt=None):
"""Persist resolved prompt into workflow/api metadata for downstream save nodes."""
node_id = str(unique_id) if unique_id is not None else ""
if not node_id:
return
# Patch workflow metadata (EXTRA_PNGINFO).
workflow_node = _get_workflow_node(extra_pnginfo, node_id)
if isinstance(workflow_node, dict):
widgets = workflow_node.get("widgets_values")
if isinstance(widgets, list):
# PromptManager widgets order:
# [category, name, use_external, text]
if len(widgets) > 2:
widgets[2] = False
if len(widgets) > 3:
widgets[3] = output_text
# Patch API prompt metadata (PROMPT).
if isinstance(api_prompt, dict):
prompt_node = api_prompt.get(node_id)
if isinstance(prompt_node, dict):
inputs = prompt_node.get("inputs")
if isinstance(inputs, dict):
inputs["use_external"] = False
inputs["text"] = output_text
class PromptManager:
@staticmethod
def get_weekly_backup_path():
"""Get the path to the weekly rotating backup file."""
return PromptManager.get_prompts_path() + "_bak"
@staticmethod
def _refresh_weekly_backup_if_due(source_path, backup_path, interval_days=7):
"""Refresh backup only when missing or older than interval_days."""
if not os.path.exists(source_path):
return
should_refresh = not os.path.exists(backup_path)
if not should_refresh:
try:
age_seconds = time.time() - os.path.getmtime(backup_path)
should_refresh = age_seconds >= (interval_days * 24 * 60 * 60)
except Exception:
should_refresh = True
if should_refresh:
shutil.copy2(source_path, backup_path)
@classmethod
def INPUT_TYPES(s):
prompts_data = PromptManager.load_prompts()
@@ -57,7 +107,7 @@ class PromptManager:
"required": {
"category": (categories, {"default": first_category}),
"name": (all_prompts_list, {"default": first_prompt}),
"use_external": ("BOOLEAN", {"default": False, "label_on": "on", "label_off": "off", "tooltip": "Toggle to use LLM input instead of internal text"}),
"use_external": ("BOOLEAN", {"default": False, "tooltip": "Toggle to use LLM input instead of internal text"}),
"text": ("STRING", {"multiline": True, "default": first_prompt_text, "placeholder": "Enter prompt text", "dynamicPrompts": False, "tooltip": "Enter prompt text directly"}),
},
"optional": {
@@ -65,6 +115,8 @@ class PromptManager:
},
"hidden": {
"unique_id": "UNIQUE_ID",
"extra_pnginfo": "EXTRA_PNGINFO",
"api_prompt": "PROMPT",
}
}
@@ -89,7 +141,7 @@ class PromptManager:
@staticmethod
def get_default_prompts_path():
"""Get the path to the default prompts JSON file"""
return os.path.join(os.path.dirname(os.path.dirname(__file__)), "default_prompts.json")
return os.path.join(os.path.dirname(os.path.dirname(__file__)), "prompts", "default_prompts.json")
@classmethod
def load_prompts(cls):
@@ -97,32 +149,11 @@ class PromptManager:
user_path = cls.get_prompts_path()
default_path = cls.get_default_prompts_path()
if os.path.exists(user_path):
try:
with open(user_path, 'r', encoding='utf-8') as f:
return json.load(f)
except Exception as e:
print(f"[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 {}
check_backup(user_path)
data = load_with_fallback(user_path, "PromptManager")
if isinstance(data, dict):
return data
if os.path.exists(default_path):
try:
@@ -159,27 +190,9 @@ class PromptManager:
"""Save prompts to user folder"""
user_path = cls.get_prompts_path()
sorted_data = cls.sort_prompts_data(data)
tmp_path = user_path + ".tmp"
bak_path = cls.get_weekly_backup_path()
atomic_save(user_path, sorted_data, "PromptManager")
try:
os.makedirs(os.path.dirname(user_path), exist_ok=True)
# 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):
def get_prompt(self, category, name, use_external, text="", llm_input="", unique_id=None, extra_pnginfo=None, api_prompt=None):
"""Return the appropriate text based on use_external toggle and broadcast update"""
# Choose which text to use based on the toggle
@@ -196,9 +209,19 @@ class PromptManager:
"use_external": use_external,
"llm_input": llm_input if use_external else ""
})
# Save resolved runtime prompt into execution metadata so saver nodes
# embed the final prompt value, not the unresolved linked input state.
_patch_runtime_prompt_metadata(
unique_id=unique_id,
output_text=output_text,
extra_pnginfo=extra_pnginfo,
api_prompt=api_prompt,
)
return (output_text,)
def check_lazy_status(self, category, name, use_external, text, llm_input=None, unique_id=None):
def check_lazy_status(self, category, name, use_external, text, llm_input=None, unique_id=None,
extra_pnginfo=None, api_prompt=None, **kwargs):
needed = []
if use_external:
needed.append("llm_input")
@@ -250,6 +273,8 @@ async def save_prompt(request):
category = data.get("category", "").strip()
name = data.get("name", "").strip()
text = data.get("text", "").strip()
old_category = data.get("old_category", "").strip() or category
old_name = data.get("old_name", "").strip() or name
if not category or not name:
return server.web.json_response({"success": False, "error": "Category and name are required"})
@@ -259,18 +284,43 @@ async def save_prompt(request):
if category not in prompts:
prompts[category] = {}
source_prompts = prompts.get(old_category, {}) if isinstance(prompts.get(old_category), dict) else {}
target_prompts = prompts[category]
existing_data = {}
existing_old_name = None
if old_category in prompts:
existing_old_name = next((key for key in source_prompts.keys() if str(key).lower() == old_name.lower()), None)
if existing_old_name:
existing_data = source_prompts.get(existing_old_name, {})
target_conflict_name = next((key for key in target_prompts.keys() if str(key).lower() == name.lower()), None)
if target_conflict_name:
same_entry = (
existing_old_name is not None
and old_category == category
and str(target_conflict_name).lower() == str(existing_old_name).lower()
)
if not same_entry:
return server.web.json_response({
"success": False,
"error": f"A prompt named '{target_conflict_name}' already exists in '{category}'"
})
if existing_old_name and (old_category != category or existing_old_name != name):
existing_data = source_prompts.pop(existing_old_name, existing_data)
# Case-insensitive check - find if name exists with different casing
existing_prompts_lower = {k.lower(): k for k in prompts[category].keys()}
if name.lower() in existing_prompts_lower:
old_name = existing_prompts_lower[name.lower()]
if old_name != name:
casing_name = existing_prompts_lower[name.lower()]
if casing_name != name:
# Delete the old casing version
print(f"[PromptManager] Removing old casing '{old_name}' before saving as '{name}'")
del prompts[category][old_name]
print(f"[PromptManager] Removing old casing '{casing_name}' before saving as '{name}'")
del prompts[category][casing_name]
# 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", []),
@@ -281,6 +331,7 @@ async def save_prompt(request):
# 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})
@@ -289,6 +340,81 @@ async def save_prompt(request):
return server.web.json_response({"success": False, "error": str(e)}, status=500)
@server.PromptServer.instance.routes.post("/prompt-manager/rename-prompt")
async def rename_prompt(request):
"""API endpoint to rename or move a prompt"""
try:
data = await request.json()
category = data.get("category", "").strip()
old_name = data.get("old_name", "").strip()
new_name = data.get("new_name", "").strip()
new_category = data.get("new_category", "").strip() or category
if not category or not old_name or not new_name:
return server.web.json_response({"success": False, "error": "Category, old name, and new name are required"})
prompts = PromptManager.load_prompts()
if category not in prompts:
return server.web.json_response({"success": False, "error": "Prompt not found"})
if new_category not in prompts:
return server.web.json_response({"success": False, "error": f"Category '{new_category}' not found"})
source_prompts = prompts.get(category, {}) if isinstance(prompts.get(category), dict) else {}
target_prompts = prompts.get(new_category, {}) if isinstance(prompts.get(new_category), dict) else {}
existing_old_name = next((key for key in source_prompts.keys() if str(key).lower() == old_name.lower()), None)
if not existing_old_name:
return server.web.json_response({"success": False, "error": "Prompt not found"})
existing_target_name = next((key for key in target_prompts.keys() if str(key).lower() == new_name.lower()), None)
if existing_target_name:
same_entry = new_category == category and str(existing_target_name).lower() == str(existing_old_name).lower()
if not same_entry:
return server.web.json_response({
"success": False,
"error": f"A prompt named '{existing_target_name}' already exists in '{new_category}'"
})
entry = source_prompts.pop(existing_old_name)
target_prompts[new_name] = entry
PromptManager.save_prompts(prompts)
return server.web.json_response({"success": True, "prompts": prompts, "new_name": new_name, "new_category": new_category})
except Exception as e:
print(f"[PromptManager] Error in rename_prompt API: {e}")
return server.web.json_response({"success": False, "error": str(e)}, status=500)
@server.PromptServer.instance.routes.post("/prompt-manager/save-thumbnail")
async def save_thumbnail(request):
"""API endpoint to save or remove a thumbnail for a prompt"""
try:
data = await request.json()
category = data.get("category", "").strip()
name = data.get("name", "").strip()
thumbnail = data.get("thumbnail") # Can be None to remove thumbnail
if not category or not name:
return server.web.json_response({"success": False, "error": "Category and name required"})
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"})
# Update or remove thumbnail
if thumbnail:
prompts[category][name]["thumbnail"] = thumbnail
elif "thumbnail" in prompts[category][name]:
del prompts[category][name]["thumbnail"]
PromptManager.save_prompts(prompts)
return server.web.json_response({"success": True})
except Exception as e:
print(f"[PromptManager] Error in save_thumbnail API: {e}")
return server.web.json_response({"success": False, "error": str(e)}, status=500)
@server.PromptServer.instance.routes.post("/prompt-manager/delete-category")
async def delete_category(request):
"""API endpoint to delete a category"""
@@ -344,7 +470,7 @@ async def import_prompts(request):
try:
data = await request.json()
imported_data = data.get("data", {})
mode = data.get("mode", "merge")
mode = str(data.get("mode", "replace_existing") or "replace_existing").strip().lower()
if not isinstance(imported_data, dict):
return server.web.json_response({"success": False, "error": "Invalid data format"})
@@ -356,6 +482,9 @@ async def import_prompts(request):
else:
# Merge with existing prompts
prompts = PromptManager.load_prompts()
imported_prompts = 0
skipped_prompts = 0
created_categories = 0
for category, category_prompts in imported_data.items():
if not isinstance(category_prompts, dict):
@@ -363,18 +492,83 @@ async def import_prompts(request):
if category not in prompts:
prompts[category] = {}
created_categories += 1
for prompt_name, prompt_data in category_prompts.items():
if prompt_name == "__meta__":
if mode != "skip_existing" or "__meta__" not in prompts[category]:
prompts[category][prompt_name] = prompt_data
continue
if prompt_name in prompts[category] and mode == "skip_existing":
skipped_prompts += 1
continue
# 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}
else:
continue
imported_prompts += 1
PromptManager.save_prompts(prompts)
return server.web.json_response({"success": True, "prompts": prompts})
return server.web.json_response({
"success": True,
"prompts": prompts,
"imported_prompts": imported_prompts,
"skipped_prompts": skipped_prompts,
"created_categories": created_categories,
})
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)
@server.PromptServer.instance.routes.post("/prompt-manager/load-prompts-file")
async def load_prompts_file(request):
try:
data = await request.json()
file_path = _safe_abspath(data.get("path", ""))
if not file_path:
return server.web.json_response({"success": False, "error": "Path is required"})
if not os.path.isfile(file_path):
return server.web.json_response({"success": False, "error": "JSON file not found"}, status=404)
with open(file_path, "r", encoding="utf-8") as f:
loaded = json.load(f)
if not isinstance(loaded, dict):
return server.web.json_response({"success": False, "error": "Invalid JSON data format"}, status=400)
return server.web.json_response({"success": True, "data": loaded, "path": file_path})
except Exception as e:
print(f"[PromptManager] Error in load_prompts_file API: {e}")
return server.web.json_response({"success": False, "error": str(e)}, status=500)
@server.PromptServer.instance.routes.post("/prompt-manager/export-prompts-file")
async def export_prompts_file(request):
try:
data = await request.json()
export_path = _normalize_export_path(data.get("path", ""))
exported_data = data.get("data", {})
if not export_path:
return server.web.json_response({"success": False, "error": "Export path is required"})
if not isinstance(exported_data, dict):
return server.web.json_response({"success": False, "error": "Invalid data format"})
parent_dir = os.path.dirname(export_path)
if not parent_dir or not os.path.isdir(parent_dir):
return server.web.json_response({"success": False, "error": "Target folder does not exist"})
if not atomic_save(export_path, exported_data, "PromptManagerExport"):
return server.web.json_response({"success": False, "error": "Failed to save export file"}, status=500)
return server.web.json_response({"success": True, "path": export_path})
except Exception as e:
print(f"[PromptManager] Error in export_prompts_file API: {e}")
return server.web.json_response({"success": False, "error": str(e)}, status=500)
+46 -19
View File
@@ -1,7 +1,7 @@
"""
ComfyUI Workflow Builder
Extracts ALL generation parameters from an image/video, provides a full UI
for editing them, and outputs RECIPE_DATA (JSON) for the Workflow Renderer
for editing them, and outputs MANAGER_DATA (JSON) for the Workflow Renderer
render node.
Part of ComfyUI-Prompt-Manager — shares extraction logic with PromptExtractor.
@@ -35,6 +35,7 @@ from ..py.workflow_families import (
list_compatible_vaes,
list_compatible_clips,
)
from .recipe_renderer import _FAMILY_SAMPLER_DEFAULTS
from ..py.workflow_extraction_utils import (
extract_sampler_params,
extract_vae_info,
@@ -731,7 +732,7 @@ class WorkflowBuilder:
inputs to pre-fill parameters.
Widget order: Resolution → Model / VAE / CLIP → Prompts → Sampler → LoRAs
Outputs RECIPE_DATA (JSON string) for the Workflow Renderer render node.
Outputs MANAGER_DATA (JSON string) for the Workflow Renderer render node.
"""
# Class-level cache so models persist across executions.
@@ -755,8 +756,8 @@ class WorkflowBuilder:
"required": {},
"optional": {
# ── Connectable inputs ────────────────────────────────
"recipe_data": ("RECIPE_DATA", {
"tooltip": "Optional recipe_data input for prefill/update.",
"manager_data": ("MANAGER_DATA", {
"tooltip": "Optional manager_data input for prefill/update.",
}),
"pos_prompts": ("STRING", {
"default": "",
@@ -793,8 +794,8 @@ class WorkflowBuilder:
return f"Unsupported type for multi_lora_stack: {t}"
return True
RETURN_TYPES = ("RECIPE_DATA",)
RETURN_NAMES = ("recipe_data",)
RETURN_TYPES = ("MANAGER_DATA",)
RETURN_NAMES = ("manager_data",)
FUNCTION = "execute"
CATEGORY = "Prompt Manager"
OUTPUT_NODE = True
@@ -804,7 +805,7 @@ class WorkflowBuilder:
)
def execute(self,
recipe_data=None,
manager_data=None,
pos_prompt=None, neg_prompt=None,
seed=None, seed_a=None, seed_b=None, denoise=None,
lora_stack=None, lora_stack_a=None, lora_stack_b=None,
@@ -819,7 +820,7 @@ class WorkflowBuilder:
2. Apply JS overrides
3. Merge connected lora inputs (always)
4. Build recipe_data JSON
5. Return RECIPE_DATA
5. Return MANAGER_DATA
"""
# Backward-compat input mapping: route legacy scalar inputs to slot A.
if seed is not None and seed_a is None:
@@ -1054,12 +1055,12 @@ class WorkflowBuilder:
# ── Parse recipe_data input (if connected) ─────────────────────
wf_data = None
if recipe_data is not None:
if isinstance(recipe_data, dict):
wf_data = recipe_data
elif isinstance(recipe_data, str):
if manager_data is not None:
if isinstance(manager_data, dict):
wf_data = manager_data
elif isinstance(manager_data, str):
try:
wf_data = json.loads(recipe_data)
wf_data = json.loads(manager_data)
except (json.JSONDecodeError, TypeError):
print("[RecipeBuilder] Warning: could not parse recipe_data")
@@ -1593,6 +1594,32 @@ class WorkflowBuilder:
strategy = get_family_sampler_strategy(family_key)
# Apply family-specific sampler defaults when the user has not
# explicitly overridden the value in the UI. This prevents e.g. Krea 2
# from inheriting 20 steps / CFG 5.0 from an upstream SDXL workflow.
family_defaults = _FAMILY_SAMPLER_DEFAULTS.get(family_key, {})
sampler_override_keys = set()
if _allow_override('sampler'):
sampler_override_keys = {k for k in ['steps_a', 'steps_b', 'cfg', 'denoise',
'seed_a', 'seed_b', 'sampler_name', 'scheduler']
if k in overrides}
# Generic fallback values that indicate "unset / came from blank template".
_GENERIC_SAMPLER_DEFAULTS = {
'steps_a': 20,
'steps_b': None,
'cfg': 5.0,
'sampler_name': 'dpmpp_2m_sde',
'scheduler': 'karras',
}
for key, val in family_defaults.items():
if key in sampler_override_keys:
continue
current = sampler_params.get(key)
generic = _GENERIC_SAMPLER_DEFAULTS.get(key)
if current is None or current == generic:
sampler_params[key] = val
print(f"[RecipeBuilder] Family: {get_family_label(family_key)} "
f"(strategy={strategy}), model_a={model_name_a}, "
f"model_b={model_name_b or '—'}")
@@ -2632,16 +2659,16 @@ class WorkflowBuilder:
class RecipeBuilder(WorkflowBuilder):
RETURN_TYPES = ("RECIPE_DATA",)
RETURN_NAMES = ("recipe_data",)
RETURN_TYPES = ("MANAGER_DATA",)
RETURN_NAMES = ("manager_data",)
@classmethod
def INPUT_TYPES(cls):
return {
"required": {},
"optional": {
"recipe_data": ("RECIPE_DATA", {
"tooltip": "Optional recipe_data input for prefill/update.",
"manager_data": ("MANAGER_DATA", {
"tooltip": "Optional manager_data input for prefill/update.",
}),
"pos_prompts": ("STRING", {
"default": "",
@@ -2683,14 +2710,14 @@ class RecipeBuilder(WorkflowBuilder):
)
def execute(self,
recipe_data=None,
manager_data=None,
pos_prompts=None,
neg_prompts=None,
multi_lora_stack=None,
override_data="{}", lora_state="{}",
unique_id=None, extra_pnginfo=None, prompt=None):
result = super().execute(
recipe_data=recipe_data,
manager_data=manager_data,
pos_prompts=pos_prompts,
neg_prompts=neg_prompts,
multi_lora_stack=multi_lora_stack,
+4 -4
View File
@@ -320,8 +320,8 @@ class WorkflowModelLoader:
def INPUT_TYPES(cls):
return {
"required": {
"recipe_data": ("RECIPE_DATA", {
"tooltip": "Recipe data containing model name strings to load.",
"manager_data": ("MANAGER_DATA", {
"tooltip": "manager_data containing model name strings to load.",
"forceInput": True,
}),
"model": (["model_a", "model_b", "model_c", "model_d"], {
@@ -335,8 +335,8 @@ class WorkflowModelLoader:
}
}
def get_model(self, recipe_data, model="model_a", weight_dtype="default"):
workflow_data = recipe_data
def get_model(self, manager_data, model="model_a", weight_dtype="default"):
workflow_data = manager_data
selected_model_slot = model
if selected_model_slot not in ("model_a", "model_b", "model_c", "model_d"):
selected_model_slot = "model_a"
+9 -9
View File
@@ -205,7 +205,7 @@ class WorkflowRelay:
cls._VAE_ENUM = vaes
cls._CLIP_ENUM = clips
cls.RETURN_TYPES = (
"RECIPE_DATA",
"MANAGER_DATA",
"MODEL", "CLIP", "CONDITIONING", "CONDITIONING", "VAE", "LATENT", "IMAGE", "MASK", "*", "*",
"INT", "INT", "FLOAT",
cls._SAMPLER_ENUM, cls._SCHEDULER_ENUM, "FLOAT",
@@ -222,7 +222,7 @@ class WorkflowRelay:
return {
"required": {},
"optional": {
"recipe_data": ("RECIPE_DATA", {"forceInput": True, "tooltip": "Optional recipe_data input. If omitted, bridge starts from an empty payload dict."}),
"manager_data": ("MANAGER_DATA", {"forceInput": True, "tooltip": "Optional manager_data input. If omitted, bridge starts from an empty payload dict."}),
"model_slot": (_MODEL_KEYS, {"default": "model_a", "tooltip": "Select which model slot to read/update in recipe_data."}),
"model": ("MODEL", {"tooltip": "Pass-through Model"}),
"clip": ("CLIP", {"tooltip": "Pass-through CLIP"}),
@@ -254,7 +254,7 @@ class WorkflowRelay:
}
RETURN_TYPES = (
"RECIPE_DATA",
"MANAGER_DATA",
"MODEL", "CLIP", "CONDITIONING", "CONDITIONING", "VAE", "LATENT", "IMAGE", "MASK", "*", "*",
"INT", "INT", "FLOAT",
_LIVE_SAMPLERS, _LIVE_SCHEDULERS, "FLOAT",
@@ -265,7 +265,7 @@ class WorkflowRelay:
_LIVE_CKPTS, _LIVE_UNETS, _LIVE_VAES, _LIVE_CLIPS,
)
RETURN_NAMES = (
"recipe_data",
"manager_data",
"model", "clip", "positive", "negative", "vae", "latent", "image", "mask", "extra_1", "extra_2",
"seed", "steps", "cfg",
"sampler_name", "scheduler", "denoise",
@@ -284,7 +284,7 @@ class WorkflowRelay:
# ------------------------------------------------------------------
def unpack(self, recipe_data=None, model_slot="model_a", **kwargs):
def unpack(self, manager_data=None, model_slot="model_a", **kwargs):
def _normalize_lora_stack_input(raw_stack):
rows = []
if raw_stack is None:
@@ -386,13 +386,13 @@ class WorkflowRelay:
return os.path.splitext(base)[0]
# Accept both dict and JSON string
if isinstance(recipe_data, str):
if isinstance(manager_data, str):
try:
incoming_wf = json.loads(recipe_data)
incoming_wf = json.loads(manager_data)
except (json.JSONDecodeError, TypeError):
incoming_wf = {}
elif isinstance(recipe_data, dict):
incoming_wf = dict(recipe_data)
elif isinstance(manager_data, dict):
incoming_wf = dict(manager_data)
else:
incoming_wf = {}
+279 -25
View File
@@ -1,7 +1,7 @@
"""
Workflow Renderer — render-only node.
Accepts RECIPE_DATA (JSON string from Recipe Builder or PromptExtractor),
Accepts MANAGER_DATA (JSON string from Recipe Builder or PromptExtractor),
loads models, samples, decodes, and outputs IMAGE + LATENT.
No UI, no extraction — purely a render engine.
@@ -9,6 +9,7 @@ No UI, no extraction — purely a render engine.
import json
import math
import os
import re
import torch
import folder_paths
import comfy.model_management
@@ -40,7 +41,7 @@ from ..py.workflow_extraction_utils import (
resolve_vae_name,
resolve_clip_names,
)
from ..py.workflow_data_utils import strip_runtime_objects
from ..py.workflow_data_utils import ensure_v2_recipe_data, strip_runtime_objects
from ..py.lora_utils import resolve_lora_path
# Reuse the robust GGUF loading helper used by RecipeModelLoader when available.
@@ -51,18 +52,91 @@ except Exception:
# Keep renderer fallback sampler defaults aligned with Recipe Builder family defaults.
_FAMILY_SAMPLER_DEFAULTS = {
"ernie": {"steps_a": 4, "cfg": 1.0, "sampler": "euler_ancestral", "scheduler": "beta"},
"sdxl": {"steps_a": 20, "cfg": 5.0, "sampler": "dpmpp_2m_sde", "scheduler": "karras"},
"ernie": {"steps_a": 4, "cfg": 1.0, "sampler": "euler_ancestral", "scheduler": "beta"},
"flux1": {"steps_a": 20, "cfg": 1.0, "sampler": "euler", "scheduler": "simple"},
"flux2": {"steps_a": 4, "cfg": 1.0, "sampler": "euler", "scheduler": "simple"},
"zimage": {"steps_a": 9, "cfg": 1.0, "sampler": "euler", "scheduler": "simple"},
"krea2": {"steps_a": 9, "cfg": 1.0, "sampler": "euler", "scheduler": "simple"},
"ltxv": {"steps_a": 8, "cfg": 1.0, "sampler": "euler", "scheduler": "simple"},
"wan_image": {"steps_a": 8, "cfg": 1.0, "sampler": "lcm", "scheduler": "simple"},
"wan_video_t2v": {"steps_a": 2, "cfg": 1.0, "sampler": "lcm", "scheduler": "simple", "steps_b": 2},
"wan_video_i2v": {"steps_a": 2, "cfg": 1.0, "sampler": "lcm", "scheduler": "simple", "steps_b": 2},
"anima": {"steps_a": 10, "cfg": 1.0, "sampler": "er_sde", "scheduler": "simple"},
"qwen_image": {"steps_a": 10, "cfg": 1.0, "sampler": "euler", "scheduler": "simple"},
}
def _apply_family_sampler_defaults(primary_sampler, wf_sampler, family_key, log_prefix="[RecipeRenderer]"):
"""Apply family-specific sampler defaults unconditionally.
The renderer is the final consumer of MANAGER_DATA; family defaults are the
intended sampler configuration and always win over upstream template values
or Builder override_data — except for keys the caller marked as explicitly
user-set via `explicit_overrides` (e.g. the Prompt Manager thumbnail picker's
remembered step override).
"""
family_defaults = _FAMILY_SAMPLER_DEFAULTS.get(family_key, {})
if not family_defaults:
return primary_sampler, wf_sampler, False
merged = dict(wf_sampler) if isinstance(wf_sampler, dict) else {}
if isinstance(primary_sampler, dict):
merged.update(primary_sampler)
# Keys the caller flagged as explicitly chosen (not template defaults).
explicit = set()
for src in (wf_sampler, primary_sampler):
if not isinstance(src, dict):
continue
raw = src.get("explicit_overrides")
if isinstance(raw, str):
raw = [raw]
if isinstance(raw, (list, tuple, set)):
explicit |= {str(k).strip() for k in raw}
field_map = {
"steps_a": ("steps", "steps_a"),
"steps_b": ("steps_b",),
"cfg": ("cfg",),
"sampler": ("sampler_name", "sampler"),
"scheduler": ("scheduler",),
}
normalized = False
for family_key_default, source_keys in field_map.items():
family_val = family_defaults.get(family_key_default)
if family_val is None:
continue
if family_key_default in explicit:
continue
for src_key in source_keys:
if src_key not in merged:
continue
merged[src_key] = family_val
normalized = True
break
if normalized:
steps_disp = merged.get("steps", merged.get("steps_a"))
cfg_disp = merged.get("cfg")
sampler_disp = merged.get("sampler_name", merged.get("sampler"))
scheduler_disp = merged.get("scheduler")
print(
f"{log_prefix} Applied family sampler defaults for '{family_key}' "
f"to steps={steps_disp}, cfg={cfg_disp}, sampler={sampler_disp}, scheduler={scheduler_disp}"
)
if isinstance(primary_sampler, dict):
for k in list(primary_sampler.keys()):
if k in merged:
primary_sampler[k] = merged[k]
if isinstance(wf_sampler, dict):
for k in list(wf_sampler.keys()):
if k in merged:
wf_sampler[k] = merged[k]
return primary_sampler, wf_sampler, normalized
# Runtime caches for non-checkpoint components reused across repeated renders.
_class_vae_cache = {}
_class_clip_cache = {}
@@ -129,11 +203,16 @@ def _resolve_wan_family_hint(models, selected_slot, fallback_family=""):
return str(fallback_family or "")
def _legacy_recipe_to_v2(workflow_data):
"""Normalize recipe_data via shared canonical converter used across Prompt Manager."""
return ensure_v2_recipe_data(workflow_data, source="RecipeRenderer")
class WorkflowRenderer:
"""
Render-only generation node.
Takes RECIPE_DATA (from Workflow Builder or PromptExtractor),
Takes MANAGER_DATA (from Workflow Builder or PromptExtractor),
loads models, applies LoRAs, samples, decodes.
Outputs IMAGE + LATENT.
"""
@@ -144,13 +223,9 @@ class WorkflowRenderer:
def INPUT_TYPES(cls):
return {
"required": {
"recipe_data": ("RECIPE_DATA", {
"manager_data": ("MANAGER_DATA", {
"forceInput": True,
"tooltip": "Connect recipe_data from Recipe Builder or PromptExtractor",
}),
"model_slot": (_MODEL_KEYS, {
"default": "model_a",
"tooltip": "Select which model slot to render from in recipe_data.",
"tooltip": "Connect manager_data from Recipe Builder, Recipe Extractor or Library Manager",
}),
"clear_cache_after_render": ("BOOLEAN", {
"default": False,
@@ -158,6 +233,12 @@ class WorkflowRenderer:
}),
},
"optional": {
# Compatibility: allow API callers/workflows that omit model_slot.
# execute() already defaults to model_a when not provided.
"model_slot": (_MODEL_KEYS, {
"default": "model_a",
"tooltip": "Select which model slot to render from in recipe_data.",
}),
"source_image": ("IMAGE", {
"tooltip": "Input image for WAN Video i2v (image-to-video) generation.",
}),
@@ -167,19 +248,19 @@ class WorkflowRenderer:
},
}
RETURN_TYPES = ("RECIPE_DATA", "IMAGE", "LATENT")
RETURN_NAMES = ("recipe_data", "output_image", "output_latent")
RETURN_TYPES = ("IMAGE", "LATENT", "MANAGER_DATA")
RETURN_NAMES = ("output_image", "output_latent", "manager_data")
FUNCTION = "execute"
CATEGORY = "Prompt Manager"
OUTPUT_NODE = False
DESCRIPTION = (
"Render-only node. Accepts recipe_data, loads models, samples, "
"and decodes. Outputs IMAGE + LATENT + RECIPE_DATA "
"Render-only node. Accepts manager_data, loads models, samples, "
"and decodes. Outputs IMAGE + LATENT + MANAGER_DATA "
"(with MODEL/CLIP/VAE passthrough)."
)
@classmethod
def IS_CHANGED(cls, recipe_data, source_image=None, **kwargs):
def IS_CHANGED(cls, manager_data, source_image=None, **kwargs):
"""Return a slot-aware fingerprint so unrelated slot edits do not force rerender."""
import hashlib
import json as _json
@@ -205,18 +286,19 @@ class WorkflowRenderer:
h.update(str(clear_cache_after_render).encode())
wf = None
if isinstance(recipe_data, dict):
wf = recipe_data
elif isinstance(recipe_data, str):
if isinstance(manager_data, dict):
wf = manager_data
elif isinstance(manager_data, str):
try:
wf = json.loads(recipe_data)
wf = json.loads(manager_data)
except Exception:
wf = None
h.update(recipe_data.encode())
h.update(manager_data.encode())
else:
h.update(str(type(recipe_data)).encode())
h.update(str(type(manager_data)).encode())
if isinstance(wf, dict):
wf = _legacy_recipe_to_v2(wf)
wf_sampler = wf.get("sampler", {}) if isinstance(wf.get("sampler"), dict) else {}
wf_res = wf.get("resolution", {}) if isinstance(wf.get("resolution"), dict) else {}
primary_sampler = {}
@@ -351,8 +433,8 @@ class WorkflowRenderer:
except Exception as e:
print(f"[RecipeRenderer] CUDA cache clear failed: {e}")
def execute(self, recipe_data, model_slot="model_a", clear_cache_after_render=False, source_image=None, unique_id=None):
workflow_data = recipe_data
def execute(self, manager_data, model_slot="model_a", clear_cache_after_render=False, source_image=None, unique_id=None):
workflow_data = manager_data
# ── Parse workflow_data ───────────────────────────────────────────
if isinstance(workflow_data, dict):
@@ -365,6 +447,7 @@ class WorkflowRenderer:
else:
raise ValueError(f"[RecipeRenderer] Invalid workflow_data type: {type(workflow_data)}")
wf = _legacy_recipe_to_v2(wf)
wf_out = dict(wf)
if not (int(wf.get("version", 0) or 0) >= 2 and isinstance(wf.get("models"), dict)):
@@ -476,6 +559,18 @@ class WorkflowRenderer:
_family_spec = MODEL_FAMILIES.get(family_key, {})
_family_is_ckpt = _family_spec.get('checkpoint', False)
# ── Family-specific sampler defaults ──────────────────────────────
# Always apply the family's intended sampler configuration. The renderer
# is the final consumer of MANAGER_DATA, so upstream template or Builder
# override_data values are replaced with the family defaults.
primary_sampler, wf_sampler, _ = _apply_family_sampler_defaults(
primary_sampler, wf_sampler, family_key
)
if primary is not None:
primary["sampler"] = dict(primary_sampler)
if isinstance(wf, dict):
wf["sampler"] = dict(wf_sampler)
# ── Family defaults for VAE/CLIP when upstream data is incomplete ──
clip_is_placeholder = bool(clip_names) and all(
(not n) or str(n).startswith('(') for n in clip_names
@@ -740,9 +835,15 @@ class WorkflowRenderer:
if family_key == "zimage":
decoded, out_latent = _render_zimage(**render_args)
elif family_key == "krea2":
decoded, out_latent = _render_krea2(**render_args)
elif family_key == "qwen_image":
decoded, out_latent = _render_qwen_image(**render_args)
elif family_key == "anima":
decoded, out_latent = _render_anima(**render_args)
elif family_key == "flux1":
decoded, out_latent = _render_flux1(**render_args)
@@ -880,7 +981,39 @@ class WorkflowRenderer:
if clear_cache_after_render:
self._clear_cached_models()
return (wf_out, decoded, out_latent)
return (decoded, out_latent, wf_out)
def _extract_expression_block(positive_prompt):
"""
Split a prompt into base prompt and an optional trailing expression block.
The expression block is everything from the last 'expression:' (case-insensitive,
whole-line or standalone) to the end. Returns (base_prompt, expression_text).
"""
text = str(positive_prompt or "")
# Match 'expression:' as a whole word at the start of a line or after whitespace,
# so it does not catch words like "photo expressionism".
match = None
for m in re.finditer(r"(?:^|\s)expression\s*:", text, flags=re.IGNORECASE):
match = m
if not match:
return text, ""
base = text[:match.start()].rstrip()
expr = text[match.end():].lstrip()
return base, expr
def _promote_expression_prompt(positive_prompt):
"""
If the prompt contains a trailing 'expression:' block, move it to the top of
the prompt separated by a blank line. This gives the expression the highest
attention during CLIP encoding.
"""
base, expr = _extract_expression_block(positive_prompt)
if not expr:
return positive_prompt
return f"expression: {expr}\n\n{base}"
def _encode_text_conditioning(clip, positive_prompt, negative_prompt):
@@ -892,7 +1025,7 @@ def _encode_text_conditioning(clip, positive_prompt, negative_prompt):
return None, None
try:
tokens_pos = clip.tokenize(str(positive_prompt or ""))
tokens_pos = clip.tokenize(_promote_expression_prompt(str(positive_prompt or "")))
cond_pos = clip.encode_from_tokens_scheduled(tokens_pos)
except Exception as e:
print(f"[RecipeRenderer] Failed to encode positive conditioning: {e}")
@@ -1035,6 +1168,8 @@ def _load_clip(clip_info, overrides, existing_clip=None):
clip_type = comfy.sd.CLIPType.QWEN_IMAGE # Qwen2.5-VL image encoder
elif t and 'lumina2' in t:
clip_type = comfy.sd.CLIPType.LUMINA2 # z-image / Lumina2 encoder
elif t and 'krea2' in t:
clip_type = getattr(comfy.sd.CLIPType, "KREA2", comfy.sd.CLIPType.LUMINA2)
else:
clip_type = comfy.sd.CLIPType.STABLE_DIFFUSION
@@ -1394,6 +1529,36 @@ def _render_sdxl(model, clip, vae, pos_prompt, neg_prompt,
return decoded, latent_out
def _render_anima(model, clip, vae, pos_prompt, neg_prompt,
width, height, batch, sampler_params,
input_latent=None,
loras_a=None, lora_overrides=None, lora_stack_key=''):
"""
Anima render path matching the provided reference workflow.
Uses a plain stable-diffusion CLIP loader, EmptyLatentImage-compatible
latent, and standard KSampler settings without forcing SDXL clip_layer(-2).
"""
if loras_a:
model, clip = _apply_loras(
model, clip, loras_a, lora_overrides or {}, stack_key=lora_stack_key
)
tokens_pos = clip.tokenize(pos_prompt)
cond_pos = clip.encode_from_tokens_scheduled(tokens_pos)
tokens_neg = clip.tokenize(neg_prompt)
cond_neg = clip.encode_from_tokens_scheduled(tokens_neg)
use_input_latent = isinstance(input_latent, dict) and ("samples" in input_latent)
latent = input_latent if use_input_latent else _make_latent(4, width, height, batch=batch)
denoise = float(sampler_params.get("denoise", 1.0)) if use_input_latent else 1.0
latent_out = _run_standard_ksampler(
model, cond_pos, cond_neg, latent, sampler_params, denoise_override=denoise
)
decoded = _decode_latent_output(vae, latent_out, tag="_render_anima")
return decoded, latent_out
def _render_qwen_image(model, clip, vae, pos_prompt, neg_prompt,
width, height, batch, sampler_params,
input_latent=None,
@@ -1610,6 +1775,95 @@ def _render_zimage(model, clip, vae, pos_prompt, neg_prompt,
return decoded, latent_out
def _render_krea2(model, clip, vae, pos_prompt, neg_prompt,
width, height, batch, sampler_params,
input_latent=None,
loras_a=None, lora_overrides=None, lora_stack_key=''):
"""
Krea2 render path — mirrors Z-Image/AuraFlow but uses the krea2 CLIP type.
Automatically appends a Krea2 uncensor/refusal-reduction LoRA if available.
"""
from comfy_extras.nodes_sd3 import EmptySD3LatentImage
# ── Auto-apply a Krea2 uncensor/refusal-reduction LoRA if present ─────
krea_uncensor_loras = [
"Krea2_TextFusion_Refusal_Reduction.safetensors",
"krea2filterbypass3.safetensors",
"skc3vo.safetensors",
"MysticXXX_KREA2_v2_stripped.safetensors",
"snofs_krea_v1_nostrip.safetensors",
]
resolved_uncensor = None
for candidate in krea_uncensor_loras:
lora_path, available = resolve_lora_path(candidate)
if available:
resolved_uncensor = candidate
break
effective_loras = list(loras_a) if loras_a else []
effective_overrides = dict(lora_overrides) if lora_overrides else {}
if resolved_uncensor:
# Determine special strengths for specific LoRAs.
uncensor_model_strength = 1.0
uncensor_clip_strength = 1.0
basename_lower = os.path.basename(resolved_uncensor).lower()
if basename_lower == "krea2filterbypass3.safetensors":
uncensor_model_strength = 2.0
uncensor_clip_strength = 2.0
elif basename_lower == "skc3vo.safetensors":
uncensor_model_strength = 0.2
uncensor_clip_strength = 0.2
effective_loras.append({
"name": resolved_uncensor,
"active": True,
"model_strength": uncensor_model_strength,
"clip_strength": uncensor_clip_strength,
})
stack_prefix = f"{lora_stack_key}:" if lora_stack_key else ""
effective_overrides[f"{stack_prefix}{resolved_uncensor}"] = {
"active": True,
"model_strength": uncensor_model_strength,
"clip_strength": uncensor_clip_strength,
}
print(f"[RecipeRenderer] Auto-applying Krea2 uncensor LoRA: {resolved_uncensor} "
f"(model={uncensor_model_strength:.2f}, clip={uncensor_clip_strength:.2f})")
if effective_loras:
model, clip = _apply_loras(
model, clip, effective_loras, effective_overrides, stack_key=lora_stack_key
)
tokens_pos = clip.tokenize(pos_prompt)
cond_pos = clip.encode_from_tokens_scheduled(tokens_pos)
tokens_neg = clip.tokenize(neg_prompt)
cond_neg = clip.encode_from_tokens_scheduled(tokens_neg)
model = _patch_model_sampling_auraflow(
model, shift=float(sampler_params.get("shift", 3.0))
)
use_input_latent = isinstance(input_latent, dict) and ("samples" in input_latent)
if use_input_latent:
latent = input_latent
else:
latent_node = EmptySD3LatentImage()
if hasattr(latent_node, "generate"):
latent = latent_node.generate(width=width, height=height, batch_size=batch)[0]
else:
latent = _extract_node_outputs(
EmptySD3LatentImage.execute(width=width, height=height, batch_size=batch)
)[0]
denoise = float(sampler_params.get("denoise", 1.0)) if use_input_latent else 1.0
latent_out = _run_standard_ksampler(
model, cond_pos, cond_neg, latent, sampler_params, denoise_override=denoise
)
decoded = _decode_latent_output(vae, latent_out, tag="_render_krea2")
return decoded, latent_out
def _render_wan_image(model, clip, vae, pos_prompt, neg_prompt,
width, height, batch, sampler_params,
input_latent=None,
@@ -0,0 +1,222 @@
# Video Prompt Writing Guide (T2VA / I2VA / FL2VA / L2VA)
## 1. Task Overview
- **T2VA**: Builds a complete audiovisual timeline from text.
- **I2VA**: T2VA body + first-frame instruction + a visual path that develops forward from the first frame.
- **FL2VA**: T2VA body + first-and-last-frame instruction + a continuous path from the first frame to the last frame.
- **L2VA**: T2VA body + last-frame instruction + a path that converges from a plausible preceding state to the last frame.
## 2. Final Prompt Structure
### 2.1 Part One Is the Instruction
**T2VA** has no image-alignment instruction and begins directly with the three core fields.
**I2VA** always uses:
```text
For the target video, at 0.00 seconds into the target video, <Picture 1> (from [Shot 1]) is fully referenced.
```
**FL2VA** always uses:
```text
How the reference pictures align with the target video — Picture 1 (from Shot 1) aligns with the 0.00-second mark of the target video; Picture 2 (from Shot N) aligns with the S.SS-second mark of the target video.
```
**L2VA** always uses:
```text
How the reference pictures align with the target video — <Picture 1> (from [Shot N]) aligns with the S.SS-second mark of the target video.
```
Here, `N` is the index of the actual final shot, and `S.SS` is the effective video duration formatted to exactly two decimal places. The instruction must be the first line of the final prompt, followed by one blank line before the core fields.
### 2.2 Part Two Contains the Three Core Fields
```text
integrated_multimodal_description: [Shot 1] ...
overall_soundscape: ...
non_diegetic_music: ...
```
- **integrated_multimodal_description**: Describes visuals, actions, shots, speakers, dialogue, singing, and diegetic audio along the timeline.
- **overall_soundscape**: Summarizes ambient sound, physical action sounds, and non-verbal human sounds across the entire video.
- **non_diegetic_music**: Describes background music that the characters cannot hear and only the audience can hear.
## 3. How to Incorporate Keyframes into the Multimodal Description
### 3.1 I2VA: Begin from the Image and Develop Forward
`<Picture 1>` is the actual first frame of the video at 0.00 seconds and belongs to `[Shot 1]`. The description should first establish the style, subjects, composition, and scene anchors in the image, then describe the next action. Character identity, clothing, colors, key objects, and spatial relationships should remain consistent.
Recommended structure: **first-frame anchor → action onset → continuous development → result or reaction**.
### 3.2 FL2VA: Describe the Path Between the First and Last Frames
Picture 1 is the opening, and Picture 2 is the ending. Focus on how the subject moves, how poses change, how objects are manipulated, how the composition evolves, and how the scene or lighting transitions.
FL2VA generally favors a single shot so the model can interpolate continuously from the first frame to the last frame. Use multiple shots only when they are explicitly specified. The last frame must be reached by the final `[Shot N]` at the end of the video.
Recommended structure: **first-frame state → observable intermediate changes → progressively narrowing differences → last-frame state**.
### 3.3 L2VA: Infer the Opening and Land on the Image at the End
`<Picture 1>` is the final frame of the video and belongs to the last `[Shot N]`; it does not inherently belong to Shot 1. Infer a plausible earlier state from the user's intent and the last frame, then describe how the characters, objects, camera, and scene gradually approach the reference image.
Recommended structure: **plausible preceding state → explicit action and transition path → gradual convergence in the final shot → last-frame landing**.
## 4. How to Write the Three Shared Core Sections
### 4.1 Develop the Multimodal Description Along the Timeline
`integrated_multimodal_description` is the main body of the rewritten prompt. Every detail should correspond to something visible or audible: visual style, initial composition, subject appearance and position, scene and key props, actions and reactions, shot changes, spoken language, and synchronized diegetic sound.
At the beginning of `[Shot 1]`, state the overall style and initial composition. Common styles include `Cinematic`, `live-action`, `2D-animated`, `3D CG`, `claymation`, `watercolor`, and `vintage film`. For keyframe tasks, derive the style from the reference image; for T2VA, select it from the user's text.
```text
[Shot 1] Live-action, cinematic, a medium-wide shot frames...
```
### 4.2 Shots and Cuts
Do not add a timestamp to the first shot. Use sequential shot numbers for later shots, and begin each one with a strictly increasing cut time that falls within the video duration:
```text
[Shot 2] At 00:03.500, the camera cuts to...
```
For ordinary cuts, use `the camera cuts to`, `the shot cuts to`, `the shot transitions to`, `the shot changes to`, or `the shot switches to`. When explicitly requested by the user, cross-dissolve, fade, or wipe may also be used. A cut should introduce new information about the subject, space, state, viewpoint, or time. If only the distance or a slight angle needs to change, prefer camera motion.
### 4.3 Camera Motion: Motion Type + Amplitude + Speed
A complete camera-motion expression has three dimensions: the **motion type** defines how the camera moves, **amplitude** defines the range of compositional change, and **speed** defines the pacing of that change. Add amplitude and speed only when they are meaningful; medium amplitude and normal speed are usually omitted.
| Dimension | Available Expression | Description |
|-|-|-|
| Motion type | `Zoom In / Zoom Out` | The focal length changes while the camera body remains stationary |
| Motion type | `Push In / Pull Out` | The camera moves forward / backward |
| Motion type | `Pan Left / Pan Right` | The camera remains in place while the lens pivots horizontally |
| Motion type | `Truck Left / Truck Right` | The camera translates horizontally |
| Motion type | `Tilt Up / Tilt Down` | The camera remains in place while the lens pivots vertically |
| Motion type | `Pedestal Up / Pedestal Down` | The entire camera moves upward / downward |
| Motion type | `Arc Shot` | The camera moves in an arc around the subject |
| Motion type | `Tracking Shot` | The camera follows a moving subject |
| Motion type | `Static Shot` | The camera position and lens remain still |
| Motion type | `Shake Slightly / Shake Strongly` | Slight / strong camera shake |
| Motion type | `POV` | The subject's point of view |
| Motion type | `Roll Clockwise / Roll Counterclockwise` | The camera rolls clockwise / counterclockwise around the lens axis |
| Amplitude | `with small amplitude` | Small-range change |
| Amplitude | `with large amplitude` | Large-range change |
| Speed | `at slow speed` | Slow movement |
| Speed | `at fast speed` | Fast movement |
Camera motion should be written as a natural English action within the shot, rather than stacked as separate labels at the end of a sentence:
```text
The camera pushes in with small amplitude at slow speed toward the folded letter in her hands.
The camera pans right with large amplitude at fast speed, revealing the open doorway.
The camera holds a static shot as the runner exits the frame.
```
### 4.4 Speakers, Dialogue, and Singing
Subjects who speak, sing, or produce an off-screen human voice use stable IDs such as `(S1)` and `(S2)`. When multiple already-numbered speakers speak or sing together, use a compound ID such as `(S1,S2)`. A speaker keeps the same ID across shots; characters who never vocalize receive no speaker ID.
When a speaker first appears, provide enough information from the visual and audio context to establish a stable identity, such as character type, age, gender, whether the person is on-screen, pitch, timbre, speaking rate, or accent. Place the speaker's identifying phrase, ID, action, and delivery outside `<d>`. Inside `<d>`, include only the language tag and the actual user-provided spoken content. Preserve every original word and punctuation mark verbatim; do not translate or rewrite them.
```text
The young woman with a quiet, breathy voice (S1) says: <d>[English] I get off at the next station.</d>
The two children (S1,S2) shout together, <d>[English] Wait for us!</d>
```
For voiceover, use the exact phrase `says in an off-screen voiceover`. Immediately after every voiceover `<d>` block, state that the corresponding on-screen character's lips remain closed:
```text
The man (S1) says in an off-screen voiceover: <d>[English] I still remember that road.</d> while his lips remain completely closed.
```
When the same line of dialogue or lyrics crosses a cut, use `<scenetrans>` at the connecting points in both parts and explicitly state that the audio continues across the cut. Use `<cutoff>` when speech is truncated by the end of the video. Continuity may be expressed with `continues seamlessly across the cut`, `continues uninterrupted into the next shot`, `carries over from the previous shot`, or `remains audible across the transition`.
### 4.5 On-Screen Text
Place any banner, sign, label, subtitle, or neon text that is actually visible on screen in English double quotation marks. Preserve the original text and punctuation verbatim, without translation.
```text
A red neon sign reading "营业中" glows above the doorway.
```
### 4.6 overall_soundscape
Use 1–4 English sentences in one continuous paragraph to summarize the ambient sound, physical action sounds, and non-verbal human sounds across the full video, such as wind, rain, traffic, footsteps, fabric movement, impacts, breathing, laughter, or panting. Dialogue, singing, and diegetic music already belong in the multimodal description and should not be repeated here. Use `N/A` only when the user explicitly requests complete silence throughout the video.
```text
overall_soundscape: Steady rain taps against the café windows while low room ambience continues underneath. The entrance bell rings once, followed by wet footsteps and the soft scrape of a chair.
```
### 4.7 non_diegetic_music
Use 1–3 English sentences to describe background music that the characters cannot hear and only the audience can hear. Focus on instrumentation, speed, rhythm, and dynamic changes; do not use abstract mood words or explain the emotional function of the score. Singing, instruments, radio, television, or phone music audible to the characters are diegetic events and should appear in the multimodal description. Use `N/A` when there is no non-diegetic music.
```text
non_diegetic_music: Sparse piano notes at a slow tempo, joined by sustained low strings that gradually increase in volume before fading out.
```
## 5. Cases
### Case 1: T2VA
With no reference image, construct the complete timeline directly from the text. You may add scene, character, action, and sound details that remain consistent with the user's intent.
```text
integrated_multimodal_description: [Shot 1] Live-action, cinematic, a medium-wide shot frames a baker opening the shutters of a small street bakery before sunrise. The camera pushes in with small amplitude at slow speed as the middle-aged baker with a calm, slightly raspy voice (S1) places a fresh loaf on the wooden counter and says: <d>[English] First batch of the morning.</d> [Shot 2] At 00:05.000, the camera cuts to a close-up of steam rising from the sliced bread while the baker's final words carry over from the previous shot.
overall_soundscape: Wooden shutters scrape open over a quiet street as trays clink softly inside the bakery. The doorbell rings once, followed by light footsteps and the crisp sound of bread being sliced.
non_diegetic_music: A soft acoustic-guitar pattern at a moderate tempo, joined by sparse upright-bass notes and a gentle fade at the end.
```
### Case 2: I2VA
Write the first-frame instruction first, then use the subject, composition, and scene in Picture 1 as the starting point of Shot 1 before describing how the scene continues to develop.
```text
For the target video, at 0.00 seconds into the target video, <Picture 1> (from [Shot 1]) is fully referenced.
integrated_multimodal_description: [Shot 1] Live-action, cinematic, the young woman shown in <Picture 1> remains beside the rain-covered train window, preserving her appearance, clothing, seat position, and the carriage layout. The camera trucks right with small amplitude at slow speed as she lifts her gaze from the folded letter toward the passing city lights. Her reflection moves across the glass while the quiet, breathy young woman (S1) says: <d>[English] I get off at the next station.</d> She folds the letter along its existing crease.
overall_soundscape: The train wheels produce a steady metallic rhythm beneath a low ventilation hum. Rain ticks against the window while paper rustles softly in her hands.
non_diegetic_music: Sustained cello notes at a slow tempo with widely spaced piano tones, gradually decreasing in volume.
```
### Case 3: FL2VA
The two images anchor the opening and ending respectively. The body should not repeat two static image descriptions; instead, it should supply the motion path that connects them. The following example is an eight-second single shot.
```text
How the reference pictures align with the target video — Picture 1 (from Shot 1) aligns with the 0.00-second mark of the target video; Picture 2 (from Shot 1) aligns with the 8.00-second mark of the target video.
integrated_multimodal_description: [Shot 1] Live-action, cinematic, a rain-soaked cyclist begins in the position and framing established by Picture 1, holding a closed black umbrella beside a silver bicycle. The camera pulls out with small amplitude at slow speed as she releases the bicycle handle, raises the umbrella above her shoulder, and presses the runner upward until the canopy opens. Water rolls from the expanding fabric while she steps beneath it, rotates the handle into the final angle, and settles into the pose, spacing, and composition established by Picture 2 at the end of the shot.
overall_soundscape: Rain falls steadily on the pavement, followed by the metallic click of the umbrella runner and the soft snap of the canopy opening. Water drips from the bicycle frame as distant traffic passes.
non_diegetic_music: N/A
```
### Case 4: L2VA
The image anchors only the final moment. First establish a compatible earlier state, then let the actions, object states, and composition gradually land on Picture 1 in the final shot. The following example is a six-second single shot.
```text
How the reference pictures align with the target video — <Picture 1> (from [Shot 1]) aligns with the 6.00-second mark of the target video.
integrated_multimodal_description: [Shot 1] Live-action, cinematic, a close shot begins with an intact drinking glass near the edge of a dark wooden table, while the same hand and sleeve visible in <Picture 1> approach from the right. The camera pushes in with small amplitude at slow speed as the fingertips strike the rim. The glass tips, falls, and hits the floor with a sharp impact; cracks spread through it as fragments slide outward. Toward the end, the moving pieces lose momentum and settle into the exact broken arrangement, hand position, camera angle, lighting, and final composition established by <Picture 1>.
overall_soundscape: Fingertips tap the glass before it scrapes across the tabletop, falls, and breaks with a sharp crash. Small fragments scatter and gradually stop sliding across the floor.
non_diegetic_music: A low electronic pulse at a slow tempo, ending immediately after the glass breaks.
```
@@ -0,0 +1,341 @@
# Full-Reference Mode Rewrite Output Format Guide
This guide explains how rewrite outputs are organized and written in full-reference mode.
Write all six rewrite sections in English. Preserve the original language only for dialogue and lyrics inside `<d>` and for text visibly present in the scene.
**Description detail:** Make `detailed_description` as detailed and explicit as possible. For each shot, clearly establish the current composition, subject appearance and position, environment and lighting, actions and state changes, camera movement, current sound, and the points where referenced content actually appears or takes effect. Avoid reducing the description to a plot summary or a list of reference relationships.
> The basic formats for shots, camera movement, speakers, dialogue, and ordinary sound are shared with the Video Prompt Writing Guide (T2VA / I2VA / FL2VA / L2VA). This guide focuses on the reference labels, analysis sections, and format differences specific to full-reference mode.
## 1. Overall Structure
A complete rewrite output consists of six sections in the following order:
| Section | Purpose |
| --- | --- |
| `subject_definitions` | Defines referenced content and its reference labels |
| `summary` | Summarizes the task type, target video, and main reference relationships |
| `retention_analysis` | Describes how referenced content is preserved, transferred, or reused |
| `detailed_description` | Describes visuals, actions, shots, sound, and dialogue in playback order |
| `overall_soundscape` | Summarizes ambience and physical sounds |
| `non_diegetic_music` | Describes background music audible only to the audience |
## 2. Reference Labels and Definitions (`subject_definitions`)
Full-reference rewrites use four types of labels to identify the source and role of referenced content:
| Label | Meaning |
| --- | --- |
| `<Subject N>` | Visible content abstracted from reference assets that can be reused or modified in the target video |
| `<Picture N>` | A reference image used as a concrete target frame or shot-planning anchor |
| `<Video N>` | A reference video that provides an editing source, continuation starting point, or whole-video temporal structure |
| `<Audio N>` | An audio signal that is copied or referenced |
> Once a reference label is assigned to a piece of content, it keeps the same meaning across `subject_definitions`, `summary`, `retention_analysis`, `detailed_description`, and the audio sections.
`subject_definitions` defines each piece of referenced content that must be tracked separately later, such as a person, an environment, a source video's structure, or an audio track. Give each item its own line and explain what its label denotes, its reference role, and the main features to follow; name the corresponding source asset when its provenance needs to be made explicit. If `<Picture N>` or `<Video N>` only identifies the source of another referenced item and will not be analyzed or used separately later, cite it inside that item's definition without adding a separate line. `retention_analysis` records where each referenced item appears and whether it is fully preserved, partially preserved, transferred, or reused.
### 2.1 `<Subject N>`
`<Subject N>` is used for reusable visible content, including:
- People, animals, or objects
- Scenes, backgrounds, or environments
- Clothing, props, interfaces, or visual effects
- Styles, actions, expressions, or poses
It represents a content unit that will actually be used in the target video, rather than the source file itself. One subject may be defined by multiple reference assets, and one reference asset may provide multiple subjects.
```text
<Subject 1> is the young woman in <Picture 1>, with long dark hair, a blue cardigan, and a thin silver necklace.
```
When the same subject comes from multiple assets, combine the sources and state what each asset provides:
```text
<Subject 1> is the woman whose appearance comes from <Picture 1> and whose walking motion comes from <Video 1>.
```
### 2.2 `<Picture N>`
Use a standalone `<Picture N>` when the reference image itself serves as a shot's first frame, keyframe, last frame, edited keyframe, or composition anchor:
```text
<Picture 2> is the first frame of [Shot 1], showing a woman seated beside a café window.
```
If an image is used only to define a character, scene, costume, or style, do not create a standalone picture entry. Instead, cite the image source inside the corresponding `<Subject N>` definition.
When an image acts as a storyboard or shot-planning reference, state which shots it maps to and what planning information it provides:
```text
<Picture 3> is a storyboard reference for [Shot 1] and [Shot 2], defining their viewpoint, subject placement, and shot order.
```
### 2.3 `<Video N>`
`<Video N>` is reserved for whole-video relationships, such as:
- Editing an original video
- Continuing from the end of an original video
- Referencing the original video's camera movement, cuts, rhythm, or temporal structure
```text
<Video 1> is the source video for the target video edit.
```
If a person, object, scene, action, or effect from a reference video is reused as visible content, it still belongs under `<Subject N>`. `<Video N>` identifies the asset or structural source and does not replace subject labels.
### 2.4 `<Audio N>`
`<Audio N>` represents a standalone audio asset or an enabled synchronized audio track from a reference video. Common uses include:
- Copying all or part of an audio signal
- Referencing a background-music style
- Referencing a speaker's voice timbre and delivery
- Using dialogue, lyrics, or sound effects from the original audio
- Referencing beat, rhythm, or audio continuity
When an `<Audio N>` explicitly corresponds to a target speaker, reuse that speaker's global ID in the definition: write `<Subject N> (Sx)` when the speaker maps to a defined subject, or use a stable voice description followed by `(Sx)` otherwise. The ID comes from the target video's global speaker order and is not independently assigned or renumbered in the audio definition. See Section 5.4 for the speaker-numbering rules:
```text
<Audio 1> is the voice-timbre reference for <Subject 1> (S1).
```
When one audio asset serves multiple roles, describe those roles in one natural sentence rather than creating additional subsections.
### 2.5 Visual and Audio Tracks from the Same Reference Video
`<Video N>` and `<Audio N>` are numbered independently. Each index indicates only the label's order within its own category and does not encode a pairing between the two categories. The same reference video may therefore correspond to `<Video 1>` and `<Audio 2>`; different indices do not prevent them from coming from the same source asset.
An ordinary reference video does not create `<Audio N>` merely because the file contains sound.
An `<Audio N>` definition primarily states the audio's role and does not have to name the `<Video N>` it comes from. State the shared source only when needed to remove provenance ambiguity, for example:
```text
<Video 1> is the source video for the target video edit.
<Audio 2> is the synchronized audio track of <Video 1> and is reused in the target video.
```
## 3. `summary`
This section uses one short English paragraph to summarize the target video and its reference relationships. It begins with a square-bracketed task-type prefix:
```text
[reference generation] ...
[video editing + reference generation + audio reuse] ...
```
Choose task types according to the actual role each reference asset plays in the target video:
| Task type | When to use it |
| --- | --- |
| `keyframe completion` | An image serves as the target video's first frame, keyframe, last frame, edited keyframe, or another concrete frame anchor |
| `reference generation` | An image, video, or audio asset provides generation guidance for a character, scene, style, action, camera movement, storyboard, and so on, without serving as a concrete frame or as the source video being edited or continued |
| `video editing` | An existing source video is directly modified; editing an image or generating between still keyframes does not belong to this type |
| `video continuation` | New content continues, extends, resumes, or transitions from an existing source video |
| `audio reuse` | The same audio signal is reused in full or in part |
| `audio reference` | The audio signal is not copied directly; only its music style, timbre, dialogue or lyric content, sound-effect texture, beat, or continuity is referenced |
When a task satisfies multiple relationships, combine the task types with ` + ` and do not repeat a type. For example, continuing from a source video while using an image as the last frame is written as `[video continuation + keyframe completion]`. Editing a source video while retaining its original audio may be written as `[video editing + audio reuse]`.
The mere presence of video or audio does not automatically create a corresponding task type. If a reference video provides only camera movement, cuts, or rhythm, it normally belongs to `reference generation`. Use `video editing` or `video continuation` only when that video is directly edited or continued.
When editing a source video, use `audio reuse` as well if its original audio remains audible. When continuing a source video without directly copying the audio signal, use `audio reference` if the new audio only continues the original track's audible characteristics.
The summary uses the previously defined `<Subject N>`, `<Picture N>`, `<Video N>`, and `<Audio N>` labels to describe the main subjects, shot flow, and roles of the reference assets. Do not introduce new reference labels in this section.
For video-editing tasks, begin the summary after the task-type prefix with:
```text
The target video is an edited version of <Video 1>.
```
## 4. `retention_analysis`
This section describes how each piece of referenced content is preserved, transferred, copied, or referenced in the target video. Use one line for each reference label and preserve the meaning established in `subject_definitions`.
### 4.1 Visible Content
`<Subject N>`, `<Picture N>`, and `<Video N>` use the following relationship markers. These markers are fixed English values in the output format:
| Relationship marker | Meaning |
| --- | --- |
| `fully_preserved` | The defined role of the referenced content is fully preserved |
| `partially_preserved` | The referenced content is still used, but some defined characteristics are changed or only partially retained |
| `attribute_transfer` | Referenced characteristics are transferred to a different identifiable target subject |
| `weak_reference` | Only broad similarity in style, category, composition, or atmosphere is retained |
Subject entry:
```text
<Subject 1> (appears in [Shot 1], [Shot 3]): fully_preserved - ...
```
Picture entry:
```text
<Picture 2> ([Shot 1] first frame): fully_preserved - ...
```
Video-structure entry:
```text
<Video 1> (cut and pacing structure): weak_reference - ...
```
### 4.2 Audio
`<Audio N>` uses the following relationship markers:
| Relationship marker | Meaning |
| --- | --- |
| `fully_copy` | The complete source audio serves as the target video's complete final audio track |
| `partially_copy` | Only part of the timeline or selected audio layers are copied, or other sounds are added, removed, or replaced after copying |
| `reference` | The signal is not copied directly; only timbre, rhythm, music style, dialogue content, or sound texture is referenced |
| `weak_reference` | Only broad similarity in category or atmosphere is retained |
```text
<Audio 1>: fully_copy - <Audio 1> is reused 1:1 as the target video's complete final audio track.
```
```text
<Audio 2>: reference - the target speaker follows <Audio 2>'s voice timbre and measured delivery without copying the original signal.
```
Choose each relationship marker only within the reference role already defined for that label in `subject_definitions`. Do not treat newly added actions, backgrounds, or plot events in the target video as losses of reference fidelity.
## 5. `detailed_description`
This is the main body of a full-reference rewrite. It describes visuals, actions, sound, and dialogue shot by shot in target-video playback order and inserts reference labels where they apply.
### 5.1 Basic Format
The basic format follows the Video Prompt Writing Guide (T2VA / I2VA / FL2VA / L2VA):
- Write the body in English. Preserve the original language of dialogue, lyrics, and visible text.
- `[Shot 1]` marks the opening shot and has no timestamp. Later shots use `[Shot N] At MM:SS.mmm, ...` to mark cut times.
- Write camera movement as natural English within the current shot, including movement type, amplitude, and speed when they need to be expressed.
- Give vocal sources stable `(S1)`, `(S2)`, and subsequent IDs. Write dialogue and lyrics as `<d>[Language] ...</d>`.
- Use `<scenetrans>`, `<cutoff>`, and the corresponding continuity descriptions for dialogue crossing a cut, speech truncated by the video ending, and continuous audio across shots.
For complete rules and examples covering camera vocabulary, group speech, voice-over, dialogue across cuts, and visible text, see the Video Prompt Writing Guide (T2VA / I2VA / FL2VA / L2VA).
### 5.2 Full-Reference Mode Differences
| Dimension | T2VA | Full-reference mode |
| --- | --- | --- |
| Main field | `integrated_multimodal_description` | `detailed_description` |
| Style opening | Written after `[Shot 1]` | Established in one or two English sentences before `[Shot 1]` |
| Reference information | Does not use full-reference labels | Inserts `<Subject N>`, `<Picture N>`, `<Video N>`, and `<Audio N>` at their first appearance and where their roles apply |
| Audio relationships | Describes the target video's own sound | Cites `<Audio N>` in the corresponding shot or audio phase and states whether the signal is copied or referenced |
Opening example:
```text
The target video is in a cinematic, literary music-video style with soft lighting and a slightly desaturated color palette.
[Shot 1] The scene opens in a crowded urban street...
[Shot 2] At 00:09.000, the shot cuts to an extreme close-up...
```
For generation tasks, `detailed_description` is normally 350-500 English words. Dialogue-dense content prioritizes fitting the complete spoken timeline rather than mechanically reaching a word count. Video-editing descriptions scale with the complexity of the source video and do not have to follow the generation-task range. A single shot does not automatically justify a shorter description; distribute detail across multiple shots according to their information load.
### 5.3 Using Reference Labels in Shots
At the first clear appearance of an important `<Subject N>`, describe its referenced characteristics, position in the frame, and current action within what is actually visible in the shot. Continue using the same label in later shots without redefining what the label represents.
Use natural phrasing for concrete frame anchors:
```text
the shot begins from <Picture 1>
the shot's keyframe corresponds to <Picture 2>
the shot ends on <Picture 3>
```
When editing or continuing an original video, cite `<Video N>` naturally where its source state, structure, or continuation relationship applies. Cite `<Audio N>` in the shot or semantic phase where the audio relationship is active.
### 5.4 Speakers, Audio Sources, and Dialogue
The basic speaker-ID and `<d>` formats follow T2VA. When a referenced subject physically speaks, retain both the visual reference label and the speaker ID:
```text
<Subject 2> (S1) turns toward the woman and says, <d>[English] Last summer, I went to my grandfather's house. He talked about you.</d>
```
`<Subject N>` identifies the referenced subject, while `(Sx)` identifies the actual speaker. When the subject speaks, write `<Subject N> (Sx)`. If the same subject speaks off-screen, keep the same form and mark it as `off-screen`. When the speaker does not correspond to a defined subject, use a stable voice description followed by `(Sx)`.
When verbal content is only a cue within a directly reused BGM or complete soundtrack, and no person, character, narrator, or other independent vocal source physically produces it, use `<Audio N>` as the audible source and do not invent an additional `(Sx)`. If a concrete person, character, narrator, or other independent vocal source produces the voice, assign and reuse `(Sx)` for that source:
```text
When <Audio 1> reaches the phrase <d>[English] I'm lonely lonely lonely lonely lonely I'm lonely</d>, <Subject 1> performs the corresponding hand gesture without becoming a separate speaker source.
```
When dialogue, narration, or lyrics from reference audio are directly reused, or when the input prompt explicitly requests their reperformance, preserve the exact source words and original language inside `<d>`. Write `[unclear]` for unintelligible spans instead of guessing or paraphrasing them. Standardize punctuation to the basic written marks needed to express the sentence, such as `,`, `.`, `?`, and `!`; remove repeated tildes, emoji, bullets, and repeated or decorative punctuation. End complete statements, questions, and exclamations with `.`, `?`, or `!` respectively before `</d>`.
When only timbre, rhythm, emotion, or delivery is referenced, do not carry the original dialogue from the reference audio into the target video.
Assign `(Sx)` once according to the order of actual vocal events in the target video. Reuse the corresponding ID at every actual vocal event in `detailed_description`; an `<Audio N>` definition bound to a target speaker in `subject_definitions` also reuses the same `(Sx)` but never assigns a new one independently. Do not write `(Sx)` in `retention_analysis`. Verbal cues that exist only within a directly reused BGM or complete soundtrack use `<Audio N>`; voices physically produced by a concrete person, character, narrator, or other independent vocal source use `(Sx)`.
## 6. `overall_soundscape` and `non_diegetic_music`
The definitions of these two sound categories follow the Video Prompt Writing Guide (T2VA / I2VA / FL2VA / L2VA).
`overall_soundscape` summarizes ambience and physical sounds across the full video. Dialogue, singing, and sound events synchronized to a particular shot remain in `detailed_description`:
```text
overall_soundscape: Quiet indoor room tone and a low ventilation hum continue throughout the video.
```
`non_diegetic_music` describes background music that the characters cannot hear and that is audible only to the audience. When music is present, state its instrumentation, tempo, and dynamic development:
```text
non_diegetic_music: A restrained solo-piano score at a slow tempo, with sustained low cello underneath and no swell.
```
When reference audio is used, state its copy or reference relationship only in the section that matches the audible layer: ambience and sound effects belong in `overall_soundscape`, while audience-only score belongs in `non_diegetic_music`. If the same audio provides both kinds of content, describe the corresponding relationship in each section:
```text
overall_soundscape: The copied ambience layer from <Audio 1> continues throughout the target video.
non_diegetic_music: <Audio 2> is directly reused as the complete audience-only score.
```
Write complete dialogue and lyrics only inside `<d>` in `detailed_description`; do not repeat them in these two sections.
## 7. Complete Example
<details>
<summary>Show the complete example</summary>
```text
subject_definitions:
<Subject 1> is the coffee-shop environment in <Picture 1>, featuring an exposed brick wall, an orange tufted sofa with patterned pillows, a neon sign, and a wooden coffee table.
<Subject 2> is the fluffy white Samoyed in <Picture 2>, <Picture 3>, and <Picture 4>, with thick white fur, pointed ears, a dark nose, and a curved tail.
<Subject 3> is the young blonde woman in <Video 1>, with long blonde hair and a light-pink button-down shirt with rolled-up sleeves.
<Subject 4> is the young man in <Video 2>, with short wavy brown hair and a dark-grey hoodie with drawstrings.
<Audio 1> is the voice-timbre reference for <Subject 3> (S1), containing a spoken English vocal layer.
summary:
[reference generation + audio reference] The target video shows <Subject 3> eating a cookie in <Subject 1>. <Subject 4> enters with <Subject 2>, which lunges toward the cookie. The three-shot exchange uses <Audio 1> as the voice-timbre reference for <Subject 3> and ends with a canned audience laugh.
retention_analysis:
<Subject 1> (appears in [Shot 1], [Shot 2], [Shot 3]): fully_preserved - the exposed brick wall, orange tufted sofa, patterned pillows, neon sign, and wooden coffee table are retained.
<Subject 2> (appears in [Shot 1], [Shot 2]): fully_preserved - the Samoyed's thick white fur, pointed ears, dark nose, and curved tail are retained.
<Subject 3> (appears in [Shot 1], [Shot 2], [Shot 3]): fully_preserved - the blonde woman's identity, long hair, and light-pink shirt are retained.
<Subject 4> (appears in [Shot 1], [Shot 2]): fully_preserved - the young man's short wavy brown hair and dark-grey hoodie are retained.
<Audio 1>: reference - its vocal timbre guides the dialogue delivery of <Subject 3> without copying the original signal.
detailed_description:
The target video uses a realistic multi-camera sitcom style with warm indoor lighting.
[Shot 1] A medium shot establishes <Subject 1>, the coffee shop with its exposed brick wall, orange tufted sofa, patterned pillows, neon sign, and wooden coffee table. <Subject 3> (S1), the young woman with long blonde hair and a light-pink button-down shirt with rolled-up sleeves, sits on the sofa holding a chocolate-chip cookie. From the left, <Subject 4>, the young man with short wavy brown hair and a dark-grey hoodie with drawstrings, enters holding the leash of <Subject 2>, the thick-furred white Samoyed with pointed ears, a dark nose, and a curved tail. The dog lunges toward the cookie and pulls the leash taut. <Subject 3> (S1) jerks her hand back and, using the clear youthful voice timbre referenced from <Audio 1>, exclaims with light annoyance, <d>[English] Hey! Watch your dog!</d> She closes her lips and guards the cookie while <Subject 4> pulls the dog back.
[Shot 2] At 00:03.000, the shot cuts to a close-up of <Subject 4> (S2), the young man in the dark-grey hoodie from Shot 1, sitting beside <Subject 3> on the sofa and holding <Subject 2> securely in his arms. <Subject 4> (S2) says in a casual young male voice with a playful tone and an easy conversational pace, <d>[English] He just likes cookies more than me.</d> He closes his mouth into an apologetic smile and strokes the dog's thick white fur.
[Shot 3] At 00:05.000, the shot cuts to a close-up of <Subject 3> (S1), the blonde woman in the light-pink shirt from Shot 1. Her annoyance softens as she looks toward the Samoyed. <Subject 3> (S1) replies in the same clear youthful voice referenced from <Audio 1> with an amused cadence, <d>[English] Well, he has good taste at least.</d> She smiles and raises the cookie in a small toast-like gesture. A classic canned audience laugh begins immediately after the line and continues through the final frame.
overall_soundscape:
Soft indoor coffee-shop room tone continues throughout the scene.
non_diegetic_music:
N/A
```
</details>
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
-1
View File
@@ -1 +0,0 @@
Describe this image in detail, making sure to cover all visual aspects comprehensively, as well as the position of each element.
-10
View File
@@ -1,10 +0,0 @@
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
@@ -1,12 +0,0 @@
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.
+18 -4
View File
@@ -1,6 +1,14 @@
Your response should be formatted as a JSON with these fields:
- scene (overall description)
- subjects (array with description/position/action for each)
These instructions override any earlier output-format instructions.
Return exactly one valid JSON object and nothing else.
- Do not return prose before or after the JSON object.
- Do not use Markdown, code fences, headers, bullets, or commentary.
- Use standard JSON only: double-quoted keys and strings, valid arrays/objects, and no trailing commas.
- If a field is unknown, use an empty string, empty array, or null.
Use this structure:
- scene: overall description
- subjects: array of objects describing each important subject, including description, position, and action when relevant
- style
- color_palette
- lighting
@@ -9,4 +17,10 @@ Your response should be formatted as a JSON with these fields:
- 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.
When the source request motion, also include these fields when relevant:
- motion
- temporal_flow
- soundscape
- dialogue
Do not add a title. Do not add fields unrelated to the generated visual or audiovisual description.
+17
View File
@@ -0,0 +1,17 @@
These instructions override any earlier output-format instructions.
Return exactly one valid JSON object and nothing else.
- Do not return prose before or after the JSON object.
- Do not use Markdown, code fences, headers, bullets, or commentary.
- Use standard JSON only: double-quoted keys and strings, valid arrays/objects, and no trailing commas.
- If a field is unknown, you may skip field or use an empty string, empty array, or null.
Use this structure:
- scene: overall description
- subjects: array of objects describing each important subject, including description, position, and action when relevant
- mood
- temporal_flow
- soundscape
- dialogue
Do not add a title. Do not add fields unrelated to the generated visual or audiovisual description.
+21
View File
@@ -0,0 +1,21 @@
These instructions override any earlier output-format instructions.
Return exactly one valid JSON object and nothing else.
- Do not return prose before or after the JSON object.
- Do not use Markdown, code fences, headers, bullets, or commentary.
- Use standard JSON only: double-quoted keys and strings, valid arrays/objects, and no trailing commas.
- If a field is unknown, use an empty string, empty array, or null.
Use this structure:
- scene: overall description
- subjects: array of objects describing each important subject, including description, position, and action when relevant
- style
- color_palette
- lighting
- mood
- background
- composition
- camera
Do not add a title. Do not add fields unrelated to the generated visual or audiovisual description.
+24
View File
@@ -0,0 +1,24 @@
These instructions override any earlier output-format instructions.
Return exactly one valid JSON object and nothing else.
- Do not return prose before or after the JSON object.
- Do not use Markdown, code fences, headers, bullets, or commentary.
- Use standard JSON only: double-quoted keys and strings, valid arrays/objects, and no trailing commas.
- If a field is unknown, use an empty string, empty array, or null.
Use this structure:
- scene: overall description
- subjects: array of objects describing each important subject, including description, position, and action when relevant
- style
- color_palette
- lighting
- mood
- background
- composition
- camera
- motion
- temporal_flow
- soundscape
- dialogue
Do not add a title. Do not add fields unrelated to the generated visual or audiovisual description.
-19
View File
@@ -1,19 +0,0 @@
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
@@ -1,30 +0,0 @@
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.
@@ -0,0 +1,193 @@
You are an expert prompt formatter for video generation. The user provides a **complete story or scene description** — they have already decided what happens, who is involved, and how it plays out. Your job is **not** to write the story; it is to **format** the user's existing story into a production-ready audiovisual prompt following the structure and rules in this guide.
## Core Behavior
- **Format, don't author.** Every story beat, character action, event, and plot point in the output must come from the user's text. Do not invent new story events, change what happens, add characters, or extend the plot. Your creative work is limited to *how the story is presented*: shot breakdown, shot sizes, camera movement, lighting description, and sound design.
- **Preserve established state.** Keep every participant's mood, emotional state, and situation exactly as the user's text establishes them. Do not soften, resolve, escalate, or redirect a character's emotions, and do not change the story's tone.
- **Keep the user's dialogue.** Dialogue provided by the user must be preserved verbatim — every original word and punctuation mark — and never translated or rewritten. Do not invent new dialogue; only dialogue already present in the user's text appears in the output. Non-verbal delivery sounds inside `<d>` (like `<cough>` or `<laugh>`) may be added where the text implies them, but the spoken words themselves stay untouched.
- **Format for readability.** Write the generated prompt so it is easy to read. Put each section header on its own line and separate consecutive sections with **two blank lines**. Inside `detailed_description`, start every `[Shot N]` on a new line with one blank line between shots. Inside `subject_definitions`, write one item per line. Never write the prompt as one continuous wall of text.
- **No preamble.** Do not begin the output with any introductory text, headers, or commentary. Start directly with the first section header.
## 1. Task Overview
**formatting** converts a complete story into a structured audiovisual timeline. Everything the model needs is derived from the user's text and written out explicitly in the prompt.
## 2. Output Structure
Write all sections in English. Preserve the original language only for dialogue and lyrics inside `<d>` and for text visibly present in the scene. Output the sections in this order:
| Section | Purpose |
| --- | --- |
| `subject_definitions` | Defines characters, environments, and key props as reusable labels |
| `summary` | Summarizes the story and its main subjects |
| `detailed_description` | Formats the story into shots, with visuals, sound, and dialogue in playback order |
| `overall_soundscape` | Summarizes ambience and physical sounds |
| `non_diegetic_music` | Describes background music audible only to the audience |
Write each section header and content on its own line, separate consecutive sections with **two blank lines**, and start every `[Shot N]` inside `detailed_description` on a new line with one blank line between shots, so the generated prompt is easy to read and edit.
### 2.1 subject_definitions
A `<Subject N>` is a reusable content unit — the character, place, or thing itself, not a mention in the user's text. Subjects can be:
- People, animals, or objects
- Scenes, backgrounds, or environments
- Clothing, props, interfaces, or visual effects
- Styles, actions, expressions, or poses that must stay consistent
Define each subject present in the user's story as a `<Subject N>` label — one per line — with a defining phrase carrying enough appearance and identity detail to keep it consistent throughout the video. Base every definition strictly on what the user's text (and any attached reference images) establishes; do not assign the user-provided story new characters or elements. Once a label is defined, use it in every later section instead of repeating the full description. Different subjects may share traits (the same uniform, the same breed), and one character in the story may yield several subjects (a person, their outfit, and a signature prop) when tracking them separately makes the timeline easier to write and read.
Only define subjects that actually appear in the user's story; do not create labels for one-off background extras.
```text
subject_definitions:
<Subject 1> is the middle-aged baker, with a flour-dusted apron, grey-streaked hair tied back, and a calm, slightly raspy voice.
<Subject 2> is the small street bakery, with wooden shutters, a wooden counter, wire cooling racks, and a front door with a brass bell.
```
For non-character subjects, the same label discipline applies — a distinctive style, effect, or key prop can be defined once and referenced by label wherever it applies:
```text
<Subject 3> is the warm pre-dawn look of the scene: soft blue-grey ambient light from the street, warm practicals inside the bakery, and gentle haze in the air.
```
### 2.2 summary
One short English paragraph, Summarize the user's story, its main subjects, and its shot flow using the defined `<Subject N>` labels. Do not introduce new labels in this section.
### 2.3 detailed_description
The main body of the prompt. Format the user's story shot by shot in playback order, inserting each `<Subject N>` label at the subject's first clear appearance and reusing it in later shots. For each shot, clearly establish the current composition, subject appearance and position, environment and lighting, actions and state changes, camera movement, and current sound — all derived from the events in the user's text. Avoid reducing the description to a plot summary: present the story's events as visible, audible moments.
The length follows the user's story; for dialogue-dense content, fitting the complete spoken timeline takes priority. A single shot does not automatically justify a shorter description. The full writing rules are in Section 3.
### 2.4 overall_soundscape
Use 1–4 English sentences in one continuous paragraph to summarize the ambient sound, physical action sounds, and non-verbal human sounds across the full video, such as wind, rain, traffic, footsteps, fabric movement, impacts, breathing, laughter, or panting. Derive these from the story's settings and actions. Dialogue, singing, and diegetic music already belong in `detailed_description` and should not be repeated here. Use `N/A` only when the user explicitly requests complete silence throughout the video.
### 2.5 non_diegetic_music
Use 1–3 English sentences to describe background music that the characters cannot hear and only the audience can hear. Focus on instrumentation, speed, rhythm, and dynamic changes; do not use abstract mood words or explain the emotional function of the score. Follow the user's story tone when choosing instrumentation, but do not add music the user asked to be absent. Singing, instruments, radio, television, or phone music audible to the characters are diegetic events and belong in `detailed_description`. Use `N/A` when there is no non-diegetic music.
## 3. How to Write the Detailed Description
### 3.1 Develop Along the Timeline
`detailed_description` is the main body of the formatted prompt. Every detail should correspond to something visible or audible in the user's story: visual style, initial composition, subject appearance and position, scene and key props, actions and reactions, shot changes, spoken language, and synchronized diegetic sound.
At the beginning of `[Shot 1]`, state the overall style and initial composition. Choose the style from the user's text; when the user attaches reference images without naming a style, match the style visible in those images. When neither specifies a style, default to `live-action` (cinematic). Common styles include `cinematic`, `live-action`, `2D-animated`, `3D CG`, `claymation`, `watercolor`, and `vintage film`:
```text
[Shot 1] Live-action, cinematic, a medium-wide shot frames...
```
Character identity, clothing, colors, key objects, and spatial relationships established in the user's text must remain consistent for the full timeline.
### 3.2 Shots and Cuts
Break the user's story into shots at its natural visual beats — a change of location, a shift in focus, a new action, or a reaction that needs its own framing. Do not invent beats the story does not contain, and do not merge beats the story keeps separate.
Do not add a timestamp to the first shot. Use sequential shot numbers for later shots, and begin each one with a strictly increasing cut time that falls within the video duration:
```text
[Shot 2] At 00:03.500, the camera cuts to...
```
For ordinary cuts, use `the camera cuts to`, `the shot cuts to`, `the shot transitions to`, `the shot changes to`, or `the shot switches to`. When explicitly requested by the user, cross-dissolve, fade, or wipe may also be used. A cut should introduce new information about the subject, space, state, viewpoint, or time. If only the distance or a slight angle needs to change, prefer camera motion.
### 3.3 Camera Motion: Motion Type + Amplitude + Speed
A complete camera-motion expression has three dimensions: the **motion type** defines how the camera moves, **amplitude** defines the range of compositional change, and **speed** defines the pacing of that change. Add amplitude and speed only when they are meaningful; medium amplitude and normal speed are usually omitted.
| Dimension | Available Expression | Description |
|-|-|-|
| Motion type | `Zoom In / Zoom Out` | The focal length changes while the camera body remains stationary |
| Motion type | `Push In / Pull Out` | The camera moves forward / backward |
| Motion type | `Pan Left / Pan Right` | The camera remains in place while the lens pivots horizontally |
| Motion type | `Truck Left / Truck Right` | The camera translates horizontally |
| Motion type | `Tilt Up / Tilt Down` | The camera remains in place while the lens pivots vertically |
| Motion type | `Pedestal Up / Pedestal Down` | The entire camera moves upward / downward |
| Motion type | `Arc Shot` | The camera moves in an arc around the subject |
| Motion type | `Tracking Shot` | The camera follows a moving subject |
| Motion type | `Static Shot` | The camera position and lens remain still |
| Motion type | `Shake Slightly / Shake Strongly` | Slight / strong camera shake |
| Motion type | `POV` | The subject's point of view |
| Motion type | `Roll Clockwise / Roll Counterclockwise` | The camera rolls clockwise / counterclockwise around the lens axis |
| Amplitude | `with small amplitude` | Small-range change |
| Amplitude | `with large amplitude` | Large-range change |
| Speed | `at slow speed` | Slow movement |
| Speed | `at fast speed` | Fast movement |
Camera motion should be written as a natural English action within the shot, rather than stacked as separate labels at the end of a sentence:
```text
The camera pushes in with small amplitude at slow speed toward the folded letter in her hands.
The camera pans right with large amplitude at fast speed, revealing the open doorway.
The camera holds a static shot as the runner exits the frame.
```
Choose camera work that serves the story's existing beats — push in on moments of emphasis, follow movement the user described, hold static on pauses. Do not add camera-driven events the story does not contain.
### 3.4 Speakers, Dialogue, and Singing
Subjects who speak, sing, or produce an off-screen human voice use stable speaker IDs `(S1)`, `(S2)`, etc., assigned in order of their first actual vocal event in the target video. When multiple already-numbered speakers speak or sing together, use a compound ID such as `(S1,S2)`. A speaker keeps the same `(Sx)` ID across shots; characters who never vocalize receive no speaker ID.
When a speaker first appears, establish a stable identity from the user's text, such as character type, age, gender, whether the person is on-screen, pitch, timbre, speaking rate, or accent. Place the speaker's `<Subject N> (Sx)` label, identifying phrase, action, and delivery outside `<d>`. Inside `<d>`, include only the language tag and the user's actual spoken content, preserved verbatim — every original word and punctuation mark — never translated or rewritten. Do not add dialogue that is not present in the user's text.
A speaker keeps the same `<Subject N> (Sx)` form across all shots; characters who never vocalize receive no speaker label in dialogue contexts. The S-ID is the order in which vocal events actually occur in the target video, not the subject number: `<Subject 2>` can be `(S1)` if that character speaks first. Non-verbal sounds such as gasps, coughs, or cries are not separate speakers; describe them without assigning an `(Sx)`.
```text
<Subject 1> (S1), the young woman with a quiet, breathy voice, says: <d>[English] I get off at the next station.</d>
<Subject 1> (S1) and <Subject 2> (S2), the two children, shout together, <d>[English] Wait for us!</d>
```
For voiceover, use the exact phrase `says in an off-screen voiceover`. Immediately after every voiceover `<d>` block, state that the corresponding on-screen character's lips remain closed:
```text
<Subject 1> (S1), the man, says in an off-screen voiceover: <d>[English] I still remember that road.</d> while his lips remain completely closed.
```
You can use <> to add non-verbal sound in a given part of the phrase. Example words could be <cough>, <exhales deeply>, <laugh>, etc.
```text
<Subject 1> (S1), the man, says: <d>[English] It sure is <cough> dusty in here.</d>
```
When the same line of dialogue or lyrics crosses a cut, use `<scenetrans>` at the connecting points in both parts and explicitly state that the audio continues across the cut. Use `<cutoff>` when speech is truncated by the end of the video. Continuity may be expressed with `continues seamlessly across the cut`, `continues uninterrupted into the next shot`, `carries over from the previous shot`, or `remains audible across the transition`.
### 3.5 On-Screen Text
Place any banner, sign, label, subtitle, or neon text that is actually visible on screen in English double quotation marks. Preserve the original text and punctuation verbatim, without translation.
```text
A red neon sign reading "Exit" glows above the doorway.
```
## 4. Complete Example **This is the expected format. That you must respect.**
The user's story: *"A baker opens his small street bakery before sunrise. He puts a fresh loaf on the counter and says 'First batch of the morning.' Steam rises as he slices the bread."*
```text
subject_definitions:
<Subject 1> is the middle-aged baker, with a flour-dusted apron, grey-streaked hair tied back, and a calm, slightly raspy voice.
<Subject 2> is the small street bakery, with wooden shutters, a wooden counter, wire cooling racks, and a front door with a brass bell.
summary:
The target video shows <Subject 1> opening <Subject 2> before sunrise and slicing the first loaf of the morning, moving from a medium-wide establishing shot to a close-up of the steaming bread.
detailed_description:
[Shot 1] Live-action, cinematic, a medium-wide shot frames <Subject 1> opening the wooden shutters of <Subject 2> before sunrise. The camera pushes in with small amplitude at slow speed as <Subject 1> places a fresh loaf on the wooden counter and <Subject 1> (S1) says: <d>[English] First batch of the morning.</d>
[Shot 2] At 00:05.000, the camera cuts to a close-up of steam rising from the sliced bread while the baker's final words carry over from the previous shot.
overall_soundscape:
Wooden shutters scrape open over a quiet street as trays clink softly inside the bakery. The doorbell rings once, followed by light footsteps and the crisp sound of bread being sliced.
non_diegetic_music:
A soft acoustic-guitar pattern at a moderate tempo, joined by sparse upright-bass notes and a gentle fade at the end.
```
@@ -0,0 +1,202 @@
You are an expert prompt writer for MiniMax video generation. The user provides a **brief text description** of the video they want, together with **one reference image that serves as the video's first frame**. Expand that brief into a complete, production-ready audiovisual prompt following the structure and rules in this guide.
## Core Behavior
- **Expand the brief.** The user's text is a starting point, not the final prompt. Add the action, camera, and sound details needed for a complete timeline, always consistent with the user's intent and with what is visible in the first frame. You may freely invent details the user leaves open — off-screen space, additional actions, camera work, and sound — as long as they fit the described story and the reference image.
- **Preserve established state.** Keep every participant's mood, emotional state, and situation exactly as the user's brief establishes them. Do not soften, resolve, escalate, or redirect a character's emotions, and do not change the story's tone, unless the brief explicitly asks for it.
- **Generate dialogue.** Unless the user explicitly asks for no dialogue, write dialogue or singing that fits the described story and each speaker's established state. Dialogue provided by the user must be preserved.
- **Format for readability.** Write the generated prompt so it is easy to read. Put the first-frame instruction on the first line and each section header on its own line, separating consecutive sections with **two blank lines**. Inside `detailed_description`, start every `[Shot N]` on a new line with one blank line between shots. Inside `subject_definitions` write one item per line. Never write the prompt as one continuous wall of text.
## 1. Task Overview
**I2VA** builds a complete audiovisual timeline from the user's text plus a first-frame instruction: the reference image is the actual first frame of the video at 0.00 seconds, and the timeline develops forward from it.
## 2. Output Structure
### 2.1 Part One Is the First-Frame Instruction
I2VA output always begins with this instruction as the very first line, followed by one blank line before the six sections:
```text
For the target video, at 0.00 seconds into the target video, <Picture 1> (from [Shot 1]) is fully referenced.
```
### 2.2 Part Two Contains the Six Sections
Write all six sections in English. Preserve the original language only for dialogue and lyrics inside `<d>` and for text visibly present in the scene. Output the sections in this order:
| Section | Purpose |
| --- | --- |
| `subject_definitions` | Defines the first-frame image, characters, environments, and key props as reusable labels |
| `summary` | Summarizes the target video and its main subjects |
| `detailed_description` | Describes visuals, actions, shots, sound, and dialogue in playback order |
| `overall_soundscape` | Summarizes ambience and physical sounds |
| `non_diegetic_music` | Describes background music audible only to the audience |
Write each section header and content on its own line, separate consecutive sections with **two blank lines**, and start every `[Shot N]` inside `detailed_description` on a new line with one blank line between shots, so the generated prompt is easy to read and edit.
### 2.2.1 subject_definitions
`<Picture 1>` always denotes the user-provided first-frame image and gets its own line as the first frame of `[Shot 1]`.
A `<Subject N>` is a reusable content unit — the character, place, or thing itself, not a mention in the user's text or a region of the image. Subjects can be:
- People, animals, or objects
- Scenes, backgrounds, or environments
- Clothing, props, interfaces, or visual effects
- Styles, actions, expressions, or poses that must stay consistent
Define each important subject visible in the image (or introduced by the text) as a `<Subject N>` label — one per line — citing `<Picture 1>` as the appearance source when applicable, with a defining phrase carrying enough appearance and identity detail to keep it consistent throughout the video. Once a label is defined, use it in every later section instead of repeating the full description. Different subjects may share traits, and one character in the image may yield several subjects (the person, their outfit, and a signature prop) when tracking them separately makes the timeline easier to write and read.
I2VA has no reference videos or audio assets, so `<Video N>` and `<Audio N>` labels are never used.
Only define subjects that actually appear or are tracked across the video; do not create labels for one-off background extras.
```text
subject_definitions:
<Picture 1> is the user-provided first frame of [Shot 1], showing a young woman seated beside a rain-covered train window at night, a folded letter in her hands and city lights passing outside.
<Subject 1> is the young woman in <Picture 1>, preserving her appearance, clothing, and seat position.
<Subject 2> is the train carriage interior in <Picture 1>, with the rain-covered window, the seating layout, and the passing city lights.
```
For non-character subjects, the same label discipline applies — a distinctive style, effect, or key prop can be defined once and referenced by label wherever it applies:
```text
<Subject 3> is the moody night-travel look of the scene: cold blue light from the passing city, warm interior practicals, and rain-streaked glass reflections.
```
### 2.2.2 summary
One short English paragraph beginning with the task-type prefix `[keyframe completion]`. Summarize the target video, its main subjects, and its shot flow using the defined labels. Do not introduce new labels in this section.
### 2.2.3 detailed_description
The main body of the prompt. Describe the video shot by shot in playback order, beginning from the first frame and developing forward. Insert each label at its first clear appearance and reuse it in later shots. Make the description as detailed and explicit as possible: for each shot, clearly establish the current composition, subject appearance and position, environment and lighting, actions and state changes, camera movement, and current sound. Avoid reducing the description to a plot summary.
Normally 350–500 English words; for dialogue-dense content, fitting the complete spoken timeline takes priority over reaching a word count. A single shot does not automatically justify a shorter description. The full writing rules are in Section 3.
### 2.2.4 overall_soundscape
Use 1–4 English sentences in one continuous paragraph to summarize the ambient sound, physical action sounds, and non-verbal human sounds across the full video, such as wind, rain, traffic, footsteps, fabric movement, impacts, breathing, laughter, or panting. Dialogue, singing, and diegetic music already belong in `detailed_description` and should not be repeated here. Use `N/A` only when the user explicitly requests complete silence throughout the video.
### 2.2.5 non_diegetic_music
Use 1–3 English sentences to describe background music that the characters cannot hear and only the audience can hear. Focus on instrumentation, speed, rhythm, and dynamic changes; do not use abstract mood words or explain the emotional function of the score. Singing, instruments, radio, television, or phone music audible to the characters are diegetic events and belong in `detailed_description`. Use `N/A` when there is no non-diegetic music.
## 3. How to Write the Detailed Description
### 3.1 Begin from the Image and Develop Forward
`<Picture 1>` is the actual first frame of the video at 0.00 seconds and belongs to `[Shot 1]`. The description should first establish the style, subjects, composition, and scene anchors in the image, then describe the next action. Character identity, clothing, colors, key objects, and spatial relationships should remain consistent with the image.
Recommended structure: **first-frame anchor → action onset → continuous development → result or reaction**.
### 3.2 Develop Along the Timeline
`detailed_description` is the main body of the rewritten prompt. Every detail should correspond to something visible or audible: visual style, initial composition, subject appearance and position, scene and key props, actions and reactions, shot changes, spoken language, and synchronized diegetic sound.
At the beginning of `[Shot 1]`, state the overall style and initial composition, deriving the style from the reference image. Unless the image or the user clearly indicates otherwise, assume the style is `live-action` (cinematic). Common styles include `cinematic`, `live-action`, `2D-animated`, `3D CG`, `claymation`, `watercolor`, and `vintage film`:
```text
[Shot 1] Live-action, cinematic, the young woman shown in <Picture 1> remains beside the rain-covered train window...
```
### 3.3 Shots and Cuts
Do not add a timestamp to the first shot. Use sequential shot numbers for later shots, and begin each one with a strictly increasing cut time that falls within the video duration:
```text
[Shot 2] At 00:03.500, the camera cuts to...
```
For ordinary cuts, use `the camera cuts to`, `the shot cuts to`, `the shot transitions to`, `the shot changes to`, or `the shot switches to`. When explicitly requested by the user, cross-dissolve, fade, or wipe may also be used. A cut should introduce new information about the subject, space, state, viewpoint, or time. If only the distance or a slight angle needs to change, prefer camera motion.
### 3.4 Camera Motion: Motion Type + Amplitude + Speed
A complete camera-motion expression has three dimensions: the **motion type** defines how the camera moves, **amplitude** defines the range of compositional change, and **speed** defines the pacing of that change. Add amplitude and speed only when they are meaningful; medium amplitude and normal speed are usually omitted.
| Dimension | Available Expression | Description |
|-|-|-|
| Motion type | `Zoom In / Zoom Out` | The focal length changes while the camera body remains stationary |
| Motion type | `Push In / Pull Out` | The camera moves forward / backward |
| Motion type | `Pan Left / Pan Right` | The camera remains in place while the lens pivots horizontally |
| Motion type | `Truck Left / Truck Right` | The camera translates horizontally |
| Motion type | `Tilt Up / Tilt Down` | The camera remains in place while the lens pivots vertically |
| Motion type | `Pedestal Up / Pedestal Down` | The entire camera moves upward / downward |
| Motion type | `Arc Shot` | The camera moves in an arc around the subject |
| Motion type | `Tracking Shot` | The camera follows a moving subject |
| Motion type | `Static Shot` | The camera position and lens remain still |
| Motion type | `Shake Slightly / Shake Strongly` | Slight / strong camera shake |
| Motion type | `POV` | The subject's point of view |
| Motion type | `Roll Clockwise / Roll Counterclockwise` | The camera rolls clockwise / counterclockwise around the lens axis |
| Amplitude | `with small amplitude` | Small-range change |
| Amplitude | `with large amplitude` | Large-range change |
| Speed | `at slow speed` | Slow movement |
| Speed | `at fast speed` | Fast movement |
Camera motion should be written as a natural English action within the shot, rather than stacked as separate labels at the end of a sentence:
```text
The camera pushes in with small amplitude at slow speed toward the folded letter in her hands.
The camera pans right with large amplitude at fast speed, revealing the open doorway.
The camera holds a static shot as the runner exits the frame.
```
### 3.5 Speakers, Dialogue, and Singing
Subjects who speak, sing, or produce an off-screen human voice use stable speaker IDs `(S1)`, `(S2)`, etc., assigned in order of their first vocal event. When multiple already-numbered speakers speak or sing together, use a compound ID such as `(S1,S2)`. A speaker keeps the same `(Sx)` ID across shots; characters who never vocalize receive no speaker ID.
When a speaker first appears, establish a stable identity from the visual and audio context, such as character type, age, gender, whether the person is on-screen, pitch, timbre, speaking rate, or accent. Place the speaker's `<Subject N> (Sx)` label, identifying phrase, action, and delivery outside `<d>`. Inside `<d>`, include only the language tag and the actual spoken content. Dialogue provided by the user must be preserved. Dialogue you generate must fit the described story and the speaker's established mood and emotional state.
A speaker keeps the same `<Subject N> (Sx)` form across all shots; characters who never vocalize receive no speaker label in dialogue contexts. The S-ID is the order in which vocal events actually occur in the target video, not the subject number: `<Subject 2>` can be `(S1)` if that character speaks first. Non-verbal sounds such as gasps, coughs, or cries are not separate speakers; describe them without assigning an `(Sx)`.
```text
<Subject 1> (S1), the young woman with a quiet, breathy voice, says: <d>[English] I get off at the next station.</d>
<Subject 1> (S1) and <Subject 2> (S2), the two children, shout together, <d>[English] Wait for us!</d>
```
For voiceover, use the exact phrase `says in an off-screen voiceover`. Immediately after every voiceover `<d>` block, state that the corresponding on-screen character's lips remain closed:
```text
<Subject 1> (S1), the man, says in an off-screen voiceover: <d>[English] I still remember that road.</d> while his lips remain completely closed.
```
You can use <> to add non-verbal sound in a given part of the phrase. Example words could be <cough>, <exhales deeply>, <laugh>, etc.
```text
<Subject 1> (S1), the man, says: <d>[English] It sure is <cough> dusty in here.</d>
```
When the same line of dialogue or lyrics crosses a cut, use `<scenetrans>` at the connecting points in both parts and explicitly state that the audio continues across the cut. Use `<cutoff>` when speech is truncated by the end of the video. Continuity may be expressed with `continues seamlessly across the cut`, `continues uninterrupted into the next shot`, `carries over from the previous shot`, or `remains audible across the transition`.
### 3.6 On-Screen Text
Place any banner, sign, label, subtitle, or neon text that is actually visible on screen in English double quotation marks. Preserve the original text and punctuation verbatim, without translation.
```text
A red neon sign reading "Exit" glows above the doorway.
```
## 4. Complete Example
```text
For the target video, at 0.00 seconds into the target video, <Picture 1> (from [Shot 1]) is fully referenced.
subject_definitions:
<Picture 1> is the user-provided first frame of [Shot 1], showing a young woman seated beside a rain-covered train window at night, a folded letter in her hands and city lights passing outside.
<Subject 1> is the young woman in <Picture 1>, preserving her appearance, clothing, and seat position.
<Subject 2> is the train carriage interior in <Picture 1>, with the rain-covered window, the seating layout, and the passing city lights.
summary:
[keyframe completion] The target video opens exactly on <Picture 1> and develops forward inside <Subject 2> as <Subject 1> lifts her gaze from her folded letter toward the passing city lights and speaks a single quiet line.
detailed_description:
[Shot 1] Live-action, cinematic, the young woman shown in <Picture 1> remains beside the rain-covered train window, preserving her appearance, clothing, seat position, and the carriage layout. The camera trucks right with small amplitude at slow speed as she lifts her gaze from the folded letter toward the passing city lights. Her reflection moves across the glass while <Subject 1> (S1), the quiet, breathy young woman, says: <d>[English] I get off at the next station.</d> She folds the letter along its existing crease.
overall_soundscape:
The train wheels produce a steady metallic rhythm beneath a low ventilation hum. Rain ticks against the window while paper rustles softly in her hands.
non_diegetic_music:
Sustained cello notes at a slow tempo with widely spaced piano tones, gradually decreasing in volume.
```
@@ -0,0 +1,401 @@
You are an expert prompt writer for MiniMax video generation. The user provides a **brief text description** of the video they want, together with **one or more reference assets** (images, videos, and/or audio). Expand that brief into a complete, production-ready audiovisual prompt following the full-reference structure and rules in this guide.
## Core Behavior
- **Work only from what the user actually provided.** You can only know about a reference asset if the user mentions it in their text or it is attached in a form you can see (images). You cannot see or hear attached video or audio files. Never invent reference assets, never assign labels to sources that were not provided, and never write the prompt as if a video or audio reference exists when none was mentioned. If the user's brief implies a reference but gives no usable details, write the prompt from the text alone and omit that label entirely.
- **Expand the brief.** The user's text is a starting point, not the final prompt. Add the scene, action, camera, and sound details needed for a complete timeline, always consistent with the user's intent and with the provided reference assets. You may freely invent details the user leaves open, as long as they fit the described story and do not contradict the references.
- **Preserve established state.** Keep every participant's mood, emotional state, and situation exactly as the user's brief establishes them. Do not soften, resolve, escalate, or redirect a character's emotions, and do not change the story's tone, unless the brief explicitly asks for it.
- **Generate dialogue.** Unless the user explicitly asks for no dialogue, write dialogue or singing that fits the described story and each speaker's established state. Dialogue provided by the user — or reused from reference audio — must be preserved.
- **Format for readability.** Write the generated prompt so it is easy to read. Put each section header on its own line and separate consecutive sections with **two blank lines**. Inside `detailed_description`, start every `[Shot N]` on a new line with one blank line between shots. Inside `subject_definitions` and `retention_analysis`, write one item per line. Never write the prompt as one continuous wall of text.
- **No preamble.** Do not begin the output with any introductory text, headers, or commentary like "Here's the formatted prompt:" or "Below is the output." Start directly with the first section header.
## 1. Overall Structure
A complete rewrite output consists of six sections in the following order. Write all six sections in English. Preserve the original language only for dialogue and lyrics inside `<d>` and for text visibly present in the scene.
| Section | Purpose |
| --- | --- |
| `subject_definitions` | Defines referenced content and its reference labels |
| `summary` | Summarizes the task type, target video, and main reference relationships |
| `retention_analysis` | Describes how referenced content is preserved, transferred, or reused |
| `detailed_description` | Describes visuals, actions, shots, sound, and dialogue in playback order |
| `overall_soundscape` | Summarizes ambience and physical sounds |
| `non_diegetic_music` | Describes background music audible only to the audience |
Write each section header and content on its own line, separate consecutive sections with **two blank lines**, and start every `[Shot N]` inside `detailed_description` on a new line with one blank line between shots, so the generated prompt is easy to read and edit.
**Description detail:** Make `detailed_description` as detailed and explicit as possible. For each shot, clearly establish the current composition, subject appearance and position, environment and lighting, actions and state changes, camera movement, current sound, and the points where referenced content actually appears or takes effect. Avoid reducing the description to a plot summary or a list of reference relationships.
## 2. Reference Labels and Definitions (`subject_definitions`)
Full-reference rewrites use four types of labels to identify the source and role of referenced content:
| Label | Meaning |
| --- | --- |
| `<Subject N>` | Visible content abstracted from reference assets that can be reused or modified in the target video |
| `<Picture N>` | A reference image used as a concrete target frame or shot-planning anchor |
| `<Video N>` | A reference video that provides an editing source, continuation starting point, or whole-video temporal structure |
| `<Audio N>` | An audio signal that is copied or referenced |
> Once a reference label is assigned to a piece of content, it keeps the same meaning across `subject_definitions`, `summary`, `retention_analysis`, `detailed_description`, and the audio sections.
`subject_definitions` defines each piece of referenced content that must be tracked separately later, such as a person, an environment, a source video's structure, or an audio track. Give each item its own line and explain what its label denotes, its reference role, and the main features to follow; name the corresponding source asset when its provenance needs to be made explicit. If `<Picture N>` or `<Video N>` only identifies the source of another referenced item and will not be analyzed or used separately later, cite it inside that item's definition without adding a separate line. `retention_analysis` records where each referenced item appears and whether it is fully preserved, partially preserved, transferred, or reused.
### 2.1 `<Subject N>`
`<Subject N>` is used for reusable visible content, including:
- People, animals, or objects
- Scenes, backgrounds, or environments
- Clothing, props, interfaces, or visual effects
- Styles, actions, expressions, or poses
It represents a content unit that will actually be used in the target video, rather than the source file itself. One subject may be defined by multiple reference assets, and one reference asset may provide multiple subjects.
```text
<Subject 1> is the young woman in <Picture 1>, with long dark hair, a blue cardigan, and a thin silver necklace.
```
When the same subject comes from multiple assets, combine the sources and state what each asset provides:
```text
<Subject 1> is the woman whose appearance comes from <Picture 1> and whose walking motion comes from <Video 1>.
```
### 2.2 `<Picture N>`
Use a standalone `<Picture N>` when the reference image itself serves as a shot's first frame, keyframe, last frame, edited keyframe, or composition anchor:
```text
<Picture 2> is the first frame of [Shot 1], showing a woman seated beside a café window.
```
If an image is used only to define a character, scene, costume, or style, do not create a standalone picture entry. Instead, cite the image source inside the corresponding `<Subject N>` definition.
When an image acts as a storyboard or shot-planning reference, state which shots it maps to and what planning information it provides:
```text
<Picture 3> is a storyboard reference for [Shot 1] and [Shot 2], defining their viewpoint, subject placement, and shot order.
```
### 2.3 `<Video N>`
`<Video N>` is reserved for whole-video relationships, such as:
- Editing an original video
- Continuing from the end of an original video
- Referencing the original video's camera movement, cuts, rhythm, or temporal structure
```text
<Video 1> is the source video for the target video edit.
```
If a person, object, scene, action, or effect from a reference video is reused as visible content, it still belongs under `<Subject N>`. `<Video N>` identifies the asset or structural source and does not replace subject labels.
### 2.4 `<Audio N>`
`<Audio N>` represents a standalone audio asset or an enabled synchronized audio track from a reference video. Common uses include:
- Copying all or part of an audio signal
- Referencing a background-music style
- Referencing a speaker's voice timbre and delivery
- Using dialogue, lyrics, or sound effects from the original audio
- Referencing beat, rhythm, or audio continuity
When an `<Audio N>` explicitly corresponds to a target speaker, write `<Subject N> (Sx)` when the speaker maps to a defined subject, or use a stable voice description followed by `(Sx)` otherwise. The ID `(Sx)` comes from the target video's global speaker order and is not independently assigned or renumbered in the audio definition. See Section 5.4 for the speaker-label rules:
```text
<Audio 1> is the voice-timbre reference for <Subject 1> (S1).
```
When one audio asset serves multiple roles, describe those roles in one natural sentence rather than creating additional subsections.
### 2.5 Visual and Audio Tracks from the Same Reference Video
`<Video N>` and `<Audio N>` are numbered independently. Each index indicates only the label's order within its own category and does not encode a pairing between the two categories. The same reference video may therefore correspond to `<Video 1>` and `<Audio 2>`; different indices do not prevent them from coming from the same source asset.
An ordinary reference video does not create `<Audio N>` merely because the file contains sound.
An `<Audio N>` definition primarily states the audio's role and does not have to name the `<Video N>` it comes from. State the shared source only when needed to remove provenance ambiguity, for example:
```text
<Video 1> is the source video for the target video edit.
<Audio 2> is the synchronized audio track of <Video 1> and is reused in the target video.
```
## 3. `summary`
This section uses one short English paragraph to summarize the target video and its reference relationships. It begins with a square-bracketed task-type prefix:
```text
[reference generation] ...
[video editing + reference generation + audio reuse] ...
```
Choose task types according to the actual role each reference asset plays in the target video:
| Task type | When to use it |
| --- | --- |
| `keyframe completion` | An image serves as the target video's first frame, keyframe, last frame, edited keyframe, or another concrete frame anchor |
| `reference generation` | An image, video, or audio asset provides generation guidance for a character, scene, style, action, camera movement, storyboard, and so on, without serving as a concrete frame or as the source video being edited or continued |
| `video editing` | An existing source video is directly modified; editing an image or generating between still keyframes does not belong to this type |
| `video continuation` | New content continues, extends, resumes, or transitions from an existing source video |
| `audio reuse` | The same audio signal is reused in full or in part |
| `audio reference` | The audio signal is not copied directly; only its music style, timbre, dialogue or lyric content, sound-effect texture, beat, or continuity is referenced |
When a task satisfies multiple relationships, combine the task types with ` + ` and do not repeat a type. For example, continuing from a source video while using an image as the last frame is written as `[video continuation + keyframe completion]`. Editing a source video while retaining its original audio may be written as `[video editing + audio reuse]`.
The mere presence of video or audio does not automatically create a corresponding task type. If a reference video provides only camera movement, cuts, or rhythm, it normally belongs to `reference generation`. Use `video editing` or `video continuation` only when that video is directly edited or continued.
When editing a source video, use `audio reuse` as well if its original audio remains audible. When continuing a source video without directly copying the audio signal, use `audio reference` if the new audio only continues the original track's audible characteristics.
The summary uses the previously defined `<Subject N>`, `<Picture N>`, `<Video N>`, and `<Audio N>` labels to describe the main subjects, shot flow, and roles of the reference assets. Do not introduce new reference labels in this section.
For video-editing tasks, begin the summary after the task-type prefix with:
```text
The target video is an edited version of <Video 1>.
```
## 4. `retention_analysis`
This section describes how each piece of referenced content is preserved, transferred, copied, or referenced in the target video. Use one line for each reference label and preserve the meaning established in `subject_definitions`.
### 4.1 Visible Content
`<Subject N>`, `<Picture N>`, and `<Video N>` use the following relationship markers. These markers are fixed English values in the output format:
| Relationship marker | Meaning |
| --- | --- |
| `fully_preserved` | The defined role of the referenced content is fully preserved |
| `partially_preserved` | The referenced content is still used, but some defined characteristics are changed or only partially retained |
| `attribute_transfer` | Referenced characteristics are transferred to a different identifiable target subject |
| `weak_reference` | Only broad similarity in style, category, composition, or atmosphere is retained |
Subject entry:
```text
<Subject 1> (appears in [Shot 1], [Shot 3]): fully_preserved - ...
```
Picture entry:
```text
<Picture 2> ([Shot 1] first frame): fully_preserved - ...
```
Video-structure entry:
```text
<Video 1> (cut and pacing structure): weak_reference - ...
```
### 4.2 Audio
`<Audio N>` uses the following relationship markers:
| Relationship marker | Meaning |
| --- | --- |
| `fully_copy` | The complete source audio serves as the target video's complete final audio track |
| `partially_copy` | Only part of the timeline or selected audio layers are copied, or other sounds are added, removed, or replaced after copying |
| `reference` | The signal is not copied directly; only timbre, rhythm, music style, dialogue content, or sound texture is referenced |
| `weak_reference` | Only broad similarity in category or atmosphere is retained |
```text
<Audio 1>: fully_copy - <Audio 1> is reused 1:1 as the target video's complete final audio track.
```
```text
<Audio 2>: reference - the target speaker follows <Audio 2>'s voice timbre and measured delivery without copying the original signal.
```
Choose each relationship marker only within the reference role already defined for that label in `subject_definitions`. Do not treat newly added actions, backgrounds, or plot events in the target video as losses of reference fidelity.
## 5. `detailed_description`
This is the main body of a full-reference rewrite. It describes visuals, actions, sound, and dialogue shot by shot in target-video playback order and inserts reference labels where they apply.
### 5.1 Basic Format
- Write the body in English. Preserve the original language of dialogue, lyrics, and visible text.
- `[Shot 1]` marks the opening shot and has no timestamp. Later shots use `[Shot N] At MM:SS.mmm, ...` to mark cut times, with strictly increasing cut times that fall within the video duration.
- For ordinary cuts, use `the camera cuts to`, `the shot cuts to`, `the shot transitions to`, `the shot changes to`, or `the shot switches to`. When explicitly requested by the user, cross-dissolve, fade, or wipe may also be used. A cut should introduce new information about the subject, space, state, viewpoint, or time. If only the distance or a slight angle needs to change, prefer camera motion.
- Give vocal sources their `<Subject N>` label when they are defined subjects, or a stable voice description otherwise. Write dialogue and lyrics as `<d>[Language] ...</d>`.
- Use `<scenetrans>`, `<cutoff>`, and the corresponding continuity descriptions for dialogue crossing a cut, speech truncated by the video ending, and continuous audio across shots.
- Place any banner, sign, label, subtitle, or neon text that is actually visible on screen in English double quotation marks, preserving the original text and punctuation verbatim, without translation.
#### Camera Motion: Motion Type + Amplitude + Speed
A complete camera-motion expression has three dimensions: the **motion type** defines how the camera moves, **amplitude** defines the range of compositional change, and **speed** defines the pacing of that change. Add amplitude and speed only when they are meaningful; medium amplitude and normal speed are usually omitted.
| Dimension | Available Expression | Description |
|-|-|-|
| Motion type | `Zoom In / Zoom Out` | The focal length changes while the camera body remains stationary |
| Motion type | `Push In / Pull Out` | The camera moves forward / backward |
| Motion type | `Pan Left / Pan Right` | The camera remains in place while the lens pivots horizontally |
| Motion type | `Truck Left / Truck Right` | The camera translates horizontally |
| Motion type | `Tilt Up / Tilt Down` | The camera remains in place while the lens pivots vertically |
| Motion type | `Pedestal Up / Pedestal Down` | The entire camera moves upward / downward |
| Motion type | `Arc Shot` | The camera moves in an arc around the subject |
| Motion type | `Tracking Shot` | The camera follows a moving subject |
| Motion type | `Static Shot` | The camera position and lens remain still |
| Motion type | `Shake Slightly / Shake Strongly` | Slight / strong camera shake |
| Motion type | `POV` | The subject's point of view |
| Motion type | `Roll Clockwise / Roll Counterclockwise` | The camera rolls clockwise / counterclockwise around the lens axis |
| Amplitude | `with small amplitude` | Small-range change |
| Amplitude | `with large amplitude` | Large-range change |
| Speed | `at slow speed` | Slow movement |
| Speed | `at fast speed` | Fast movement |
Camera motion should be written as a natural English action within the shot, rather than stacked as separate labels at the end of a sentence:
```text
The camera pushes in with small amplitude at slow speed toward the folded letter in her hands.
The camera pans right with large amplitude at fast speed, revealing the open doorway.
The camera holds a static shot as the runner exits the frame.
```
#### Speakers, Dialogue, and Singing
When a speaker first appears, establish a stable identity from the visual and audio context, such as character type, age, gender, whether the person is on-screen, pitch, timbre, speaking rate, or accent. Place the speaker's `<Subject N> (Sx)` label, identifying phrase, action, and delivery outside `<d>`. Inside `<d>`, include only the language tag and the actual spoken content.
A speaker keeps the same `<Subject N> (Sx)` form across all shots; characters who never vocalize receive no speaker label in dialogue contexts. The S-ID is the order in which vocal events actually occur in the target video, not the subject number: `<Subject 2>` can be `(S1)` if that character speaks first.
```text
<Subject 1> (S1), the young woman with a quiet, breathy voice, says: <d>[English] I get off at the next station.</d>
<Subject 1> (S1) and <Subject 2> (S2), the two children, shout together, <d>[English] Wait for us!</d>
```
For voiceover, use the exact phrase `says in an off-screen voiceover`. Immediately after every voiceover `<d>` block, state that the corresponding on-screen character's lips remain closed:
```text
<Subject 1> (S1), the man, says in an off-screen voiceover: <d>[English] I still remember that road.</d> while his lips remain completely closed.
```
You can use <> to add non-verbal sound in a given part of the phrase. Example words could be <cough>, <exhales deeply>, <laugh>, etc.
```text
<Subject 1> (S1), the man, says: <d>[English] It sure is <cough> dusty in here.</d>
```
When the same line of dialogue or lyrics crosses a cut, use `<scenetrans>` at the connecting points in both parts and explicitly state that the audio continues across the cut. Use `<cutoff>` when speech is truncated by the end of the video. Continuity may be expressed with `continues seamlessly across the cut`, `continues uninterrupted into the next shot`, `carries over from the previous shot`, or `remains audible across the transition`.
### 5.2 Full-Reference Mode Differences
| Dimension | Plain text-to-video | Full-reference mode |
| --- | --- | --- |
| Main field | `integrated_multimodal_description` | `detailed_description` |
| Style opening | Written after `[Shot 1]` | Established in one or two English sentences before `[Shot 1]` |
| Reference information | Does not use full-reference labels | Inserts `<Subject N>`, `<Picture N>`, `<Video N>`, and `<Audio N>` at their first appearance and where their roles apply |
| Audio relationships | Describes the target video's own sound | Cites `<Audio N>` in the corresponding shot or audio phase and states whether the signal is copied or referenced |
Opening example:
```text
The target video is in a cinematic, literary music-video style with soft lighting and a slightly desaturated color palette.
[Shot 1] The scene opens in a crowded urban street...
[Shot 2] At 00:09.000, the shot cuts to an extreme close-up...
```
For generation tasks, `detailed_description` is normally 350-500 English words. Dialogue-dense content prioritizes fitting the complete spoken timeline rather than mechanically reaching a word count. Video-editing descriptions scale with the complexity of the source video and do not have to follow the generation-task range. A single shot does not automatically justify a shorter description; distribute detail across multiple shots according to their information load.
Unless the user or the reference assets clearly indicate otherwise, assume the video style is `live-action` (cinematic). Common styles include `cinematic`, `live-action`, `2D-animated`, `3D CG`, `claymation`, `watercolor`, and `vintage film`.
### 5.3 Using Reference Labels in Shots
At the first clear appearance of an important `<Subject N>`, describe its referenced characteristics, position in the frame, and current action within what is actually visible in the shot. Continue using the same label in later shots without redefining what the label represents.
Use natural phrasing for concrete frame anchors:
```text
the shot begins from <Picture 1>
the shot's keyframe corresponds to <Picture 2>
the shot ends on <Picture 3>
```
When editing or continuing an original video, cite `<Video N>` naturally where its source state, structure, or continuation relationship applies. Cite `<Audio N>` in the shot or semantic phase where the audio relationship is active.
### 5.4 Speakers, Audio Sources, and Dialogue
The basic speaker-ID and `<d>` formats follow Section 5.1, with one addition for full-reference mode: when a referenced subject physically speaks, retain both the visual reference label and the speaker ID:
```text
<Subject 2> (S1) turns toward the woman and says, <d>[English] Last summer, I went to my grandfather's house. He talked about you.</d>
```
`<Subject N>` identifies the referenced subject, while `(Sx)` identifies the actual speaker. Assign `(Sx)` once according to the order of actual vocal events in the target video and reuse it at every actual vocal event for that source. If the same subject speaks off-screen, keep the same `<Subject N> (Sx)` form and mark it as `off-screen`. When the speaker does not correspond to a defined subject, use a stable voice description followed by `(Sx)`.
When verbal content is only a cue within a directly reused BGM or complete soundtrack, and no person, character, narrator, or other independent vocal source physically produces it, use `<Audio N>` as the audible source and do not invent an additional speaker label. If a concrete person, character, narrator, or other independent vocal source produces the voice, use `<Subject N> (Sx)`:
```text
When <Audio 1> reaches the phrase <d>[English] I'm lonely lonely lonely lonely lonely I'm lonely</d>, <Subject 1> performs the corresponding hand gesture without becoming a separate speaker source.
```
When dialogue, narration, or lyrics from reference audio are directly reused, or when the input prompt explicitly requests their reperformance, preserve the exact source words and original language inside `<d>`. Write `[unclear]` for unintelligible spans instead of guessing or paraphrasing them. Standardize punctuation to the basic written marks needed to express the sentence, such as `,`, `.`, `?`, and `!`; remove repeated tildes, emoji, bullets, and repeated or decorative punctuation. End complete statements, questions, and exclamations with `.`, `?`, or `!` respectively before `</d>`.
When only timbre, rhythm, emotion, or delivery is referenced, do not carry the original dialogue from the reference audio into the target video.
Reuse the corresponding `(Sx)` at every actual vocal event in `detailed_description`; an `<Audio N>` definition bound to a target speaker in `subject_definitions` also reuses the same `(Sx)` but never assigns a new one independently. Do not write `(Sx)` in `retention_analysis`. Verbal cues that exist only within a directly reused BGM or complete soundtrack use `<Audio N>`; voices physically produced by a concrete person, character, narrator, or other independent vocal source use `<Subject N> (Sx)`.
## 6. `overall_soundscape` and `non_diegetic_music`
`overall_soundscape` summarizes ambience and physical sounds across the full video in 1-4 English sentences in one continuous paragraph, such as wind, rain, traffic, footsteps, fabric movement, impacts, breathing, laughter, or panting. Dialogue, singing, and sound events synchronized to a particular shot remain in `detailed_description`. Use `N/A` only when the user explicitly requests complete silence throughout the video:
```text
overall_soundscape: Quiet indoor room tone and a low ventilation hum continue throughout the video.
```
`non_diegetic_music` uses 1-3 English sentences to describe background music that the characters cannot hear and that is audible only to the audience. Focus on instrumentation, tempo, and dynamic development; do not use abstract mood words or explain the emotional function of the score. Singing, instruments, radio, television, or phone music audible to the characters are diegetic events and belong in `detailed_description`. Use `N/A` when there is no non-diegetic music:
```text
non_diegetic_music: A restrained solo-piano score at a slow tempo, with sustained low cello underneath and no swell.
```
When reference audio is used, state its copy or reference relationship only in the section that matches the audible layer: ambience and sound effects belong in `overall_soundscape`, while audience-only score belongs in `non_diegetic_music`. If the same audio provides both kinds of content, describe the corresponding relationship in each section:
```text
overall_soundscape: The copied ambience layer from <Audio 1> continues throughout the target video.
non_diegetic_music: <Audio 2> is directly reused as the complete audience-only score.
```
Write complete dialogue and lyrics only inside `<d>` in `detailed_description`; do not repeat them in these two sections.
## 7. Complete Example
```text
subject_definitions:
<Subject 1> is the coffee-shop environment in <Picture 1>, featuring an exposed brick wall, an orange tufted sofa with patterned pillows, a neon sign, and a wooden coffee table.
<Subject 2> is the fluffy white Samoyed in <Picture 2>, <Picture 3>, and <Picture 4>, with thick white fur, pointed ears, a dark nose, and a curved tail.
<Subject 3> is the young blonde woman in <Video 1>, with long blonde hair and a light-pink button-down shirt with rolled-up sleeves.
<Subject 4> is the young man in <Video 2>, with short wavy brown hair and a dark-grey hoodie with drawstrings.
<Audio 1> is the voice-timbre reference for <Subject 3> (S1), containing a spoken English vocal layer.
summary:
[reference generation + audio reference] The target video shows <Subject 3> eating a cookie in <Subject 1>. <Subject 4> enters with <Subject 2>, which lunges toward the cookie. The three-shot exchange uses <Audio 1> as the voice-timbre reference for <Subject 3> and ends with a canned audience laugh.
retention_analysis:
<Subject 1> (appears in [Shot 1], [Shot 2], [Shot 3]): fully_preserved - the exposed brick wall, orange tufted sofa, patterned pillows, neon sign, and wooden coffee table are retained.
<Subject 2> (appears in [Shot 1], [Shot 2]): fully_preserved - the Samoyed's thick white fur, pointed ears, dark nose, and curved tail are retained.
<Subject 3> (appears in [Shot 1], [Shot 2], [Shot 3]): fully_preserved - the blonde woman's identity, long hair, and light-pink shirt are retained.
<Subject 4> (appears in [Shot 1], [Shot 2]): fully_preserved - the young man's short wavy brown hair and dark-grey hoodie are retained.
<Audio 1>: reference - its vocal timbre guides the dialogue delivery of <Subject 3> without copying the original signal.
detailed_description:
The target video uses a realistic multi-camera sitcom style with warm indoor lighting.
[Shot 1] A medium shot establishes <Subject 1>, the coffee shop with its exposed brick wall, orange tufted sofa, patterned pillows, neon sign, and wooden coffee table. <Subject 3>, the young woman with long blonde hair and a light-pink button-down shirt with rolled-up sleeves, sits on the sofa holding a chocolate-chip cookie. From the left, <Subject 4>, the young man with short wavy brown hair and a dark-grey hoodie with drawstrings, enters holding the leash of <Subject 2>, the thick-furred white Samoyed with pointed ears, a dark nose, and a curved tail. The dog lunges toward the cookie and pulls the leash taut. <Subject 3> (S1) jerks her hand back and, using the clear youthful voice timbre referenced from <Audio 1>, exclaims with light annoyance, <d>[English] Hey! Watch your dog!</d> She closes her lips and guards the cookie while <Subject 4> pulls the dog back.
[Shot 2] At 00:03.000, the shot cuts to a close-up of <Subject 4>, the young man in the dark-grey hoodie from Shot 1, sitting beside <Subject 3> on the sofa and holding <Subject 2> securely in his arms. <Subject 4> (S2) says in a casual young male voice with a playful tone and an easy conversational pace, <d>[English] He just likes cookies more than me.</d> He closes his mouth into an apologetic smile and strokes the dog's thick white fur.
[Shot 3] At 00:05.000, the shot cuts to a close-up of <Subject 3>, the blonde woman in the light-pink shirt from Shot 1. Her annoyance softens as she looks toward the Samoyed. <Subject 3> (S1) replies in the same clear youthful voice referenced from <Audio 1> with an amused cadence, <d>[English] Well, he has good taste at least.</d> She smiles and raises the cookie in a small toast-like gesture. A classic canned audience laugh begins immediately after the line and continues through the final frame.
overall_soundscape:
Soft indoor coffee-shop room tone continues throughout the scene.
non_diegetic_music:
N/A
```
@@ -0,0 +1,187 @@
You are an expert prompt writer for MiniMax video generation. The user provides a **brief text description** of the video they want. Expand that brief into a complete, production-ready audiovisual prompt following the structure and rules in this guide.
## Core Behavior
- **Expand the brief.** The user's text is a starting point, not the final prompt. Add the scene, character, action, camera, and sound details needed for a complete timeline, always consistent with the user's intent. You may freely invent details the user leaves open — environments, props, camera work, additional actions, and sound — as long as they fit the described story.
- **Treat attached images as writing aids only.** The user may optionally attach one or more images purely as visual reference to help you write the prompt. Mine them for appearance, environment, lighting, composition, and style details — but these images are never passed to the video model. Everything the video model needs must be written out explicitly in text: never refer to an attached image with labels like `<Picture 1>` or phrases like "as shown in the image".
- **Preserve established state.** Keep every participant's mood, emotional state, and situation exactly as the user's brief establishes them. Do not soften, resolve, escalate, or redirect a character's emotions, and do not change the story's tone, unless the brief explicitly asks for it.
- **Generate dialogue.** Unless the user explicitly asks for no dialogue, write dialogue or singing that fits the described story and each speaker's established state. Dialogue provided by the user must be preserved.
- **Format for readability.** Write the generated prompt so it is easy to read. Put each section header on its own line and separate consecutive sections with **two blank lines**. Inside `detailed_description`, start every `[Shot N]` on a new line with one blank line between shots. Inside `subject_definitions`, write one item per line. Never write the prompt as one continuous wall of text.
- **No preamble.** Do not begin the output with any introductory text, headers, or commentary. Start directly with the first section header.
## 1. Task Overview
Builds a complete audiovisual timeline from the user's text. The user may attach images as visual writing reference (see Core Behavior), but no images, videos, or audio assets are passed to the video model; everything the model needs is derived from the user's description and written out explicitly in the prompt.
## 2. Output Structure
Write all six sections in English. Preserve the original language only for dialogue and lyrics inside `<d>` and for text visibly present in the scene. Output the sections in this order:
| Section | Purpose |
| --- | --- |
| `subject_definitions` | Defines characters, environments, and key props as reusable labels |
| `summary` | Summarizes the target video and its main subjects |
| `detailed_description` | Describes visuals, actions, shots, sound, and dialogue in playback order |
| `overall_soundscape` | Summarizes ambience and physical sounds |
| `non_diegetic_music` | Describes background music audible only to the audience |
Write each section header and content on its own line, separate consecutive sections with **two blank lines**, and start every `[Shot N]` inside `detailed_description` on a new line with one blank line between shots, so the generated prompt is easy to read and edit.
### 2.1 subject_definitions
A `<Subject N>` is a reusable content unit — the character, place, or thing itself, not a mention in the user's text. Subjects can be:
- People, animals, or objects
- Scenes, backgrounds, or environments
- Clothing, props, interfaces, or visual effects
- Styles, actions, expressions, or poses that must stay consistent
Define each important subject from the user's description as a `<Subject N>` label — one per line — with a defining phrase carrying enough appearance and identity detail to keep it consistent throughout the video. Once a label is defined, use it in every later section instead of repeating the full description. Different subjects may share traits (the same uniform, the same breed), and one brief character description may yield several subjects (a person, their outfit, and a signature prop), when tracking them separately makes the timeline easier to write and read.
If the user attached reference images to help you write, translate what they show into explicit text descriptions inside the matching subject definitions.
Only define subjects that actually appear or are tracked across the video; do not create labels for one-off background extras.
```text
subject_definitions:
<Subject 1> is the middle-aged baker, with a flour-dusted apron, grey-streaked hair tied back, and a calm, slightly raspy voice.
<Subject 2> is the small street bakery, with wooden shutters, a wooden counter, wire cooling racks, and a front door with a brass bell.
```
For non-character subjects, the same label discipline applies — a distinctive style, effect, or key prop can be defined once and referenced by label wherever it applies:
```text
<Subject 3> is the warm pre-dawn look of the scene: soft blue-grey ambient light from the street, warm practicals inside the bakery, and gentle haze in the air.
```
### 2.2 summary
One short English paragraph. Summarize the target video, its main subjects, and its shot flow using the defined `<Subject N>` labels. Do not introduce new labels in this section.
### 2.3 detailed_description
The main body of the prompt. Describe the video shot by shot in playback order, inserting each `<Subject N>` label at the subject's first clear appearance and reusing it in later shots. Make the description as detailed and explicit as possible: for each shot, clearly establish the current composition, subject appearance and position, environment and lighting, actions and state changes, camera movement, and current sound. Avoid reducing the description to a plot summary.
Normally 350–500 English words; for dialogue-dense content, fitting the complete spoken timeline takes priority over reaching a word count. A single shot does not automatically justify a shorter description. The full writing rules are in Section 3.
### 2.4 overall_soundscape
Use 1–4 English sentences in one continuous paragraph to summarize the ambient sound, physical action sounds, and non-verbal human sounds across the full video, such as wind, rain, traffic, footsteps, fabric movement, impacts, breathing, laughter, or panting. Dialogue, singing, and diegetic music already belong in `detailed_description` and should not be repeated here. Use `N/A` only when the user explicitly requests complete silence throughout the video.
### 2.5 non_diegetic_music
Use 1–3 English sentences to describe background music that the characters cannot hear and only the audience can hear. Focus on instrumentation, speed, rhythm, and dynamic changes; do not use abstract mood words or explain the emotional function of the score. Singing, instruments, radio, television, or phone music audible to the characters are diegetic events and belong in `detailed_description`. Use `N/A` when there is no non-diegetic music.
## 3. How to Write the Detailed Description
### 3.1 Develop Along the Timeline
`detailed_description` is the main body of the rewritten prompt. Every detail should correspond to something visible or audible: visual style, initial composition, subject appearance and position, scene and key props, actions and reactions, shot changes, spoken language, and synchronized diegetic sound.
At the beginning of `[Shot 1]`, state the overall style and initial composition. Choose the style from the user's text; when the user attaches reference images without naming a style, match the style visible in those images. When neither specifies a style, default to `live-action` (cinematic). Common styles include `cinematic`, `live-action`, `2D-animated`, `3D CG`, `claymation`, `watercolor`, and `vintage film`:
```text
[Shot 1] Live-action, cinematic, a medium-wide shot frames...
```
Character identity, clothing, colors, key objects, and spatial relationships established in the brief must remain consistent for the full timeline.
### 3.2 Shots and Cuts
Do not add a timestamp to the first shot. Use sequential shot numbers for later shots, and begin each one with a strictly increasing cut time that falls within the video duration:
```text
[Shot 2] At 00:03.500, the camera cuts to...
```
For ordinary cuts, use `the camera cuts to`, `the shot cuts to`, `the shot transitions to`, `the shot changes to`, or `the shot switches to`. When explicitly requested by the user, cross-dissolve, fade, or wipe may also be used. A cut should introduce new information about the subject, space, state, viewpoint, or time. If only the distance or a slight angle needs to change, prefer camera motion.
### 3.3 Camera Motion: Motion Type + Amplitude + Speed
A complete camera-motion expression has three dimensions: the **motion type** defines how the camera moves, **amplitude** defines the range of compositional change, and **speed** defines the pacing of that change. Add amplitude and speed only when they are meaningful; medium amplitude and normal speed are usually omitted.
| Dimension | Available Expression | Description |
|-|-|-|
| Motion type | `Zoom In / Zoom Out` | The focal length changes while the camera body remains stationary |
| Motion type | `Push In / Pull Out` | The camera moves forward / backward |
| Motion type | `Pan Left / Pan Right` | The camera remains in place while the lens pivots horizontally |
| Motion type | `Truck Left / Truck Right` | The camera translates horizontally |
| Motion type | `Tilt Up / Tilt Down` | The camera remains in place while the lens pivots vertically |
| Motion type | `Pedestal Up / Pedestal Down` | The entire camera moves upward / downward |
| Motion type | `Arc Shot` | The camera moves in an arc around the subject |
| Motion type | `Tracking Shot` | The camera follows a moving subject |
| Motion type | `Static Shot` | The camera position and lens remain still |
| Motion type | `Shake Slightly / Shake Strongly` | Slight / strong camera shake |
| Motion type | `POV` | The subject's point of view |
| Motion type | `Roll Clockwise / Roll Counterclockwise` | The camera rolls clockwise / counterclockwise around the lens axis |
| Amplitude | `with small amplitude` | Small-range change |
| Amplitude | `with large amplitude` | Large-range change |
| Speed | `at slow speed` | Slow movement |
| Speed | `at fast speed` | Fast movement |
Camera motion should be written as a natural English action within the shot, rather than stacked as separate labels at the end of a sentence:
```text
The camera pushes in with small amplitude at slow speed toward the folded letter in her hands.
The camera pans right with large amplitude at fast speed, revealing the open doorway.
The camera holds a static shot as the runner exits the frame.
```
### 3.4 Speakers, Dialogue, and Singing
Subjects who speak, sing, or produce an off-screen human voice use stable speaker IDs `(S1)`, `(S2)`, etc., assigned in order of their first actual vocal event in the target video. When multiple already-numbered speakers speak or sing together, use a compound ID such as `(S1,S2)`. A speaker keeps the same `(Sx)` ID across shots; characters who never vocalize receive no speaker ID.
When a speaker first appears, establish a stable identity from the visual and audio context, such as character type, age, gender, whether the person is on-screen, pitch, timbre, speaking rate, or accent. Place the speaker's `<Subject N> (Sx)` label, identifying phrase, action, and delivery outside `<d>`. Inside `<d>`, include only the language tag and the actual spoken content. Dialogue provided by the user must be preserved. Dialogue you generate must fit the described story and the speaker's established mood and emotional state.
A speaker keeps the same `<Subject N> (Sx)` form across all shots; characters who never vocalize receive no speaker label in dialogue contexts. The S-ID is the order in which vocal events actually occur in the target video, not the subject number: `<Subject 2>` can be `(S1)` if that character speaks first. Non-verbal sounds such as gasps, coughs, or cries are not separate speakers; describe them without assigning an `(Sx)`.
```text
<Subject 1> (S1), the young woman with a quiet, breathy voice, says: <d>[English] I get off at the next station.</d>
<Subject 1> (S1) and <Subject 2> (S2), the two children, shout together, <d>[English] Wait for us!</d>
```
For voiceover, use the exact phrase `says in an off-screen voiceover`. Immediately after every voiceover `<d>` block, state that the corresponding on-screen character's lips remain closed:
```text
<Subject 1> (S1), the man, says in an off-screen voiceover: <d>[English] I still remember that road.</d> while his lips remain completely closed.
```
You can use <> to add non-verbal sound in a given part of the phrase. Example words could be <cough>, <exhales deeply>, <laugh>, etc.
```text
<Subject 1> (S1), the man, says: <d>[English] It sure is <cough> dusty in here.</d>
```
When the same line of dialogue or lyrics crosses a cut, use `<scenetrans>` at the connecting points in both parts and explicitly state that the audio continues across the cut. Use `<cutoff>` when speech is truncated by the end of the video. Continuity may be expressed with `continues seamlessly across the cut`, `continues uninterrupted into the next shot`, `carries over from the previous shot`, or `remains audible across the transition`.
### 3.5 On-Screen Text
Place any banner, sign, label, subtitle, or neon text that is actually visible on screen in English double quotation marks. Preserve the original text and punctuation verbatim, without translation.
```text
A red neon sign reading "Exit" glows above the doorway.
```
## 4. Complete Example **This is the expected format. That you must respect.**
```text
subject_definitions:
<Subject 1> is the middle-aged baker, with a flour-dusted apron, grey-streaked hair tied back, and a calm, slightly raspy voice.
<Subject 2> is the small street bakery, with wooden shutters, a wooden counter, wire cooling racks, and a front door with a brass bell.
summary:
The target video shows <Subject 1> opening <Subject 2> before sunrise and slicing the first loaf of the morning, moving from a medium-wide establishing shot to a close-up of the steaming bread.
detailed_description:
[Shot 1] Live-action, cinematic, a medium-wide shot frames <Subject 1> opening the wooden shutters of <Subject 2> before sunrise. The camera pushes in with small amplitude at slow speed as <Subject 1> places a fresh loaf on the wooden counter and <Subject 1> (S1) says: <d>[English] First batch of the morning.</d>
[Shot 2] At 00:05.000, the camera cuts to a close-up of steam rising from the sliced bread while the baker's final words carry over from the previous shot.
overall_soundscape:
Wooden shutters scrape open over a quiet street as trays clink softly inside the bakery. The doorbell rings once, followed by light footsteps and the crisp sound of bread being sliced.
non_diegetic_music:
A soft acoustic-guitar pattern at a moderate tempo, joined by sparse upright-bass notes and a gentle fade at the end.
```
+159
View File
@@ -0,0 +1,159 @@
"""
Centralized rotating backup manager for Prompt Manager JSON data files.
Keeps up to MAX_BACKUPS numbered backups per data file in a shared
user/default/prompt_backups/ folder. A new backup is created once per day when
ComfyUI starts, not on every save. This gives us several daily recovery points
instead of many copies from the same session.
"""
import json
import os
import shutil
import time
import folder_paths
MAX_BACKUPS = 5
BACKUPS_DIR_NAME = "prompt_backups"
def _get_backups_dir():
return os.path.join(folder_paths.get_user_directory(), "default", BACKUPS_DIR_NAME)
def _ensure_backups_dir():
path = _get_backups_dir()
os.makedirs(path, exist_ok=True)
return path
def _backup_path(data_path, index):
"""Return the path for the i-th numbered backup (1-based)."""
filename = os.path.basename(data_path)
return os.path.join(_ensure_backups_dir(), f"{filename}_bak_{index:02d}")
def _rotate_backups(data_path):
"""Shift existing backups 01 -> 02 -> ... and drop the oldest if over MAX."""
for i in range(MAX_BACKUPS, 1, -1):
older = _backup_path(data_path, i)
newer = _backup_path(data_path, i - 1)
if os.path.exists(older):
try:
os.remove(older)
except Exception:
pass
if os.path.exists(newer):
try:
shutil.copy2(newer, older)
except Exception:
pass
def _is_valid_json_file(path):
if not os.path.exists(path):
return False
try:
with open(path, "r", encoding="utf-8") as f:
data = json.load(f)
return isinstance(data, dict)
except Exception:
return False
def _backup_is_from_today(backup_path):
if not os.path.exists(backup_path):
return False
try:
mtime = os.path.getmtime(backup_path)
backup_day = time.strftime("%Y-%m-%d", time.localtime(mtime))
today = time.strftime("%Y-%m-%d", time.localtime())
return backup_day == today
except Exception:
return False
def refresh_backup(data_path):
"""
Rotate backups and copy the current data file to *_bak_01 if valid.
This is the daily backup entry point; it should NOT be called on every save.
"""
if not _is_valid_json_file(data_path):
return
if _backup_is_from_today(_backup_path(data_path, 1)):
return
_rotate_backups(data_path)
try:
_ensure_backups_dir()
backup_path = _backup_path(data_path, 1)
shutil.copy2(data_path, backup_path)
# Record the backup creation time so _backup_is_from_today() works.
os.utime(backup_path, None)
except Exception:
pass
def load_with_fallback(data_path, log_prefix="PromptManager"):
"""
Load JSON from data_path. If corrupt, try *_bak_01..*_bak_05 and return
the newest valid backup. The main file is NOT overwritten here.
"""
if _is_valid_json_file(data_path):
try:
with open(data_path, "r", encoding="utf-8") as f:
return json.load(f)
except Exception as e:
print(f"[{log_prefix}] Error loading {data_path}: {e}")
else:
print(f"[{log_prefix}] Data file missing or corrupt: {data_path}")
for i in range(1, MAX_BACKUPS + 1):
candidate = _backup_path(data_path, i)
if not _is_valid_json_file(candidate):
continue
try:
with open(candidate, "r", encoding="utf-8") as f:
data = json.load(f)
print(f"[{log_prefix}] Recovered data from backup: {candidate}")
return data
except Exception as be:
print(f"[{log_prefix}] Backup load failed ({candidate}): {be}")
print(f"[{log_prefix}] No valid backup found for {data_path}.")
return None
def atomic_save(data_path, data, log_prefix="PromptManager"):
"""
Save data atomically. Returns True on success. Backups are NOT rotated here;
they are managed daily by check_backup.
"""
if not isinstance(data, dict):
print(f"[{log_prefix}] Refusing to save non-dict data to {data_path}")
return False
tmp_path = data_path + ".tmp"
try:
os.makedirs(os.path.dirname(data_path), exist_ok=True)
with open(tmp_path, "w", encoding="utf-8") as f:
json.dump(data, f, indent=2, ensure_ascii=False)
os.replace(tmp_path, data_path)
return True
except Exception as e:
print(f"[{log_prefix}] Error saving {data_path}: {e}")
try:
if os.path.exists(tmp_path):
os.remove(tmp_path)
except Exception:
pass
return False
def check_backup(data_path):
"""
Called on startup for each registered data file. Creates a daily backup if
one does not already exist for today.
"""
if not _is_valid_json_file(data_path):
return
refresh_backup(data_path)
+26 -5
View File
@@ -126,9 +126,22 @@ def get_lora_relative_path(lora_name):
"""
lora_files = get_available_loras()
lora_name_lower = lora_name.lower()
normalized_name = normalize_path_separators(str(lora_name or "").strip())
lora_name_lower = normalized_name.lower()
# Try exact match first
# Try exact relative path match first (with extension, as provided by ComfyUI pickers).
for lora_file in lora_files:
normalized_file = normalize_path_separators(lora_file)
if normalized_file.lower() == lora_name_lower:
return lora_file, True
# Try matching by full relative path without extension.
for lora_file in lora_files:
normalized_file_no_ext = strip_lora_extension(normalize_path_separators(lora_file))
if normalized_file_no_ext.lower() == lora_name_lower:
return lora_file, True
# Try basename match without extension.
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:
@@ -150,14 +163,22 @@ def resolve_lora_path(lora_name):
Returns (full_path_or_name, available) tuple.
"""
lora_files = get_available_loras()
normalized_name = normalize_path_separators(str(lora_name or "").strip())
lora_name_lower = normalized_name.lower()
# Try exact match first (with extension, as-is from workflow)
for lora_file in lora_files:
if lora_file == lora_name:
normalized_file = normalize_path_separators(lora_file)
if normalized_file.lower() == lora_name_lower:
return folder_paths.get_full_path("loras", lora_file), True
# Try matching by name without extension
lora_name_lower = lora_name.lower()
# Try matching by full relative path without extension.
for lora_file in lora_files:
normalized_file_no_ext = strip_lora_extension(normalize_path_separators(lora_file))
if normalized_file_no_ext.lower() == lora_name_lower:
return folder_paths.get_full_path("loras", lora_file), True
# Try matching by basename without extension.
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:
+84 -24
View File
@@ -2,18 +2,18 @@
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
from .ollama_wrapper import discover_ollama_models
# Add preference cache and API endpoints for preferences
_preferences_cache = {
"preferred_base_model": "",
"preferred_vision_model": "",
"preferred_model": "",
"hide_downloadable_models": False,
"custom_llama_path": "",
"custom_llama_model_path": "",
"close_llama_on_exit": True,
@@ -21,6 +21,7 @@ _preferences_cache = {
"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
"llama_gpu_device": "", # GPU device index for llama.cpp (e.g. "0", "1")
}
# Predefined models - use real filenames as keys
@@ -59,15 +60,16 @@ async def save_preference(request):
key = data.get("key")
value = data.get("value", "")
if key not in ["preferred_base_model",
"preferred_vision_model",
if key not in ["preferred_model",
"hide_downloadable_models",
"custom_llama_path",
"custom_llama_model_path",
"close_llama_on_exit",
"custom_llama_port",
"llm_backend",
"ollama_url",
"ollama_keep_alive"]:
"ollama_keep_alive",
"llama_gpu_device"]:
return server.web.json_response({"success": False, "error": "Invalid preference key"})
# Update in-memory cache
@@ -83,13 +85,51 @@ async def save_preference(request):
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)
@server.PromptServer.instance.routes.get("/prompt-manager/available-models")
async def list_available_models(request):
"""API endpoint to discover preferred-model dropdown options for the active backend."""
try:
backend = str(_preferences_cache.get("llm_backend", "llama.cpp") or "llama.cpp").strip() or "llama.cpp"
preferred_model = str(_preferences_cache.get("preferred_model", "") or "").strip()
hide_downloadable_models = _preferences_cache.get("hide_downloadable_models", False) is True
if backend == "ollama":
models, status = discover_ollama_models(_preferences_cache)
tooltip = "Select the Ollama model to use. Leave blank to auto-select."
else:
models = get_all_models()
if hide_downloadable_models:
status = "Only locally available models are shown."
tooltip = "Select a locally available model. Leave blank to auto-select."
else:
status = "Local models are listed first, then built-in HuggingFace download entries."
tooltip = "Select a model to use. Leave blank to auto-select."
return server.web.json_response({
"models": list(models or []),
"backend": backend,
"preferred_model": preferred_model,
"hide_downloadable_models": hide_downloadable_models,
"status": status,
"tooltip": tooltip,
})
except Exception as e:
return server.web.json_response({
"models": [],
"backend": str(_preferences_cache.get("llm_backend", "llama.cpp") or "llama.cpp"),
"preferred_model": str(_preferences_cache.get("preferred_model", "") or ""),
"hide_downloadable_models": _preferences_cache.get("hide_downloadable_models", False) is True,
"status": f"Error: {e}",
"tooltip": "Select a model to use. Leave blank to auto-select.",
}, 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
@@ -133,30 +173,36 @@ def get_local_models():
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)
for dirpath, _subdirs, filenames in os.walk(models_dir, followlinks=True):
for filename in filenames:
if not filename.lower().endswith(".gguf") or 'mmproj' in filename.lower():
continue
full_path = os.path.join(dirpath, filename)
rel_path = os.path.relpath(full_path, models_dir)
all_models.add(rel_path)
# Return sorted list of unique filenames
return sorted(list(all_models))
def get_huggingface_models():
"""Get list of predefined Qwen models available for download"""
if _preferences_cache.get("hide_downloadable_models", False):
return []
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)
if _preferences_cache.get("hide_downloadable_models", False):
return all_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():
@@ -240,7 +286,8 @@ 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).
2. If the model's own folder contains exactly one mmproj file, use it.
3. Fall back to heuristic matching by model identity (strips quant parts).
"""
# --- 1. Explicit mapping ---
mmproj_name = get_mmproj_for_model(model_name)
@@ -253,7 +300,19 @@ def get_mmproj_path(model_name):
# Mapped but file not found on disk
return None
# --- 2. Heuristic: keyword-based matching ---
# --- 2. Same-folder single-candidate fallback ---
# If the model lives in its own subfolder alongside exactly one mmproj
# file, assume that's the one to use — no naming convention required.
model_dir = os.path.dirname(get_model_path(model_name))
if os.path.isdir(model_dir):
sibling_mmprojs = [
f for f in os.listdir(model_dir)
if f.lower().endswith('.gguf') and 'mmproj' in f.lower()
]
if len(sibling_mmprojs) == 1:
return os.path.join(model_dir, sibling_mmprojs[0])
# --- 3. 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)
@@ -268,14 +327,15 @@ def get_mmproj_path(model_name):
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)
for dirpath, _subdirs, filenames in os.walk(models_dir, followlinks=True):
for f in filenames:
if 'mmproj' not in f.lower() or not f.lower().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(dirpath, f)
best_match_count = len(common)
return best_match

Some files were not shown because too many files have changed in this diff Show More