Spaces:
Running
on
Zero
Running
on
Zero
File size: 14,948 Bytes
1f5fa16 4f8d4c0 1f5fa16 4f5b8e3 2015dcc 4f8d4c0 1f5fa16 4f8d4c0 5bdb5dc 1f5fa16 4f8d4c0 1f5fa16 4f8d4c0 1f5fa16 4f8d4c0 1f5fa16 4f8d4c0 1f5fa16 4f8d4c0 8d08409 4f8d4c0 1f5fa16 4f8d4c0 5439aa4 b8d3d2d 5439aa4 1f5fa16 2015dcc 4f8d4c0 2015dcc bd40815 5439aa4 1f5fa16 5439aa4 1f5fa16 5439aa4 1f5fa16 5439aa4 1f5fa16 2015dcc 1f5fa16 4f8d4c0 5439aa4 4f8d4c0 1f5fa16 2015dcc 4f8d4c0 2015dcc 4f8d4c0 2015dcc 4f8d4c0 5439aa4 4f8d4c0 5439aa4 dd86f76 5439aa4 4f8d4c0 1f5fa16 4f8d4c0 1f5fa16 4f8d4c0 1f5fa16 2015dcc 4f8d4c0 2015dcc 4f8d4c0 1f5fa16 3cd5fe0 ce4c1b6 2015dcc ce4c1b6 4f8d4c0 ce4c1b6 5d64731 ce4c1b6 2015dcc ce4c1b6 4f8d4c0 1f5fa16 4f8d4c0 1f5fa16 4f8d4c0 1f5fa16 2015dcc 1f5fa16 4f8d4c0 1f5fa16 4f8d4c0 1f5fa16 5439aa4 1f5fa16 4f8d4c0 |
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 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 |
import spaces
import gradio as gr
import torch
from PIL import Image
from diffusers import DiffusionPipeline, QwenImageEditPipeline, FlowMatchEulerDiscreteScheduler
import random
import uuid
import numpy as np
import time
import zipfile
import os
import requests
from urllib.parse import urlparse
import tempfile
import shutil
import math
# --- App Description ---
DESCRIPTION = """## Qwen Image Hpc/."""
# --- Helper Functions for Both Tabs ---
MAX_SEED = np.iinfo(np.int32).max
def save_image(img):
"""Saves a PIL image to a temporary file with a unique name."""
unique_name = str(uuid.uuid4()) + ".png"
img.save(unique_name)
return unique_name
def randomize_seed_fn(seed: int, randomize_seed: bool) -> int:
"""Returns a random seed if randomize_seed is True, otherwise returns the original seed."""
if randomize_seed:
seed = random.randint(0, MAX_SEED)
return seed
# --- Model Loading ---
dtype = torch.bfloat16
device = "cuda" if torch.cuda.is_available() else "cpu"
# --- Qwen-Image-Gen Model ---
pipe_qwen_gen = DiffusionPipeline.from_pretrained(
"Qwen/Qwen-Image",
torch_dtype=dtype
).to(device)
# --- Qwen-Image-Edit Model with Lightning LoRA ---
scheduler_config = {
"base_image_seq_len": 256,
"base_shift": math.log(3),
"invert_sigmas": False,
"max_image_seq_len": 8192,
"max_shift": math.log(3),
"num_train_timesteps": 1000,
"shift": 1.0,
"shift_terminal": None,
"stochastic_sampling": False,
"time_shift_type": "exponential",
"use_beta_sigmas": False,
"use_dynamic_shifting": True,
"use_exponential_sigmas": False,
"use_karras_sigmas": False,
}
scheduler = FlowMatchEulerDiscreteScheduler.from_config(scheduler_config)
pipe_qwen_edit = QwenImageEditPipeline.from_pretrained(
"Qwen/Qwen-Image-Edit",
scheduler=scheduler,
torch_dtype=dtype
).to(device)
try:
pipe_qwen_edit.load_lora_weights(
"lightx2v/Qwen-Image-Lightning",
weight_name="Qwen-Image-Lightning-8steps-V1.1.safetensors"
)
pipe_qwen_edit.fuse_lora()
print("Successfully loaded Lightning LoRA weights for Qwen-Image-Edit")
except Exception as e:
print(f"Warning: Could not load Lightning LoRA weights for Qwen-Image-Edit: {e}")
print("Continuing with the base Qwen-Image-Edit model...")
# --- Qwen-Image-Gen Functions ---
aspect_ratios = {
"1:1": (1328, 1328),
"16:9": (1664, 928),
"9:16": (928, 1664),
"4:3": (1472, 1140),
"3:4": (1140, 1472)
}
def load_lora_opt(pipe, lora_input):
"""Loads a LoRA from a local path, Hugging Face repo, or URL."""
lora_input = lora_input.strip()
if not lora_input:
return
if "/" in lora_input and not lora_input.startswith("http"):
pipe.load_lora_weights(lora_input, adapter_name="default")
return
if lora_input.startswith("http"):
url = lora_input
if "huggingface.co" in url and "/blob/" not in url and "/resolve/" not in url:
repo_id = urlparse(url).path.strip("/")
pipe.load_lora_weights(repo_id, adapter_name="default")
return
if "/blob/" in url:
url = url.replace("/blob/", "/resolve/")
tmp_dir = tempfile.mkdtemp()
local_path = os.path.join(tmp_dir, os.path.basename(urlparse(url).path))
try:
print(f"Downloading LoRA from {url}...")
resp = requests.get(url, stream=True)
resp.raise_for_status()
with open(local_path, "wb") as f:
for chunk in resp.iter_content(chunk_size=8192):
f.write(chunk)
print(f"Saved LoRA to {local_path}")
pipe.load_lora_weights(local_path, adapter_name="default")
finally:
shutil.rmtree(tmp_dir, ignore_errors=True)
@spaces.GPU(duration=120)
def generate_qwen(
prompt: str,
negative_prompt: str = "",
seed: int = 0,
width: int = 1024,
height: int = 1024,
guidance_scale: float = 4.0,
randomize_seed: bool = False,
num_inference_steps: int = 50,
num_images: int = 1,
zip_images: bool = False,
lora_input: str = "",
lora_scale: float = 1.0,
progress=gr.Progress(track_tqdm=True),
):
"""Main generation function for Qwen-Image-Gen."""
seed = randomize_seed_fn(seed, randomize_seed)
generator = torch.Generator(device).manual_seed(seed)
start_time = time.time()
current_adapters = pipe_qwen_gen.get_list_adapters()
for adapter in current_adapters:
pipe_qwen_gen.delete_adapters(adapter)
pipe_qwen_gen.disable_lora()
if lora_input and lora_input.strip() != "":
load_lora_opt(pipe_qwen_gen, lora_input)
pipe_qwen_gen.set_adapters(["default"], adapter_weights=[lora_scale])
images = pipe_qwen_gen(
prompt=prompt,
negative_prompt=negative_prompt if negative_prompt else " ",
height=height,
width=width,
guidance_scale=guidance_scale,
num_inference_steps=num_inference_steps,
num_images_per_prompt=num_images,
generator=generator,
).images
end_time = time.time()
duration = end_time - start_time
image_paths = [save_image(img) for img in images]
zip_path = None
if zip_images and len(image_paths) > 0:
zip_name = str(uuid.uuid4()) + ".zip"
with zipfile.ZipFile(zip_name, 'w') as zipf:
for i, img_path in enumerate(image_paths):
zipf.write(img_path, arcname=f"Img_{i}.png")
zip_path = zip_name
current_adapters = pipe_qwen_gen.get_list_adapters()
for adapter in current_adapters:
pipe_qwen_gen.delete_adapters(adapter)
pipe_qwen_gen.disable_lora()
return image_paths, seed, f"{duration:.2f}", zip_path
@spaces.GPU(duration=120)
def generate(
prompt: str,
negative_prompt: str,
use_negative_prompt: bool,
seed: int,
width: int,
height: int,
guidance_scale: float,
randomize_seed: bool,
num_inference_steps: int,
num_images: int,
zip_images: bool,
lora_input: str,
lora_scale: float,
progress=gr.Progress(track_tqdm=True),
):
"""UI wrapper for the Qwen-Image-Gen generation function."""
final_negative_prompt = negative_prompt if use_negative_prompt else ""
return generate_qwen(
prompt=prompt,
negative_prompt=final_negative_prompt,
seed=seed,
width=width,
height=height,
guidance_scale=guidance_scale,
randomize_seed=randomize_seed,
num_inference_steps=num_inference_steps,
num_images=num_images,
zip_images=zip_images,
lora_input=lora_input,
lora_scale=lora_scale,
progress=progress,
)
# --- Qwen-Image-Edit Functions ---
@spaces.GPU(duration=60)
def infer_edit(
image,
prompt,
seed=42,
randomize_seed=False,
true_guidance_scale=1.0,
num_inference_steps=8,
progress=gr.Progress(track_tqdm=True),
):
"""Main inference function for Qwen-Image-Edit."""
if image is None:
raise gr.Error("Please upload an image to edit.")
negative_prompt = " "
seed = randomize_seed_fn(seed, randomize_seed)
generator = torch.Generator(device=device).manual_seed(seed)
print(f"Original prompt: '{prompt}'")
print(f"Negative Prompt: '{negative_prompt}'")
print(f"Seed: {seed}, Steps: {num_inference_steps}, Guidance: {true_guidance_scale}")
try:
images = pipe_qwen_edit(
image,
prompt=prompt,
negative_prompt=negative_prompt,
num_inference_steps=num_inference_steps,
generator=generator,
true_cfg_scale=true_guidance_scale,
num_images_per_prompt=1
).images
return images[0], seed
except Exception as e:
print(f"Error during inference: {e}")
raise gr.Error(f"An error occurred during image editing: {e}")
# --- Gradio UI ---
css = '''
.gradio-container {
max-width: 800px !important;
margin: 0 auto !important;
}
h1 {
text-align: center;
}
footer {
visibility: hidden;
}
'''
with gr.Blocks(css=css, theme="bethecloud/storj_theme", delete_cache=(240, 240)) as demo:
gr.Markdown(DESCRIPTION)
with gr.Tabs():
with gr.TabItem("Qwen-Image-Gen"):
with gr.Column():
with gr.Row():
prompt_gen = gr.Text(
label="Prompt",
show_label=False,
max_lines=1,
placeholder="✦︎ Enter your prompt for generation",
container=False,
)
run_button_gen = gr.Button("Generate", scale=0, variant="primary")
result_gen = gr.Gallery(label="Result", columns=2, show_label=False, preview=True, height="auto")
with gr.Row():
aspect_ratio_gen = gr.Dropdown(
label="Aspect Ratio",
choices=list(aspect_ratios.keys()),
value="1:1",
)
lora_gen = gr.Textbox(label="Optional LoRA", placeholder="Enter Hugging Face repo ID or URL...")
with gr.Accordion("Additional Options", open=False):
use_negative_prompt_gen = gr.Checkbox(label="Use negative prompt", value=True)
negative_prompt_gen = gr.Text(
label="Negative prompt",
max_lines=1,
placeholder="Enter a negative prompt",
value="text, watermark, copyright, blurry, low resolution",
)
seed_gen = gr.Slider(label="Seed", minimum=0, maximum=MAX_SEED, step=1, value=0)
randomize_seed_gen = gr.Checkbox(label="Randomize seed", value=True)
with gr.Row():
width_gen = gr.Slider(label="Width", minimum=512, maximum=2048, step=64, value=1328)
height_gen = gr.Slider(label="Height", minimum=512, maximum=2048, step=64, value=1328)
guidance_scale_gen = gr.Slider(label="Guidance Scale", minimum=0.0, maximum=20.0, step=0.1, value=4.0)
num_inference_steps_gen = gr.Slider("Number of inference steps", 1, 100, 50, step=1)
num_images_gen = gr.Slider("Number of images", 1, 5, 1, step=1)
zip_images_gen = gr.Checkbox(label="Zip generated images", value=False)
with gr.Row():
lora_scale_gen = gr.Slider(label="LoRA Scale", minimum=0, maximum=2, step=0.01, value=1)
gr.Markdown("### Output Information")
seed_display_gen = gr.Textbox(label="Seed used", interactive=False)
generation_time_gen = gr.Textbox(label="Generation time (seconds)", interactive=False)
zip_file_gen = gr.File(label="Download ZIP")
# --- Gen Tab Logic ---
def set_dimensions(ar):
w, h = aspect_ratios[ar]
return gr.update(value=w), gr.update(value=h)
aspect_ratio_gen.change(fn=set_dimensions, inputs=aspect_ratio_gen, outputs=[width_gen, height_gen])
use_negative_prompt_gen.change(fn=lambda x: gr.update(visible=x), inputs=use_negative_prompt_gen, outputs=negative_prompt_gen)
gen_inputs = [
prompt_gen, negative_prompt_gen, use_negative_prompt_gen, seed_gen, width_gen, height_gen,
guidance_scale_gen, randomize_seed_gen, num_inference_steps_gen, num_images_gen,
zip_images_gen, lora_gen, lora_scale_gen
]
gen_outputs = [result_gen, seed_display_gen, generation_time_gen, zip_file_gen]
gr.on(triggers=[prompt_gen.submit, run_button_gen.click], fn=generate, inputs=gen_inputs, outputs=gen_outputs)
gen_examples = [
"A decadent slice of layered chocolate cake on a ceramic plate with a drizzle of chocolate syrup and powdered sugar dusted on top.",
"A young girl wearing school uniform stands in a classroom, writing on a chalkboard. The text 'Introducing Qwen-Image' appears in neat white chalk.",
"一幅精致细腻的工笔画,画面中心是一株蓬勃生长的红色牡丹,花朵繁茂。",
"Realistic still life photography style: A single, fresh apple, resting on a clean, soft-textured surface.",
]
gr.Examples(examples=gen_examples, inputs=prompt_gen, outputs=gen_outputs, fn=generate, cache_examples=False)
with gr.TabItem("Qwen-Image-Edit"):
with gr.Column():
with gr.Row():
input_image_edit = gr.Image(label="Input Image", type="pil", height=400)
result_edit = gr.Image(label="Result", type="pil", height=400)
with gr.Row():
prompt_edit = gr.Text(
label="Edit Instruction",
show_label=False,
placeholder="Describe the edit you want to make",
container=False,
)
run_button_edit = gr.Button("Edit", variant="primary")
with gr.Accordion("Advanced Settings", open=False):
seed_edit = gr.Slider(label="Seed", minimum=0, maximum=MAX_SEED, step=1, value=42)
randomize_seed_edit = gr.Checkbox(label="Randomize seed", value=True)
with gr.Row():
true_guidance_scale_edit = gr.Slider(
label="True guidance scale", minimum=1.0, maximum=10.0, step=0.1, value=1.0
)
num_inference_steps_edit = gr.Slider(
label="Inference steps (Lightning LoRA)", minimum=4, maximum=28, step=1, value=8
)
# --- Edit Tab Logic ---
edit_inputs = [
input_image_edit, prompt_edit, seed_edit, randomize_seed_edit,
true_guidance_scale_edit, num_inference_steps_edit
]
edit_outputs = [result_edit, seed_edit]
gr.on(triggers=[prompt_edit.submit, run_button_edit.click], fn=infer_edit, inputs=edit_inputs, outputs=edit_outputs)
edit_examples = [
["image-edit/cat.png", "make the cat wear sunglasses"],
["image-edit/girl.png", "change her hair to blonde"],
]
gr.Examples(examples=edit_examples, inputs=[input_image_edit, prompt_edit], outputs=edit_outputs, fn=infer_edit, cache_examples=True)
if __name__ == "__main__":
demo.queue(max_size=50).launch(share=False, debug=True) |