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