Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e20f6523d9 | ||
|
|
d7fde3cce4 | ||
|
|
bf0edbabc9 | ||
|
|
ed78a1bf05 | ||
|
|
698cd7b725 | ||
|
|
d93c2713d5 | ||
|
|
dc971491d1 | ||
|
|
f5391da99a | ||
|
|
539828c8af | ||
|
|
16192ad6dd | ||
|
|
4dad2816d0 | ||
|
|
d1967d8395 | ||
|
|
ad1a4290bc | ||
|
|
e800b272cc | ||
|
|
4b93b7902d | ||
|
|
04808107c2 | ||
|
|
376e973ba0 | ||
|
|
0e4ca673fc | ||
|
|
70dc0e38e0 | ||
|
|
0297da28e6 |
@@ -0,0 +1,15 @@
|
||||
# These are supported funding model platforms
|
||||
|
||||
github: franckyb # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
|
||||
patreon: # Replace with a single Patreon username
|
||||
open_collective: # Replace with a single Open Collective username
|
||||
ko_fi: # Replace with a single Ko-fi username
|
||||
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
|
||||
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
|
||||
liberapay: # Replace with a single Liberapay username
|
||||
issuehunt: # Replace with a single IssueHunt username
|
||||
lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry
|
||||
polar: # Replace with a single Polar username
|
||||
buy_me_a_coffee: # Replace with a single Buy Me a Coffee username
|
||||
thanks_dev: # Replace with a single thanks.dev username
|
||||
custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
|
||||
@@ -7,7 +7,7 @@ A complete prompt management solution featuring three core capabilities:
|
||||
|
||||
**Prompt Manager Advanced** — Save and organize prompts with categories, complete with matching LoRA stacks, trigger words, and thumbnail previews. Supports dual LoRA stacks for complex workflows like Wan videos. Toggle LoRAs on/off or adjust strengths directly from saved presets. Will also remap Loras if path differs.
|
||||
|
||||
**Prompt Generator** — Generate and enhance prompts using local LLMs via [llama.cpp](https://github.com/ggerganov/llama.cpp). Supports text enhancement, image analysis with vision models (Qwen3VL), and thinking mode for deeper reasoning. Analyze up to 5 images at once.
|
||||
**Prompt Generator** — Generate and enhance prompts using local LLMs via [llama.cpp](https://github.com/ggerganov/llama.cpp) or [Ollama](https://ollama.com). Supports text enhancement, image analysis with vision models (Qwen3.5), and thinking mode for deeper reasoning. Analyze up to 5 images at once.
|
||||
|
||||
**Prompt Extractor** — Extract prompts and LoRA configurations from existing images, videos, or JSON workflow files. Will extract first frame from any video. Automatically parses embedded metadata and outputs active LoRA as Lora stacks. When used in conjunction with Prompt Manager Advanced, Loras will be automatically found if available, regardless of path. For those that aren't, right click offers the option to look for them on Civitai.
|
||||
___
|
||||
@@ -33,12 +33,17 @@ ___
|
||||
### Prompt Manager:
|
||||
- **Category Organization**: Create and manage multiple categories to organize your prompts
|
||||
- **Save & Load Prompts**: Quickly save and recall your favorite prompts with custom names
|
||||
- **NSFW Tagging**: Mark categories and individual prompts as NSFW with visual badge indicator on the node title bar
|
||||
- **NSFW Filtering**: Hide/show NSFW content via a global preference — NSFW categories and prompts are filtered from dropdowns when hidden
|
||||
- **LLM Input Toggle**: Connect text outputs from other nodes and toggle between using them or your internal prompts
|
||||
- **LLM Input Toggle**: When in use, display of categories and prompt is disabled, allowing user to switch category and save.
|
||||
- **Persistent Storage**: All prompts saved in your ComfyUI user folder
|
||||
|
||||
### Prompt Manager Advanced:
|
||||
- **All Prompt Manager Features**: Everything from the basic Prompt Manager, plus LoRA and Trigger word integration
|
||||
- **NSFW Tagging**: Mark categories and individual prompts as NSFW — red "NSFW" badge appears on the prompt selector and in the thumbnail browser
|
||||
- **NSFW Filtering**: Session-persistent NSFW toggle button in the thumbnail browser to show/hide NSFW content; navigation arrows skip NSFW entries when hidden
|
||||
- **List View Mode**: Switch between thumbnail grid and compact list view in the prompt browser, with session-persistent preference
|
||||
- **Prompt Thumbnails**: Save thumbnail images with your prompts for visual identification in the dropdown
|
||||
- **Dual LoRA Stack Support**: Two separate LoRA stack inputs/outputs for complex workflows (e.g., Wan video with different LoRAs for image and video)
|
||||
- **Visual LoRA Tags**: See connected LoRAs as clickable tags with strength values
|
||||
@@ -68,16 +73,17 @@ ___
|
||||
|
||||
### Prompt Generator
|
||||
- **Three Generation Modes**: Enhance text prompts, analyze images, or analyze images with custom instructions
|
||||
- **Dual Backend Support**: Use llama.cpp (local server, default) or Ollama as the LLM backend
|
||||
- **Prompt Enhancement**: Transform basic prompts into detailed descriptions using local LLMs
|
||||
- **Vision Analysis**: Analyze images with Qwen3VL models to generate detailed descriptions
|
||||
- **Vision Analysis**: Analyze images with vision-capable models to generate detailed descriptions
|
||||
- **Custom Image Analysis**: Provide your own instructions for image analysis
|
||||
- **JSON Output**: Optional structured JSON output with scene breakdown
|
||||
- **Thinking Support**: Support Thinking models to perform deeper generative reasoning.
|
||||
- **Automatic Server Management**: Starts/stops llama.cpp server as needed, with automatic shut off at exit.
|
||||
- **Smart Model Selection**: Auto-selects appropriate model (vision or text) based on mode or Thinking mode.
|
||||
- **Smart Model Selection**: Auto-selects appropriate model based on mode, using mmproj-based vision detection.
|
||||
|
||||
### Prompt Generator Options
|
||||
- **Model Selection**: Choose from local models or download Qwen3, Qwen3VL and Qwen3VL Thinking models from HuggingFace
|
||||
- **Model Selection**: Choose from local models or download Qwen3.5 models from HuggingFace
|
||||
- **Auto-Download**: Automatically downloads both model and required mmproj files for vision models
|
||||
- **LLM Parameters**: Fine-tune temperature, top_k, top_p, min_p, repeat_penalty and context size.
|
||||
- **Custom Instructions**: Override default system prompt for different enhancement styles.
|
||||
@@ -85,9 +91,11 @@ ___
|
||||
- **Console Debugging**: Enable outputing the entire process to the console for debugging purposes.
|
||||
|
||||
### Preference Options
|
||||
- Set choices for prefered Model for both base mode and VL model.
|
||||
- Set choices for prefered Model for both base mode and vision model.
|
||||
- Set new default model location, previous folder (gguf and llm) will still be scanned, but model will save in new default.
|
||||
- Set custom Location for Llama.cpp. If Llama.cpp was not added to the system Path, this option let's you specify it's location.
|
||||
- **LLM Backend**: Choose between llama.cpp (default) or Ollama as the generation backend.
|
||||
- **Ollama Settings**: Configure Ollama URL and keep-alive duration for model memory management.
|
||||
|
||||
### Save Video H264/H265
|
||||
- **Codec Selection**: Choose between H.264 (8-bit, better compatibility) or H.265/HEVC (10-bit, better compression and gradients)
|
||||
@@ -196,13 +204,11 @@ ___
|
||||
7. **Enable Debugging**: Enable complete printout of process to console using show_everything_in_console
|
||||
|
||||
**Qwen models found in options**
|
||||
- Qwen3-1.7B-Q8_0.gguf: Fastest, lowest VRAM (~2GB)
|
||||
- Qwen3-4B-Q8_0.gguf: Balanced performance (~4GB VRAM)
|
||||
- Qwen3-8B-Q8_0.gguf: Best quality, highest VRAM (~8GB)
|
||||
- Qwen3VL-4B-Instruct-Q8_0.gguf: Vision model, balanced performance (~5GB VRAM)
|
||||
- Qwen3VL-8B-Instruct-Q8_0.gguf: Vision model, best quality (~9GB VRAM)
|
||||
- Qwen3VL-4B-Thinking-Q8_0.gguf: Vision model, Thinking variant, balanced performance (~5GB VRAM)
|
||||
- Qwen3VL-8B-Thinking-Q8_0.gguf: Vision model, Thinking variant, best quality (~9GB VRAM)
|
||||
- Qwen3.5-9B-UD-Q4_K_XL.gguf: Unsloth Dynamic 4-bit, good balance (~6GB VRAM)
|
||||
- Qwen3.5-9B-Q8_0.gguf: Standard 8-bit, high quality (~9.5GB VRAM)
|
||||
- Qwen3.5-9B-UD-Q8_K_XL.gguf: Unsloth Dynamic 8-bit, best quality (~13GB VRAM)
|
||||
|
||||
All Qwen3.5 models are unified vision+text — every model supports both text enhancement and image analysis via its mmproj file. Thinking mode is controlled at runtime via a toggle, no separate model variant needed.
|
||||
|
||||
**Model Management**:
|
||||
- Place gguf files in models/gguf folder
|
||||
@@ -210,10 +216,15 @@ ___
|
||||
|
||||
**Preferences**:
|
||||
Preference settings can be found in ComfyUI Settings → Prompt Manager
|
||||
- **Preferred Base Model**: Name of model used for "Enhance User Prompt" mode (text-only models)
|
||||
- **Preferred Vision Model**: Name of model Used for "Analyze Image" modes (Qwen3VL models)
|
||||
- **Preferred Base Model**: Name of model used for "Enhance User Prompt" mode
|
||||
- **Preferred Vision Model**: Name of model used for "Analyze Image" modes
|
||||
- **Set Default Port** You can set the port used by Llama.cpp
|
||||
- **Close Llama on Exit** By default Llama.cpp with be close on exit.
|
||||
- **Close Llama on Exit** By default Llama.cpp will be closed on exit.
|
||||
- **Hide NSFW by Default**: When enabled, NSFW categories and prompts are hidden from all dropdowns, navigation, and the thumbnail browser
|
||||
- **Default View Mode**: Choose between thumbnail grid or list view for the Advanced prompt browser
|
||||
- **LLM Backend**: Choose between llama.cpp (default) or Ollama
|
||||
- **Ollama URL**: Set the Ollama server address (default: http://127.0.0.1:11434)
|
||||
- **Keep Alive Duration**: How long Ollama keeps the model loaded after a request (e.g. 5m, 30m, 0 for immediate unload)
|
||||
|
||||
### Save Video H264/H265
|
||||
|
||||
@@ -239,11 +250,11 @@ Preference settings can be found in ComfyUI Settings → Prompt Manager
|
||||
|
||||
- ComfyUI
|
||||
- Python 3.8+
|
||||
- requests >= 2.31.0
|
||||
- huggingface_hub >= 0.20.0
|
||||
- psutil >= 5.9.0
|
||||
- tqdm >= 4.66.0
|
||||
- Pillow >= 10.0.0
|
||||
- requests
|
||||
- huggingface_hub
|
||||
- psutil
|
||||
- tqdm
|
||||
- Pillow
|
||||
- colorama
|
||||
- llama-server (from llama.cpp)
|
||||
|
||||
@@ -279,6 +290,70 @@ Preference settings can be found in ComfyUI Settings → Prompt Manager
|
||||
|
||||
## Changelog
|
||||
|
||||
### version 1.17.5
|
||||
- **Browser Context Menu Enhancements**
|
||||
- Added "Delete Prompt" option to prompt right-click menu in the thumbnail browser
|
||||
- Added "Delete Category", "Rename Category" options to category right-click menu
|
||||
- Added "+" button at the end of the category list to create new categories directly from the browser
|
||||
- All browser operations preserve unsaved prompt state (text, loras, trigger words are not reset)
|
||||
- **Streamlined More Dropdown**
|
||||
- Removed Rename Category, New Category, Delete Category, and Delete Prompt from the "More" dropdown (now accessible via browser context menus)
|
||||
|
||||
### version 1.17.0
|
||||
- **NSFW Tagging & Filtering**
|
||||
- Mark entire categories or individual prompts as NSFW
|
||||
- Visual red "NSFW" badge on the Prompt Manager node title bar and on the Advanced prompt selector
|
||||
- NSFW badge appears on all prompts within an NSFW-tagged category in the thumbnail browser
|
||||
- Category buttons show red border for NSFW categories in the thumbnail browser
|
||||
- Global preference to hide/show NSFW content — filters dropdowns, navigation arrows, and browser
|
||||
- Session-persistent NSFW toggle button in the Advanced thumbnail browser
|
||||
- Toggle NSFW on categories and prompts via context menu or the save/new category dialogs
|
||||
- **List View Mode**
|
||||
- New compact list view alternative to the thumbnail grid in the Advanced prompt browser
|
||||
- Toggle between grid and list view with a button in the browser controls bar
|
||||
- View mode preference is session-persistent
|
||||
- Default view mode configurable in ComfyUI settings
|
||||
- **UI Improvements**
|
||||
- Search input moved into the controls bar with a clear (×) button
|
||||
- Separator line between category buttons and prompt content
|
||||
|
||||
### version 1.16.0
|
||||
- **Ollama Support**
|
||||
- Added Ollama as an alternative LLM backend alongside llama.cpp
|
||||
- Auto-discovers available Ollama models when no model is explicitly configured
|
||||
- Keep-alive duration setting controls how long Ollama keeps the model loaded in memory
|
||||
- "Stop server after" toggle unloads the model from Ollama memory to free VRAM
|
||||
- **Upgraded to Qwen3.5 Models**
|
||||
- Replaced Qwen3/Qwen3VL models with unified Qwen3.5-9B (vision+text in one model)
|
||||
- Three download options: UD-Q4_K_XL (~6GB), Q8_0 (~9.5GB), UD-Q8_K_XL (~13GB)
|
||||
- Thinking mode is now a runtime toggle — no separate model variant needed
|
||||
- **mmproj-Based Vision Detection**
|
||||
- Vision model detection no longer relies on "VL" in the filename
|
||||
- Models are identified as vision-capable based on the presence of an mmproj file
|
||||
- Heuristic matching supports user-provided models outside the predefined registry
|
||||
- Backward compatible with existing Qwen3VL models and their mmproj files
|
||||
- **Bug Fixes**
|
||||
- Fixed seed control_after_generate not working (increment/decrement/randomize)
|
||||
- Improved Prompt Extractor detection logic
|
||||
|
||||
### version 1.15.9
|
||||
- **Bug Fixes**
|
||||
- Improved Prompt Extractor, enhanced detection logic
|
||||
|
||||
### version 1.15.7
|
||||
- **Added Rename Category Option**
|
||||
- **Bug Fixes**
|
||||
|
||||
### version 1.15.6
|
||||
- **Video Metadata Reader - VHS Compatible**
|
||||
- Added capability to read metadata from VideoHelperSuite generated videos.
|
||||
|
||||
### version 1.15.5
|
||||
- **Added get video components+ node**
|
||||
- Since our save video node can saves latents, this also returns the matching latent (if found) and filepath.
|
||||
- **Video Preview in Prompt Extractor**
|
||||
- Added the option to preview in fullscreen with dark overlay for both images and video on the Prompt Extractor node.
|
||||
|
||||
### version 1.15.0
|
||||
- **Added Animated Latent Preview**
|
||||
- Added Similar option to VideoHelperSuite, to display animated Latent preview. With the addition that it works in TAESD mode.
|
||||
|
||||
+4
-2
@@ -2,7 +2,7 @@
|
||||
ComfyUI Prompt Manager - A simple custom node for saving and reusing prompts
|
||||
A prompt management system for ComfyUI with LLM input support
|
||||
"""
|
||||
__version__ = "1.14.0"
|
||||
__version__ = "1.17.5"
|
||||
__author__ = "François Beaudry"
|
||||
__license__ = "MIT"
|
||||
|
||||
@@ -13,7 +13,7 @@ from .prompt_generator_options import PromptGenOptions
|
||||
from .prompt_apply_lora import PromptApplyLora
|
||||
from .prompt_extractor import PromptExtractor
|
||||
from .model_manager import get_local_models
|
||||
from .save_video_h26x import SaveVideoH26x, LoadLatentFile, MonoToStereo
|
||||
from .save_video_h26x import SaveVideoH26x, LoadLatentFile, MonoToStereo, GetVideoComponentsPlus
|
||||
from server import PromptServer
|
||||
|
||||
# Initialize latent preview hook (with VHS conflict detection)
|
||||
@@ -30,6 +30,7 @@ NODE_CLASS_MAPPINGS = {
|
||||
"SaveVideoH26x": SaveVideoH26x,
|
||||
"LoadLatentFile": LoadLatentFile,
|
||||
"AudioMonoToStereo": MonoToStereo,
|
||||
"GetVideoComponentsPlus": GetVideoComponentsPlus,
|
||||
}
|
||||
|
||||
NODE_DISPLAY_NAME_MAPPINGS = {
|
||||
@@ -42,6 +43,7 @@ NODE_DISPLAY_NAME_MAPPINGS = {
|
||||
"SaveVideoH26x": "Save Video H264/H265",
|
||||
"LoadLatentFile": "Load Latent File",
|
||||
"AudioMonoToStereo": "Audio Mono to Stereo",
|
||||
"GetVideoComponentsPlus": "Get Video Components+",
|
||||
}
|
||||
|
||||
WEB_DIRECTORY = "./js"
|
||||
|
||||
File diff suppressed because one or more lines are too long
+471
-9
@@ -435,6 +435,336 @@ async function cacheVideoFrame(filename, frameData, framePosition) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create and show image preview modal
|
||||
*/
|
||||
function showImagePreviewModal(filename) {
|
||||
// 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=input`;
|
||||
if (subfolder) {
|
||||
imageUrl += `&subfolder=${encodeURIComponent(subfolder)}`;
|
||||
}
|
||||
|
||||
// Create modal overlay
|
||||
const overlay = document.createElement('div');
|
||||
overlay.style.cssText = `
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background: rgba(0, 0, 0, 0.85);
|
||||
z-index: 10000;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
`;
|
||||
|
||||
// Create header with filename and close button
|
||||
const header = document.createElement('div');
|
||||
header.style.cssText = `
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
padding: 15px 20px;
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
background: rgba(0, 0, 0, 0.5);
|
||||
`;
|
||||
|
||||
const title = document.createElement('span');
|
||||
title.textContent = filename;
|
||||
title.style.cssText = `
|
||||
color: #fff;
|
||||
font-size: 14px;
|
||||
font-family: sans-serif;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
max-width: calc(100% - 50px);
|
||||
`;
|
||||
|
||||
const closeBtn = document.createElement('button');
|
||||
closeBtn.textContent = '✕';
|
||||
closeBtn.style.cssText = `
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
border: none;
|
||||
color: #fff;
|
||||
font-size: 20px;
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
border-radius: 50%;
|
||||
cursor: pointer;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
transition: background 0.2s;
|
||||
`;
|
||||
closeBtn.onmouseover = () => closeBtn.style.background = 'rgba(255, 255, 255, 0.2)';
|
||||
closeBtn.onmouseout = () => closeBtn.style.background = 'rgba(255, 255, 255, 0.1)';
|
||||
closeBtn.onclick = () => overlay.remove();
|
||||
|
||||
header.appendChild(title);
|
||||
header.appendChild(closeBtn);
|
||||
|
||||
// Create image container
|
||||
const imageContainer = document.createElement('div');
|
||||
imageContainer.style.cssText = `
|
||||
max-width: 90%;
|
||||
max-height: 80%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
`;
|
||||
|
||||
// Create image element
|
||||
const img = document.createElement('img');
|
||||
img.src = imageUrl;
|
||||
img.style.cssText = `
|
||||
max-width: 100%;
|
||||
max-height: 80vh;
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 10px 40px rgba(0, 0, 0, 0.5);
|
||||
`;
|
||||
|
||||
// Error handling
|
||||
img.onerror = () => {
|
||||
imageContainer.innerHTML = `
|
||||
<div style="color: #ff6666; font-family: sans-serif; text-align: center;">
|
||||
<div style="font-size: 48px; margin-bottom: 10px;">⚠️</div>
|
||||
<div>Failed to load image</div>
|
||||
<div style="font-size: 12px; margin-top: 5px; opacity: 0.7;">${filename}</div>
|
||||
</div>
|
||||
`;
|
||||
};
|
||||
|
||||
imageContainer.appendChild(img);
|
||||
|
||||
// Create keyboard hint
|
||||
const hint = document.createElement('div');
|
||||
hint.textContent = 'Press ESC or click outside to close';
|
||||
hint.style.cssText = `
|
||||
position: absolute;
|
||||
bottom: 20px;
|
||||
color: rgba(255, 255, 255, 0.5);
|
||||
font-size: 12px;
|
||||
font-family: sans-serif;
|
||||
`;
|
||||
|
||||
overlay.appendChild(header);
|
||||
overlay.appendChild(imageContainer);
|
||||
overlay.appendChild(hint);
|
||||
|
||||
// Close on overlay click (but not image click)
|
||||
overlay.onclick = (e) => {
|
||||
if (e.target === overlay) {
|
||||
overlay.remove();
|
||||
}
|
||||
};
|
||||
|
||||
// Close on ESC key
|
||||
const handleKeydown = (e) => {
|
||||
if (e.key === 'Escape') {
|
||||
overlay.remove();
|
||||
document.removeEventListener('keydown', handleKeydown);
|
||||
}
|
||||
};
|
||||
document.addEventListener('keydown', handleKeydown);
|
||||
|
||||
// Add to document
|
||||
document.body.appendChild(overlay);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create and show video preview modal
|
||||
*/
|
||||
function showVideoPreviewModal(filename) {
|
||||
// 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=input`;
|
||||
if (subfolder) {
|
||||
videoUrl += `&subfolder=${encodeURIComponent(subfolder)}`;
|
||||
}
|
||||
|
||||
// Create modal overlay
|
||||
const overlay = document.createElement('div');
|
||||
overlay.style.cssText = `
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background: rgba(0, 0, 0, 0.85);
|
||||
z-index: 10000;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
`;
|
||||
|
||||
// Create header with filename and close button
|
||||
const header = document.createElement('div');
|
||||
header.style.cssText = `
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
padding: 15px 20px;
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
background: rgba(0, 0, 0, 0.5);
|
||||
`;
|
||||
|
||||
const title = document.createElement('span');
|
||||
title.textContent = filename;
|
||||
title.style.cssText = `
|
||||
color: #fff;
|
||||
font-size: 14px;
|
||||
font-family: sans-serif;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
max-width: calc(100% - 50px);
|
||||
`;
|
||||
|
||||
const closeBtn = document.createElement('button');
|
||||
closeBtn.textContent = '✕';
|
||||
closeBtn.style.cssText = `
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
border: none;
|
||||
color: #fff;
|
||||
font-size: 20px;
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
border-radius: 50%;
|
||||
cursor: pointer;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
transition: background 0.2s;
|
||||
`;
|
||||
closeBtn.onmouseover = () => closeBtn.style.background = 'rgba(255, 255, 255, 0.2)';
|
||||
closeBtn.onmouseout = () => closeBtn.style.background = 'rgba(255, 255, 255, 0.1)';
|
||||
closeBtn.onclick = () => overlay.remove();
|
||||
|
||||
header.appendChild(title);
|
||||
header.appendChild(closeBtn);
|
||||
|
||||
// Create video container
|
||||
const videoContainer = document.createElement('div');
|
||||
videoContainer.style.cssText = `
|
||||
max-width: 90%;
|
||||
max-height: 80%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
`;
|
||||
|
||||
// Create video element
|
||||
const video = document.createElement('video');
|
||||
video.src = videoUrl;
|
||||
video.controls = true;
|
||||
video.autoplay = true;
|
||||
video.loop = true;
|
||||
video.style.cssText = `
|
||||
max-width: 100%;
|
||||
max-height: 80vh;
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 10px 40px rgba(0, 0, 0, 0.5);
|
||||
`;
|
||||
|
||||
// Error handling
|
||||
video.onerror = () => {
|
||||
videoContainer.innerHTML = `
|
||||
<div style="color: #ff6666; font-family: sans-serif; text-align: center;">
|
||||
<div style="font-size: 48px; margin-bottom: 10px;">⚠️</div>
|
||||
<div>Failed to load video</div>
|
||||
<div style="font-size: 12px; margin-top: 5px; opacity: 0.7;">${filename}</div>
|
||||
</div>
|
||||
`;
|
||||
};
|
||||
|
||||
videoContainer.appendChild(video);
|
||||
|
||||
// Create keyboard hint
|
||||
const hint = document.createElement('div');
|
||||
hint.textContent = 'Press ESC or click outside to close';
|
||||
hint.style.cssText = `
|
||||
position: absolute;
|
||||
bottom: 20px;
|
||||
color: rgba(255, 255, 255, 0.5);
|
||||
font-size: 12px;
|
||||
font-family: sans-serif;
|
||||
`;
|
||||
|
||||
overlay.appendChild(header);
|
||||
overlay.appendChild(videoContainer);
|
||||
overlay.appendChild(hint);
|
||||
|
||||
// Close on overlay click (but not video click)
|
||||
overlay.onclick = (e) => {
|
||||
if (e.target === overlay) {
|
||||
overlay.remove();
|
||||
}
|
||||
};
|
||||
|
||||
// Close on ESC key
|
||||
const handleKeydown = (e) => {
|
||||
if (e.key === 'Escape') {
|
||||
overlay.remove();
|
||||
document.removeEventListener('keydown', handleKeydown);
|
||||
}
|
||||
};
|
||||
document.addEventListener('keydown', handleKeydown);
|
||||
|
||||
// Add to document
|
||||
document.body.appendChild(overlay);
|
||||
|
||||
// Focus video for keyboard controls
|
||||
video.focus();
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if filename is a video file
|
||||
*/
|
||||
function isVideoFile(filename) {
|
||||
if (!filename) return false;
|
||||
const ext = filename.split('.').pop().toLowerCase();
|
||||
return ['mp4', 'webm', 'mov', 'avi', 'mkv', 'm4v', 'wmv'].includes(ext);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if filename is a previewable file (image or video)
|
||||
*/
|
||||
function isPreviewableFile(filename) {
|
||||
if (!filename || filename === '(none)') return false;
|
||||
const ext = filename.split('.').pop().toLowerCase();
|
||||
const imageExtensions = ['png', 'jpg', 'jpeg', 'webp', 'gif', 'bmp'];
|
||||
const videoExtensions = ['mp4', 'webm', 'mov', 'avi', 'mkv', 'm4v', 'wmv'];
|
||||
return imageExtensions.includes(ext) || videoExtensions.includes(ext);
|
||||
}
|
||||
|
||||
app.registerExtension({
|
||||
name: "PromptExtractor",
|
||||
|
||||
@@ -479,6 +809,12 @@ app.registerExtension({
|
||||
|
||||
// Track workflow metadata status for indicator
|
||||
node.hasWorkflow = false;
|
||||
// Track the currently loaded image filename and frame position to prevent unnecessary reloads
|
||||
node._loadedImageFilename = null;
|
||||
node._loadedFramePosition = null;
|
||||
|
||||
// Find the frame_position widget (slider) early so we can reference it
|
||||
const framePositionWidget = this.widgets?.find(w => w.name === "frame_position");
|
||||
|
||||
// Find the image widget (combo dropdown)
|
||||
const imageWidget = this.widgets?.find(w => w.name === "image");
|
||||
@@ -546,14 +882,44 @@ app.registerExtension({
|
||||
// Insert button right after the image widget
|
||||
this.widgets.splice(imageWidgetIndex + 1, 0, browseButton);
|
||||
Object.defineProperty(browseButton, "node", { value: node });
|
||||
|
||||
// Track if current file is a video for UI behavior
|
||||
node._isVideoFile = false;
|
||||
|
||||
// Function to update video-specific UI visibility
|
||||
const updateVideoUIVisibility = () => {
|
||||
const isVideo = isVideoFile(imageWidget.value);
|
||||
node._isVideoFile = isVideo;
|
||||
|
||||
// Show/hide frame_position widget based on file type
|
||||
if (framePositionWidget) {
|
||||
framePositionWidget.hidden = !isVideo;
|
||||
}
|
||||
|
||||
node.setDirtyCanvas(true);
|
||||
};
|
||||
|
||||
// Wrap the image widget callback to also update visibility
|
||||
const wrappedCallback = imageWidget.callback;
|
||||
imageWidget.callback = function(value) {
|
||||
if (wrappedCallback) {
|
||||
wrappedCallback.apply(this, arguments);
|
||||
}
|
||||
updateVideoUIVisibility();
|
||||
};
|
||||
|
||||
// Initial visibility check
|
||||
setTimeout(updateVideoUIVisibility, 100);
|
||||
}
|
||||
|
||||
// Find the frame_position widget (slider)
|
||||
const framePositionWidget = this.widgets?.find(w => w.name === "frame_position");
|
||||
// Configure frame_position widget behavior
|
||||
if (framePositionWidget) {
|
||||
// Ensure the widget is serialized (saved in workflows)
|
||||
framePositionWidget.serialize = true;
|
||||
|
||||
// Initially hide frame_position (will be shown if video is loaded)
|
||||
framePositionWidget.hidden = true;
|
||||
|
||||
// Store original callback
|
||||
const originalFrameCallback = framePositionWidget.callback;
|
||||
|
||||
@@ -602,11 +968,22 @@ app.registerExtension({
|
||||
}
|
||||
|
||||
// After workflow is configured, load the preview if a file is selected
|
||||
// Only reload if we don't already have a preview image displayed
|
||||
if (imageWidget && imageWidget.value) {
|
||||
const previewWidget = this.widgets?.find(w => w.name === "preview" && w.type === "image");
|
||||
// Only load if preview is not already showing this image
|
||||
if (!previewWidget || !previewWidget.value) {
|
||||
// Only reload if we're not already displaying this exact image/video frame (prevents refresh on queue)
|
||||
if (imageWidget && imageWidget.value && imageWidget.value !== "(none)") {
|
||||
const isVideo = isVideoFile(imageWidget.value);
|
||||
const currentFramePos = framePositionWidget ? framePositionWidget.value : 0.0;
|
||||
|
||||
// Check if we already have this exact image/frame loaded
|
||||
// Also verify the actual image src matches (prevents stale images when switching tabs)
|
||||
const expectedFilename = encodeURIComponent(imageWidget.value);
|
||||
const hasCorrectImage = node.imgs && node.imgs[0] &&
|
||||
node.imgs[0].src && node.imgs[0].src.includes(expectedFilename);
|
||||
|
||||
const alreadyLoaded = node._loadedImageFilename === imageWidget.value &&
|
||||
(!isVideo || node._loadedFramePosition === currentFramePos) &&
|
||||
hasCorrectImage;
|
||||
|
||||
if (!alreadyLoaded) {
|
||||
loadAndDisplayImage(node, imageWidget.value);
|
||||
}
|
||||
}
|
||||
@@ -619,7 +996,10 @@ app.registerExtension({
|
||||
// Use setTimeout to ensure node is fully initialized
|
||||
setTimeout(() => {
|
||||
if (imageWidget.value && imageWidget.value !== "(none)") {
|
||||
loadAndDisplayImage(node, imageWidget.value);
|
||||
// Only load if not already loaded
|
||||
if (node._loadedImageFilename !== imageWidget.value) {
|
||||
loadAndDisplayImage(node, imageWidget.value);
|
||||
}
|
||||
} else {
|
||||
// Show placeholder for (none) or empty
|
||||
showPlaceholder(node);
|
||||
@@ -707,7 +1087,7 @@ app.registerExtension({
|
||||
return true;
|
||||
};
|
||||
|
||||
// Add workflow status indicator light
|
||||
// Add workflow status indicator light and preview button
|
||||
const onDrawForeground = node.onDrawForeground;
|
||||
node.onDrawForeground = function(ctx) {
|
||||
const result = onDrawForeground ? onDrawForeground.apply(this, arguments) : undefined;
|
||||
@@ -728,6 +1108,36 @@ app.registerExtension({
|
||||
ctx.strokeStyle = node.hasWorkflow ? '#054405' : '#550505';
|
||||
ctx.lineWidth = 1;
|
||||
ctx.stroke();
|
||||
|
||||
// Draw preview play icon (simple triangle) left of workflow indicator - only for images/videos
|
||||
const imageWidget = node.widgets?.find(w => w.name === "image");
|
||||
const currentFile = imageWidget?.value;
|
||||
|
||||
if (isPreviewableFile(currentFile)) {
|
||||
const playX = node.size[0] - radius - 8 - 34;
|
||||
const playY = (titleHeight / 2) - 30;
|
||||
const triSize = 8;
|
||||
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(playX - triSize, playY - triSize);
|
||||
ctx.lineTo(playX - triSize, playY + triSize);
|
||||
ctx.lineTo(playX + triSize, playY);
|
||||
ctx.closePath();
|
||||
ctx.fillStyle = node._hoverPreviewIcon ? '#ffffff' : 'rgba(255, 255, 255, 0.7)';
|
||||
ctx.fill();
|
||||
|
||||
// Store play icon bounds for click detection
|
||||
node._previewIconBounds = {
|
||||
x: playX - triSize - 3,
|
||||
y: playY - triSize - 3,
|
||||
width: triSize * 2 + 6,
|
||||
height: triSize * 2 + 6
|
||||
};
|
||||
} else {
|
||||
node._previewIconBounds = null;
|
||||
}
|
||||
} else {
|
||||
node._previewIconBounds = null;
|
||||
}
|
||||
|
||||
return result;
|
||||
@@ -754,10 +1164,51 @@ app.registerExtension({
|
||||
canvas.canvas.title = node.hasWorkflow ?
|
||||
'Workflow metadata found' :
|
||||
'No workflow metadata';
|
||||
node._hoverPreviewIcon = false;
|
||||
} else if (node._previewIconBounds) {
|
||||
// Check if hovering over preview icon
|
||||
const bounds = node._previewIconBounds;
|
||||
if (localPos[0] >= bounds.x && localPos[0] <= bounds.x + bounds.width &&
|
||||
localPos[1] >= bounds.y && localPos[1] <= bounds.y + bounds.height) {
|
||||
canvas.canvas.style.cursor = 'pointer';
|
||||
canvas.canvas.title = 'Click to preview';
|
||||
node._hoverPreviewIcon = true;
|
||||
node.setDirtyCanvas(true);
|
||||
} else {
|
||||
if (node._hoverPreviewIcon) {
|
||||
node._hoverPreviewIcon = false;
|
||||
node.setDirtyCanvas(true);
|
||||
}
|
||||
canvas.canvas.style.cursor = '';
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
// Handle click on preview icon
|
||||
const onMouseDown = node.onMouseDown;
|
||||
node.onMouseDown = function(e, localPos, canvas) {
|
||||
// Check if clicking on preview icon
|
||||
if (node._previewIconBounds && node.imgs && node.imgs.length > 0) {
|
||||
const bounds = node._previewIconBounds;
|
||||
if (localPos[0] >= bounds.x && localPos[0] <= bounds.x + bounds.width &&
|
||||
localPos[1] >= bounds.y && localPos[1] <= bounds.y + bounds.height) {
|
||||
// Open preview modal
|
||||
const imageWidget = node.widgets?.find(w => w.name === "image");
|
||||
if (imageWidget && imageWidget.value) {
|
||||
if (node._isVideoFile) {
|
||||
showVideoPreviewModal(imageWidget.value);
|
||||
} else {
|
||||
showImagePreviewModal(imageWidget.value);
|
||||
}
|
||||
}
|
||||
return true; // Consume the event
|
||||
}
|
||||
}
|
||||
|
||||
return onMouseDown ? onMouseDown.apply(this, arguments) : undefined;
|
||||
};
|
||||
|
||||
return result;
|
||||
};
|
||||
@@ -925,6 +1376,8 @@ async function loadImageFile(node, filename) {
|
||||
img.onload = () => {
|
||||
node.imgs = [img];
|
||||
node.imageIndex = 0;
|
||||
// Track that this image is now loaded
|
||||
node._loadedImageFilename = filename;
|
||||
|
||||
// Resize node to fit image (like Load Image does)
|
||||
const targetWidth = Math.max(node.size[0], 256);
|
||||
@@ -965,6 +1418,8 @@ async function loadJSONFile(node, filename) {
|
||||
// Update workflow status flag
|
||||
// Check if metadata has workflow property OR if metadata itself is a workflow (has nodes/links)
|
||||
node.hasWorkflow = !!(metadata && (metadata.workflow || (metadata.nodes && metadata.links)));
|
||||
// Track that this JSON is now loaded
|
||||
node._loadedImageFilename = filename;
|
||||
|
||||
// Force canvas redraw to update indicator immediately
|
||||
node.setDirtyCanvas(true, true);
|
||||
@@ -1046,6 +1501,9 @@ async function loadVideoFrame(node, filename) {
|
||||
// Display the frame
|
||||
node.imgs = [img];
|
||||
node.imageIndex = 0;
|
||||
// Track that this video frame is now loaded at this specific position
|
||||
node._loadedImageFilename = filename;
|
||||
node._loadedFramePosition = framePosition;
|
||||
|
||||
// Cache frame as base64 for Python backend
|
||||
const frameData = canvas.toDataURL('image/png');
|
||||
@@ -1085,6 +1543,10 @@ async function loadVideoFrame(node, filename) {
|
||||
* Show placeholder image for non-image files
|
||||
*/
|
||||
function showPlaceholder(node) {
|
||||
// Clear the loaded filename and frame position since we're showing a placeholder
|
||||
node._loadedImageFilename = null;
|
||||
node._loadedFramePosition = null;
|
||||
|
||||
const placeholderImg = new Image();
|
||||
placeholderImg.src = PLACEHOLDER_IMAGE_PATH;
|
||||
placeholderImg.onload = () => {
|
||||
|
||||
+207
-68
@@ -114,20 +114,92 @@ app.registerExtension({
|
||||
tooltip: "Show a warning when switching prompts if there are unsaved changes to the current prompt text, LoRAs, or trigger words.",
|
||||
type: "boolean",
|
||||
defaultValue: true
|
||||
},
|
||||
{
|
||||
id: "PromptManager.DefaultHideNSFW",
|
||||
category: ["Prompt Manager", "4. Advanced Preferences", "Hide NSFW by Default"],
|
||||
name: "Hide NSFW prompts by default",
|
||||
tooltip: "When enabled, NSFW categories and prompts are hidden in the prompt browser on startup. Can be toggled per session.",
|
||||
type: "boolean",
|
||||
defaultValue: true
|
||||
},
|
||||
{
|
||||
id: "PromptManager.DefaultViewMode",
|
||||
category: ["Prompt Manager", "4. Advanced Preferences", "Prompt Browser View Mode"],
|
||||
name: "Default prompt browser view mode",
|
||||
tooltip: "Choose the default display mode for the prompt browser: thumbnails grid or compact list view.",
|
||||
type: "combo",
|
||||
options: ["thumbnails", "list"],
|
||||
defaultValue: "thumbnails"
|
||||
},
|
||||
{
|
||||
id: "PromptManager.LLMBackend",
|
||||
category: ["Prompt Manager", "5. Ollama Settings", "LLM Backend"],
|
||||
name: "LLM Backend",
|
||||
tooltip: "Choose the LLM backend: llama.cpp (local server, default) or Ollama",
|
||||
type: "combo",
|
||||
options: ["llama.cpp", "ollama"],
|
||||
defaultValue: "llama.cpp",
|
||||
onChange(value) {
|
||||
fetch("/prompt-manager/save-preference", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ key: "llm_backend", value: value })
|
||||
}).catch(error => {
|
||||
console.error("[PromptManager] Error saving LLM backend preference:", error);
|
||||
});
|
||||
}
|
||||
},
|
||||
{
|
||||
id: "PromptManager.OllamaUrl",
|
||||
category: ["Prompt Manager", "5. Ollama Settings", "Ollama URL"],
|
||||
name: "Ollama URL",
|
||||
tooltip: "URL of the Ollama server (default: http://127.0.0.1:11434)",
|
||||
type: "text",
|
||||
defaultValue: "http://127.0.0.1:11434",
|
||||
onChange(value) {
|
||||
fetch("/prompt-manager/save-preference", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ key: "ollama_url", value: value })
|
||||
}).catch(error => {
|
||||
console.error("[PromptManager] Error saving Ollama URL preference:", error);
|
||||
});
|
||||
}
|
||||
},
|
||||
{
|
||||
id: "PromptManager.OllamaKeepAlive",
|
||||
category: ["Prompt Manager", "5. Ollama Settings", "Keep Alive Duration"],
|
||||
name: "Keep Alive Duration",
|
||||
tooltip: "How long Ollama keeps the model loaded in memory after a request. Examples: '5m' (5 minutes), '30m', '1h', '0' (unload immediately), '-1' (keep forever). Default: 5m",
|
||||
type: "text",
|
||||
defaultValue: "5m",
|
||||
onChange(value) {
|
||||
fetch("/prompt-manager/save-preference", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ key: "ollama_keep_alive", value: value })
|
||||
}).catch(error => {
|
||||
console.error("[PromptManager] Error saving Ollama keep alive preference:", error);
|
||||
});
|
||||
}
|
||||
}
|
||||
],
|
||||
async setup() {
|
||||
// Load settings from ComfyUI and sync to Python cache
|
||||
try {
|
||||
// Sync current values to Python cache first
|
||||
const baseModel = app.ui.settings.getSettingValue("PromptManager.PreferredBaseModel", "");
|
||||
const visionModel = app.ui.settings.getSettingValue("PromptManager.PreferredVisionModel", "");
|
||||
const llamaPath = app.ui.settings.getSettingValue("PromptManager.LlamaPath", "");
|
||||
const modelPath = app.ui.settings.getSettingValue("PromptManager.ModelPath", "");
|
||||
const port = app.ui.settings.getSettingValue("PromptManager.Port", "8080");
|
||||
const CloseLlama = app.ui.settings.getSettingValue("PromptManager.CloseLlama", true);
|
||||
const baseModel = app.ui.settings.getSettingValue("PromptManager.PreferredBaseModel");
|
||||
const visionModel = app.ui.settings.getSettingValue("PromptManager.PreferredVisionModel");
|
||||
const llamaPath = app.ui.settings.getSettingValue("PromptManager.LlamaPath");
|
||||
const modelPath = app.ui.settings.getSettingValue("PromptManager.ModelPath");
|
||||
const port = app.ui.settings.getSettingValue("PromptManager.Port");
|
||||
const CloseLlama = app.ui.settings.getSettingValue("PromptManager.CloseLlama");
|
||||
const llmBackend = app.ui.settings.getSettingValue("PromptManager.LLMBackend");
|
||||
const ollamaUrl = app.ui.settings.getSettingValue("PromptManager.OllamaUrl");
|
||||
const ollamaKeepAlive = app.ui.settings.getSettingValue("PromptManager.OllamaKeepAlive");
|
||||
|
||||
console.log("[PromptManager] Syncing preferences:", { baseModel, visionModel, llamaPath, modelPath, port, CloseLlama });
|
||||
console.log("[PromptManager] Syncing preferences:", { baseModel, visionModel, llamaPath, modelPath, port, CloseLlama, llmBackend, ollamaUrl, ollamaKeepAlive });
|
||||
await fetch("/prompt-manager/save-preference", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
@@ -158,6 +230,21 @@ app.registerExtension({
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ key: "close_llama_on_exit", value: CloseLlama })
|
||||
});
|
||||
await fetch("/prompt-manager/save-preference", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ key: "llm_backend", value: llmBackend })
|
||||
});
|
||||
await fetch("/prompt-manager/save-preference", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ key: "ollama_url", value: ollamaUrl })
|
||||
});
|
||||
await fetch("/prompt-manager/save-preference", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ key: "ollama_keep_alive", value: ollamaKeepAlive })
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("[PromptManager] Error syncing preferences:", error);
|
||||
}
|
||||
@@ -277,6 +364,53 @@ app.registerExtension({
|
||||
return result;
|
||||
};
|
||||
|
||||
// Draw red NSFW badge at the top of the node when NSFW content is selected
|
||||
const onDrawForeground = nodeType.prototype.onDrawForeground;
|
||||
nodeType.prototype.onDrawForeground = function(ctx) {
|
||||
if (onDrawForeground) onDrawForeground.apply(this, arguments);
|
||||
|
||||
const hideNSFW = app.ui.settings.getSettingValue("PromptManager.DefaultHideNSFW");
|
||||
if (hideNSFW || !this.prompts) return;
|
||||
|
||||
const categoryWidget = this.widgets?.find(w => w.name === "category");
|
||||
const promptWidget = this.widgets?.find(w => w.name === "name");
|
||||
if (!categoryWidget || !promptWidget) return;
|
||||
|
||||
const category = categoryWidget.value;
|
||||
const promptName = promptWidget.value;
|
||||
const catIsNSFW = this.prompts[category]?.["__meta__"]?.nsfw === true;
|
||||
const promptIsNSFW = this.prompts[category]?.[promptName]?.nsfw === true;
|
||||
|
||||
if (catIsNSFW || promptIsNSFW) {
|
||||
ctx.save();
|
||||
// Draw red "NSFW" badge at top-right of node
|
||||
const text = "NSFW";
|
||||
ctx.font = "bold 8px sans-serif";
|
||||
const textWidth = ctx.measureText(text).width;
|
||||
const badgeW = textWidth + 8;
|
||||
const badgeH = 12;
|
||||
const badgeX = this.size[0] - badgeW - 4;
|
||||
const badgeY = -LiteGraph.NODE_TITLE_HEIGHT + (LiteGraph.NODE_TITLE_HEIGHT - badgeH) / 2;
|
||||
|
||||
// Badge background
|
||||
ctx.fillStyle = "rgba(204, 50, 50, 0.85)";
|
||||
ctx.beginPath();
|
||||
if (ctx.roundRect) {
|
||||
ctx.roundRect(badgeX, badgeY, badgeW, badgeH, 2);
|
||||
} else {
|
||||
ctx.rect(badgeX, badgeY, badgeW, badgeH);
|
||||
}
|
||||
ctx.fill();
|
||||
|
||||
// Badge text
|
||||
ctx.fillStyle = "#fff";
|
||||
ctx.textAlign = "center";
|
||||
ctx.textBaseline = "middle";
|
||||
ctx.fillText(text, badgeX + badgeW / 2, badgeY + badgeH / 2);
|
||||
ctx.restore();
|
||||
}
|
||||
};
|
||||
|
||||
// Enforce minimum node width
|
||||
const onResize = nodeType.prototype.onResize;
|
||||
nodeType.prototype.onResize = function(size) {
|
||||
@@ -379,9 +513,31 @@ function filterPromptDropdown(node) {
|
||||
const promptWidget = node.widgets.find(w => w.name === "name");
|
||||
|
||||
if (categoryWidget && promptWidget) {
|
||||
const hideNSFW = app.ui.settings.getSettingValue("PromptManager.DefaultHideNSFW");
|
||||
|
||||
// Filter NSFW categories from the category dropdown
|
||||
if (hideNSFW && node.prompts) {
|
||||
let categories = Object.keys(node.prompts).sort((a, b) => a.localeCompare(b));
|
||||
categories = categories.filter(cat => node.prompts[cat]?.["__meta__"]?.nsfw !== true);
|
||||
categoryWidget.options.values = categories.length > 0 ? categories : ["Default"];
|
||||
|
||||
// If current category is now hidden, switch to first visible
|
||||
if (!categories.includes(categoryWidget.value) && categories.length > 0) {
|
||||
categoryWidget.value = categories[0];
|
||||
}
|
||||
}
|
||||
|
||||
const currentCategory = categoryWidget.value;
|
||||
if (node.prompts[currentCategory]) {
|
||||
const promptNames = Object.keys(node.prompts[currentCategory]).sort((a, b) => a.localeCompare(b));
|
||||
let promptNames = Object.keys(node.prompts[currentCategory]).filter(k => k !== '__meta__').sort((a, b) => a.localeCompare(b));
|
||||
if (hideNSFW) {
|
||||
const catIsNSFW = node.prompts[currentCategory]?.["__meta__"]?.nsfw === true;
|
||||
if (catIsNSFW) {
|
||||
promptNames = [];
|
||||
} else {
|
||||
promptNames = promptNames.filter(name => !node.prompts[currentCategory][name]?.nsfw);
|
||||
}
|
||||
}
|
||||
if (promptNames.length === 0) {
|
||||
promptNames.push("");
|
||||
}
|
||||
@@ -436,7 +592,7 @@ function addButtonBar(node) {
|
||||
// Case-insensitive check for existing prompt
|
||||
let existingPromptName = null;
|
||||
if (node.prompts[targetCategory]) {
|
||||
const existingNames = Object.keys(node.prompts[targetCategory]);
|
||||
const existingNames = Object.keys(node.prompts[targetCategory]).filter(k => k !== '__meta__');
|
||||
existingPromptName = existingNames.find(name => name.toLowerCase() === promptName.toLowerCase());
|
||||
}
|
||||
|
||||
@@ -468,16 +624,16 @@ function addButtonBar(node) {
|
||||
}
|
||||
});
|
||||
|
||||
// New Prompt button with category selection
|
||||
// New Prompt button - simply clears fields for a fresh start
|
||||
const newPromptBtn = createButton("New Prompt", async () => {
|
||||
// Check for unsaved changes before creating new prompt
|
||||
const hasUnsaved = hasUnsavedChanges(node);
|
||||
const warnEnabled = app.ui.settings.getSettingValue("PromptManager.warnUnsavedChanges", true);
|
||||
const warnEnabled = app.ui.settings.getSettingValue("PromptManager.warnUnsavedChanges");
|
||||
|
||||
if (hasUnsaved && warnEnabled) {
|
||||
const confirmed = await showConfirm(
|
||||
"Unsaved Changes",
|
||||
"You have unsaved changes to the current prompt. Do you want to discard them and create a new prompt?",
|
||||
"You have unsaved changes to the current prompt. Do you want to discard them and start fresh?",
|
||||
"Discard & Continue",
|
||||
"#f80"
|
||||
);
|
||||
@@ -486,59 +642,27 @@ function addButtonBar(node) {
|
||||
}
|
||||
}
|
||||
|
||||
const categories = Object.keys(node.prompts || {}).sort((a, b) => a.localeCompare(b));
|
||||
// Keep the current category, just clear the prompt selection and content
|
||||
const currentCategory = categoryWidget.value;
|
||||
|
||||
const result = await showPromptWithCategory(
|
||||
"New Prompt",
|
||||
"Enter new prompt name:",
|
||||
"",
|
||||
categories,
|
||||
currentCategory
|
||||
);
|
||||
// Clear prompt selection (set to empty/placeholder)
|
||||
promptWidget.value = "";
|
||||
textWidget.value = "";
|
||||
|
||||
if (result && result.name && result.name.trim()) {
|
||||
const promptName = result.name.trim();
|
||||
const targetCategory = result.category;
|
||||
|
||||
// Check for existing prompt
|
||||
let existingPromptName = null;
|
||||
if (node.prompts[targetCategory]) {
|
||||
const existingNames = Object.keys(node.prompts[targetCategory]);
|
||||
existingPromptName = existingNames.find(name => name.toLowerCase() === promptName.toLowerCase());
|
||||
}
|
||||
|
||||
if (existingPromptName) {
|
||||
await showInfo(
|
||||
"Prompt Exists",
|
||||
`Prompt "${existingPromptName}" already exists in category "${targetCategory}".`
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// Set up UI for new prompt (temporary, not saved yet)
|
||||
// User must click "Save Prompt" to persist it
|
||||
categoryWidget.value = targetCategory;
|
||||
|
||||
// Add prompt name to dropdown temporarily so it can be selected
|
||||
if (!promptWidget.options.values.includes(promptName)) {
|
||||
promptWidget.options.values = [...promptWidget.options.values, promptName].sort((a, b) => a.localeCompare(b));
|
||||
}
|
||||
promptWidget.value = promptName;
|
||||
textWidget.value = "";
|
||||
|
||||
// Mark as unsaved/new prompt
|
||||
node.isNewUnsavedPrompt = true;
|
||||
node.newPromptCategory = targetCategory;
|
||||
node.newPromptName = promptName;
|
||||
|
||||
// Update previous values so cancel/revert works correctly
|
||||
node._previousCategory = targetCategory;
|
||||
node._previousPrompt = promptName;
|
||||
|
||||
node.serialize_widgets = true;
|
||||
app.graph.setDirtyCanvas(true, true);
|
||||
}
|
||||
// Update previous values for cancel/revert
|
||||
node._previousCategory = currentCategory;
|
||||
node._previousPrompt = "";
|
||||
|
||||
// Mark as new unsaved prompt state
|
||||
node.isNewUnsavedPrompt = true;
|
||||
node.newPromptCategory = currentCategory;
|
||||
node.newPromptName = null;
|
||||
|
||||
// Clear the last saved state since this is a brand new prompt
|
||||
node.lastSavedState = null;
|
||||
|
||||
node.serialize_widgets = true;
|
||||
app.graph.setDirtyCanvas(true, true);
|
||||
});
|
||||
|
||||
// More dropdown button
|
||||
@@ -635,7 +759,11 @@ function setupCategoryChangeHandler(node) {
|
||||
|
||||
const category = value;
|
||||
if (node.prompts && node.prompts[category]) {
|
||||
const promptNames = Object.keys(node.prompts[category]).sort((a, b) => a.localeCompare(b));
|
||||
const hideNSFW = app.ui.settings.getSettingValue("PromptManager.DefaultHideNSFW");
|
||||
let promptNames = Object.keys(node.prompts[category]).filter(k => k !== '__meta__').sort((a, b) => a.localeCompare(b));
|
||||
if (hideNSFW) {
|
||||
promptNames = promptNames.filter(name => !node.prompts[category][name]?.nsfw);
|
||||
}
|
||||
promptWidget.options.values = promptNames;
|
||||
|
||||
if (promptNames.length > 0) {
|
||||
@@ -673,7 +801,11 @@ function setupCategoryChangeHandler(node) {
|
||||
|
||||
// Update prompt dropdown options in case prompts were deleted/added in another tab
|
||||
if (node.prompts && node.prompts[category]) {
|
||||
const promptNames = Object.keys(node.prompts[category]).sort((a, b) => a.localeCompare(b));
|
||||
const hideNSFW = app.ui.settings.getSettingValue("PromptManager.DefaultHideNSFW");
|
||||
let promptNames = Object.keys(node.prompts[category]).filter(k => k !== '__meta__').sort((a, b) => a.localeCompare(b));
|
||||
if (hideNSFW) {
|
||||
promptNames = promptNames.filter(name => !node.prompts[category][name]?.nsfw);
|
||||
}
|
||||
promptWidget.options.values = promptNames.length > 0 ? promptNames : [""];
|
||||
|
||||
// Check if selected prompt still exists after reload
|
||||
@@ -709,7 +841,7 @@ function setupCategoryChangeHandler(node) {
|
||||
if (node.prompts && categoryWidget && newValues && newValues.length > 0) {
|
||||
const currentCategory = categoryWidget.value;
|
||||
if (node.prompts[currentCategory]) {
|
||||
const categoryPrompts = Object.keys(node.prompts[currentCategory]);
|
||||
const categoryPrompts = Object.keys(node.prompts[currentCategory]).filter(k => k !== '__meta__');
|
||||
const hasOtherCategoryPrompts = newValues.some(val =>
|
||||
val !== "" && !categoryPrompts.includes(val)
|
||||
);
|
||||
@@ -1451,8 +1583,12 @@ function updateDropdowns(node) {
|
||||
if (!categoryWidget || !promptWidget || !textWidget) return;
|
||||
|
||||
// Update category dropdown (sorted alphabetically)
|
||||
const categories = Object.keys(node.prompts).sort((a, b) => a.localeCompare(b));
|
||||
categoryWidget.options.values = categories;
|
||||
const hideNSFW = app.ui.settings.getSettingValue("PromptManager.DefaultHideNSFW");
|
||||
let categories = Object.keys(node.prompts).sort((a, b) => a.localeCompare(b));
|
||||
if (hideNSFW) {
|
||||
categories = categories.filter(cat => node.prompts[cat]?.["__meta__"]?.nsfw !== true);
|
||||
}
|
||||
categoryWidget.options.values = categories.length > 0 ? categories : ["Default"];
|
||||
|
||||
if (!node.prompts[categoryWidget.value] && categories.length > 0) {
|
||||
categoryWidget.value = categories[0];
|
||||
@@ -1461,7 +1597,10 @@ function updateDropdowns(node) {
|
||||
// Update prompt dropdown for current category (sorted alphabetically)
|
||||
const currentCategory = categoryWidget.value;
|
||||
if (node.prompts[currentCategory]) {
|
||||
const promptNames = Object.keys(node.prompts[currentCategory]).sort((a, b) => a.localeCompare(b));
|
||||
let promptNames = Object.keys(node.prompts[currentCategory]).filter(k => k !== '__meta__').sort((a, b) => a.localeCompare(b));
|
||||
if (hideNSFW) {
|
||||
promptNames = promptNames.filter(name => !node.prompts[currentCategory][name]?.nsfw);
|
||||
}
|
||||
|
||||
if (promptNames.length === 0) {
|
||||
promptNames.push("");
|
||||
|
||||
+1125
-168
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,197 @@
|
||||
/**
|
||||
* Video Metadata Reader - VHS Compatible
|
||||
* Enables drag-and-drop workflow loading from videos saved by VideoHelperSuite
|
||||
* without needing VHS installed.
|
||||
*
|
||||
* Based on VideoHelperSuite's videoinfo.js implementation.
|
||||
*/
|
||||
|
||||
import { app } from '../../../scripts/app.js'
|
||||
|
||||
/**
|
||||
* Parse video file bytes to extract embedded workflow/prompt metadata.
|
||||
* Supports webm/mkv (EBML/Matroska) and mp4 (QuickTime) formats.
|
||||
*/
|
||||
function getVideoMetadata(file) {
|
||||
return new Promise((resolve) => {
|
||||
const reader = new FileReader();
|
||||
reader.onload = (event) => {
|
||||
const videoData = new Uint8Array(event.target.result);
|
||||
const dataView = new DataView(videoData.buffer);
|
||||
const decoder = new TextDecoder();
|
||||
|
||||
// Check for known valid magic bytes
|
||||
if (dataView.getUint32(0) === 0x1A45DFA3) {
|
||||
// webm/mkv - EBML/Matroska format
|
||||
// Metadata stored in COMMENT tags
|
||||
// See: http://wiki.webmproject.org/webm-metadata/global-metadata
|
||||
// See: https://www.matroska.org/technical/elements.html
|
||||
let offset = 4 + 8; // Skip header, COMMENT is 7 chars + 1 to realign
|
||||
|
||||
while (offset < videoData.length - 16) {
|
||||
// Check for text tags (0x4487 = TagString element)
|
||||
if (dataView.getUint16(offset) === 0x4487) {
|
||||
// Check that name of tag is COMMENT
|
||||
const name = String.fromCharCode(...videoData.slice(offset - 7, offset));
|
||||
if (name === "COMMENT") {
|
||||
// Parse EBML variable-length integer
|
||||
// See: https://github.com/ietf-wg-cellar/ebml-specification/blob/master/specification.markdown
|
||||
let vint = dataView.getUint32(offset + 2);
|
||||
let n_octets = Math.clz32(vint) + 1;
|
||||
if (n_octets < 4) { // 250MB sanity cutoff
|
||||
let length = (vint >> (8 * (4 - n_octets))) & ~(1 << (7 * n_octets));
|
||||
const content = decoder.decode(videoData.slice(offset + 2 + n_octets, offset + 2 + n_octets + length));
|
||||
try {
|
||||
const json = JSON.parse(content);
|
||||
resolve(json);
|
||||
return;
|
||||
} catch (e) {
|
||||
console.warn("[VideoMetadata] Failed to parse COMMENT JSON:", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
offset += 1;
|
||||
}
|
||||
} else if (dataView.getUint32(4) === 0x66747970) {
|
||||
// mp4 - QuickTime/ISO format
|
||||
// See: https://developer.apple.com/documentation/quicktime-file-format
|
||||
// Metadata can be in various locations, search from end
|
||||
|
||||
// First try: Look for ©cmt (comment) atom - VHS style
|
||||
let offset = videoData.length - 4;
|
||||
while (offset > 16) {
|
||||
if (dataView.getUint32(offset) === 0x64617461) { // 'data' tag
|
||||
if (dataView.getUint32(offset - 8) === 0xa9636d74) { // '©cmt' (comment) tag
|
||||
let size = dataView.getUint32(offset - 4) - 4 * 4;
|
||||
const content = decoder.decode(videoData.slice(offset + 12, offset + 12 + size));
|
||||
try {
|
||||
const json = JSON.parse(content);
|
||||
resolve(json);
|
||||
return;
|
||||
} catch (e) {
|
||||
console.warn("[VideoMetadata] Failed to parse ©cmt JSON:", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
offset -= 1;
|
||||
}
|
||||
|
||||
// Second try: Look for 'prompt' or 'workflow' tags in metadata
|
||||
// These are stored by our SaveVideoH26x node using movflags=use_metadata_tags
|
||||
offset = 0;
|
||||
while (offset < videoData.length - 100) {
|
||||
// Look for 'prompt' or 'workflow' strings followed by JSON
|
||||
const slice = decoder.decode(videoData.slice(offset, offset + 20));
|
||||
if (slice.includes('prompt') || slice.includes('workflow')) {
|
||||
// Try to find JSON starting after the key
|
||||
for (let i = 0; i < 50 && offset + i < videoData.length - 1; i++) {
|
||||
if (videoData[offset + i] === 0x7B) { // '{'
|
||||
// Found potential JSON start, try to parse
|
||||
let jsonEnd = offset + i;
|
||||
let braceCount = 0;
|
||||
for (let j = jsonEnd; j < Math.min(jsonEnd + 1000000, videoData.length); j++) {
|
||||
if (videoData[j] === 0x7B) braceCount++;
|
||||
if (videoData[j] === 0x7D) braceCount--;
|
||||
if (braceCount === 0) {
|
||||
jsonEnd = j + 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
const jsonStr = decoder.decode(videoData.slice(offset + i, jsonEnd));
|
||||
try {
|
||||
const json = JSON.parse(jsonStr);
|
||||
if (json.workflow || json.prompt || json.nodes) {
|
||||
resolve(json.workflow ? json : { workflow: json });
|
||||
return;
|
||||
}
|
||||
} catch (e) {
|
||||
// Not valid JSON, continue searching
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
offset += 100; // Skip ahead in larger chunks
|
||||
}
|
||||
}
|
||||
|
||||
// No metadata found
|
||||
resolve(undefined);
|
||||
};
|
||||
|
||||
reader.onerror = () => {
|
||||
console.error("[VideoMetadata] Failed to read file");
|
||||
resolve(undefined);
|
||||
};
|
||||
|
||||
reader.readAsArrayBuffer(file);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if file is a video by extension
|
||||
*/
|
||||
function isVideoFile(file) {
|
||||
const videoExtensions = ['.webm', '.mp4', '.mkv', '.mov', '.avi'];
|
||||
const name = file?.name?.toLowerCase() || '';
|
||||
return videoExtensions.some(ext => name.endsWith(ext));
|
||||
}
|
||||
|
||||
// Store original handler
|
||||
let originalHandleFile = null;
|
||||
|
||||
/**
|
||||
* Custom file handler that intercepts video files to extract workflow metadata
|
||||
*/
|
||||
async function handleFile(file) {
|
||||
// Check if this is a video file
|
||||
if (file?.type?.startsWith("video/") || isVideoFile(file)) {
|
||||
console.log("[VideoMetadata] Processing video file:", file.name);
|
||||
|
||||
try {
|
||||
const videoInfo = await getVideoMetadata(file);
|
||||
|
||||
if (videoInfo?.workflow) {
|
||||
console.log("[VideoMetadata] Found workflow in video, loading...");
|
||||
await app.loadGraphData(videoInfo.workflow);
|
||||
return;
|
||||
} else {
|
||||
console.log("[VideoMetadata] No workflow metadata found in video");
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("[VideoMetadata] Error extracting metadata:", e);
|
||||
}
|
||||
}
|
||||
|
||||
// Fall through to original handler
|
||||
if (originalHandleFile) {
|
||||
return await originalHandleFile.apply(this, arguments);
|
||||
}
|
||||
}
|
||||
|
||||
// Register extension
|
||||
app.registerExtension({
|
||||
name: "PromptManager.VideoMetadata",
|
||||
|
||||
async setup() {
|
||||
// Only hijack if not already done by VHS
|
||||
if (!window._vhsVideoMetadataRegistered) {
|
||||
// Store and replace the file handler
|
||||
originalHandleFile = app.handleFile;
|
||||
app.handleFile = handleFile;
|
||||
|
||||
// Add video formats to file input accept attribute
|
||||
const fileInput = document.getElementById("comfy-file-input");
|
||||
if (fileInput && !fileInput.accept.includes("video/")) {
|
||||
fileInput.accept += ",video/webm,video/mp4,video/x-matroska";
|
||||
}
|
||||
|
||||
// Mark as registered to avoid double-registration if VHS loads later
|
||||
window._vhsVideoMetadataRegistered = true;
|
||||
|
||||
console.log("[VideoMetadata] VHS-compatible video metadata reader registered");
|
||||
} else {
|
||||
console.log("[VideoMetadata] Video metadata handler already registered (likely by VHS)");
|
||||
}
|
||||
}
|
||||
});
|
||||
+4
-4
@@ -224,9 +224,9 @@ class WrappedPreviewer(_latent_preview_module.LatentPreviewer):
|
||||
|
||||
x_sample = self.taesd.decode(x0[:1, :, :1])[0][0]
|
||||
|
||||
# Apply contrast boost for Wan models (TAESD looks washed out)
|
||||
if self.model_name and self.model_name.startswith('Wan'):
|
||||
x_sample = self._apply_contrast(x_sample, contrast=1.5, brightness=1.2)
|
||||
# # Apply contrast boost for Wan models (TAESD looks washed out)
|
||||
# if self.model_name and self.model_name.startswith('Wan'):
|
||||
# x_sample = self._apply_contrast(x_sample, contrast=1.2, brightness=1.0)
|
||||
|
||||
# Video TAEs output 0-1 range, not -1 to 1
|
||||
return self._tensor_to_image(x_sample, do_scale=False)
|
||||
@@ -235,7 +235,7 @@ class WrappedPreviewer(_latent_preview_module.LatentPreviewer):
|
||||
x_sample = self.taesd.decode(x0[:1])[0].movedim(0, 2)
|
||||
return self._tensor_to_image(x_sample, do_scale=True)
|
||||
|
||||
def _apply_contrast(self, tensor, contrast=1.2, brightness=1.0):
|
||||
def _apply_contrast(self, tensor, contrast=1.0, brightness=1.0):
|
||||
"""Apply contrast and brightness adjustment to a tensor in 0-1 range."""
|
||||
# Contrast: (x - 0.5) * contrast + 0.5
|
||||
# Brightness: x * brightness
|
||||
|
||||
+126
-56
@@ -17,33 +17,32 @@ _preferences_cache = {
|
||||
"custom_llama_path": "",
|
||||
"custom_llama_model_path": "",
|
||||
"close_llama_on_exit": True,
|
||||
"custom_llama_port": 8080
|
||||
"custom_llama_port": 8080,
|
||||
"llm_backend": "llama.cpp", # "llama.cpp" or "ollama"
|
||||
"ollama_url": "http://127.0.0.1:11434",
|
||||
"ollama_keep_alive": "5m", # How long Ollama keeps model loaded after request
|
||||
}
|
||||
|
||||
# Predefined models - use real filenames as keys
|
||||
# Qwen3.5 models are unified vision+text — every model supports vision via its mmproj.
|
||||
# "mmproj" is the LOCAL filename we store on disk.
|
||||
# "mmproj_repo_filename" is the filename in the HuggingFace repo (may differ).
|
||||
QWEN_MODELS = {
|
||||
"Qwen3-4B-Q8_0.gguf": {
|
||||
"repo": "Qwen/Qwen3-4B-GGUF"
|
||||
"Qwen3.5-9B-UD-Q4_K_XL.gguf": {
|
||||
"repo": "unsloth/Qwen3.5-9B-GGUF",
|
||||
"mmproj": "mmproj-Qwen3.5-9B-F16.gguf",
|
||||
"mmproj_repo_filename": "mmproj-F16.gguf"
|
||||
},
|
||||
"Qwen3-8B-Q8_0.gguf": {
|
||||
"repo": "Qwen/Qwen3-8B-GGUF"
|
||||
"Qwen3.5-9B-Q8_0.gguf": {
|
||||
"repo": "unsloth/Qwen3.5-9B-GGUF",
|
||||
"mmproj": "mmproj-Qwen3.5-9B-F16.gguf",
|
||||
"mmproj_repo_filename": "mmproj-F16.gguf"
|
||||
},
|
||||
"Qwen3VL-4B-Instruct-Q8_0.gguf": {
|
||||
"repo": "Qwen/Qwen3-VL-4B-Instruct-GGUF",
|
||||
"mmproj": "mmproj-Qwen3VL-4B-Instruct-Q8_0.gguf"
|
||||
"Qwen3.5-9B-UD-Q8_K_XL.gguf": {
|
||||
"repo": "unsloth/Qwen3.5-9B-GGUF",
|
||||
"mmproj": "mmproj-Qwen3.5-9B-F16.gguf",
|
||||
"mmproj_repo_filename": "mmproj-F16.gguf"
|
||||
},
|
||||
"Qwen3VL-8B-Instruct-Q8_0.gguf": {
|
||||
"repo": "Qwen/Qwen3-VL-8B-Instruct-GGUF",
|
||||
"mmproj": "mmproj-Qwen3VL-8B-Instruct-Q8_0.gguf"
|
||||
},
|
||||
"Qwen3VL-4B-Thinking-Q8_0.gguf": {
|
||||
"repo": "Qwen/Qwen3-VL-4B-Thinking-GGUF",
|
||||
"mmproj": "mmproj-Qwen3VL-4B-Thinking-Q8_0.gguf"
|
||||
},
|
||||
"Qwen3VL-8B-Thinking-Q8_0.gguf": {
|
||||
"repo": "Qwen/Qwen3-VL-8B-Thinking-GGUF",
|
||||
"mmproj": "mmproj-Qwen3VL-8B-Thinking-Q8_0.gguf"
|
||||
}
|
||||
}
|
||||
|
||||
@server.PromptServer.instance.routes.get("/prompt-manager/load-preferences")
|
||||
@@ -65,7 +64,10 @@ async def save_preference(request):
|
||||
"custom_llama_path",
|
||||
"custom_llama_model_path",
|
||||
"close_llama_on_exit",
|
||||
"custom_llama_port"]:
|
||||
"custom_llama_port",
|
||||
"llm_backend",
|
||||
"ollama_url",
|
||||
"ollama_keep_alive"]:
|
||||
return server.web.json_response({"success": False, "error": "Invalid preference key"})
|
||||
|
||||
# Update in-memory cache
|
||||
@@ -76,6 +78,18 @@ async def save_preference(request):
|
||||
print(f"[Model Manager] Error saving preference: {e}")
|
||||
return server.web.json_response({"success": False, "error": str(e)}, status=500)
|
||||
|
||||
|
||||
@server.PromptServer.instance.routes.get("/prompt-manager/ollama-models")
|
||||
async def list_ollama_models(request):
|
||||
"""API endpoint to discover available Ollama models."""
|
||||
try:
|
||||
from .ollama_wrapper import discover_ollama_models
|
||||
models, status = discover_ollama_models(_preferences_cache)
|
||||
return server.web.json_response({"models": models, "status": status})
|
||||
except Exception as e:
|
||||
return server.web.json_response({"models": [], "status": f"Error: {e}"}, status=500)
|
||||
|
||||
|
||||
def get_models_directory():
|
||||
"""Get the path to the primary models directory (ComfyUI/models/gguf) for downloads"""
|
||||
# Register both gguf and LLM folders
|
||||
@@ -176,41 +190,91 @@ def get_model_path(model_name):
|
||||
models_dir = get_models_directory()
|
||||
return os.path.join(models_dir, model_name)
|
||||
|
||||
# Quantization-related filename parts — stripped when matching models to mmproj files
|
||||
_QUANT_PARTS = frozenset({
|
||||
"Q2", "Q3", "Q4", "Q5", "Q6", "Q8",
|
||||
"K", "M", "S", "L", "XS", "XL", "XXS", "XXL",
|
||||
"IQ1", "IQ2", "IQ3", "IQ4", "NL",
|
||||
"BF16", "F16", "F32",
|
||||
"0", "1", "UD",
|
||||
})
|
||||
|
||||
|
||||
def _get_model_identity(name):
|
||||
"""Extract the model's identity parts from a filename, stripping quant info.
|
||||
|
||||
Example: 'Qwen3.5-9B-Q4_K_M.gguf' → ('Qwen3', '5', '9B')
|
||||
'mmproj-Qwen3.5-9B-F16.gguf' → ('Qwen3', '5', '9B')
|
||||
"""
|
||||
base = os.path.splitext(os.path.basename(name))[0]
|
||||
parts = [p for p in re.split(r"[-._ ]", base) if p]
|
||||
return tuple(p for p in parts if p not in _QUANT_PARTS and p.lower() != "mmproj")
|
||||
|
||||
|
||||
def get_mmproj_for_model(model_name):
|
||||
"""Get the mmproj filename for a given vision model"""
|
||||
"""Get the mmproj filename for a given model from the predefined registry."""
|
||||
if model_name in QWEN_MODELS and "mmproj" in QWEN_MODELS[model_name]:
|
||||
return QWEN_MODELS[model_name]["mmproj"]
|
||||
return None
|
||||
|
||||
|
||||
def get_mmproj_path(model_name):
|
||||
"""Get the path to the mmproj file for a vision model, if it exists
|
||||
Searches for mmproj files that contain all parts of the model name
|
||||
"""Get the path to the mmproj file for a model, if it exists.
|
||||
|
||||
1. Check the explicit QWEN_MODELS mapping first.
|
||||
2. Fall back to heuristic matching by model identity (strips quant parts).
|
||||
"""
|
||||
# Get all parts of the model name (excluding .gguf)
|
||||
model_parts = [part for part in re.split(r"[-.]", os.path.splitext(os.path.basename(model_name))[0]) if part]
|
||||
# --- 1. Explicit mapping ---
|
||||
mmproj_name = get_mmproj_for_model(model_name)
|
||||
if mmproj_name:
|
||||
all_dirs = get_all_model_directories()
|
||||
for d in all_dirs:
|
||||
p = os.path.join(d, mmproj_name)
|
||||
if os.path.exists(p):
|
||||
return p
|
||||
# Mapped but file not found on disk
|
||||
return None
|
||||
|
||||
# --- 2. Heuristic: match by model identity ---
|
||||
model_identity = _get_model_identity(model_name)
|
||||
if not model_identity:
|
||||
return None
|
||||
|
||||
# Get all local mmproj files
|
||||
all_dirs = get_all_model_directories()
|
||||
mmproj_files = []
|
||||
for models_dir in all_dirs:
|
||||
if os.path.exists(models_dir):
|
||||
for f in os.listdir(models_dir):
|
||||
if 'mmproj' in f.lower() and f.endswith('.gguf'):
|
||||
mmproj_files.append(f)
|
||||
if not os.path.exists(models_dir):
|
||||
continue
|
||||
for f in os.listdir(models_dir):
|
||||
if 'mmproj' not in f.lower() or not f.endswith('.gguf'):
|
||||
continue
|
||||
mmproj_identity = _get_model_identity(f)
|
||||
if mmproj_identity and mmproj_identity == model_identity:
|
||||
return os.path.join(models_dir, f)
|
||||
|
||||
# Find mmproj that contains all model parts
|
||||
for mmproj_file in mmproj_files:
|
||||
# Let's split the mmproj filename to check for matching bits, we remove extension and mmproj
|
||||
mmproj_parts = [part for part in re.split(r"[-.]", os.path.splitext(os.path.basename(mmproj_file))[0].replace('mmproj', '')) if part]
|
||||
if all(part in mmproj_parts for part in model_parts):
|
||||
return get_model_path(mmproj_file)
|
||||
return None
|
||||
|
||||
|
||||
def has_vision_support(model_name):
|
||||
"""Check whether a model has vision capabilities.
|
||||
|
||||
Returns True if an mmproj file is available (on disk or in the registry).
|
||||
"""
|
||||
# Check explicit registry first (even if not yet downloaded)
|
||||
if get_mmproj_for_model(model_name):
|
||||
return True
|
||||
# Check if a matching mmproj file already exists on disk
|
||||
return get_mmproj_path(model_name) is not None
|
||||
|
||||
def download_model(model_name):
|
||||
"""Download a model from HuggingFace with automatic progress display
|
||||
For VL models, also downloads the matching mmproj file if needed
|
||||
"""Download a model from HuggingFace with automatic progress display.
|
||||
Also downloads the matching mmproj file if one is defined.
|
||||
|
||||
The mmproj file in the repo may have a generic name (e.g. 'mmproj-F16.gguf').
|
||||
We rename it on download to a model-specific name to avoid conflicts when
|
||||
multiple model sizes are installed side-by-side.
|
||||
|
||||
Args:
|
||||
model_name: Filename of the model (e.g., "Qwen3-4B-Q8_0.gguf")
|
||||
model_name: Filename of the model (e.g., 'Qwen3.5-9B-Q8_0.gguf')
|
||||
|
||||
Returns:
|
||||
Path to downloaded model or None on error
|
||||
@@ -224,38 +288,44 @@ def download_model(model_name):
|
||||
models_dir = get_models_directory()
|
||||
|
||||
# Build list of files to download
|
||||
# Each entry: repo_filename (name in the HF repo), local_filename (name on disk), desc
|
||||
files_to_download = [
|
||||
{"filename": model_name, "desc": "Downloading model"}
|
||||
{"repo_filename": model_name, "local_filename": model_name, "desc": "Downloading model"}
|
||||
]
|
||||
|
||||
# Add mmproj file if this is a VL model
|
||||
mmproj_name = get_mmproj_for_model(model_name)
|
||||
if mmproj_name:
|
||||
# Add mmproj file if this model has one
|
||||
mmproj_local = get_mmproj_for_model(model_name)
|
||||
if mmproj_local:
|
||||
mmproj_repo = model_info.get("mmproj_repo_filename", mmproj_local)
|
||||
files_to_download.append({
|
||||
"filename": mmproj_name,
|
||||
"repo_filename": mmproj_repo,
|
||||
"local_filename": mmproj_local,
|
||||
"desc": "Downloading mmproj"
|
||||
})
|
||||
|
||||
# Download each file if it doesn't exist
|
||||
for file_info in files_to_download:
|
||||
filename = file_info["filename"]
|
||||
local_path = os.path.join(models_dir, filename)
|
||||
repo_filename = file_info["repo_filename"]
|
||||
local_filename = file_info["local_filename"]
|
||||
local_path = os.path.join(models_dir, local_filename)
|
||||
|
||||
if os.path.exists(local_path):
|
||||
print(f"[Model Manager] File already exists: {filename}")
|
||||
print(f"[Model Manager] File already exists: {local_filename}")
|
||||
continue
|
||||
|
||||
# Download the file
|
||||
try:
|
||||
print(f"[Model Manager] Downloading {filename} from {repo_id}...")
|
||||
print(f"[Model Manager] Downloading {repo_filename} from {repo_id}...")
|
||||
api = HfApi()
|
||||
repo_info = api.repo_info(repo_id=repo_id, files_metadata=True)
|
||||
file_metadata = next((f for f in repo_info.siblings if f.rfilename == filename), None)
|
||||
repo_info_obj = api.repo_info(repo_id=repo_id, files_metadata=True)
|
||||
file_metadata = next((f for f in repo_info_obj.siblings if f.rfilename == repo_filename), None)
|
||||
if not file_metadata or file_metadata.size is None:
|
||||
print(f"[Model Manager] Could not find file size for {filename} in {repo_id}")
|
||||
print(f"[Model Manager] Could not find file size for {repo_filename} in {repo_id}")
|
||||
return None
|
||||
total_size = file_metadata.size
|
||||
download_url = f"https://huggingface.co/{repo_id}/resolve/main/{filename}"
|
||||
download_url = f"https://huggingface.co/{repo_id}/resolve/main/{repo_filename}"
|
||||
if local_filename != repo_filename:
|
||||
print(f"[Model Manager] Will save as: {local_filename}")
|
||||
pbar = tqdm(total=total_size, unit="B", unit_scale=True, desc=file_info["desc"])
|
||||
with requests.get(download_url, stream=True) as r, open(local_path, "wb") as f:
|
||||
r.raise_for_status()
|
||||
@@ -264,9 +334,9 @@ def download_model(model_name):
|
||||
f.write(chunk)
|
||||
pbar.update(len(chunk))
|
||||
pbar.close()
|
||||
print(f"[Model Manager] Successfully downloaded {filename}")
|
||||
print(f"[Model Manager] Successfully downloaded {local_filename}")
|
||||
except Exception as e:
|
||||
print(f"[Model Manager] Error downloading {filename}: {e}")
|
||||
print(f"[Model Manager] Error downloading {repo_filename}: {e}")
|
||||
return None
|
||||
|
||||
return os.path.join(models_dir, model_name)
|
||||
|
||||
@@ -0,0 +1,198 @@
|
||||
"""
|
||||
Ollama integration for ComfyUI Prompt Manager.
|
||||
|
||||
Provides model discovery, generation, and memory management
|
||||
via Ollama's native API and OpenAI-compatible endpoint.
|
||||
"""
|
||||
import requests
|
||||
import json
|
||||
|
||||
# ============================================================================
|
||||
# Default endpoints
|
||||
# ============================================================================
|
||||
|
||||
DEFAULT_OLLAMA_URL = "http://127.0.0.1:11434"
|
||||
|
||||
|
||||
def _get_ollama_base(user_config):
|
||||
"""Resolve Ollama base URL (without /v1 or /api) from config."""
|
||||
url = str(user_config.get("ollama_url", DEFAULT_OLLAMA_URL)).strip().rstrip("/")
|
||||
if not url:
|
||||
url = DEFAULT_OLLAMA_URL
|
||||
# Strip trailing /v1 or /api paths so we always have the root
|
||||
for suffix in ("/v1", "/api", "/api/tags", "/api/chat"):
|
||||
if url.endswith(suffix):
|
||||
url = url[: -len(suffix)]
|
||||
break
|
||||
return url
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Model discovery
|
||||
# ============================================================================
|
||||
|
||||
def discover_ollama_models(user_config):
|
||||
"""Query Ollama for available models.
|
||||
|
||||
Returns:
|
||||
(list_of_model_names, status_message)
|
||||
"""
|
||||
base = _get_ollama_base(user_config)
|
||||
tags_url = f"{base}/api/tags"
|
||||
timeout = 12
|
||||
|
||||
try:
|
||||
response = requests.get(tags_url, timeout=timeout)
|
||||
if response.status_code == 200:
|
||||
payload = response.json()
|
||||
names = []
|
||||
if isinstance(payload, dict):
|
||||
for item in payload.get("models", []):
|
||||
if isinstance(item, dict):
|
||||
name = item.get("model") or item.get("name")
|
||||
if isinstance(name, str) and name.strip():
|
||||
names.append(name.strip())
|
||||
if names:
|
||||
unique = sorted(set(names), key=lambda x: x.lower())
|
||||
return unique, f"Found {len(unique)} Ollama model(s)."
|
||||
return [], "Ollama responded but no models were found. Pull one first, e.g. `ollama pull llama3.1`."
|
||||
return [], f"Ollama returned HTTP {response.status_code}."
|
||||
except requests.exceptions.ConnectionError:
|
||||
return [], f"Could not connect to Ollama at {base}. Start `ollama serve` and retry."
|
||||
except requests.exceptions.Timeout:
|
||||
return [], f"Timed out querying Ollama at {base}."
|
||||
except Exception as e:
|
||||
return [], f"Failed to query Ollama models: {e}"
|
||||
|
||||
|
||||
def is_ollama_available(user_config):
|
||||
"""Check if Ollama is reachable."""
|
||||
base = _get_ollama_base(user_config)
|
||||
try:
|
||||
resp = requests.get(f"{base}/api/tags", timeout=5)
|
||||
return resp.status_code == 200
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Generation (OpenAI-compatible chat/completions via Ollama)
|
||||
# ============================================================================
|
||||
|
||||
def generate_chat(user_config, model_name, messages, temperature=0.8,
|
||||
top_k=40, top_p=0.95, min_p=0.05, repeat_penalty=1.0,
|
||||
seed=None, stream=True, timeout=120,
|
||||
use_model_defaults=True, enable_thinking=False):
|
||||
"""Send a chat completion request to Ollama's OpenAI-compatible endpoint.
|
||||
|
||||
Args:
|
||||
user_config: preferences dict with ollama_url, ollama_keep_alive, etc.
|
||||
model_name: Ollama model tag (e.g. "llama3.1:latest")
|
||||
messages: list of {role, content} dicts (OpenAI format)
|
||||
stream: if True, returns a streaming response iterator
|
||||
timeout: request timeout in seconds
|
||||
|
||||
Returns:
|
||||
If stream=False: (response_text, thinking_text, usage_stats, error_msg)
|
||||
If stream=True: (response_object, error_msg) — caller handles streaming
|
||||
"""
|
||||
base = _get_ollama_base(user_config)
|
||||
url = f"{base}/v1/chat/completions"
|
||||
|
||||
payload = {
|
||||
"model": model_name,
|
||||
"messages": messages,
|
||||
"stream": stream,
|
||||
}
|
||||
|
||||
# Set keep_alive to control how long the model stays loaded after this request
|
||||
keep_alive = user_config.get("ollama_keep_alive", "5m")
|
||||
if keep_alive:
|
||||
payload["keep_alive"] = keep_alive
|
||||
|
||||
if stream:
|
||||
payload["stream_options"] = {"include_usage": True}
|
||||
|
||||
if seed is not None:
|
||||
payload["seed"] = seed
|
||||
|
||||
if enable_thinking:
|
||||
payload["chat_template_kwargs"] = {"enable_thinking": True}
|
||||
|
||||
if not use_model_defaults:
|
||||
payload["temperature"] = temperature
|
||||
payload["top_k"] = top_k
|
||||
payload["top_p"] = top_p
|
||||
payload["min_p"] = min_p
|
||||
payload["repeat_penalty"] = repeat_penalty
|
||||
|
||||
try:
|
||||
response = requests.post(url, json=payload, timeout=timeout, stream=stream)
|
||||
if response.status_code != 200:
|
||||
detail = _extract_error(response)
|
||||
return (None, f"Ollama request failed ({response.status_code}): {detail}")
|
||||
if stream:
|
||||
return (response, None)
|
||||
else:
|
||||
result = response.json()
|
||||
text = result["choices"][0]["message"]["content"]
|
||||
usage = result.get("usage")
|
||||
return (text.strip(), "", usage, None)
|
||||
except requests.exceptions.ConnectionError:
|
||||
return (None, "Could not connect to Ollama. Start 'ollama serve' and retry.")
|
||||
except requests.exceptions.Timeout:
|
||||
return (None, f"Ollama request timed out ({timeout}s). Try a shorter prompt or smaller model.")
|
||||
except (KeyError, IndexError):
|
||||
return (None, "Unexpected response format from Ollama.")
|
||||
except Exception as e:
|
||||
return (None, f"Ollama generation failed: {e}")
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Memory management — unload model from Ollama VRAM
|
||||
# ============================================================================
|
||||
|
||||
def unload_model(user_config, model_name):
|
||||
"""Tell Ollama to unload a model from memory (free VRAM).
|
||||
|
||||
Uses the /api/generate endpoint with keep_alive=0 to immediately
|
||||
evict the model from GPU memory.
|
||||
"""
|
||||
base = _get_ollama_base(user_config)
|
||||
url = f"{base}/api/generate"
|
||||
|
||||
try:
|
||||
response = requests.post(url, json={
|
||||
"model": model_name,
|
||||
"keep_alive": 0,
|
||||
}, timeout=15)
|
||||
if response.status_code == 200:
|
||||
return True, f"Model '{model_name}' unloaded from Ollama memory."
|
||||
return False, f"Ollama returned HTTP {response.status_code} while unloading model."
|
||||
except requests.exceptions.ConnectionError:
|
||||
return False, "Could not connect to Ollama to unload model."
|
||||
except Exception as e:
|
||||
return False, f"Failed to unload model from Ollama: {e}"
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Helpers
|
||||
# ============================================================================
|
||||
|
||||
def _extract_error(response):
|
||||
"""Extract error message from an Ollama error response."""
|
||||
try:
|
||||
payload = response.json()
|
||||
except ValueError:
|
||||
text = (response.text or "").strip()
|
||||
return text[:300] if text else f"HTTP {response.status_code}"
|
||||
|
||||
if isinstance(payload, dict):
|
||||
err = payload.get("error")
|
||||
if isinstance(err, str) and err.strip():
|
||||
return err.strip()
|
||||
msg = payload.get("message")
|
||||
if isinstance(msg, str) and msg.strip():
|
||||
return msg.strip()
|
||||
|
||||
return f"HTTP {response.status_code}"
|
||||
+183
-29
@@ -25,6 +25,28 @@ _file_metadata_cache = {}
|
||||
# Cache for video frames extracted by JavaScript
|
||||
_video_frames_cache = {}
|
||||
|
||||
# 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
|
||||
|
||||
def is_lora_blacklisted(lora_name):
|
||||
"""Check if a LoRA name contains any blacklisted keywords (case-insensitive)"""
|
||||
if not lora_name:
|
||||
return False
|
||||
lora_name_lower = lora_name.lower()
|
||||
for keyword in LORA_BLACKLIST:
|
||||
if isinstance(keyword, list):
|
||||
# We check if all keywords in the list are present in the lora_name for a match
|
||||
if all(k.lower() in lora_name_lower for k in keyword):
|
||||
return True
|
||||
else:
|
||||
if keyword.lower() in lora_name_lower:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def parse_a1111_parameters(parameters_text):
|
||||
"""
|
||||
@@ -1487,6 +1509,9 @@ def parse_workflow_for_prompts(prompt_data, workflow_data=None):
|
||||
|
||||
# Add all LoRAs to stack_a (A1111 doesn't have dual stacks)
|
||||
for lora in prompt_data.get('loras', []):
|
||||
# Skip blacklisted LoRAs
|
||||
if is_lora_blacklisted(lora['name']):
|
||||
continue
|
||||
result['loras_a'].append({
|
||||
'name': lora['name'],
|
||||
'model_strength': lora['model_strength'],
|
||||
@@ -1640,7 +1665,13 @@ def parse_workflow_for_prompts(prompt_data, workflow_data=None):
|
||||
chain_loras, chain_titles = collect_lora_model_chain(source_id, node_map, link_map)
|
||||
|
||||
if chain_loras:
|
||||
print(f"[PromptExtractor] Chain from terminal {terminal_id} ({terminal_info.get('terminal_title', '')}): {len(chain_loras)} LoRAs")
|
||||
active_count = sum(1 for lora in chain_loras if lora.get('active', True))
|
||||
inactive_count = len(chain_loras) - active_count
|
||||
lora_names_in_chain = [lora.get('name', 'unknown') for lora in chain_loras if lora.get('active', True)]
|
||||
print(f"[PromptExtractor] Chain from terminal {terminal_id} ({terminal_info.get('terminal_title', '')}), input '{input_name}': {active_count} active, {inactive_count} inactive LoRAs")
|
||||
print(f"[PromptExtractor] Active LoRAs: {lora_names_in_chain}")
|
||||
print(f"[PromptExtractor] Chain titles: {chain_titles}")
|
||||
print(f"[PromptExtractor] Input label: {terminal_info.get('input_label', '')}")
|
||||
|
||||
# Mark this terminal input as processed
|
||||
processed_terminals.add(terminal_key)
|
||||
@@ -1716,6 +1747,7 @@ def parse_workflow_for_prompts(prompt_data, workflow_data=None):
|
||||
|
||||
lora_chains.sort(key=lambda x: x.get('source_id', 0))
|
||||
|
||||
print(f"[PromptExtractor] Processing {len(lora_chains)} chains for stack assignment")
|
||||
for i, chain in enumerate(lora_chains):
|
||||
# Check ALL titles in the chain for high/low hints
|
||||
all_titles = chain.get('titles', []) + [chain.get('terminal_title', '')]
|
||||
@@ -1725,49 +1757,140 @@ def parse_workflow_for_prompts(prompt_data, workflow_data=None):
|
||||
input_name = chain.get('input_name', '').lower()
|
||||
input_label = chain.get('input_label', '').lower()
|
||||
|
||||
# More specific matching - look for whole words or clear patterns
|
||||
has_high = (
|
||||
'high' in all_titles_lower or
|
||||
'high' in input_name or
|
||||
'high' in input_label
|
||||
# IMPORTANT: Only check ACTIVE loras for the chain assignment
|
||||
active_loras = [lora for lora in chain.get('loras', []) if lora.get('active', True)]
|
||||
|
||||
print(f"[PromptExtractor] Chain {i}: {len(chain.get('loras', []))} total LoRAs, {len(active_loras)} active")
|
||||
print(f" Titles: {all_titles}")
|
||||
print(f" Active LoRA names: {[lora.get('name', '') for lora in active_loras]}")
|
||||
|
||||
# PRIORITY 1: Check CHAIN STRUCTURE (most reliable)
|
||||
# Use word boundaries to match complete words in titles and input names
|
||||
chain_has_high = (
|
||||
re.search(r'\bhigh\b', all_titles_lower) or
|
||||
re.search(r'\bhigh\b', input_name) or
|
||||
re.search(r'\bhigh\b', input_label) or
|
||||
'highnoise' in all_titles_lower.replace('_', '').replace('-', '').replace(' ', '')
|
||||
)
|
||||
has_low = (
|
||||
'low' in all_titles_lower or
|
||||
'low' in input_name or
|
||||
'low' in input_label
|
||||
chain_has_low = (
|
||||
re.search(r'\blow\b', all_titles_lower) or
|
||||
re.search(r'\blow\b', input_name) or
|
||||
re.search(r'\blow\b', input_label) or
|
||||
'lownoise' in all_titles_lower.replace('_', '').replace('-', '').replace(' ', '')
|
||||
)
|
||||
|
||||
# PRIORITY 2: Check LoRA filenames with MAJORITY VOTING (fallback when chain structure unclear)
|
||||
# Count how many LoRAs have high/low indicators (excluding blacklisted LoRAs)
|
||||
high_count = 0
|
||||
low_count = 0
|
||||
for lora in active_loras:
|
||||
lora_name = lora.get('name', '')
|
||||
# Skip blacklisted LoRAs from voting
|
||||
if is_lora_blacklisted(lora_name):
|
||||
continue
|
||||
lora_name_lower = lora_name.lower()
|
||||
has_high_pattern = (
|
||||
'_high' in lora_name_lower or
|
||||
'-high' in lora_name_lower or
|
||||
'high_' in lora_name_lower or
|
||||
'_h.' in lora_name_lower or
|
||||
'_h_' in lora_name_lower
|
||||
)
|
||||
has_low_pattern = (
|
||||
'_low' in lora_name_lower or
|
||||
'-low' in lora_name_lower or
|
||||
'low_' in lora_name_lower or
|
||||
'_l.' in lora_name_lower or
|
||||
'_l_' in lora_name_lower
|
||||
)
|
||||
if has_high_pattern:
|
||||
high_count += 1
|
||||
if has_low_pattern:
|
||||
low_count += 1
|
||||
low_count += 1
|
||||
|
||||
# Combine: Chain structure takes priority, filenames used as tiebreaker
|
||||
has_high = chain_has_high or (not chain_has_low and high_count > low_count)
|
||||
has_low = chain_has_low or (not chain_has_high and low_count > high_count)
|
||||
|
||||
print(f" Chain structure: high={chain_has_high}, low={chain_has_low}")
|
||||
print(f" LoRA filename voting: {high_count} high, {low_count} low")
|
||||
print(f" Final decision: has_high={has_high}, has_low={has_low}")
|
||||
|
||||
# Determine which stack based on title hints
|
||||
if has_high and not has_low:
|
||||
print(f"[PromptExtractor] Chain {i} → STACK A (high detected in chain structure)")
|
||||
for lora in chain['loras']:
|
||||
# Only add active LoRAs
|
||||
if not lora.get('active', True):
|
||||
continue
|
||||
# Skip blacklisted LoRAs
|
||||
if is_lora_blacklisted(lora['name']):
|
||||
print(f" Skipping blacklisted LoRA: {lora['name']}")
|
||||
continue
|
||||
if lora['name'] not in lora_names_seen_a:
|
||||
lora_names_seen_a.add(lora['name'])
|
||||
loras_a.append(lora)
|
||||
elif has_low and not has_high:
|
||||
print(f"[PromptExtractor] Chain {i} → STACK B (low detected in chain structure)")
|
||||
for lora in chain['loras']:
|
||||
# Only add active LoRAs
|
||||
if not lora.get('active', True):
|
||||
continue
|
||||
# Skip blacklisted LoRAs
|
||||
if is_lora_blacklisted(lora['name']):
|
||||
print(f" Skipping blacklisted LoRA: {lora['name']}")
|
||||
continue
|
||||
if lora['name'] not in lora_names_seen_b:
|
||||
lora_names_seen_b.add(lora['name'])
|
||||
loras_b.append(lora)
|
||||
elif i == 0:
|
||||
# First chain defaults to A
|
||||
print(f"[PromptExtractor] Chain {i} → STACK A (first chain default, has_high={has_high}, has_low={has_low})")
|
||||
for lora in chain['loras']:
|
||||
# Only add active LoRAs
|
||||
if not lora.get('active', True):
|
||||
continue
|
||||
# Skip blacklisted LoRAs
|
||||
if is_lora_blacklisted(lora['name']):
|
||||
print(f" Skipping blacklisted LoRA: {lora['name']}")
|
||||
continue
|
||||
if lora['name'] not in lora_names_seen_a:
|
||||
lora_names_seen_a.add(lora['name'])
|
||||
loras_a.append(lora)
|
||||
elif i == 1:
|
||||
# Second chain defaults to B
|
||||
print(f"[PromptExtractor] Chain {i} → STACK B (second chain default, has_high={has_high}, has_low={has_low})")
|
||||
for lora in chain['loras']:
|
||||
# Only add active LoRAs
|
||||
if not lora.get('active', True):
|
||||
continue
|
||||
# Skip blacklisted LoRAs
|
||||
if is_lora_blacklisted(lora['name']):
|
||||
print(f" Skipping blacklisted LoRA: {lora['name']}")
|
||||
continue
|
||||
if lora['name'] not in lora_names_seen_b:
|
||||
lora_names_seen_b.add(lora['name'])
|
||||
loras_b.append(lora)
|
||||
else:
|
||||
# Additional chains go to A
|
||||
print(f"[PromptExtractor] Chain {i} → STACK A (additional chain default, has_high={has_high}, has_low={has_low})")
|
||||
for lora in chain['loras']:
|
||||
# Only add active LoRAs
|
||||
if not lora.get('active', True):
|
||||
continue
|
||||
# Skip blacklisted LoRAs
|
||||
if is_lora_blacklisted(lora['name']):
|
||||
print(f" Skipping blacklisted LoRA: {lora['name']}")
|
||||
continue
|
||||
if lora['name'] not in lora_names_seen_a:
|
||||
lora_names_seen_a.add(lora['name'])
|
||||
loras_a.append(lora)
|
||||
|
||||
# Also iterate through prompt_data format (API format)
|
||||
# BUT: Only extract LoRAs from API format if we didn't already get them from workflow chains
|
||||
skip_api_lora_extraction = len(lora_chains) > 0
|
||||
|
||||
for node_id, node_data in data.items():
|
||||
if not isinstance(node_data, dict):
|
||||
continue
|
||||
@@ -1779,16 +1902,37 @@ def parse_workflow_for_prompts(prompt_data, workflow_data=None):
|
||||
if class_type in ['CLIPTextEncode', 'CLIPTextEncodeSDXL', 'CLIPTextEncodeFlux']:
|
||||
text = inputs.get('text', '')
|
||||
if text and isinstance(text, str):
|
||||
positive_prompts.append(text)
|
||||
# Determine if this is positive or negative by checking connections
|
||||
connection_type = None
|
||||
if node_map:
|
||||
actual_node_id = int(node_id) if str(node_id).isdigit() else node_id
|
||||
connection_type = determine_clip_text_encode_type(actual_node_id, workflow_data, node_map)
|
||||
|
||||
# PromptManager nodes
|
||||
# Fallback: check node title if we have node_map
|
||||
if not connection_type and node_map:
|
||||
node = node_map.get(actual_node_id)
|
||||
if node:
|
||||
title_lower = node.get('title', '').lower()
|
||||
if 'negative' in title_lower:
|
||||
connection_type = 'negative'
|
||||
elif 'positive' in title_lower:
|
||||
connection_type = 'positive'
|
||||
|
||||
# Add to appropriate list (default to positive if unclear)
|
||||
if connection_type == 'negative':
|
||||
negative_prompts.append(text)
|
||||
else:
|
||||
positive_prompts.append(text)
|
||||
|
||||
# PromptManager nodes (always positive)
|
||||
elif class_type in ['PromptManager', 'PromptManagerAdvanced']:
|
||||
text = inputs.get('text', '')
|
||||
if text and isinstance(text, str):
|
||||
positive_prompts.append(text)
|
||||
|
||||
# Standard LoRA loaders (API format)
|
||||
elif class_type in ['LoraLoader', 'LoraLoaderModelOnly']:
|
||||
# Skip this if we already extracted LoRAs from workflow chains
|
||||
elif class_type in ['LoraLoader', 'LoraLoaderModelOnly'] and not skip_api_lora_extraction:
|
||||
# Check if this node's MODEL output is connected
|
||||
if node_map:
|
||||
node = node_map.get(int(node_id) if str(node_id).isdigit() else node_id)
|
||||
@@ -1806,33 +1950,43 @@ def parse_workflow_for_prompts(prompt_data, workflow_data=None):
|
||||
|
||||
lora_name = inputs.get('lora_name', '')
|
||||
if lora_name and lora_name not in lora_names_seen_a:
|
||||
# Skip blacklisted LoRAs
|
||||
lora_basename = os.path.splitext(os.path.basename(lora_name))[0]
|
||||
if is_lora_blacklisted(lora_basename):
|
||||
continue
|
||||
lora_names_seen_a.add(lora_name)
|
||||
model_strength = float(inputs.get('strength_model', inputs.get('strength', 1.0)))
|
||||
clip_strength = float(inputs.get('strength_clip', model_strength))
|
||||
loras_a.append({
|
||||
'name': os.path.splitext(os.path.basename(lora_name))[0],
|
||||
'name': lora_basename,
|
||||
'path': lora_name,
|
||||
'model_strength': model_strength,
|
||||
'clip_strength': clip_strength
|
||||
})
|
||||
|
||||
# Also check for LoRA syntax in prompts: <lora:name:strength>
|
||||
all_prompts = ' '.join(positive_prompts + negative_prompts)
|
||||
lora_pattern = r'<lora:([^:>]+):([^:>]+)(?::([^>]+))?>'
|
||||
for match in re.finditer(lora_pattern, all_prompts):
|
||||
lora_name = match.group(1).strip()
|
||||
if lora_name not in lora_names_seen_a:
|
||||
lora_names_seen_a.add(lora_name)
|
||||
model_strength = float(match.group(2)) if match.group(2) else 1.0
|
||||
clip_strength = float(match.group(3)) if match.group(3) else model_strength
|
||||
loras_a.append({
|
||||
'name': lora_name,
|
||||
'path': '',
|
||||
'model_strength': model_strength,
|
||||
'clip_strength': clip_strength
|
||||
})
|
||||
# Skip this if we already extracted LoRAs from workflow chains
|
||||
if not skip_api_lora_extraction:
|
||||
all_prompts = ' '.join(positive_prompts + negative_prompts)
|
||||
lora_pattern = r'<lora:([^:>]+):([^:>]+)(?::([^>]+))?>'
|
||||
for match in re.finditer(lora_pattern, all_prompts):
|
||||
lora_name = match.group(1).strip()
|
||||
# Skip blacklisted LoRAs
|
||||
if is_lora_blacklisted(lora_name):
|
||||
continue
|
||||
if lora_name not in lora_names_seen_a:
|
||||
lora_names_seen_a.add(lora_name)
|
||||
model_strength = float(match.group(2)) if match.group(2) else 1.0
|
||||
clip_strength = float(match.group(3)) if match.group(3) else model_strength
|
||||
loras_a.append({
|
||||
'name': lora_name,
|
||||
'path': '',
|
||||
'model_strength': model_strength,
|
||||
'clip_strength': clip_strength
|
||||
})
|
||||
|
||||
# Clean LoRA syntax from prompts
|
||||
# Clean LoRA syntax from prompts (even if we skipped extraction, we still clean the syntax)
|
||||
lora_pattern = r'<lora:([^:>]+):([^:>]+)(?::([^>]+))?>'
|
||||
clean_positive = []
|
||||
for p in positive_prompts:
|
||||
cleaned = re.sub(lora_pattern, '', p).strip()
|
||||
|
||||
+296
-92
@@ -13,7 +13,10 @@ import numpy as np
|
||||
from colorama import Fore, Style
|
||||
from PIL import Image
|
||||
from io import BytesIO
|
||||
from .model_manager import get_local_models, get_model_path, is_model_local, download_model, get_mmproj_path
|
||||
from .model_manager import get_local_models, get_model_path, is_model_local, download_model, get_mmproj_path, has_vision_support
|
||||
|
||||
# Ollama integration
|
||||
from .ollama_wrapper import generate_chat as ollama_generate_chat, unload_model as ollama_unload_model
|
||||
|
||||
# ComfyUI interrupt helper
|
||||
import comfy.model_management
|
||||
@@ -229,7 +232,7 @@ class PromptGenerator:
|
||||
|
||||
@staticmethod
|
||||
def get_image_system_prompt():
|
||||
"""Load the system prompt for image description (used with Qwen3VL)."""
|
||||
"""Load the system prompt for image description (used with vision models)."""
|
||||
return load_prompt("image_default_system_prompt.txt")
|
||||
|
||||
@staticmethod
|
||||
@@ -248,63 +251,54 @@ class PromptGenerator:
|
||||
return load_prompt("json_system_prompt.txt")
|
||||
|
||||
@staticmethod
|
||||
def find_qwen3vl_model(available_models, thinking):
|
||||
"""Find the preferred or smallest available Qwen3VL model
|
||||
def find_vision_model(available_models):
|
||||
"""Find the preferred or first available vision-capable model.
|
||||
|
||||
First checks user preferences, then falls back to smallest model (4B preferred over 8B)
|
||||
A model is considered vision-capable if it has an mmproj file
|
||||
(either in the registry or on disk).
|
||||
"""
|
||||
|
||||
qwen3vl_models = [m for m in available_models if 'qwen3vl' in m.lower()]
|
||||
if not qwen3vl_models:
|
||||
vision_models = [m for m in available_models if has_vision_support(m)]
|
||||
if not vision_models:
|
||||
return None
|
||||
|
||||
# Check user preference first
|
||||
preferred = _preferences_cache.get("preferred_vision_model", "")
|
||||
if preferred and preferred in qwen3vl_models and is_model_local(preferred):
|
||||
if thinking:
|
||||
if 'thinking' in preferred.lower():
|
||||
return preferred
|
||||
else:
|
||||
if 'thinking' not in preferred.lower():
|
||||
return preferred
|
||||
if preferred and preferred in vision_models and is_model_local(preferred):
|
||||
return preferred
|
||||
|
||||
# Let's filter models based on thinking mode
|
||||
if thinking:
|
||||
filtered_models = [model for model in qwen3vl_models if 'thinking' in model.lower()]
|
||||
else:
|
||||
filtered_models = [model for model in qwen3vl_models if 'thinking' not in model.lower()]
|
||||
if filtered_models:
|
||||
qwen3vl_models = filtered_models
|
||||
|
||||
# Fall back to smaller model (prefer 4B over 8B)
|
||||
for model in qwen3vl_models:
|
||||
if '4b' in model.lower():
|
||||
# Fall back to smallest model
|
||||
for model in vision_models:
|
||||
if '4b' in model.lower() or '3b' in model.lower():
|
||||
return model
|
||||
|
||||
return qwen3vl_models[0]
|
||||
return vision_models[0]
|
||||
|
||||
@staticmethod
|
||||
def find_non_vl_model(available_models):
|
||||
"""Find the preferred or smallest available non-vision model by file size
|
||||
def find_text_model(available_models):
|
||||
"""Find the preferred or smallest available model for text enhancement.
|
||||
|
||||
First checks user preferences, then falls back to smallest model by file size
|
||||
Any model can be used for text (vision models work too),
|
||||
but we prefer non-vision models when available to save resources.
|
||||
Falls back to vision-capable models if that's all there is.
|
||||
"""
|
||||
# Prefer models without mmproj (lighter weight)
|
||||
text_only = [m for m in available_models if not has_vision_support(m)]
|
||||
|
||||
non_vl_models = [m for m in available_models if 'qwen3vl' not in m.lower()]
|
||||
if not non_vl_models:
|
||||
candidates = text_only if text_only else available_models
|
||||
if not candidates:
|
||||
return None
|
||||
|
||||
# Check user preference first
|
||||
preferred = _preferences_cache.get("preferred_base_model", "")
|
||||
if preferred and preferred in non_vl_models and is_model_local(preferred):
|
||||
if preferred and preferred in candidates and is_model_local(preferred):
|
||||
return preferred
|
||||
|
||||
# Fall back to smaller model (prefer 4B over 8B)
|
||||
for model in non_vl_models:
|
||||
if '4b' in model.lower():
|
||||
# Fall back to smallest model
|
||||
for model in candidates:
|
||||
if '4b' in model.lower() or '3b' in model.lower():
|
||||
return model
|
||||
|
||||
return non_vl_models[0]
|
||||
return candidates[0]
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
@@ -314,7 +308,8 @@ class PromptGenerator:
|
||||
"default": 0,
|
||||
"min": 0,
|
||||
"max": 0xffffffffffffffff,
|
||||
"tooltip": "Seed for reproducible generation."
|
||||
"tooltip": "Seed for reproducible generation.",
|
||||
"control_after_generate": True
|
||||
}),
|
||||
},
|
||||
"optional": {
|
||||
@@ -443,15 +438,14 @@ class PromptGenerator:
|
||||
# Build command arguments
|
||||
cmd_args = [server_cmd, "-m", model_path, "--port", str(PromptGenerator.SERVER_PORT), "--no-warmup", "-c", str(context_size)]
|
||||
|
||||
# Add vision flags for VL models
|
||||
# Add vision flags for models with mmproj
|
||||
if use_vision_model:
|
||||
mmproj_path = get_mmproj_path(model_name)
|
||||
if mmproj_path:
|
||||
# Only print if mmproj is used
|
||||
print_pg(f"Vision model: using mmproj: {os.path.basename(mmproj_path)}")
|
||||
cmd_args.extend(["--mmproj", mmproj_path])
|
||||
else:
|
||||
error_msg = f"Error: Vision model requires mmproj file for '{model_name}' but it was not found. \nPlease ensure it exists, or use the Generator Options node to download the Qwen3VL model and its mmproj file."
|
||||
error_msg = f"Error: Vision mode requires an mmproj file for '{model_name}' but none was found.\nPlease ensure an mmproj file exists, or use the Generator Options node to download a vision-capable model."
|
||||
print_pg(error_msg, RED)
|
||||
return (False, error_msg)
|
||||
|
||||
@@ -650,11 +644,17 @@ class PromptGenerator:
|
||||
return PromptGenerator.fetch_model_defaults()
|
||||
|
||||
def convert_prompt(self, seed: int, mode="Enhance Prompt (Image)", prompt="", image=None, format_as_json=False, enable_thinking=True, stop_server_after=False, options=None, **kwargs) -> str:
|
||||
"""Convert prompt using llama.cpp server, with caching for repeated requests."""
|
||||
"""Convert prompt using llama.cpp server or Ollama, with caching for repeated requests."""
|
||||
global _current_model
|
||||
|
||||
print_pg_header() # Print header for this execution
|
||||
|
||||
# Determine LLM backend: "ollama" or "llama.cpp"
|
||||
use_ollama = (
|
||||
(options and options.get("llm_backend") == "ollama")
|
||||
or _preferences_cache.get("llm_backend", "llama.cpp") == "ollama"
|
||||
)
|
||||
|
||||
# Extract console option from connected options node
|
||||
show_everything_in_console = False # Default to False when options not connected
|
||||
use_model_default_sampling = True # Default to using model defaults
|
||||
@@ -678,57 +678,69 @@ class PromptGenerator:
|
||||
|
||||
# Always determine a valid model filename before running server
|
||||
model_to_use = None
|
||||
available_models = get_local_models()
|
||||
|
||||
if use_vision_model:
|
||||
# Check if options specifies a Qwen3VL model
|
||||
if options and "model" in options and "vl" in options["model"].lower() and is_model_local(options["model"]):
|
||||
if use_ollama:
|
||||
# ── Ollama model selection ──
|
||||
# Priority: Options node > auto-discover from Ollama
|
||||
if options and "model" in options:
|
||||
model_to_use = options["model"]
|
||||
elif options and "model" in options and is_model_local(options["model"]):
|
||||
# Non-VL model selected but in vision mode
|
||||
print_pg(f"Warning: Non-vision model '{options['model']}' selected but '{mode}' mode is active.\nIgnoring model selection and using a Vision Model instead.")
|
||||
model_to_use = self.find_qwen3vl_model(available_models, enable_thinking)
|
||||
if model_to_use is None:
|
||||
error_msg = f"Error: '{mode}' mode requires a Qwen3VL model. Please connect the Options node and select a Qwen3VL model (Qwen3VL-4B or Qwen3VL-8B) to use vision capabilities."
|
||||
print_pg(error_msg, RED)
|
||||
return (error_msg,)
|
||||
else:
|
||||
# Try to find a Qwen3VL model automatically
|
||||
model_to_use = self.find_qwen3vl_model(available_models, enable_thinking)
|
||||
if model_to_use is None:
|
||||
error_msg = f"Error: '{mode}' mode requires a Qwen3VL model. Please connect the Options node and select a Qwen3VL model (Qwen3VL-4B or Qwen3VL-8B) to use vision capabilities."
|
||||
# Auto-discover available models from Ollama
|
||||
from .ollama_wrapper import discover_ollama_models
|
||||
discovered, status = discover_ollama_models(_preferences_cache)
|
||||
if discovered:
|
||||
model_to_use = discovered[0]
|
||||
print_pg(f"Auto-selected Ollama model: {model_to_use}")
|
||||
else:
|
||||
error_msg = (f"Error: No Ollama model available. {status}\n"
|
||||
"Pull a model first (e.g. `ollama pull llama3.1`).")
|
||||
print_pg(error_msg, RED)
|
||||
return (error_msg,)
|
||||
|
||||
print_pg("Backend : Ollama")
|
||||
|
||||
else:
|
||||
# Enhance Prompt mode - use regular model selection logic (exclude Qwen3VL models)
|
||||
if options and "model" in options and is_model_local(options["model"]):
|
||||
# If user explicitly selected a Qwen3VL model but in Enhance mode, use first non-VL model instead
|
||||
if "qwen3vl" in options["model"].lower():
|
||||
model_to_use = self.find_non_vl_model(available_models)
|
||||
if model_to_use:
|
||||
print_pg(f"Warning: Qwen3VL model '{options['model']}' selected but 'Enhance Prompt' mode is active. Ignoring model selection and using {model_to_use} instead.")
|
||||
else:
|
||||
error_msg = "Error: Only Qwen3VL models available but 'Enhance Prompt' mode is active. Please add a .gguf model or use Generator Options to add a non-vision model."
|
||||
# ── llama.cpp model selection ──
|
||||
print_pg("Backend : llama.cpp")
|
||||
available_models = get_local_models()
|
||||
|
||||
if use_vision_model:
|
||||
# Check if the selected model supports vision (has mmproj)
|
||||
if options and "model" in options and has_vision_support(options["model"]) and is_model_local(options["model"]):
|
||||
model_to_use = options["model"]
|
||||
elif options and "model" in options and is_model_local(options["model"]):
|
||||
# Selected model doesn't support vision
|
||||
print_pg(f"Warning: Model '{options['model']}' has no mmproj (no vision support) but '{mode}' mode is active.\nIgnoring model selection and searching for a vision-capable model.")
|
||||
model_to_use = self.find_vision_model(available_models)
|
||||
if model_to_use is None:
|
||||
error_msg = f"Error: '{mode}' mode requires a vision model (one with an mmproj file). Please download a vision-capable model via the Options node."
|
||||
print_pg(error_msg, RED)
|
||||
return (error_msg,)
|
||||
else:
|
||||
model_to_use = options["model"]
|
||||
# Try to find a vision model automatically
|
||||
model_to_use = self.find_vision_model(available_models)
|
||||
if model_to_use is None:
|
||||
error_msg = f"Error: '{mode}' mode requires a vision model (one with an mmproj file). Please download a vision-capable model via the Options node."
|
||||
print_pg(error_msg, RED)
|
||||
return (error_msg,)
|
||||
else:
|
||||
if not available_models:
|
||||
error_msg = "Error: No models found in models/ folder. Please add a .gguf model or use Generator Options node to download one."
|
||||
print_pg(error_msg, RED)
|
||||
return (error_msg,)
|
||||
# Find smallest non-VL model
|
||||
model_to_use = self.find_non_vl_model(available_models)
|
||||
if not model_to_use:
|
||||
error_msg = "Error: Only Qwen3VL models available but 'Enhance Prompt' mode is active. Please add a non-vision model or switch to 'Describe Image' mode."
|
||||
print_pg(error_msg, RED)
|
||||
return (error_msg,)
|
||||
# Enhance Prompt mode - any model works, prefer text-only for efficiency
|
||||
if options and "model" in options and is_model_local(options["model"]):
|
||||
model_to_use = options["model"]
|
||||
else:
|
||||
if not available_models:
|
||||
error_msg = "Error: No models found in models/ folder. Please add a .gguf model or use Generator Options node to download one."
|
||||
print_pg(error_msg, RED)
|
||||
return (error_msg,)
|
||||
model_to_use = self.find_text_model(available_models)
|
||||
if not model_to_use:
|
||||
error_msg = "Error: No suitable model found. Please add a .gguf model or use the Generator Options node to download one."
|
||||
print_pg(error_msg, RED)
|
||||
return (error_msg,)
|
||||
|
||||
# let's make sure thinking is disabled for non-thinking versions of Qwen3VL
|
||||
if enable_thinking and "qwen3vl" in model_to_use.lower() and "thinking" not in model_to_use.lower():
|
||||
print_pg("Warning: Thinking disabled - model does not support it.")
|
||||
enable_thinking = False
|
||||
# Thinking mode is only meaningful if the model explicitly supports it
|
||||
# (no longer tied to Qwen3VL naming — generic check)
|
||||
# Users can always enable thinking; the model will simply ignore it if unsupported.
|
||||
|
||||
print_pg(f"Vision mode : {'ON' if use_vision_model else 'OFF'}")
|
||||
print_pg(f"Thinking mode : {'ON' if enable_thinking else 'OFF'}")
|
||||
@@ -754,14 +766,15 @@ class PromptGenerator:
|
||||
return (error_msg,)
|
||||
|
||||
# If the current model is not the one we want, or server is not running, restart
|
||||
# Also restart if context_size has changed
|
||||
# Also restart if context_size has changed (llama.cpp only)
|
||||
context_size = options.get("context_size", 4096) if options else 4096
|
||||
if _current_model != model_to_use or _current_context_size != context_size or not self.is_server_alive():
|
||||
self.stop_server()
|
||||
# Get context_size from options or use default
|
||||
success, error_msg = self.start_server(model_to_use, context_size, use_vision_model)
|
||||
if not success:
|
||||
return (error_msg,)
|
||||
if not use_ollama:
|
||||
if _current_model != model_to_use or _current_context_size != context_size or not self.is_server_alive():
|
||||
self.stop_server()
|
||||
# Get context_size from options or use default
|
||||
success, error_msg = self.start_server(model_to_use, context_size, use_vision_model)
|
||||
if not success:
|
||||
return (error_msg,)
|
||||
|
||||
# Build the endpoint URL
|
||||
full_url = f"http://localhost:{self.SERVER_PORT}/v1/chat/completions"
|
||||
@@ -795,9 +808,9 @@ class PromptGenerator:
|
||||
else:
|
||||
user_content = prompt
|
||||
|
||||
# === TOKENIZATION (only for non-cached requests) ===
|
||||
# === TOKENIZATION (only for non-cached requests, llama.cpp only) ===
|
||||
cached_token_counts = None
|
||||
if show_everything_in_console:
|
||||
if show_everything_in_console and not use_ollama:
|
||||
cached_token_counts = self._get_token_counts_parallel(system_prompt, user_content)
|
||||
|
||||
# If in vision mode, encode images for the request
|
||||
@@ -830,7 +843,7 @@ class PromptGenerator:
|
||||
img_base64 = base64.b64encode(buffered.getvalue()).decode('utf-8')
|
||||
image_contents.append({"type": "image_url", "image_url": {"url": f"data:image/png;base64,{img_base64}"}})
|
||||
|
||||
# Qwen3VL format for vision messages: all images, then text
|
||||
# Vision format: all images first, then text
|
||||
user_message = {
|
||||
"role": "user",
|
||||
"content": image_contents + [{"type": "text", "text": user_content}]
|
||||
@@ -838,6 +851,29 @@ class PromptGenerator:
|
||||
else:
|
||||
user_message = {"role": "user", "content": user_content}
|
||||
|
||||
# ================================================================
|
||||
# Ollama generation path
|
||||
# ================================================================
|
||||
if use_ollama:
|
||||
return self._generate_via_ollama(
|
||||
model_to_use=model_to_use,
|
||||
system_prompt=system_prompt,
|
||||
user_message=user_message,
|
||||
user_content=user_content,
|
||||
seed=seed,
|
||||
enable_thinking=enable_thinking,
|
||||
use_model_default_sampling=use_model_default_sampling,
|
||||
show_everything_in_console=show_everything_in_console,
|
||||
stop_server_after=stop_server_after,
|
||||
options=options,
|
||||
images=images,
|
||||
context_size=context_size,
|
||||
prompt=prompt,
|
||||
)
|
||||
|
||||
# ================================================================
|
||||
# llama.cpp generation path (existing)
|
||||
# ================================================================
|
||||
payload = {
|
||||
"messages": [
|
||||
{"role": "system", "content": system_prompt},
|
||||
@@ -1021,6 +1057,174 @@ class PromptGenerator:
|
||||
error_msg += "\nConsider increasing context size using Generator Options node."
|
||||
return (error_msg,)
|
||||
|
||||
# ================================================================
|
||||
# Ollama generation helper
|
||||
# ================================================================
|
||||
def _generate_via_ollama(self, model_to_use, system_prompt, user_message,
|
||||
user_content, seed, enable_thinking,
|
||||
use_model_default_sampling, show_everything_in_console,
|
||||
stop_server_after, options, images, context_size, prompt):
|
||||
"""Generate text using Ollama's OpenAI-compatible endpoint with streaming."""
|
||||
|
||||
messages = [
|
||||
{"role": "system", "content": system_prompt},
|
||||
user_message,
|
||||
]
|
||||
|
||||
# Sampling parameters
|
||||
temperature = 0.8
|
||||
top_k = 40
|
||||
top_p = 0.95
|
||||
min_p = 0.05
|
||||
repeat_penalty = 1.0
|
||||
if options and not use_model_default_sampling:
|
||||
temperature = options.get("temperature", temperature)
|
||||
top_k = options.get("top_k", top_k)
|
||||
top_p = options.get("top_p", top_p)
|
||||
min_p = options.get("min_p", min_p)
|
||||
repeat_penalty = options.get("repeat_penalty", repeat_penalty)
|
||||
|
||||
if show_everything_in_console:
|
||||
print_pg(f"{'=' * 60}", GREEN)
|
||||
print_pg(" DETAILED INFORMATION ENABLED (Ollama)", GREEN)
|
||||
print_pg(f"{'=' * 60}", GREEN)
|
||||
if not use_model_default_sampling:
|
||||
print_pg("------ GENERATION PARAMETERS ------", GREEN)
|
||||
for name, val in [("seed", seed), ("temperature", temperature),
|
||||
("top_k", top_k), ("top_p", top_p),
|
||||
("min_p", min_p), ("repeat_penalty", repeat_penalty)]:
|
||||
print_pg(f"{name} = {val}", GREEN)
|
||||
else:
|
||||
print_pg("Using model default sampling parameters", GREEN)
|
||||
print_pg("\n--------- SYSTEM PROMPT ---------", GREEN)
|
||||
print_pg(f"{system_prompt}", GREEN)
|
||||
print_pg("\n--------- USER PROMPT ---------", GREEN)
|
||||
print_pg(f"{user_content}", GREEN)
|
||||
|
||||
# Call Ollama (streaming)
|
||||
result = ollama_generate_chat(
|
||||
user_config=_preferences_cache,
|
||||
model_name=model_to_use,
|
||||
messages=messages,
|
||||
temperature=temperature,
|
||||
top_k=top_k,
|
||||
top_p=top_p,
|
||||
min_p=min_p,
|
||||
repeat_penalty=repeat_penalty,
|
||||
seed=seed,
|
||||
stream=True,
|
||||
timeout=120,
|
||||
use_model_defaults=use_model_default_sampling,
|
||||
enable_thinking=enable_thinking,
|
||||
)
|
||||
|
||||
# result is (response_obj, error_msg) for streaming
|
||||
if result[1] is not None:
|
||||
print_pg(f"Ollama error: {result[1]}", RED)
|
||||
return (result[1],)
|
||||
|
||||
response = result[0]
|
||||
|
||||
try:
|
||||
full_response = ""
|
||||
thinking_content = ""
|
||||
usage_stats = None
|
||||
first_thinking = True
|
||||
first_content = True
|
||||
|
||||
for line in response.iter_lines():
|
||||
# Check for user interrupt
|
||||
try:
|
||||
comfy.model_management.throw_exception_if_processing_interrupted()
|
||||
except Exception:
|
||||
try:
|
||||
response.close()
|
||||
except Exception:
|
||||
pass
|
||||
raise
|
||||
|
||||
if line:
|
||||
line = line.decode('utf-8')
|
||||
if line.startswith('data: '):
|
||||
data = line[6:]
|
||||
if data == '[DONE]':
|
||||
break
|
||||
try:
|
||||
chunk = json.loads(data)
|
||||
|
||||
if "usage" in chunk:
|
||||
usage_stats = chunk["usage"]
|
||||
|
||||
if 'choices' in chunk and len(chunk['choices']) > 0:
|
||||
delta = chunk['choices'][0].get('delta', {})
|
||||
if 'reasoning_content' in delta:
|
||||
reasoning_delta = delta['reasoning_content']
|
||||
if reasoning_delta is not None:
|
||||
thinking_content += str(reasoning_delta)
|
||||
if show_everything_in_console:
|
||||
if first_thinking:
|
||||
print_pg("\n--------- THINKING ---------", GREEN)
|
||||
first_thinking = False
|
||||
print(f"{GREEN}{str(reasoning_delta)}{RESET}", end='', flush=True)
|
||||
if 'content' in delta:
|
||||
content_delta = delta['content']
|
||||
if content_delta is not None:
|
||||
full_response += str(content_delta)
|
||||
if show_everything_in_console:
|
||||
if first_content:
|
||||
print_pg("\n\n--------- FINAL ANSWER ---------", CYAN)
|
||||
first_content = False
|
||||
print(f"{CYAN}{str(content_delta)}{RESET}", end='', flush=True)
|
||||
except json.JSONDecodeError:
|
||||
continue
|
||||
|
||||
if show_everything_in_console:
|
||||
print('') # Final newline
|
||||
|
||||
if not show_everything_in_console:
|
||||
print_pg("Prompt generation complete (Ollama).")
|
||||
|
||||
if show_everything_in_console and usage_stats:
|
||||
self.print_token_stats(usage_stats, None, thinking_content, full_response, images)
|
||||
else:
|
||||
print_pg_footer()
|
||||
|
||||
if not full_response:
|
||||
print_pg("Warning: Empty response from Ollama")
|
||||
full_response = prompt
|
||||
|
||||
# "stop_server_after" → unload model from Ollama memory immediately
|
||||
# (This overrides the keep_alive duration for this request)
|
||||
if stop_server_after:
|
||||
print_pg("Unloading model from Ollama memory...")
|
||||
ok, msg = ollama_unload_model(_preferences_cache, model_to_use)
|
||||
print_pg(msg, GREEN if ok else RED)
|
||||
else:
|
||||
keep_alive = _preferences_cache.get("ollama_keep_alive", "5m")
|
||||
if keep_alive and str(keep_alive) != "0":
|
||||
print_pg(f"Model will stay loaded for: {keep_alive}")
|
||||
|
||||
return (full_response, thinking_content)
|
||||
|
||||
except comfy.model_management.InterruptProcessingException:
|
||||
try:
|
||||
response.close()
|
||||
except Exception:
|
||||
pass
|
||||
raise
|
||||
except requests.exceptions.ConnectionError:
|
||||
error_msg = "Error: Lost connection to Ollama during generation."
|
||||
print_pg(error_msg, RED)
|
||||
return (error_msg,)
|
||||
except requests.exceptions.Timeout:
|
||||
error_msg = "Error: Ollama request timed out (>120s)"
|
||||
print_pg(error_msg, RED)
|
||||
return (error_msg,)
|
||||
except Exception as e:
|
||||
error_msg = f"Error (Ollama): {e}"
|
||||
print_pg(error_msg, RED)
|
||||
return (error_msg,)
|
||||
|
||||
def print_token_stats(self, usage_stats, cached_token_counts, thinking_content, full_response, images):
|
||||
"""Print token statistics using pre-cached counts"""
|
||||
print_pg(f"{'=' * 60}", GREEN)
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
from .model_manager import get_all_models, is_model_local, download_model, get_mmproj_for_model, get_mmproj_path
|
||||
from .model_manager import get_all_models, is_model_local, download_model, get_mmproj_for_model, get_mmproj_path, _preferences_cache
|
||||
from .ollama_wrapper import discover_ollama_models, is_ollama_available
|
||||
import time
|
||||
|
||||
# Global timestamp to track when models were last updated
|
||||
@@ -14,17 +15,25 @@ class PromptGenOptions:
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
available_models = get_all_models()
|
||||
backend = _preferences_cache.get("llm_backend", "llama.cpp")
|
||||
|
||||
# If no models found, show a placeholder
|
||||
if not available_models:
|
||||
available_models = ["No models found - check HuggingFace"]
|
||||
if backend == "ollama":
|
||||
# Discover models from Ollama
|
||||
ollama_models, _status = discover_ollama_models(_preferences_cache)
|
||||
if not ollama_models:
|
||||
available_models = ["No Ollama models found - run 'ollama pull <model>'"]
|
||||
else:
|
||||
available_models = ollama_models
|
||||
else:
|
||||
available_models = get_all_models()
|
||||
if not available_models:
|
||||
available_models = ["No models found - check HuggingFace"]
|
||||
|
||||
return {
|
||||
"optional": {
|
||||
"model": (available_models, {
|
||||
"default": available_models[0] if available_models else "",
|
||||
"tooltip": "Select model to use (local models listed first, then HuggingFace models)"
|
||||
"tooltip": "Select model to use (local models listed first, then HuggingFace models)\nDownload sizes: UD-Q4_K_XL ~6GB | Q8_0 ~9.5GB | UD-Q8_K_XL ~13GB"
|
||||
}),
|
||||
"image2": ("IMAGE", {
|
||||
"tooltip": "Connect an image (required for 'Analyze Image' and 'Analyze Image with Prompt' modes)"
|
||||
@@ -117,16 +126,23 @@ class PromptGenOptions:
|
||||
options = {}
|
||||
|
||||
# Handle model selection and download if needed
|
||||
if model and model != "No models found - check HuggingFace":
|
||||
backend = _preferences_cache.get("llm_backend", "llama.cpp")
|
||||
|
||||
if backend == "ollama":
|
||||
# Ollama mode — no download needed, just validate the selection
|
||||
if model and model != "No Ollama models found - run 'ollama pull <model>'":
|
||||
options["model"] = model
|
||||
options["llm_backend"] = "ollama"
|
||||
elif model and model != "No models found - check HuggingFace":
|
||||
# Check if model is local
|
||||
model_exists = is_model_local(model)
|
||||
|
||||
# For VL models, also check if mmproj exists
|
||||
# For vision models, also check if mmproj exists
|
||||
needs_download = not model_exists
|
||||
if model_exists:
|
||||
mmproj_name = get_mmproj_for_model(model)
|
||||
if mmproj_name:
|
||||
# This is a VL model, check if mmproj is present
|
||||
# This is a vision model, check if mmproj is present
|
||||
mmproj_path = get_mmproj_path(model)
|
||||
if not mmproj_path:
|
||||
print(f"[Prompt Generator Options] Vision model found but mmproj missing, downloading: {mmproj_name}")
|
||||
|
||||
+17
-5
@@ -13,7 +13,7 @@ class PromptManager:
|
||||
|
||||
all_prompts = set()
|
||||
for category_prompts in prompts_data.values():
|
||||
all_prompts.update(category_prompts.keys())
|
||||
all_prompts.update(k for k in category_prompts.keys() if k != "__meta__")
|
||||
|
||||
all_prompts.add("")
|
||||
all_prompts_list = sorted(list(all_prompts))
|
||||
@@ -24,7 +24,7 @@ class PromptManager:
|
||||
first_prompt = ""
|
||||
first_prompt_text = ""
|
||||
if prompts_data and first_category in prompts_data and prompts_data[first_category]:
|
||||
first_category_prompts = list(prompts_data[first_category].keys())
|
||||
first_category_prompts = [k for k in prompts_data[first_category].keys() if k != "__meta__"]
|
||||
first_prompt = sorted(first_category_prompts, key=str.lower)[0] if first_category_prompts else ""
|
||||
if first_prompt:
|
||||
first_prompt_text = prompts_data[first_category][first_prompt].get("prompt", "")
|
||||
@@ -94,10 +94,19 @@ class PromptManager:
|
||||
|
||||
@staticmethod
|
||||
def sort_prompts_data(data):
|
||||
"""Sort categories and prompts alphabetically (case-insensitive)"""
|
||||
"""Sort categories and prompts alphabetically (case-insensitive), preserving __meta__"""
|
||||
sorted_data = {}
|
||||
for category in sorted(data.keys(), key=str.lower):
|
||||
sorted_data[category] = dict(sorted(data[category].items(), key=lambda item: item[0].lower()))
|
||||
cat_data = data[category]
|
||||
meta = cat_data.get("__meta__")
|
||||
sorted_prompts = dict(sorted(
|
||||
((k, v) for k, v in cat_data.items() if k != "__meta__"),
|
||||
key=lambda item: item[0].lower()
|
||||
))
|
||||
if meta is not None:
|
||||
sorted_prompts["__meta__"] = meta
|
||||
sorted_data[category] = sorted_prompts
|
||||
return sorted_data
|
||||
return sorted_data
|
||||
|
||||
@classmethod
|
||||
@@ -203,7 +212,7 @@ async def save_prompt(request):
|
||||
print(f"[PromptManager] Removing old casing '{old_name}' before saving as '{name}'")
|
||||
del prompts[category][old_name]
|
||||
|
||||
# Save prompt in dict, preserving any existing lora data, trigger words, and thumbnail from PromptManagerAdvanced
|
||||
# Save prompt in dict, preserving any existing lora data, trigger words, thumbnail, and nsfw from PromptManagerAdvanced
|
||||
existing_data = prompts[category].get(name, {})
|
||||
prompts[category][name] = {
|
||||
"prompt": text,
|
||||
@@ -212,6 +221,9 @@ async def save_prompt(request):
|
||||
"trigger_words": existing_data.get("trigger_words", []),
|
||||
"thumbnail": existing_data.get("thumbnail")
|
||||
}
|
||||
# Preserve nsfw flag if it was set
|
||||
if existing_data.get("nsfw"):
|
||||
prompts[category][name]["nsfw"] = existing_data["nsfw"]
|
||||
PromptManager.save_prompts(prompts)
|
||||
|
||||
return server.web.json_response({"success": True, "prompts": prompts})
|
||||
|
||||
+106
-5
@@ -218,7 +218,7 @@ class PromptManagerAdvanced:
|
||||
|
||||
all_prompts = set()
|
||||
for category_prompts in prompts_data.values():
|
||||
all_prompts.update(category_prompts.keys())
|
||||
all_prompts.update(k for k in category_prompts.keys() if k != "__meta__")
|
||||
|
||||
all_prompts.add("")
|
||||
all_prompts_list = sorted(list(all_prompts))
|
||||
@@ -229,7 +229,7 @@ class PromptManagerAdvanced:
|
||||
first_prompt = ""
|
||||
first_prompt_text = ""
|
||||
if prompts_data and first_category in prompts_data and prompts_data[first_category]:
|
||||
first_category_prompts = list(prompts_data[first_category].keys())
|
||||
first_category_prompts = [k for k in prompts_data[first_category].keys() if k != "__meta__"]
|
||||
first_prompt = sorted(first_category_prompts, key=str.lower)[0] if first_category_prompts else ""
|
||||
if first_prompt:
|
||||
first_prompt_text = prompts_data[first_category][first_prompt].get("prompt", "")
|
||||
@@ -344,10 +344,19 @@ class PromptManagerAdvanced:
|
||||
|
||||
@staticmethod
|
||||
def sort_prompts_data(data):
|
||||
"""Sort categories and prompts alphabetically (case-insensitive)"""
|
||||
"""Sort categories and prompts alphabetically (case-insensitive), preserving __meta__"""
|
||||
sorted_data = {}
|
||||
for category in sorted(data.keys(), key=str.lower):
|
||||
sorted_data[category] = dict(sorted(data[category].items(), key=lambda item: item[0].lower()))
|
||||
cat_data = data[category]
|
||||
# Preserve __meta__ key (not a prompt), sort the rest
|
||||
meta = cat_data.get("__meta__")
|
||||
sorted_prompts = dict(sorted(
|
||||
((k, v) for k, v in cat_data.items() if k != "__meta__"),
|
||||
key=lambda item: item[0].lower()
|
||||
))
|
||||
if meta is not None:
|
||||
sorted_prompts["__meta__"] = meta
|
||||
sorted_data[category] = sorted_prompts
|
||||
return sorted_data
|
||||
|
||||
@classmethod
|
||||
@@ -1020,7 +1029,11 @@ async def save_category_advanced(request):
|
||||
"error": f"Category already exists as '{existing_categories_lower[category_name.lower()]}'"
|
||||
})
|
||||
|
||||
prompts[category_name] = {}
|
||||
nsfw = data.get("nsfw", False)
|
||||
cat_data = {}
|
||||
if nsfw:
|
||||
cat_data["__meta__"] = {"nsfw": True}
|
||||
prompts[category_name] = cat_data
|
||||
PromptManagerAdvanced.save_prompts(prompts)
|
||||
|
||||
return server.web.json_response({"success": True, "prompts": prompts})
|
||||
@@ -1029,6 +1042,42 @@ async def save_category_advanced(request):
|
||||
return server.web.json_response({"success": False, "error": str(e)}, status=500)
|
||||
|
||||
|
||||
@server.PromptServer.instance.routes.post("/prompt-manager-advanced/rename-category")
|
||||
async def rename_category_advanced(request):
|
||||
"""API endpoint to rename a category"""
|
||||
try:
|
||||
data = await request.json()
|
||||
old_category = data.get("old_category", "").strip()
|
||||
new_category = data.get("new_category", "").strip()
|
||||
|
||||
if not old_category or not new_category:
|
||||
return server.web.json_response({"success": False, "error": "Both old and new category names are required"})
|
||||
|
||||
prompts = PromptManagerAdvanced.load_prompts()
|
||||
|
||||
# Check if old category exists
|
||||
if old_category not in prompts:
|
||||
return server.web.json_response({"success": False, "error": f"Category '{old_category}' not found"})
|
||||
|
||||
# Case-insensitive check for new category name conflicts (excluding the old name)
|
||||
existing_categories_lower = {k.lower(): k for k in prompts.keys() if k.lower() != old_category.lower()}
|
||||
if new_category.lower() in existing_categories_lower:
|
||||
return server.web.json_response({
|
||||
"success": False,
|
||||
"error": f"Category already exists as '{existing_categories_lower[new_category.lower()]}'"
|
||||
})
|
||||
|
||||
# Rename by copying data and deleting old
|
||||
prompts[new_category] = prompts[old_category]
|
||||
del prompts[old_category]
|
||||
PromptManagerAdvanced.save_prompts(prompts)
|
||||
|
||||
return server.web.json_response({"success": True, "prompts": prompts, "new_category": new_category})
|
||||
except Exception as e:
|
||||
print(f"[PromptManagerAdvanced] Error in rename_category API: {e}")
|
||||
return server.web.json_response({"success": False, "error": str(e)}, status=500)
|
||||
|
||||
|
||||
@server.PromptServer.instance.routes.post("/prompt-manager-advanced/save-prompt")
|
||||
async def save_prompt_advanced(request):
|
||||
"""API endpoint to save a prompt with lora configurations"""
|
||||
@@ -1112,6 +1161,13 @@ async def save_prompt_advanced(request):
|
||||
if thumbnail:
|
||||
prompt_data["thumbnail"] = thumbnail
|
||||
|
||||
# Preserve or set NSFW flag
|
||||
nsfw = data.get("nsfw")
|
||||
if nsfw is not None:
|
||||
prompt_data["nsfw"] = bool(nsfw)
|
||||
elif existing_prompt.get("nsfw"):
|
||||
prompt_data["nsfw"] = existing_prompt["nsfw"]
|
||||
|
||||
prompts[category][name] = prompt_data
|
||||
PromptManagerAdvanced.save_prompts(prompts)
|
||||
|
||||
@@ -1273,6 +1329,11 @@ async def import_prompts_advanced(request):
|
||||
if not isinstance(prompt_data, dict):
|
||||
continue
|
||||
|
||||
# Handle __meta__ key (category metadata, not a prompt)
|
||||
if prompt_name == "__meta__" and isinstance(prompt_data, dict):
|
||||
prompts[category]["__meta__"] = prompt_data
|
||||
continue
|
||||
|
||||
# Normalize the prompt data structure (include thumbnail if present)
|
||||
normalized = {
|
||||
"prompt": prompt_data.get("prompt", ""),
|
||||
@@ -1285,6 +1346,10 @@ async def import_prompts_advanced(request):
|
||||
if "thumbnail" in prompt_data and prompt_data["thumbnail"]:
|
||||
normalized["thumbnail"] = prompt_data["thumbnail"]
|
||||
|
||||
# Preserve NSFW flag if present
|
||||
if prompt_data.get("nsfw"):
|
||||
normalized["nsfw"] = prompt_data["nsfw"]
|
||||
|
||||
prompts[category][prompt_name] = normalized
|
||||
|
||||
PromptManagerAdvanced.save_prompts(prompts)
|
||||
@@ -1324,3 +1389,39 @@ async def save_thumbnail(request):
|
||||
except Exception as e:
|
||||
print(f"[PromptManagerAdvanced] 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-advanced/toggle-nsfw")
|
||||
async def toggle_nsfw_advanced(request):
|
||||
"""API endpoint to toggle NSFW flag on a category or prompt"""
|
||||
try:
|
||||
data = await request.json()
|
||||
toggle_type = data.get("type", "").strip() # "category" or "prompt"
|
||||
category = data.get("category", "").strip()
|
||||
name = data.get("name", "").strip()
|
||||
|
||||
if not category:
|
||||
return server.web.json_response({"success": False, "error": "Category is required"})
|
||||
|
||||
prompts = PromptManagerAdvanced.load_prompts()
|
||||
|
||||
if category not in prompts:
|
||||
return server.web.json_response({"success": False, "error": "Category not found"})
|
||||
|
||||
if toggle_type == "category":
|
||||
meta = prompts[category].get("__meta__", {})
|
||||
meta["nsfw"] = not meta.get("nsfw", False)
|
||||
prompts[category]["__meta__"] = meta
|
||||
elif toggle_type == "prompt":
|
||||
if not name or name not in prompts[category]:
|
||||
return server.web.json_response({"success": False, "error": "Prompt not found"})
|
||||
prompts[category][name]["nsfw"] = not prompts[category][name].get("nsfw", False)
|
||||
else:
|
||||
return server.web.json_response({"success": False, "error": "Invalid type, must be 'category' or 'prompt'"})
|
||||
|
||||
PromptManagerAdvanced.save_prompts(prompts)
|
||||
|
||||
return server.web.json_response({"success": True, "prompts": prompts})
|
||||
except Exception as e:
|
||||
print(f"[PromptManagerAdvanced] Error in toggle_nsfw API: {e}")
|
||||
return server.web.json_response({"success": False, "error": str(e)}, status=500)
|
||||
|
||||
+2
-2
@@ -1,7 +1,7 @@
|
||||
[project]
|
||||
name = "prompt-manager"
|
||||
description = "A comprehensive prompt management system for ComfyUI that saves complete workflow recipes including prompts, LoRAs, and their settings. Features AI-powered prompt generation, prompt extraction from ComfyUI/A1111 images and videos, and Dual LoRA Stack support for Wan workflows."
|
||||
version = "1.15.0"
|
||||
version = "1.17.5"
|
||||
license = {file = "LICENSE"}
|
||||
# classifiers = [
|
||||
# # For OS-independent nodes (works on all operating systems)
|
||||
@@ -20,7 +20,7 @@ license = {file = "LICENSE"}
|
||||
# "Environment :: GPU :: Apple Metal", # Apple Metal support
|
||||
# ]
|
||||
|
||||
dependencies = ["requests>=2.31.0", "huggingface_hub>=0.20.0", "psutil>=5.9.0", "tqdm>=4.66.0", "Pillow>=10.0.0", "torch>=2.0.0", "numpy>=1.24.0", "colorama"]
|
||||
dependencies = ["requests", "huggingface_hub", "psutil", "tqdm", "Pillow", "torch", "numpy", "colorama"]
|
||||
|
||||
[project.urls]
|
||||
Repository = "https://github.com/FranckyB/ComfyUI-Prompt-Manager"
|
||||
|
||||
+1
-7
@@ -1,8 +1,2 @@
|
||||
requests>=2.31.0
|
||||
huggingface_hub>=0.20.0
|
||||
psutil>=5.9.0
|
||||
tqdm>=4.66.0
|
||||
Pillow>=10.0.0
|
||||
torch>=2.0.0
|
||||
numpy>=1.24.0
|
||||
huggingface_hub
|
||||
colorama
|
||||
@@ -417,15 +417,76 @@ class MonoToStereo:
|
||||
return ({"waveform": stereo_waveform, "sample_rate": sample_rate},)
|
||||
|
||||
|
||||
class GetVideoComponentsPlus:
|
||||
"""
|
||||
Extract video components (images, audio, fps) plus the filepath.
|
||||
Like ComfyUI's GetVideoComponents but also outputs the file path as a string,
|
||||
and automatically loads a matching .latent file if one exists.
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {
|
||||
"video": ("VIDEO", {"tooltip": "The video to extract components from."}),
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("IMAGE", "AUDIO", "FLOAT", "STRING", "LATENT")
|
||||
RETURN_NAMES = ("images", "audio", "fps", "filepath", "latent")
|
||||
FUNCTION = "get_components"
|
||||
CATEGORY = "Prompt Manager"
|
||||
DESCRIPTION = "Extract video frames, audio, fps, filepath, and matching latent file if found."
|
||||
|
||||
def get_components(self, video):
|
||||
# Get video components using the standard API
|
||||
components = video.get_components()
|
||||
images = components.images
|
||||
audio = components.audio
|
||||
fps = float(components.frame_rate)
|
||||
|
||||
# Try to get the file path from the video object
|
||||
video_path = ""
|
||||
try:
|
||||
source = video.get_stream_source()
|
||||
if isinstance(source, str):
|
||||
video_path = source
|
||||
except Exception as e:
|
||||
print(f"[GetVideoComponentsPlus] Could not get video path: {e}")
|
||||
|
||||
# Check for matching .latent file
|
||||
latent = None
|
||||
if video_path and os.path.exists(video_path):
|
||||
latent_path = os.path.splitext(video_path)[0] + '.latent'
|
||||
if os.path.exists(latent_path):
|
||||
try:
|
||||
# Load the latent file (same logic as LoadLatentFile)
|
||||
latent_data = safetensors.torch.load_file(latent_path, device="cpu")
|
||||
|
||||
# Handle version differences
|
||||
multiplier = 1.0
|
||||
if "latent_format_version_0" not in latent_data:
|
||||
multiplier = 1.0 / 0.18215
|
||||
|
||||
latent = {"samples": latent_data["latent_tensor"].float() * multiplier}
|
||||
print(f"[GetVideoComponentsPlus] Loaded matching latent: {latent_path}")
|
||||
except Exception as e:
|
||||
print(f"[GetVideoComponentsPlus] Could not load latent file: {e}")
|
||||
|
||||
return (images, audio, fps, video_path, latent)
|
||||
|
||||
|
||||
# Node registration
|
||||
NODE_CLASS_MAPPINGS = {
|
||||
"SaveVideoH26x": SaveVideoH26x,
|
||||
"LoadLatentFile": LoadLatentFile,
|
||||
"AudioMonoToStereo": MonoToStereo,
|
||||
"GetVideoComponentsPlus": GetVideoComponentsPlus,
|
||||
}
|
||||
|
||||
NODE_DISPLAY_NAME_MAPPINGS = {
|
||||
"SaveVideoH26x": "Save Video H264/H265",
|
||||
"LoadLatentFile": "Load Latent File",
|
||||
"AudioMonoToStereo": "Audio Mono to Stereo",
|
||||
"GetVideoComponentsPlus": "Get Video Components+",
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user