Spaces:
Sleeping
Sleeping
Commit
·
799d465
1
Parent(s):
739496f
Commit
Browse files- app.py +159 -3
- custom_nodes/ComfyUI-to-Python-Extension +1 -0
- custom_nodes/ComfyUI_Comfyroll_CustomNodes +1 -0
- live_preview_helpers.py +166 -0
- python.py +262 -0
app.py
CHANGED
|
@@ -1,7 +1,163 @@
|
|
|
|
|
| 1 |
import gradio as gr
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
|
| 3 |
-
|
| 4 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
|
| 6 |
-
demo = gr.Interface(fn=greet, inputs="text", outputs="text")
|
| 7 |
demo.launch()
|
|
|
|
| 1 |
+
import spaces
|
| 2 |
import gradio as gr
|
| 3 |
+
import numpy as np
|
| 4 |
+
import random
|
| 5 |
+
import python
|
| 6 |
+
import spaces
|
| 7 |
+
import torch
|
| 8 |
+
import os
|
| 9 |
+
from huggingface_hub import hf_hub_download
|
| 10 |
+
from diffusers import DiffusionPipeline, FlowMatchEulerDiscreteScheduler, AutoencoderKL
|
| 11 |
+
from transformers import CLIPTextModel, CLIPTokenizer, T5EncoderModel, T5TokenizerFast
|
| 12 |
+
from live_preview_helpers import calculate_shift, retrieve_timesteps, flux_pipe_call_that_returns_an_iterable_of_images
|
| 13 |
+
from peft import PeftModel
|
| 14 |
|
| 15 |
+
dtype = torch.bfloat16
|
| 16 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 17 |
+
token = os.getenv("HUGGINGFACE_TOKEN")
|
| 18 |
+
|
| 19 |
+
# good_vae = AutoencoderKL.from_pretrained("black-forest-labs/FLUX.1-dev", subfolder="vae", torch_dtype=dtype, token=token).to(device)
|
| 20 |
+
# pipe = DiffusionPipeline.from_pretrained("black-forest-labs/FLUX.1-dev", torch_dtype=dtype, token=token).to(device)
|
| 21 |
+
torch.cuda.empty_cache()
|
| 22 |
+
|
| 23 |
+
MAX_SEED = np.iinfo(np.int32).max
|
| 24 |
+
MAX_IMAGE_SIZE = 2048 # not used anymore
|
| 25 |
+
|
| 26 |
+
# Bind the custom method
|
| 27 |
+
# pipe.flux_pipe_call_that_returns_an_iterable_of_images = flux_pipe_call_that_returns_an_iterable_of_images.__get__(pipe)
|
| 28 |
+
python.model_loading()
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
@spaces.GPU()
|
| 32 |
+
def infer(prompt, seed=42, randomize_seed=False, aspect_ratio="4:3 landscape 1152x896", lora_weight="lora_weight_rank_32_alpha_32.safetensors",
|
| 33 |
+
guidance_scale=3.5, num_inference_steps=28, progress=gr.Progress(track_tqdm=True)):
|
| 34 |
+
# Default height + width
|
| 35 |
+
width, height = 1024, 1024
|
| 36 |
+
|
| 37 |
+
# Randomize seed if requested
|
| 38 |
+
if randomize_seed:
|
| 39 |
+
seed = random.randint(0, MAX_SEED)
|
| 40 |
+
generator = torch.Generator().manual_seed(seed)
|
| 41 |
+
|
| 42 |
+
# Load the selected LoRA weight and fuse it
|
| 43 |
+
lora_weight_path = os.path.join("lora_weights", lora_weight)
|
| 44 |
+
# pipe.load_lora_weights(weight_path)
|
| 45 |
+
# pipe.fuse_lora()
|
| 46 |
+
torch.cuda.empty_cache()
|
| 47 |
+
image = python.generate_image(
|
| 48 |
+
prompt,
|
| 49 |
+
height,
|
| 50 |
+
width,
|
| 51 |
+
aspect_ratio,
|
| 52 |
+
seed,
|
| 53 |
+
guidance_scale=guidance_scale,
|
| 54 |
+
).images[0]
|
| 55 |
+
# Generate images
|
| 56 |
+
# for img in pipe.flux_pipe_call_that_returns_an_iterable_of_images(
|
| 57 |
+
# prompt=prompt,
|
| 58 |
+
# guidance_scale=guidance_scale,
|
| 59 |
+
# num_inference_steps=num_inference_steps,
|
| 60 |
+
# width=width,
|
| 61 |
+
# height=height,
|
| 62 |
+
# generator=generator,
|
| 63 |
+
# output_type="pil",
|
| 64 |
+
# good_vae=good_vae,
|
| 65 |
+
# ):
|
| 66 |
+
# out_img = img
|
| 67 |
+
return image,seed
|
| 68 |
+
|
| 69 |
+
# Examples for the prompt
|
| 70 |
+
examples = [
|
| 71 |
+
"Photo on a small glass panel. Color. A vintage Autochrome photograph, early 1900s aesthetic depicts four roses in a brown vase with dark background.",
|
| 72 |
+
"Colorized photograph on a small glass panel depicting trees with orange leaves, a dirt path, and a wood and rope fence.",
|
| 73 |
+
]
|
| 74 |
+
|
| 75 |
+
css = """
|
| 76 |
+
#col-container {
|
| 77 |
+
margin: 0 auto;
|
| 78 |
+
max-width: 520px;
|
| 79 |
+
}
|
| 80 |
+
"""
|
| 81 |
+
|
| 82 |
+
with gr.Blocks(css=css) as demo:
|
| 83 |
+
with gr.Column(elem_id="col-container"):
|
| 84 |
+
gr.Markdown(f"""# Autochrome image generator demo using FLUX.1 [dev]
|
| 85 |
+
[[non-commercial license](https://huggingface.co/black-forest-labs/FLUX.1-dev/blob/main/LICENSE.md)] [[blog](https://blackforestlabs.ai/announcing-black-forest-labs/)] [[model](https://huggingface.co/black-forest-labs/FLUX.1-dev)]
|
| 86 |
+
""")
|
| 87 |
+
|
| 88 |
+
with gr.Row():
|
| 89 |
+
prompt = gr.Text(
|
| 90 |
+
label="Prompt",
|
| 91 |
+
show_label=False,
|
| 92 |
+
max_lines=5,
|
| 93 |
+
placeholder="Enter your prompt",
|
| 94 |
+
container=False,
|
| 95 |
+
)
|
| 96 |
+
run_button = gr.Button("Run", scale=0)
|
| 97 |
+
|
| 98 |
+
result = gr.Image(label="Result", show_label=False)
|
| 99 |
+
|
| 100 |
+
with gr.Accordion("Advanced Settings", open=False):
|
| 101 |
+
seed = gr.Slider(
|
| 102 |
+
label="Seed",
|
| 103 |
+
minimum=0,
|
| 104 |
+
maximum=MAX_SEED,
|
| 105 |
+
step=1,
|
| 106 |
+
value=0,
|
| 107 |
+
)
|
| 108 |
+
randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
|
| 109 |
+
|
| 110 |
+
# Dropdown for aspect ratio selection
|
| 111 |
+
aspect_ratio = gr.Dropdown(
|
| 112 |
+
label="Aspect Ratio",
|
| 113 |
+
choices=["1:1 square 1024x1024", "3:4 portrait 896x1152", "5:8 portrait 832x1216", "9:16 portrait 768x1344", "4:3 landscape 1152x896", "3:2 landscape 1216x832", "16:9 landscape 1344x768"],
|
| 114 |
+
value="4:3 landscape 1152x896",
|
| 115 |
+
interactive=True,
|
| 116 |
+
)
|
| 117 |
+
|
| 118 |
+
# Dropdown for LoRA weight selection
|
| 119 |
+
lora_weight = gr.Dropdown(
|
| 120 |
+
label="LoRA Weight",
|
| 121 |
+
choices=[
|
| 122 |
+
"lora_weight_rank_16_alpha_32_1.safetensors",
|
| 123 |
+
"lora_weight_rank_16_alpha_32_2.safetensors",
|
| 124 |
+
"lora_weight_rank_32_alpha_32.safetensors",
|
| 125 |
+
"lora_weight_rank_32_alpha_64.safetensors",
|
| 126 |
+
],
|
| 127 |
+
value="lora_weight_rank_32_alpha_32.safetensors",
|
| 128 |
+
interactive=True,
|
| 129 |
+
)
|
| 130 |
+
|
| 131 |
+
with gr.Row():
|
| 132 |
+
guidance_scale = gr.Slider(
|
| 133 |
+
label="Guidance Scale",
|
| 134 |
+
minimum=1,
|
| 135 |
+
maximum=25,
|
| 136 |
+
step=0.1,
|
| 137 |
+
value=6,
|
| 138 |
+
)
|
| 139 |
+
num_inference_steps = gr.Slider(
|
| 140 |
+
label="Number of inference steps",
|
| 141 |
+
minimum=1,
|
| 142 |
+
maximum=100,
|
| 143 |
+
step=1,
|
| 144 |
+
value=40,
|
| 145 |
+
)
|
| 146 |
+
|
| 147 |
+
gr.Examples(
|
| 148 |
+
examples=examples,
|
| 149 |
+
fn=infer,
|
| 150 |
+
inputs=[prompt],
|
| 151 |
+
outputs=[result, seed],
|
| 152 |
+
cache_examples="lazy"
|
| 153 |
+
)
|
| 154 |
+
|
| 155 |
+
gr.on(
|
| 156 |
+
triggers=[run_button.click, prompt.submit],
|
| 157 |
+
fn=infer,
|
| 158 |
+
inputs=[prompt, seed, randomize_seed, aspect_ratio, lora_weight, guidance_scale, num_inference_steps],
|
| 159 |
+
outputs=[result, seed]
|
| 160 |
+
|
| 161 |
+
)
|
| 162 |
|
|
|
|
| 163 |
demo.launch()
|
custom_nodes/ComfyUI-to-Python-Extension
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
Subproject commit 0aa2747736193939a3e1e8ef35aa3d0e378c60db
|
custom_nodes/ComfyUI_Comfyroll_CustomNodes
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
Subproject commit d78b780ae43fcf8c6b7c6505e6ffb4584281ceca
|
live_preview_helpers.py
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import numpy as np
|
| 3 |
+
from diffusers import FluxPipeline, AutoencoderTiny, FlowMatchEulerDiscreteScheduler
|
| 4 |
+
from typing import Any, Dict, List, Optional, Union
|
| 5 |
+
|
| 6 |
+
# Helper functions
|
| 7 |
+
def calculate_shift(
|
| 8 |
+
image_seq_len,
|
| 9 |
+
base_seq_len: int = 256,
|
| 10 |
+
max_seq_len: int = 4096,
|
| 11 |
+
base_shift: float = 0.5,
|
| 12 |
+
max_shift: float = 1.16,
|
| 13 |
+
):
|
| 14 |
+
m = (max_shift - base_shift) / (max_seq_len - base_seq_len)
|
| 15 |
+
b = base_shift - m * base_seq_len
|
| 16 |
+
mu = image_seq_len * m + b
|
| 17 |
+
return mu
|
| 18 |
+
|
| 19 |
+
def retrieve_timesteps(
|
| 20 |
+
scheduler,
|
| 21 |
+
num_inference_steps: Optional[int] = None,
|
| 22 |
+
device: Optional[Union[str, torch.device]] = None,
|
| 23 |
+
timesteps: Optional[List[int]] = None,
|
| 24 |
+
sigmas: Optional[List[float]] = None,
|
| 25 |
+
**kwargs,
|
| 26 |
+
):
|
| 27 |
+
if timesteps is not None and sigmas is not None:
|
| 28 |
+
raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
|
| 29 |
+
if timesteps is not None:
|
| 30 |
+
scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
|
| 31 |
+
timesteps = scheduler.timesteps
|
| 32 |
+
num_inference_steps = len(timesteps)
|
| 33 |
+
elif sigmas is not None:
|
| 34 |
+
scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
|
| 35 |
+
timesteps = scheduler.timesteps
|
| 36 |
+
num_inference_steps = len(timesteps)
|
| 37 |
+
else:
|
| 38 |
+
scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
|
| 39 |
+
timesteps = scheduler.timesteps
|
| 40 |
+
return timesteps, num_inference_steps
|
| 41 |
+
|
| 42 |
+
# FLUX pipeline function
|
| 43 |
+
@torch.inference_mode()
|
| 44 |
+
def flux_pipe_call_that_returns_an_iterable_of_images(
|
| 45 |
+
self,
|
| 46 |
+
prompt: Union[str, List[str]] = None,
|
| 47 |
+
prompt_2: Optional[Union[str, List[str]]] = None,
|
| 48 |
+
height: Optional[int] = None,
|
| 49 |
+
width: Optional[int] = None,
|
| 50 |
+
num_inference_steps: int = 28,
|
| 51 |
+
timesteps: List[int] = None,
|
| 52 |
+
guidance_scale: float = 3.5,
|
| 53 |
+
num_images_per_prompt: Optional[int] = 1,
|
| 54 |
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
| 55 |
+
latents: Optional[torch.FloatTensor] = None,
|
| 56 |
+
prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 57 |
+
pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 58 |
+
output_type: Optional[str] = "pil",
|
| 59 |
+
return_dict: bool = True,
|
| 60 |
+
joint_attention_kwargs: Optional[Dict[str, Any]] = None,
|
| 61 |
+
max_sequence_length: int = 512,
|
| 62 |
+
good_vae: Optional[Any] = None,
|
| 63 |
+
):
|
| 64 |
+
height = height or self.default_sample_size * self.vae_scale_factor
|
| 65 |
+
width = width or self.default_sample_size * self.vae_scale_factor
|
| 66 |
+
|
| 67 |
+
# 1. Check inputs
|
| 68 |
+
self.check_inputs(
|
| 69 |
+
prompt,
|
| 70 |
+
prompt_2,
|
| 71 |
+
height,
|
| 72 |
+
width,
|
| 73 |
+
prompt_embeds=prompt_embeds,
|
| 74 |
+
pooled_prompt_embeds=pooled_prompt_embeds,
|
| 75 |
+
max_sequence_length=max_sequence_length,
|
| 76 |
+
)
|
| 77 |
+
|
| 78 |
+
self._guidance_scale = guidance_scale
|
| 79 |
+
self._joint_attention_kwargs = joint_attention_kwargs
|
| 80 |
+
self._interrupt = False
|
| 81 |
+
|
| 82 |
+
# 2. Define call parameters
|
| 83 |
+
batch_size = 1 if isinstance(prompt, str) else len(prompt)
|
| 84 |
+
device = self._execution_device
|
| 85 |
+
|
| 86 |
+
# 3. Encode prompt
|
| 87 |
+
lora_scale = joint_attention_kwargs.get("scale", None) if joint_attention_kwargs is not None else None
|
| 88 |
+
prompt_embeds, pooled_prompt_embeds, text_ids = self.encode_prompt(
|
| 89 |
+
prompt=prompt,
|
| 90 |
+
prompt_2=prompt_2,
|
| 91 |
+
prompt_embeds=prompt_embeds,
|
| 92 |
+
pooled_prompt_embeds=pooled_prompt_embeds,
|
| 93 |
+
device=device,
|
| 94 |
+
num_images_per_prompt=num_images_per_prompt,
|
| 95 |
+
max_sequence_length=max_sequence_length,
|
| 96 |
+
lora_scale=lora_scale,
|
| 97 |
+
)
|
| 98 |
+
# 4. Prepare latent variables
|
| 99 |
+
num_channels_latents = self.transformer.config.in_channels // 4
|
| 100 |
+
latents, latent_image_ids = self.prepare_latents(
|
| 101 |
+
batch_size * num_images_per_prompt,
|
| 102 |
+
num_channels_latents,
|
| 103 |
+
height,
|
| 104 |
+
width,
|
| 105 |
+
prompt_embeds.dtype,
|
| 106 |
+
device,
|
| 107 |
+
generator,
|
| 108 |
+
latents,
|
| 109 |
+
)
|
| 110 |
+
# 5. Prepare timesteps
|
| 111 |
+
sigmas = np.linspace(1.0, 1 / num_inference_steps, num_inference_steps)
|
| 112 |
+
image_seq_len = latents.shape[1]
|
| 113 |
+
mu = calculate_shift(
|
| 114 |
+
image_seq_len,
|
| 115 |
+
self.scheduler.config.base_image_seq_len,
|
| 116 |
+
self.scheduler.config.max_image_seq_len,
|
| 117 |
+
self.scheduler.config.base_shift,
|
| 118 |
+
self.scheduler.config.max_shift,
|
| 119 |
+
)
|
| 120 |
+
timesteps, num_inference_steps = retrieve_timesteps(
|
| 121 |
+
self.scheduler,
|
| 122 |
+
num_inference_steps,
|
| 123 |
+
device,
|
| 124 |
+
timesteps,
|
| 125 |
+
sigmas,
|
| 126 |
+
mu=mu,
|
| 127 |
+
)
|
| 128 |
+
self._num_timesteps = len(timesteps)
|
| 129 |
+
|
| 130 |
+
# Handle guidance
|
| 131 |
+
guidance = torch.full([1], guidance_scale, device=device, dtype=torch.float32).expand(latents.shape[0]) if self.transformer.config.guidance_embeds else None
|
| 132 |
+
|
| 133 |
+
# 6. Denoising loop
|
| 134 |
+
for i, t in enumerate(timesteps):
|
| 135 |
+
if self.interrupt:
|
| 136 |
+
continue
|
| 137 |
+
|
| 138 |
+
timestep = t.expand(latents.shape[0]).to(latents.dtype)
|
| 139 |
+
|
| 140 |
+
noise_pred = self.transformer(
|
| 141 |
+
hidden_states=latents,
|
| 142 |
+
timestep=timestep / 1000,
|
| 143 |
+
guidance=guidance,
|
| 144 |
+
pooled_projections=pooled_prompt_embeds,
|
| 145 |
+
encoder_hidden_states=prompt_embeds,
|
| 146 |
+
txt_ids=text_ids,
|
| 147 |
+
img_ids=latent_image_ids,
|
| 148 |
+
joint_attention_kwargs=self.joint_attention_kwargs,
|
| 149 |
+
return_dict=False,
|
| 150 |
+
)[0]
|
| 151 |
+
# Yield intermediate result
|
| 152 |
+
latents_for_image = self._unpack_latents(latents, height, width, self.vae_scale_factor)
|
| 153 |
+
latents_for_image = (latents_for_image / self.vae.config.scaling_factor) + self.vae.config.shift_factor
|
| 154 |
+
image = self.vae.decode(latents_for_image, return_dict=False)[0]
|
| 155 |
+
yield self.image_processor.postprocess(image, output_type=output_type)[0]
|
| 156 |
+
|
| 157 |
+
latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0]
|
| 158 |
+
torch.cuda.empty_cache()
|
| 159 |
+
|
| 160 |
+
# Final image using good_vae
|
| 161 |
+
latents = self._unpack_latents(latents, height, width, self.vae_scale_factor)
|
| 162 |
+
latents = (latents / good_vae.config.scaling_factor) + good_vae.config.shift_factor
|
| 163 |
+
image = good_vae.decode(latents, return_dict=False)[0]
|
| 164 |
+
self.maybe_free_model_hooks()
|
| 165 |
+
torch.cuda.empty_cache()
|
| 166 |
+
yield self.image_processor.postprocess(image, output_type=output_type)[0]
|
python.py
ADDED
|
@@ -0,0 +1,262 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import random
|
| 3 |
+
import sys
|
| 4 |
+
from typing import Sequence, Mapping, Any, Union
|
| 5 |
+
import torch
|
| 6 |
+
import spaces
|
| 7 |
+
# from comfy import model_management
|
| 8 |
+
from nodes import NODE_CLASS_MAPPINGS as NODE_CLASS_MAPPINGS_1
|
| 9 |
+
from comfy_extras.nodes_custom_sampler import NODE_CLASS_MAPPINGS as NODE_CLASS_MAPPINGS_2
|
| 10 |
+
from custom_nodes.ComfyUI_Comfyroll_CustomNodes.node_mappings import NODE_CLASS_MAPPINGS as NODE_CLASS_MAPPINGS_3
|
| 11 |
+
from huggingface_hub import hf_hub_download
|
| 12 |
+
|
| 13 |
+
# Merge both mappings
|
| 14 |
+
COMBINED_NODE_CLASS_MAPPINGS = {**NODE_CLASS_MAPPINGS_1, **NODE_CLASS_MAPPINGS_2, **NODE_CLASS_MAPPINGS_3}
|
| 15 |
+
hf_hub_download(repo_id="black-forest-labs/FLUX.1-dev", filename="flux1-dev.safetensors", local_dir="models/unet")
|
| 16 |
+
hf_hub_download(repo_id="black-forest-labs/FLUX.1-dev", filename="ae.safetensors", local_dir="models/vae")
|
| 17 |
+
hf_hub_download(repo_id="comfyanonymous/flux_text_encoders", filename="clip_l.safetensors", local_dir="models/text_encoders")
|
| 18 |
+
hf_hub_download(repo_id="comfyanonymous/flux_text_encoders", filename="t5xxl_fp16.safetensors", local_dir="models/text_encoders")
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def get_value_at_index(obj: Union[Sequence, Mapping], index: int) -> Any:
|
| 22 |
+
"""Returns the value at the given index of a sequence or mapping.
|
| 23 |
+
|
| 24 |
+
If the object is a sequence (like list or string), returns the value at the given index.
|
| 25 |
+
If the object is a mapping (like a dictionary), returns the value at the index-th key.
|
| 26 |
+
|
| 27 |
+
Some return a dictionary, in these cases, we look for the "results" key
|
| 28 |
+
|
| 29 |
+
Args:
|
| 30 |
+
obj (Union[Sequence, Mapping]): The object to retrieve the value from.
|
| 31 |
+
index (int): The index of the value to retrieve.
|
| 32 |
+
|
| 33 |
+
Returns:
|
| 34 |
+
Any: The value at the given index.
|
| 35 |
+
|
| 36 |
+
Raises:
|
| 37 |
+
IndexError: If the index is o of bounds for the object and the object is not a mapping.
|
| 38 |
+
"""
|
| 39 |
+
try:
|
| 40 |
+
return obj[index]
|
| 41 |
+
except KeyError:
|
| 42 |
+
return obj["result"][index]
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def find_path(name: str, path: str = None) -> str:
|
| 46 |
+
"""
|
| 47 |
+
Recursively looks at parent folders starting from the given path until it finds the given name.
|
| 48 |
+
Returns the path as a Path object if found, or None otherwise.
|
| 49 |
+
"""
|
| 50 |
+
# If no path is given, use the current working directory
|
| 51 |
+
if path is None:
|
| 52 |
+
path = os.getcwd()
|
| 53 |
+
|
| 54 |
+
# Check if the current directory contains the name
|
| 55 |
+
if name in os.listdir(path):
|
| 56 |
+
path_name = os.path.join(path, name)
|
| 57 |
+
print(f"{name} found: {path_name}")
|
| 58 |
+
return path_name
|
| 59 |
+
|
| 60 |
+
# Get the parent directory
|
| 61 |
+
parent_directory = os.path.dirname(path)
|
| 62 |
+
|
| 63 |
+
# If the parent directory is the same as the current directory, we've reached the root and stop the search
|
| 64 |
+
if parent_directory == path:
|
| 65 |
+
return None
|
| 66 |
+
|
| 67 |
+
# Recursively call the function with the parent directory
|
| 68 |
+
return find_path(name, parent_directory)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def add_comfyui_directory_to_sys_path() -> None:
|
| 72 |
+
"""
|
| 73 |
+
Add 'ComfyUI' to the sys.path
|
| 74 |
+
"""
|
| 75 |
+
comfyui_path = find_path("ComfyUI")
|
| 76 |
+
if comfyui_path is not None and os.path.isdir(comfyui_path):
|
| 77 |
+
sys.path.append(comfyui_path)
|
| 78 |
+
print(f"'{comfyui_path}' added to sys.path")
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def add_extra_model_paths() -> None:
|
| 82 |
+
"""
|
| 83 |
+
Parse the optional extra_model_paths.yaml file and add the parsed paths to the sys.path.
|
| 84 |
+
"""
|
| 85 |
+
try:
|
| 86 |
+
from main import load_extra_path_config
|
| 87 |
+
except ImportError:
|
| 88 |
+
print(
|
| 89 |
+
"Could not import load_extra_path_config from main.py. Looking in utils.extra_config instead."
|
| 90 |
+
)
|
| 91 |
+
from utils.extra_config import load_extra_path_config
|
| 92 |
+
|
| 93 |
+
extra_model_paths = find_path("extra_model_paths.yaml")
|
| 94 |
+
|
| 95 |
+
if extra_model_paths is not None:
|
| 96 |
+
load_extra_path_config(extra_model_paths)
|
| 97 |
+
else:
|
| 98 |
+
print("Could not find the extra_model_paths config file.")
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def import_custom_nodes() -> None:
|
| 102 |
+
"""Find all custom nodes in the custom_nodes folder and add those node objects to NODE_CLASS_MAPPINGS
|
| 103 |
+
|
| 104 |
+
This function sets up a new asyncio event loop, initializes the PromptServer,
|
| 105 |
+
creates a PromptQueue, and initializes the custom nodes.
|
| 106 |
+
"""
|
| 107 |
+
import asyncio
|
| 108 |
+
import execution
|
| 109 |
+
from nodes import init_extra_nodes
|
| 110 |
+
import server
|
| 111 |
+
|
| 112 |
+
# Creating a new event loop and setting it as the default loop
|
| 113 |
+
loop = asyncio.new_event_loop()
|
| 114 |
+
asyncio.set_event_loop(loop)
|
| 115 |
+
|
| 116 |
+
# Creating an instance of PromptServer with the loop
|
| 117 |
+
server_instance = server.PromptServer(loop)
|
| 118 |
+
execution.PromptQueue(server_instance)
|
| 119 |
+
|
| 120 |
+
# Initializing custom nodes
|
| 121 |
+
init_extra_nodes()
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
add_comfyui_directory_to_sys_path()
|
| 126 |
+
import_custom_nodes()
|
| 127 |
+
# add_extra_model_paths()
|
| 128 |
+
dualcliploader = NODE_CLASS_MAPPINGS["DualCLIPLoader"]()
|
| 129 |
+
dualcliploader_11 = dualcliploader.load_clip(
|
| 130 |
+
clip_name1="t5xxl_fp16.safetensors",
|
| 131 |
+
clip_name2="clip_l.safetensors",
|
| 132 |
+
type="flux",
|
| 133 |
+
device="default",
|
| 134 |
+
)
|
| 135 |
+
|
| 136 |
+
cliptextencode = NODE_CLASS_MAPPINGS["CLIPTextEncode"]()
|
| 137 |
+
cliptextencode_6 = cliptextencode.encode(
|
| 138 |
+
text="Photo on a small glass panel. Color. Photo of trees with a body of water in the front and moutain in the background.",
|
| 139 |
+
clip=get_value_at_index(dualcliploader_11, 0),
|
| 140 |
+
)
|
| 141 |
+
|
| 142 |
+
vaeloader = NODE_CLASS_MAPPINGS["VAELoader"]()
|
| 143 |
+
vaeloader_10 = vaeloader.load_vae(vae_name="ae.safetensors")
|
| 144 |
+
|
| 145 |
+
unetloader = NODE_CLASS_MAPPINGS["UNETLoader"]()
|
| 146 |
+
unetloader_12 = unetloader.load_unet(
|
| 147 |
+
unet_name="flux1-dev.safetensors", weight_dtype="default"
|
| 148 |
+
)
|
| 149 |
+
|
| 150 |
+
ksamplerselect = NODE_CLASS_MAPPINGS["KSamplerSelect"]()
|
| 151 |
+
ksamplerselect_16 = ksamplerselect.get_sampler(sampler_name="dpmpp_2m")
|
| 152 |
+
|
| 153 |
+
randomnoise = NODE_CLASS_MAPPINGS["RandomNoise"]()
|
| 154 |
+
randomnoise_25 = randomnoise.get_noise(noise_seed='42')
|
| 155 |
+
|
| 156 |
+
loraloadermodelonly = NODE_CLASS_MAPPINGS["LoraLoaderModelOnly"]()
|
| 157 |
+
loraloadermodelonly_72 = loraloadermodelonly.load_lora_model_only(
|
| 158 |
+
lora_name='lora_weights/lora_weight_rank_32_alpha_32.safetensors',
|
| 159 |
+
strength_model=1,
|
| 160 |
+
model=get_value_at_index(unetloader_12, 0),
|
| 161 |
+
)
|
| 162 |
+
|
| 163 |
+
cr_sdxl_aspect_ratio = NODE_CLASS_MAPPINGS["CR SDXL Aspect Ratio"]()
|
| 164 |
+
cr_sdxl_aspect_ratio_85 = cr_sdxl_aspect_ratio.Aspect_Ratio(
|
| 165 |
+
width=1024,
|
| 166 |
+
height=1024,
|
| 167 |
+
aspect_ratio="4:3 landscape 1152x896",
|
| 168 |
+
swap_dimensions="Off",
|
| 169 |
+
upscale_factor=1.5,
|
| 170 |
+
batch_size=1,
|
| 171 |
+
)
|
| 172 |
+
|
| 173 |
+
modelsamplingflux = NODE_CLASS_MAPPINGS["ModelSamplingFlux"]()
|
| 174 |
+
fluxguidance = NODE_CLASS_MAPPINGS["FluxGuidance"]()
|
| 175 |
+
basicguider = NODE_CLASS_MAPPINGS["BasicGuider"]()
|
| 176 |
+
basicscheduler = NODE_CLASS_MAPPINGS["BasicScheduler"]()
|
| 177 |
+
samplercustomadvanced = NODE_CLASS_MAPPINGS["SamplerCustomAdvanced"]()
|
| 178 |
+
vaedecode = NODE_CLASS_MAPPINGS["VAEDecode"]()
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
def model_loading():
|
| 182 |
+
# loraloadermodelonly = NODE_CLASS_MAPPINGS["LoraLoaderModelOnly"]()
|
| 183 |
+
# loraloadermodelonly_72 = loraloadermodelonly.load_lora_model_only(
|
| 184 |
+
# lora_name=lora_weight_path,
|
| 185 |
+
# strength_model=1,
|
| 186 |
+
# model=get_value_at_index(unetloader_12, 0),
|
| 187 |
+
# )
|
| 188 |
+
model_loaders = [dualcliploader_11, vaeloader_10, unetloader_12, loraloadermodelonly_72]
|
| 189 |
+
valid_models = [
|
| 190 |
+
getattr(loader[0], 'patcher', loader[0])
|
| 191 |
+
for loader in model_loaders
|
| 192 |
+
if not isinstance(loader[0], dict) and not isinstance(getattr(loader[0], 'patcher', None), dict)
|
| 193 |
+
]
|
| 194 |
+
#Load the models
|
| 195 |
+
# model_management.load_models_gpu(valid_models)
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
def generate_image(prompt,
|
| 199 |
+
height,
|
| 200 |
+
width,
|
| 201 |
+
guidance_scale,
|
| 202 |
+
aspect_ratio,
|
| 203 |
+
seed,
|
| 204 |
+
num_inference_steps,
|
| 205 |
+
):
|
| 206 |
+
cliptextencode = NODE_CLASS_MAPPINGS["CLIPTextEncode"]()
|
| 207 |
+
cliptextencode_6 = cliptextencode.encode(
|
| 208 |
+
text=prompt,
|
| 209 |
+
clip=get_value_at_index(dualcliploader_11, 0),
|
| 210 |
+
)
|
| 211 |
+
cr_sdxl_aspect_ratio = NODE_CLASS_MAPPINGS["CR SDXL Aspect Ratio"]()
|
| 212 |
+
cr_sdxl_aspect_ratio_85 = cr_sdxl_aspect_ratio.Aspect_Ratio(
|
| 213 |
+
width=width,
|
| 214 |
+
height=height,
|
| 215 |
+
aspect_ratio=aspect_ratio,
|
| 216 |
+
swap_dimensions="Off",
|
| 217 |
+
upscale_factor=1.5,
|
| 218 |
+
batch_size=1,
|
| 219 |
+
)
|
| 220 |
+
with torch.inference_mode():
|
| 221 |
+
for q in range(1):
|
| 222 |
+
modelsamplingflux_61 = modelsamplingflux.patch(
|
| 223 |
+
max_shift=1.15,
|
| 224 |
+
base_shift=0.5,
|
| 225 |
+
width=get_value_at_index(cr_sdxl_aspect_ratio_85, 0),
|
| 226 |
+
height=get_value_at_index(cr_sdxl_aspect_ratio_85, 1),
|
| 227 |
+
model=get_value_at_index(loraloadermodelonly_72, 0),
|
| 228 |
+
)
|
| 229 |
+
|
| 230 |
+
fluxguidance_60 = fluxguidance.append(
|
| 231 |
+
guidance=guidance_scale, conditioning=get_value_at_index(cliptextencode_6, 0)
|
| 232 |
+
)
|
| 233 |
+
|
| 234 |
+
basicguider_22 = basicguider.get_guider(
|
| 235 |
+
model=get_value_at_index(modelsamplingflux_61, 0),
|
| 236 |
+
conditioning=get_value_at_index(fluxguidance_60, 0),
|
| 237 |
+
)
|
| 238 |
+
|
| 239 |
+
basicscheduler_17 = basicscheduler.get_sigmas(
|
| 240 |
+
scheduler="sgm_uniform",
|
| 241 |
+
steps=num_inference_steps,
|
| 242 |
+
denoise=1,
|
| 243 |
+
model=get_value_at_index(modelsamplingflux_61, 0),
|
| 244 |
+
)
|
| 245 |
+
|
| 246 |
+
samplercustomadvanced_13 = samplercustomadvanced.sample(
|
| 247 |
+
noise=get_value_at_index(randomnoise_25, 0),
|
| 248 |
+
guider=get_value_at_index(basicguider_22, 0),
|
| 249 |
+
sampler=get_value_at_index(ksamplerselect_16, 0),
|
| 250 |
+
sigmas=get_value_at_index(basicscheduler_17, 0),
|
| 251 |
+
latent_image=get_value_at_index(cr_sdxl_aspect_ratio_85, 4),
|
| 252 |
+
)
|
| 253 |
+
|
| 254 |
+
vaedecode_8 = vaedecode.decode(
|
| 255 |
+
samples=get_value_at_index(samplercustomadvanced_13, 0),
|
| 256 |
+
vae=get_value_at_index(vaeloader_10, 0),
|
| 257 |
+
)
|
| 258 |
+
|
| 259 |
+
# saveimage_9 = saveimage.save_images(
|
| 260 |
+
# filename_prefix="MarkuryFLUX", images=get_value_at_index(vaedecode_8, 0)
|
| 261 |
+
# )
|
| 262 |
+
return get_value_at_index(vaedecode_8, 0), seed
|