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590498
 
8ce917e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a4fd555
8ce917e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
import os
import gradio as gr
import json
import logging
import torch
from PIL import Image
import spaces
from diffusers import DiffusionPipeline, FlowMatchEulerDiscreteScheduler
from huggingface_hub import hf_hub_download, HfFileSystem, ModelCard, snapshot_download
import copy
import random
import time
import re
import math
import numpy as np

# Load LoRAs from JSON
loras = [
    {
        "repo": "flymy-ai/qwen-image-realism-lora",
        "image": "https://huggingface.co/flymy-ai/qwen-image-realism-lora/resolve/main/assets/flymy_realism.png",
        "trigger_word": "Super Realism portrait of",
        "trigger_position": "prepend",
        "title": "Super Realism"
    },
    {
        "repo": "threecrowco/VolkClipartQwen",
        "image": "https://huggingface.co/threecrowco/VolkClipartQwen/resolve/main/images/_app_ai-toolkit_output_VolkDrawings_Qwen_v1_samples_1754805220500__000003000_3.jpg",
        "trigger_word": "volk clipart, black and white, ",
        "trigger_position": "prepend",
        "title": "Volk Clipart"
    },
    {
        "repo": "janekm/analog_film",
        "image": "https://huggingface.co/spaces/multimodalart/Qwen-Image-LoRA-Explorer/resolve/main/cat.webp",
        "trigger_word": "fifthel",
        "trigger_position": "prepend",
        "weights": "converted_complete.safetensors",
        "title": "Analog Film"
    },
    {
        "repo": "itspoidaman/qwenglitch",
        "image": "https://huggingface.co/itspoidaman/qwenglitch/resolve/main/images/GydaJ5LbEAAWKJU.jpeg",
        "trigger_word": "qwenglitch",
        "title": "Glitch"
    },
    {
        "repo": "alfredplpl/qwen-image-modern-anime-lora",
        "image": "https://huggingface.co/alfredplpl/qwen-image-modern-anime-lora/resolve/main/sample1.jpg",
        "trigger_word": "Japanese modern anime style, ",
        "trigger_position": "prepend",
        "title": "Modern Anime"
    },
    {
        "repo": "lichorosario/qwen-image-dottrmstr",
        "image": "https://huggingface.co/lichorosario/qwen-image-dottrmstr/resolve/main/images/Day_of_the_Tentacle_Remastered_(PC)_08.jpg",
        "trigger_word": "DOTTRMSTR",
        "trigger_position": "prepend",
        "title": "Day of the Tentacle Style"
    }
]

# Initialize the base model
dtype = torch.bfloat16
device = "cuda" if torch.cuda.is_available() else "cpu"
base_model = "Qwen/Qwen-Image"

# Scheduler configuration from the Qwen-Image-Lightning repository
scheduler_config = {
    "base_image_seq_len": 256,
    "base_shift": math.log(3),
    "invert_sigmas": False,
    "max_image_seq_len": 8192,
    "max_shift": math.log(3),
    "num_train_timesteps": 1000,
    "shift": 1.0,
    "shift_terminal": None,
    "stochastic_sampling": False,
    "time_shift_type": "exponential",
    "use_beta_sigmas": False,
    "use_dynamic_shifting": True,
    "use_exponential_sigmas": False,
    "use_karras_sigmas": False,
}

scheduler = FlowMatchEulerDiscreteScheduler.from_config(scheduler_config)
pipe = DiffusionPipeline.from_pretrained(
    base_model, scheduler=scheduler, torch_dtype=dtype
).to(device)

# Lightning LoRA info (no global state)
LIGHTNING_LORA_REPO = "lightx2v/Qwen-Image-Lightning"
LIGHTNING_LORA_WEIGHT = "Qwen-Image-Lightning-8steps-V1.0.safetensors"

MAX_SEED = np.iinfo(np.int32).max

class calculateDuration:
    def __init__(self, activity_name=""):
        self.activity_name = activity_name

    def __enter__(self):
        self.start_time = time.time()
        return self
    
    def __exit__(self, exc_type, exc_value, traceback):
        self.end_time = time.time()
        self.elapsed_time = self.end_time - self.start_time
        if self.activity_name:
            print(f"Elapsed time for {self.activity_name}: {self.elapsed_time:.6f} seconds")
        else:
            print(f"Elapsed time: {self.elapsed_time:.6f} seconds")

