Spaces:
Running
on
Zero
Running
on
Zero
Delete app.py
Browse files
app.py
DELETED
|
@@ -1,544 +0,0 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import json
|
| 3 |
-
import copy
|
| 4 |
-
import math
|
| 5 |
-
import time
|
| 6 |
-
import random
|
| 7 |
-
import logging
|
| 8 |
-
import numpy as np
|
| 9 |
-
from typing import Any, Dict, List, Optional, Union
|
| 10 |
-
import torch
|
| 11 |
-
from PIL import Image
|
| 12 |
-
import gradio as gr
|
| 13 |
-
import spaces
|
| 14 |
-
from diffusers import (
|
| 15 |
-
DiffusionPipeline,
|
| 16 |
-
FlowMatchEulerDiscreteScheduler)
|
| 17 |
-
from huggingface_hub import (
|
| 18 |
-
hf_hub_download,
|
| 19 |
-
HfFileSystem,
|
| 20 |
-
ModelCard,
|
| 21 |
-
snapshot_download)
|
| 22 |
-
from diffusers.utils import load_image
|
| 23 |
-
import requests
|
| 24 |
-
from urllib.parse import urlparse
|
| 25 |
-
import tempfile
|
| 26 |
-
import shutil
|
| 27 |
-
import uuid
|
| 28 |
-
import zipfile
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
# META: CUDA_CHECK / GPU_INFO
|
| 32 |
-
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 33 |
-
print("CUDA_VISIBLE_DEVICES=", os.environ.get("CUDA_VISIBLE_DEVICES"))
|
| 34 |
-
print("torch.__version__ =", torch.__version__)
|
| 35 |
-
print("torch.version.cuda =", torch.version.cuda)
|
| 36 |
-
print("cuda available:", torch.cuda.is_available())
|
| 37 |
-
print("cuda device count:", torch.cuda.device_count())
|
| 38 |
-
if torch.cuda.is_available():
|
| 39 |
-
print("current device:", torch.cuda.current_device())
|
| 40 |
-
print("device name:", torch.cuda.get_device_name(torch.cuda.current_device()))
|
| 41 |
-
|
| 42 |
-
print("Using device:", device)
|
| 43 |
-
|
| 44 |
-
loras = [
|
| 45 |
-
# Sample Qwen-compatible LoRAs
|
| 46 |
-
{
|
| 47 |
-
"image": "https://huggingface.co/damnthatai/Game_Boy_Camera_Pixel_Style_Qwen/resolve/main/images/20250818090201_Qwen8s_00001_.jpg",
|
| 48 |
-
"title": "Camera Pixel Style",
|
| 49 |
-
"repo": "damnthatai/Game_Boy_Camera_Pixel_Style_Qwen",
|
| 50 |
-
"weights": "g4m3b0yc4m3r4_qwen.safetensors",
|
| 51 |
-
"trigger_word": "g4m3b0yc4m3r4, grayscale, pixel photo"
|
| 52 |
-
},
|
| 53 |
-
{
|
| 54 |
-
"image": "https://huggingface.co/prithivMLmods/Qwen-Image-Studio-Realism/resolve/main/images/2.png",
|
| 55 |
-
"title": "Studio Realism",
|
| 56 |
-
"repo": "prithivMLmods/Qwen-Image-Studio-Realism",
|
| 57 |
-
"weights": "qwen-studio-realism.safetensors",
|
| 58 |
-
"trigger_word": "Studio Realism"
|
| 59 |
-
},
|
| 60 |
-
{
|
| 61 |
-
"image": "https://huggingface.co/prithivMLmods/Qwen-Image-Sketch-Smudge/resolve/main/images/1.png",
|
| 62 |
-
"title": "Sketch Smudge",
|
| 63 |
-
"repo": "prithivMLmods/Qwen-Image-Sketch-Smudge",
|
| 64 |
-
"weights": "qwen-sketch-smudge.safetensors",
|
| 65 |
-
"trigger_word": "Sketch Smudge"
|
| 66 |
-
},
|
| 67 |
-
{
|
| 68 |
-
"image": "https://huggingface.co/prithivMLmods/Qwen-Image-Anime-LoRA/resolve/main/images/1.png",
|
| 69 |
-
"title": "Qwen Anime",
|
| 70 |
-
"repo": "prithivMLmods/Qwen-Image-Anime-LoRA",
|
| 71 |
-
"weights": "qwen-anime.safetensors",
|
| 72 |
-
"trigger_word": "Qwen Anime"
|
| 73 |
-
},
|
| 74 |
-
{
|
| 75 |
-
"image": "https://huggingface.co/prithivMLmods/Qwen-Image-Fragmented-Portraiture/resolve/main/images/3.png",
|
| 76 |
-
"title": "Fragmented Portraiture",
|
| 77 |
-
"repo": "prithivMLmods/Qwen-Image-Fragmented-Portraiture",
|
| 78 |
-
"weights": "qwen-fragmented-portraiture.safetensors",
|
| 79 |
-
"trigger_word": "Fragmented Portraiture"
|
| 80 |
-
},
|
| 81 |
-
{
|
| 82 |
-
"image": "https://huggingface.co/prithivMLmods/Qwen-Image-Synthetic-Face/resolve/main/images/2.png",
|
| 83 |
-
"title": "Synthetic Face",
|
| 84 |
-
"repo": "prithivMLmods/Qwen-Image-Synthetic-Face",
|
| 85 |
-
"weights": "qwen-synthetic-face.safetensors",
|
| 86 |
-
"trigger_word": "Synthetic Face"
|
| 87 |
-
},
|
| 88 |
-
{
|
| 89 |
-
"image": "https://huggingface.co/Tomechi02/Macne_style_enahncer/resolve/main/images/pixai-1913880604374308947-2.png",
|
| 90 |
-
"title": "Macne Style Enahncer",
|
| 91 |
-
"repo": "Tomechi02/Macne_style_enahncer",
|
| 92 |
-
"weights": "Macne_Style_enhancer.safetensors",
|
| 93 |
-
"trigger_word": "macloid, gomoku"
|
| 94 |
-
},
|
| 95 |
-
{
|
| 96 |
-
"image": "https://huggingface.co/itspoidaman/qwenglitch/resolve/main/images/GyZTwJIbkAAhS4h.jpeg",
|
| 97 |
-
"title": "Qwen Glitch",
|
| 98 |
-
"repo": "itspoidaman/qwenglitch",
|
| 99 |
-
"weights": "qwenglitch1.safetensors",
|
| 100 |
-
"trigger_word": "qwenglitch"
|
| 101 |
-
},
|
| 102 |
-
{
|
| 103 |
-
"image": "https://huggingface.co/alfredplpl/qwen-image-modern-anime-lora/resolve/main/sample1.jpg",
|
| 104 |
-
"title": "Modern Anime Lora",
|
| 105 |
-
"repo": "alfredplpl/qwen-image-modern-anime-lora",
|
| 106 |
-
"weights": "lora.safetensors",
|
| 107 |
-
"trigger_word": "Japanese modern anime style"
|
| 108 |
-
},
|
| 109 |
-
{
|
| 110 |
-
"image": "https://huggingface.co/damnthatai/Apple_QuickTake_150_Digital_Camera_Qwen/resolve/main/images/20250817084713_Qwen.jpg",
|
| 111 |
-
"title": "Apple QuickTake 150 Digital Camera",
|
| 112 |
-
"repo": "damnthatai/Apple_QuickTake_150_Digital_Camera_Qwen",
|
| 113 |
-
"weights": "quicktake150style_qwen.safetensors",
|
| 114 |
-
"trigger_word": "quicktake150style"
|
| 115 |
-
},
|
| 116 |
-
]
|
| 117 |
-
|
| 118 |
-
# Initialize the base model
|
| 119 |
-
dtype = torch.bfloat16
|
| 120 |
-
base_model = "Qwen/Qwen-Image"
|
| 121 |
-
|
| 122 |
-
# Scheduler configuration from the Qwen-Image-Lightning repository
|
| 123 |
-
scheduler_config = {
|
| 124 |
-
"base_image_seq_len": 256,
|
| 125 |
-
"base_shift": math.log(3),
|
| 126 |
-
"invert_sigmas": False,
|
| 127 |
-
"max_image_seq_len": 8192,
|
| 128 |
-
"max_shift": math.log(3),
|
| 129 |
-
"num_train_timesteps": 1000,
|
| 130 |
-
"shift": 1.0,
|
| 131 |
-
"shift_terminal": None,
|
| 132 |
-
"stochastic_sampling": False,
|
| 133 |
-
"time_shift_type": "exponential",
|
| 134 |
-
"use_beta_sigmas": False,
|
| 135 |
-
"use_dynamic_shifting": True,
|
| 136 |
-
"use_exponential_sigmas": False,
|
| 137 |
-
"use_karras_sigmas": False,
|
| 138 |
-
}
|
| 139 |
-
|
| 140 |
-
scheduler = FlowMatchEulerDiscreteScheduler.from_config(scheduler_config)
|
| 141 |
-
pipe = DiffusionPipeline.from_pretrained(
|
| 142 |
-
base_model, scheduler=scheduler, torch_dtype=dtype
|
| 143 |
-
).to(device)
|
| 144 |
-
|
| 145 |
-
# Lightning LoRA info (no global state)
|
| 146 |
-
LIGHTNING_LORA_REPO = "lightx2v/Qwen-Image-Lightning"
|
| 147 |
-
LIGHTNING_LORA_WEIGHT = "Qwen-Image-Lightning-8steps-V1.0.safetensors"
|
| 148 |
-
|
| 149 |
-
MAX_SEED = np.iinfo(np.int32).max
|
| 150 |
-
|
| 151 |
-
class Timer:
|
| 152 |
-
def __init__(self, task_name=""):
|
| 153 |
-
self.task_name = task_name
|
| 154 |
-
|
| 155 |
-
def __enter__(self):
|
| 156 |
-
self.start_time = time.time()
|
| 157 |
-
return self
|
| 158 |
-
|
| 159 |
-
def __exit__(self, exc_type, exc_value, traceback):
|
| 160 |
-
self.end_time = time.time()
|
| 161 |
-
self.elapsed_time = self.end_time - self.start_time
|
| 162 |
-
if self.task_name:
|
| 163 |
-
print(f"Elapsed time for {self.task_name}: {self.elapsed_time:.6f} seconds")
|
| 164 |
-
else:
|
| 165 |
-
print(f"Elapsed time: {self.elapsed_time:.6f} seconds")
|
| 166 |
-
|
| 167 |
-
def compute_image_dimensions(aspect_ratio):
|
| 168 |
-
"""Converts aspect ratio string to width, height tuple."""
|
| 169 |
-
if aspect_ratio == "1:1":
|
| 170 |
-
return 1024, 1024
|
| 171 |
-
elif aspect_ratio == "16:9":
|
| 172 |
-
return 1152, 640
|
| 173 |
-
elif aspect_ratio == "9:16":
|
| 174 |
-
return 640, 1152
|
| 175 |
-
elif aspect_ratio == "4:3":
|
| 176 |
-
return 1024, 768
|
| 177 |
-
elif aspect_ratio == "3:4":
|
| 178 |
-
return 768, 1024
|
| 179 |
-
elif aspect_ratio == "3:2":
|
| 180 |
-
return 1024, 688
|
| 181 |
-
elif aspect_ratio == "2:3":
|
| 182 |
-
return 688, 1024
|
| 183 |
-
else:
|
| 184 |
-
return 1024, 1024
|
| 185 |
-
|
| 186 |
-
def handle_lora_selection(evt: gr.SelectData, aspect_ratio):
|
| 187 |
-
selected_lora = loras[evt.index]
|
| 188 |
-
new_placeholder = f"Type a prompt for {selected_lora['title']}"
|
| 189 |
-
lora_repo = selected_lora["repo"]
|
| 190 |
-
updated_text = f"### Selected: [{lora_repo}](https://huggingface.co/{lora_repo}) ✨"
|
| 191 |
-
|
| 192 |
-
# Update aspect ratio if specified in LoRA config
|
| 193 |
-
if "aspect" in selected_lora:
|
| 194 |
-
if selected_lora["aspect"] == "portrait":
|
| 195 |
-
aspect_ratio = "9:16"
|
| 196 |
-
elif selected_lora["aspect"] == "landscape":
|
| 197 |
-
aspect_ratio = "16:9"
|
| 198 |
-
else:
|
| 199 |
-
aspect_ratio = "1:1"
|
| 200 |
-
|
| 201 |
-
return (
|
| 202 |
-
gr.update(placeholder=new_placeholder),
|
| 203 |
-
updated_text,
|
| 204 |
-
evt.index,
|
| 205 |
-
aspect_ratio,
|
| 206 |
-
)
|
| 207 |
-
|
| 208 |
-
def adjust_generation_mode(speed_mode):
|
| 209 |
-
"""Update UI based on speed/quality toggle."""
|
| 210 |
-
if speed_mode == "Fast (8 steps)":
|
| 211 |
-
return gr.update(value="Fast mode selected - 8 steps with Lightning LoRA"), 8, 1.0
|
| 212 |
-
else:
|
| 213 |
-
return gr.update(value="Base mode selected - 48 steps for best quality"), 48, 4.0
|
| 214 |
-
|
| 215 |
-
@spaces.GPU(duration=108)
|
| 216 |
-
def create_image(prompt_mash, steps, seed, cfg_scale, width, height, lora_scale, negative_prompt=""):
|
| 217 |
-
pipe.to("cuda")
|
| 218 |
-
generator = torch.Generator(device="cuda").manual_seed(seed)
|
| 219 |
-
|
| 220 |
-
with Timer("Generating image"):
|
| 221 |
-
# Generate image
|
| 222 |
-
image = pipe(
|
| 223 |
-
prompt=prompt_mash,
|
| 224 |
-
negative_prompt=negative_prompt,
|
| 225 |
-
num_inference_steps=steps,
|
| 226 |
-
true_cfg_scale=cfg_scale, # Use true_cfg_scale for Qwen-Image
|
| 227 |
-
width=width,
|
| 228 |
-
height=height,
|
| 229 |
-
generator=generator,
|
| 230 |
-
).images[0]
|
| 231 |
-
|
| 232 |
-
return image
|
| 233 |
-
|
| 234 |
-
@spaces.GPU(duration=108)
|
| 235 |
-
def process_adapter_generation(prompt, cfg_scale, steps, selected_index, randomize_seed, seed, aspect_ratio, lora_scale, speed_mode, progress=gr.Progress(track_tqdm=True)):
|
| 236 |
-
if selected_index is None:
|
| 237 |
-
raise gr.Error("You must select a LoRA before proceeding.")
|
| 238 |
-
|
| 239 |
-
selected_lora = loras[selected_index]
|
| 240 |
-
lora_path = selected_lora["repo"]
|
| 241 |
-
trigger_word = selected_lora["trigger_word"]
|
| 242 |
-
|
| 243 |
-
# Prepare prompt with trigger word
|
| 244 |
-
if trigger_word:
|
| 245 |
-
if "trigger_position" in selected_lora:
|
| 246 |
-
if selected_lora["trigger_position"] == "prepend":
|
| 247 |
-
prompt_mash = f"{trigger_word} {prompt}"
|
| 248 |
-
else:
|
| 249 |
-
prompt_mash = f"{prompt} {trigger_word}"
|
| 250 |
-
else:
|
| 251 |
-
prompt_mash = f"{trigger_word} {prompt}"
|
| 252 |
-
else:
|
| 253 |
-
prompt_mash = prompt
|
| 254 |
-
|
| 255 |
-
# Always unload any existing LoRAs first to avoid conflicts
|
| 256 |
-
with Timer("Unloading existing LoRAs"):
|
| 257 |
-
pipe.unload_lora_weights()
|
| 258 |
-
|
| 259 |
-
# Load LoRAs based on speed mode
|
| 260 |
-
if speed_mode == "Fast (8 steps)":
|
| 261 |
-
with Timer("Loading Lightning LoRA and style LoRA"):
|
| 262 |
-
# Load Lightning LoRA first
|
| 263 |
-
pipe.load_lora_weights(
|
| 264 |
-
LIGHTNING_LORA_REPO,
|
| 265 |
-
weight_name=LIGHTNING_LORA_WEIGHT,
|
| 266 |
-
adapter_name="lightning"
|
| 267 |
-
)
|
| 268 |
-
|
| 269 |
-
# Load the selected style LoRA
|
| 270 |
-
weight_name = selected_lora.get("weights", None)
|
| 271 |
-
pipe.load_lora_weights(
|
| 272 |
-
lora_path,
|
| 273 |
-
weight_name=weight_name,
|
| 274 |
-
low_cpu_mem_usage=True,
|
| 275 |
-
adapter_name="style"
|
| 276 |
-
)
|
| 277 |
-
|
| 278 |
-
# Set both adapters active with their weights
|
| 279 |
-
pipe.set_adapters(["lightning", "style"], adapter_weights=[1.0, lora_scale])
|
| 280 |
-
else:
|
| 281 |
-
# Quality mode - only load the style LoRA
|
| 282 |
-
with Timer(f"Loading LoRA weights for {selected_lora['title']}"):
|
| 283 |
-
weight_name = selected_lora.get("weights", None)
|
| 284 |
-
pipe.load_lora_weights(
|
| 285 |
-
lora_path,
|
| 286 |
-
weight_name=weight_name,
|
| 287 |
-
low_cpu_mem_usage=True
|
| 288 |
-
)
|
| 289 |
-
|
| 290 |
-
# Set random seed for reproducibility
|
| 291 |
-
with Timer("Randomizing seed"):
|
| 292 |
-
if randomize_seed:
|
| 293 |
-
seed = random.randint(0, MAX_SEED)
|
| 294 |
-
|
| 295 |
-
# Get image dimensions from aspect ratio
|
| 296 |
-
width, height = compute_image_dimensions(aspect_ratio)
|
| 297 |
-
|
| 298 |
-
# Generate the image
|
| 299 |
-
final_image = create_image(prompt_mash, steps, seed, cfg_scale, width, height, lora_scale)
|
| 300 |
-
|
| 301 |
-
return final_image, seed
|
| 302 |
-
|
| 303 |
-
def fetch_hf_adapter_files(link):
|
| 304 |
-
split_link = link.split("/")
|
| 305 |
-
if len(split_link) != 2:
|
| 306 |
-
raise Exception("Invalid Hugging Face repository link format.")
|
| 307 |
-
|
| 308 |
-
print(f"Repository attempted: {split_link}")
|
| 309 |
-
|
| 310 |
-
# Load model card
|
| 311 |
-
model_card = ModelCard.load(link)
|
| 312 |
-
base_model = model_card.data.get("base_model")
|
| 313 |
-
print(f"Base model: {base_model}")
|
| 314 |
-
|
| 315 |
-
# Validate model type (for Qwen-Image)
|
| 316 |
-
acceptable_models = {"Qwen/Qwen-Image"}
|
| 317 |
-
|
| 318 |
-
models_to_check = base_model if isinstance(base_model, list) else [base_model]
|
| 319 |
-
|
| 320 |
-
if not any(model in acceptable_models for model in models_to_check):
|
| 321 |
-
raise Exception("Not a Qwen-Image LoRA!")
|
| 322 |
-
|
| 323 |
-
# Extract image and trigger word
|
| 324 |
-
image_path = model_card.data.get("widget", [{}])[0].get("output", {}).get("url", None)
|
| 325 |
-
trigger_word = model_card.data.get("instance_prompt", "")
|
| 326 |
-
image_url = f"https://huggingface.co/{link}/resolve/main/{image_path}" if image_path else None
|
| 327 |
-
|
| 328 |
-
# Initialize Hugging Face file system
|
| 329 |
-
fs = HfFileSystem()
|
| 330 |
-
try:
|
| 331 |
-
list_of_files = fs.ls(link, detail=False)
|
| 332 |
-
|
| 333 |
-
# Find safetensors file
|
| 334 |
-
safetensors_name = None
|
| 335 |
-
for file in list_of_files:
|
| 336 |
-
filename = file.split("/")[-1]
|
| 337 |
-
if filename.endswith(".safetensors"):
|
| 338 |
-
safetensors_name = filename
|
| 339 |
-
break
|
| 340 |
-
|
| 341 |
-
if not safetensors_name:
|
| 342 |
-
raise Exception("No valid *.safetensors file found in the repository.")
|
| 343 |
-
|
| 344 |
-
except Exception as e:
|
| 345 |
-
print(e)
|
| 346 |
-
raise Exception("You didn't include a valid Hugging Face repository with a *.safetensors LoRA")
|
| 347 |
-
|
| 348 |
-
return split_link[1], link, safetensors_name, trigger_word, image_url
|
| 349 |
-
|
| 350 |
-
def validate_custom_adapter(link):
|
| 351 |
-
print(f"Checking a custom model on: {link}")
|
| 352 |
-
|
| 353 |
-
if link.endswith('.safetensors'):
|
| 354 |
-
if 'huggingface.co' in link:
|
| 355 |
-
parts = link.split('/')
|
| 356 |
-
try:
|
| 357 |
-
hf_index = parts.index('huggingface.co')
|
| 358 |
-
username = parts[hf_index + 1]
|
| 359 |
-
repo_name = parts[hf_index + 2]
|
| 360 |
-
repo = f"{username}/{repo_name}"
|
| 361 |
-
|
| 362 |
-
safetensors_name = parts[-1]
|
| 363 |
-
|
| 364 |
-
try:
|
| 365 |
-
model_card = ModelCard.load(repo)
|
| 366 |
-
trigger_word = model_card.data.get("instance_prompt", "")
|
| 367 |
-
image_path = model_card.data.get("widget", [{}])[0].get("output", {}).get("url", None)
|
| 368 |
-
image_url = f"https://huggingface.co/{repo}/resolve/main/{image_path}" if image_path else None
|
| 369 |
-
except:
|
| 370 |
-
trigger_word = ""
|
| 371 |
-
image_url = None
|
| 372 |
-
|
| 373 |
-
return repo_name, repo, safetensors_name, trigger_word, image_url
|
| 374 |
-
except:
|
| 375 |
-
raise Exception("Invalid safetensors URL format")
|
| 376 |
-
|
| 377 |
-
if link.startswith("https://"):
|
| 378 |
-
if link.startswith("https://huggingface.co") or link.startswith("https://www.huggingface.co"):
|
| 379 |
-
link_split = link.split("huggingface.co/")
|
| 380 |
-
return fetch_hf_adapter_files(link_split[1])
|
| 381 |
-
else:
|
| 382 |
-
return fetch_hf_adapter_files(link)
|
| 383 |
-
|
| 384 |
-
def incorporate_custom_adapter(custom_lora):
|
| 385 |
-
global loras
|
| 386 |
-
if custom_lora:
|
| 387 |
-
try:
|
| 388 |
-
title, repo, path, trigger_word, image = validate_custom_adapter(custom_lora)
|
| 389 |
-
print(f"Loaded custom LoRA: {repo}")
|
| 390 |
-
card = f'''
|
| 391 |
-
<div class="custom_lora_card">
|
| 392 |
-
<span>Loaded custom LoRA:</span>
|
| 393 |
-
<div class="card_internal">
|
| 394 |
-
<img src="{image}" />
|
| 395 |
-
<div>
|
| 396 |
-
<h3>{title}</h3>
|
| 397 |
-
<small>{"Using: <code><b>"+trigger_word+"</code></b> as the trigger word" if trigger_word else "No trigger word found. If there's a trigger word, include it in your prompt"}<br></small>
|
| 398 |
-
</div>
|
| 399 |
-
</div>
|
| 400 |
-
</div>
|
| 401 |
-
'''
|
| 402 |
-
existing_item_index = next((index for (index, item) in enumerate(loras) if item['repo'] == repo), None)
|
| 403 |
-
if existing_item_index is None:
|
| 404 |
-
new_item = {
|
| 405 |
-
"image": image,
|
| 406 |
-
"title": title,
|
| 407 |
-
"repo": repo,
|
| 408 |
-
"weights": path,
|
| 409 |
-
"trigger_word": trigger_word
|
| 410 |
-
}
|
| 411 |
-
print(new_item)
|
| 412 |
-
loras.append(new_item)
|
| 413 |
-
existing_item_index = len(loras) - 1 # Get the actual index after adding
|
| 414 |
-
|
| 415 |
-
return gr.update(visible=True, value=card), gr.update(visible=True), gr.Gallery(selected_index=None), f"Custom: {path}", existing_item_index, trigger_word
|
| 416 |
-
except Exception as e:
|
| 417 |
-
gr.Warning(f"Invalid LoRA: either you entered an invalid link, or a non-Qwen-Image LoRA, this was the issue: {e}")
|
| 418 |
-
return gr.update(visible=True, value=f"Invalid LoRA: either you entered an invalid link, a non-Qwen-Image LoRA"), gr.update(visible=True), gr.update(), "", None, ""
|
| 419 |
-
else:
|
| 420 |
-
return gr.update(visible=False), gr.update(visible=False), gr.update(), "", None, ""
|
| 421 |
-
|
| 422 |
-
def discard_custom_adapter():
|
| 423 |
-
return gr.update(visible=False), gr.update(visible=False), gr.update(), "", None, ""
|
| 424 |
-
|
| 425 |
-
process_adapter_generation.zerogpu = True
|
| 426 |
-
|
| 427 |
-
css = '''
|
| 428 |
-
#gen_btn{height: 100%}
|
| 429 |
-
#gen_column{align-self: stretch}
|
| 430 |
-
#title{text-align: center}
|
| 431 |
-
#title h1{font-size: 3em; display:inline-flex; align-items:center}
|
| 432 |
-
#title img{width: 100px; margin-right: 0.5em}
|
| 433 |
-
#gallery .grid-wrap{height: 10vh}
|
| 434 |
-
#lora_list{background: var(--block-background-fill);padding: 0 1em .3em; font-size: 90%}
|
| 435 |
-
.card_internal{display: flex;height: 100px;margin-top: .5em}
|
| 436 |
-
.card_internal img{margin-right: 1em}
|
| 437 |
-
.styler{--form-gap-width: 0px !important}
|
| 438 |
-
#speed_status{padding: .5em; border-radius: 5px; margin: 1em 0}
|
| 439 |
-
'''
|
| 440 |
-
|
| 441 |
-
with gr.Blocks(theme="bethecloud/storj_theme", css=css, delete_cache=(120, 120)) as app:
|
| 442 |
-
title = gr.HTML("""<h1>Qwen Image LoRA DLC⛵</h1>""", elem_id="title")
|
| 443 |
-
selected_index = gr.State(None)
|
| 444 |
-
|
| 445 |
-
with gr.Row():
|
| 446 |
-
with gr.Column(scale=3):
|
| 447 |
-
prompt = gr.Textbox(label="Prompt", lines=1, placeholder="Type a prompt after selecting a LoRA")
|
| 448 |
-
with gr.Column(scale=1, elem_id="gen_column"):
|
| 449 |
-
generate_button = gr.Button("Generate", variant="primary", elem_id="gen_btn")
|
| 450 |
-
|
| 451 |
-
with gr.Row():
|
| 452 |
-
with gr.Column():
|
| 453 |
-
selected_info = gr.Markdown("")
|
| 454 |
-
gallery = gr.Gallery(
|
| 455 |
-
[(item["image"], item["title"]) for item in loras],
|
| 456 |
-
label="LoRA Gallery",
|
| 457 |
-
allow_preview=False,
|
| 458 |
-
columns=3,
|
| 459 |
-
elem_id="gallery",
|
| 460 |
-
show_share_button=False
|
| 461 |
-
)
|
| 462 |
-
with gr.Group():
|
| 463 |
-
custom_lora = gr.Textbox(label="Custom LoRA", info="LoRA Hugging Face path", placeholder="username/qwen-image-custom-lora")
|
| 464 |
-
gr.Markdown("[Check Qwen-Image LoRAs](https://huggingface.co/models?other=base_model:adapter:Qwen/Qwen-Image)", elem_id="lora_list")
|
| 465 |
-
custom_lora_info = gr.HTML(visible=False)
|
| 466 |
-
custom_lora_button = gr.Button("Remove custom LoRA", visible=False)
|
| 467 |
-
|
| 468 |
-
with gr.Column():
|
| 469 |
-
result = gr.Image(label="Generated Image")
|
| 470 |
-
|
| 471 |
-
with gr.Row():
|
| 472 |
-
aspect_ratio = gr.Dropdown(
|
| 473 |
-
label="Aspect Ratio",
|
| 474 |
-
choices=["1:1", "16:9", "9:16", "4:3", "3:4", "3:2", "2:3"],
|
| 475 |
-
value="1:1"
|
| 476 |
-
)
|
| 477 |
-
with gr.Row():
|
| 478 |
-
speed_mode = gr.Dropdown(
|
| 479 |
-
label="Generation Mode",
|
| 480 |
-
choices=["Fast (8 steps)", "Base (48 steps)"],
|
| 481 |
-
value="Base (48 steps)",
|
| 482 |
-
)
|
| 483 |
-
|
| 484 |
-
speed_status = gr.Markdown("Base mode selected", elem_id="speed_status")
|
| 485 |
-
|
| 486 |
-
with gr.Row():
|
| 487 |
-
with gr.Accordion("Advanced Settings", open=False):
|
| 488 |
-
with gr.Column():
|
| 489 |
-
with gr.Row():
|
| 490 |
-
cfg_scale = gr.Slider(
|
| 491 |
-
label="Guidance Scale (True CFG)",
|
| 492 |
-
minimum=1.0,
|
| 493 |
-
maximum=5.0,
|
| 494 |
-
step=0.1,
|
| 495 |
-
value=4.0,
|
| 496 |
-
info="Lower for speed mode, higher for quality"
|
| 497 |
-
)
|
| 498 |
-
steps = gr.Slider(
|
| 499 |
-
label="Steps",
|
| 500 |
-
minimum=4,
|
| 501 |
-
maximum=50,
|
| 502 |
-
step=1,
|
| 503 |
-
value=48,
|
| 504 |
-
info="Automatically set by speed mode"
|
| 505 |
-
)
|
| 506 |
-
|
| 507 |
-
with gr.Row():
|
| 508 |
-
randomize_seed = gr.Checkbox(True, label="Randomize seed")
|
| 509 |
-
seed = gr.Slider(label="Seed", minimum=0, maximum=MAX_SEED, step=1, value=0, randomize=True)
|
| 510 |
-
lora_scale = gr.Slider(label="LoRA Scale", minimum=0, maximum=2, step=0.01, value=1.0)
|
| 511 |
-
|
| 512 |
-
# Event handlers
|
| 513 |
-
gallery.select(
|
| 514 |
-
handle_lora_selection,
|
| 515 |
-
inputs=[aspect_ratio],
|
| 516 |
-
outputs=[prompt, selected_info, selected_index, aspect_ratio]
|
| 517 |
-
)
|
| 518 |
-
|
| 519 |
-
speed_mode.change(
|
| 520 |
-
adjust_generation_mode,
|
| 521 |
-
inputs=[speed_mode],
|
| 522 |
-
outputs=[speed_status, steps, cfg_scale]
|
| 523 |
-
)
|
| 524 |
-
|
| 525 |
-
custom_lora.input(
|
| 526 |
-
incorporate_custom_adapter,
|
| 527 |
-
inputs=[custom_lora],
|
| 528 |
-
outputs=[custom_lora_info, custom_lora_button, gallery, selected_info, selected_index, prompt]
|
| 529 |
-
)
|
| 530 |
-
|
| 531 |
-
custom_lora_button.click(
|
| 532 |
-
discard_custom_adapter,
|
| 533 |
-
outputs=[custom_lora_info, custom_lora_button, gallery, selected_info, selected_index, custom_lora]
|
| 534 |
-
)
|
| 535 |
-
|
| 536 |
-
gr.on(
|
| 537 |
-
triggers=[generate_button.click, prompt.submit],
|
| 538 |
-
fn=process_adapter_generation,
|
| 539 |
-
inputs=[prompt, cfg_scale, steps, selected_index, randomize_seed, seed, aspect_ratio, lora_scale, speed_mode],
|
| 540 |
-
outputs=[result, seed]
|
| 541 |
-
)
|
| 542 |
-
|
| 543 |
-
app.queue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