Spaces:
Sleeping
Sleeping
File size: 11,908 Bytes
799d465 af8c1fd 81cec35 799d465 fa96107 d909487 8bb51aa 202caac f446947 4f00e0c d909487 799d465 af8c1fd 799d465 d909487 0e674ea 799d465 81cec35 799d465 202caac 799d465 89e0ec3 799d465 89e0ec3 799d465 89e0ec3 799d465 a643d17 799d465 89e0ec3 799d465 89e0ec3 799d465 6bc792b 799d465 89e0ec3 799d465 e7fedfd 799d465 89e0ec3 799d465 d8c229d 799d465 e7fedfd 2957199 e7fedfd 377cd30 799d465 8bb51aa 81cec35 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 |
import os
import random
import sys
from typing import Sequence, Mapping, Any, Union
import torch
#import spaces
import numpy as np
from PIL import Image
# from comfy import model_management
from nodes import NODE_CLASS_MAPPINGS as NODE_CLASS_MAPPINGS_1
from comfy_extras.nodes_custom_sampler import NODE_CLASS_MAPPINGS as NODE_CLASS_MAPPINGS_2
from custom_nodes.ComfyUI_Comfyroll_CustomNodes.node_mappings import NODE_CLASS_MAPPINGS as NODE_CLASS_MAPPINGS_3
from custom_nodes.ComfyUI_Comfyroll_CustomNodes.node_mappings import NODE_CLASS_MAPPINGS as NODE_CLASS_MAPPINGS_4
from comfy_extras.nodes_model_advanced import NODE_CLASS_MAPPINGS as NODE_CLASS_MAPPINGS_5
from comfy_extras.nodes_flux import NODE_CLASS_MAPPINGS as NODE_CLASS_MAPPINGS_6
from torchvision.transforms.functional import to_pil_image
from PIL import Image
import numpy as np
import time
from huggingface_hub import hf_hub_download
token = os.getenv("HF_TKN")
# Merge both mappings
NODE_CLASS_MAPPINGS = {**NODE_CLASS_MAPPINGS_1, **NODE_CLASS_MAPPINGS_2, **NODE_CLASS_MAPPINGS_3, **NODE_CLASS_MAPPINGS_4, **NODE_CLASS_MAPPINGS_5, **NODE_CLASS_MAPPINGS_6}
hf_hub_download(repo_id="black-forest-labs/FLUX.1-dev", filename="flux1-dev.safetensors", local_dir="models/unet", token = token)
hf_hub_download(repo_id="black-forest-labs/FLUX.1-dev", filename="ae.safetensors", local_dir="models/vae", token = token)
hf_hub_download(repo_id="comfyanonymous/flux_text_encoders", filename="clip_l.safetensors", local_dir="models/text_encoders", token = token)
hf_hub_download(repo_id="comfyanonymous/flux_text_encoders", filename="t5xxl_fp16.safetensors", local_dir="models/text_encoders", token = token)
def preprocess_image_tensor(image):
# If image has a batch dimension (shape: [1, C, H, W]), remove it.
if image.ndim == 4 and image.shape[0] == 1:
image = image.squeeze(0)
# If image is in channels-first format (i.e. [C, H, W]) and has 3 or 4 channels,
# convert it to channels-last format ([H, W, C]).
if image.ndim == 3 and image.shape[0] in [1, 3, 4]:
image = image.permute(1, 2, 0)
# Ensure the image values are between 0 and 1. Then scale them to [0, 255].
image = image.detach().cpu().numpy()
image = np.clip(image, 0, 1) * 255
# Convert to unsigned 8-bit integer type.
image = image.astype(np.uint8)
return image
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 o 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 utils.extra_config instead."
)
from utils.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.")
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()
def preprocess_image_tensor(image):
# If image has a batch dimension (shape: [1, C, H, W]), remove it.
if image.ndim == 4 and image.shape[0] == 1:
image = image.squeeze(0)
# If image is in channels-first format (i.e. [C, H, W]) and has 3 or 4 channels,
# convert it to channels-last format ([H, W, C]).
if image.ndim == 3 and image.shape[0] in [1, 3, 4]:
image = image.permute(1, 2, 0)
# Ensure the image values are between 0 and 1. Then scale them to [0, 255].
image = image.detach().cpu().numpy()
image = np.clip(image, 0, 1) * 255
# Convert to unsigned 8-bit integer type.
image = image.astype(np.uint8)
return image
add_comfyui_directory_to_sys_path()
import_custom_nodes()
# add_extra_model_paths()
dualcliploader = NODE_CLASS_MAPPINGS["DualCLIPLoader"]()
dualcliploader_11 = dualcliploader.load_clip(
clip_name1="t5xxl_fp16.safetensors",
clip_name2="clip_l.safetensors",
type="flux",
device="default",
)
cliptextencode = NODE_CLASS_MAPPINGS["CLIPTextEncode"]()
cliptextencode_6 = cliptextencode.encode(
text="Photo on a small glass panel. Color. Photo of trees with a body of water in the front and moutain in the background.",
clip=get_value_at_index(dualcliploader_11, 0),
)
vaeloader = NODE_CLASS_MAPPINGS["VAELoader"]()
vaeloader_10 = vaeloader.load_vae(vae_name="ae.safetensors")
unetloader = NODE_CLASS_MAPPINGS["UNETLoader"]()
unetloader_12 = unetloader.load_unet(
unet_name="flux1-dev.safetensors", weight_dtype="default"
)
ksamplerselect = NODE_CLASS_MAPPINGS["KSamplerSelect"]()
ksamplerselect_16 = ksamplerselect.get_sampler(sampler_name="dpmpp_2m")
# randomnoise = NODE_CLASS_MAPPINGS["RandomNoise"]()
# randomnoise_25 = randomnoise.get_noise(noise_seed='42')
loraloadermodelonly = NODE_CLASS_MAPPINGS["LoraLoaderModelOnly"]()
loraloadermodelonly_72 = loraloadermodelonly.load_lora_model_only(
lora_name='lora_weight_rank_32_alpha_32.safetensors',
strength_model=1,
model=get_value_at_index(unetloader_12, 0),
)
cr_sdxl_aspect_ratio = NODE_CLASS_MAPPINGS["CR SDXL Aspect Ratio"]()
cr_sdxl_aspect_ratio_85 = cr_sdxl_aspect_ratio.Aspect_Ratio(
width=1024,
height=1024,
aspect_ratio="4:3 landscape 1152x896",
swap_dimensions="Off",
upscale_factor=1.5,
batch_size=1,
)
modelsamplingflux = NODE_CLASS_MAPPINGS["ModelSamplingFlux"]()
fluxguidance = NODE_CLASS_MAPPINGS["FluxGuidance"]()
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"]()
# def model_loading():
# model_loaders = [dualcliploader_11, vaeloader_10, unetloader_12, loraloadermodelonly_72]
# valid_models = [
# getattr(loader[0], 'patcher', loader[0])
# for loader in model_loaders
# if not isinstance(loader[0], dict) and not isinstance(getattr(loader[0], 'patcher', None), dict)
# ]
# #Load the models
# # model_management.load_models_gpu(valid_models)
def generate_image(prompt,
guidance_scale,
aspect_ratio,
seed,
num_inference_steps,
lora_weight,
):
# print(seed)
cliptextencode = NODE_CLASS_MAPPINGS["CLIPTextEncode"]()
cliptextencode_6 = cliptextencode.encode(
text=prompt,
clip=get_value_at_index(dualcliploader_11, 0),
)
cr_sdxl_aspect_ratio = NODE_CLASS_MAPPINGS["CR SDXL Aspect Ratio"]()
cr_sdxl_aspect_ratio_85 = cr_sdxl_aspect_ratio.Aspect_Ratio(
width=1024,
height=1024,
aspect_ratio=aspect_ratio,
swap_dimensions="Off",
upscale_factor=1.5,
batch_size=1,
)
loraloadermodelonly = NODE_CLASS_MAPPINGS["LoraLoaderModelOnly"]()
loraloadermodelonly_72 = loraloadermodelonly.load_lora_model_only(
lora_name=lora_weight,
strength_model=1,
model=get_value_at_index(unetloader_12, 0),
)
randomnoise = NODE_CLASS_MAPPINGS["RandomNoise"]()
randomnoise_25 = randomnoise.get_noise(noise_seed=str(seed))
with torch.inference_mode():
for q in range(1):
modelsamplingflux_61 = modelsamplingflux.patch(
max_shift=1.15,
base_shift=0.5,
width=get_value_at_index(cr_sdxl_aspect_ratio_85, 0),
height=get_value_at_index(cr_sdxl_aspect_ratio_85, 1),
model=get_value_at_index(loraloadermodelonly_72, 0),
)
fluxguidance_60 = fluxguidance.append(
guidance=guidance_scale, conditioning=get_value_at_index(cliptextencode_6, 0)
)
basicguider_22 = basicguider.get_guider(
model=get_value_at_index(modelsamplingflux_61, 0),
conditioning=get_value_at_index(fluxguidance_60, 0),
)
basicscheduler_17 = basicscheduler.get_sigmas(
scheduler="sgm_uniform",
steps=num_inference_steps,
denoise=1,
model=get_value_at_index(modelsamplingflux_61, 0),
)
samplercustomadvanced_13 = samplercustomadvanced.sample(
noise=get_value_at_index(randomnoise_25, 0),
guider=get_value_at_index(basicguider_22, 0),
sampler=get_value_at_index(ksamplerselect_16, 0),
sigmas=get_value_at_index(basicscheduler_17, 0),
latent_image=get_value_at_index(cr_sdxl_aspect_ratio_85, 4),
)
vaedecode_8 = vaedecode.decode(
samples=get_value_at_index(samplercustomadvanced_13, 0),
vae=get_value_at_index(vaeloader_10, 0),
)
# saveimage_9 = saveimage.save_images(
# filename_prefix="image", images=get_value_at_index(vaedecode_8, 0)
# )
image_tensor = get_value_at_index(vaedecode_8, 0)
preprocessed_image = preprocess_image_tensor(image_tensor)
pil_image = Image.fromarray(preprocessed_image)
return pil_image, seed
|