def get_image_size(aspect_ratio):
    """Converts aspect ratio string to width, height tuple."""
    if aspect_ratio == "1:1":
        return 1024, 1024
    elif aspect_ratio == "16:9":
        return 1152, 640
    elif aspect_ratio == "9:16":
        return 640, 1152
    elif aspect_ratio == "4:3":
        return 1024, 768
    elif aspect_ratio == "3:4":
        return 768, 1024
    elif aspect_ratio == "3:2":
        return 1024, 688
    elif aspect_ratio == "2:3":
        return 688, 1024
    else:
        return 1024, 1024

def update_selection(evt: gr.SelectData, aspect_ratio):
    selected_lora = loras[evt.index]
    new_placeholder = f"Type a prompt for {selected_lora['title']}"
    lora_repo = selected_lora["repo"]
    updated_text = f"### Selected: [{lora_repo}](https://huggingface.co/{lora_repo}) ✨"
    
    # Update aspect ratio if specified in LoRA config
    if "aspect" in selected_lora:
        if selected_lora["aspect"] == "portrait":
            aspect_ratio = "9:16"
        elif selected_lora["aspect"] == "landscape":
            aspect_ratio = "16:9"
        else:
            aspect_ratio = "1:1"
    
    return (
        gr.update(placeholder=new_placeholder),
        updated_text,
        evt.index,
        aspect_ratio,
    )

def handle_speed_mode(speed_mode):
    """Update UI based on speed/quality toggle."""
    if speed_mode == "Speed (8 steps)":
        return gr.update(value="Speed mode selected - 8 steps with Lightning LoRA"), 8, 1.0
    else: 
        return gr.update(value="Quality mode selected - 45 steps for best quality"), 45, 3.5

@spaces.GPU(duration=70)
def generate_image(prompt_mash, steps, seed, cfg_scale, width, height, lora_scale, negative_prompt=""):
    pipe.to("cuda")
    generator = torch.Generator(device="cuda").manual_seed(seed)
    
    with calculateDuration("Generating image"):
        # Generate image
        image = pipe(
            prompt=prompt_mash,
            negative_prompt=negative_prompt,
            num_inference_steps=steps,
            true_cfg_scale=cfg_scale,  # Use true_cfg_scale for Qwen-Image
            width=width,
            height=height,
            generator=generator,
        ).images[0]
        
    return image

@spaces.GPU(duration=70)
def run_lora(prompt, cfg_scale, steps, selected_index, randomize_seed, seed, aspect_ratio, lora_scale, speed_mode, progress=gr.Progress(track_tqdm=True)):
    if selected_index is None:
        raise gr.Error("You must select a LoRA before proceeding.")
    
    selected_lora = loras[selected_index]
    lora_path = selected_lora["repo"]
    trigger_word = selected_lora["trigger_word"]
    
    # Prepare prompt with trigger word
    if trigger_word:
        if "trigger_position" in selected_lora:
            if selected_lora["trigger_position"] == "prepend":
                prompt_mash = f"{trigger_word} {prompt}"
            else:
                prompt_mash = f"{prompt} {trigger_word}"
        else:
            prompt_mash = f"{trigger_word} {prompt}"
    else:
        prompt_mash = prompt

    # Always unload any existing LoRAs first to avoid conflicts
    with calculateDuration("Unloading existing LoRAs"):
        pipe.unload_lora_weights()

    # Load LoRAs based on speed mode
    if speed_mode == "Speed (8 steps)":
        with calculateDuration("Loading Lightning LoRA and style LoRA"):
            # Load Lightning LoRA first
            pipe.load_lora_weights(
                LIGHTNING_LORA_REPO, 
                weight_name=LIGHTNING_LORA_WEIGHT,
                adapter_name="lightning"
            )
            
            # Load the selected style LoRA
            weight_name = selected_lora.get("weights", None)
            pipe.load_lora_weights(
                lora_path, 
                weight_name=weight_name, 
                low_cpu_mem_usage=True,
                adapter_name="style"
            )
            
            # Set both adapters active with their weights
            pipe.set_adapters(["lightning", "style"], adapter_weights=[1.0, lora_scale])
    else:
        # Quality mode - only load the style LoRA
        with calculateDuration(f"Loading LoRA weights for {selected_lora['title']}"):
            weight_name = selected_lora.get("weights", None)
            pipe.load_lora_weights(
                lora_path, 
                weight_name=weight_name, 
                low_cpu_mem_usage=True
            )
                
    # Set random seed for reproducibility
    with calculateDuration("Randomizing seed"):
        if randomize_seed:
            seed = random.randint(0, MAX_SEED)
    
    # Get image dimensions from aspect ratio
    width, height = get_image_size(aspect_ratio)
    
    # Generate the image
    final_image = generate_image(prompt_mash, steps, seed, cfg_scale, width, height, lora_scale)
    
    return final_image, seed

