cine / comfypulid.py
MaykaGR's picture
Update comfypulid.py
5b42f90 verified
raw
history blame
10.5 kB
import os
import random
import sys
from typing import Sequence, Mapping, Any, Union
import torch
torch.device('cpu')
os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
def get_value_at_index(obj: Union[Sequence, Mapping], index: int) -> Any:
"""Returns the value at the given index of a sequence or mapping.
If the object is a sequence (like list or string), returns the value at the given index.
If the object is a mapping (like a dictionary), returns the value at the index-th key.
Some return a dictionary, in these cases, we look for the "results" key
Args:
obj (Union[Sequence, Mapping]): The object to retrieve the value from.
index (int): The index of the value to retrieve.
Returns:
Any: The value at the given index.
Raises:
IndexError: If the index is out of bounds for the object and the object is not a mapping.
"""
try:
return obj[index]
except KeyError:
return obj["result"][index]
def find_path(name: str, path: str = None) -> str:
"""
Recursively looks at parent folders starting from the given path until it finds the given name.
Returns the path as a Path object if found, or None otherwise.
"""
# If no path is given, use the current working directory
if path is None:
path = os.getcwd()
# Check if the current directory contains the name
if name in os.listdir(path):
path_name = os.path.join(path, name)
print(f"{name} found: {path_name}")
return path_name
# Get the parent directory
parent_directory = os.path.dirname(path)
# If the parent directory is the same as the current directory, we've reached the root and stop the search
if parent_directory == path:
return None
# Recursively call the function with the parent directory
return find_path(name, parent_directory)
def add_comfyui_directory_to_sys_path() -> None:
"""
Add 'ComfyUI' to the sys.path
"""
comfyui_path = find_path("ComfyUI")
if comfyui_path is not None and os.path.isdir(comfyui_path):
sys.path.append(comfyui_path)
print(f"'{comfyui_path}' added to sys.path")
def add_extra_model_paths() -> None:
"""
Parse the optional extra_model_paths.yaml file and add the parsed paths to the sys.path.
"""
try:
from main import load_extra_path_config
except ImportError:
print(
"Could not import load_extra_path_config from main.py. Looking in extra_config instead."
)
from extra_config import load_extra_path_config
extra_model_paths = find_path("extra_model_paths.yaml")
if extra_model_paths is not None:
load_extra_path_config(extra_model_paths)
else:
print("Could not find the extra_model_paths config file.")
add_comfyui_directory_to_sys_path()
add_extra_model_paths()
def import_custom_nodes() -> None:
"""Find all custom nodes in the custom_nodes folder and add those node objects to NODE_CLASS_MAPPINGS
This function sets up a new asyncio event loop, initializes the PromptServer,
creates a PromptQueue, and initializes the custom nodes.
"""
import asyncio
import execution
from nodes import init_extra_nodes
import server
# Creating a new event loop and setting it as the default loop
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
# Creating an instance of PromptServer with the loop
server_instance = server.PromptServer(loop)
execution.PromptQueue(server_instance)
# Initializing custom nodes
init_extra_nodes()
from nodes import NODE_CLASS_MAPPINGS
def generate_image(prompt, structure_image, style_image, depth_strength, style_strength):
import_custom_nodes()
with torch.inference_mode():
vaeloader = NODE_CLASS_MAPPINGS["VAELoader"]()
vaeloader_10 = vaeloader.load_vae(vae_name="FLUX1/ae.safetensors")
dualcliploader = NODE_CLASS_MAPPINGS["DualCLIPLoader"]()
dualcliploader_11 = dualcliploader.load_clip(
clip_name1="clip_l.safetensors",
clip_name2="t5xxl_fp8_e4m3fn.safetensors",
type="flux",
)
loadimage = NODE_CLASS_MAPPINGS["LoadImage"]()
loadimage_97 = loadimage.load_image(image=structure_image)
pulidfluxinsightfaceloader = NODE_CLASS_MAPPINGS["PulidFluxInsightFaceLoader"]()
pulidfluxinsightfaceloader_98 = pulidfluxinsightfaceloader.load_insightface(
provider="CPU"
)
pulidfluxmodelloader = NODE_CLASS_MAPPINGS["PulidFluxModelLoader"]()
pulidfluxmodelloader_99 = pulidfluxmodelloader.load_model(
pulid_file="pulid_flux_v0.9.1.safetensors"
)
pulidfluxevacliploader = NODE_CLASS_MAPPINGS["PulidFluxEvaClipLoader"]()
pulidfluxevacliploader_100 = pulidfluxevacliploader.load_eva_clip()
cliptextencode = NODE_CLASS_MAPPINGS["CLIPTextEncode"]()
cliptextencode_121 = cliptextencode.encode(
text=prompt, clip=get_value_at_index(dualcliploader_11, 0)
)
conditioningzeroout = NODE_CLASS_MAPPINGS["ConditioningZeroOut"]()
conditioningzeroout_116 = conditioningzeroout.zero_out(
conditioning=get_value_at_index(cliptextencode_121, 0)
)
loadimage_129 = loadimage.load_image(
image=style_image
)
getimagesize = NODE_CLASS_MAPPINGS["GetImageSize+"]()
getimagesize_113 = getimagesize.execute(
image=get_value_at_index(loadimage_129, 0)
)
imageresize = NODE_CLASS_MAPPINGS["ImageResize+"]()
imageresize_112 = imageresize.execute(
width=get_value_at_index(getimagesize_113, 0),
height=get_value_at_index(getimagesize_113, 1),
interpolation="nearest",
method="keep proportion",
condition="always",
multiple_of=0,
image=get_value_at_index(loadimage_129, 0),
)
layermask_personmaskultra = NODE_CLASS_MAPPINGS["LayerMask: PersonMaskUltra"]()
layermask_personmaskultra_120 = layermask_personmaskultra.person_mask_ultra(
face=True,
hair=False,
body=False,
clothes=False,
accessories=False,
background=False,
confidence=0.4,
detail_range=16,
black_point=0.01,
white_point=0.99,
process_detail=True,
images=get_value_at_index(imageresize_112, 0),
)
growmask = NODE_CLASS_MAPPINGS["GrowMask"]()
growmask_118 = growmask.expand_mask(
expand=43,
tapered_corners=True,
mask=get_value_at_index(layermask_personmaskultra_120, 1),
)
maskblur = NODE_CLASS_MAPPINGS["MaskBlur+"]()
maskblur_119 = maskblur.execute(
amount=60, device="auto", mask=get_value_at_index(growmask_118, 0)
)
inpaintmodelconditioning = NODE_CLASS_MAPPINGS["InpaintModelConditioning"]()
inpaintmodelconditioning_110 = inpaintmodelconditioning.encode(
noise_mask=True,
positive=get_value_at_index(cliptextencode_121, 0),
negative=get_value_at_index(conditioningzeroout_116, 0),
vae=get_value_at_index(vaeloader_10, 0),
pixels=get_value_at_index(imageresize_112, 0),
mask=get_value_at_index(maskblur_119, 0),
)
unetloader = NODE_CLASS_MAPPINGS["UNETLoader"]()
unetloader_111 = unetloader.load_unet(
unet_name="FLUX1/flux1-dev.safetensors", weight_dtype="fp8_e4m3fn"
)
randomnoise = NODE_CLASS_MAPPINGS["RandomNoise"]()
randomnoise_114 = randomnoise.get_noise(noise_seed=random.randint(1, 2**64))
ksamplerselect = NODE_CLASS_MAPPINGS["KSamplerSelect"]()
ksamplerselect_115 = ksamplerselect.get_sampler(sampler_name="euler")
applypulidflux = NODE_CLASS_MAPPINGS["ApplyPulidFlux"]()
repeatlatentbatch = NODE_CLASS_MAPPINGS["RepeatLatentBatch"]()
basicguider = NODE_CLASS_MAPPINGS["BasicGuider"]()
basicscheduler = NODE_CLASS_MAPPINGS["BasicScheduler"]()
samplercustomadvanced = NODE_CLASS_MAPPINGS["SamplerCustomAdvanced"]()
vaedecode = NODE_CLASS_MAPPINGS["VAEDecode"]()
saveimage = NODE_CLASS_MAPPINGS["SaveImage"]()
applypulidflux_101 = applypulidflux.apply_pulid_flux(
weight=1.1,
start_at=0,
end_at=1,
fusion="max",
fusion_weight_max=1,
fusion_weight_min=0,
train_step=1000,
use_gray=True,
model=get_value_at_index(unetloader_111, 0),
pulid_flux=get_value_at_index(pulidfluxmodelloader_99, 0),
eva_clip=get_value_at_index(pulidfluxevacliploader_100, 0),
face_analysis=get_value_at_index(pulidfluxinsightfaceloader_98, 0),
image=get_value_at_index(loadimage_97, 0),
unique_id=12000670301720322250,
)
repeatlatentbatch_107 = repeatlatentbatch.repeat(
amount=1, samples=get_value_at_index(inpaintmodelconditioning_110, 2)
)
basicguider_117 = basicguider.get_guider(
model=get_value_at_index(applypulidflux_101, 0),
conditioning=get_value_at_index(inpaintmodelconditioning_110, 0),
)
basicscheduler_130 = basicscheduler.get_sigmas(
scheduler="normal",
steps=14,
denoise=0.6,
model=get_value_at_index(unetloader_111, 0),
)
samplercustomadvanced_109 = samplercustomadvanced.sample(
noise=get_value_at_index(randomnoise_114, 0),
guider=get_value_at_index(basicguider_117, 0),
sampler=get_value_at_index(ksamplerselect_115, 0),
sigmas=get_value_at_index(basicscheduler_130, 0),
latent_image=get_value_at_index(repeatlatentbatch_107, 0),
)
vaedecode_122 = vaedecode.decode(
samples=get_value_at_index(samplercustomadvanced_109, 0),
vae=get_value_at_index(vaeloader_10, 0),
)
saveimage_127 = saveimage.save_images(
filename_prefix="ComfyUI", images=get_value_at_index(vaedecode_122, 0)
)
saved_path = f"output/{saveimage_127['ui']['images'][0]['filename']}"
return saved_path
#if __name__ == "__main__":
# main()