Delete demo_gr.py
Browse files- demo_gr.py +0 -262
demo_gr.py
DELETED
|
@@ -1,262 +0,0 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import time
|
| 3 |
-
import uuid
|
| 4 |
-
|
| 5 |
-
import gradio as gr
|
| 6 |
-
import numpy as np
|
| 7 |
-
import torch
|
| 8 |
-
from einops import rearrange
|
| 9 |
-
from PIL import ExifTags, Image
|
| 10 |
-
from transformers import pipeline
|
| 11 |
-
|
| 12 |
-
from flux.cli import SamplingOptions
|
| 13 |
-
from flux.sampling import denoise, get_noise, get_schedule, prepare, unpack
|
| 14 |
-
from flux.util import (
|
| 15 |
-
configs,
|
| 16 |
-
embed_watermark,
|
| 17 |
-
load_ae,
|
| 18 |
-
load_clip,
|
| 19 |
-
load_flow_model,
|
| 20 |
-
load_t5,
|
| 21 |
-
track_usage_via_api,
|
| 22 |
-
)
|
| 23 |
-
|
| 24 |
-
NSFW_THRESHOLD = 0.85
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
def get_models(name: str, device: torch.device, offload: bool, is_schnell: bool):
|
| 28 |
-
t5 = load_t5(device, max_length=256 if is_schnell else 512)
|
| 29 |
-
clip = load_clip(device)
|
| 30 |
-
model = load_flow_model(name, device="cpu" if offload else device)
|
| 31 |
-
ae = load_ae(name, device="cpu" if offload else device)
|
| 32 |
-
nsfw_classifier = pipeline("image-classification", model="Falconsai/nsfw_image_detection", device=device)
|
| 33 |
-
return model, ae, t5, clip, nsfw_classifier
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
class FluxGenerator:
|
| 37 |
-
def __init__(self, model_name: str, device: str, offload: bool, track_usage: bool):
|
| 38 |
-
self.device = torch.device(device)
|
| 39 |
-
self.offload = offload
|
| 40 |
-
self.model_name = model_name
|
| 41 |
-
self.is_schnell = model_name == "flux-schnell"
|
| 42 |
-
self.model, self.ae, self.t5, self.clip, self.nsfw_classifier = get_models(
|
| 43 |
-
model_name,
|
| 44 |
-
device=self.device,
|
| 45 |
-
offload=self.offload,
|
| 46 |
-
is_schnell=self.is_schnell,
|
| 47 |
-
)
|
| 48 |
-
self.track_usage = track_usage
|
| 49 |
-
|
| 50 |
-
@torch.inference_mode()
|
| 51 |
-
def generate_image(
|
| 52 |
-
self,
|
| 53 |
-
width,
|
| 54 |
-
height,
|
| 55 |
-
num_steps,
|
| 56 |
-
guidance,
|
| 57 |
-
seed,
|
| 58 |
-
prompt,
|
| 59 |
-
init_image=None,
|
| 60 |
-
image2image_strength=0.0,
|
| 61 |
-
add_sampling_metadata=True,
|
| 62 |
-
):
|
| 63 |
-
seed = int(seed)
|
| 64 |
-
if seed == -1:
|
| 65 |
-
seed = None
|
| 66 |
-
|
| 67 |
-
opts = SamplingOptions(
|
| 68 |
-
prompt=prompt,
|
| 69 |
-
width=width,
|
| 70 |
-
height=height,
|
| 71 |
-
num_steps=num_steps,
|
| 72 |
-
guidance=guidance,
|
| 73 |
-
seed=seed,
|
| 74 |
-
)
|
| 75 |
-
|
| 76 |
-
if opts.seed is None:
|
| 77 |
-
opts.seed = torch.Generator(device="cpu").seed()
|
| 78 |
-
print(f"Generating '{opts.prompt}' with seed {opts.seed}")
|
| 79 |
-
t0 = time.perf_counter()
|
| 80 |
-
|
| 81 |
-
if init_image is not None:
|
| 82 |
-
if isinstance(init_image, np.ndarray):
|
| 83 |
-
init_image = torch.from_numpy(init_image).permute(2, 0, 1).float() / 255.0
|
| 84 |
-
init_image = init_image.unsqueeze(0)
|
| 85 |
-
init_image = init_image.to(self.device)
|
| 86 |
-
init_image = torch.nn.functional.interpolate(init_image, (opts.height, opts.width))
|
| 87 |
-
if self.offload:
|
| 88 |
-
self.ae.encoder.to(self.device)
|
| 89 |
-
init_image = self.ae.encode(init_image.to())
|
| 90 |
-
if self.offload:
|
| 91 |
-
self.ae = self.ae.cpu()
|
| 92 |
-
torch.cuda.empty_cache()
|
| 93 |
-
|
| 94 |
-
# prepare input
|
| 95 |
-
x = get_noise(
|
| 96 |
-
1,
|
| 97 |
-
opts.height,
|
| 98 |
-
opts.width,
|
| 99 |
-
device=self.device,
|
| 100 |
-
dtype=torch.bfloat16,
|
| 101 |
-
seed=opts.seed,
|
| 102 |
-
)
|
| 103 |
-
timesteps = get_schedule(
|
| 104 |
-
opts.num_steps,
|
| 105 |
-
x.shape[-1] * x.shape[-2] // 4,
|
| 106 |
-
shift=(not self.is_schnell),
|
| 107 |
-
)
|
| 108 |
-
if init_image is not None:
|
| 109 |
-
t_idx = int((1 - image2image_strength) * num_steps)
|
| 110 |
-
t = timesteps[t_idx]
|
| 111 |
-
timesteps = timesteps[t_idx:]
|
| 112 |
-
x = t * x + (1.0 - t) * init_image.to(x.dtype)
|
| 113 |
-
|
| 114 |
-
if self.offload:
|
| 115 |
-
self.t5, self.clip = self.t5.to(self.device), self.clip.to(self.device)
|
| 116 |
-
inp = prepare(t5=self.t5, clip=self.clip, img=x, prompt=opts.prompt)
|
| 117 |
-
|
| 118 |
-
# offload TEs to CPU, load model to gpu
|
| 119 |
-
if self.offload:
|
| 120 |
-
self.t5, self.clip = self.t5.cpu(), self.clip.cpu()
|
| 121 |
-
torch.cuda.empty_cache()
|
| 122 |
-
self.model = self.model.to(self.device)
|
| 123 |
-
|
| 124 |
-
# denoise initial noise
|
| 125 |
-
x = denoise(self.model, **inp, timesteps=timesteps, guidance=opts.guidance)
|
| 126 |
-
|
| 127 |
-
# offload model, load autoencoder to gpu
|
| 128 |
-
if self.offload:
|
| 129 |
-
self.model.cpu()
|
| 130 |
-
torch.cuda.empty_cache()
|
| 131 |
-
self.ae.decoder.to(x.device)
|
| 132 |
-
|
| 133 |
-
# decode latents to pixel space
|
| 134 |
-
x = unpack(x.float(), opts.height, opts.width)
|
| 135 |
-
with torch.autocast(device_type=self.device.type, dtype=torch.bfloat16):
|
| 136 |
-
x = self.ae.decode(x)
|
| 137 |
-
|
| 138 |
-
if self.offload:
|
| 139 |
-
self.ae.decoder.cpu()
|
| 140 |
-
torch.cuda.empty_cache()
|
| 141 |
-
|
| 142 |
-
t1 = time.perf_counter()
|
| 143 |
-
|
| 144 |
-
print(f"Done in {t1 - t0:.1f}s.")
|
| 145 |
-
# bring into PIL format
|
| 146 |
-
x = x.clamp(-1, 1)
|
| 147 |
-
x = embed_watermark(x.float())
|
| 148 |
-
x = rearrange(x[0], "c h w -> h w c")
|
| 149 |
-
|
| 150 |
-
img = Image.fromarray((127.5 * (x + 1.0)).cpu().byte().numpy())
|
| 151 |
-
nsfw_score = [x["score"] for x in self.nsfw_classifier(img) if x["label"] == "nsfw"][0]
|
| 152 |
-
|
| 153 |
-
if nsfw_score < NSFW_THRESHOLD:
|
| 154 |
-
filename = f"output/gradio/{uuid.uuid4()}.jpg"
|
| 155 |
-
os.makedirs(os.path.dirname(filename), exist_ok=True)
|
| 156 |
-
exif_data = Image.Exif()
|
| 157 |
-
if init_image is None:
|
| 158 |
-
exif_data[ExifTags.Base.Software] = "AI generated;txt2img;flux"
|
| 159 |
-
else:
|
| 160 |
-
exif_data[ExifTags.Base.Software] = "AI generated;img2img;flux"
|
| 161 |
-
exif_data[ExifTags.Base.Make] = "Black Forest Labs"
|
| 162 |
-
exif_data[ExifTags.Base.Model] = self.model_name
|
| 163 |
-
if add_sampling_metadata:
|
| 164 |
-
exif_data[ExifTags.Base.ImageDescription] = prompt
|
| 165 |
-
img.save(filename, format="jpeg", exif=exif_data, quality=95, subsampling=0)
|
| 166 |
-
|
| 167 |
-
if self.track_usage:
|
| 168 |
-
track_usage_via_api(self.model_name, 1)
|
| 169 |
-
|
| 170 |
-
return img, str(opts.seed), filename, None
|
| 171 |
-
else:
|
| 172 |
-
return None, str(opts.seed), None, "Your generated image may contain NSFW content."
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
def create_demo(
|
| 176 |
-
model_name: str,
|
| 177 |
-
device: str = "cuda" if torch.cuda.is_available() else "cpu",
|
| 178 |
-
offload: bool = False,
|
| 179 |
-
track_usage: bool = False,
|
| 180 |
-
):
|
| 181 |
-
generator = FluxGenerator(model_name, device, offload, track_usage)
|
| 182 |
-
is_schnell = model_name == "flux-schnell"
|
| 183 |
-
|
| 184 |
-
with gr.Blocks() as demo:
|
| 185 |
-
gr.Markdown(f"# Flux Image Generation Demo - Model: {model_name}")
|
| 186 |
-
|
| 187 |
-
with gr.Row():
|
| 188 |
-
with gr.Column():
|
| 189 |
-
prompt = gr.Textbox(
|
| 190 |
-
label="Prompt",
|
| 191 |
-
value='a photo of a forest with mist swirling around the tree trunks. The word "FLUX" is painted over it in big, red brush strokes with visible texture',
|
| 192 |
-
)
|
| 193 |
-
do_img2img = gr.Checkbox(label="Image to Image", value=False, interactive=not is_schnell)
|
| 194 |
-
init_image = gr.Image(label="Input Image", visible=False)
|
| 195 |
-
image2image_strength = gr.Slider(
|
| 196 |
-
0.0, 1.0, 0.8, step=0.1, label="Noising strength", visible=False
|
| 197 |
-
)
|
| 198 |
-
|
| 199 |
-
with gr.Accordion("Advanced Options", open=False):
|
| 200 |
-
width = gr.Slider(128, 8192, 1360, step=16, label="Width")
|
| 201 |
-
height = gr.Slider(128, 8192, 768, step=16, label="Height")
|
| 202 |
-
num_steps = gr.Slider(1, 50, 4 if is_schnell else 50, step=1, label="Number of steps")
|
| 203 |
-
guidance = gr.Slider(
|
| 204 |
-
1.0, 10.0, 3.5, step=0.1, label="Guidance", interactive=not is_schnell
|
| 205 |
-
)
|
| 206 |
-
seed = gr.Textbox(-1, label="Seed (-1 for random)")
|
| 207 |
-
add_sampling_metadata = gr.Checkbox(
|
| 208 |
-
label="Add sampling parameters to metadata?", value=True
|
| 209 |
-
)
|
| 210 |
-
|
| 211 |
-
generate_btn = gr.Button("Generate")
|
| 212 |
-
|
| 213 |
-
with gr.Column():
|
| 214 |
-
output_image = gr.Image(label="Generated Image")
|
| 215 |
-
seed_output = gr.Number(label="Used Seed")
|
| 216 |
-
warning_text = gr.Textbox(label="Warning", visible=False)
|
| 217 |
-
download_btn = gr.File(label="Download full-resolution")
|
| 218 |
-
|
| 219 |
-
def update_img2img(do_img2img):
|
| 220 |
-
return {
|
| 221 |
-
init_image: gr.update(visible=do_img2img),
|
| 222 |
-
image2image_strength: gr.update(visible=do_img2img),
|
| 223 |
-
}
|
| 224 |
-
|
| 225 |
-
do_img2img.change(update_img2img, do_img2img, [init_image, image2image_strength])
|
| 226 |
-
|
| 227 |
-
generate_btn.click(
|
| 228 |
-
fn=generator.generate_image,
|
| 229 |
-
inputs=[
|
| 230 |
-
width,
|
| 231 |
-
height,
|
| 232 |
-
num_steps,
|
| 233 |
-
guidance,
|
| 234 |
-
seed,
|
| 235 |
-
prompt,
|
| 236 |
-
init_image,
|
| 237 |
-
image2image_strength,
|
| 238 |
-
add_sampling_metadata,
|
| 239 |
-
],
|
| 240 |
-
outputs=[output_image, seed_output, download_btn, warning_text],
|
| 241 |
-
)
|
| 242 |
-
|
| 243 |
-
return demo
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
if __name__ == "__main__":
|
| 247 |
-
import argparse
|
| 248 |
-
|
| 249 |
-
parser = argparse.ArgumentParser(description="Flux")
|
| 250 |
-
parser.add_argument(
|
| 251 |
-
"--name", type=str, default="flux-schnell", choices=list(configs.keys()), help="Model name"
|
| 252 |
-
)
|
| 253 |
-
parser.add_argument(
|
| 254 |
-
"--device", type=str, default="cuda" if torch.cuda.is_available() else "cpu", help="Device to use"
|
| 255 |
-
)
|
| 256 |
-
parser.add_argument("--offload", action="store_true", help="Offload model to CPU when not in use")
|
| 257 |
-
parser.add_argument("--share", action="store_true", help="Create a public link to your demo")
|
| 258 |
-
parser.add_argument("--track_usage", action="store_true", help="Track usage for licensing purposes")
|
| 259 |
-
args = parser.parse_args()
|
| 260 |
-
|
| 261 |
-
demo = create_demo(args.name, args.device, args.offload, args.track_usage)
|
| 262 |
-
demo.launch(share=args.share)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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