Spaces:
Running
on
Zero
Running
on
Zero
update app (#16)
Browse files- update app (7b6451c39f783b66a81ae62d4ad045a88c57c210)
app.py
CHANGED
|
@@ -13,17 +13,12 @@ import gradio as gr
|
|
| 13 |
import spaces
|
| 14 |
from diffusers import (
|
| 15 |
DiffusionPipeline,
|
| 16 |
-
|
| 17 |
-
AutoencoderTiny,
|
| 18 |
-
AutoPipelineForImage2Image,
|
| 19 |
-
FlowMatchEulerDiscreteScheduler
|
| 20 |
-
)
|
| 21 |
from huggingface_hub import (
|
| 22 |
hf_hub_download,
|
| 23 |
HfFileSystem,
|
| 24 |
ModelCard,
|
| 25 |
-
snapshot_download
|
| 26 |
-
)
|
| 27 |
from diffusers.utils import load_image
|
| 28 |
import requests
|
| 29 |
from urllib.parse import urlparse
|
|
@@ -120,14 +115,10 @@ loras = [
|
|
| 120 |
},
|
| 121 |
]
|
| 122 |
|
| 123 |
-
# Initialize the base model
|
| 124 |
dtype = torch.bfloat16
|
| 125 |
base_model = "Qwen/Qwen-Image"
|
| 126 |
|
| 127 |
-
# Initialize TAEF1 for fast previews and the standard VAE for high-quality final images
|
| 128 |
-
taef1 = AutoencoderTiny.from_pretrained("madebyollin/taef1", torch_dtype=dtype).to(device)
|
| 129 |
-
good_vae = AutoencoderKL.from_pretrained(base_model, subfolder="vae", torch_dtype=dtype).to(device)
|
| 130 |
-
|
| 131 |
# Scheduler configuration from the Qwen-Image-Lightning repository
|
| 132 |
scheduler_config = {
|
| 133 |
"base_image_seq_len": 256,
|
|
@@ -147,21 +138,10 @@ scheduler_config = {
|
|
| 147 |
}
|
| 148 |
|
| 149 |
scheduler = FlowMatchEulerDiscreteScheduler.from_config(scheduler_config)
|
| 150 |
-
|
| 151 |
-
# Main pipeline for text-to-image, using taef1 for fast decoding during generation
|
| 152 |
pipe = DiffusionPipeline.from_pretrained(
|
| 153 |
-
base_model, scheduler=scheduler, torch_dtype=dtype
|
| 154 |
-
).to(device)
|
| 155 |
-
|
| 156 |
-
# Image-to-image pipeline, using the high-quality VAE
|
| 157 |
-
pipe_i2i = AutoPipelineForImage2Image.from_pretrained(
|
| 158 |
-
base_model,
|
| 159 |
-
vae=good_vae,
|
| 160 |
-
scheduler=scheduler,
|
| 161 |
-
torch_dtype=dtype
|
| 162 |
).to(device)
|
| 163 |
|
| 164 |
-
|
| 165 |
# Lightning LoRA info (no global state)
|
| 166 |
LIGHTNING_LORA_REPO = "lightx2v/Qwen-Image-Lightning"
|
| 167 |
LIGHTNING_LORA_WEIGHT = "Qwen-Image-Lightning-8steps-V1.0.safetensors"
|
|
@@ -232,32 +212,29 @@ def adjust_generation_mode(speed_mode):
|
|
| 232 |
else:
|
| 233 |
return gr.update(value="Base mode selected - 48 steps for best quality"), 48, 4.0
|
| 234 |
|
| 235 |
-
|
| 236 |
-
|
|
|
|
| 237 |
generator = torch.Generator(device="cuda").manual_seed(seed)
|
| 238 |
-
pipe_i2i.to("cuda")
|
| 239 |
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
return
|
| 253 |
|
| 254 |
@spaces.GPU(duration=100)
|
| 255 |
-
def
|
| 256 |
-
prompt, image_input, image_strength, cfg_scale, steps, selected_index,
|
| 257 |
-
randomize_seed, seed, aspect_ratio, lora_scale, speed_mode, progress=gr.Progress(track_tqdm=True)
|
| 258 |
-
):
|
| 259 |
if selected_index is None:
|
| 260 |
-
raise gr.Error("You must select a LoRA before proceeding
|
| 261 |
|
| 262 |
selected_lora = loras[selected_index]
|
| 263 |
lora_path = selected_lora["repo"]
|
|
@@ -265,85 +242,63 @@ def process_generation_request(
|
|
| 265 |
|
| 266 |
# Prepare prompt with trigger word
|
| 267 |
if trigger_word:
|
| 268 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 269 |
else:
|
| 270 |
prompt_mash = prompt
|
| 271 |
|
| 272 |
-
# Set random seed if requested
|
| 273 |
-
if randomize_seed:
|
| 274 |
-
seed = random.randint(0, MAX_SEED)
|
| 275 |
-
|
| 276 |
-
# Determine which pipeline to use
|
| 277 |
-
pipe_to_use = pipe_i2i if image_input is not None else pipe
|
| 278 |
-
|
| 279 |
# Always unload any existing LoRAs first to avoid conflicts
|
| 280 |
with Timer("Unloading existing LoRAs"):
|
| 281 |
-
|
| 282 |
|
| 283 |
# Load LoRAs based on speed mode
|
| 284 |
if speed_mode == "Fast (8 steps)":
|
| 285 |
with Timer("Loading Lightning LoRA and style LoRA"):
|
| 286 |
-
|
|
|
|
| 287 |
LIGHTNING_LORA_REPO,
|
| 288 |
weight_name=LIGHTNING_LORA_WEIGHT,
|
| 289 |
adapter_name="lightning"
|
| 290 |
)
|
| 291 |
-
|
| 292 |
-
|
|
|
|
|
|
|
| 293 |
lora_path,
|
| 294 |
weight_name=weight_name,
|
|
|
|
| 295 |
adapter_name="style"
|
| 296 |
)
|
| 297 |
-
|
| 298 |
-
|
|
|
|
|
|
|
|
|
|
| 299 |
with Timer(f"Loading LoRA weights for {selected_lora['title']}"):
|
| 300 |
-
weight_name = selected_lora.get("weights")
|
| 301 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 302 |
|
|
|
|
| 303 |
width, height = compute_image_dimensions(aspect_ratio)
|
| 304 |
-
|
| 305 |
-
#
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
yield final_image, seed, gr.update(visible=False)
|
| 310 |
-
else:
|
| 311 |
-
# Text-to-Image Generation with Previews
|
| 312 |
-
pipe.to("cuda")
|
| 313 |
-
generator = torch.Generator(device="cuda").manual_seed(seed)
|
| 314 |
-
|
| 315 |
-
# Callback for generating previews
|
| 316 |
-
def callback_on_step_end(pipe, step_index, timestep, callback_kwargs):
|
| 317 |
-
latents = callback_kwargs["latents"]
|
| 318 |
-
# Use the fast taef1 decoder for previews
|
| 319 |
-
with torch.no_grad():
|
| 320 |
-
image = pipe.decode_latents(latents.to(dtype))[0]
|
| 321 |
-
progress_bar = f'<div class="progress-container"><div class="progress-bar" style="--current: {step_index + 1}; --total: {steps};"></div></div>'
|
| 322 |
-
yield {"image": image, "seed": seed, "progress": gr.update(value=progress_bar, visible=True)}
|
| 323 |
-
return callback_kwargs
|
| 324 |
-
|
| 325 |
-
# Generate image with step-by-step previews
|
| 326 |
-
with Timer("Generating image with previews"):
|
| 327 |
-
generation_output = pipe(
|
| 328 |
-
prompt=prompt_mash,
|
| 329 |
-
num_inference_steps=steps,
|
| 330 |
-
true_cfg_scale=cfg_scale,
|
| 331 |
-
width=width,
|
| 332 |
-
height=height,
|
| 333 |
-
generator=generator,
|
| 334 |
-
output_type="latent", # Get latents to decode with the good VAE later
|
| 335 |
-
callback_on_step_end=callback_on_step_end
|
| 336 |
-
)
|
| 337 |
-
|
| 338 |
-
# Decode the final image with the high-quality VAE
|
| 339 |
-
with Timer("Final decoding with good VAE"):
|
| 340 |
-
final_latents = generation_output.images
|
| 341 |
-
pipe.vae = good_vae # Temporarily swap to the good VAE
|
| 342 |
-
final_image = pipe.decode_latents(final_latents.to(dtype))[0]
|
| 343 |
-
pipe.vae = taef1 # Swap back to taef1 for the next run
|
| 344 |
-
|
| 345 |
-
yield final_image, seed, gr.update(visible=False)
|
| 346 |
-
|
| 347 |
|
| 348 |
def fetch_hf_adapter_files(link):
|
| 349 |
split_link = link.split("/")
|
|
@@ -352,37 +307,79 @@ def fetch_hf_adapter_files(link):
|
|
| 352 |
|
| 353 |
print(f"Repository attempted: {split_link}")
|
| 354 |
|
|
|
|
| 355 |
model_card = ModelCard.load(link)
|
| 356 |
base_model = model_card.data.get("base_model")
|
| 357 |
print(f"Base model: {base_model}")
|
| 358 |
|
|
|
|
| 359 |
acceptable_models = {"Qwen/Qwen-Image"}
|
|
|
|
| 360 |
models_to_check = base_model if isinstance(base_model, list) else [base_model]
|
| 361 |
|
| 362 |
if not any(model in acceptable_models for model in models_to_check):
|
| 363 |
raise Exception("Not a Qwen-Image LoRA!")
|
| 364 |
|
| 365 |
-
|
|
|
|
| 366 |
trigger_word = model_card.data.get("instance_prompt", "")
|
| 367 |
image_url = f"https://huggingface.co/{link}/resolve/main/{image_path}" if image_path else None
|
| 368 |
|
|
|
|
| 369 |
fs = HfFileSystem()
|
| 370 |
try:
|
| 371 |
list_of_files = fs.ls(link, detail=False)
|
| 372 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 373 |
if not safetensors_name:
|
| 374 |
raise Exception("No valid *.safetensors file found in the repository.")
|
|
|
|
| 375 |
except Exception as e:
|
| 376 |
print(e)
|
| 377 |
-
raise Exception("
|
| 378 |
|
| 379 |
return split_link[1], link, safetensors_name, trigger_word, image_url
|
| 380 |
|
| 381 |
def validate_custom_adapter(link):
|
| 382 |
print(f"Checking a custom model on: {link}")
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 386 |
|
| 387 |
def incorporate_custom_adapter(custom_lora):
|
| 388 |
global loras
|
|
@@ -402,21 +399,30 @@ def incorporate_custom_adapter(custom_lora):
|
|
| 402 |
</div>
|
| 403 |
</div>
|
| 404 |
'''
|
| 405 |
-
existing_item_index = next((
|
| 406 |
if existing_item_index is None:
|
| 407 |
-
new_item = {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 408 |
loras.append(new_item)
|
| 409 |
-
existing_item_index = len(loras) - 1
|
| 410 |
|
| 411 |
return gr.update(visible=True, value=card), gr.update(visible=True), gr.Gallery(selected_index=None), f"Custom: {path}", existing_item_index, trigger_word
|
| 412 |
except Exception as e:
|
| 413 |
-
gr.Warning(f"Invalid LoRA: {e}")
|
| 414 |
-
return gr.update(visible=True, value=f"Invalid LoRA:
|
| 415 |
-
|
|
|
|
| 416 |
|
| 417 |
def discard_custom_adapter():
|
| 418 |
return gr.update(visible=False), gr.update(visible=False), gr.update(), "", None, ""
|
| 419 |
|
|
|
|
| 420 |
|
| 421 |
css = '''
|
| 422 |
#gen_btn{height: 100%}
|
|
@@ -430,10 +436,6 @@ css = '''
|
|
| 430 |
.card_internal img{margin-right: 1em}
|
| 431 |
.styler{--form-gap-width: 0px !important}
|
| 432 |
#speed_status{padding: .5em; border-radius: 5px; margin: 1em 0}
|
| 433 |
-
#progress{height:30px}
|
| 434 |
-
#progress .generating{display:none}
|
| 435 |
-
.progress-container {width: 100%;height: 30px;background-color: #f0f0f0;border-radius: 15px;overflow: hidden;margin-bottom: 20px}
|
| 436 |
-
.progress-bar {height: 100%;background-color: #4f46e5;width: calc(var(--current) / var(--total) * 100%);transition: width 0.1s ease-in-out}
|
| 437 |
'''
|
| 438 |
|
| 439 |
with gr.Blocks(theme="bethecloud/storj_theme", css=css, delete_cache=(120, 120)) as app:
|
|
@@ -457,10 +459,6 @@ with gr.Blocks(theme="bethecloud/storj_theme", css=css, delete_cache=(120, 120))
|
|
| 457 |
elem_id="gallery",
|
| 458 |
show_share_button=False
|
| 459 |
)
|
| 460 |
-
with gr.Accordion("Image-to-Image (Optional)", open=False):
|
| 461 |
-
image_input = gr.Image(type="filepath", label="Input Image")
|
| 462 |
-
image_strength = gr.Slider(label="Image Strength", minimum=0.1, maximum=1.0, step=0.05, value=0.6)
|
| 463 |
-
|
| 464 |
with gr.Group():
|
| 465 |
custom_lora = gr.Textbox(label="Custom LoRA", info="LoRA Hugging Face path", placeholder="username/lora-model-name")
|
| 466 |
gr.Markdown("[Check Qwen-Image LoRAs](https://huggingface.co/models?other=base_model:adapter:Qwen/Qwen-Image)", elem_id="lora_list")
|
|
@@ -469,14 +467,13 @@ with gr.Blocks(theme="bethecloud/storj_theme", css=css, delete_cache=(120, 120))
|
|
| 469 |
|
| 470 |
with gr.Column():
|
| 471 |
result = gr.Image(label="Generated Image")
|
| 472 |
-
progress_bar = gr.HTML(visible=False, elem_id="progress")
|
| 473 |
|
| 474 |
with gr.Row():
|
| 475 |
aspect_ratio = gr.Dropdown(
|
| 476 |
label="Aspect Ratio",
|
| 477 |
choices=["1:1", "16:9", "9:16", "4:3", "3:4", "3:2", "2:3"],
|
| 478 |
value="1:1"
|
| 479 |
-
|
| 480 |
with gr.Row():
|
| 481 |
speed_mode = gr.Dropdown(
|
| 482 |
label="Output Mode",
|
|
@@ -491,12 +488,12 @@ with gr.Blocks(theme="bethecloud/storj_theme", css=css, delete_cache=(120, 120))
|
|
| 491 |
with gr.Column():
|
| 492 |
with gr.Row():
|
| 493 |
cfg_scale = gr.Slider(
|
| 494 |
-
label="Guidance Scale",
|
| 495 |
minimum=1.0,
|
| 496 |
maximum=5.0,
|
| 497 |
step=0.1,
|
| 498 |
value=4.0,
|
| 499 |
-
info="Lower for speed mode, higher for quality
|
| 500 |
)
|
| 501 |
steps = gr.Slider(
|
| 502 |
label="Steps",
|
|
@@ -536,18 +533,11 @@ with gr.Blocks(theme="bethecloud/storj_theme", css=css, delete_cache=(120, 120))
|
|
| 536 |
outputs=[custom_lora_info, custom_lora_button, gallery, selected_info, selected_index, custom_lora]
|
| 537 |
)
|
| 538 |
|
| 539 |
-
|
| 540 |
-
|
| 541 |
-
|
| 542 |
-
|
| 543 |
-
|
| 544 |
-
inputs=gen_inputs,
|
| 545 |
-
outputs=gen_outputs
|
| 546 |
-
)
|
| 547 |
-
prompt.submit(
|
| 548 |
-
fn=process_generation_request,
|
| 549 |
-
inputs=gen_inputs,
|
| 550 |
-
outputs=gen_outputs
|
| 551 |
)
|
| 552 |
|
| 553 |
app.queue()
|
|
|
|
| 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
|
|
|
|
| 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,
|
|
|
|
| 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"
|
|
|
|
| 212 |
else:
|
| 213 |
return gr.update(value="Base mode selected - 48 steps for best quality"), 48, 4.0
|
| 214 |
|
| 215 |
+
@spaces.GPU(duration=100)
|
| 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=100)
|
| 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"]
|
|
|
|
| 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("/")
|
|
|
|
| 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
|
|
|
|
| 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%}
|
|
|
|
| 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:
|
|
|
|
| 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/lora-model-name")
|
| 464 |
gr.Markdown("[Check Qwen-Image LoRAs](https://huggingface.co/models?other=base_model:adapter:Qwen/Qwen-Image)", elem_id="lora_list")
|
|
|
|
| 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="Output Mode",
|
|
|
|
| 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",
|
|
|
|
| 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()
|