Compare commits

..
8 Commits
Author SHA1 Message Date
THE_BEAST\me e08d18c783 bump version to 1.12.7; add reset functionality for LoRA strengths and improve user experience with live adjustments 2026-01-13 15:23:17 -05:00
THE_BEAST\me 769d40f9f5 enhance LoRA management by tracking input changes and improving display of unavailable LoRAs 2026-01-13 14:15:01 -05:00
THE_BEAST\me eef07948ac enhance video frame extraction and caching mechanism in PromptExtractor 2026-01-13 00:31:49 -05:00
THE_BEAST\me bf847e9639 chore: update version to 1.12.6 and enhance caching behavior in prompt extractor and prompt manager advanced 2026-01-12 23:06:27 -05:00
THE_BEAST\me 39c8b5f3b8 enhance video frame caching functionality 2026-01-12 20:01:40 -05:00
THE_BEAST\me cf810ca921 Updated Readme 2026-01-12 18:51:33 -05:00
THE_BEAST\me 422607ec8d Refactor prompt extraction and enhance LoRA matching
- Removed unnecessary print statements from prompt_extractor.py to clean up logging.
- Simplified LoRA stack processing by directly using paths if available.
- Introduced fuzzy matching for LoRA names in prompt_manager_advanced.py to handle renamed LoRAs.
- Added a new test suite (test_fuzzy_match.py) to validate fuzzy matching logic with various scenarios.
2026-01-12 18:43:17 -05:00
THE_BEAST\me f9e26c8bbd Added Lora Stack Input to Extractor.
Enhance LoRA and Prompt extraction logic, added tests
2026-01-12 17:15:22 -05:00
9 changed files with 1522 additions and 472 deletions
+16
View File
@@ -242,6 +242,22 @@ Preference settings can be found in ComfyUI Settings → Prompt Manager
## Changelog
### version 1.12.7
- Quality of life improvements and added option to change the Strenght of any Lora in Manager, so we can tweak Extracted Workflows Live.
### version 1.12.6
- Tweak to caching behavior for prompt extractor and prompt manager advanced
### version 1.12.5
- Some dependencies to FFMpeg were still present, remove them and added a frame_position value, so we can specify what frame to get from video.
### version 1.12.0
- Prompt Extractor: Added Lora inputs, so it can be used as a passthrough, with a None Choice at top, to easily deactivate it.
- Prompt Extractor: Improved logic for determining Positive prompts in Worfklow.
- Prompt Extractor: Improved logic for finding High and Low Lora Stacks
- Prompt Manager Advanced: Added Fuzzy Logic to find Loras that might have been renamed
- Prompt Manager Advanced: Fixed issue of Lora buttons getting cleared when changing tab.
### Version 1.11.5
- Slight adjustement to extractor node, gets metadata in a method more consistent with ComfyUI, removing need for ffmpeg for videos.
+1 -1
View File
@@ -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.11.5"
__version__ = "1.12.7"
__author__ = "François Beaudry"
__license__ = "MIT"
+104 -7
View File
@@ -317,9 +317,60 @@ async function cacheFileMetadata(filename, metadata) {
}
}
/**
* Send video frame to Python backend for caching
*/
async function cacheVideoFrame(filename, frameData, framePosition) {
try {
const response = await api.fetchApi("/prompt-extractor/cache-video-frame", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ filename, frame: frameData, frame_position: framePosition })
});
if (response.ok) {
console.log(`[PromptExtractor] Cached video frame at position ${framePosition.toFixed(2)} for: ${filename}`);
} else {
console.error("[PromptExtractor] Failed to cache video frame:", response.status);
}
} catch (error) {
console.error("[PromptExtractor] Error caching video frame:", error);
}
}
app.registerExtension({
name: "PromptExtractor",
async setup() {
// Listen for frame extraction requests from Python backend
api.addEventListener("prompt-extractor-extract-frame", async (event) => {
const { filename, frame_position } = event.detail;
console.log(`[PromptExtractor] Received extraction request for ${filename} at position ${frame_position}`);
// Find the node with this filename
if (app.graph && app.graph._nodes) {
for (const node of app.graph._nodes) {
if (node.type === "PromptExtractor") {
const imageWidget = node.widgets?.find(w => w.name === "image");
const frameWidget = node.widgets?.find(w => w.name === "frame_position");
if (imageWidget && imageWidget.value === filename) {
// Update frame position if provided
if (frameWidget && frame_position !== undefined) {
frameWidget.value = frame_position;
}
// Trigger extraction
await loadAndDisplayImage(node, filename);
console.log(`[PromptExtractor] Extracted and cached frame for ${filename}`);
break;
}
}
}
}
});
},
async beforeRegisterNodeDef(nodeType, nodeData, app) {
if (nodeData.name === "PromptExtractor") {
const onNodeCreated = nodeType.prototype.onNodeCreated;
@@ -349,6 +400,42 @@ app.registerExtension({
};
}
// Find the frame_position widget (slider)
const framePositionWidget = this.widgets?.find(w => w.name === "frame_position");
if (framePositionWidget) {
// Store original callback
const originalFrameCallback = framePositionWidget.callback;
// Debounce timer to prevent excessive frame extraction during slider drag
let frameUpdateTimer = null;
// Override callback to reload video frame when position changes
framePositionWidget.callback = function(value) {
if (originalFrameCallback) {
originalFrameCallback.apply(this, arguments);
}
// Clear any pending frame update
if (frameUpdateTimer) {
clearTimeout(frameUpdateTimer);
}
// Debounce: only extract frame after user stops moving slider for 300ms
frameUpdateTimer = setTimeout(() => {
// If a video is currently loaded, reload it with new frame position
if (imageWidget && imageWidget.value) {
const filename = imageWidget.value;
const ext = filename.split('.').pop().toLowerCase();
const videoExtensions = ['mp4', 'webm', 'mov', 'avi'];
if (videoExtensions.includes(ext)) {
loadVideoFrame(node, filename);
}
}
}, 300);
};
}
// Hook into workflow restoration to load preview for restored values
const onConfigure = node.onConfigure;
node.onConfigure = function(info) {
@@ -524,8 +611,8 @@ async function loadAndDisplayImage(node, filename) {
const videoExtensions = ['mp4', 'webm', 'mov', 'avi'];
if (videoExtensions.includes(ext)) {
// It's a video - extract and display first frame
loadVideoFirstFrame(node, filename);
// It's a video - extract and display frame at specified position
loadVideoFrame(node, filename);
return;
}
@@ -624,10 +711,14 @@ async function loadJSONFile(node, filename) {
}
/**
* Load first frame from a video file and extract metadata
* Load frame from a video file at specified position and extract metadata
*/
async function loadVideoFirstFrame(node, filename) {
async function loadVideoFrame(node, filename) {
try {
// Get frame position from the widget (0.0 to 1.0)
const framePositionWidget = node.widgets?.find(w => w.name === "frame_position");
const framePosition = framePositionWidget ? framePositionWidget.value : 0.0;
// Fetch the video file to extract metadata
const videoBlob = await fetch(`/view?filename=${encodeURIComponent(filename)}&type=input`)
.then(res => res.blob());
@@ -646,8 +737,9 @@ async function loadVideoFirstFrame(node, filename) {
video.preload = 'metadata';
video.onloadedmetadata = () => {
// Seek to first frame
video.currentTime = 0;
// Calculate frame time based on position (0.0 = start, 1.0 = end)
const frameTime = framePosition * Math.max(0, video.duration - 0.1);
video.currentTime = frameTime;
};
video.onseeked = () => {
@@ -663,9 +755,14 @@ async function loadVideoFirstFrame(node, filename) {
// Convert canvas to image
const img = new Image();
img.onload = () => {
// Display the frame
node.imgs = [img];
node.imageIndex = 0;
// Cache frame as base64 for Python backend
const frameData = canvas.toDataURL('image/png');
cacheVideoFrame(filename, frameData, framePosition);
// Resize node to fit image
const targetWidth = Math.max(node.size[0], 256);
const targetHeight = Math.max(node.size[1], img.naturalHeight * (targetWidth / img.naturalWidth) + 100);
@@ -676,7 +773,7 @@ async function loadVideoFirstFrame(node, filename) {
};
img.onerror = () => {
console.error(`[PromptExtractor] Failed to create image from video frame`);
console.error(`[PromptExtractor] Failed to create image from video frame at position ${framePosition.toFixed(2)}`);
showPlaceholder(node);
};
File diff suppressed because it is too large Load Diff
+314 -149
View File
@@ -22,6 +22,8 @@ except ImportError:
# Cache for file metadata (read by JavaScript, used by Python)
_file_metadata_cache = {}
# Cache for video frames extracted by JavaScript
_video_frames_cache = {}
# API endpoint to cache file metadata (sent from JavaScript)
@@ -38,9 +40,6 @@ async def cache_file_metadata(request):
if metadata:
_file_metadata_cache[filename] = metadata
print(f"[PromptExtractor] Cached file metadata for: {filename}")
else:
print(f"[PromptExtractor] No metadata found in file: {filename}")
return server.web.json_response({"success": True})
except Exception as e:
@@ -48,6 +47,29 @@ async def cache_file_metadata(request):
return server.web.json_response({"success": False, "error": str(e)}, status=500)
# API endpoint to cache video frame (sent from JavaScript)
@server.PromptServer.instance.routes.post("/prompt-extractor/cache-video-frame")
async def cache_video_frame(request):
"""API endpoint to cache a single video frame extracted by JavaScript"""
try:
data = await request.json()
filename = data.get('filename')
frame = data.get('frame') # Single base64 data URL
frame_position = data.get('frame_position', 0.0)
if not filename:
return server.web.json_response({"success": False, "error": "Missing filename"}, status=400)
if frame:
_video_frames_cache[filename] = frame
print(f"[PromptExtractor] Cached frame at position {frame_position:.2f} for: {filename}")
return server.web.json_response({"success": True})
except Exception as e:
print(f"[PromptExtractor] Error caching video frame: {e}")
return server.web.json_response({"success": False, "error": str(e)}, status=500)
# API endpoint to list files in input directory
@server.PromptServer.instance.routes.get("/prompt-extractor/list-files")
async def list_input_files(request):
@@ -180,12 +202,12 @@ def extract_metadata_from_jpeg(file_path):
try:
# Get just the filename from the path
filename = os.path.basename(file_path)
# Check if metadata was cached by JavaScript
if filename in _file_metadata_cache:
metadata = _file_metadata_cache[filename]
print(f"[PromptExtractor] Using cached JPEG/WebP metadata for: {filename}")
if isinstance(metadata, dict):
# Check for prompt/workflow structure
if 'prompt' in metadata and 'workflow' in metadata:
@@ -197,11 +219,11 @@ def extract_metadata_from_jpeg(file_path):
else:
print(f"[PromptExtractor] No cached metadata found for JPEG/WebP: {filename}")
print("[PromptExtractor] Note: Image metadata is read by JavaScript when file is selected")
# Fallback to PIL if no cached data (backwards compatibility)
if not IMAGE_SUPPORT:
return None, None
print(f"[PromptExtractor] Falling back to PIL for: {filename}")
with Image.open(file_path) as img:
# Try EXIF data
@@ -291,7 +313,6 @@ def extract_metadata_from_video(file_path):
# Check if metadata was cached by JavaScript
if filename in _file_metadata_cache:
metadata = _file_metadata_cache[filename]
print(f"[PromptExtractor] Using cached video metadata for: {filename}")
# Parse the cached metadata
if isinstance(metadata, dict):
@@ -338,64 +359,84 @@ def extract_metadata_from_video(file_path):
return None, None
def extract_first_frame_from_video(file_path):
"""Extract the first frame from a video file using ffmpeg"""
def base64_to_tensor(base64_data):
"""
Convert base64 data URL to ComfyUI tensor format.
"""
try:
import subprocess
import tempfile
import base64
import io
from PIL import Image
# Create a temporary file for the extracted frame
with tempfile.NamedTemporaryFile(suffix='.png', delete=False) as tmp_file:
tmp_path = tmp_file.name
# Remove data URL prefix (data:image/png;base64,)
if ',' in base64_data:
base64_data = base64_data.split(',', 1)[1]
# Use ffmpeg to extract the first frame
result = subprocess.run(
[
'ffmpeg', '-y', # Overwrite output file
'-i', file_path, # Input file
'-vf', 'select=eq(n\\,0)', # Select first frame
'-vframes', '1', # Only one frame
'-f', 'image2', # Output format
tmp_path # Output file
],
capture_output=True,
text=True,
timeout=30
)
# Decode base64 to bytes
img_bytes = base64.b64decode(base64_data)
if result.returncode == 0 and os.path.exists(tmp_path):
# Load the extracted frame as tensor
image_tensor = load_image_as_tensor(tmp_path)
# Load as PIL Image
img = Image.open(io.BytesIO(img_bytes))
# Clean up temporary file
try:
os.remove(tmp_path)
except:
pass
# Convert to RGB if needed
if img.mode != 'RGB':
img = img.convert('RGB')
if image_tensor is not None:
print("[PromptExtractor] Successfully extracted first frame from video")
return image_tensor
else:
print(f"[PromptExtractor] ffmpeg failed to extract frame: {result.stderr}")
# Clean up temporary file on failure
try:
os.remove(tmp_path)
except:
pass
# Convert to numpy array and normalize to 0-1
img_array = np.array(img).astype(np.float32) / 255.0
return None
except FileNotFoundError:
print("[PromptExtractor] ffmpeg not found - video frame extraction unavailable")
print("[PromptExtractor] Install ffmpeg to enable video frame extraction")
return None
# Convert to torch tensor with batch dimension (B, H, W, C)
img_tensor = torch.from_numpy(img_array).unsqueeze(0)
return img_tensor
except Exception as e:
print(f"[PromptExtractor] Error extracting video frame: {e}")
import traceback
traceback.print_exc()
print(f"[PromptExtractor] Error converting base64 to tensor: {e}")
return None
def get_cached_video_frame(filename, frame_position):
"""
Retrieve cached video frame extracted by JavaScript at the specified position.
frame_position: float from 0.0 to 1.0 representing position in video
Returns a single frame tensor.
If cache is missing, requests extraction from JavaScript and waits briefly.
"""
import time
if filename not in _video_frames_cache:
print(f"[PromptExtractor] Cache missing for: {filename}, requesting extraction...")
# Broadcast directly to JavaScript clients
try:
server.PromptServer.instance.send_sync("prompt-extractor-extract-frame", {
"filename": filename,
"frame_position": frame_position
})
# Wait briefly for JavaScript to extract and cache the frame
max_wait = 5 # seconds
start_time = time.time()
while filename not in _video_frames_cache and (time.time() - start_time) < max_wait:
time.sleep(0.1)
if filename in _video_frames_cache:
print(f"[PromptExtractor] Frame cached successfully for: {filename}")
else:
print(f"[PromptExtractor] Timeout waiting for frame extraction: {filename}")
return None
except Exception as e:
print(f"[PromptExtractor] Error requesting frame extraction: {e}")
return None
frame_data = _video_frames_cache[filename]
# Convert base64 frame to tensor
frame_tensor = base64_to_tensor(frame_data)
return frame_tensor
def build_link_map(workflow_data):
"""Build a map from link_id to (source_node_id, source_slot, dest_node_id, dest_slot)"""
links = workflow_data.get('links', [])
@@ -424,6 +465,37 @@ def build_node_map(workflow_data):
return node_map
def determine_clip_text_encode_type(node_id, workflow_data, node_map):
"""
Determine if a CLIPTextEncode node is positive or negative by checking
what input it connects to in downstream nodes.
Returns: 'positive', 'negative', or None if unclear
"""
links = workflow_data.get('links', [])
# Find all links where this node is the source
for link in links:
if len(link) >= 5:
source_node_id = link[1]
dest_node_id = link[3]
dest_slot = link[4]
if source_node_id == node_id:
# This node is the source, check where it connects
dest_node = node_map.get(dest_node_id)
if dest_node:
dest_inputs = dest_node.get('inputs', [])
# Check the destination input name
if dest_slot < len(dest_inputs):
input_name = dest_inputs[dest_slot].get('name', '').lower()
if 'positive' in input_name:
return 'positive'
elif 'negative' in input_name:
return 'negative'
return None
def traverse_to_find_text(node_id, input_slot, node_map, link_map, visited=None, max_depth=20):
"""
Traverse backwards through node connections to find the actual prompt text.
@@ -830,26 +902,73 @@ def find_lora_chain_terminals(workflow_data, node_map, link_map):
continue
# Check if this node receives MODEL input
# NOTE: Some nodes have multiple MODEL inputs (e.g., model, model_1 for high/low)
inputs = node.get('inputs', [])
for inp in inputs:
if inp.get('name') in model_input_names and inp.get('link'):
inp_name = inp.get('name', '')
inp_type = inp.get('type', '')
# Check if this is a MODEL type input (by type or by name matching)
if (inp_type == 'MODEL' or inp_name in model_input_names) and inp.get('link'):
link_id = inp['link']
link_info = link_map.get(link_id)
if link_info:
source_id = link_info['source_node']
source_node = node_map.get(source_id)
if source_node and is_lora_node(source_node.get('type', '')):
# This node receives MODEL from a LoRA loader
# Trace back through the MODEL chain to find a LoRA loader
# (might go through intermediate nodes like ModelSamplingSD3)
lora_source_id = trace_to_lora_loader(source_id, node_map, link_map, set())
if lora_source_id:
# Get the label to better identify high/low
inp_label = inp.get('label', '').lower()
# This node receives MODEL from a LoRA loader (possibly through intermediate nodes)
terminals.append({
'terminal_id': node_id,
'terminal_type': node_type,
'terminal_title': node.get('title', ''),
'lora_source_id': source_id
'lora_source_id': lora_source_id,
'input_name': inp_name, # Track which input (model, model_1, etc)
'input_label': inp_label # Track the label (model H, model L)
})
return terminals
def trace_to_lora_loader(node_id, node_map, link_map, visited, max_depth=10):
"""
Trace backwards through MODEL connections to find the first LoRA loader node.
Returns the LoRA loader node ID, or None if no LoRA loader is found.
"""
if max_depth <= 0 or node_id in visited:
return None
visited.add(node_id)
node = node_map.get(node_id)
if not node:
return None
# Check if this node is a LoRA loader
if is_lora_node(node.get('type', '')):
return node_id
# Otherwise, trace back through MODEL input
inputs = node.get('inputs', [])
for inp in inputs:
if inp.get('name') in ['model', 'MODEL'] and inp.get('link'):
link_id = inp['link']
link_info = link_map.get(link_id)
if link_info:
source_node_id = link_info['source_node']
result = trace_to_lora_loader(source_node_id, node_map, link_map, visited, max_depth - 1)
if result:
return result
return None
def parse_workflow_for_prompts(prompt_data, workflow_data=None):
"""
Parse workflow/prompt data to extract positive/negative prompts and LoRAs
@@ -910,7 +1029,19 @@ def parse_workflow_for_prompts(prompt_data, workflow_data=None):
# Extract prompts - with traversal if needed
if node_type in ['CLIPTextEncode', 'CLIPTextEncodeSDXL', 'CLIPTextEncodeFlux']:
is_negative = 'negative' in title.lower()
# Determine positive/negative by checking output connections (most reliable)
connection_type = determine_clip_text_encode_type(node_id, workflow_data, node_map)
# Fallback to title checking if connections don't give us an answer
if not connection_type:
title_lower = title.lower() if title else ""
if 'negative' in title_lower:
connection_type = 'negative'
elif 'positive' in title_lower:
connection_type = 'positive'
else:
# Default to positive if no clear indicator
connection_type = 'positive'
# First try to get text directly from widgets
text_found = ""
@@ -934,7 +1065,7 @@ def parse_workflow_for_prompts(prompt_data, workflow_data=None):
text_found = traversed_text
if text_found:
if is_negative:
if connection_type == 'negative':
negative_prompts.append(text_found)
else:
positive_prompts.append(text_found)
@@ -948,8 +1079,11 @@ def parse_workflow_for_prompts(prompt_data, workflow_data=None):
# PrimitiveStringMultiline - direct prompt text (only add if connected to something)
elif node_type == 'PrimitiveStringMultiline':
# Check title for hints
is_negative = 'negative' in title.lower()
# Check title for hints (must be explicit)
title_lower = title.lower() if title else ""
is_negative = 'negative' in title_lower
is_positive = 'positive' in title_lower or not is_negative # Default to positive if not explicitly negative
for val in widgets_values:
if isinstance(val, str) and len(val) > 20:
if is_negative:
@@ -965,31 +1099,37 @@ def parse_workflow_for_prompts(prompt_data, workflow_data=None):
# and traversing backwards through MODEL connections
lora_chains = []
processed_lora_nodes = set()
processed_terminals = set() # Track by (terminal_id, input_name) tuple to allow multiple inputs per node
if workflow_data and 'nodes' in workflow_data:
# Method 1: Find chains ending at non-LoRA nodes (MODEL input chains)
terminals = find_lora_chain_terminals(workflow_data, node_map, link_map)
for terminal_info in terminals:
terminal_id = terminal_info['terminal_id']
input_name = terminal_info.get('input_name', '')
source_id = terminal_info['lora_source_id']
if source_id in processed_lora_nodes:
# Track by (terminal_id, input_name) to allow same terminal with multiple model inputs
terminal_key = (terminal_id, input_name)
if terminal_key in processed_terminals:
continue
# Collect all LoRAs in this chain
chain_loras, chain_titles = collect_lora_model_chain(source_id, node_map, link_map)
# Mark all LoRA nodes in this chain as processed
for node in workflow_data['nodes']:
if is_lora_node(node.get('type', '')) and node.get('id') in [source_id]:
processed_lora_nodes.add(node.get('id'))
# Mark this terminal input as processed
processed_terminals.add(terminal_key)
if chain_loras:
lora_chains.append({
'titles': chain_titles,
'loras': chain_loras,
'terminal_title': terminal_info.get('terminal_title', ''),
'source_id': source_id
'terminal_id': terminal_id,
'source_id': source_id,
'input_name': terminal_info.get('input_name', ''),
'input_label': terminal_info.get('input_label', '')
})
# Method 2: Find LORA_STACK chains (for Lora Stacker nodes)
@@ -1019,9 +1159,6 @@ def parse_workflow_for_prompts(prompt_data, workflow_data=None):
terminal_stackers = [nid for nid in stacker_nodes.keys() if nid not in stackers_feeding_stackers]
for terminal_id in terminal_stackers:
if terminal_id in processed_lora_nodes:
continue
node = stacker_nodes[terminal_id]
chain_loras, chain_titles = collect_lora_stack_chain(terminal_id, node_map, link_map)
@@ -1044,8 +1181,22 @@ def parse_workflow_for_prompts(prompt_data, workflow_data=None):
# Check ALL titles in the chain for high/low hints
all_titles = chain.get('titles', []) + [chain.get('terminal_title', '')]
all_titles_lower = ' '.join(all_titles).lower()
has_high = 'high' in all_titles_lower
has_low = 'low' in all_titles_lower
# ALSO check the input_name and input_label which are the most reliable indicators
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
)
has_low = (
'low' in all_titles_lower or
'low' in input_name or
'low' in input_label
)
# Determine which stack based on title hints
if has_high and not has_low:
@@ -1142,9 +1293,10 @@ def parse_workflow_for_prompts(prompt_data, workflow_data=None):
if cleaned:
clean_negative.append(cleaned)
# Use the longest prompt as the primary (usually the most complete)
result['positive_prompt'] = max(clean_positive, key=len) if clean_positive else ''
result['negative_prompt'] = max(clean_negative, key=len) if clean_negative else ''
# Use the first prompt from each list (our connection logic already determined which is which)
# If multiple prompts exist, concatenate them with commas
result['positive_prompt'] = ', '.join(clean_positive) if clean_positive else ''
result['negative_prompt'] = ', '.join(clean_negative) if clean_negative else ''
result['loras_a'] = loras_a
result['loras_b'] = loras_b
@@ -1256,7 +1408,7 @@ class PromptExtractor:
def INPUT_TYPES(cls):
# Get list of supported files from input directory
input_dir = folder_paths.get_input_directory()
files = []
files = ["(none)"] # Add empty option at the top for passthrough
supported_extensions = ['.png', '.jpg', '.jpeg', '.webp', '.json', '.mp4', '.webm', '.mov', '.avi']
if os.path.exists(input_dir):
@@ -1265,12 +1417,22 @@ class PromptExtractor:
if ext in supported_extensions:
files.append(filename)
# Sort files alphabetically
files.sort()
# Sort files alphabetically (except first entry which is "(none)")
files_to_sort = files[1:]
files_to_sort.sort()
files = ["(none)"] + files_to_sort
return {
"required": {
"image": (sorted(files), {"image_upload": True}),
"image": (files, {"image_upload": True}),
"frame_position": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1.0, "step": 0.01, "display": "slider"}),
},
"optional": {
"lora_stack_a": ("LORA_STACK",),
"lora_stack_b": ("LORA_STACK",),
},
"hidden": {
"unique_id": "UNIQUE_ID",
},
}
@@ -1280,22 +1442,27 @@ class PromptExtractor:
FUNCTION = "extract"
OUTPUT_NODE = True # Enable preview display
def extract(self, image=""):
def extract(self, image="", frame_position=0.0, lora_stack_a=None, lora_stack_b=None, unique_id=None):
"""Extract prompts and LoRAs from the specified file."""
# Always initialize with empty strings, never None
positive_prompt = ""
negative_prompt = ""
lora_stack_a = []
lora_stack_b = []
extracted_lora_stack_a = []
extracted_lora_stack_b = []
image_tensor = None
# Handle None or missing image parameter
if image is None:
image = ""
# Skip metadata extraction if "(none)" is selected (passthrough mode)
if image == "(none)":
image = ""
# Normalize file path
resolved_path = None
file_path = "" # Initialize file_path to avoid UnboundLocalError
if image and image.strip():
file_path = image.strip()
@@ -1345,21 +1512,22 @@ class PromptExtractor:
elif ext in ['.mp4', '.webm', '.mov', '.avi']:
prompt_data, workflow_data = extract_metadata_from_video(resolved_path)
# Extract first frame as image
image_tensor = extract_first_frame_from_video(resolved_path)
# Get frame cached by JavaScript at the specified position
filename = os.path.basename(resolved_path)
image_tensor = get_cached_video_frame(filename, frame_position)
# If no cached frame, use placeholder (JavaScript will cache before execution)
if image_tensor is None:
image_tensor = get_placeholder_image_tensor()
# Parse the extracted data
if prompt_data or workflow_data:
print(f"[PromptExtractor] Calling parse_workflow_for_prompts with prompt_data={prompt_data is not None}, workflow_data={workflow_data is not None}")
print("[PromptExtractor] Successfully extracted metadata")
parsed = parse_workflow_for_prompts(prompt_data, workflow_data)
positive_prompt = parsed['positive_prompt'] or ""
negative_prompt = parsed['negative_prompt'] or ""
loras_a = parsed['loras_a']
loras_b = parsed['loras_b']
print(f"[PromptExtractor] Parsed result: positive={len(positive_prompt)} chars, negative={len(negative_prompt)} chars, loras_a={len(loras_a)}, loras_b={len(loras_b)}")
# Build LORA_STACK format
lora_files = get_available_loras()
# Process loras_a into stack A (only active LoRAs)
for lora in loras_a:
@@ -1372,14 +1540,10 @@ class PromptExtractor:
model_strength = lora['model_strength']
clip_strength = lora['clip_strength']
matched_filename = self._match_lora(lora_name, lora_path, lora_files)
if matched_filename:
lora_stack_a.append((matched_filename, model_strength, clip_strength))
else:
# Include the LoRA even if not found locally - PromptManager handles missing LoRAs
fallback_name = lora_path if lora_path else f"{lora_name}.safetensors"
lora_stack_a.append((fallback_name, model_strength, clip_strength))
print(f"[PromptExtractor] Note: LoRA not found locally (Stack A): {lora_name}")
# Use path if available, otherwise construct from name
# PromptManagerAdvanced handles matching to actual files
filename = lora_path if lora_path else f"{lora_name}.safetensors"
extracted_lora_stack_a.append((filename, model_strength, clip_strength))
# Process loras_b into stack B (only active LoRAs)
for lora in loras_b:
@@ -1392,17 +1556,50 @@ class PromptExtractor:
model_strength = lora['model_strength']
clip_strength = lora['clip_strength']
matched_filename = self._match_lora(lora_name, lora_path, lora_files)
if matched_filename:
lora_stack_b.append((matched_filename, model_strength, clip_strength))
else:
fallback_name = lora_path if lora_path else f"{lora_name}.safetensors"
lora_stack_b.append((fallback_name, model_strength, clip_strength))
print(f"[PromptExtractor] Note: LoRA not found locally (Stack B): {lora_name}")
# Use path if available, otherwise construct from name
# PromptManagerAdvanced handles matching to actual files
filename = lora_path if lora_path else f"{lora_name}.safetensors"
extracted_lora_stack_b.append((filename, model_strength, clip_strength))
else:
if file_path:
print(f"[PromptExtractor] File not found: {file_path}")
# Combine input lora stacks with extracted loras
# Extracted loras come first (to preserve workflow strengths), then input loras are appended (avoiding duplicates)
final_lora_stack_a = []
final_lora_stack_b = []
# Start with extracted loras (these have the correct strengths from the workflow)
final_lora_stack_a.extend(extracted_lora_stack_a)
final_lora_stack_b.extend(extracted_lora_stack_b)
# Build set of existing lora names (compare by base name only, without path or extension)
existing_names_a = {os.path.splitext(os.path.basename(lora[0]))[0].lower() for lora in final_lora_stack_a}
existing_names_b = {os.path.splitext(os.path.basename(lora[0]))[0].lower() for lora in final_lora_stack_b}
# Add input loras (skip duplicates)
if lora_stack_a is not None and isinstance(lora_stack_a, list):
added_count = 0
skipped_count = 0
for lora in lora_stack_a:
lora_basename = os.path.splitext(os.path.basename(lora[0]))[0].lower()
if lora_basename not in existing_names_a:
final_lora_stack_a.append(lora)
added_count += 1
else:
skipped_count += 1
if lora_stack_b is not None and isinstance(lora_stack_b, list):
added_count = 0
skipped_count = 0
for lora in lora_stack_b:
lora_basename = os.path.splitext(os.path.basename(lora[0]))[0].lower()
if lora_basename not in existing_names_b:
final_lora_stack_b.append(lora)
added_count += 1
else:
skipped_count += 1
# Provide placeholder image tensor if none loaded (e.g., for JSON files)
if image_tensor is None:
image_tensor = get_placeholder_image_tensor()
@@ -1417,43 +1614,11 @@ class PromptExtractor:
if not negative_prompt:
negative_prompt = " "
print(f"[PromptExtractor] Final output: positive_prompt type={type(positive_prompt)}, value='{positive_prompt[:50] if positive_prompt else ''}...'")
return {
"ui": {"images": preview_images},
"result": (positive_prompt, negative_prompt, lora_stack_a, lora_stack_b, image_tensor)
"result": (positive_prompt, negative_prompt, final_lora_stack_a, final_lora_stack_b, image_tensor)
}
def _match_lora(self, lora_name, lora_path, lora_files):
"""Find the matching lora filename from available loras"""
lora_name_lower = lora_name.lower()
# If we have a path, try to match it first
if lora_path:
# Try exact path match
for lora_file in lora_files:
if lora_file == lora_path:
return lora_file
# Try path ending match (handles different base directories)
if lora_file.replace('\\', '/').endswith(lora_path.replace('\\', '/')):
return lora_file
if lora_path.replace('\\', '/').endswith(lora_file.replace('\\', '/')):
return lora_file
# Try name-based matching
for lora_file in lora_files:
# Try exact name match
file_name_no_ext = os.path.splitext(os.path.basename(lora_file))[0]
if file_name_no_ext.lower() == lora_name_lower:
return lora_file
# Try partial match
for lora_file in lora_files:
if lora_name_lower in lora_file.lower():
return lora_file
return None
def save_preview_images(self, images):
"""Save images temporarily for preview display"""
import random
@@ -1482,12 +1647,12 @@ class PromptExtractor:
return results
@classmethod
def IS_CHANGED(cls, image):
def IS_CHANGED(cls, image, frame_position, **kwargs):
"""
Check if the file has changed.
Returns file modification time for existing files, or a constant for missing/empty paths.
Note: float('nan') must NOT be used - NaN != NaN, so ComfyUI would always re-execute.
Check if the file has changed or if frame position changed.
Returns a tuple of (file_modification_time, frame_position) to track changes.
"""
mtime = "no_file"
if image:
file_path = image.strip()
# Handle relative paths
@@ -1495,8 +1660,8 @@ class PromptExtractor:
input_dir = folder_paths.get_input_directory()
potential_path = os.path.join(input_dir, file_path)
if os.path.exists(potential_path):
return os.path.getmtime(potential_path)
mtime = os.path.getmtime(potential_path)
elif os.path.exists(file_path):
return os.path.getmtime(file_path)
# Return constant for empty/missing files - this ensures no re-execution
return "no_file"
mtime = os.path.getmtime(file_path)
return (mtime, frame_position)
+215 -69
View File
@@ -78,49 +78,121 @@ def get_available_loras():
return lora_files
def resolve_lora_path(lora_name):
def fuzzy_match_lora(lora_name, lora_files):
"""
Resolve a LoRA name to its full path using ComfyUI's folder system.
Returns (full_path, found) tuple.
"""
lora_files = get_available_loras()
Attempt to find a matching LoRA using fuzzy matching.
Handles renamed LoRAs by removing common WAN-related tokens.
# Try exact match first (with extension)
Example: "DR34LAY_HIGH_V2" can match "DR34LAY_I2V_14B_HIGH_V2"
Returns (matched_file, True) if found, (None, False) otherwise.
"""
import re
# Known LoRA file extensions - only strip these, not arbitrary dots in names
lora_extensions = {'.safetensors', '.ckpt', '.pt', '.bin', '.pth'}
def strip_lora_extension(name):
"""Remove only known LoRA file extensions, not arbitrary dots in names."""
name_lower = name.lower()
for ext in lora_extensions:
if name_lower.endswith(ext):
return name[:-len(ext)]
return name
# Tokens to remove for fuzzy matching (case-insensitive)
# Order matters: remove longer tokens first to avoid partial matches
wan_tokens = ['wan_2_2', 'wan22', 'wan2.2', '20epoc', 'a14b', '14b', 'i2v', 't2v']
def normalize_name(name):
"""
Remove WAN tokens from name, treating underscores and hyphens as separators.
Also removes content in parentheses (e.g., "MyLora (1)" becomes "MyLora").
Returns list of remaining non-empty parts in lowercase.
"""
name_lower = name.lower()
# Remove anything in parentheses (e.g., " (1)", "(copy)", etc.)
name_lower = re.sub(r'\s*\([^)]*\)', '', name_lower)
# Replace each token with a placeholder to preserve boundaries
for token in wan_tokens:
# Use word boundary-aware replacement with _ or - as delimiter
# Replace [_-]token[_-], [_-]token, token[_-], or standalone token
pattern = rf'(?:^|[_-]){re.escape(token)}(?:[_-]|$)'
name_lower = re.sub(pattern, '_', name_lower)
# Split by underscore or hyphen and filter out empty strings
parts = [p for p in re.split(r'[_-]', name_lower) if p]
return parts
# Normalize the search name - use our extension stripper, not splitext
search_parts = normalize_name(strip_lora_extension(lora_name))
search_set = set(search_parts)
# If search_set is empty after normalization, we can't do fuzzy matching
if not search_set:
return None, False
candidates = []
for lora_file in lora_files:
if lora_file == lora_name:
return folder_paths.get_full_path("loras", lora_file), True
file_name_no_ext = strip_lora_extension(os.path.basename(lora_file))
file_parts = normalize_name(file_name_no_ext)
file_set = set(file_parts)
# Try matching by name without extension
# Check if all search parts are present in the file parts
if search_set.issubset(file_set):
# Calculate how well this matches (prefer closer matches)
extra_parts = len(file_set - search_set)
candidates.append((lora_file, file_name_no_ext, extra_parts))
if not candidates:
return None, False
# If only one match, return it
if len(candidates) == 1:
return candidates[0][0], True
# Multiple matches - prefer ones that match i2v/t2v from original if present
lora_name_lower = lora_name.lower()
for lora_file in lora_files:
file_name_no_ext = os.path.splitext(os.path.basename(lora_file))[0]
if file_name_no_ext.lower() == lora_name_lower:
return folder_paths.get_full_path("loras", lora_file), True
has_i2v = 'i2v' in lora_name_lower
has_t2v = 't2v' in lora_name_lower
# Try partial match (lora_name might be just the filename, lora_file might have subdirs)
for lora_file in lora_files:
file_name = os.path.basename(lora_file)
file_name_no_ext = os.path.splitext(file_name)[0]
if file_name_no_ext.lower() == lora_name_lower or file_name.lower() == lora_name_lower:
return folder_paths.get_full_path("loras", lora_file), True
if has_i2v:
i2v_matches = [c for c in candidates if 'i2v' in c[1].lower()]
if i2v_matches:
candidates = i2v_matches
elif has_t2v:
t2v_matches = [c for c in candidates if 't2v' in c[1].lower()]
if t2v_matches:
candidates = t2v_matches
# Not found
return None, False
# Return the match with fewest extra parts (closest match)
candidates.sort(key=lambda x: x[2])
return candidates[0][0], True
def get_lora_relative_path(lora_name):
"""
Get the relative path for a LoRA that ComfyUI expects for loading.
Returns (relative_path, found) tuple.
Supports fuzzy matching for renamed LoRAs.
"""
lora_files = get_available_loras()
lora_name_lower = lora_name.lower()
# Try exact match first
for lora_file in lora_files:
file_name_no_ext = os.path.splitext(os.path.basename(lora_file))[0]
if file_name_no_ext.lower() == lora_name_lower:
return lora_file, True
# Try fuzzy match for renamed LoRAs
fuzzy_match, found = fuzzy_match_lora(lora_name, lora_files)
if found:
return fuzzy_match, True
# Not found
return lora_name, False
@@ -196,18 +268,30 @@ class PromptManagerAdvanced:
OUTPUT_NODE = True
@classmethod
def IS_CHANGED(cls, **kwargs):
def IS_CHANGED(cls, category, name, text, use_prompt_input, use_lora_input, **kwargs):
"""
Always return a unique value to ensure the node re-executes.
This is important because:
1. The node broadcasts UI updates to the frontend during execution
2. After browser refresh, the frontend loses its state and needs fresh data
3. Even if upstream nodes are cached, we need to re-broadcast to the new frontend session
Track changes to the node's inputs to determine if re-execution is needed.
Returns a tuple of relevant values that should trigger re-execution when changed.
"""
# Get optional inputs
prompt_input = kwargs.get('prompt_input', None)
lora_stack_a = kwargs.get('lora_stack_a', None)
lora_stack_b = kwargs.get('lora_stack_b', None)
trigger_words = kwargs.get('trigger_words', None)
The performance impact is minimal since this node's actual processing is lightweight.
"""
import time
return time.time()
# Return tuple of all values that should trigger re-execution when changed
# Convert lists/objects to strings for hashable comparison
return (
category,
name,
text,
use_prompt_input,
use_lora_input,
str(prompt_input) if prompt_input else None,
str(lora_stack_a) if lora_stack_a else None,
str(lora_stack_b) if lora_stack_b else None,
trigger_words
)
@classmethod
def VALIDATE_INPUTS(cls, name, **kwargs):
@@ -342,14 +426,15 @@ class PromptManagerAdvanced:
if not isinstance(toggle_data, list):
return list(lora_stack)
# Create a map of toggle states by lora name
# Create a map of toggle states by lora name (case-insensitive)
toggle_map = {}
for item in toggle_data:
if isinstance(item, dict):
name = item.get('name', '')
toggle_map[name] = {
toggle_map[name.lower()] = {
'active': item.get('active', True),
'strength': item.get('strength')
'strength': item.get('strength'),
'original_name': name # Keep original for debugging
}
# Filter and adjust lora stack
@@ -360,8 +445,11 @@ class PromptManagerAdvanced:
# Extract lora name from path
lora_name = os.path.splitext(os.path.basename(lora_path))[0]
# Check toggle state
toggle_state = toggle_map.get(lora_name, {'active': True, 'strength': None})
# Check toggle state (case-insensitive lookup)
toggle_state = toggle_map.get(lora_name.lower(), {'active': True, 'strength': None})
# Debug logging
print(f"[PromptManagerAdvanced] Processing LoRA: {lora_name}, original_strength={model_strength}, toggle_strength={toggle_state.get('strength')}, active={toggle_state.get('active')}")
if not toggle_state['active']:
continue # Skip inactive loras
@@ -408,31 +496,6 @@ class PromptManagerAdvanced:
# Not found
return lora_path, False
def _resolve_lora_path(self, lora_path, lora_files):
"""
Try to resolve a LoRA path to an available local LoRA.
First checks if the exact path exists, then searches by name.
Args:
lora_path: The original path from the stack
lora_files: List of available LoRA files
Returns:
Resolved path if found, original path otherwise
"""
# Check if exact path exists
if lora_path in lora_files:
return lora_path
# Try to find by name
lora_name = os.path.splitext(os.path.basename(lora_path))[0]
found_path, found = get_lora_relative_path(lora_name)
if found:
return found_path
# Return original path (will fail at load time, but at least shows in UI)
return lora_path
def get_prompt(self, category, name, use_prompt_input, text="", use_lora_input=True, prompt_input="",
lora_stack_a=None, lora_stack_b=None, trigger_words=None, thumbnail_image=None,
unique_id=None, loras_a_toggle=None, loras_b_toggle=None, trigger_words_toggle=None):
@@ -444,6 +507,12 @@ class PromptManagerAdvanced:
else:
output_text = text
# Capture the original input loras BEFORE any processing
# These are used by the frontend to detect when inputs change
# and clear toggle states accordingly
input_loras_a = self._format_loras_for_display(lora_stack_a) if lora_stack_a else []
input_loras_b = self._format_loras_for_display(lora_stack_b) if lora_stack_b else []
# Process trigger words
trigger_words_display = self._process_trigger_words(
trigger_words, trigger_words_toggle
@@ -454,6 +523,10 @@ class PromptManagerAdvanced:
preset_stack_a = self._build_stack_from_toggle(loras_a_toggle) if loras_a_toggle else []
preset_stack_b = self._build_stack_from_toggle(loras_b_toggle) if loras_b_toggle else []
# Get ALL preset loras including unavailable ones (for display purposes)
all_preset_loras_a = self._get_all_loras_from_toggle(loras_a_toggle) if loras_a_toggle else []
all_preset_loras_b = self._get_all_loras_from_toggle(loras_b_toggle) if loras_b_toggle else []
# When use_lora_input is disabled, ignore connected stacks and use only saved loras
if not use_lora_input:
lora_stack_a = preset_stack_a
@@ -475,16 +548,14 @@ class PromptManagerAdvanced:
processed_stack_a = self._process_lora_toggle(lora_stack_a, loras_a_toggle)
processed_stack_b = self._process_lora_toggle(lora_stack_b, loras_b_toggle)
# Display logic depends on use_lora_input mode:
# - use_lora_input OFF: Show only preset loras (what will actually be used)
# - use_lora_input ON: Show merged loras (preset + connected) so user sees full picture
# Display logic: Include ALL loras (available + unavailable) so UI shows complete picture
# Build display from available loras first, then add unavailable ones
if not use_lora_input:
loras_a_display = self._format_loras_for_display(preset_stack_a) if preset_stack_a else []
loras_b_display = self._format_loras_for_display(preset_stack_b) if preset_stack_b else []
loras_a_display = self._format_loras_for_display_with_unavailable(preset_stack_a, all_preset_loras_a)
loras_b_display = self._format_loras_for_display_with_unavailable(preset_stack_b, all_preset_loras_b)
else:
# Always call _format_loras_for_display even with empty stacks - it handles empty gracefully
loras_a_display = self._format_loras_for_display(lora_stack_a)
loras_b_display = self._format_loras_for_display(lora_stack_b)
loras_a_display = self._format_loras_for_display_with_unavailable(lora_stack_a, all_preset_loras_a)
loras_b_display = self._format_loras_for_display_with_unavailable(lora_stack_b, all_preset_loras_b)
# Convert thumbnail image to base64 if provided
thumbnail_base64 = None
@@ -494,6 +565,10 @@ class PromptManagerAdvanced:
except Exception as e:
print(f"[PromptManagerAdvanced] Failed to convert thumbnail image: {e}")
# Build explicit list of unavailable lora names for frontend
unavailable_loras_a = [lora['name'] for lora in all_preset_loras_a if not lora.get('available', False)]
unavailable_loras_b = [lora['name'] for lora in all_preset_loras_b if not lora.get('available', False)]
# Broadcast update to frontend
if unique_id is not None:
server.PromptServer.instance.send_sync("prompt-manager-advanced-update", {
@@ -503,6 +578,10 @@ class PromptManagerAdvanced:
"prompt_input": prompt_input,
"loras_a": loras_a_display,
"loras_b": loras_b_display,
"input_loras_a": input_loras_a, # Original input loras for change detection
"input_loras_b": input_loras_b, # Original input loras for change detection
"unavailable_loras_a": unavailable_loras_a, # Explicit list of unavailable lora names
"unavailable_loras_b": unavailable_loras_b, # Explicit list of unavailable lora names
"trigger_words": trigger_words_display,
"connected_thumbnail": thumbnail_base64
})
@@ -622,6 +701,73 @@ class PromptManagerAdvanced:
return display_list
def _get_all_loras_from_toggle(self, toggle_data):
"""
Get ALL loras from toggle data including unavailable ones.
Returns list of dicts with name, strength, active, and available status.
Used for building complete display list.
"""
if not toggle_data:
return []
try:
if isinstance(toggle_data, str):
toggle_data = json.loads(toggle_data)
except (json.JSONDecodeError, TypeError):
return []
if not isinstance(toggle_data, list):
return []
all_loras = []
for item in toggle_data:
if not isinstance(item, dict):
continue
lora_name = item.get('name', '')
if not lora_name:
continue
# Check availability using same fuzzy matching as actual loading
# UI should match what Python will actually do
_, found = get_lora_relative_path(lora_name)
all_loras.append({
"name": lora_name,
"strength": float(item.get('strength', 1.0)),
"clip_strength": float(item.get('clip_strength', item.get('strength', 1.0))),
"active": item.get('active', True),
"available": found
})
return all_loras
def _format_loras_for_display_with_unavailable(self, lora_stack, all_preset_loras):
"""
Format lora stack for frontend display, including unavailable preset loras.
This ensures the UI shows all saved loras even if they're not found locally.
"""
# Start with the available loras from the stack
display_list = self._format_loras_for_display(lora_stack) if lora_stack else []
seen_names = set(item['name'].lower() for item in display_list)
# Add any unavailable preset loras that aren't already in the list
for lora in all_preset_loras:
lora_name_lower = lora['name'].lower()
if lora_name_lower not in seen_names:
display_list.append({
"name": lora['name'],
"path": lora['name'], # Just use name as path for unavailable
"model_strength": lora['strength'],
"clip_strength": lora['clip_strength'],
"active": lora['active'],
"strength": lora['strength'],
"available": lora['available']
})
seen_names.add(lora_name_lower)
return display_list
def _process_trigger_words(self, connected_trigger_words, toggle_data):
"""
Process trigger words from connected input and saved toggle states.
+1 -1
View File
@@ -1,7 +1,7 @@
[project]
name = "prompt-manager"
description = "Prompt Manager extension for ComfyUI, allowing user to both save and generate prompts, as well as save matching loras for each prompt."
version = "1.11.5"
version = "1.12.7"
license = {file = "LICENSE"}
# classifiers = [
# # For OS-independent nodes (works on all operating systems)
+143
View File
@@ -0,0 +1,143 @@
"""
Test fuzzy LoRA matching logic
"""
import os
import re
def fuzzy_match_lora(lora_name, lora_files):
"""
Attempt to find a matching LoRA using fuzzy matching.
Handles renamed LoRAs by removing common WAN-related tokens.
Example: "DR34LAY_HIGH_V2" can match "DR34LAY_I2V_14B_HIGH_V2"
Returns (matched_file, True) if found, (None, False) otherwise.
"""
# Tokens to remove for fuzzy matching (case-insensitive)
# Order matters: remove longer tokens first to avoid partial matches
wan_tokens = ['wan_2_2', 'wan22', 'wan2.2', '20epoc', 'a14b', '14b', 'i2v', 't2v']
def normalize_name(name):
"""
Remove WAN tokens from name, treating underscores and hyphens as separators.
Also removes content in parentheses (e.g., "MyLora (1)" becomes "MyLora").
Returns list of remaining non-empty parts in lowercase.
"""
name_lower = name.lower()
# Remove anything in parentheses (e.g., " (1)", "(copy)", etc.)
name_lower = re.sub(r'\s*\([^)]*\)', '', name_lower)
# Replace each token with a placeholder to preserve boundaries
for token in wan_tokens:
# Use word boundary-aware replacement with _ or - as delimiter
# Replace [_-]token[_-], [_-]token, token[_-], or standalone token
pattern = rf'(?:^|[_-]){re.escape(token)}(?:[_-]|$)'
name_lower = re.sub(pattern, '_', name_lower)
# Split by underscore or hyphen and filter out empty strings
parts = [p for p in re.split(r'[_-]', name_lower) if p]
return parts
# Normalize the search name
search_parts = normalize_name(os.path.splitext(lora_name)[0])
search_set = set(search_parts)
candidates = []
for lora_file in lora_files:
file_name_no_ext = os.path.splitext(os.path.basename(lora_file))[0]
file_parts = normalize_name(file_name_no_ext)
file_set = set(file_parts)
# Check if all search parts are present in the file parts
if search_set.issubset(file_set):
# Calculate how well this matches (prefer closer matches)
extra_parts = len(file_set - search_set)
candidates.append((lora_file, file_name_no_ext, extra_parts))
if not candidates:
return None, False
# If only one match, return it
if len(candidates) == 1:
return candidates[0][0], True
# Multiple matches - prefer ones that match i2v/t2v from original if present
lora_name_lower = lora_name.lower()
has_i2v = 'i2v' in lora_name_lower
has_t2v = 't2v' in lora_name_lower
if has_i2v:
i2v_matches = [c for c in candidates if 'i2v' in c[1].lower()]
if i2v_matches:
candidates = i2v_matches
elif has_t2v:
t2v_matches = [c for c in candidates if 't2v' in c[1].lower()]
if t2v_matches:
candidates = t2v_matches
# Return the match with fewest extra parts (closest match)
candidates.sort(key=lambda x: x[2])
return candidates[0][0], True
def test_fuzzy_matching():
"""Test various fuzzy matching scenarios"""
# Simulate available LoRA files
available_loras = [
"DR34LAY_I2V_14B_HIGH_V2.safetensors",
"DR34LAY_T2V_14B_HIGH_V2.safetensors",
"DR34LAY_I2V_A14B_LOW_V2.safetensors",
"SomeOther_I2V_LoRA.safetensors",
"ExactMatch.safetensors",
"MyLora_WAN_2_2_I2V_Style.safetensors",
"MyLora_Style.safetensors",
"CoolStyle_I2V (1).safetensors",
"CoolStyle_I2V.safetensors",
]
test_cases = [
("DR34LAY_HIGH_V2", "DR34LAY_I2V_14B_HIGH_V2.safetensors", "Renamed WAN LoRA (missing I2V, 14B)"),
("DR34LAY_HIGH_V2.safetensors", "DR34LAY_I2V_14B_HIGH_V2.safetensors", "Renamed WAN LoRA with extension"),
("DR34LAY_LOW_V2", "DR34LAY_I2V_A14B_LOW_V2.safetensors", "Renamed WAN LoRA (missing I2V, A14B)"),
("DR34LAY_I2V_HIGH_V2", "DR34LAY_I2V_14B_HIGH_V2.safetensors", "Has I2V - should prefer I2V match"),
("DR34LAY_T2V_HIGH_V2", "DR34LAY_T2V_14B_HIGH_V2.safetensors", "Has T2V - should prefer T2V match"),
("MyLora_Style", "MyLora_WAN_2_2_I2V_Style.safetensors", "Should match with WAN_2_2 removed"),
("CoolStyle_I2V", "CoolStyle_I2V (1).safetensors", "Should match ignoring (1) suffix"),
("ExactMatch", "ExactMatch.safetensors", "Exact match case"),
("NonExistent_LoRA", None, "Non-existent LoRA"),
]
print("=" * 80)
print("FUZZY LORA MATCHING TESTS")
print("=" * 80)
all_passed = True
for search_name, expected_match, description in test_cases:
result, found = fuzzy_match_lora(search_name, available_loras)
expected_found = expected_match is not None
passed = (found == expected_found and (not found or result == expected_match))
status = "[PASS]" if passed else "[FAIL]"
print(f"\n{status} {description}")
print(f" Search: '{search_name}'")
print(f" Expected: {expected_match}")
print(f" Got: {result}")
if not passed:
all_passed = False
print("\n" + "=" * 80)
if all_passed:
print("[SUCCESS] All tests passed!")
else:
print("[FAILURE] Some tests failed!")
print("=" * 80)
return all_passed
if __name__ == "__main__":
test_fuzzy_matching()
+90
View File
@@ -0,0 +1,90 @@
"""
Test LoRA extraction from workflow data
"""
import json
import sys
import os
from unittest.mock import Mock
# Add parent directory to path so we can import prompt_extractor
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
# Mock ComfyUI and heavy dependencies
sys.modules['folder_paths'] = Mock()
sys.modules['server'] = Mock()
sys.modules['torch'] = Mock()
sys.modules['PIL'] = Mock()
from prompt_extractor import parse_workflow_for_prompts
def test_wan_workflow_with_shared_lora_loader():
"""
Test case: WAN workflow where both high and low noise models
connect to the same Power Lora Loader, but should still extract
separate lora stacks based on which model they feed into.
"""
# Load the problematic workflow
workflow_path = r"d:\ComfyUI\user\default\workflows\Unsaved Workflow (4).json"
if not os.path.exists(workflow_path):
print(f"Workflow file not found: {workflow_path}")
return
with open(workflow_path, 'r', encoding='utf-8') as f:
workflow_data = json.load(f)
# Parse the workflow
result = parse_workflow_for_prompts(None, workflow_data)
print("\n" + "=" * 80)
print("TEST: WAN Workflow with Shared LoRA Loader")
print("=" * 80)
print(f"\nPositive prompt: {result['positive_prompt'][:100] if result['positive_prompt'] else 'EMPTY'}...")
print(f"Negative prompt: {result['negative_prompt'][:100] if result['negative_prompt'] else 'EMPTY'}")
print(f"\nLoRAs Stack A (High): {len(result['loras_a'])} LoRAs")
for lora in result['loras_a']:
print(f" - {lora['name']} (model: {lora['model_strength']}, clip: {lora['clip_strength']})")
print(f"\nLoRAs Stack B (Low): {len(result['loras_b'])} LoRAs")
for lora in result['loras_b']:
print(f" - {lora['name']} (model: {lora['model_strength']}, clip: {lora['clip_strength']})")
print("\n" + "=" * 80)
# Assertions
assert len(result['loras_a']) > 0, "Stack A should have LoRAs (high noise)"
assert len(result['loras_b']) > 0, "Stack B should have LoRAs (low noise)"
# Note: This workflow uses subgraphs, so prompts might be inside the subgraph
# assert result['positive_prompt'], "Should have positive prompt"
print("\n[PASS] All tests passed!")
def test_non_wan_workflow():
"""
Test case: Regular workflow without high/low naming conventions.
Should fall back to position-based assignment (1st chain -> A, 2nd -> B)
"""
workflow_path = r"d:\ComfyUI\user\default\workflows\Unsaved Workflow.json"
if not os.path.exists(workflow_path):
print(f"Workflow file not found: {workflow_path}")
return
with open(workflow_path, 'r', encoding='utf-8') as f:
workflow_data = json.load(f)
result = parse_workflow_for_prompts(None, workflow_data)
print("\n" + "=" * 80)
print("TEST: Non-WAN Workflow (backward compatibility)")
print("=" * 80)
print(f"\nLoRAs Stack A: {len(result['loras_a'])} LoRAs")
print(f"LoRAs Stack B: {len(result['loras_b'])} LoRAs")
print("\n" + "=" * 80)
print("\n[PASS] Backward compatibility maintained!")
if __name__ == "__main__":
test_wan_workflow_with_shared_lora_loader()
test_non_wan_workflow()