Spaces:
Running
on
Zero
Running
on
Zero
Update app.py
Browse files
app.py
CHANGED
|
@@ -2,10 +2,9 @@ import spaces
|
|
| 2 |
import gradio as gr
|
| 3 |
import torch
|
| 4 |
from PIL import Image
|
| 5 |
-
from diffusers import DiffusionPipeline
|
| 6 |
import random
|
| 7 |
import uuid
|
| 8 |
-
from typing import Union, List, Optional
|
| 9 |
import numpy as np
|
| 10 |
import time
|
| 11 |
import zipfile
|
|
@@ -14,32 +13,74 @@ import requests
|
|
| 14 |
from urllib.parse import urlparse
|
| 15 |
import tempfile
|
| 16 |
import shutil
|
|
|
|
| 17 |
|
| 18 |
-
#
|
| 19 |
DESCRIPTION = """## Qwen Image Hpc/."""
|
| 20 |
|
| 21 |
-
# Helper
|
|
|
|
|
|
|
| 22 |
def save_image(img):
|
|
|
|
| 23 |
unique_name = str(uuid.uuid4()) + ".png"
|
| 24 |
img.save(unique_name)
|
| 25 |
return unique_name
|
| 26 |
|
| 27 |
def randomize_seed_fn(seed: int, randomize_seed: bool) -> int:
|
|
|
|
| 28 |
if randomize_seed:
|
| 29 |
seed = random.randint(0, MAX_SEED)
|
| 30 |
return seed
|
| 31 |
|
| 32 |
-
|
| 33 |
-
MAX_IMAGE_SIZE = 2048
|
| 34 |
-
|
| 35 |
-
# Load Qwen/Qwen-Image pipeline
|
| 36 |
dtype = torch.bfloat16
|
| 37 |
-
device =
|
| 38 |
|
| 39 |
-
# --- Model
|
| 40 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
|
| 42 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
aspect_ratios = {
|
| 44 |
"1:1": (1328, 1328),
|
| 45 |
"16:9": (1664, 928),
|
|
@@ -49,29 +90,25 @@ aspect_ratios = {
|
|
| 49 |
}
|
| 50 |
|
| 51 |
def load_lora_opt(pipe, lora_input):
|
|
|
|
| 52 |
lora_input = lora_input.strip()
|
| 53 |
if not lora_input:
|
| 54 |
return
|
| 55 |
|
| 56 |
-
# If it's just an ID like "author/model"
|
| 57 |
if "/" in lora_input and not lora_input.startswith("http"):
|
| 58 |
pipe.load_lora_weights(lora_input, adapter_name="default")
|
| 59 |
return
|
| 60 |
|
| 61 |
if lora_input.startswith("http"):
|
| 62 |
url = lora_input
|
| 63 |
-
|
| 64 |
-
# Repo page (no blob/resolve)
|
| 65 |
if "huggingface.co" in url and "/blob/" not in url and "/resolve/" not in url:
|
| 66 |
repo_id = urlparse(url).path.strip("/")
|
| 67 |
pipe.load_lora_weights(repo_id, adapter_name="default")
|
| 68 |
return
|
| 69 |
|
| 70 |
-
# Blob link → convert to resolve link
|
| 71 |
if "/blob/" in url:
|
| 72 |
url = url.replace("/blob/", "/resolve/")
|
| 73 |
|
| 74 |
-
# Download direct file
|
| 75 |
tmp_dir = tempfile.mkdtemp()
|
| 76 |
local_path = os.path.join(tmp_dir, os.path.basename(urlparse(url).path))
|
| 77 |
|
|
@@ -87,7 +124,6 @@ def load_lora_opt(pipe, lora_input):
|
|
| 87 |
finally:
|
| 88 |
shutil.rmtree(tmp_dir, ignore_errors=True)
|
| 89 |
|
| 90 |
-
# Generation function for Qwen/Qwen-Image
|
| 91 |
@spaces.GPU(duration=120)
|
| 92 |
def generate_qwen(
|
| 93 |
prompt: str,
|
|
@@ -104,56 +140,51 @@ def generate_qwen(
|
|
| 104 |
lora_scale: float = 1.0,
|
| 105 |
progress=gr.Progress(track_tqdm=True),
|
| 106 |
):
|
| 107 |
-
|
| 108 |
-
|
| 109 |
generator = torch.Generator(device).manual_seed(seed)
|
| 110 |
-
|
| 111 |
start_time = time.time()
|
| 112 |
|
| 113 |
-
current_adapters =
|
| 114 |
for adapter in current_adapters:
|
| 115 |
-
|
| 116 |
-
|
| 117 |
|
| 118 |
-
use_lora = False
|
| 119 |
if lora_input and lora_input.strip() != "":
|
| 120 |
-
load_lora_opt(
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
images = pipe_qwen(
|
| 125 |
prompt=prompt,
|
| 126 |
-
negative_prompt=negative_prompt if negative_prompt else "",
|
| 127 |
height=height,
|
| 128 |
width=width,
|
| 129 |
guidance_scale=guidance_scale,
|
| 130 |
num_inference_steps=num_inference_steps,
|
| 131 |
num_images_per_prompt=num_images,
|
| 132 |
generator=generator,
|
| 133 |
-
output_type="pil",
|
| 134 |
).images
|
| 135 |
-
|
| 136 |
end_time = time.time()
|
| 137 |
duration = end_time - start_time
|
| 138 |
-
|
| 139 |
image_paths = [save_image(img) for img in images]
|
| 140 |
zip_path = None
|
| 141 |
-
if zip_images:
|
| 142 |
zip_name = str(uuid.uuid4()) + ".zip"
|
| 143 |
with zipfile.ZipFile(zip_name, 'w') as zipf:
|
| 144 |
for i, img_path in enumerate(image_paths):
|
| 145 |
zipf.write(img_path, arcname=f"Img_{i}.png")
|
| 146 |
zip_path = zip_name
|
| 147 |
|
| 148 |
-
|
| 149 |
-
current_adapters = pipe_qwen.get_list_adapters()
|
| 150 |
for adapter in current_adapters:
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
return image_paths, seed, f"{duration:.2f}", zip_path
|
| 155 |
|
| 156 |
-
# Wrapper function to handle UI logic
|
| 157 |
@spaces.GPU(duration=120)
|
| 158 |
def generate(
|
| 159 |
prompt: str,
|
|
@@ -171,6 +202,7 @@ def generate(
|
|
| 171 |
lora_scale: float,
|
| 172 |
progress=gr.Progress(track_tqdm=True),
|
| 173 |
):
|
|
|
|
| 174 |
final_negative_prompt = negative_prompt if use_negative_prompt else ""
|
| 175 |
return generate_qwen(
|
| 176 |
prompt=prompt,
|
|
@@ -188,19 +220,48 @@ def generate(
|
|
| 188 |
progress=progress,
|
| 189 |
)
|
| 190 |
|
| 191 |
-
#
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 200 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 201 |
css = '''
|
| 202 |
.gradio-container {
|
| 203 |
-
max-width:
|
| 204 |
margin: 0 auto !important;
|
| 205 |
}
|
| 206 |
h1 {
|
|
@@ -211,148 +272,123 @@ footer {
|
|
| 211 |
}
|
| 212 |
'''
|
| 213 |
|
| 214 |
-
# Gradio interface
|
| 215 |
with gr.Blocks(css=css, theme="bethecloud/storj_theme", delete_cache=(240, 240)) as demo:
|
| 216 |
gr.Markdown(DESCRIPTION)
|
| 217 |
-
with gr.Row():
|
| 218 |
-
prompt = gr.Text(
|
| 219 |
-
label="Prompt",
|
| 220 |
-
show_label=False,
|
| 221 |
-
max_lines=1,
|
| 222 |
-
placeholder="✦︎ Enter your prompt",
|
| 223 |
-
container=False,
|
| 224 |
-
)
|
| 225 |
-
run_button = gr.Button("Run", scale=0, variant="primary")
|
| 226 |
-
result = gr.Gallery(label="Result", columns=1, show_label=False, preview=True)
|
| 227 |
-
|
| 228 |
-
with gr.Row():
|
| 229 |
-
aspect_ratio = gr.Dropdown(
|
| 230 |
-
label="Aspect Ratio",
|
| 231 |
-
choices=list(aspect_ratios.keys()),
|
| 232 |
-
value="1:1",
|
| 233 |
-
)
|
| 234 |
-
lora = gr.Textbox(label="qwen image lora (optional)", placeholder="enter the path...")
|
| 235 |
-
with gr.Accordion("Additional Options", open=False):
|
| 236 |
-
use_negative_prompt = gr.Checkbox(
|
| 237 |
-
label="Use negative prompt",
|
| 238 |
-
value=True,
|
| 239 |
-
visible=True
|
| 240 |
-
)
|
| 241 |
-
negative_prompt = gr.Text(
|
| 242 |
-
label="Negative prompt",
|
| 243 |
-
max_lines=1,
|
| 244 |
-
placeholder="Enter a negative prompt",
|
| 245 |
-
value="text, watermark, copyright, blurry, low resolution",
|
| 246 |
-
visible=True,
|
| 247 |
-
)
|
| 248 |
-
seed = gr.Slider(
|
| 249 |
-
label="Seed",
|
| 250 |
-
minimum=0,
|
| 251 |
-
maximum=MAX_SEED,
|
| 252 |
-
step=1,
|
| 253 |
-
value=0,
|
| 254 |
-
)
|
| 255 |
-
randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
|
| 256 |
-
with gr.Row():
|
| 257 |
-
width = gr.Slider(
|
| 258 |
-
label="Width",
|
| 259 |
-
minimum=512,
|
| 260 |
-
maximum=2048,
|
| 261 |
-
step=64,
|
| 262 |
-
value=1024,
|
| 263 |
-
)
|
| 264 |
-
height = gr.Slider(
|
| 265 |
-
label="Height",
|
| 266 |
-
minimum=512,
|
| 267 |
-
maximum=2048,
|
| 268 |
-
step=64,
|
| 269 |
-
value=1024,
|
| 270 |
-
)
|
| 271 |
-
guidance_scale = gr.Slider(
|
| 272 |
-
label="Guidance Scale",
|
| 273 |
-
minimum=0.0,
|
| 274 |
-
maximum=20.0,
|
| 275 |
-
step=0.1,
|
| 276 |
-
value=4.0,
|
| 277 |
-
)
|
| 278 |
-
num_inference_steps = gr.Slider(
|
| 279 |
-
label="Number of inference steps",
|
| 280 |
-
minimum=1,
|
| 281 |
-
maximum=100,
|
| 282 |
-
step=1,
|
| 283 |
-
value=50,
|
| 284 |
-
)
|
| 285 |
-
num_images = gr.Slider(
|
| 286 |
-
label="Number of images",
|
| 287 |
-
minimum=1,
|
| 288 |
-
maximum=5,
|
| 289 |
-
step=1,
|
| 290 |
-
value=1,
|
| 291 |
-
)
|
| 292 |
-
zip_images = gr.Checkbox(label="Zip generated images", value=False)
|
| 293 |
-
with gr.Row():
|
| 294 |
-
lora_scale = gr.Slider(
|
| 295 |
-
label="LoRA Scale",
|
| 296 |
-
minimum=0,
|
| 297 |
-
maximum=2,
|
| 298 |
-
step=0.01,
|
| 299 |
-
value=1,
|
| 300 |
-
)
|
| 301 |
-
|
| 302 |
-
gr.Markdown("### Output Information")
|
| 303 |
-
seed_display = gr.Textbox(label="Seed used", interactive=False)
|
| 304 |
-
generation_time = gr.Textbox(label="Generation time (seconds)", interactive=False)
|
| 305 |
-
zip_file = gr.File(label="Download ZIP")
|
| 306 |
-
|
| 307 |
-
# Update aspect ratio
|
| 308 |
-
def set_dimensions(ar):
|
| 309 |
-
w, h = aspect_ratios[ar]
|
| 310 |
-
return gr.update(value=w), gr.update(value=h)
|
| 311 |
-
|
| 312 |
-
aspect_ratio.change(
|
| 313 |
-
fn=set_dimensions,
|
| 314 |
-
inputs=aspect_ratio,
|
| 315 |
-
outputs=[width, height]
|
| 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 |
-
# Examples
|
| 349 |
-
gr.Examples(
|
| 350 |
-
examples=examples,
|
| 351 |
-
inputs=prompt,
|
| 352 |
-
outputs=[result, seed_display, generation_time, zip_file],
|
| 353 |
-
fn=generate,
|
| 354 |
-
cache_examples=False,
|
| 355 |
-
)
|
| 356 |
|
| 357 |
if __name__ == "__main__":
|
| 358 |
-
demo.queue(max_size=50).launch(share=False,
|
|
|
|
| 2 |
import gradio as gr
|
| 3 |
import torch
|
| 4 |
from PIL import Image
|
| 5 |
+
from diffusers import DiffusionPipeline, QwenImageEditPipeline, FlowMatchEulerDiscreteScheduler
|
| 6 |
import random
|
| 7 |
import uuid
|
|
|
|
| 8 |
import numpy as np
|
| 9 |
import time
|
| 10 |
import zipfile
|
|
|
|
| 13 |
from urllib.parse import urlparse
|
| 14 |
import tempfile
|
| 15 |
import shutil
|
| 16 |
+
import math
|
| 17 |
|
| 18 |
+
# --- App Description ---
|
| 19 |
DESCRIPTION = """## Qwen Image Hpc/."""
|
| 20 |
|
| 21 |
+
# --- Helper Functions for Both Tabs ---
|
| 22 |
+
MAX_SEED = np.iinfo(np.int32).max
|
| 23 |
+
|
| 24 |
def save_image(img):
|
| 25 |
+
"""Saves a PIL image to a temporary file with a unique name."""
|
| 26 |
unique_name = str(uuid.uuid4()) + ".png"
|
| 27 |
img.save(unique_name)
|
| 28 |
return unique_name
|
| 29 |
|
| 30 |
def randomize_seed_fn(seed: int, randomize_seed: bool) -> int:
|
| 31 |
+
"""Returns a random seed if randomize_seed is True, otherwise returns the original seed."""
|
| 32 |
if randomize_seed:
|
| 33 |
seed = random.randint(0, MAX_SEED)
|
| 34 |
return seed
|
| 35 |
|
| 36 |
+
# --- Model Loading ---
|
|
|
|
|
|
|
|
|
|
| 37 |
dtype = torch.bfloat16
|
| 38 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 39 |
|
| 40 |
+
# --- Qwen-Image-Gen Model ---
|
| 41 |
+
pipe_qwen_gen = DiffusionPipeline.from_pretrained(
|
| 42 |
+
"Qwen/Qwen-Image",
|
| 43 |
+
torch_dtype=dtype
|
| 44 |
+
).to(device)
|
| 45 |
+
|
| 46 |
+
# --- Qwen-Image-Edit Model with Lightning LoRA ---
|
| 47 |
+
scheduler_config = {
|
| 48 |
+
"base_image_seq_len": 256,
|
| 49 |
+
"base_shift": math.log(3),
|
| 50 |
+
"invert_sigmas": False,
|
| 51 |
+
"max_image_seq_len": 8192,
|
| 52 |
+
"max_shift": math.log(3),
|
| 53 |
+
"num_train_timesteps": 1000,
|
| 54 |
+
"shift": 1.0,
|
| 55 |
+
"shift_terminal": None,
|
| 56 |
+
"stochastic_sampling": False,
|
| 57 |
+
"time_shift_type": "exponential",
|
| 58 |
+
"use_beta_sigmas": False,
|
| 59 |
+
"use_dynamic_shifting": True,
|
| 60 |
+
"use_exponential_sigmas": False,
|
| 61 |
+
"use_karras_sigmas": False,
|
| 62 |
+
}
|
| 63 |
+
scheduler = FlowMatchEulerDiscreteScheduler.from_config(scheduler_config)
|
| 64 |
|
| 65 |
+
pipe_qwen_edit = QwenImageEditPipeline.from_pretrained(
|
| 66 |
+
"Qwen/Qwen-Image-Edit",
|
| 67 |
+
scheduler=scheduler,
|
| 68 |
+
torch_dtype=dtype
|
| 69 |
+
).to(device)
|
| 70 |
+
|
| 71 |
+
try:
|
| 72 |
+
pipe_qwen_edit.load_lora_weights(
|
| 73 |
+
"lightx2v/Qwen-Image-Lightning",
|
| 74 |
+
weight_name="Qwen-Image-Lightning-8steps-V1.1.safetensors"
|
| 75 |
+
)
|
| 76 |
+
pipe_qwen_edit.fuse_lora()
|
| 77 |
+
print("Successfully loaded Lightning LoRA weights for Qwen-Image-Edit")
|
| 78 |
+
except Exception as e:
|
| 79 |
+
print(f"Warning: Could not load Lightning LoRA weights for Qwen-Image-Edit: {e}")
|
| 80 |
+
print("Continuing with the base Qwen-Image-Edit model...")
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
# --- Qwen-Image-Gen Functions ---
|
| 84 |
aspect_ratios = {
|
| 85 |
"1:1": (1328, 1328),
|
| 86 |
"16:9": (1664, 928),
|
|
|
|
| 90 |
}
|
| 91 |
|
| 92 |
def load_lora_opt(pipe, lora_input):
|
| 93 |
+
"""Loads a LoRA from a local path, Hugging Face repo, or URL."""
|
| 94 |
lora_input = lora_input.strip()
|
| 95 |
if not lora_input:
|
| 96 |
return
|
| 97 |
|
|
|
|
| 98 |
if "/" in lora_input and not lora_input.startswith("http"):
|
| 99 |
pipe.load_lora_weights(lora_input, adapter_name="default")
|
| 100 |
return
|
| 101 |
|
| 102 |
if lora_input.startswith("http"):
|
| 103 |
url = lora_input
|
|
|
|
|
|
|
| 104 |
if "huggingface.co" in url and "/blob/" not in url and "/resolve/" not in url:
|
| 105 |
repo_id = urlparse(url).path.strip("/")
|
| 106 |
pipe.load_lora_weights(repo_id, adapter_name="default")
|
| 107 |
return
|
| 108 |
|
|
|
|
| 109 |
if "/blob/" in url:
|
| 110 |
url = url.replace("/blob/", "/resolve/")
|
| 111 |
|
|
|
|
| 112 |
tmp_dir = tempfile.mkdtemp()
|
| 113 |
local_path = os.path.join(tmp_dir, os.path.basename(urlparse(url).path))
|
| 114 |
|
|
|
|
| 124 |
finally:
|
| 125 |
shutil.rmtree(tmp_dir, ignore_errors=True)
|
| 126 |
|
|
|
|
| 127 |
@spaces.GPU(duration=120)
|
| 128 |
def generate_qwen(
|
| 129 |
prompt: str,
|
|
|
|
| 140 |
lora_scale: float = 1.0,
|
| 141 |
progress=gr.Progress(track_tqdm=True),
|
| 142 |
):
|
| 143 |
+
"""Main generation function for Qwen-Image-Gen."""
|
| 144 |
+
seed = randomize_seed_fn(seed, randomize_seed)
|
| 145 |
generator = torch.Generator(device).manual_seed(seed)
|
| 146 |
+
|
| 147 |
start_time = time.time()
|
| 148 |
|
| 149 |
+
current_adapters = pipe_qwen_gen.get_list_adapters()
|
| 150 |
for adapter in current_adapters:
|
| 151 |
+
pipe_qwen_gen.delete_adapters(adapter)
|
| 152 |
+
pipe_qwen_gen.disable_lora()
|
| 153 |
|
|
|
|
| 154 |
if lora_input and lora_input.strip() != "":
|
| 155 |
+
load_lora_opt(pipe_qwen_gen, lora_input)
|
| 156 |
+
pipe_qwen_gen.set_adapters(["default"], adapter_weights=[lora_scale])
|
| 157 |
+
|
| 158 |
+
images = pipe_qwen_gen(
|
|
|
|
| 159 |
prompt=prompt,
|
| 160 |
+
negative_prompt=negative_prompt if negative_prompt else " ",
|
| 161 |
height=height,
|
| 162 |
width=width,
|
| 163 |
guidance_scale=guidance_scale,
|
| 164 |
num_inference_steps=num_inference_steps,
|
| 165 |
num_images_per_prompt=num_images,
|
| 166 |
generator=generator,
|
|
|
|
| 167 |
).images
|
| 168 |
+
|
| 169 |
end_time = time.time()
|
| 170 |
duration = end_time - start_time
|
| 171 |
+
|
| 172 |
image_paths = [save_image(img) for img in images]
|
| 173 |
zip_path = None
|
| 174 |
+
if zip_images and len(image_paths) > 0:
|
| 175 |
zip_name = str(uuid.uuid4()) + ".zip"
|
| 176 |
with zipfile.ZipFile(zip_name, 'w') as zipf:
|
| 177 |
for i, img_path in enumerate(image_paths):
|
| 178 |
zipf.write(img_path, arcname=f"Img_{i}.png")
|
| 179 |
zip_path = zip_name
|
| 180 |
|
| 181 |
+
current_adapters = pipe_qwen_gen.get_list_adapters()
|
|
|
|
| 182 |
for adapter in current_adapters:
|
| 183 |
+
pipe_qwen_gen.delete_adapters(adapter)
|
| 184 |
+
pipe_qwen_gen.disable_lora()
|
| 185 |
+
|
| 186 |
return image_paths, seed, f"{duration:.2f}", zip_path
|
| 187 |
|
|
|
|
| 188 |
@spaces.GPU(duration=120)
|
| 189 |
def generate(
|
| 190 |
prompt: str,
|
|
|
|
| 202 |
lora_scale: float,
|
| 203 |
progress=gr.Progress(track_tqdm=True),
|
| 204 |
):
|
| 205 |
+
"""UI wrapper for the Qwen-Image-Gen generation function."""
|
| 206 |
final_negative_prompt = negative_prompt if use_negative_prompt else ""
|
| 207 |
return generate_qwen(
|
| 208 |
prompt=prompt,
|
|
|
|
| 220 |
progress=progress,
|
| 221 |
)
|
| 222 |
|
| 223 |
+
# --- Qwen-Image-Edit Functions ---
|
| 224 |
+
@spaces.GPU(duration=60)
|
| 225 |
+
def infer_edit(
|
| 226 |
+
image,
|
| 227 |
+
prompt,
|
| 228 |
+
seed=42,
|
| 229 |
+
randomize_seed=False,
|
| 230 |
+
true_guidance_scale=1.0,
|
| 231 |
+
num_inference_steps=8,
|
| 232 |
+
progress=gr.Progress(track_tqdm=True),
|
| 233 |
+
):
|
| 234 |
+
"""Main inference function for Qwen-Image-Edit."""
|
| 235 |
+
if image is None:
|
| 236 |
+
raise gr.Error("Please upload an image to edit.")
|
| 237 |
+
|
| 238 |
+
negative_prompt = " "
|
| 239 |
+
seed = randomize_seed_fn(seed, randomize_seed)
|
| 240 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
| 241 |
+
|
| 242 |
+
print(f"Original prompt: '{prompt}'")
|
| 243 |
+
print(f"Negative Prompt: '{negative_prompt}'")
|
| 244 |
+
print(f"Seed: {seed}, Steps: {num_inference_steps}, Guidance: {true_guidance_scale}")
|
| 245 |
|
| 246 |
+
try:
|
| 247 |
+
images = pipe_qwen_edit(
|
| 248 |
+
image,
|
| 249 |
+
prompt=prompt,
|
| 250 |
+
negative_prompt=negative_prompt,
|
| 251 |
+
num_inference_steps=num_inference_steps,
|
| 252 |
+
generator=generator,
|
| 253 |
+
true_cfg_scale=true_guidance_scale,
|
| 254 |
+
num_images_per_prompt=1
|
| 255 |
+
).images
|
| 256 |
+
return images[0], seed
|
| 257 |
+
except Exception as e:
|
| 258 |
+
print(f"Error during inference: {e}")
|
| 259 |
+
raise gr.Error(f"An error occurred during image editing: {e}")
|
| 260 |
+
|
| 261 |
+
# --- Gradio UI ---
|
| 262 |
css = '''
|
| 263 |
.gradio-container {
|
| 264 |
+
max-width: 800px !important;
|
| 265 |
margin: 0 auto !important;
|
| 266 |
}
|
| 267 |
h1 {
|
|
|
|
| 272 |
}
|
| 273 |
'''
|
| 274 |
|
|
|
|
| 275 |
with gr.Blocks(css=css, theme="bethecloud/storj_theme", delete_cache=(240, 240)) as demo:
|
| 276 |
gr.Markdown(DESCRIPTION)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 277 |
|
| 278 |
+
with gr.Tabs():
|
| 279 |
+
with gr.TabItem("Qwen-Image-Gen"):
|
| 280 |
+
with gr.Column():
|
| 281 |
+
with gr.Row():
|
| 282 |
+
prompt_gen = gr.Text(
|
| 283 |
+
label="Prompt",
|
| 284 |
+
show_label=False,
|
| 285 |
+
max_lines=1,
|
| 286 |
+
placeholder="✦︎ Enter your prompt for generation",
|
| 287 |
+
container=False,
|
| 288 |
+
)
|
| 289 |
+
run_button_gen = gr.Button("Generate", scale=0, variant="primary")
|
| 290 |
+
result_gen = gr.Gallery(label="Result", columns=2, show_label=False, preview=True, height="auto")
|
| 291 |
|
| 292 |
+
with gr.Row():
|
| 293 |
+
aspect_ratio_gen = gr.Dropdown(
|
| 294 |
+
label="Aspect Ratio",
|
| 295 |
+
choices=list(aspect_ratios.keys()),
|
| 296 |
+
value="1:1",
|
| 297 |
+
)
|
| 298 |
+
lora_gen = gr.Textbox(label="Optional LoRA", placeholder="Enter Hugging Face repo ID or URL...")
|
| 299 |
+
|
| 300 |
+
with gr.Accordion("Additional Options", open=False):
|
| 301 |
+
use_negative_prompt_gen = gr.Checkbox(label="Use negative prompt", value=True)
|
| 302 |
+
negative_prompt_gen = gr.Text(
|
| 303 |
+
label="Negative prompt",
|
| 304 |
+
max_lines=1,
|
| 305 |
+
placeholder="Enter a negative prompt",
|
| 306 |
+
value="text, watermark, copyright, blurry, low resolution",
|
| 307 |
+
)
|
| 308 |
+
seed_gen = gr.Slider(label="Seed", minimum=0, maximum=MAX_SEED, step=1, value=0)
|
| 309 |
+
randomize_seed_gen = gr.Checkbox(label="Randomize seed", value=True)
|
| 310 |
+
with gr.Row():
|
| 311 |
+
width_gen = gr.Slider(label="Width", minimum=512, maximum=2048, step=64, value=1328)
|
| 312 |
+
height_gen = gr.Slider(label="Height", minimum=512, maximum=2048, step=64, value=1328)
|
| 313 |
+
guidance_scale_gen = gr.Slider(label="Guidance Scale", minimum=0.0, maximum=20.0, step=0.1, value=4.0)
|
| 314 |
+
num_inference_steps_gen = gr.Slider("Number of inference steps", 1, 100, 50, step=1)
|
| 315 |
+
num_images_gen = gr.Slider("Number of images", 1, 5, 1, step=1)
|
| 316 |
+
zip_images_gen = gr.Checkbox(label="Zip generated images", value=False)
|
| 317 |
+
with gr.Row():
|
| 318 |
+
lora_scale_gen = gr.Slider(label="LoRA Scale", minimum=0, maximum=2, step=0.01, value=1)
|
| 319 |
+
|
| 320 |
+
gr.Markdown("### Output Information")
|
| 321 |
+
seed_display_gen = gr.Textbox(label="Seed used", interactive=False)
|
| 322 |
+
generation_time_gen = gr.Textbox(label="Generation time (seconds)", interactive=False)
|
| 323 |
+
zip_file_gen = gr.File(label="Download ZIP")
|
| 324 |
+
|
| 325 |
+
# --- Gen Tab Logic ---
|
| 326 |
+
def set_dimensions(ar):
|
| 327 |
+
w, h = aspect_ratios[ar]
|
| 328 |
+
return gr.update(value=w), gr.update(value=h)
|
| 329 |
+
|
| 330 |
+
aspect_ratio_gen.change(fn=set_dimensions, inputs=aspect_ratio_gen, outputs=[width_gen, height_gen])
|
| 331 |
+
use_negative_prompt_gen.change(fn=lambda x: gr.update(visible=x), inputs=use_negative_prompt_gen, outputs=negative_prompt_gen)
|
| 332 |
+
|
| 333 |
+
gen_inputs = [
|
| 334 |
+
prompt_gen, negative_prompt_gen, use_negative_prompt_gen, seed_gen, width_gen, height_gen,
|
| 335 |
+
guidance_scale_gen, randomize_seed_gen, num_inference_steps_gen, num_images_gen,
|
| 336 |
+
zip_images_gen, lora_gen, lora_scale_gen
|
| 337 |
+
]
|
| 338 |
+
gen_outputs = [result_gen, seed_display_gen, generation_time_gen, zip_file_gen]
|
| 339 |
+
|
| 340 |
+
gr.on(triggers=[prompt_gen.submit, run_button_gen.click], fn=generate, inputs=gen_inputs, outputs=gen_outputs)
|
| 341 |
+
|
| 342 |
+
gen_examples = [
|
| 343 |
+
"A decadent slice of layered chocolate cake on a ceramic plate with a drizzle of chocolate syrup and powdered sugar dusted on top.",
|
| 344 |
+
"A young girl wearing school uniform stands in a classroom, writing on a chalkboard. The text 'Introducing Qwen-Image' appears in neat white chalk.",
|
| 345 |
+
"一幅精致细腻的工笔画,画面中心是一株��勃生长的红色牡丹,花朵繁茂。",
|
| 346 |
+
"Realistic still life photography style: A single, fresh apple, resting on a clean, soft-textured surface.",
|
| 347 |
+
]
|
| 348 |
+
gr.Examples(examples=gen_examples, inputs=prompt_gen, outputs=gen_outputs, fn=generate, cache_examples=False)
|
| 349 |
+
|
| 350 |
+
with gr.TabItem("Qwen-Image-Edit"):
|
| 351 |
+
with gr.Column():
|
| 352 |
+
with gr.Row():
|
| 353 |
+
input_image_edit = gr.Image(label="Input Image", type="pil", height=400)
|
| 354 |
+
result_edit = gr.Image(label="Result", type="pil", height=400)
|
| 355 |
+
|
| 356 |
+
with gr.Row():
|
| 357 |
+
prompt_edit = gr.Text(
|
| 358 |
+
label="Edit Instruction",
|
| 359 |
+
show_label=False,
|
| 360 |
+
placeholder="Describe the edit you want to make",
|
| 361 |
+
container=False,
|
| 362 |
+
)
|
| 363 |
+
run_button_edit = gr.Button("Edit", variant="primary")
|
| 364 |
+
|
| 365 |
+
with gr.Accordion("Advanced Settings", open=False):
|
| 366 |
+
seed_edit = gr.Slider(label="Seed", minimum=0, maximum=MAX_SEED, step=1, value=42)
|
| 367 |
+
randomize_seed_edit = gr.Checkbox(label="Randomize seed", value=True)
|
| 368 |
+
with gr.Row():
|
| 369 |
+
true_guidance_scale_edit = gr.Slider(
|
| 370 |
+
label="True guidance scale", minimum=1.0, maximum=10.0, step=0.1, value=1.0
|
| 371 |
+
)
|
| 372 |
+
num_inference_steps_edit = gr.Slider(
|
| 373 |
+
label="Inference steps (Lightning LoRA)", minimum=4, maximum=28, step=1, value=8
|
| 374 |
+
)
|
| 375 |
+
|
| 376 |
+
# --- Edit Tab Logic ---
|
| 377 |
+
edit_inputs = [
|
| 378 |
+
input_image_edit, prompt_edit, seed_edit, randomize_seed_edit,
|
| 379 |
+
true_guidance_scale_edit, num_inference_steps_edit
|
| 380 |
+
]
|
| 381 |
+
edit_outputs = [result_edit, seed_edit]
|
| 382 |
+
|
| 383 |
+
gr.on(triggers=[prompt_edit.submit, run_button_edit.click], fn=infer_edit, inputs=edit_inputs, outputs=edit_outputs)
|
| 384 |
+
|
| 385 |
+
edit_examples = [
|
| 386 |
+
["image-edit/cat.png", "make the cat wear sunglasses"],
|
| 387 |
+
["image-edit/girl.png", "change her hair to blonde"],
|
| 388 |
+
]
|
| 389 |
+
|
| 390 |
+
gr.Examples(examples=edit_examples, inputs=[input_image_edit, prompt_edit], outputs=edit_outputs, fn=infer_edit, cache_examples=True)
|
| 391 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 392 |
|
| 393 |
if __name__ == "__main__":
|
| 394 |
+
demo.queue(max_size=50).launch(share=False, debug=True)
|