def get_huggingface_safetensors(link):
    split_link = link.split("/")
    if len(split_link) != 2:
        raise Exception("Invalid Hugging Face repository link format.")

    print(f"Repository attempted: {split_link}")
    
    # Load model card
    model_card = ModelCard.load(link)
    base_model = model_card.data.get("base_model")
    print(f"Base model: {base_model}")

    # Validate model type (for Qwen-Image)
    acceptable_models = {"Qwen/Qwen-Image"}
    
    models_to_check = base_model if isinstance(base_model, list) else [base_model]
    
    if not any(model in acceptable_models for model in models_to_check):
        raise Exception("Not a Qwen-Image LoRA!")
        
    # Extract image and trigger word
    image_path = model_card.data.get("widget", [{}])[0].get("output", {}).get("url", None)
    trigger_word = model_card.data.get("instance_prompt", "")
    image_url = f"https://huggingface.co/{link}/resolve/main/{image_path}" if image_path else None

    # Initialize Hugging Face file system
    fs = HfFileSystem()
    try:
        list_of_files = fs.ls(link, detail=False)
        
        # Find safetensors file
        safetensors_name = None
        for file in list_of_files:
            filename = file.split("/")[-1]
            if filename.endswith(".safetensors"):
                safetensors_name = filename
                break

        if not safetensors_name:
            raise Exception("No valid *.safetensors file found in the repository.")

    except Exception as e:
        print(e)
        raise Exception("You didn't include a valid Hugging Face repository with a *.safetensors LoRA")
    
    return split_link[1], link, safetensors_name, trigger_word, image_url

def check_custom_model(link):
    print(f"Checking a custom model on: {link}")
    
    if link.endswith('.safetensors'):
        if 'huggingface.co' in link:
            parts = link.split('/')
            try:
                hf_index = parts.index('huggingface.co')
                username = parts[hf_index + 1]
                repo_name = parts[hf_index + 2]
                repo = f"{username}/{repo_name}"
                
                safetensors_name = parts[-1]
                
                try:
                    model_card = ModelCard.load(repo)
                    trigger_word = model_card.data.get("instance_prompt", "")
                    image_path = model_card.data.get("widget", [{}])[0].get("output", {}).get("url", None)
                    image_url = f"https://huggingface.co/{repo}/resolve/main/{image_path}" if image_path else None
                except:
                    trigger_word = ""
                    image_url = None
                
                return repo_name, repo, safetensors_name, trigger_word, image_url
            except:
                raise Exception("Invalid safetensors URL format")
    
    if link.startswith("https://"):
        if link.startswith("https://huggingface.co") or link.startswith("https://www.huggingface.co"):
            link_split = link.split("huggingface.co/")
            return get_huggingface_safetensors(link_split[1])
    else: 
        return get_huggingface_safetensors(link)

def add_custom_lora(custom_lora):
    global loras
    if custom_lora:
        try:
            title, repo, path, trigger_word, image = check_custom_model(custom_lora)
            print(f"Loaded custom LoRA: {repo}")
            card = f'''
            <div class="custom_lora_card">
              <span>Loaded custom LoRA:</span>
              <div class="card_internal">
                <img src="{image}" />
                <div>
                    <h3>{title}</h3>
                    <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>
                </div>
              </div>
            </div>
            '''
            existing_item_index = next((index for (index, item) in enumerate(loras) if item['repo'] == repo), None)
            if existing_item_index is None:
                new_item = {
                    "image": image,
                    "title": title,
                    "repo": repo,
                    "weights": path,
                    "trigger_word": trigger_word
                }
                print(new_item)
                loras.append(new_item)
                existing_item_index = len(loras) - 1  # Get the actual index after adding
        
            return gr.update(visible=True, value=card), gr.update(visible=True), gr.Gallery(selected_index=None), f"Custom: {path}", existing_item_index, trigger_word
        except Exception as e:
            gr.Warning(f"Invalid LoRA: either you entered an invalid link, or a non-Qwen-Image LoRA, this was the issue: {e}")
            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, ""
    else:
        return gr.update(visible=False), gr.update(visible=False), gr.update(), "", None, ""

def remove_custom_lora():
    return gr.update(visible=False), gr.update(visible=False), gr.update(), "", None, ""

run_lora.zerogpu = True

