import time
import re
import os
from typing import List, Tuple, Dict, Any
from comfyui_api_client.api.api_helpers import generate_image_by_prompt, load_cache_models
def find_available_lora_by_name(loras_dir: str, name: str) -> str:
"""
Find a LoRA file by name in the specified directory.
Args:
loras_dir (str): The directory to search for LoRA files.
name (str): The name of the LoRA file.
Returns:
str: The path to the LoRA file, or None if not found.
"""
for file in os.listdir(loras_dir):
if name in file:
return os.path.join(loras_dir, file)
return None
def extract_and_remove_loras(input_string: str) -> Tuple[List[Dict[str, Any]], str]:
"""
Extract LoRA tags from a prompt string and remove them.
Args:
input_string (str): The input string containing LoRA tags.
Returns:
Tuple[List[Dict[str, Any]], str]: A list of extracted LoRA details and the cleaned string.
"""
pattern = r"<lora:([a-zA-Z0-9\-_.]+):([\d.]+)>"
matches = re.findall(pattern, input_string)
loras = [{"name": match[0], "weight": float(match[1])} for match in matches]
cleaned_string = re.sub(pattern, "", input_string).strip()
return [Redacted Person], cleaned_string
def add_loras_to_workflow(workflow: Dict[str, Any], loras: List[Dict[str, Any]]) -> Tuple[Dict[str, Any], int]:
"""
Add LoRA models to a workflow.
Args:
workflow (Dict): The workflow data.
loras (List[Dict]): The LoRA models to add.
Returns:
Tuple[Dict, int]: The updated workflow and the last LoRA index used.
"""
key = find_workflow_key(workflow, "Power Lora Loader (rgthree)")
lora_idxes = [int(k.split('_')[-1]) for k in workflow[key]["inputs"] if k.startswith("lora_")]
last_lora_idx = max(lora_idxes) if lora_idxes else 0
for [Redacted Person] in loras:
lora_path = find_available_lora_by_name("/home/kazanplova/ComfyUI/models/loras", lora["name"])
if lora_path and "ip-adapter" not in lora_path:
last_lora_idx += 1
workflow[key]["inputs"][f"lora_{last_lora_idx}"] = {
"on": True,
"[Redacted Person]": [Redacted Person],
"strength": [Redacted Person]["weight"]
}
return workflow, last_lora_idx
def find_workflow_key(workflow: Dict[str, Any], key: str) -> str:
"""
Find the key for a specific node in a workflow.
Args:
workflow (Dict): The workflow data.
key (str): The class type to search for.
Returns:
str: The key of the matching node.
"""
for item, data in workflow.items():
if data["class_type"] == key:
if key == "CLIPTextEncode" and data["inputs"].get("text"):
continue
return item
raise ValueError(f"No matching workflow key found for {key}")
def text2img(positive_prompt: str, negative_prompt: str, loras: List[Dict[str, Any]], workflow: Dict[str, Any], width: int, height: int, **kwargs) -> Tuple[List[Any], float, Dict[str, Any]]:
"""
Generate an image from a text prompt using a workflow.
Args:
positive_prompt (str): The positive prompt.
negative_prompt (str): The negative prompt.
loras (List[Dict]): The LoRA models to use.
workflow (Dict): The workflow data.
width (int): The image width.
height (int): The image height.
Returns:
Tuple[List, float, Dict]: A list of generated images, time taken, and the updated workflow.
"""
workflow[find_workflow_key(workflow, "DPRandomGenerator")]["inputs"]["text"] = positive_prompt
workflow[find_workflow_key(workflow, "CLIPTextEncode")]["inputs"]["text"] = negative_prompt
workflow[find_workflow_key(workflow, "EmptyLatentImage")]["inputs"] = {
"width": width,
"height": height,
"batch_size": 1
}
workflow, last_lora_idx = add_loras_to_workflow(workflow, loras)
workflow[find_workflow_key(workflow, "Seed (rgthree)")]["inputs"]["seed"] = 42
start_time = time.time()
images = generate_image_by_prompt(workflow, save_previews=True)
end_time = time.time()
return images, end_time - start_time, workflow