css = '''
#gen_btn{height: 100%}
#gen_column{align-self: stretch}
#title{text-align: center}
#title h1{font-size: 3em; display:inline-flex; align-items:center}
#title img{width: 100px; margin-right: 0.5em}
#gallery .grid-wrap{height: 10vh}
#lora_list{background: var(--block-background-fill);padding: 0 1em .3em; font-size: 90%}
.card_internal{display: flex;height: 100px;margin-top: .5em}
.card_internal img{margin-right: 1em}
.styler{--form-gap-width: 0px !important}
#speed_status{padding: .5em; border-radius: 5px; margin: 1em 0}
'''

with gr.Blocks(theme=gr.themes.Soft(), css=css, delete_cache=(60, 60)) as app:
    title = gr.HTML(
        """<img src="https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen-Image/qwen_image_logo.png" alt="Qwen-Image" style="width: 280px; margin: 0 auto">        
        <h3 style="margin-top: -10px">LoRA Explorer</h3>""",
        elem_id="title",
    )
    
    selected_index = gr.State(None)
    
    with gr.Row():
        with gr.Column(scale=3):
            prompt = gr.Textbox(label="Prompt", lines=1, placeholder="Type a prompt after selecting a LoRA")
        with gr.Column(scale=1, elem_id="gen_column"):
            generate_button = gr.Button("Generate", variant="primary", elem_id="gen_btn")
    
    with gr.Row():
        with gr.Column():
            selected_info = gr.Markdown("")
            gallery = gr.Gallery(
                [(item["image"], item["title"]) for item in loras],
                label="LoRA Gallery",
                allow_preview=False,
                columns=3,
                elem_id="gallery",
                show_share_button=False
            )
            with gr.Group():
                custom_lora = gr.Textbox(label="Custom LoRA", info="LoRA Hugging Face path", placeholder="username/qwen-image-custom-lora")
                gr.Markdown("[Check Qwen-Image LoRAs](https://huggingface.co/models?other=base_model:adapter:Qwen/Qwen-Image)", elem_id="lora_list")
            custom_lora_info = gr.HTML(visible=False)
            custom_lora_button = gr.Button("Remove custom LoRA", visible=False)
        
        with gr.Column():
            result = gr.Image(label="Generated Image")
            
            with gr.Row():
                speed_mode = gr.Radio(
                    label="Generation Mode",
                    choices=["Speed (8 steps)", "Quality (45 steps)"],
                    value="Quality (45 steps)",
                    info="Speed mode uses Lightning LoRA for faster generation"
                )
            
            speed_status = gr.Markdown("Quality mode active", elem_id="speed_status")

    with gr.Row():
        with gr.Accordion("Advanced Settings", open=False):
            with gr.Column():
                with gr.Row():
                    aspect_ratio = gr.Radio(
                        label="Aspect Ratio",
                        choices=["1:1", "16:9", "9:16", "4:3", "3:4", "3:2", "2:3"],
                        value="1:1"
                    )
                    
                with gr.Row():
                    cfg_scale = gr.Slider(
                        label="Guidance Scale (True CFG)", 
                        minimum=1.0, 
                        maximum=5.0, 
                        step=0.1, 
                        value=3.5,
                        info="Lower for speed mode, higher for quality"
                    )
                    steps = gr.Slider(
                        label="Steps", 
                        minimum=4, 
                        maximum=50, 
                        step=1, 
                        value=45,
                        info="Automatically set by speed mode"
                    )
                
                with gr.Row():
                    randomize_seed = gr.Checkbox(True, label="Randomize seed")
                    seed = gr.Slider(label="Seed", minimum=0, maximum=MAX_SEED, step=1, value=0, randomize=True)
                    lora_scale = gr.Slider(label="LoRA Scale", minimum=0, maximum=2, step=0.01, value=1.0)

    # Event handlers
    gallery.select(
        update_selection,
        inputs=[aspect_ratio],
        outputs=[prompt, selected_info, selected_index, aspect_ratio]
    )
    
    speed_mode.change(
        handle_speed_mode,
        inputs=[speed_mode],
        outputs=[speed_status, steps, cfg_scale]
    )
    
    custom_lora.input(
        add_custom_lora,
        inputs=[custom_lora],
        outputs=[custom_lora_info, custom_lora_button, gallery, selected_info, selected_index, prompt]
    )
    
    custom_lora_button.click(
        remove_custom_lora,
        outputs=[custom_lora_info, custom_lora_button, gallery, selected_info, selected_index, custom_lora]
    )
    
    gr.on(
        triggers=[generate_button.click, prompt.submit],
        fn=run_lora,
        inputs=[prompt, cfg_scale, steps, selected_index, randomize_seed, seed, aspect_ratio, lora_scale, speed_mode],
        outputs=[result, seed]
    )

app.queue()
app.launch()